问:
Remove non-text chars (like emoticons) from string
How can I replace chars like  from a string? Sometime the YouTube video title contains characters like this. I don't want to replace characters like !@#$%^&*().

I am currently using preg_replace('/[^A-Za-z0-9\-]/', '', $VideoTitle);

Samples Array:

```<code>$VideoTitles[]='Sia 2017 Cheap Thrills 2017 live ';

$VideoTitles[]='TAYLOR SWIFT - SHAKE IT OFF  #1989';
</code>```

Expected Output:

```<code>Sia 2017 Cheap Thrills 2017 live
TAYLOR SWIFT - SHAKE IT OFF #1989
</code>```

答:
Code with sample input: Demo

```<code>$VideoTitles=[
    'Kilian à Dijon #4 • Vlog #2 • Primark again !?  - YouTube',
    'Funfesty   on Twitter: "Je commence à avoir mal à la tête à force',
    'Sia 2017 Cheap Thrills 2017 live '
];

$VideoTitles=preg_replace('/[^ -\x{2122}]\s+|\s*[^ -\x{2122}]/u','',$VideoTitles);  // remove out of range characters and whitespace character on one side only

var_export($VideoTitles);
</code>```

Output:

```<code>array (
  0 => 'Kilian à Dijon #4 • Vlog #2 • Primark again !? - YouTube',
  1 => 'Funfesty on Twitter: "Je commence à avoir mal à la tête à force',
  2 => 'Sia 2017 Cheap Thrills 2017 live',
)
</code>```

The above regex pattern uses a character range from \x20-\x2122 (space to trade-mark-sign).  I have selected this range because it should cover the vast majority of word-related characters including letters with accents and non-English characters.  (Admittedly, it also includes many non-word-related characters.  You may like to use two separate ranges for greater specificity like: /[^\x{20}-\x{60}\x{7B}-\x{FF}]/ui -- this case-insensitively searches two ranges: space to grave accent and left curly bracket to latin small letter y with diaeresis)

If you find that this range is unnecessarily generous or takes too long to process, you can make your own decision about the appropriate character range.

For instance, you might like the much lighter but less generous /[^\x20-\x7E]/u (from space to tilde).  However, if you apply it to either of my above French $VideoTitles then you will mangle the text by removing legitimate letters.

Here is a menu of characters and their unicode numbers to help you understand what is inside the aforementioned ranges and beyond.

*And remember to include a unicode flag u after your closing delimiter.

For completeness, I should say the literal/narrow solution for removing the two emojis would be:

```<code>$VideoTitle=preg_replace('/[\x{1F3A7}\x{1F3AC}]/u','',$VideoTitle);  // omit 2 emojis
</code>```

These emojis are called "clapper board (U+1F3AC)" and "headphone (U+1F3A7)".

ContentLicense: CC BY-SA 4.0

Body:
How can I replace chars like  from a string? Sometime the YouTube video title contains characters like this. I don't want to replace characters like !@#$%^&*().

I am currently using preg_replace('/[^A-Za-z0-9\-]/', '', $VideoTitle);

Samples Array:

$VideoTitles[]='Sia 2017 Cheap Thrills 2017 live ';

$VideoTitles[]='TAYLOR SWIFT - SHAKE IT OFF  #1989';

Expected Output:

Sia 2017 Cheap Thrills 2017 live
TAYLOR SWIFT - SHAKE IT OFF #1989

Body:
Code with sample input: Demo

$VideoTitles=[
    'Kilian à Dijon #4 • Vlog #2 • Primark again !?  - YouTube',
    'Funfesty   on Twitter: "Je commence à avoir mal à la tête à force',
    'Sia 2017 Cheap Thrills 2017 live '
];

$VideoTitles=preg_replace('/[^ -\x{2122}]\s+|\s*[^ -\x{2122}]/u','',$VideoTitles);  // remove out of range characters and whitespace character on one side only

var_export($VideoTitles);

Output:

array (
  0 => 'Kilian à Dijon #4 • Vlog #2 • Primark again !? - YouTube',
  1 => 'Funfesty on Twitter: "Je commence à avoir mal à la tête à force',
  2 => 'Sia 2017 Cheap Thrills 2017 live',
)

The above regex pattern uses a character range from \x20-\x2122 (space to trade-mark-sign).  I have selected this range because it should cover the vast majority of word-related characters including letters with accents and non-English characters.  (Admittedly, it also includes many non-word-related characters.  You may like to use two separate ranges for greater specificity like: /[^\x{20}-\x{60}\x{7B}-\x{FF}]/ui -- this case-insensitively searches two ranges: space to grave accent and left curly bracket to latin small letter y with diaeresis)

If you find that this range is unnecessarily generous or takes too long to process, you can make your own decision about the appropriate character range.

For instance, you might like the much lighter but less generous /[^\x20-\x7E]/u (from space to tilde).  However, if you apply it to either of my above French $VideoTitles then you will mangle the text by removing legitimate letters.

Here is a menu of characters and their unicode numbers to help you understand what is inside the aforementioned ranges and beyond.

*And remember to include a unicode flag u after your closing delimiter.

For completeness, I should say the literal/narrow solution for removing the two emojis would be:

$VideoTitle=preg_replace('/[\x{1F3A7}\x{1F3AC}]/u','',$VideoTitle);  // omit 2 emojis

These emojis are called "clapper board (U+1F3AC)" and "headphone (U+1F3A7)".


来源: stackexchange

问:
Rotate MapView in Android
I am writing an Android app where one of the features is that the map will rotate according to the compass (i.e. if the phone is pointing east, the map will be oriented so that the east side of the map is on top). Previous answers that I have found suggested over writing the onDraw() method in mapView, however, the api changed the method to final so it cannot be overwritten. As a result I have tried to overwrite the dispatchDraw() method like so:

Note:

-compass is a boolean that if true, rotate the view

-bearing is a float variable that has the degrees that the view should rotate

```<code>protected void dispatchDraw(Canvas canvas) {
    canvas.save();
         if (compass) {
             final float w = this.getWidth();
             final float h = this.getHeight();

             final float scaleFactor = (float)(Math.sqrt(h * h + w * w) / Math.min(w, h));

             final float centerX = w / 2.0f;
             final float centerY = h / 2.0f;

             canvas.rotate(bearing, centerX, centerY);
             canvas.scale(scaleFactor, scaleFactor, centerX, centerY);

         }
         super.dispatchDraw(canvas);
         canvas.restore();
}
</code>```

答:
From the docs:

protected void dispatchDraw (Canvas canvas)

Called by draw to draw the child views. This may be overridden by derived classes to gain control just before its children are drawn (but after its own view has been drawn).

So overriding dispatchDraw is no good as the main map view has already been drawn

One solution might be to add the MapView as a child of another CustomView (a sub-class of ViewGroup) and then use the dispatchDraw method of CustomView to draw the MapView (now a child) rotated. So in xml you'd do something like:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

  <com.example.CustomView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.google.android.maps.MapView
      android:id="@+id/mapview"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:apiKey="XXXXXXXXXXXXXXXXX"/>

  </com.example.CustomView>
</RelativeLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rotate MapView in Android

Body:
I am writing an Android app where one of the features is that the map will rotate according to the compass (i.e. if the phone is pointing east, the map will be oriented so that the east side of the map is on top). Previous answers that I have found suggested over writing the onDraw() method in mapView, however, the api changed the method to final so it cannot be overwritten. As a result I have tried to overwrite the dispatchDraw() method like so:

Note:

-compass is a boolean that if true, rotate the view

-bearing is a float variable that has the degrees that the view should rotate

protected void dispatchDraw(Canvas canvas) {
    canvas.save();
         if (compass) {
             final float w = this.getWidth();
             final float h = this.getHeight();

             final float scaleFactor = (float)(Math.sqrt(h * h + w * w) / Math.min(w, h));

             final float centerX = w / 2.0f;
             final float centerY = h / 2.0f;

             canvas.rotate(bearing, centerX, centerY);
             canvas.scale(scaleFactor, scaleFactor, centerX, centerY);

         }
         super.dispatchDraw(canvas);
         canvas.restore();
}

Body:
From the docs:

protected void dispatchDraw (Canvas canvas)

Called by draw to draw the child views. This may be overridden by derived classes to gain control just before its children are drawn (but after its own view has been drawn).

So overriding dispatchDraw is no good as the main map view has already been drawn

One solution might be to add the MapView as a child of another CustomView (a sub-class of ViewGroup) and then use the dispatchDraw method of CustomView to draw the MapView (now a child) rotated. So in xml you'd do something like:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

  <com.example.CustomView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.google.android.maps.MapView
      android:id="@+id/mapview"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:apiKey="XXXXXXXXXXXXXXXXX"/>

  </com.example.CustomView>
</RelativeLayout>

ContentLicense: CC BY-SA 2.5


问:
SQL Server 2014 - How to find Distinct records
I have a list of Contact that have First Names, Last Names and Email addresses. Some Email addresses have multiple First and Last Names. I am more concerned about the Email Addresses. I really just want the top name for that Email Address.

My Code doesn't work obviously:

```<code>SELECT Salutation
, FirstName
, LastName
, EmailAddress
FROM Contact
--GROUP BY EmailAddress  ---I know a Group by will surely help
</code>```

I have tried

```<code>SELECT max(Salutation)
    ,max(FirstName)
    ,max(LastName)
    ,max(EMailAddress)
FROM Contact
WHERE EMailAddress NOT LIKE ''
GROUP BY EMailAddress
</code>```

This worked but I'm wondering if there is a better way to do it.

答:
Try:

```<code>SELECT Salutation
, FirstName
, LastName
, EmailAddress
FROM Contact
WHERE EmailAddress IS NULL
      OR ID IN
      (SELECT MAX(ID)
       FROM Contact
       WHERE EmailAddress IS NOT NULL
       GROUP BY EmailAddress)
</code>```

This will give you the last one added for each email address.

Body:
I have a list of Contact that have First Names, Last Names and Email addresses. Some Email addresses have multiple First and Last Names. I am more concerned about the Email Addresses. I really just want the top name for that Email Address.

My Code doesn't work obviously:

SELECT Salutation
, FirstName
, LastName
, EmailAddress
FROM Contact
--GROUP BY EmailAddress  ---I know a Group by will surely help

I have tried

SELECT max(Salutation)
    ,max(FirstName)
    ,max(LastName)
    ,max(EMailAddress)
FROM Contact
WHERE EMailAddress NOT LIKE ''
GROUP BY EMailAddress

This worked but I'm wondering if there is a better way to do it.

Body:
Try:

SELECT Salutation
, FirstName
, LastName
, EmailAddress
FROM Contact
WHERE EmailAddress IS NULL
      OR ID IN
      (SELECT MAX(ID)
       FROM Contact
       WHERE EmailAddress IS NOT NULL
       GROUP BY EmailAddress)

This will give you the last one added for each email address.


问:
Build query string using urlencode python
I am trying to build a url so that I can send a get request to it using urllib module.

Let's suppose my final_url should be

```<code>url = "www.example.com/find.php?data=http%3A%2F%2Fwww.stackoverflow.com&search=Generate+value"
</code>```

Now to achieve this I tried the following way:

```<code>>>> initial_url = "http://www.stackoverflow.com"
>>> search = "Generate+value"
>>> params = {"data":initial_url,"search":search}
>>> query_string = urllib.urlencode(params)
>>> query_string
'search=Generate%2Bvalue&data=http%3A%2F%2Fwww.stackoverflow.com'
</code>```

Now if you compare my query_string with the format of final_url you can observer two things

1) The order of params are reversed instead of data=()&search= it is search=()&data=

2) urlencode also encoded the + in Generate+value

I believe the first change is due to the random behaviour of dictionary. So, I though of using OrderedDict to reverse the dictionary. As, I am using python 2.6.5 I did

```<code>pip install ordereddict
</code>```

But I am not able to use it in my code when I try

```<code>>>> od = OrderedDict((('a', 'first'), ('b', 'second')))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'OrderedDict' is not defined
</code>```

So, my question is what is the correct way to use OrderedDict in python 2.6.5 and how do I make urlencode ignores the + in Generate+value.

Also, is this the correct approach to build URL.

答:
Some comments on the question and other answers:

If you want to preserve order with urllib.urlencode, submit an ordered sequence of k/v pairs instead of mapping(dict).  when you pass in a dict,  urlencode just calls foo.items() to grab an iterable sequence.

    # urllib.urlencode accepts a mapping or sequence
    # the output of this can vary, because `items()` is called on the dict
    urllib.urlencode({"data": initial_url,"search": search})
    # the output of this will not vary
    urllib.urlencode((("data", initial_url), ("search", search)))

you can also pass in a secondard doseq argument to adjust how iterable values are handled.

The order of parameters is not irrelevant.  take these two urls for example:

https://example.com?foo=bar&bar=foo
https://example.com?bar=foo&foo=bar

A http server should consider the order of these parameters irrelevant, but a function designed to compare URLs would not.  In order to safely compare urls, these params would need to be sorted.

However, consider duplicate keys:

https://example.com?foo=3&foo=2&foo=1

The URI specs support duplicate keys, but don't address precedence or ordering.

In a given application, these could each trigger different results and be valid as well:

```<code>https://example.com?foo=1&foo=2&foo=3
https://example.com?foo=1&foo=3&foo=2
https://example.com?foo=2&foo=3&foo=1
https://example.com?foo=2&foo=1&foo=3
https://example.com?foo=3&foo=1&foo=2
https://example.com?foo=3&foo=2&foo=1
</code>```

The + is a reserved character that represents a space in a urlencoded form (vs %20 for part of the path). urllib.urlencode escapes using urllib.quote_plus(), not urllib.quote().  The OP most likely wanted to just do this:

    initial_url = "http://www.stackoverflow.com"
    search = "Generate value"
    urllib.urlencode((("data", initial_url), ("search", search)))

Which produces:

data=http%3A%2F%2Fwww.stackoverflow.com&search=Generate+value

as the output.

Body:
I am trying to build a url so that I can send a get request to it using urllib module.

Let's suppose my final_url should be

url = "www.example.com/find.php?data=http%3A%2F%2Fwww.stackoverflow.com&search=Generate+value"

Now to achieve this I tried the following way:

>>> initial_url = "http://www.stackoverflow.com"
>>> search = "Generate+value"
>>> params = {"data":initial_url,"search":search}
>>> query_string = urllib.urlencode(params)
>>> query_string
'search=Generate%2Bvalue&data=http%3A%2F%2Fwww.stackoverflow.com'

Now if you compare my query_string with the format of final_url you can observer two things

1) The order of params are reversed instead of data=()&search= it is search=()&data=

2) urlencode also encoded the + in Generate+value

I believe the first change is due to the random behaviour of dictionary. So, I though of using OrderedDict to reverse the dictionary. As, I am using python 2.6.5 I did

pip install ordereddict

But I am not able to use it in my code when I try

>>> od = OrderedDict((('a', 'first'), ('b', 'second')))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'OrderedDict' is not defined

So, my question is what is the correct way to use OrderedDict in python 2.6.5 and how do I make urlencode ignores the + in Generate+value.

Also, is this the correct approach to build URL.

Body:
Some comments on the question and other answers:

If you want to preserve order with urllib.urlencode, submit an ordered sequence of k/v pairs instead of mapping(dict).  when you pass in a dict,  urlencode just calls foo.items() to grab an iterable sequence.

    # urllib.urlencode accepts a mapping or sequence
    # the output of this can vary, because `items()` is called on the dict
    urllib.urlencode({"data": initial_url,"search": search})
    # the output of this will not vary
    urllib.urlencode((("data", initial_url), ("search", search)))

you can also pass in a secondard doseq argument to adjust how iterable values are handled.

The order of parameters is not irrelevant.  take these two urls for example:

https://example.com?foo=bar&bar=foo
https://example.com?bar=foo&foo=bar

A http server should consider the order of these parameters irrelevant, but a function designed to compare URLs would not.  In order to safely compare urls, these params would need to be sorted.

However, consider duplicate keys:

https://example.com?foo=3&foo=2&foo=1

The URI specs support duplicate keys, but don't address precedence or ordering.

In a given application, these could each trigger different results and be valid as well:

https://example.com?foo=1&foo=2&foo=3
https://example.com?foo=1&foo=3&foo=2
https://example.com?foo=2&foo=3&foo=1
https://example.com?foo=2&foo=1&foo=3
https://example.com?foo=3&foo=1&foo=2
https://example.com?foo=3&foo=2&foo=1

The + is a reserved character that represents a space in a urlencoded form (vs %20 for part of the path). urllib.urlencode escapes using urllib.quote_plus(), not urllib.quote().  The OP most likely wanted to just do this:

    initial_url = "http://www.stackoverflow.com"
    search = "Generate value"
    urllib.urlencode((("data", initial_url), ("search", search)))

Which produces:

data=http%3A%2F%2Fwww.stackoverflow.com&search=Generate+value

as the output.


问:
Button aligned to bottom of RelativeLayout is cut off
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>
</code>```

答:
I see that you use the layout in a PlaceholderFragment. I had the same problem with an adapter in a fragment. You should try to constrain the button with the second EditText and then run the code(quick fix). I think the problem is that when you run the code in a Fragment the layout is shifted and match_parent is computed as the whole screen(or the activity's size) thus aligning the button with the parent Activity and then it moves the layout down to make room for the tabs labels.

The layout looks fine

Body:
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>


问:
Cordova: camera.getPicture fails with "Camera cancelled"
I'm developing a cordova app (cli-5.2.0) in which pictures are taken using the cordova camera plugin (cordova-plugin-camera, version 1.2.0).

var camera = navigator.camera;
var cameraOptions = {
  destinationType: Camera.DestinationType.DATA_URL
};

camera.getPicture(function(result) {
    alert('success');
  }, function(error) {
    alert('fail ' + error);
  }, cameraOptions);```
</div>
</div>
</p>

<p>This code works fine.. ..most of the time. <br/>
On a particular slow android 4.4.4 device, this only works fine like 9 out of 10 times. <br/>
In like 1 out of 10, the call fails saying 'Camera cancelled' (although it was not cancelled with the back button or something). <br/><br/></p>

<p>In that case, the failure callback 'Camera cancelled' is fired, and right after that, the Camera UI is shown nevertheless. <br/>
(if a picture is taken then, the success callback is not called). <br/><br/></p>

<p>It's hard to tell when this happens, but it looks like it happens more often if the device is app is more busy. <br/>
The log files do not show much more detail, except for things like:</p>

<blockquote>
  <p>Attempted to send a second callback for ID: Camera1337050609</p>
</blockquote>

<p>However, these logs are also written if the call succeeds.</p>

<p><br/>
Any hints or help is much appreciated.<br/><br/>
Thanks for your time,<br/>
Koen</p>

<p><strong>update 1</strong> (answer to comment)</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>ProjectDetailCtrl.prototype.takePhoto = function () {
    var _this = this;
    // this cameraService calls the code from above
    return this.cameraService.getPicture()
        .then(function (imageData) {
            _this.$log.debug('got camera data');
            // ..
        },</code>```

<md-button ng-click="vm.takePhoto()">
    Add photo
</md-button>```

答:
My problem was that I had Angular material installed which provokes that the buttons and other click elements gets fired two times. To solve it I had to add this line in my app.js</p>

```<code>.config(function($stateProvider, $urlRouterProvider, $mdThemingProvider, $mdGestureProvider) {

$mdGestureProvider.skipClickHijack();
</code>```

Body:
I'm developing a cordova app (cli-5.2.0) in which pictures are taken using the cordova camera plugin (cordova-plugin-camera, version 1.2.0).

var camera = navigator.camera;
var cameraOptions = {
  destinationType: Camera.DestinationType.DATA_URL
};

camera.getPicture(function(result) {
    alert('success');
  }, function(error) {
    alert('fail ' + error);
  }, cameraOptions);

This code works fine.. ..most of the time.

On a particular slow android 4.4.4 device, this only works fine like 9 out of 10 times.

In like 1 out of 10, the call fails saying 'Camera cancelled' (although it was not cancelled with the back button or something).

In that case, the failure callback 'Camera cancelled' is fired, and right after that, the Camera UI is shown nevertheless.

(if a picture is taken then, the success callback is not called).

It's hard to tell when this happens, but it looks like it happens more often if the device is app is more busy.

The log files do not show much more detail, except for things like:

Attempted to send a second callback for ID: Camera1337050609

However, these logs are also written if the call succeeds.

Any hints or help is much appreciated.

Thanks for your time,

Koen

update 1 (answer to comment)

ProjectDetailCtrl.prototype.takePhoto = function () {
    var _this = this;
    // this cameraService calls the code from above
    return this.cameraService.getPicture()
        .then(function (imageData) {
            _this.$log.debug('got camera data');
            // ..
        },

<md-button ng-click="vm.takePhoto()">
    Add photo
</md-button>

Body:
My problem was that I had Angular material installed which provokes that the buttons and other click elements gets fired two times. To solve it I had to add this line in my app.js

.config(function($stateProvider, $urlRouterProvider, $mdThemingProvider, $mdGestureProvider) {

$mdGestureProvider.skipClickHijack();


问:
how to make saveAsTextFile NOT split output into multiple file?
When using Scala in Spark, whenever I dump the results out using saveAsTextFile, it seems to split the output into multiple parts. I'm just passing a parameter(path) to it.

```<code>val year = sc.textFile("apat63_99.txt").map(_.split(",")(1)).flatMap(_.split(",")).map((_,1)).reduceByKey((_+_)).map(_.swap)
year.saveAsTextFile("year")
</code>```

Does the number of outputs correspond to the number of reducers it uses?

Does this mean the output is compressed?

I know I can combine the output together using bash, but is there an option to store the output in a single text file, without splitting?? I looked at the API docs, but it doesn't say much about this.

答: As others have mentioned, you can collect or coalesce your data set to force Spark to produce a single file. But this also limits the number of Spark tasks that can work on your dataset in parallel. I prefer to let it create a hundred files in the output HDFS directory, then use hadoop fs -getmerge /hdfs/dir /local/file.txt to extract the results into a single file in the local filesystem. This makes the most sense when your output is a relatively small report, of course.

Body:
When using Scala in Spark, whenever I dump the results out using saveAsTextFile, it seems to split the output into multiple parts. I'm just passing a parameter(path) to it.

val year = sc.textFile("apat63_99.txt").map(_.split(",")(1)).flatMap(_.split(",")).map((_,1)).reduceByKey((_+_)).map(_.swap)
year.saveAsTextFile("year")

Does the number of outputs correspond to the number of reducers it uses?

Does this mean the output is compressed?

I know I can combine the output together using bash, but is there an option to store the output in a single text file, without splitting?? I looked at the API docs, but it doesn't say much about this.


问:
iOS Watch Simulator Crashes Mac
I've been fighting with this for a few days now.  Whenever I run a watchKit App from the simulator my mac will get the black screen of death and reboot my machine.  I am running XCode 8.2.1 running simulators for iPhone 6 or 7 and watches with watchOS 3 for both the original watch and version 2 in both sizes.  The watch simulator will start, but whenever it attempts to launch a watchkit app that was deployed with XCode my machine will crash.  This can be any watchkit app, even a simple Hello World app.

I have also tried completely uninstalling XCode 8 and 7 as well as all of the simulators and derived info, but the watch apps will still crash my machine.  I've filed a bug report with Apple, but they won't reply back to me.  I am also running on a Mid 2014 MacBook Pro with Sierra version 10.12.3.

Has anyone else experienced this?  I'm running out of ideas to fix this and I cannot do anything watch related until I get past this.  I've listed some of the logs from the activity monitor below as well as the Panic report:

ACTIVITY LOG:

```<code>Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FD/2940F9BA8137988BB56CC86EFEDC84
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FE/872728C5713EA69D9D3FBC6C653C19
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FE/B838E71BA739F4AA6F121E88E788B5
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FF/0B49D70BCF30419AD992D76F372F19
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext total: 3188, in_use:2294, marked:0, recent:254, deleted 640
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext slib tree cleaned up (0)
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext uuid tree cleaned up (3)
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext cleaned up (0)
Mar 24 09:04:17 C02N618RG3QD logd[74]: Purged 114692767 bytes from uuidtext.
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03260b130>: 9223372036854847488.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034800ba0>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03260ac80>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0349017f0>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034a07340>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0324107b0>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD useractivityd[1022]: BUG in libdispatch client: kevent[EVFILT_MACHPORT] monitored resource vanished before the source cancel handler was invoked
Mar 24 09:04:19 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034b0e0c0>: 9223372036854855680.000000]
Mar 24 09:04:19 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0326088d0>: 9223372036854855680.000000]
Mar 24 09:04:19 C02N618RG3QD UserEventAgent[1178]: assertion failed: 16D32 14S471a: com.apple.cts + 20609 [D0046D83-09B7-3C10-A783-396F29B9B380]: 0x0
Mar 24 09:04:21 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:22 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:22 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.quicklook[30456]): Endpoint has been activated through legacy launch(3) APIs. Please switch to XPC or bootstrap_check_in(): com.apple.quicklook
Mar 24 09:04:32 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 1 seconds. Pushing respawn out by 9 seconds.
Mar 24 09:04:33 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:39 C02N618RG3QD IBCocoaTouchImageCatalogTool[30517]: assertion failed: 16D32: libxpc.dylib + 34617 [D3538D2B-EEA9-3C74-890E-6F4AE4F51F0E]: 0x8d
Mar 24 09:04:40 C02N618RG3QD IBCocoaTouchImageCatalogTool[30517]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:42 C02N618RG3QD Interface Builder WatchKit Tool[30530]: assertion failed: 16D32: libxpc.dylib + 34617 [D3538D2B-EEA9-3C74-890E-6F4AE4F51F0E]: 0x8d
Mar 24 09:04:42 --- last message repeated 2 times ---
Mar 24 09:04:42 C02N618RG3QD Interface Builder WatchKit Tool[30530]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:42 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 1 seconds. Pushing respawn out by 9 seconds.
Mar 24 09:04:43 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 --- last message repeated 1 time ---
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: BUG in libdispatch: 16D32 14C89 - 1296 - 0x2
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: BUG in libdispatch: 16D32 14C89 - 1296 - 0x2
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:48 C02N618RG3QD IBCocoaTouchImageCatalogTool[30687]: BUG in libdispatch: 16D32 14C89 - 1296 - 0x2
Mar 24 09:04:48 C02N618RG3QD IBCocoaTouchImageCatalogTool[30687]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:52 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 1 seconds. Pushing respawn out by 9 seconds.
Mar 24 09:04:53 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:58 C02N618RG3QD Simulator (Watch)[30853]: BUG in libdispatch client: kevent[EVFILT_MACHPORT] monitored resource vanished before the source cancel handler was invoked
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe032706fc0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0327081f0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0326114b0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03250fbf0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03250d9d0>: 9223372036854857728.000000]
</code>```

AND

```<code>Mar 24 09:05:53 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034801f40>: 9223372036854861824.000000]
Mar 24 09:05:53 C02N618RG3QD diagnosticd[380]: JSON->NS failed [type" : "u",
        "timestamp" : 58798649826108
      },
      "timeGMTsec" : 1490360753,
      "procid" : {
        "procid" : 30972,
        "_type" : "u"
      },
      "persisted" : {
        "_type" : "b",
        "persisted" : 0
      },
      "thread" : {
        "_type" : "u",
        "thread" : 529028
      },
      "pid" : {
        "pid" : 30972,
        "_type" : "u"
      },
      "procpath" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneSimulator.platform\/Developer\/SDKs\/iPhoneSimulator.sdk\/System\/Library\/CoreServices\/SpringBoard.app\/SpringBoard",
      "SIMULATOR_UDID" : "4855B6A5-7A82-49AE-94E4-DBA2BED65585"
    }]
Mar 24 09:05:53 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe032403a30>: 9223372036854861824.000000]
</code>```

PANIC REPORT

```<code>Anonymous UUID:       56E742E7-D1F7-AB9B-90CC-58BFFAFB991E

Fri Mar 24 09:07:31 2017

*** Panic Report ***
panic(cpu 4 caller 0xffffff8018e05ecd): Kernel trap at 0xffffff8018dfc620, type 14=page fault, registers:
CR0: 0x000000008001003b, CR2: 0xffffff806783403c, CR3: 0x00000002cb9b6256, CR4: 0x00000000001627e0
RAX: 0x00000000ffffff01, RBX: 0x000000002d1e202c, RCX: 0x00000000ffffffa1, RDX: 0x000000000000000a
RSP: 0xffffff921b9fb7c0, RBP: 0xffffff921b9fb7c0, RSI: 0xffffff7f9c364723, RDI: 0xffffff806783403c
R8:  0x0000000000000002, R9:  0x0000000000000ff8, R10: 0xe326417ed3850092, R11: 0xffffff804d3b5bb8
R12: 0x000000000000000a, R13: 0x0000000000000054, R14: 0x0000000000906065, R15: 0xffffff803a652010
RFL: 0x0000000000010206, RIP: 0xffffff8018dfc620, CS:  0x0000000000000008, SS:  0x0000000000000010
Fault CR2: 0xffffff806783403c, Error code: 0x0000000000000000, Fault CPU: 0x4, PL: 0, VF: 1

Backtrace (CPU 4), Frame : Return Address
0xffffff921b9fb450 : 0xffffff8018cf210c
0xffffff921b9fb4d0 : 0xffffff8018e05ecd
0xffffff921b9fb6b0 : 0xffffff8018ca3743
0xffffff921b9fb6d0 : 0xffffff8018dfc620
0xffffff921b9fb7c0 : 0xffffff7f9c33e471
0xffffff921b9fb800 : 0xffffff7f9c33e4fa
0xffffff921b9fb830 : 0xffffff7f9c33e719
0xffffff921b9fb910 : 0xffffff7f9c33e839
0xffffff921b9fb950 : 0xffffff7f9c3604fa
0xffffff921b9fb9a0 : 0xffffff7f9c3603b4
0xffffff921b9fb9c0 : 0xffffff7f9c3474b7
0xffffff921b9fbe60 : 0xffffff7f9c3479e1
0xffffff921b9fbf40 : 0xffffff8202aea6a0
0xffffff921b9fbf50 : 0xffffff8019227066
0xffffff921b9fbfb0 : 0xffffff8018ca3c38
      Kernel Extensions in backtrace:
         com.verdasys.dgagent(23.20.7)[90F4996A-8100-3509-BBCA-9778AAA30E30]@0xffffff7f9c338000->0xffffff7f9c374fff
            dependency: com.apple.security.sandbox(300.0)[8997F7FD-7C04-38F6-86DB-BACDE9137374]@0xffffff7f99937000

BSD process name corresponding to current thread: xpcproxy_sim

Mac OS version:
16D32

Kernel version:
Darwin Kernel Version 16.4.0: Thu Dec 22 22:53:21 PST 2016; root:xnu-3789.41.3~3/RELEASE_X86_64
Kernel UUID: C67A8D03-DEAC-35B8-8F68-06FF7B687215
Kernel slide:     0x0000000018a00000
Kernel text base: 0xffffff8018c00000
__HIB  text base: 0xffffff8018b00000
System model name: MacBookPro11,3 (Mac-2BD1B31983FE1663)

System uptime in nanoseconds: 2958365287234
last loaded kext at 359084323236: com.apple.filesystems.smbfs   3.1.1 (addr 0xffffff7f998b3000, size 425984)
loaded kexts:
com.McAfee.FMPSysCore   1
com.verdasys.dgagent    0023.20.7
com.intel.kext.intelhaxm    1.1.1
com.squirrels.airparrot.framebuffer 5
com.squirrels.driver.AirParrotSpeakers  1.8
com.apple.filesystems.smbfs 3.1.1
com.apple.driver.AppleHWSensor  1.9.5d0
com.apple.filesystems.autofs    3.0
com.apple.driver.AGPM   110.23.14
com.apple.driver.ApplePlatformEnabler   2.7.0d0
com.apple.driver.X86PlatformShim    1.0.0
com.apple.driver.pmtelemetry    1
com.apple.iokit.IOUserEthernet  1.0.1
com.apple.iokit.IOBluetoothSerialManager    5.0.3f1
com.apple.Dont_Steal_Mac_OS_X   7.0.0
com.apple.driver.AppleHV    1
com.apple.driver.AppleOSXWatchdog   1
com.apple.driver.AppleGraphicsDevicePolicy  3.13.79
com.apple.driver.AppleHDAHardwareConfigDriver   278.56
com.apple.driver.AppleHDA   278.56
com.apple.driver.AppleUpstreamUserClient    3.6.4
com.apple.GeForce   10.1.4
com.apple.driver.AppleIntelHD5000Graphics   10.2.2
com.apple.driver.ACPI_SMC_PlatformPlugin    1.0.0
com.apple.driver.AppleFIVRDriver    4.1.0
com.apple.driver.AppleBacklight 170.9.10
com.apple.driver.AppleLPC   3.1
com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport 5.0.3f1
com.apple.nvidia.NVDAStartup    10.1.4
com.apple.driver.AudioAUUC  1.70
com.apple.driver.AppleSMCLMU    208
com.apple.driver.AppleCameraInterface   5.57.0
com.apple.driver.AppleMuxControl    3.13.79
com.apple.driver.AppleIntelSlowAdaptiveClocking 4.0.0
com.apple.driver.AppleIntelFramebufferAzul  10.2.2
com.apple.driver.AppleThunderboltIP 3.0.8
com.apple.driver.AppleMCCSControl   1.2.15
com.apple.driver.AppleUSBDisplays   380
com.apple.iokit.SCSITaskUserClient  394.30.2
com.apple.driver.AppleUSBStorageCoexistentDriver    404.30.1
com.apple.driver.AppleUSBCardReader 404.30.1
com.apple.iokit.IOBluetoothUSBDFU   5.0.3f1
com.apple.driver.AppleUSBTCKeyEventDriver   252
com.apple.driver.AppleUSBTCKeyboard 252
com.apple.driver.AppleUSBTCButtons  252
com.apple.driver.CoreStorageFsck    540.30.1
com.apple.driver.AppleFileSystemDriver  3.0.1
com.apple.AppleFSCompression.AppleFSCompressionTypeDataless 1.0.0d1
com.apple.AppleFSCompression.AppleFSCompressionTypeZlib 1.0.0
com.apple.BootCache 40
com.apple.filesystems.hfs.kext  366.30.3
com.apple.iokit.IOAHCIBlockStorage  295.20.1
com.apple.driver.AppleAHCIPort  326
com.apple.iokit.AppleBCM5701Ethernet    10.2.7
com.apple.driver.AppleFWOHCI    5.5.5
com.apple.driver.AirPort.Brcm4360   1130.3.1a5
com.apple.driver.AppleSmartBatteryManager   161.0.0
com.apple.driver.AppleACPIButtons   5.0
com.apple.driver.AppleRTC   2.0
com.apple.driver.AppleHPET  1.8
com.apple.driver.AppleSMBIOS    2.1
com.apple.driver.AppleACPIEC    5.0
com.apple.driver.AppleAPIC  1.7
com.apple.nke.applicationfirewall   172
com.apple.security.quarantine   3
com.apple.security.TMSafetyNet  8
com.apple.kext.triggers 1.0
com.apple.iokit.IOSerialFamily  11
com.apple.driver.AppleSSE   1.0
com.apple.driver.DspFuncLib 278.56
com.apple.kext.OSvKernDSPLib    525
com.apple.nvidia.driver.NVDAGK100Hal    10.1.4
com.apple.nvidia.driver.NVDAResman  10.1.4
com.apple.iokit.IOSurface   153.3
com.apple.driver.IOPlatformPluginLegacy 1.0.0
com.apple.iokit.IOFireWireIP    2.2.7
com.apple.driver.X86PlatformPlugin  1.0.0
com.apple.driver.IOPlatformPluginFamily 6.0.0d8
com.apple.iokit.IOBluetoothHostControllerUSBTransport   5.0.3f1
com.apple.iokit.IOBluetoothHostControllerTransport  5.0.3f1
com.apple.iokit.IOBluetoothFamily   5.0.3f1
com.apple.driver.AppleHDAController 278.56
com.apple.iokit.IOHDAFamily 278.56
com.apple.driver.AppleSMBusPCI  1.0.14d1
com.apple.driver.AppleBacklightExpert   1.1.0
com.apple.iokit.IONDRVSupport   513.1
com.apple.driver.AppleGraphicsControl   3.13.79
com.apple.iokit.IOSlowAdaptiveClockingFamily    1.0.0
com.apple.AppleGraphicsDeviceControl    3.13.79
com.apple.iokit.IOAcceleratorFamily2    289.32
com.apple.driver.AppleThunderboltEDMSink    4.1.1
com.apple.driver.AppleSMC   3.1.9
com.apple.driver.AppleSMBusController   1.0.14d1
com.apple.iokit.IOGraphicsFamily    513.1
com.apple.driver.AppleUSBComposite  900.4.1
com.apple.driver.AppleUSBAudio  307.7
com.apple.iokit.IOAudioFamily   205.12
com.apple.vecLib.kext   1.2.0
com.apple.iokit.IOUSBMassStorageClass   4.0.4
com.apple.iokit.IOSCSIBlockCommandsDevice   394.30.2
com.apple.iokit.IOUSBMassStorageDriver  131.1.1
com.apple.iokit.IOSCSIArchitectureModelFamily   394.30.2
com.apple.driver.AppleThunderboltDPInAdapter    4.6.1
com.apple.driver.AppleThunderboltDPOutAdapter   4.6.1
com.apple.driver.AppleThunderboltDPAdapterFamily    4.6.1
com.apple.driver.AppleThunderboltPCIUpAdapter   2.1.1
com.apple.driver.AppleThunderboltPCIDownAdapter 2.1.1
com.apple.driver.AppleUSBMultitouch 258
com.apple.driver.usb.IOUSBHostHIDDevice 1.1
com.apple.driver.usb.cdc    5.0.0
com.apple.driver.usb.networking 5.0.0
com.apple.driver.usb.AppleUSBHostCompositeDevice    1.1
com.apple.driver.CoreStorage    540.30.1
com.apple.filesystems.hfs.encodings.kext    1
com.apple.driver.AppleUSBMergeNub   900.4.1
com.apple.driver.usb.AppleUSBHub    1.1
com.apple.driver.AppleXsanScheme    3
com.apple.iokit.IOAHCIFamily    288
com.apple.driver.usb.AppleUSBEHCIPCI    1.1
com.apple.driver.usb.AppleUSBEHCI   1.1
com.apple.iokit.IOEthernetAVBController 1.0.3b4
com.apple.iokit.IOFireWireFamily    4.6.5
com.apple.driver.AppleThunderboltNHI    4.1.8
com.apple.iokit.IOThunderboltFamily 6.3.3
com.apple.iokit.IO80211Family   1200.12.2
com.apple.driver.mDNSOffloadUserClient  1.0.1b8
com.apple.iokit.IONetworkingFamily  3.2
com.apple.driver.corecapture    1.0.4
com.apple.driver.AppleIntelLpssGspi 3.0.60
com.apple.driver.usb.AppleUSBXHCIPCI    1.1
com.apple.driver.usb.AppleUSBXHCI   1.1
com.apple.driver.usb.AppleUSBHostPacketFilter   1.0
com.apple.iokit.IOUSBFamily 900.4.1
com.apple.driver.AppleUSBHostMergeProperties    1.1
com.apple.driver.AppleEFINVRAM  2.1
com.apple.driver.AppleEFIRuntime    2.0
com.apple.iokit.IOHIDFamily 2.0.0
com.apple.iokit.IOSMBusFamily   1.1
com.apple.security.sandbox  300.0
com.apple.kext.AppleMatch   1.0.0d1
com.apple.driver.AppleKeyStore  2
com.apple.driver.AppleMobileFileIntegrity   1.0.5
com.apple.driver.AppleCredentialManager 1.0
com.apple.driver.KernelRelayHost    1
com.apple.iokit.IOUSBHostFamily 1.1
com.apple.driver.AppleBusPowerController    1.0
com.apple.driver.DiskImages 444.41.1
com.apple.iokit.IOStorageFamily 2.1
com.apple.iokit.IOReportFamily  31
com.apple.driver.AppleFDEKeyStore   28.30
com.apple.driver.AppleACPIPlatform  5.0
com.apple.iokit.IOPCIFamily 2.9
com.apple.iokit.IOACPIFamily    1.4
com.apple.kec.Libm  1
com.apple.kec.pthread   1
com.apple.kec.corecrypto    1.0
</code>```

答:
You have Verdasys Digital Guardian Agent and McAfee installed, both of which have injected kernel extensions that may be causing the panic.

It appears to be happening during an XPC call's security checks. The Simulator is a separate user space sharing the host Mac kernel. My guess is the developers of one or both kernel extensions are not properly handling certain data or are mangling private kernel data structures. $rip is the address of the next instruction. Page faulting on that address means something has gone seriously wrong.

I suggest uninstalling all 3rd-party kernel extensions then attempting to reproduce the problem. If that fixes it then file a bug with Verdasys or McAfee to have them fix their kernel extensions.

Title: iOS Watch Simulator Crashes Mac

Body:
I've been fighting with this for a few days now.  Whenever I run a watchKit App from the simulator my mac will get the black screen of death and reboot my machine.  I am running XCode 8.2.1 running simulators for iPhone 6 or 7 and watches with watchOS 3 for both the original watch and version 2 in both sizes.  The watch simulator will start, but whenever it attempts to launch a watchkit app that was deployed with XCode my machine will crash.  This can be any watchkit app, even a simple Hello World app.

I have also tried completely uninstalling XCode 8 and 7 as well as all of the simulators and derived info, but the watch apps will still crash my machine.  I've filed a bug report with Apple, but they won't reply back to me.  I am also running on a Mid 2014 MacBook Pro with Sierra version 10.12.3.

Has anyone else experienced this?  I'm running out of ideas to fix this and I cannot do anything watch related until I get past this.  I've listed some of the logs from the activity monitor below as well as the Panic report:

ACTIVITY LOG:

Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FD/2940F9BA8137988BB56CC86EFEDC84
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FE/872728C5713EA69D9D3FBC6C653C19
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FE/B838E71BA739F4AA6F121E88E788B5
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext unlinking /var/db/uuidtext/FF/0B49D70BCF30419AD992D76F372F19
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext total: 3188, in_use:2294, marked:0, recent:254, deleted 640
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext slib tree cleaned up (0)
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext uuid tree cleaned up (3)
Mar 24 09:04:17 C02N618RG3QD logd[74]: _purge_uuidtext cleaned up (0)
Mar 24 09:04:17 C02N618RG3QD logd[74]: Purged 114692767 bytes from uuidtext.
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03260b130>: 9223372036854847488.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034800ba0>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03260ac80>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0349017f0>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034a07340>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0324107b0>: 9223372036854855680.000000]
Mar 24 09:04:18 C02N618RG3QD useractivityd[1022]: BUG in libdispatch client: kevent[EVFILT_MACHPORT] monitored resource vanished before the source cancel handler was invoked
Mar 24 09:04:19 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034b0e0c0>: 9223372036854855680.000000]
Mar 24 09:04:19 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0326088d0>: 9223372036854855680.000000]
Mar 24 09:04:19 C02N618RG3QD UserEventAgent[1178]: assertion failed: 16D32 14S471a: com.apple.cts + 20609 [D0046D83-09B7-3C10-A783-396F29B9B380]: 0x0
Mar 24 09:04:21 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:22 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:22 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.quicklook[30456]): Endpoint has been activated through legacy launch(3) APIs. Please switch to XPC or bootstrap_check_in(): com.apple.quicklook
Mar 24 09:04:32 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 1 seconds. Pushing respawn out by 9 seconds.
Mar 24 09:04:33 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:39 C02N618RG3QD IBCocoaTouchImageCatalogTool[30517]: assertion failed: 16D32: libxpc.dylib + 34617 [D3538D2B-EEA9-3C74-890E-6F4AE4F51F0E]: 0x8d
Mar 24 09:04:40 C02N618RG3QD IBCocoaTouchImageCatalogTool[30517]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:42 C02N618RG3QD Interface Builder WatchKit Tool[30530]: assertion failed: 16D32: libxpc.dylib + 34617 [D3538D2B-EEA9-3C74-890E-6F4AE4F51F0E]: 0x8d
Mar 24 09:04:42 --- last message repeated 2 times ---
Mar 24 09:04:42 C02N618RG3QD Interface Builder WatchKit Tool[30530]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:42 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 1 seconds. Pushing respawn out by 9 seconds.
Mar 24 09:04:43 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 --- last message repeated 1 time ---
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: BUG in libdispatch: 16D32 14C89 - 1296 - 0x2
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: BUG in libdispatch: 16D32 14C89 - 1296 - 0x2
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30671]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:47 C02N618RG3QD Interface Builder Cocoa Touch Tool[30670]: assertion failed: 16D32 14C89: libxpc.dylib + 31485 [0339A402-6531-30E9-8BC2-589C463CD6D6]: 0x8d
Mar 24 09:04:48 C02N618RG3QD IBCocoaTouchImageCatalogTool[30687]: BUG in libdispatch: 16D32 14C89 - 1296 - 0x2
Mar 24 09:04:48 C02N618RG3QD IBCocoaTouchImageCatalogTool[30687]: BUG in libdispatch client: kevent[EVFILT_VNODE] add: "Bad file descriptor" - 0x9
Mar 24 09:04:52 C02N618RG3QD com.apple.xpc.launchd[1] (com.mcafee.ssm.ScanManager): Service only ran for 1 seconds. Pushing respawn out by 9 seconds.
Mar 24 09:04:53 C02N618RG3QD com.apple.xpc.launchd[1] (com.apple.nowplayingtouchui): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Mar 24 09:04:58 C02N618RG3QD Simulator (Watch)[30853]: BUG in libdispatch client: kevent[EVFILT_MACHPORT] monitored resource vanished before the source cancel handler was invoked
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe032706fc0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0327081f0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe0326114b0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03250fbf0>: 9223372036854857728.000000]
Mar 24 09:05:00 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe03250d9d0>: 9223372036854857728.000000]

AND

Mar 24 09:05:53 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe034801f40>: 9223372036854861824.000000]
Mar 24 09:05:53 C02N618RG3QD diagnosticd[380]: JSON->NS failed [type" : "u",
        "timestamp" : 58798649826108
      },
      "timeGMTsec" : 1490360753,
      "procid" : {
        "procid" : 30972,
        "_type" : "u"
      },
      "persisted" : {
        "_type" : "b",
        "persisted" : 0
      },
      "thread" : {
        "_type" : "u",
        "thread" : 529028
      },
      "pid" : {
        "pid" : 30972,
        "_type" : "u"
      },
      "procpath" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneSimulator.platform\/Developer\/SDKs\/iPhoneSimulator.sdk\/System\/Library\/CoreServices\/SpringBoard.app\/SpringBoard",
      "SIMULATOR_UDID" : "4855B6A5-7A82-49AE-94E4-DBA2BED65585"
    }]
Mar 24 09:05:53 C02N618RG3QD diagnosticd[380]: Unexpected xpc type [<double: 0x7fe032403a30>: 9223372036854861824.000000]

PANIC REPORT

Anonymous UUID:       56E742E7-D1F7-AB9B-90CC-58BFFAFB991E

Fri Mar 24 09:07:31 2017

*** Panic Report ***
panic(cpu 4 caller 0xffffff8018e05ecd): Kernel trap at 0xffffff8018dfc620, type 14=page fault, registers:
CR0: 0x000000008001003b, CR2: 0xffffff806783403c, CR3: 0x00000002cb9b6256, CR4: 0x00000000001627e0
RAX: 0x00000000ffffff01, RBX: 0x000000002d1e202c, RCX: 0x00000000ffffffa1, RDX: 0x000000000000000a
RSP: 0xffffff921b9fb7c0, RBP: 0xffffff921b9fb7c0, RSI: 0xffffff7f9c364723, RDI: 0xffffff806783403c
R8:  0x0000000000000002, R9:  0x0000000000000ff8, R10: 0xe326417ed3850092, R11: 0xffffff804d3b5bb8
R12: 0x000000000000000a, R13: 0x0000000000000054, R14: 0x0000000000906065, R15: 0xffffff803a652010
RFL: 0x0000000000010206, RIP: 0xffffff8018dfc620, CS:  0x0000000000000008, SS:  0x0000000000000010
Fault CR2: 0xffffff806783403c, Error code: 0x0000000000000000, Fault CPU: 0x4, PL: 0, VF: 1

Backtrace (CPU 4), Frame : Return Address
0xffffff921b9fb450 : 0xffffff8018cf210c
0xffffff921b9fb4d0 : 0xffffff8018e05ecd
0xffffff921b9fb6b0 : 0xffffff8018ca3743
0xffffff921b9fb6d0 : 0xffffff8018dfc620
0xffffff921b9fb7c0 : 0xffffff7f9c33e471
0xffffff921b9fb800 : 0xffffff7f9c33e4fa
0xffffff921b9fb830 : 0xffffff7f9c33e719
0xffffff921b9fb910 : 0xffffff7f9c33e839
0xffffff921b9fb950 : 0xffffff7f9c3604fa
0xffffff921b9fb9a0 : 0xffffff7f9c3603b4
0xffffff921b9fb9c0 : 0xffffff7f9c3474b7
0xffffff921b9fbe60 : 0xffffff7f9c3479e1
0xffffff921b9fbf40 : 0xffffff8202aea6a0
0xffffff921b9fbf50 : 0xffffff8019227066
0xffffff921b9fbfb0 : 0xffffff8018ca3c38
      Kernel Extensions in backtrace:
         com.verdasys.dgagent(23.20.7)[90F4996A-8100-3509-BBCA-9778AAA30E30]@0xffffff7f9c338000->0xffffff7f9c374fff
            dependency: com.apple.security.sandbox(300.0)[8997F7FD-7C04-38F6-86DB-BACDE9137374]@0xffffff7f99937000

BSD process name corresponding to current thread: xpcproxy_sim

Mac OS version:
16D32

Kernel version:
Darwin Kernel Version 16.4.0: Thu Dec 22 22:53:21 PST 2016; root:xnu-3789.41.3~3/RELEASE_X86_64
Kernel UUID: C67A8D03-DEAC-35B8-8F68-06FF7B687215
Kernel slide:     0x0000000018a00000
Kernel text base: 0xffffff8018c00000
__HIB  text base: 0xffffff8018b00000
System model name: MacBookPro11,3 (Mac-2BD1B31983FE1663)

System uptime in nanoseconds: 2958365287234
last loaded kext at 359084323236: com.apple.filesystems.smbfs   3.1.1 (addr 0xffffff7f998b3000, size 425984)
loaded kexts:
com.McAfee.FMPSysCore   1
com.verdasys.dgagent    0023.20.7
com.intel.kext.intelhaxm    1.1.1
com.squirrels.airparrot.framebuffer 5
com.squirrels.driver.AirParrotSpeakers  1.8
com.apple.filesystems.smbfs 3.1.1
com.apple.driver.AppleHWSensor  1.9.5d0
com.apple.filesystems.autofs    3.0
com.apple.driver.AGPM   110.23.14
com.apple.driver.ApplePlatformEnabler   2.7.0d0
com.apple.driver.X86PlatformShim    1.0.0
com.apple.driver.pmtelemetry    1
com.apple.iokit.IOUserEthernet  1.0.1
com.apple.iokit.IOBluetoothSerialManager    5.0.3f1
com.apple.Dont_Steal_Mac_OS_X   7.0.0
com.apple.driver.AppleHV    1
com.apple.driver.AppleOSXWatchdog   1
com.apple.driver.AppleGraphicsDevicePolicy  3.13.79
com.apple.driver.AppleHDAHardwareConfigDriver   278.56
com.apple.driver.AppleHDA   278.56
com.apple.driver.AppleUpstreamUserClient    3.6.4
com.apple.GeForce   10.1.4
com.apple.driver.AppleIntelHD5000Graphics   10.2.2
com.apple.driver.ACPI_SMC_PlatformPlugin    1.0.0
com.apple.driver.AppleFIVRDriver    4.1.0
com.apple.driver.AppleBacklight 170.9.10
com.apple.driver.AppleLPC   3.1
com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport 5.0.3f1
com.apple.nvidia.NVDAStartup    10.1.4
com.apple.driver.AudioAUUC  1.70
com.apple.driver.AppleSMCLMU    208
com.apple.driver.AppleCameraInterface   5.57.0
com.apple.driver.AppleMuxControl    3.13.79
com.apple.driver.AppleIntelSlowAdaptiveClocking 4.0.0
com.apple.driver.AppleIntelFramebufferAzul  10.2.2
com.apple.driver.AppleThunderboltIP 3.0.8
com.apple.driver.AppleMCCSControl   1.2.15
com.apple.driver.AppleUSBDisplays   380
com.apple.iokit.SCSITaskUserClient  394.30.2
com.apple.driver.AppleUSBStorageCoexistentDriver    404.30.1
com.apple.driver.AppleUSBCardReader 404.30.1
com.apple.iokit.IOBluetoothUSBDFU   5.0.3f1
com.apple.driver.AppleUSBTCKeyEventDriver   252
com.apple.driver.AppleUSBTCKeyboard 252
com.apple.driver.AppleUSBTCButtons  252
com.apple.driver.CoreStorageFsck    540.30.1
com.apple.driver.AppleFileSystemDriver  3.0.1
com.apple.AppleFSCompression.AppleFSCompressionTypeDataless 1.0.0d1
com.apple.AppleFSCompression.AppleFSCompressionTypeZlib 1.0.0
com.apple.BootCache 40
com.apple.filesystems.hfs.kext  366.30.3
com.apple.iokit.IOAHCIBlockStorage  295.20.1
com.apple.driver.AppleAHCIPort  326
com.apple.iokit.AppleBCM5701Ethernet    10.2.7
com.apple.driver.AppleFWOHCI    5.5.5
com.apple.driver.AirPort.Brcm4360   1130.3.1a5
com.apple.driver.AppleSmartBatteryManager   161.0.0
com.apple.driver.AppleACPIButtons   5.0
com.apple.driver.AppleRTC   2.0
com.apple.driver.AppleHPET  1.8
com.apple.driver.AppleSMBIOS    2.1
com.apple.driver.AppleACPIEC    5.0
com.apple.driver.AppleAPIC  1.7
com.apple.nke.applicationfirewall   172
com.apple.security.quarantine   3
com.apple.security.TMSafetyNet  8
com.apple.kext.triggers 1.0
com.apple.iokit.IOSerialFamily  11
com.apple.driver.AppleSSE   1.0
com.apple.driver.DspFuncLib 278.56
com.apple.kext.OSvKernDSPLib    525
com.apple.nvidia.driver.NVDAGK100Hal    10.1.4
com.apple.nvidia.driver.NVDAResman  10.1.4
com.apple.iokit.IOSurface   153.3
com.apple.driver.IOPlatformPluginLegacy 1.0.0
com.apple.iokit.IOFireWireIP    2.2.7
com.apple.driver.X86PlatformPlugin  1.0.0
com.apple.driver.IOPlatformPluginFamily 6.0.0d8
com.apple.iokit.IOBluetoothHostControllerUSBTransport   5.0.3f1
com.apple.iokit.IOBluetoothHostControllerTransport  5.0.3f1
com.apple.iokit.IOBluetoothFamily   5.0.3f1
com.apple.driver.AppleHDAController 278.56
com.apple.iokit.IOHDAFamily 278.56
com.apple.driver.AppleSMBusPCI  1.0.14d1
com.apple.driver.AppleBacklightExpert   1.1.0
com.apple.iokit.IONDRVSupport   513.1
com.apple.driver.AppleGraphicsControl   3.13.79
com.apple.iokit.IOSlowAdaptiveClockingFamily    1.0.0
com.apple.AppleGraphicsDeviceControl    3.13.79
com.apple.iokit.IOAcceleratorFamily2    289.32
com.apple.driver.AppleThunderboltEDMSink    4.1.1
com.apple.driver.AppleSMC   3.1.9
com.apple.driver.AppleSMBusController   1.0.14d1
com.apple.iokit.IOGraphicsFamily    513.1
com.apple.driver.AppleUSBComposite  900.4.1
com.apple.driver.AppleUSBAudio  307.7
com.apple.iokit.IOAudioFamily   205.12
com.apple.vecLib.kext   1.2.0
com.apple.iokit.IOUSBMassStorageClass   4.0.4
com.apple.iokit.IOSCSIBlockCommandsDevice   394.30.2
com.apple.iokit.IOUSBMassStorageDriver  131.1.1
com.apple.iokit.IOSCSIArchitectureModelFamily   394.30.2
com.apple.driver.AppleThunderboltDPInAdapter    4.6.1
com.apple.driver.AppleThunderboltDPOutAdapter   4.6.1
com.apple.driver.AppleThunderboltDPAdapterFamily    4.6.1
com.apple.driver.AppleThunderboltPCIUpAdapter   2.1.1
com.apple.driver.AppleThunderboltPCIDownAdapter 2.1.1
com.apple.driver.AppleUSBMultitouch 258
com.apple.driver.usb.IOUSBHostHIDDevice 1.1
com.apple.driver.usb.cdc    5.0.0
com.apple.driver.usb.networking 5.0.0
com.apple.driver.usb.AppleUSBHostCompositeDevice    1.1
com.apple.driver.CoreStorage    540.30.1
com.apple.filesystems.hfs.encodings.kext    1
com.apple.driver.AppleUSBMergeNub   900.4.1
com.apple.driver.usb.AppleUSBHub    1.1
com.apple.driver.AppleXsanScheme    3
com.apple.iokit.IOAHCIFamily    288
com.apple.driver.usb.AppleUSBEHCIPCI    1.1
com.apple.driver.usb.AppleUSBEHCI   1.1
com.apple.iokit.IOEthernetAVBController 1.0.3b4
com.apple.iokit.IOFireWireFamily    4.6.5
com.apple.driver.AppleThunderboltNHI    4.1.8
com.apple.iokit.IOThunderboltFamily 6.3.3
com.apple.iokit.IO80211Family   1200.12.2
com.apple.driver.mDNSOffloadUserClient  1.0.1b8
com.apple.iokit.IONetworkingFamily  3.2
com.apple.driver.corecapture    1.0.4
com.apple.driver.AppleIntelLpssGspi 3.0.60
com.apple.driver.usb.AppleUSBXHCIPCI    1.1
com.apple.driver.usb.AppleUSBXHCI   1.1
com.apple.driver.usb.AppleUSBHostPacketFilter   1.0
com.apple.iokit.IOUSBFamily 900.4.1
com.apple.driver.AppleUSBHostMergeProperties    1.1
com.apple.driver.AppleEFINVRAM  2.1
com.apple.driver.AppleEFIRuntime    2.0
com.apple.iokit.IOHIDFamily 2.0.0
com.apple.iokit.IOSMBusFamily   1.1
com.apple.security.sandbox  300.0
com.apple.kext.AppleMatch   1.0.0d1
com.apple.driver.AppleKeyStore  2
com.apple.driver.AppleMobileFileIntegrity   1.0.5
com.apple.driver.AppleCredentialManager 1.0
com.apple.driver.KernelRelayHost    1
com.apple.iokit.IOUSBHostFamily 1.1
com.apple.driver.AppleBusPowerController    1.0
com.apple.driver.DiskImages 444.41.1
com.apple.iokit.IOStorageFamily 2.1
com.apple.iokit.IOReportFamily  31
com.apple.driver.AppleFDEKeyStore   28.30
com.apple.driver.AppleACPIPlatform  5.0
com.apple.iokit.IOPCIFamily 2.9
com.apple.iokit.IOACPIFamily    1.4
com.apple.kec.Libm  1
com.apple.kec.pthread   1
com.apple.kec.corecrypto    1.0


问:
TypeError: unsupported operand type(s) for /: 'str' and 'float'
I am using Python 2 but I'm getting an error:

```
TypeError: unsupported operand type(s) for /: 'str' and 'float'
```

when the script runs to the last line.  I don't understand which variable is still a string type.

```<code>from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:')
print 'your BMI is %r'%weight/((float(height)/100)**2)
</code>```

答:
```<code>weight = float(weight)
height = float(height)
age = int(age)
</code>```

You forgot to convert the input from string to numeric.  To diagnose:

```<code>print weight, type(weight)
print height, type(height)
print age, type(age)
...
</code>```

Body:
I am using Python 2 but I'm getting an error:

TypeError: unsupported operand type(s) for /: 'str' and 'float'

when the script runs to the last line.  I don't understand which variable is still a string type.

from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:')
print 'your BMI is %r'%weight/((float(height)/100)**2)

Body:
weight = float(weight)
height = float(height)
age = int(age)

You forgot to convert the input from string to numeric.  To diagnose:

print weight, type(weight)
print height, type(height)
print age, type(age)
...


问:
How to clean up a string excluding certain characters
I want to clean up the below string but only get rid of the \n, \r and extra spaces but not the apostrophe(') and other characters like dash(-) and colon(:).

Right now I am using this code but it gets rid of all special characters.

```<code>string = "\n\n\r\n            Scott Hibb's Amazing Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
rx = re.compile('\W+')
string = rx.sub(' ', string).strip()
print(string)
</code>```

How can i do this?

答: Use a character class, like [abc] matches a, b, or c

Body:
I want to clean up the below string but only get rid of the \n, \r and extra spaces but not the apostrophe(') and other characters like dash(-) and colon(:).

Right now I am using this code but it gets rid of all special characters.

string = "\n\n\r\n            Scott Hibb's Amazing Whisky Grilled Baby Back Ribs\r\n                \n\n\n\n"
rx = re.compile('\W+')
string = rx.sub(' ', string).strip()
print(string)

How can i do this?


问:
Data type for storing hour interval
Is there a specific data type that allows you to store data for which hour interval an event has occurred (for example "15.00-15.59", "16.00-16.59" etc)?

If there isn't, what is the best way to store this data?

答:
Yes there is:

https://dev.mysql.com/doc/refman/5.7/en/time.html

So you would need two fields.. time_start and time_end to reflect your case.

Title: Data type for storing hour interval


问:
Want to show custom Geodesic buffer points using local CSV in ArcGIS
I used the Geodesic buffers sample code of ArcGIS from the following link

https://developers.arcgis.com/javascript/3/jssamples/ge_geodesic_buffers.html

Setup the proxy. it worked fine and showed all the points with features.

It was getting the points from this link  http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.csv"

but I wanted to show points from my own CSV file but I didn't find a way to do in this sample code, then I used CSVLayer to show points which worked fine to show my points but it doesn't have features what was in Geodesic buffer. I couldn't add feature layer to it because map didn't contain graphics.

Could you please provide me a way that I can show my own points, just like Geodesic buffer sample does?

答:
If you are using ArcGIS Runtime SDK for .NET v100, you can parse csv file to get lat/lon values, use GeometryEngine.BufferGeodetic method and GraphicsOverlay to display result.

    var overlay = MyMapView.GraphicsOverlays[0];
    foreach (var line in result)
    {
        var longitude = Convert.ToDouble(line["longitude"]);
        var latitude = Convert.ToDouble(line["latitude"]);
        var mp = new MapPoint(longitude, latitude, SpatialReferences.Wgs84);
        var buffer = GeometryEngine.BufferGeodetic(mp, 2000, LinearUnits.Kilometers);
        var graphic = new Graphic(buffer, new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Colors.Blue, null));
        overlay.Graphics.Add(graphic);
    }


问:
How to get size of iPad/iPhone app programmatically in Swift
I'm trying to get the size of my an app programmatically. The app downloads large amounts of audio files, and I'm trying to check that when I delete files, the app size diminishes as expected. So far the only way I know how to do this is by looking in the settings of the iPad, but the numbers there don't seem to be correct always.

```<code>func getAppSize(){
    let paths : NSArray = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
    var errorP = NSErrorPointer()
    let pathDictionary: NSDictionary = NSFileManager.defaultManager().attributesOfFileSystemForPath(paths.firstObject as String, error: errorP)!
    if(pathDictionary.count != 0){
        var fileSystemSizeInBytes: Double = pathDictionary.objectForKey("NSFileSystemSize") as Double
        var fileSystemSizeInMegaBytes : Double = fileSystemSizeInBytes/1000000
        println("Total Space: \(fileSystemSizeInMegaBytes) MB")
    }else{

    }
}
</code>```

Currently I'm just using the File-System Attirbute Key for the File System Size, which I expected to be the size of my current app, but since it is returning 249 GB, its obviouslly reading my entire MacBook File System size, rather than the simulator's document path.

I looked up the other Attribute Key options and found:

```<code>let NSFileSystemSize: NSString!
let NSFileSystemFreeSize: NSString!
let NSFileSystemNodes: NSString!
let NSFileSystemFreeNodes: NSString!
let NSFileSystemNumber: NSString!
</code>```

However, I haven't found a key that specifies the size of the actual space taken by my app. I'm thinking maybe there is a way to get all the nodes, and then add up their sizes, but I'm not quite sure how to do that.

EDIT:
So the bundle does appear to give me my apps size, but without any of the mp3 files I save into the document path. I'm guessing I might be saving them to the wrong spot or something, here is a simplified version of how I save them to the app.

```<code>//Make HTTP Request Ect... before here...
if(data.length > 1000){
    let documentPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
    let uuid = NSUUID().UUIDString
    let localUrl = uuid + ".mp3"
    let destPath = (documentPath[0] as String) + "/" + localUrl
    data.writeToFile(destPath, atomically: true)
    var error: NSErrorPointer = nil
    data.writeToFile(destPath, options: NSDataWritingOptions.DataWritingAtomic, error: error)
    if(error != nil){
        println("data write error: \(error.memory?.localizedDescription)")
    }
}
</code>```

答:
Updated and refactored @lyndsey-scott's answer for Swift 3. I modified the code to return the size in megabytes as a Float64 instead of printing it to the console, since that was appropriate for my purposes.

```<code>private class func appSizeInMegaBytes() -> Float64 { // approximate value

    // create list of directories
    var paths = [Bundle.main.bundlePath] // main bundle
    let docDirDomain = FileManager.SearchPathDirectory.documentDirectory
    let docDirs = NSSearchPathForDirectoriesInDomains(docDirDomain, .userDomainMask, true)
    if let docDir = docDirs.first {
        paths.append(docDir) // documents directory
    }
    let libDirDomain = FileManager.SearchPathDirectory.libraryDirectory
    let libDirs = NSSearchPathForDirectoriesInDomains(libDirDomain, .userDomainMask, true)
    if let libDir = libDirs.first {
        paths.append(libDir) // library directory
    }
    paths.append(NSTemporaryDirectory() as String) // temp directory

    // combine sizes
    var totalSize: Float64 = 0
    for path in paths {
        if let size = bytesIn(directory: path) {
            totalSize += size
        }
    }
    return totalSize / 1000000 // megabytes
}

private class func bytesIn(directory: String) -> Float64? {
    let fm = FileManager.default
    guard let subdirectories = try? fm.subpathsOfDirectory(atPath: directory) as NSArray else {
        return nil
    }
    let enumerator = subdirectories.objectEnumerator()
    var size: UInt64 = 0
    while let fileName = enumerator.nextObject() as? String {
        do {
            let fileDictionary = try fm.attributesOfItem(atPath: directory.appending("/" + fileName)) as NSDictionary
            size += fileDictionary.fileSize()
        } catch let err {
            print("err getting attributes of file \(fileName): \(err.localizedDescription)")
        }
    }
    return Float64(size)
}
</code>```

Body:
I'm trying to get the size of my an app programmatically. The app downloads large amounts of audio files, and I'm trying to check that when I delete files, the app size diminishes as expected. So far the only way I know how to do this is by looking in the settings of the iPad, but the numbers there don't seem to be correct always.

func getAppSize(){
    let paths : NSArray = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
    var errorP = NSErrorPointer()
    let pathDictionary: NSDictionary = NSFileManager.defaultManager().attributesOfFileSystemForPath(paths.firstObject as String, error: errorP)!
    if(pathDictionary.count != 0){
        var fileSystemSizeInBytes: Double = pathDictionary.objectForKey("NSFileSystemSize") as Double
        var fileSystemSizeInMegaBytes : Double = fileSystemSizeInBytes/1000000
        println("Total Space: \(fileSystemSizeInMegaBytes) MB")
    }else{

    }
}

Currently I'm just using the File-System Attirbute Key for the File System Size, which I expected to be the size of my current app, but since it is returning 249 GB, its obviouslly reading my entire MacBook File System size, rather than the simulator's document path.

I looked up the other Attribute Key options and found:

let NSFileSystemSize: NSString!
let NSFileSystemFreeSize: NSString!
let NSFileSystemNodes: NSString!
let NSFileSystemFreeNodes: NSString!
let NSFileSystemNumber: NSString!

However, I haven't found a key that specifies the size of the actual space taken by my app. I'm thinking maybe there is a way to get all the nodes, and then add up their sizes, but I'm not quite sure how to do that.

EDIT:
So the bundle does appear to give me my apps size, but without any of the mp3 files I save into the document path. I'm guessing I might be saving them to the wrong spot or something, here is a simplified version of how I save them to the app.

//Make HTTP Request Ect... before here...
if(data.length > 1000){
    let documentPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
    let uuid = NSUUID().UUIDString
    let localUrl = uuid + ".mp3"
    let destPath = (documentPath[0] as String) + "/" + localUrl
    data.writeToFile(destPath, atomically: true)
    var error: NSErrorPointer = nil
    data.writeToFile(destPath, options: NSDataWritingOptions.DataWritingAtomic, error: error)
    if(error != nil){
        println("data write error: \(error.memory?.localizedDescription)")
    }
}

Body:
Updated and refactored @lyndsey-scott's answer for Swift 3. I modified the code to return the size in megabytes as a Float64 instead of printing it to the console, since that was appropriate for my purposes.

private class func appSizeInMegaBytes() -> Float64 { // approximate value

    // create list of directories
    var paths = [Bundle.main.bundlePath] // main bundle
    let docDirDomain = FileManager.SearchPathDirectory.documentDirectory
    let docDirs = NSSearchPathForDirectoriesInDomains(docDirDomain, .userDomainMask, true)
    if let docDir = docDirs.first {
        paths.append(docDir) // documents directory
    }
    let libDirDomain = FileManager.SearchPathDirectory.libraryDirectory
    let libDirs = NSSearchPathForDirectoriesInDomains(libDirDomain, .userDomainMask, true)
    if let libDir = libDirs.first {
        paths.append(libDir) // library directory
    }
    paths.append(NSTemporaryDirectory() as String) // temp directory

    // combine sizes
    var totalSize: Float64 = 0
    for path in paths {
        if let size = bytesIn(directory: path) {
            totalSize += size
        }
    }
    return totalSize / 1000000 // megabytes
}

private class func bytesIn(directory: String) -> Float64? {
    let fm = FileManager.default
    guard let subdirectories = try? fm.subpathsOfDirectory(atPath: directory) as NSArray else {
        return nil
    }
    let enumerator = subdirectories.objectEnumerator()
    var size: UInt64 = 0
    while let fileName = enumerator.nextObject() as? String {
        do {
            let fileDictionary = try fm.attributesOfItem(atPath: directory.appending("/" + fileName)) as NSDictionary
            size += fileDictionary.fileSize()
        } catch let err {
            print("err getting attributes of file \(fileName): \(err.localizedDescription)")
        }
    }
    return Float64(size)
}


问:
Disable all styles for a container
On my site, I have one CSS file that dictates all the styles for the site, "styles.css".

However, I've recently installed a forum module.

This forum module has its own CSS file, "chatter.css", and it's placed on one of the pages of my site.

Problem is, there's a LOT of conflicting styles going on.

The entire forum is contained within a div with the id of "chatter".

Is there any way I could tell the dom "hey, only apply chatter.css in this div"?

答:
You may put entire css file into #chatter between brackets, but that requires usage of precompiler(SASS,Less).

Like that...

#chatter {
<css file content>
}

Title: Disable all styles for a container


问:
How to delete object from arrayObject in php?
I want delete object from arrayObject in php, but in deleteComputer method show this error: "Warning: Illegal offset type", help me pls, Im starting with php :)

i've:

```<code>       class ControllerList {

            private $computers;

            function __construct() {
                $this->computers= new ArrayObject();

            }

         public function addComputer($computer) {
             $this->computers->append($computer);
         }

         public function deleteComputer($computerNumber) {
             foreach ($this->computers as $value) {
                 if($value->getNumber() == computerNumber){
                    unset($this->computers[$value]);
                    echo 'Delete!!';
                 } else {
                    echo 'Don't delete!!';
                 }
               }
         }

        }
</code>```

Main file:/

```<code>         $list = new ControllerList();

         $computer1 = new Computer();
         $computer1->setNumber(001);
         $computer1->setColor("Black");

         $computer2 = new Computer();
         $computer2->setNumber(002);
         $computer2->setColor("White");

         $list->addComputer($computer1);
         $list->addComputer($computer2);

         $list->deleteComputer(001);  --> error method
</code>```

答:
As with Barmar's solution, I would address your escaping issue here.

```<code> echo 'Don't delete!!';
</code>```

to

```<code>echo "Don't delete!!";
</code>```

or

```<code>echo 'Don\'t delete!!';
</code>```

Additional information on escaping strings can be found here:
Escaping quotation marks in PHP

Body:
I want delete object from arrayObject in php, but in deleteComputer method show this error: "Warning: Illegal offset type", help me pls, Im starting with php :)

i've:

       class ControllerList {

            private $computers;

            function __construct() {
                $this->computers= new ArrayObject();

            }

         public function addComputer($computer) {
             $this->computers->append($computer);
         }

         public function deleteComputer($computerNumber) {
             foreach ($this->computers as $value) {
                 if($value->getNumber() == computerNumber){
                    unset($this->computers[$value]);
                    echo 'Delete!!';
                 } else {
                    echo 'Don't delete!!';
                 }
               }
         }

        }

Main file:/

         $list = new ControllerList();

         $computer1 = new Computer();
         $computer1->setNumber(001);
         $computer1->setColor("Black");

         $computer2 = new Computer();
         $computer2->setNumber(002);
         $computer2->setColor("White");

         $list->addComputer($computer1);
         $list->addComputer($computer2);

         $list->deleteComputer(001);  --> error method

Body:
As with Barmar's solution, I would address your escaping issue here.

 echo 'Don't delete!!';

to

echo "Don't delete!!";

or

echo 'Don\'t delete!!';

Additional information on escaping strings can be found here:
Escaping quotation marks in PHP


问:
Can you rescue from specific errors with messages in ruby?
I'm trying to understand how errors propogate between classes in Ruby. I have this so far:

```<code>class User
  def charge
    puts "charging order soon"
    raise RuntimeError.new("This is a runtime error")
  rescue ArgumentError
    puts "should never gets here"
  end
end

class Runner
  def run
    begin
      User.new.charge
    rescue RuntimeError => e
      puts e.message
    end
  end
end

Runner.new.run
</code>```

When I run this, I get this which seems right:

```<code>$ ruby errors.rb
charging order soon
This is a runtime error
</code>```

Inside runner, can I rescue from the RuntimeError with a specific message? If I have multiple RuntimeErrors being raised around my application, is there any way for the Runner's rescue clause to be raised only for RuntimeErrors with specific messages?

答:
See https://stackoverflow.com/a/23771227/2981429

If you call raise inside a rescue block, the last raised exception will be re-raised.

In your exception block, you can check the message and choose to re-raise or not:

```<code>begin
  User.new.charge
rescue RuntimeError => e
  case e.message
  when "This is a runtime error"
    # put your handler code here
  else
    raise # re-raise the last exception
  end
end
</code>```

However if it's your goal to solely rescue errors that you yourself raise manually, then it's probably easier to define a custom error class instead:

```<code>class MyError < StandardError; end
</code>```

Then instead of raise RuntimeError.new("message") use raise MyError.new("message"), and rescue it normally:

```<code>begin
  User.new.charge
rescue MyError => e
  # handler
end
</code>```

This way you don't have to worry about your rescues interfering with the built-in exceptions.

Body:
I'm trying to understand how errors propogate between classes in Ruby. I have this so far:

class User
  def charge
    puts "charging order soon"
    raise RuntimeError.new("This is a runtime error")
  rescue ArgumentError
    puts "should never gets here"
  end
end

class Runner
  def run
    begin
      User.new.charge
    rescue RuntimeError => e
      puts e.message
    end
  end
end

Runner.new.run

When I run this, I get this which seems right:

$ ruby errors.rb
charging order soon
This is a runtime error

Inside runner, can I rescue from the RuntimeError with a specific message? If I have multiple RuntimeErrors being raised around my application, is there any way for the Runner's rescue clause to be raised only for RuntimeErrors with specific messages?

Body:
See https://stackoverflow.com/a/23771227/2981429

If you call raise inside a rescue block, the last raised exception will be re-raised.

In your exception block, you can check the message and choose to re-raise or not:

begin
  User.new.charge
rescue RuntimeError => e
  case e.message
  when "This is a runtime error"
    # put your handler code here
  else
    raise # re-raise the last exception
  end
end

However if it's your goal to solely rescue errors that you yourself raise manually, then it's probably easier to define a custom error class instead:

class MyError < StandardError; end

Then instead of raise RuntimeError.new("message") use raise MyError.new("message"), and rescue it normally:

begin
  User.new.charge
rescue MyError => e
  # handler
end

This way you don't have to worry about your rescues interfering with the built-in exceptions.


问:
Angular 2 Reactive Forms, select control filled from service
I'm trying to use Angular's reactive forms and I have trouble figuring out how to delay default value binding for drop down lists filled by a service. Here's fragments of my component's code:

```<code>export class TransferComponent {
id: number;
accounts: Account[] = [];
myForm: FormGroup;
transfer: Transfer;

constructor(
    private http: Http,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private transferService: TransferService,
    private accountService: AccountService,
    private router: Router) {
    this.transfer = new Transfer();
    this.myForm = fb.group({
        'id': [null],
        'accountFromId': [this.transfer.accountFromId, Validators.required],
        'accountToId': [this.transfer.accountToId, Validators.required],
        'title': [this.transfer.title, Validators.required],
        'amount': [this.transfer.amount, Validators.required],
        'transferDate': [this.transfer.transferDate, Validators.required]
    });
}

ngOnInit(): void {
    this.accountService.getAccountList()
        .then(accounts => this.accounts = accounts);
    this.route.queryParams.subscribe(params => {
        this.id = params['id'];
        if (this.id) {
            this.transferService.getTransfer(this.id)
                .then(transfer => {
                    this.transfer = transfer;
                    this.myForm.setValue(transfer);
                });
        }
    });
}
</code>```

The idea here is to try and get 'id' parameter, call service for a transfer entity and bind it to form with prefilled drop downs with account entries. Part of my view looks like this:

```<code><select class="form-control"
                id="accountFromInput"
                [formControl]="myForm.controls['accountFromId']">
            <option *ngFor="let acc of this.accounts" value="{{acc.id}}">{{acc.name}}</option>
        </select>
</code>```

Transfer entity binds correctly for most fields, but 'accountFromId' select element is left with empty value selected (options are there, but not selected properly). How should I rewire my component to ensure accountFromId is being bound after getting account values from service and adding them to select?

答:
It turns out I was looking for Promise.all(). I had to wait for both transfer and account[] entities from services and then bind to form. Updated and working code below:</p>

```<code>export class TransferComponent {
id: number;
accounts: Account[] = [];
myForm: FormGroup;
submitted: boolean = false;
saved: boolean = false;

constructor(
    private http: Http,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private transferService: TransferService,
    private accountService: AccountService,
    private router: Router) {
    this.myForm = fb.group({
        'id': [null],
        'accountFromId': [null, Validators.required],
        'accountToId': [null, Validators.required],
        'title': [null, Validators.required],
        'amount': [null, Validators.required],
        'transferDate': [null, Validators.required]
    });
}

ngOnInit(): void {
    var accountPromise:Promise<Account[]> = this.accountService.getAccountList()
        .then(accounts => this.accounts = accounts);
    this.route.queryParams.subscribe(params => {
        this.id = params['id'];
        if (this.id) {
            var transferPromise: Promise<Transfer> = this.transferService.getTransfer(this.id);
            Promise.all([
                accountPromise,
                transferPromise
            ]).then(value => {
                this.myForm.setValue(value[1]);
            })
        }
    })
}
</code>```

Body:
I'm trying to use Angular's reactive forms and I have trouble figuring out how to delay default value binding for drop down lists filled by a service. Here's fragments of my component's code:

export class TransferComponent {
id: number;
accounts: Account[] = [];
myForm: FormGroup;
transfer: Transfer;

constructor(
    private http: Http,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private transferService: TransferService,
    private accountService: AccountService,
    private router: Router) {
    this.transfer = new Transfer();
    this.myForm = fb.group({
        'id': [null],
        'accountFromId': [this.transfer.accountFromId, Validators.required],
        'accountToId': [this.transfer.accountToId, Validators.required],
        'title': [this.transfer.title, Validators.required],
        'amount': [this.transfer.amount, Validators.required],
        'transferDate': [this.transfer.transferDate, Validators.required]
    });
}

ngOnInit(): void {
    this.accountService.getAccountList()
        .then(accounts => this.accounts = accounts);
    this.route.queryParams.subscribe(params => {
        this.id = params['id'];
        if (this.id) {
            this.transferService.getTransfer(this.id)
                .then(transfer => {
                    this.transfer = transfer;
                    this.myForm.setValue(transfer);
                });
        }
    });
}

The idea here is to try and get 'id' parameter, call service for a transfer entity and bind it to form with prefilled drop downs with account entries. Part of my view looks like this:

<select class="form-control"
                id="accountFromInput"
                [formControl]="myForm.controls['accountFromId']">
            <option *ngFor="let acc of this.accounts" value="{{acc.id}}">{{acc.name}}</option>
        </select>

Transfer entity binds correctly for most fields, but 'accountFromId' select element is left with empty value selected (options are there, but not selected properly). How should I rewire my component to ensure accountFromId is being bound after getting account values from service and adding them to select?

Body:
It turns out I was looking for Promise.all(). I had to wait for both transfer and account[] entities from services and then bind to form. Updated and working code below:

export class TransferComponent {
id: number;
accounts: Account[] = [];
myForm: FormGroup;
submitted: boolean = false;
saved: boolean = false;

constructor(
    private http: Http,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private transferService: TransferService,
    private accountService: AccountService,
    private router: Router) {
    this.myForm = fb.group({
        'id': [null],
        'accountFromId': [null, Validators.required],
        'accountToId': [null, Validators.required],
        'title': [null, Validators.required],
        'amount': [null, Validators.required],
        'transferDate': [null, Validators.required]
    });
}

ngOnInit(): void {
    var accountPromise:Promise<Account[]> = this.accountService.getAccountList()
        .then(accounts => this.accounts = accounts);
    this.route.queryParams.subscribe(params => {
        this.id = params['id'];
        if (this.id) {
            var transferPromise: Promise<Transfer> = this.transferService.getTransfer(this.id);
            Promise.all([
                accountPromise,
                transferPromise
            ]).then(value => {
                this.myForm.setValue(value[1]);
            })
        }
    })
}