问:
Release apk wont open w/ firebase installed in react native
I started creating apk file w/ command

"./gradlew assembleRelease"

But when i install the apk on the android phone, the app install failed and it won't open.

Upon investigating the logs and history of my work. I think react-native-firebase is the problem here but I don't know how to fix it.

before I installed react-native-firebase the app release is working as always but
after that the app won't open

Note: I only implement Firebase Notification and Cloud Messaging.

It works in debug mode but not in release.

Edit:
For my further investigation. when I comment out this line with RNfirebase dependencies, the app release work again

Here is my AndroidManifest.xml

```<code> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.sdg.projectdave">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:networkSecurityConfig="@xml/network_security_config"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

<!-- comment out all firebase related and the app will work -->
    <application>

    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
     <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
    <intent-filter>
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
  </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
    <intent-filter>
        <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
    </intent-filter>
    </receiver>
    <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>
    </application>

    <application>
  <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
  <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
    <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED"/>
      <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
      <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
      <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
  </receiver>
  </application>

    <application>

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/launch_screen" />

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_color"
      android:resource="@color/blueish" />

     <meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/>
    </application>

    <!-- data only -->

    <!-- <application ...>
       <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
    </application> -->

</manifest>
</code>```

答:
I finally fixed the issue. the problem is that i declared multiple application tag wrapper "<application>" inside AndroidManifest. it should only used once.

i modify my code like this:

```<code>    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.sdg.projectdave">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:networkSecurityConfig="@xml/network_security_config"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

    <application>

    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
     <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
    <intent-filter>
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
  </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
    <intent-filter>
        <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
    </intent-filter>
    </receiver>
    <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>
    </application>

    <application>
  <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
  <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
    <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED"/>
      <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
      <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
      <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
  </receiver>
  </application>

    <application>

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/launch_screen" />

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_color"
      android:resource="@color/blueish" />

     <meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/>
    </application>

    <!-- data only -->

    <!-- <application ...>
       <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
    </application> -->

</manifest>
</code>```

This made me confused, because it works on debug mode but for some reason in release build it wont install. w/ multiple <application> tag.

Body:
I started creating apk file w/ command

"./gradlew assembleRelease"

But when i install the apk on the android phone, the app install failed and it won't open.

Upon investigating the logs and history of my work. I think react-native-firebase is the problem here but I don't know how to fix it.

before I installed react-native-firebase the app release is working as always but
after that the app won't open

Note: I only implement Firebase Notification and Cloud Messaging.

It works in debug mode but not in release.

Edit:
For my further investigation. when I comment out this line with RNfirebase dependencies, the app release work again

Here is my AndroidManifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.sdg.projectdave">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:networkSecurityConfig="@xml/network_security_config"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

    <application>

    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
     <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
    <intent-filter>
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
  </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
    <intent-filter>
        <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
    </intent-filter>
    </receiver>
    <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>
    </application>

    <application>
  <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
  <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
    <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED"/>
      <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
      <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
      <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
  </receiver>
  </application>

    <application>

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/launch_screen" />

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_color"
      android:resource="@color/blueish" />

     <meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/>
    </application>

</manifest>

Body:
I finally fixed the issue. the problem is that i declared multiple application tag wrapper "<application>" inside AndroidManifest. it should only used once.

i modify my code like this:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.sdg.projectdave">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:networkSecurityConfig="@xml/network_security_config"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

    <application>

    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
     <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
    <intent-filter>
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
  </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
    <intent-filter>
        <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
    </intent-filter>
    </receiver>
    <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>
    </application>

    <application>
  <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
  <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
    <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED"/>
      <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
      <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
      <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
  </receiver>
  </application>

    <application>

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/launch_screen" />

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_color"
      android:resource="@color/blueish" />

     <meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/>
    </application>

    <!-- data only -->

    <!-- <application ...>
       <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
    </application> -->

</manifest>

This made me confused, because it works on debug mode but for some reason in release build it wont install. w/ multiple <application> tag.


来源: stackexchange

问:
How could I get changed value from vuetify select by emitting in atomic design pattern?
I am trying to get the changed value of vuetify v-select by using $emit but it doesn't work.
I divided components by applying atomic design pattern (atoms(child component and not to connect with the store), organisms(parent component)) and vuex stores.
I think $emit data is OK but anything doesn't work after the process.

This is for a new application for management page with
using vue, vuex, vuetify, atomic design connecting to API server.

Components

child component - in atoms folder

```<code><template>
  <v-select
    :items="list"
    :label="label"
    v-model="selected"
    item-value="id"
    item-text="name"
    return-object
    @change="changeSelected"
  ></v-select>
</template>

<script>
export default {
  props: ["list", "label", "defaultSelected"],
  data() {
    return {
      selected: this.defaultSelected
    };
  },
  methods: {
    changeSelected(newValue) {
      console.log(newValue);    // display changed new data
      this.$emit("changeSelected", newValue);
    }
  }
};
</script>

</code>```

parent component - in organisms folder

```<code><template>
  <v-select-child
    :select-label="label"
    :select-list="list"
    :default-selected="selected"
    @change-selected="changeSelected"    // problem issue?
  >
  </v-select-child>
</template>
<script>
import { mapState } from "vuex";
export default {
  data() {
    ...
  },
  computed: {
    ...mapState({
      list: state => state.list
    })
  },
  methods: {
    changeSelected() {
      console.log("changeSelected");    // doesn't work
      this.$store.dispatch("setSelected", { payload: this.selected });
    }
  }
};
</script>
</code>```

vuex stores

index.js

```<code>export default new Vuex.Store({
  modules: {
    xxx
  },
  state: {
    list: [
      {
        name: "aaaaa",
        id: "001"
      },
      {
        name: "bbbbb",
        id: "002"
      }
    ]
  },
  getters: {},
  mutations: {},
  actions: {}
});

</code>```

xxx.js

```<code>export default {
    selected: { id: "001" }
  },

  getters: {
    //
  },

  mutations: {
    updateSelected(state, payload) {
      console.log("payload");    // doesn't work
      console.log(payload);
      state.selected = payload;
      console.log(state.selected);
    }
  },

  actions: {
    setSelected({ commit }, payload) {
      console.log("Action");    // doesn't work
      commit("updateSelected", payload);
    }
  }
};
</code>```

It does not print any console log after changeSelected function.

答:
I found a solution below:

child component

```<code><template>
  <v-select
    :label="label"
    :items="list"
    v-model="selected"
    item-value="id"
    item-text="name"
    return-object
  ></v-select>
</template>

<script>
export default {
  props: ["list", "label", "defaultSelected"],
  computed: {
    selected: {
      get() {
        return this.defaultSelected;
      },
      set(newVal) {
        if (this.selected !== newVal) {
          this.$emit("changeSelected", newVal);
        }
      }
    }
  }
};
</script>
</code>```

parent component

```<code><template>
  <v-select-child
   :label="label"
   :list="list"
   :defaultSelected="selected"
   @changeSelected="changeSelected"  // fix the property using camelCase
  ></v-select-child>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    ...
  },
  computed: {
    ...mapState({
      list: state => state.list
    })
  },
  methods: {
    changeSelected(val) {   // val: changed object value
      this.$store.dispatch("setSelected", { id:val.id });
    }
  }
};
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get the changed value of vuetify v-select by using $emit but it doesn't work.
I divided components by applying atomic design pattern (atoms(child component and not to connect with the store), organisms(parent component)) and vuex stores.
I think $emit data is OK but anything doesn't work after the process.

This is for a new application for management page with
using vue, vuex, vuetify, atomic design connecting to API server.

Components

child component - in atoms folder

<template>
  <v-select
    :items="list"
    :label="label"
    v-model="selected"
    item-value="id"
    item-text="name"
    return-object
    @change="changeSelected"
  ></v-select>
</template>

parent component - in organisms folder

<template>
  <v-select-child
    :select-label="label"
    :select-list="list"
    :default-selected="selected"
    @change-selected="changeSelected"    // problem issue?
  >
  </v-select-child>
</template>

vuex stores

index.js

export default new Vuex.Store({
  modules: {
    xxx
  },
  state: {
    list: [
      {
        name: "aaaaa",
        id: "001"
      },
      {
        name: "bbbbb",
        id: "002"
      }
    ]
  },
  getters: {},
  mutations: {},
  actions: {}
});

xxx.js

export default {
    selected: { id: "001" }
  },

  getters: {
    //
  },

  mutations: {
    updateSelected(state, payload) {
      console.log("payload");    // doesn't work
      console.log(payload);
      state.selected = payload;
      console.log(state.selected);
    }
  },

  actions: {
    setSelected({ commit }, payload) {
      console.log("Action");    // doesn't work
      commit("updateSelected", payload);
    }
  }
};

It does not print any console log after changeSelected function.

Body:
I found a solution below:

child component

<template>
  <v-select
    :label="label"
    :items="list"
    v-model="selected"
    item-value="id"
    item-text="name"
    return-object
  ></v-select>
</template>

<script>
export default {
  props: ["list", "label", "defaultSelected"],
  computed: {
    selected: {
      get() {
        return this.defaultSelected;
      },
      set(newVal) {
        if (this.selected !== newVal) {
          this.$emit("changeSelected", newVal);
        }
      }
    }
  }
};
</script>

parent component

<template>
  <v-select-child
   :label="label"
   :list="list"
   :defaultSelected="selected"
   @changeSelected="changeSelected"  // fix the property using camelCase
  ></v-select-child>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    ...
  },
  computed: {
    ...mapState({
      list: state => state.list
    })
  },
  methods: {
    changeSelected(val) {   // val: changed object value
      this.$store.dispatch("setSelected", { id:val.id });
    }
  }
};
</script>


问:
Python: Neural Network - TypeError: 'History' object is not subscriptable
I have been practicing building and comparing neural networks using Keras and Tensorflow in python, but when I look to plot the models for comparisons I am receiving an error:

```<code>TypeError: 'History' object is not subscriptable
</code>```

Here is my code for the three models:

```<code>############################## Initiate model 1 ###############################
# Model 1 has no hidden layers
from keras.models import Sequential
model1 = Sequential()

# Get layers
from keras.layers import Dense
# Add first layer
n_cols = len(X.columns)
model1.add(Dense(units=n_cols, activation='relu', input_shape=(n_cols,)))
# Add output layer
model1.add(Dense(units=2, activation='softmax'))

# Compile the model
model1.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])

# Define early_stopping_monitor
from keras.callbacks import EarlyStopping
early_stopping_monitor = EarlyStopping(patience=2)

# Fit model
model1.fit(X, y, validation_split=0.33, epochs=30, callbacks=
[early_stopping_monitor], verbose=False)

############################## Initiate model 2 ###############################
# Model 2 has 1 hidden layer that has the mean number of nodes of input and output layer
model2 = Sequential()

# Add first layer
model2.add(Dense(units=n_cols, activation='relu', input_shape=(n_cols,)))
# Add hidden layer
import math
model2.add(Dense(units=math.ceil((n_cols+2)/2), activation='relu'))
# Add output layer
model2.add(Dense(units=2, activation='softmax'))

# Compile the model
model2.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])

# Fit model
model2.fit(X, y, validation_split=0.33, epochs=30, callbacks=
[early_stopping_monitor], verbose=False)

############################## Initiate model 3 ###############################
# Model 3 has 1 hidden layer that is 2/3 the size of the input layer plus the size of the output layer
model3 = Sequential()

# Add first layer
model3.add(Dense(units=n_cols, activation='relu', input_shape=(n_cols,)))
# Add hidden layer
model3.add(Dense(units=math.ceil((n_cols*(2/3))+2), activation='relu'))
# Add output layer
model3.add(Dense(units=2, activation='softmax'))

# Compile the model
model3.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])

# Fit model
model3.fit(X, y, validation_split=0.33, epochs=30, callbacks=
[early_stopping_monitor], verbose=False)

# Plot the models
plt.plot(model1.history['val_loss'], 'r', model2.history['val_loss'], 'b',
model3.history['val_loss'], 'g')
plt.xlabel('Epochs')
plt.ylabel('Validation score')
plt.show()
</code>```

I have no problems with running any of my models, getting predicted probabilities, plotting ROC curves, or plotting PR curves. However, when I attempt to plot the three curves together I am getting an error from this area of my code:

```<code>model1.history['val_loss']

TypeError: 'History' object is not subscriptable
</code>```

Does anyone have experience with this type of error and can lead me to what I am doing wrong?

Thank you in advance.

答:
```<code>history =  model.fit(trainX, trainy, batch_size=50, epochs=200, validation_split=0.3,callbacks=[tensorboard]).history
</code>```

This is another solution have to include .history at the end of the model fit

Body:
I have been practicing building and comparing neural networks using Keras and Tensorflow in python, but when I look to plot the models for comparisons I am receiving an error:

TypeError: 'History' object is not subscriptable

Here is my code for the three models:

############################## Initiate model 1 ###############################
# Model 1 has no hidden layers
from keras.models import Sequential
model1 = Sequential()

# Get layers
from keras.layers import Dense
# Add first layer
n_cols = len(X.columns)
model1.add(Dense(units=n_cols, activation='relu', input_shape=(n_cols,)))
# Add output layer
model1.add(Dense(units=2, activation='softmax'))

# Compile the model
model1.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])

# Define early_stopping_monitor
from keras.callbacks import EarlyStopping
early_stopping_monitor = EarlyStopping(patience=2)

# Fit model
model1.fit(X, y, validation_split=0.33, epochs=30, callbacks=
[early_stopping_monitor], verbose=False)

############################## Initiate model 2 ###############################
# Model 2 has 1 hidden layer that has the mean number of nodes of input and output layer
model2 = Sequential()

# Add first layer
model2.add(Dense(units=n_cols, activation='relu', input_shape=(n_cols,)))
# Add hidden layer
import math
model2.add(Dense(units=math.ceil((n_cols+2)/2), activation='relu'))
# Add output layer
model2.add(Dense(units=2, activation='softmax'))

# Compile the model
model2.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])

# Fit model
model2.fit(X, y, validation_split=0.33, epochs=30, callbacks=
[early_stopping_monitor], verbose=False)

############################## Initiate model 3 ###############################
# Model 3 has 1 hidden layer that is 2/3 the size of the input layer plus the size of the output layer
model3 = Sequential()

# Add first layer
model3.add(Dense(units=n_cols, activation='relu', input_shape=(n_cols,)))
# Add hidden layer
model3.add(Dense(units=math.ceil((n_cols*(2/3))+2), activation='relu'))
# Add output layer
model3.add(Dense(units=2, activation='softmax'))

# Compile the model
model3.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
['accuracy'])

# Fit model
model3.fit(X, y, validation_split=0.33, epochs=30, callbacks=
[early_stopping_monitor], verbose=False)

# Plot the models
plt.plot(model1.history['val_loss'], 'r', model2.history['val_loss'], 'b',
model3.history['val_loss'], 'g')
plt.xlabel('Epochs')
plt.ylabel('Validation score')
plt.show()

I have no problems with running any of my models, getting predicted probabilities, plotting ROC curves, or plotting PR curves. However, when I attempt to plot the three curves together I am getting an error from this area of my code:

model1.history['val_loss']

TypeError: 'History' object is not subscriptable

Does anyone have experience with this type of error and can lead me to what I am doing wrong?

Thank you in advance.

Body:
history =  model.fit(trainX, trainy, batch_size=50, epochs=200, validation_split=0.3,callbacks=[tensorboard]).history

This is another solution have to include .history at the end of the model fit


问:
Preview android cam in tabhost
I have a TabHost in my Android application and I want to preview my camera IN one of my tabs.

Thanks

答:
Use a SurfaceHolder in the sub Activity like you would do in a normal activity (lot of example about it) then insert this activity in a tab in the classical way:</p>

```<code>intent = new Intent(this, PreviewActivity.class);
        tabHost.addTab(tabHost
                .newTabSpec("previewtab")
                .setIndicator(getText(R.string.tab_item_preview),
                        getResources().getDrawable(R.drawable.icon_preview))
                .setContent(intent));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Preview android cam in tabhost

Body:
Use a SurfaceHolder in the sub Activity like you would do in a normal activity (lot of example about it) then insert this activity in a tab in the classical way:

intent = new Intent(this, PreviewActivity.class);
        tabHost.addTab(tabHost
                .newTabSpec("previewtab")
                .setIndicator(getText(R.string.tab_item_preview),
                        getResources().getDrawable(R.drawable.icon_preview))
                .setContent(intent));


问:
How to enter number in this input with the developer tool?
When clicked input-currency it switches to focus input-currency input-currency_focus

I Tried: getElementsByClassName; text; inerhtml; value; write;

Which command can I use?

```<code><div class="sum
            field-wrapper  js_tu_deal_sum ">
<div class="deal-form-select-block">
<button type="button" class="deal-form-pick-button  deal-form-select-block__btn" data-test="deal-select-amount-down" data-tracking="" data-product="" data-action=""><span class="deal-form-pick-button__svg-wrapper">
<svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" class="deal-form-pick-button__svg"><path d="M8.5 12h7a.5.5 0 1 0 0-1h-7a.5.5 0 1 0 0 1z"></path></svg></span></button>
<div class="deal-form-select-block__input">

<div class="input-currency  ">
<input type="tel" autocomplete="off" class="input-currency__input" data-test="deal-amount-input" maxlength="9"
value="2.5">
<div class="input-currency__values">
<span class="input-currency__value">2.5</span>

<span class="input-currency__sign psign">a</span></div></div></div>
<button type="button" class="deal-form-pick-button  deal-form-select-block__btn" data-test="deal-select-amount-up" data-tracking="" data-product="" data-action=""><span class="deal-form-pick-button__svg-wrapper"><svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" class="deal-form-pick-button__svg"><path d="M11 12v3.5a.5.5 0 1 0 1 0V12h3.5a.5.5 0 1 0 0-1H12V7.5a.5.5 0 1 0-1 0V11H7.5a.5.5 0 1 0 0 1H11z"></path></svg></span></button></div></div>```

```

答:
```<code>document.getElementsByClassName('input-currency__input')[0].value = "VALUE"
</code>```

Body:
When clicked input-currency it switches to focus input-currency input-currency_focus

I Tried: getElementsByClassName; text; inerhtml; value; write;

Which command can I use?

<button type="button" class="deal-form-pick-button  deal-form-select-block__btn" data-test="deal-select-amount-down" data-tracking="" data-product="" data-action="">
<svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" class="deal-form-pick-button__svg"><path d="M8.5 12h7a.5.5 0 1 0 0-1h-7a.5.5 0 1 0 0 1z"></path></svg></button>

<input type="tel" autocomplete="off" class="input-currency__input" data-test="deal-amount-input" maxlength="9"
value="2.5">

2.5

a

<button type="button" class="deal-form-pick-button  deal-form-select-block__btn" data-test="deal-select-amount-up" data-tracking="" data-product="" data-action=""><svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor" class="deal-form-pick-button__svg"><path d="M11 12v3.5a.5.5 0 1 0 1 0V12h3.5a.5.5 0 1 0 0-1H12V7.5a.5.5 0 1 0-1 0V11H7.5a.5.5 0 1 0 0 1H11z"></path></svg></button>

```


问:
unable to parse h1 element following execute_script()
I'm trying to scrape the h1 element after the click of a JS link. As I'm new to python, selenium, and beautifulsoup, I'm not sure if what followed the JS execution changes the way parsing works, or if I'm just grabbing the new url improperly. Everything I've tried has returned something different, from Incompleteread, Nonetype object is not callable, [-1, None, -1, None], to a simple None. I'm just not sure where to go after the containers variable, which I left the way it is just to pull the html.

All I'm wanting to pull from this is the name

```<div class="name"> <h1 itemprop="name"> Nicolette Shea </h1> ```

```<code>star_button = driver.find_element_by_css_selector("a[href*='/pornstar/']")

click = driver.execute_script('arguments[0].click();', star_button)

wait = WebDriverWait(driver, 5)

try:
    wait.until(EC.url_contains('-'))
except TimeOutException:
    print("Unable to load")

new_url = driver.current_url

page = pUrl(new_url)

p_read = page.read()
page.close()

p_parse = soup(p_read, 'html.parser')

containers = p_parse.find('div', {'class' : 'name'})

print(containers)
</code>```

答:
Why not after your wait simply load driver.page_source into BeautifulSoup?</p>

```<code>#try:
#except: ....your code
soup = BeautifulSoup(driver.page_source, 'lxml')
names = [item.text for item in soup.select('div.name')]
</code>```

Body:
I'm trying to scrape the h1 element after the click of a JS link. As I'm new to python, selenium, and beautifulsoup, I'm not sure if what followed the JS execution changes the way parsing works, or if I'm just grabbing the new url improperly. Everything I've tried has returned something different, from Incompleteread, Nonetype object is not callable, [-1, None, -1, None], to a simple None. I'm just not sure where to go after the containers variable, which I left the way it is just to pull the html.

All I'm wanting to pull from this is the name

 Nicolette Shea

star_button = driver.find_element_by_css_selector("a[href*='/pornstar/']")

click = driver.execute_script('arguments[0].click();', star_button)

wait = WebDriverWait(driver, 5)

try:
    wait.until(EC.url_contains('-'))
except TimeOutException:
    print("Unable to load")

new_url = driver.current_url

page = pUrl(new_url)

p_read = page.read()
page.close()

p_parse = soup(p_read, 'html.parser')

containers = p_parse.find('div', {'class' : 'name'})

print(containers)

Body:
Why not after your wait simply load driver.page_source into BeautifulSoup?

#try:
#except: ....your code
soup = BeautifulSoup(driver.page_source, 'lxml')
names = [item.text for item in soup.select('div.name')]


问:
Html2Canvas render full div content
I'm trying to use html2canvas to print to pdf the content of a div:

```<code><div #printSection>
  some content
</div>
</code>```

I have a function that serves this purpose:

```<code>public print(el: ElementRef, name: string, orientation: string = 'l') {
    const doc = new jsPDF(orientation, 'px', 'a4');
    html2Canvas(el.nativeElement).then(
      (canvas) => {
        const img = canvas.toDataURL('image/png');
        const ratio = canvas.height / canvas.width;
        const w = doc.internal.pageSize.width;
        const h = w * ratio;
        doc.addImage(img, 'JPEG', 0, 10, w, h);
        doc.save(name);
      }
    );
  }
</code>```

where I pass the element ref as parameter and it exports its content as pdf.
The problem is: this works fine as long as I use a large screen, when my screen gets smaller and the div is not rendered as a whole but it has scroll bars on the sides this function doesn't print the whole div content but it is limited to the visibile section.

Is there a workaround for this issure. I need this print to be independant from the screen it is launched because this app is meant to run on tablets as well.

Thanks for advices.

答:
html2pdf could probably solve your problem. It's built on top of jsPDF and html2canvas.
https://github.com/eKoopmans/html2pdf.js
Give it a try.</p>

Title: Html2Canvas render full div content

Body:
I'm trying to use html2canvas to print to pdf the content of a div:

  some content

I have a function that serves this purpose:

public print(el: ElementRef, name: string, orientation: string = 'l') {
    const doc = new jsPDF(orientation, 'px', 'a4');
    html2Canvas(el.nativeElement).then(
      (canvas) => {
        const img = canvas.toDataURL('image/png');
        const ratio = canvas.height / canvas.width;
        const w = doc.internal.pageSize.width;
        const h = w * ratio;
        doc.addImage(img, 'JPEG', 0, 10, w, h);
        doc.save(name);
      }
    );
  }

where I pass the element ref as parameter and it exports its content as pdf.
The problem is: this works fine as long as I use a large screen, when my screen gets smaller and the div is not rendered as a whole but it has scroll bars on the sides this function doesn't print the whole div content but it is limited to the visibile section.

Is there a workaround for this issure. I need this print to be independant from the screen it is launched because this app is meant to run on tablets as well.

Thanks for advices.


问:
Gap in image - only on mobile - (how to make a responsive website)
I'm trying to make a gap between the bottom of my div and my image disappear.

I tried reducing the bottom margin of the image, which worked...but only on pc, if you were to open my site on a mobile phone the gap would still be there

here is the class for the image and what I wrote for it to prevent the gap from happening but sadly this doesn't work on mobile:

.mountain {margin-bottom: -5px;}

It should've made there be no gap on both PC and mobile, so why is there one. Am I doing something wrong

btw if you guys could possibly open it on mobile (if you don't mind, literally everything changes), I also want to know how what I see on PC can be put at least almost the same thing on mobile

p.s. Here is the photo of the image on PC without changing the margin-bottom, should I add another photo but from mobile?

p.s.s here is the link to my little website . . . https://raynature.github.io/personal-site/

答:
Images by default are inline elements. They follow the baseline of the text of the container they are in (even if there is no text). Add: </p>

```<code>.mountain {
  vertical-align: bottom;
}
</code>```

<p>to your image via your CSS. </p>

Body:
Images by default are inline elements. They follow the baseline of the text of the container they are in (even if there is no text). Add:

.mountain {
  vertical-align: bottom;
}

to your image via your CSS.


问:
Error uploading file using MSGraph in onedrive business account
I use Microsoft graph to create a web application that uploads files to OneDrive.
File upload uses upload session.
https://learn.microsoft.com/ja-jp/graph/api/driveitem-createuploadsession?view=graph-rest-1.0

uploading a file fails if the upload destination account is a Business account.
The error that occurs is
{" error ": {" innerError ": {" code ":" invalidToken "}," code ":" unauthenticated "," message ":" This access token is not valid on this endpoint. "}}.

However, it will succeed if the upload destination is a personal account
By the way, the simple upload will succeed in both business and personal.
Do you know if there are any measures?

The following is the upload procedure.

(1)

```<code>POST /me/drive/root:/sample.txt:/createUploadSession
Authorization: Bearer {bearer token}
Content-Type: application/json
{
  "item": {
    "@microsoft.graph.conflictBehavior": "rename",
    "name": "sample.txt"
  }
}
</code>```

(2)response

```<code>HTTP/1.1 200 OK
Content-Type: application/json

{
  "uploadUrl": "https://our-tenant-my.sharepoint.com/personal/our_tenant_onmicrosoft_com/_api/v2.0/drive/items/aaaa/uploadSession?guid='example'&path='example'&overwrite=False&rename=True&dc=0&tempauth=example",
  "expirationDateTime": "2019-05-24T05:07:08.728Z"
}
</code>```

(3)
Upload bytes to the upload session

```<code>PUT https://our-tenant-my.sharepoint.com/personal/our_tenant_onmicrosoft_com/_api/v2.0/drive/items/aaaa/uploadSession?guid='example'&path='example'&overwrite=False&rename=True&dc=0&tempauth=example
</code>```

(4) return error

```<code>HTTP/1.1 401
{"error":{"innerError":{"code":"invalidToken"},"code":"unauthenticated","message":"This access token is not valid on this endpoint."}}
</code>```

By the way, in case of a personal account, uploadUrl of the response is

```<code>https://api.onedrive.com/rup/example/more~~~
</code>```

Will be back.

I can upload with this path.
UploadUrl is different in the personal account and the business account, is this related to this error?
Is there a way to solve this problem?

答:
This problem has been resolved.
The reason is that the HTTP client of the web application has rearranged the query parameter of the URL.
I used faraday of Ruby on Rails, so I changed this.</p>

Body:
I use Microsoft graph to create a web application that uploads files to OneDrive.
File upload uses upload session.
https://learn.microsoft.com/ja-jp/graph/api/driveitem-createuploadsession?view=graph-rest-1.0

uploading a file fails if the upload destination account is a Business account.
The error that occurs is
{" error ": {" innerError ": {" code ":" invalidToken "}," code ":" unauthenticated "," message ":" This access token is not valid on this endpoint. "}}.

However, it will succeed if the upload destination is a personal account
By the way, the simple upload will succeed in both business and personal.
Do you know if there are any measures?

The following is the upload procedure.

(1)

POST /me/drive/root:/sample.txt:/createUploadSession
Authorization: Bearer {bearer token}
Content-Type: application/json
{
  "item": {
    "@microsoft.graph.conflictBehavior": "rename",
    "name": "sample.txt"
  }
}

(2)response

HTTP/1.1 200 OK
Content-Type: application/json

{
  "uploadUrl": "https://our-tenant-my.sharepoint.com/personal/our_tenant_onmicrosoft_com/_api/v2.0/drive/items/aaaa/uploadSession?guid='example'&path='example'&overwrite=False&rename=True&dc=0&tempauth=example",
  "expirationDateTime": "2019-05-24T05:07:08.728Z"
}

(3)
Upload bytes to the upload session

PUT https://our-tenant-my.sharepoint.com/personal/our_tenant_onmicrosoft_com/_api/v2.0/drive/items/aaaa/uploadSession?guid='example'&path='example'&overwrite=False&rename=True&dc=0&tempauth=example

(4) return error

HTTP/1.1 401
{"error":{"innerError":{"code":"invalidToken"},"code":"unauthenticated","message":"This access token is not valid on this endpoint."}}

By the way, in case of a personal account, uploadUrl of the response is

https://api.onedrive.com/rup/example/more~~~

Will be back.

I can upload with this path.
UploadUrl is different in the personal account and the business account, is this related to this error?
Is there a way to solve this problem?


问:
Fixing image not showing Laravel with data-bg-img
I need to add an image to my laravel blade using data-bg-img

I am new to larvel currently using Laravel 5.8, I have the regular routing, my image is in the image/bg folder which is in the public folder

```<code><section class="inner-header divider parallax layer-overlay overlay-dark-6" data-bg-img="{{asset('/images/bg/bg6.jpg') }}">
</code>```

答:
I would rather use style then data-bg  to make the image appear as a proper CSS background-image, like this:

style="background-image: url(images/bg/bg6.jpg")"

So you code:

```<code><section class="inner-header divider parallax layer-overlay overlay-dark-6" style="background-image: url(images/bg/bg6.jpg")">
</code>```

Hope it helps :D

Body:
I would rather use style then data-bg  to make the image appear as a proper CSS background-image, like this:

style="background-image: url(images/bg/bg6.jpg")"

So you code:

<section class="inner-header divider parallax layer-overlay overlay-dark-6" style="background-image: url(images/bg/bg6.jpg")">

Hope it helps :D


问:
CMS + Java Application Server Integration Architecture
Has anyone integrated a Java application server (e.g. JBoss) with one of the following CMSs (Content Management Systems)?

SDL Tridion

Sitecore

Drupal

I'm looking for one of the above CMSs to create/manange a corporate website which consists mostly of static content coming from the CMS, but also includes integration points into java web applications, which may also in turn use content from the CMS.  (There is a requirement to use one of the above CMSs.)

What CMS and Java web application server architecture have you successfully used in your engagements and corporate web sites to provide seemless integration of CMS site content with Java web applications?

答:
Although it's not one of the CMS above: We use OpenCMS in conjunction with our shop application. In this setup the shop is the primary application built in struts2, EJB 3.0 etc.

Communcation between the shop and OpenCMS happens in two ways (although we currently almost only use first one):

JSON, i.e. read from an URL (a JSP) that returns JSON

Webservice

Both approaches should be doable with the CMS listed above, since they are programming language independent.

Edit: I forgot to mention that both applications run in a JBoss 4.2.3 instance, although you could put the CMS on any other capable server (like plain Tomcat in our case).

ContentLicense: CC BY-SA 2.5


问:
Salesforce: SObject row was retrieved via SOQL without querying the requested field
I'm working on an application that creates and save invoices on salesforce cloud but when i try to create a transaction i get the following error

"SObject row was retrieved via SOQL without querying the requested field: s2cor__Sage_INV_Trade_Document_Type__c.s2cor__Use_Company_Shipping__c"

below is my code for creating the transaction

```<code>SuccessResponse createTransResponse = await client.CreateAsync("s2cor__Sage_INV_Trade_Document__c", transaction);
</code>```

the Transaction class is created like so

```<code>public class Transaction
    {
        public String Name { get; set; }
        public String Id { get; set; }
        public string s2cor__Reference__c { get; set; }
        public String s2cor__Account__c { get; set; }
        public String s2cor__Date__c { get; set; }
        public string s2cor__Trade_Document_Type__c = "a211v0000022YBpAAM"; // use this
        //public string s2cor__Net_Amount__c { get; set; }
        public string s2cor__Currency__c { get; set; }
        public string s2cor__Exchange_Rate__c { get; set; }
    }
</code>```

答: Check for triggers defined on the "s2cor__Sage_INV_Trade_Document__c" SObject in Salesforce. Looks like an error in a trigger to me.</p>

Body:
I'm working on an application that creates and save invoices on salesforce cloud but when i try to create a transaction i get the following error

"SObject row was retrieved via SOQL without querying the requested field: s2cor__Sage_INV_Trade_Document_Type__c.s2cor__Use_Company_Shipping__c"

below is my code for creating the transaction

SuccessResponse createTransResponse = await client.CreateAsync("s2cor__Sage_INV_Trade_Document__c", transaction);

the Transaction class is created like so

public class Transaction
    {
        public String Name { get; set; }
        public String Id { get; set; }
        public string s2cor__Reference__c { get; set; }
        public String s2cor__Account__c { get; set; }
        public String s2cor__Date__c { get; set; }
        public string s2cor__Trade_Document_Type__c = "a211v0000022YBpAAM"; // use this
        //public string s2cor__Net_Amount__c { get; set; }
        public string s2cor__Currency__c { get; set; }
        public string s2cor__Exchange_Rate__c { get; set; }
    }


问:
How do I put async error handling into a separate function?
I'd like to put the error handling showed in the below example into a single function:

```<code>import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x,
                            async (error) => {
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        }
                        )
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, async (error) => {
                            console.log("the error is: ");
                            console.log(error);
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        })
                    );
    }

}
</code>```

However, when I do that, the injected AlertController no longer seems to be available.

```<code>import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    async handleError(error) {
        console.log(error);
        const alert = await this.alertCon.create({
            header: 'Error',
            subHeader: null,
            message: this.errorCodeToMessage[error.status],
            buttons: ['OK']
          });

        await alert.present();
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
    }

}
</code>```

Runtime error:

```<code>    ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'create' of undefined
TypeError: Cannot read property 'create' of undefined
    at TapSubscriber.<anonymous> (api.interceptor.ts:23)
    at step (tslib.es6.js:97)
    at Object.next (tslib.es6.js:78)
    at tslib.es6.js:71
    at new ZoneAwarePromise (zone.js:910)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at resolvePromise (zone.js:831)
    at new ZoneAwarePromise (zone.js:913)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
</code>```

I'm guessing it has something to do with being outside of the closure, but I may be wrong. Why is that happening and what can I do to get a single function to do the error handling?

答:
If you make your errorHandler an arrow function, it should wrap the this context and give you access to the injected AlertController inside of the intercept method.

```<code>handleError = async (error: any) => {
    console.log(error);
    const alert = await this.alertCon.create({
        header: 'Error',
        subHeader: null,
        message: this.errorCodeToMessage[error.status],
        buttons: ['OK']
      });

    await alert.present();
}
</code>```

Body:
I'd like to put the error handling showed in the below example into a single function:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x,
                            async (error) => {
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        }
                        )
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, async (error) => {
                            console.log("the error is: ");
                            console.log(error);
                            const alert = await this.alertCon.create({
                                header: 'Error',
                                subHeader: null,
                                message: this.errorCodeToMessage[error.status],
                                buttons: ['OK']
                              });

                            await alert.present();
                        })
                    );
    }

}

However, when I do that, the injected AlertController no longer seems to be available.

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { tap, flatMap, concatMap } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService, private alertCon: AlertController) { }

    errorCodeToMessage = {
        500: "Internal server error has occurred. Please contact support.",
        404: "This resource can not be found. Please contact support.",
        403: "Access denied. Are you logged in?"
    };

    async handleError(error) {
        console.log(error);
        const alert = await this.alertCon.create({
            header: 'Error',
            subHeader: null,
            message: this.errorCodeToMessage[error.status],
            buttons: ['OK']
          });

        await alert.present();
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.url != this.auth.LOGIN_URL && req.url != this.auth.REGISTRATION_URL)
            return this.auth.getToken()
            .pipe(
                concatMap((token: string) => {
                        req = req.clone({
                            setHeaders: {
                                'authorization': token
                            }
                        });
                    // Also handle errors globally
                    return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
                }))
                ;
        else
            return next.handle(req).pipe(
                        tap(x => x, this.handleError)
                    );
    }

}

Runtime error:

    ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'create' of undefined
TypeError: Cannot read property 'create' of undefined
    at TapSubscriber.<anonymous> (api.interceptor.ts:23)
    at step (tslib.es6.js:97)
    at Object.next (tslib.es6.js:78)
    at tslib.es6.js:71
    at new ZoneAwarePromise (zone.js:910)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at resolvePromise (zone.js:831)
    at new ZoneAwarePromise (zone.js:913)
    at Module.__awaiter (tslib.es6.js:67)
    at TapSubscriber.push../src/app/api/api.interceptor.ts.ApiInterceptor.handleError [as _tapError] (api.interceptor.ts:21)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:55)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at XMLHttpRequest.onLoad (http.js:1640)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)

I'm guessing it has something to do with being outside of the closure, but I may be wrong. Why is that happening and what can I do to get a single function to do the error handling?

Body:
If you make your errorHandler an arrow function, it should wrap the this context and give you access to the injected AlertController inside of the intercept method.

handleError = async (error: any) => {
    console.log(error);
    const alert = await this.alertCon.create({
        header: 'Error',
        subHeader: null,
        message: this.errorCodeToMessage[error.status],
        buttons: ['OK']
      });

    await alert.present();
}


问:
How to migrate elasticsearch indices from version 5.6.2 to 6.8?
I want to update all elasticsearch indices from elasticsearch 5.6.2 to 6.8 version.
I don't want to use X-PACK for migration.
I am not using any elastic products.
So, Is there any proper guideline of way for this migration?

I can do it manually like write new mappings without type for my existing indices and then dump documents from my current indices to new one.
But I've more than 150 indices and it will take time to create new mappings and migrate it manually.

答:
Elastic is the company behind Elasticsearch, so by using that you are using an Elastic product ;-)

The only upgrade assistant I'm aware of is in the free Basic (X-Pack) version of Kibana. Otherwise you'll have to manually run through the features described in https://www.elastic.co/guide/en/kibana/6.0/xpack-upgrade-assistant.html.


问:
Converting Negative Number in String Format to Numeric when Sign as at the end
I have certain numbers within a column of my dataframe that have negative numbers in a string format like this: "500.00-" I need to convert every negative number within the column to numeric format. I'm sure there's an easy way to do this, but I have struggled finding one specific to pandas dataframe. Any help would be greatly appreciated.   </p>

<p>I have tried the basic to_numeric function as shown below, but it doesn't read it in correctly. Also, only some of the numbers within the column are negative, therefore I can't simply remove all the negative signs and multiply the column by 1. </p>

```<code>Q1['Credit'] = pd.to_numeric(Q1['Credit'])
</code>```

答:
Let us consider the following example dataframe:

```<code>Q1 = pd.DataFrame({'Credit':['500.00-', '100.00', '300.00-']})

    Credit
0  500.00-
1   100.00
2  300.00-
</code>```

We can use str.endswith to create a mask which indicates the negative numbers. Then we use np.where to conditionally convert the numbers to negative:

```<code>m1 = Q1['Credit'].str.endswith('-')
m2 = Q1['Credit'].str[:-1].astype(float)
Q1['Credit'] = np.where(m1, -m2, m2)
</code>```

Output

```<code>   Credit
0  -500.0
1   100.0
2  -300.0
</code>```

Body:
I have certain numbers within a column of my dataframe that have negative numbers in a string format like this: "500.00-" I need to convert every negative number within the column to numeric format. I'm sure there's an easy way to do this, but I have struggled finding one specific to pandas dataframe. Any help would be greatly appreciated.

I have tried the basic to_numeric function as shown below, but it doesn't read it in correctly. Also, only some of the numbers within the column are negative, therefore I can't simply remove all the negative signs and multiply the column by 1.

Q1['Credit'] = pd.to_numeric(Q1['Credit'])

Body:
Let us consider the following example dataframe:

Q1 = pd.DataFrame({'Credit':['500.00-', '100.00', '300.00-']})

    Credit
0  500.00-
1   100.00
2  300.00-

We can use str.endswith to create a mask which indicates the negative numbers. Then we use np.where to conditionally convert the numbers to negative:

m1 = Q1['Credit'].str.endswith('-')
m2 = Q1['Credit'].str[:-1].astype(float)
Q1['Credit'] = np.where(m1, -m2, m2)

Output

   Credit
0  -500.0
1   100.0
2  -300.0


问:
Rendering empty space in React
Please see the snippet below. I am trying to render a blinking text, that, when it does not appear, leaves an empty space. However, React is just removing the element all together it seems. How do I properly render an empty space in React? Tried to do some searching and testing with various spans but still didn't get anywhere. Thanks.

class Blinker extends React.Component {
    constructor(props) {
    super();
    this.state = {
      appear: true
    }
    this.blinker = this.blinker.bind(this);
  }

  blinker()  {
    this.setState({appear: !this.state.appear });
  }

  componentDidMount() {
    setInterval(this.blinker, 1000)
  }

  componentWillUnmount() {
    clearInterval(this.blinker);
  }

  render() {
    const name = "testing";
    const underScore = "_";
    const com = "com";
    return (

 { name }

          { (this.state.appear) ? underScore : ' '}

 { com }

    );
  }
}

ReactDOM.render(<Blinker />, app);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test {
  display: inline-block;
}</code>```

```

答:
It is because the three nested lines get transpiled as individual children of the parent div element, without taking the spaces into account. Solution is putting a space explicitly between the elements:</p>

```<code><div>
    <div id="test"> { name } </div>
    {''}
    <div id="test">
          { (this.state.appear) ? underScore : "\u00a0\u00a0"}
    {''}
    </div>
        <div id="test"> { com } </div>
</div>
</code>```

Title: Rendering empty space in React

Body:
Please see the snippet below. I am trying to render a blinking text, that, when it does not appear, leaves an empty space. However, React is just removing the element all together it seems. How do I properly render an empty space in React? Tried to do some searching and testing with various spans but still didn't get anywhere. Thanks.

class Blinker extends React.Component {
    constructor(props) {
    super();
    this.state = {
      appear: true
    }
    this.blinker = this.blinker.bind(this);
  }

  blinker()  {
    this.setState({appear: !this.state.appear });
  }

  componentDidMount() {
    setInterval(this.blinker, 1000)
  }

  componentWillUnmount() {
    clearInterval(this.blinker);
  }

  render() {
    const name = "testing";
    const underScore = "_";
    const com = "com";
    return (

 { name }

          { (this.state.appear) ? underScore : ' '}

 { com }

    );
  }
}

ReactDOM.render(<Blinker />, app);

#test {
  display: inline-block;
}

Body:
It is because the three nested lines get transpiled as individual children of the parent div element, without taking the spaces into account. Solution is putting a space explicitly between the elements:

<div>
    <div id="test"> { name } </div>
    {''}
    <div id="test">
          { (this.state.appear) ? underScore : "\u00a0\u00a0"}
    {''}
    </div>
        <div id="test"> { com } </div>
</div>


问:
Mongoose: How to populate sub properties from within a schema's virtual properties
I have a mongodb schema defined using mongoose and I have some sub documents nested over multiple levels. I want to be able to access these (populated) subdocuments within another schema's virtual properties but I can't seem to do so. I seem to be able to access the documents at the first level of nesting but not further down.

Here's an example of my schemas:

```<code>
const SchemaA = {
   name: {type: string}
   items: [
     {
      schemaB: {
       type: schema.type.ObjectId,
       ref: "B"
      }
     }
   ]
}
</code>```

```<code>const SchemaB = {
   name: {type: string}
   schemaC: {
       type: schema.type.ObjectId,
       ref: "C"
      }
}
</code>```

```<code>const SchemaC = {
   types: [{label: {type: String}}]
}

</code>```

What I want to be able to do is access the SchemaC.types from inside a virtual property on SchemaA.

Here's what I want to achieve:

```<code>
SchemaA.virtual("types").get(function(){
   return this.items.map(item => {
       return {name: item.schemaB.name, types: item.schemaB.SchemaC.types}
   })
})

</code>```

From the above item.schemaB seems to populate just fine but item.schemaB.SchemaC seems to just be the objectId of schemaC.

I'm not sure if this is even possible, to be honest, but I can't seem to find a definitive answer anywhere online so I'm hoping someone on here can help. Thanks!

答:
So in mongoose you need to use the populate method.

```<code> .populate({
    path: 'schemaB',
    populate: {
      path: 'schemaC'
    }
  });
</code>```

mongoose populate

Body:
I have a mongodb schema defined using mongoose and I have some sub documents nested over multiple levels. I want to be able to access these (populated) subdocuments within another schema's virtual properties but I can't seem to do so. I seem to be able to access the documents at the first level of nesting but not further down.

Here's an example of my schemas:

const SchemaA = {
   name: {type: string}
   items: [
     {
      schemaB: {
       type: schema.type.ObjectId,
       ref: "B"
      }
     }
   ]
}

const SchemaB = {
   name: {type: string}
   schemaC: {
       type: schema.type.ObjectId,
       ref: "C"
      }
}

const SchemaC = {
   types: [{label: {type: String}}]
}

What I want to be able to do is access the SchemaC.types from inside a virtual property on SchemaA.

Here's what I want to achieve:

SchemaA.virtual("types").get(function(){
   return this.items.map(item => {
       return {name: item.schemaB.name, types: item.schemaB.SchemaC.types}
   })
})

From the above item.schemaB seems to populate just fine but item.schemaB.SchemaC seems to just be the objectId of schemaC.

I'm not sure if this is even possible, to be honest, but I can't seem to find a definitive answer anywhere online so I'm hoping someone on here can help. Thanks!

Body:
So in mongoose you need to use the populate method.

 .populate({
    path: 'schemaB',
    populate: {
      path: 'schemaC'
    }
  });

mongoose populate


问:
Error: Custom Code Problem in callback: RangeError: Invalid status code: 0
I was creating apps retrieving/writing data from API and using http native for android apps. Get method is okay now. But, When I am using post and patch to save data, the method is not working yet.

Could you please guide me how to save data using POST? Here is my code as below :

In service.ts,

```<code> updateProfile(userProfile) {
    console.log("UpdatePro_"+JSON.stringify(userProfile));
    return this.http.patch(this.mcs.mobileBackend.getCustomCodeUrl(mcsConfig.environment + '_api_care/my/profile'), userProfile, this.getMcsHeadersString());
  }

getMcsHeadersString() {
    var cheaders = {};
    for (let key in this.mcs.mobileBackend.getHttpHeaders()) {
      cheaders[key]= this.mcs.mobileBackend.getHttpHeaders()[key];
    }
    //console.log("STring_HeaderKey_"+cheaders['_keys']+"HeaderValue_"+cheaders['_values']);
    delete cheaders['_keys'];
    delete cheaders['_values'];
    return cheaders;
  }

</code>```

In profileedit.ts

```<code>save() {

    this.mcsService.updateProfile(this.userProfile).then((res) => {

      console.log("testUp"+this.userProfile);
      this.router.navigate(['menu/profile']);
    }, (err) => {
      console.log("Invalid_"+err.error);
      this.presentAlert(err.error);
    }
    );
  }
</code>```

The error message shows that as below :

```<code>{"message":"Custom Code Problem in callback: RangeError: Invalid status code: 0"}

Custom Code Problem in callback:
request:
 patch  /profile
caused unhandled error:
 RangeError: Invalid status code: 0
    at ServerResponse.writeHead (_http_server.js:192:11)
    at ServerResponse.res.writeHead (/u01/app/mobile_ccc/mcs-node-router/mcs-node-server.js:765:35)
    at ServerResponse._implicitHeader (_http_server.js:157:8)
    at ServerResponse.OutgoingMessage.end (_http_outgoing.js:571:10)
    at ServerResponse.send (/u01/app/mobile_ccc/node-configurations/6.10/node_modules/express/lib/response.js:205:10)
    at getMyProfileRow.then.catch (/u01/app/mobile_ccc/custom_code_modules/01fead32-6294-4f8e-8dcb-fa405af7d75a_6/rest_api/custom/my/router_dbtable.js:545:36)
</code>```

答: The answer is I need to parse the JSON obj such as this.userProfile.user_name= JSON.parse(mcsService.userProfile).user_name; </p>

Body:
I was creating apps retrieving/writing data from API and using http native for android apps. Get method is okay now. But, When I am using post and patch to save data, the method is not working yet.

Could you please guide me how to save data using POST? Here is my code as below :

In service.ts,

 updateProfile(userProfile) {
    console.log("UpdatePro_"+JSON.stringify(userProfile));
    return this.http.patch(this.mcs.mobileBackend.getCustomCodeUrl(mcsConfig.environment + '_api_care/my/profile'), userProfile, this.getMcsHeadersString());
  }

getMcsHeadersString() {
    var cheaders = {};
    for (let key in this.mcs.mobileBackend.getHttpHeaders()) {
      cheaders[key]= this.mcs.mobileBackend.getHttpHeaders()[key];
    }
    //console.log("STring_HeaderKey_"+cheaders['_keys']+"HeaderValue_"+cheaders['_values']);
    delete cheaders['_keys'];
    delete cheaders['_values'];
    return cheaders;
  }

In profileedit.ts

save() {

    this.mcsService.updateProfile(this.userProfile).then((res) => {

      console.log("testUp"+this.userProfile);
      this.router.navigate(['menu/profile']);
    }, (err) => {
      console.log("Invalid_"+err.error);
      this.presentAlert(err.error);
    }
    );
  }

The error message shows that as below :

{"message":"Custom Code Problem in callback: RangeError: Invalid status code: 0"}

Custom Code Problem in callback:
request:
 patch  /profile
caused unhandled error:
 RangeError: Invalid status code: 0
    at ServerResponse.writeHead (_http_server.js:192:11)
    at ServerResponse.res.writeHead (/u01/app/mobile_ccc/mcs-node-router/mcs-node-server.js:765:35)
    at ServerResponse._implicitHeader (_http_server.js:157:8)
    at ServerResponse.OutgoingMessage.end (_http_outgoing.js:571:10)
    at ServerResponse.send (/u01/app/mobile_ccc/node-configurations/6.10/node_modules/express/lib/response.js:205:10)
    at getMyProfileRow.then.catch (/u01/app/mobile_ccc/custom_code_modules/01fead32-6294-4f8e-8dcb-fa405af7d75a_6/rest_api/custom/my/router_dbtable.js:545:36)


问:
Question about recoding categorical variables in R
Very green R user here. I have to categorical variables: One is, committee crime against child or has mental health issues (dichotomous, 1= crime and 0 = mental health) and committed crime against child or has substance abuse issues (dichotomous, 1= crime and 0 = substance abuse). I'd like to combine these groups so I will have a dichotomous, crime against child and mental health or substance abuse group. What would be the best way to do this? I have been playing around with "if" statements but to no avail.

I have been playing around with "if" statements but to no avail. I want to make a new variable in my dataset (com) that combines crime against child (1) and mental health/substance abuse (0)

```<code>x$com <- if(x$Group.finalCvsM == 1) {
  x$com("1") }
  if(x$Group.finalCvsS == 1) {
    x$com("1") }
  if(x$Group.finalCvsM == 0) {
    x$com("0") }
    if(x$Group.finalCvsS == 0) {
      x$com("0") }
</code>```

答:
Because your data is coded as binary 0/1, we can just use the logical OR operator, |.

```<code>## very nice way to solve this particular problem
x$com = x$Group.finalCvsM | x$Group.finalCvsS
## The result will be TRUE or FALSE.
## If you want 1/0 instead, then wrap it in as.integer:
x$com = as.integer(x$Group.finalCvsM | x$Group.finalCvsS)
</code>```

In general, ifelse() is a vectorized version of if that is made for cases like this. See the help page ?ifelse for some detail. Here you would use it as:

```<code>x$com = ifelse(x$Group.finalCvsM == 1 | x$Group.finalCvsS == 1, 1, 0)
</code>```

(Note:: since your question doesn't give sample input and desired output, I'm not 100% sure you want OR |. Maybe you want &? Both work fine, use whichever meets your goal.)

Body:
Very green R user here. I have to categorical variables: One is, committee crime against child or has mental health issues (dichotomous, 1= crime and 0 = mental health) and committed crime against child or has substance abuse issues (dichotomous, 1= crime and 0 = substance abuse). I'd like to combine these groups so I will have a dichotomous, crime against child and mental health or substance abuse group. What would be the best way to do this? I have been playing around with "if" statements but to no avail.

I have been playing around with "if" statements but to no avail. I want to make a new variable in my dataset (com) that combines crime against child (1) and mental health/substance abuse (0)

x$com <- if(x$Group.finalCvsM == 1) {
  x$com("1") }
  if(x$Group.finalCvsS == 1) {
    x$com("1") }
  if(x$Group.finalCvsM == 0) {
    x$com("0") }
    if(x$Group.finalCvsS == 0) {
      x$com("0") }

Body:
Because your data is coded as binary 0/1, we can just use the logical OR operator, |.

## very nice way to solve this particular problem
x$com = x$Group.finalCvsM | x$Group.finalCvsS
## The result will be TRUE or FALSE.
## If you want 1/0 instead, then wrap it in as.integer:
x$com = as.integer(x$Group.finalCvsM | x$Group.finalCvsS)

In general, ifelse() is a vectorized version of if that is made for cases like this. See the help page ?ifelse for some detail. Here you would use it as:

x$com = ifelse(x$Group.finalCvsM == 1 | x$Group.finalCvsS == 1, 1, 0)

(Note:: since your question doesn't give sample input and desired output, I'm not 100% sure you want OR |. Maybe you want &? Both work fine, use whichever meets your goal.)


问:
CakePHP displaying checkbox options and corresponding values from database
Background

I have a 'doctors' and a 'hospitals' table. They are linked(many to many) by a 'doctor_hospital' table.

Problem

While adding a doctor I want multiple check-boxes for selecting hospitals. The problem is I can't display hospitals 'name' as options and corresponding 'id' as values from the database.

What I have tried

The best I can do(and not get any error) is this:

Code

controller.php

```<code>$hospitals = $this->Hcp->Hospitals->find('all', ['fields' => ['id', 'name']]);
</code>```

add.ctp

```<code><?php
   foreach ($hospitals as $hospital) {
   echo $this->Form->control('hospitals', ['type' => 'select',
                                           'multiple' => 'checkbox',
                                            $hospital->id => $hospital->name
                                          ]);
            }
      ?>
</code>```

What I want

when selecting the boxes, display 'name' but submit the corresponding 'id' back to the controller.

答:
You should use 'form->checkbox' instead 'form->control'</p>

```<code><?php
       foreach ($hospitals as $hospital) {
          echo "<label>";
          echo $this->Form->checkbox('hospitals', ['value'=>$hospital->id]);
          echo $hospital->name. "</label>";
       }
?>
</code>```

Body:
Background

I have a 'doctors' and a 'hospitals' table. They are linked(many to many) by a 'doctor_hospital' table.

Problem

While adding a doctor I want multiple check-boxes for selecting hospitals. The problem is I can't display hospitals 'name' as options and corresponding 'id' as values from the database.

What I have tried

The best I can do(and not get any error) is this:

Code

controller.php

$hospitals = $this->Hcp->Hospitals->find('all', ['fields' => ['id', 'name']]);

add.ctp

<?php
   foreach ($hospitals as $hospital) {
   echo $this->Form->control('hospitals', ['type' => 'select',
                                           'multiple' => 'checkbox',
                                            $hospital->id => $hospital->name
                                          ]);
            }
      ?>

What I want

when selecting the boxes, display 'name' but submit the corresponding 'id' back to the controller.

Body:
You should use 'form->checkbox' instead 'form->control'

<?php
       foreach ($hospitals as $hospital) {
          echo "<label>";
          echo $this->Form->checkbox('hospitals', ['value'=>$hospital->id]);
          echo $hospital->name. "</label>";
       }
?>


问:
Bokeh: Models must be owned by only a single document
I'm working with Bokeh 0.12.2 in a Jupyter notebook and it frequently throws exceptions about "Models must be owned by only a single document":

```<code>---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-23-f50ac7abda5e> in <module>()
      2     ea.legend.label_text_font_size = '10pt'
      3
----> 4 show(column([co2, co, nox, o3]))

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in show(obj, browser, new, notebook_handle)
    308     '''
    309     if obj not in _state.document.roots:
--> 310         _state.document.add_root(obj)
    311     return _show_with_state(obj, _state, browser, new, notebook_handle=notebook_handle)
    312

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in add_root(self, model)
    443             self._roots.append(model)
    444         finally:
--> 445             self._pop_all_models_freeze()
    446         self._trigger_on_change(RootAddedEvent(self, model))
    447

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in _pop_all_models_freeze(self)
    343         self._all_models_freeze_count -= 1
    344         if self._all_models_freeze_count == 0:
--> 345             self._recompute_all_models()
    346
    347     def _invalidate_all_models(self):

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in _recompute_all_models(self)
    367             d._detach_document()
    368         for a in to_attach:
--> 369             a._attach_document(self)
    370         self._all_models = recomputed
    371         self._all_models_by_name = recomputed_by_name

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\model.py in _attach_document(self, doc)
     89         '''This should only be called by the Document implementation to set the document field'''
     90         if self._document is not None and self._document is not doc:
---> 91             raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self))
     92         doc.theme.apply_to_model(self)
     93         self._document = doc

RuntimeError: Models must be owned by only a single document, <bokeh.models.tickers.DaysTicker object at 0x00000000042540B8> is already in a doc
</code>```

The trigger is always calling show(...) (although never the first time after kernel start-up, only subsequent calls).

Based on the docs, I thought reset_output() would return my notebook to an operable state but the exception persists. Through trial-and-error, I've determined it's necessary to also re-define everything being passing to show(). That makes interactive work cumbersome and error-prone.

[Ref]:

reset_output(state=None)

  Clear the default state of all output modes.

  Returns:    None

Am I right about reset_output() -- is it supposed to resolve the situation causing this exception?

Else, how do I avoid this kind of exception?

答:
Seems it can by fixed by differentiating the source name
Like this: </p>

```<code>source1 = df
p1.circle('A', 'B', source=source1)

source2 = df
p2 = figure()
p2.circle('C', 'D', source=source2)

sourceN = df
p2 = figure()
p2.circle('X', 'Y', source=sourceN)
</code>```

Body:
I'm working with Bokeh 0.12.2 in a Jupyter notebook and it frequently throws exceptions about "Models must be owned by only a single document":

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-23-f50ac7abda5e> in <module>()
      2     ea.legend.label_text_font_size = '10pt'
      3
----> 4 show(column([co2, co, nox, o3]))

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\io.py in show(obj, browser, new, notebook_handle)
    308     '''
    309     if obj not in _state.document.roots:
--> 310         _state.document.add_root(obj)
    311     return _show_with_state(obj, _state, browser, new, notebook_handle=notebook_handle)
    312

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in add_root(self, model)
    443             self._roots.append(model)
    444         finally:
--> 445             self._pop_all_models_freeze()
    446         self._trigger_on_change(RootAddedEvent(self, model))
    447

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in _pop_all_models_freeze(self)
    343         self._all_models_freeze_count -= 1
    344         if self._all_models_freeze_count == 0:
--> 345             self._recompute_all_models()
    346
    347     def _invalidate_all_models(self):

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\document.py in _recompute_all_models(self)
    367             d._detach_document()
    368         for a in to_attach:
--> 369             a._attach_document(self)
    370         self._all_models = recomputed
    371         self._all_models_by_name = recomputed_by_name

C:\Users\pokeeffe\AppData\Local\Continuum\Anaconda3\lib\site-packages\bokeh\model.py in _attach_document(self, doc)
     89         '''This should only be called by the Document implementation to set the document field'''
     90         if self._document is not None and self._document is not doc:
---> 91             raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self))
     92         doc.theme.apply_to_model(self)
     93         self._document = doc

RuntimeError: Models must be owned by only a single document, <bokeh.models.tickers.DaysTicker object at 0x00000000042540B8> is already in a doc

The trigger is always calling show(...) (although never the first time after kernel start-up, only subsequent calls).

Based on the docs, I thought reset_output() would return my notebook to an operable state but the exception persists. Through trial-and-error, I've determined it's necessary to also re-define everything being passing to show(). That makes interactive work cumbersome and error-prone.

[Ref]:

reset_output(state=None)

  Clear the default state of all output modes.

  Returns:    None

Am I right about reset_output() -- is it supposed to resolve the situation causing this exception?

Else, how do I avoid this kind of exception?

Body:
Seems it can by fixed by differentiating the source name
Like this:

source1 = df
p1.circle('A', 'B', source=source1)

source2 = df
p2 = figure()
p2.circle('C', 'D', source=source2)

sourceN = df
p2 = figure()
p2.circle('X', 'Y', source=sourceN)


问:
Possible to link my static library with a dynamic library in Xcode?
I am currently creating a static library that contains functionality I want to provide to some other applications. However, my static library requires libxml2.dylib and compiling my static library fails at the moment because it's having trouble accessing the dylib. Is there a way to link my static lib with a dynamic lib? </p>

答:
Yes, this is possible. However, the resulting static library will have a run-time dependency to libxml2. Notice that you will have to specify the location of the dynamic library at linktime using the -L switch. Assuming you have installed libxml2 using MacPorts the path is /opt/local/lib.

```<code>g++ -staticlib -o libyourlib.a file1.o file2.o -L/opt/local/lib -lxml2
</code>```

Body:
Yes, this is possible. However, the resulting static library will have a run-time dependency to libxml2. Notice that you will have to specify the location of the dynamic library at linktime using the -L switch. Assuming you have installed libxml2 using MacPorts the path is /opt/local/lib.

g++ -staticlib -o libyourlib.a file1.o file2.o -L/opt/local/lib -lxml2


问:
Random numbers are generated twice when verifying email
I'm new to PHP. I'm currently doing an email validation. My code is supposed to generate a random number, send to user via email and verify it when user enters.

Here is my code:

```<code><?php

require 'PHPMailer/PHPMailerAutoload.php';

session_start();

// initializing variables
$email = $_SESSION ['email'];
$user_code = "";
$errors = array();

// generate a four digit random number
$gen_code = strval (rand (10000, 99999));

// send code to user email

// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'register');

// REGISTER USER
if (isset($_POST['email_confirm'])) {

  // receive all input values from the form
  $user_code = mysqli_real_escape_string($db, $_POST['code']);

  // check whether both codes match
  if ($user_code != $gen_code) { array_push($errors, "The codes do not match"); }
  else {
    // set isConfirmed == true
    if (count($errors) == 0) {
        $query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
        mysqli_query($db, $query);
        $_SESSION['email'] = $email;
        header('location: user_details.php');
    }
  }
}
?>
</code>```

Here email_confirm is the name of my submit button and code is the name of text box.

It all works fine when page is first loaded. I get an email with a random integer.

Problem starts when I click my submit button. I receive another email with different number and the number I already entered is not equal to the one I received from email.

Please help

答:
If this is a simpler and an experimental application, you should store gen_code in this session soon after its sent to the user confirmation email. Otherwise, store the code in db and retrieve it when your application receives email confirm POST request and compare the code that was sent by the user against the session or db wherever you'd stored it.</p>

```<code>if (isset($_POST['email_confirm'])) {
    // receive all input values from the form
    $code = $_SESSION['gen_code']; // in case you would wish to store and retrieve code from db, replace this code with one which retrieved from db by email id... SELECT code from user where email=$email
    $user_code = mysqli_real_escape_string($db, $_POST['code']);
    // check whether both codes match
    if ($user_code != $code) {
        array_push($errors, "The codes do not match");
    } else {
        if (count($errors) == 0) {
            $query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
            mysqli_query($db, $query);
            $_SESSION['email'] = $email;
            header('location: user_details.php');
        }
     }
}
</code>```

Body:
I'm new to PHP. I'm currently doing an email validation. My code is supposed to generate a random number, send to user via email and verify it when user enters.

Here is my code:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

session_start();

// initializing variables
$email = $_SESSION ['email'];
$user_code = "";
$errors = array();

// generate a four digit random number
$gen_code = strval (rand (10000, 99999));

// send code to user email

// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'register');

// REGISTER USER
if (isset($_POST['email_confirm'])) {

  // receive all input values from the form
  $user_code = mysqli_real_escape_string($db, $_POST['code']);

  // check whether both codes match
  if ($user_code != $gen_code) { array_push($errors, "The codes do not match"); }
  else {
    // set isConfirmed == true
    if (count($errors) == 0) {
        $query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
        mysqli_query($db, $query);
        $_SESSION['email'] = $email;
        header('location: user_details.php');
    }
  }
}
?>

Here email_confirm is the name of my submit button and code is the name of text box.

It all works fine when page is first loaded. I get an email with a random integer.

Problem starts when I click my submit button. I receive another email with different number and the number I already entered is not equal to the one I received from email.

Please help

Body:
If this is a simpler and an experimental application, you should store gen_code in this session soon after its sent to the user confirmation email. Otherwise, store the code in db and retrieve it when your application receives email confirm POST request and compare the code that was sent by the user against the session or db wherever you'd stored it.

if (isset($_POST['email_confirm'])) {
    // receive all input values from the form
    $code = $_SESSION['gen_code']; // in case you would wish to store and retrieve code from db, replace this code with one which retrieved from db by email id... SELECT code from user where email=$email
    $user_code = mysqli_real_escape_string($db, $_POST['code']);
    // check whether both codes match
    if ($user_code != $code) {
        array_push($errors, "The codes do not match");
    } else {
        if (count($errors) == 0) {
            $query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
            mysqli_query($db, $query);
            $_SESSION['email'] = $email;
            header('location: user_details.php');
        }
     }
}


问:
Laravel - Setting null to model columns has no effect
I'm trying to set a null value on a Model column but it gets ignored and it doesn't update.

```<code>if($rol_colegio)
    $update_pl['rol_colegio'] = $rol_colegio; //$rol_colegio may be null

$usuario->update($update_pl);
</code>```

The data does get updated successfully when I try to use non-null data, but if the variable is null this entry doesn't get updated.

What would be the cause of this?

答:
Just simply do like this.</p>

```<code>$update_pl['rol_colegio'] = $rol_colegio; //$rol_colegio may be null

$usuario->update($update_pl);
</code>```

Body:
I'm trying to set a null value on a Model column but it gets ignored and it doesn't update.

if($rol_colegio)
    $update_pl['rol_colegio'] = $rol_colegio; //$rol_colegio may be null

$usuario->update($update_pl);

The data does get updated successfully when I try to use non-null data, but if the variable is null this entry doesn't get updated.

What would be the cause of this?

Body:
Just simply do like this.

$update_pl['rol_colegio'] = $rol_colegio; //$rol_colegio may be null

$usuario->update($update_pl);