问:
Runtime exception when using SharedPreferences
DISCLAIMER: I have never used SharedPreferences before and the first time I tried isn't going that well.

I wanted to save a value that's going to be constant for the application. I figured SharedPreferences is the way to go, since I want to ask for this value from the user only once and that is when the user opens the application for the first time.

Here is my code

```<code>SharedPreferences runCheck = getApplicationContext().getSharedPreferences("hasRunBefore", 0); //load the preferences
    Boolean hasRun = runCheck.getBoolean("hasRun", false); //see if it's run before, default no
    if (!hasRun) {
//This code runs the first time the app is opened
        SharedPreferences settings = getSharedPreferences("hasRunBefore", 0);
        SharedPreferences.Editor edit = settings.edit();
        edit.putBoolean("hasRun", true); //set to has run

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        builder.setView(inflater.inflate(R.layout.alertdialog,null))
        .setPositiveButton(AlertDialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText editText = (EditText)findViewById(R.id.alert_dialog_editText);
                if(editText.getText().toString() != null) {
                    regNum = editText.getText().toString();
                }
            }
        });
        edit.putString("registerNumber",regNum);
        builder.show();
        TextView textView = (TextView)findViewById(R.id.regNum_textView);
        textView.setText(regNum);
        edit.commit(); //apply
    }
    else
    {
        //code if the app HAS run before
        TextView textView = (TextView)findViewById(R.id.regNum_textView);
        textView.setText(regNum);
    }
</code>```

And the XML file that I am inflating for the AlertDialog

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/alertDialog"
>

<TextView
    android:id="@+id/alert_dialog_textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Your Register Number"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="37dp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/alert_dialog_editText"
    android:layout_below="@+id/alert_dialog_textview"
    android:layout_centerHorizontal="true" />

</RelativeLayout>
</code>```

Can anyone be kind enough to tell me what I am doing wrong?  TIA!

EDIT: Updated with Logcat.

```<code><code>    04-02 23:32:15.574 12826-12826/? I/art: Late-enabling -Xcheck:jni
    04-02 23:32:15.609 12826-12826/teamfour.bluetoothtracker D/TidaProvider: TidaProvider()
04-02 23:32:15.657 12826-12826/teamfour.bluetoothtracker W/System: ClassLoader referenced unknown path: /data/app/teamfour.bluetoothtracker-2/lib/arm64
04-02 23:32:15.688 12826-12843/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
04-02 23:32:15.696 12826-12843/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
04-02 23:32:15.729 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.flags:2 and remote module com.google.android.gms.flags:0
04-02 23:32:15.729 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected local version of com.google.android.gms.flags
04-02 23:32:15.739 12826-12826/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
04-02 23:32:15.742 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.crash:0 and remote module com.google.android.gms.crash:4
04-02 23:32:15.742 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected remote version of com.google.android.gms.crash, version >= 4
04-02 23:32:15.751 12826-12826/teamfour.bluetoothtracker W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/0000000f/n/arm64-v8a
04-02 23:32:15.785 12826-12826/teamfour.bluetoothtracker I/FirebaseCrashApiImpl: FirebaseCrashApiImpl created by ClassLoader p[DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/0000000f/DynamiteModulesC_GmsCore_prodmnc_xxhdpi_release.apk"],nativeLibraryDirectories=[/data/user/0/com.google.android.gms/app_chimera/m/0000000f/n/arm64-v8a, /vendor/lib64, /system/lib64]]]
04-02 23:32:15.806 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.flags:2 and remote module com.google.android.gms.flags:0
04-02 23:32:15.806 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected local version of com.google.android.gms.flags
04-02 23:32:15.823 12826-12826/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
04-02 23:32:15.857 12826-12826/teamfour.bluetoothtracker I/FA: App measurement is starting up, version: 10298
04-02 23:32:15.857 12826-12826/teamfour.bluetoothtracker I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker V/FA: Collection enabled
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker V/FA: App package, google app id: teamfour.bluetoothtracker, 1:269251234897:android:6720288a2e1342a0
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker I/FA: To enable faster debug mode event logging run:     adb shell setprop debug.firebase.analytics.app teamfour.bluetoothtracker
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker D/FA: Debug-level message logging enabled
04-02 23:32:15.868 12826-12826/teamfour.bluetoothtracker V/FA: Registered activity lifecycle callback
04-02 23:32:15.869 12826-12826/teamfour.bluetoothtracker I/FirebaseCrash: FirebaseCrash reporting initialized com.google.android.gms.internal.zzbnq@c77270d
04-02 23:32:15.870 12826-12826/teamfour.bluetoothtracker I/FirebaseInitProvider: FirebaseApp initialization successful
04-02 23:32:15.878 12826-12864/teamfour.bluetoothtracker V/FA: Using measurement service
04-02 23:32:15.878 12826-12864/teamfour.bluetoothtracker V/FA: Connecting to remote service
04-02 23:32:15.920 12826-12826/teamfour.bluetoothtracker W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-02 23:32:15.927 12826-12826/teamfour.bluetoothtracker V/FA: onActivityCreated
04-02 23:32:15.986 12826-12826/teamfour.bluetoothtracker W/ResourceType: No known package when getting value for resource number 0xffffffff
04-02 23:32:15.990 12826-12826/teamfour.bluetoothtracker D/AndroidRuntime: Shutting down VM
04-02 23:32:15.996 12826-12826/teamfour.bluetoothtracker E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{teamfour.bluetoothtracker/teamfour.bluetoothtracker.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                               Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                                                at android.content.res.Resources.getText(Resources.java:328)
                                                                                at android.content.res.MiuiResources.getText(MiuiResources.java:123)
                                                                                at android.content.Context.getText(Context.java:405)
                                                                                at android.support.v7.app.AlertDialog$Builder.setPositiveButton(AlertDialog.java:451)
                                                                                at teamfour.bluetoothtracker.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6303)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
04-02 23:32:16.002 12826-12864/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.tagmanager:9 and remote module com.google.android.gms.tagmanager:9
04-02 23:32:16.002 12826-12864/teamfour.bluetoothtracker I/DynamiteModule: Selected remote version of com.google.android.gms.tagmanager, version >= 9
[ 04-02 23:32:16.003 12883:12883 I/         ]                            ARTPROXY OFFSET: method_entry_offset = 48
[ 04-02 23:32:16.003 12883:12883 I/         ]
 ARTPROXY OFFSET: method_interpreter_entry_offset = 32
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: managed_stack_size = 24
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: thread_deliver_exception_entry_offset = 1088
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: thread_exception_offset = 136
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: method_code_size_offset = 4
04-02 23:32:16.031 12826-12864/teamfour.bluetoothtracker W/GoogleTagManager: No container asset found in /assets/containers. Checking top level /assets directory for container assets.
04-02 23:32:16.045 12826-12864/teamfour.bluetoothtracker W/GoogleTagManager: Tag Manager's event handler WILL NOT be installed (no container loaded)
04-02 23:32:16.045 12826-12864/teamfour.bluetoothtracker I/GoogleTagManager: Tag Manager initilization took 31ms
04-02 23:32:16.060 12826-12864/teamfour.bluetoothtracker V/FA: Using measurement service
04-02 23:32:16.060 12826-12864/teamfour.bluetoothtracker V/FA: Connection attempt already in progress
04-02 23:32:16.239 12826-12826/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: teamfour.bluetoothtracker, PID: 12826
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{teamfour.bluetoothtracker/teamfour.bluetoothtracker.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                       at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                    Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                       at android.content.res.Resources.getText(Resources.java:328)
                                                       at android.content.res.MiuiResources.getText(MiuiResources.java:123)
                                                       at android.content.Context.getText(Context.java:405)
                                                       at android.support.v7.app.AlertDialog$Builder.setPositiveButton(AlertDialog.java:451)
                                                       at teamfour.bluetoothtracker.MainActivity.onCreate(MainActivity.java:67)
                                                       at android.app.Activity.performCreate(Activity.java:6303)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                       at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
04-02 23:32:16.243 12826-12826/? I/Process: Sending signal. PID: 12826 SIG: 9 </code>
</code>```

答:
At least 1 mistake I can see is that you are looking for EditText inside onClick, but you are looking inside activity, not inside dialog's view. As result you will have editText equal null. Also there is no need to have 2 variables for SharedPreferences.

```<code>    SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0);
    boolean hasRun = sharedPreferences.getBoolean("hasRun", false);
    if (!hasRun) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean("hasRun", true);

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final View dialogView = getLayoutInflater().inflate(R.layout.alertdialog, null);
        builder.setView(dialogView)
                .setPositiveButton(AlertDialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Here important change, before you had NPE
                        EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);
                        if (editText.getText().toString() != null) {
                            regNum = editText.getText().toString();
                        }
                    }
                });
        edit.putString("registerNumber", regNum);
        builder.show();
        TextView textView = (TextView) findViewById(R.id.regNum_textView);
        textView.setText(regNum);
        edit.commit(); //apply
    } else {
        //code if the app HAS run before
        TextView textView = (TextView) findViewById(R.id.regNum_textView);
        textView.setText(regNum);
    }
</code>```

UPDATE:

setPositiveButton, method experts id of string resource as first argument in order to show it as the label, but you are passing AlertDialog.BUTTON_POSITIVE which first of all doesn't make any sense, and second it crashes you app.

So you can either pass id on string resource or just String, e.g.:

setPositiveButton("LABEL", ...

Body:
DISCLAIMER: I have never used SharedPreferences before and the first time I tried isn't going that well.

I wanted to save a value that's going to be constant for the application. I figured SharedPreferences is the way to go, since I want to ask for this value from the user only once and that is when the user opens the application for the first time.

Here is my code

SharedPreferences runCheck = getApplicationContext().getSharedPreferences("hasRunBefore", 0); //load the preferences
    Boolean hasRun = runCheck.getBoolean("hasRun", false); //see if it's run before, default no
    if (!hasRun) {
//This code runs the first time the app is opened
        SharedPreferences settings = getSharedPreferences("hasRunBefore", 0);
        SharedPreferences.Editor edit = settings.edit();
        edit.putBoolean("hasRun", true); //set to has run

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        builder.setView(inflater.inflate(R.layout.alertdialog,null))
        .setPositiveButton(AlertDialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText editText = (EditText)findViewById(R.id.alert_dialog_editText);
                if(editText.getText().toString() != null) {
                    regNum = editText.getText().toString();
                }
            }
        });
        edit.putString("registerNumber",regNum);
        builder.show();
        TextView textView = (TextView)findViewById(R.id.regNum_textView);
        textView.setText(regNum);
        edit.commit(); //apply
    }
    else
    {
        //code if the app HAS run before
        TextView textView = (TextView)findViewById(R.id.regNum_textView);
        textView.setText(regNum);
    }

And the XML file that I am inflating for the AlertDialog

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/alertDialog"
>

<TextView
    android:id="@+id/alert_dialog_textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Your Register Number"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="37dp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/alert_dialog_editText"
    android:layout_below="@+id/alert_dialog_textview"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

Can anyone be kind enough to tell me what I am doing wrong?  TIA!

EDIT: Updated with Logcat.

    04-02 23:32:15.574 12826-12826/? I/art: Late-enabling -Xcheck:jni
    04-02 23:32:15.609 12826-12826/teamfour.bluetoothtracker D/TidaProvider: TidaProvider()
04-02 23:32:15.657 12826-12826/teamfour.bluetoothtracker W/System: ClassLoader referenced unknown path: /data/app/teamfour.bluetoothtracker-2/lib/arm64
04-02 23:32:15.688 12826-12843/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
04-02 23:32:15.696 12826-12843/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
04-02 23:32:15.729 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.flags:2 and remote module com.google.android.gms.flags:0
04-02 23:32:15.729 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected local version of com.google.android.gms.flags
04-02 23:32:15.739 12826-12826/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
04-02 23:32:15.742 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.crash:0 and remote module com.google.android.gms.crash:4
04-02 23:32:15.742 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected remote version of com.google.android.gms.crash, version >= 4
04-02 23:32:15.751 12826-12826/teamfour.bluetoothtracker W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/0000000f/n/arm64-v8a
04-02 23:32:15.785 12826-12826/teamfour.bluetoothtracker I/FirebaseCrashApiImpl: FirebaseCrashApiImpl created by ClassLoader p[DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/0000000f/DynamiteModulesC_GmsCore_prodmnc_xxhdpi_release.apk"],nativeLibraryDirectories=[/data/user/0/com.google.android.gms/app_chimera/m/0000000f/n/arm64-v8a, /vendor/lib64, /system/lib64]]]
04-02 23:32:15.806 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.flags:2 and remote module com.google.android.gms.flags:0
04-02 23:32:15.806 12826-12826/teamfour.bluetoothtracker I/DynamiteModule: Selected local version of com.google.android.gms.flags
04-02 23:32:15.823 12826-12826/teamfour.bluetoothtracker W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
04-02 23:32:15.857 12826-12826/teamfour.bluetoothtracker I/FA: App measurement is starting up, version: 10298
04-02 23:32:15.857 12826-12826/teamfour.bluetoothtracker I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker V/FA: Collection enabled
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker V/FA: App package, google app id: teamfour.bluetoothtracker, 1:269251234897:android:6720288a2e1342a0
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker I/FA: To enable faster debug mode event logging run:     adb shell setprop debug.firebase.analytics.app teamfour.bluetoothtracker
04-02 23:32:15.862 12826-12826/teamfour.bluetoothtracker D/FA: Debug-level message logging enabled
04-02 23:32:15.868 12826-12826/teamfour.bluetoothtracker V/FA: Registered activity lifecycle callback
04-02 23:32:15.869 12826-12826/teamfour.bluetoothtracker I/FirebaseCrash: FirebaseCrash reporting initialized com.google.android.gms.internal.zzbnq@c77270d
04-02 23:32:15.870 12826-12826/teamfour.bluetoothtracker I/FirebaseInitProvider: FirebaseApp initialization successful
04-02 23:32:15.878 12826-12864/teamfour.bluetoothtracker V/FA: Using measurement service
04-02 23:32:15.878 12826-12864/teamfour.bluetoothtracker V/FA: Connecting to remote service
04-02 23:32:15.920 12826-12826/teamfour.bluetoothtracker W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-02 23:32:15.927 12826-12826/teamfour.bluetoothtracker V/FA: onActivityCreated
04-02 23:32:15.986 12826-12826/teamfour.bluetoothtracker W/ResourceType: No known package when getting value for resource number 0xffffffff
04-02 23:32:15.990 12826-12826/teamfour.bluetoothtracker D/AndroidRuntime: Shutting down VM
04-02 23:32:15.996 12826-12826/teamfour.bluetoothtracker E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{teamfour.bluetoothtracker/teamfour.bluetoothtracker.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                                               Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                                                at android.content.res.Resources.getText(Resources.java:328)
                                                                                at android.content.res.MiuiResources.getText(MiuiResources.java:123)
                                                                                at android.content.Context.getText(Context.java:405)
                                                                                at android.support.v7.app.AlertDialog$Builder.setPositiveButton(AlertDialog.java:451)
                                                                                at teamfour.bluetoothtracker.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6303)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
04-02 23:32:16.002 12826-12864/teamfour.bluetoothtracker I/DynamiteModule: Considering local module com.google.android.gms.tagmanager:9 and remote module com.google.android.gms.tagmanager:9
04-02 23:32:16.002 12826-12864/teamfour.bluetoothtracker I/DynamiteModule: Selected remote version of com.google.android.gms.tagmanager, version >= 9
[ 04-02 23:32:16.003 12883:12883 I/         ]                            ARTPROXY OFFSET: method_entry_offset = 48
[ 04-02 23:32:16.003 12883:12883 I/         ]
 ARTPROXY OFFSET: method_interpreter_entry_offset = 32
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: managed_stack_size = 24
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: thread_deliver_exception_entry_offset = 1088
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: thread_exception_offset = 136
[ 04-02 23:32:16.003 12883:12883 I/         ]
ARTPROXY OFFSET: method_code_size_offset = 4
04-02 23:32:16.031 12826-12864/teamfour.bluetoothtracker W/GoogleTagManager: No container asset found in /assets/containers. Checking top level /assets directory for container assets.
04-02 23:32:16.045 12826-12864/teamfour.bluetoothtracker W/GoogleTagManager: Tag Manager's event handler WILL NOT be installed (no container loaded)
04-02 23:32:16.045 12826-12864/teamfour.bluetoothtracker I/GoogleTagManager: Tag Manager initilization took 31ms
04-02 23:32:16.060 12826-12864/teamfour.bluetoothtracker V/FA: Using measurement service
04-02 23:32:16.060 12826-12864/teamfour.bluetoothtracker V/FA: Connection attempt already in progress
04-02 23:32:16.239 12826-12826/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: teamfour.bluetoothtracker, PID: 12826
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{teamfour.bluetoothtracker/teamfour.bluetoothtracker.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                       at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
                                                    Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
                                                       at android.content.res.Resources.getText(Resources.java:328)
                                                       at android.content.res.MiuiResources.getText(MiuiResources.java:123)
                                                       at android.content.Context.getText(Context.java:405)
                                                       at android.support.v7.app.AlertDialog$Builder.setPositiveButton(AlertDialog.java:451)
                                                       at teamfour.bluetoothtracker.MainActivity.onCreate(MainActivity.java:67)
                                                       at android.app.Activity.performCreate(Activity.java:6303)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
                                                       at android.app.ActivityThread.access$900(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:148)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5441)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
04-02 23:32:16.243 12826-12826/? I/Process: Sending signal. PID: 12826 SIG: 9

Body:
At least 1 mistake I can see is that you are looking for EditText inside onClick, but you are looking inside activity, not inside dialog's view. As result you will have editText equal null. Also there is no need to have 2 variables for SharedPreferences.

    SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0);
    boolean hasRun = sharedPreferences.getBoolean("hasRun", false);
    if (!hasRun) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean("hasRun", true);

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final View dialogView = getLayoutInflater().inflate(R.layout.alertdialog, null);
        builder.setView(dialogView)
                .setPositiveButton(AlertDialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Here important change, before you had NPE
                        EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);
                        if (editText.getText().toString() != null) {
                            regNum = editText.getText().toString();
                        }
                    }
                });
        edit.putString("registerNumber", regNum);
        builder.show();
        TextView textView = (TextView) findViewById(R.id.regNum_textView);
        textView.setText(regNum);
        edit.commit(); //apply
    } else {
        //code if the app HAS run before
        TextView textView = (TextView) findViewById(R.id.regNum_textView);
        textView.setText(regNum);
    }

UPDATE:

setPositiveButton, method experts id of string resource as first argument in order to show it as the label, but you are passing AlertDialog.BUTTON_POSITIVE which first of all doesn't make any sense, and second it crashes you app.

So you can either pass id on string resource or just String, e.g.:

setPositiveButton("LABEL", ...


来源: stackexchange

问:
What naming convention do you use for the service layer in a Spring MVC application?
I'm stuck with figuring out a good naming convention for the service layer in a spring application. For each class in the service layer I first write the interface it should implement and then the actual class. So for example I have the following interface:

```<code>public interface UserAccountManager{
   public void registerUser(UserAccount newUserAccount);
   public void resetPassword(UserAccount userAccount);
...
}
</code>```

And then the implementation class...

What bugs me here is UserAccountManager is a good name for the implementation class so I'm forced into giving it a stupid name like SimpleUserAccountManager or UserAccountDbManager.
What are some of the conventions you've used so far? Is it a good idea to put the implementation classes in a different package and give them the same names as the interfaces?
Also what are your thoughts on using names ending with Manager over names ending with Service?

答: To me a service class is about implementing a use case, so I name it according to what kind of user the service is acting on behalf of. So if I have an application with different roles, say Customers, Order Fullfillment people, Data entry people, and Admins, then I'd likely have a CustomerService, an OrderFulfillmentService, a DataEntryService, and an AdminService. I think naming a service according to the kind of data being fetched or twiddled is an anti-pattern. So guessing that UserAccount manipulation would be the domain of an Administrator I would probably call it "AdminService".</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm stuck with figuring out a good naming convention for the service layer in a spring application. For each class in the service layer I first write the interface it should implement and then the actual class. So for example I have the following interface:

public interface UserAccountManager{
   public void registerUser(UserAccount newUserAccount);
   public void resetPassword(UserAccount userAccount);
...
}

And then the implementation class...

What bugs me here is UserAccountManager is a good name for the implementation class so I'm forced into giving it a stupid name like SimpleUserAccountManager or UserAccountDbManager.
What are some of the conventions you've used so far? Is it a good idea to put the implementation classes in a different package and give them the same names as the interfaces?
Also what are your thoughts on using names ending with Manager over names ending with Service?


问:
AWS: Custom SSL certificate option is disabled in CloudFront, but I created a SSL certificate using AWS Certificate Manager
I am creating a SSL certificate for my amazon S3 static website. I created a SSL certificate using Certificate Manager for my domain and its status is 'Issued'. I am creating a CloudFront Distribution, but the Custom SSL Certificate option is disabled.

Will it take some time (a day or more) before I can see my custom SSL certificate? Or am I doing something wrong?

答:
Certificates that will be used with an Application Load Balancer (ELB/2.0) need to be created in ACM in the same region as the balancer.

Certificates that will be used with CloudFront always need to be created in us-east-1.

To use an ACM Certificate with Amazon CloudFront, you must request or import the certificate in the US East (N. Virginia) region. ACM Certificates in this region that are associated with a CloudFront distribution are distributed to all the geographic locations configured for that distribution.

– http://docs.aws.amazon.com/acm/latest/userguide/acm-regions.html

The reason for this is that CloudFront doesn't follow the regional boundary model in AWS.  CloudFront edge locations are all over the globe, but are configured and managed out of us-east-1 -- think of it as CloudFront's home region.  Once a distribution reaches the Deployed state, it is not operationally dependent on us-east-1, but during provisioning, everything originates from that region, so that's the only ACM region that CloudFront can access.

ContentLicense: CC BY-SA 3.0


问:
Can't produce a viable .jar with IntelliJ
First of all I'm not able to produce a .jar with IntelliJ without using Artifacts and I don't understand why. I make my project, build it, run it, make module but none of that produce de .jar in out directory... Maybe the reason is that I never wait to then end of the run and always interrupt with alt+F2 because the program is very long to run entirely, it's a bot.

So then I try to produce .jar using Artifact function in IntelliJ but it produces a .jar that I can't run :

-java prgr.jar returns Error: Could not find or load main class prgr.jar
and -java -jar prgr.jar returns no main manifest attribute, in prgr.jar

So I got few questions given that my program runs perfectly when I run the main class from IntelliJ :

What is the difference between commands : -java prgr.jar and -java
-jar prgr.jar

What is the MANIFEST.MF and how to use it ?

How can I do to produce a .jar that I can run from a shell ? How to use the artifact function properly, what files do I have to put and where in order to make it work ?

Edit : I just saw that I need the MANIFEST.MF but how do I tell the .jar where to find the MANIFEST ?

答:
If you include any signed JARs in your app and then use IntelliJ to build artifacts, it will extract the JARS and bundle them with your compiled output.

This then causes a JAVA security exception. I've seen this with Eclipse Paho and Bouncy Castle which are signed.

You can check if any of the library JARs you are using are signed using the jarsigner tool.

```<code>jarsigner -verify -verbose  <path to library JAR>
</code>```

Change your IntelliJ artifact setup so that these get bundled as libraries instead of being extracted. Extraction invalidates the certificate as you'd expect.

Try creating a dummy project with just Main. Add 1 library JAR (that you are trying to build with) at a time. Build an output JAR each time until Main breaks. That's how I found this.

IntelliJ should warn you.....

Body:
If you include any signed JARs in your app and then use IntelliJ to build artifacts, it will extract the JARS and bundle them with your compiled output.

This then causes a JAVA security exception. I've seen this with Eclipse Paho and Bouncy Castle which are signed.

You can check if any of the library JARs you are using are signed using the jarsigner tool.

jarsigner -verify -verbose  <path to library JAR>

Change your IntelliJ artifact setup so that these get bundled as libraries instead of being extracted. Extraction invalidates the certificate as you'd expect.

Try creating a dummy project with just Main. Add 1 library JAR (that you are trying to build with) at a time. Build an output JAR each time until Main breaks. That's how I found this.

IntelliJ should warn you.....


问:
Getting unique column names to allow a creation of a view?
I'm currently trying to create a view from two tables by doing a join, I've methods used here but i'm still getting this error:

Msg 4506, Level 16, State >1, Procedure vw_Employee, Line 3 [Batch Start Line 19]

  Column names in each view or function must be unique. Column name 'empNumber' in view or function 'vw_Employee' is specified more than once.

My view is as follows:

```<code>create view vw_Employee as
(
    select *
    from Employees e1
    inner join EmpInfo e2 on e2.empNumber = e1.empNumber
)
</code>```

答: you must write the name of column in select query and take only e1.empNumber</p>

Body:
I'm currently trying to create a view from two tables by doing a join, I've methods used here but i'm still getting this error:

Msg 4506, Level 16, State >1, Procedure vw_Employee, Line 3 [Batch Start Line 19]

  Column names in each view or function must be unique. Column name 'empNumber' in view or function 'vw_Employee' is specified more than once.

My view is as follows:

create view vw_Employee as
(
    select *
    from Employees e1
    inner join EmpInfo e2 on e2.empNumber = e1.empNumber
)


问:
Python - return value from dict if cell contains substring
I'm working with excel file where one column contains "Description" (=strings i.e. "abc_123") and I need to create categories based on the description. I checked Fuzzywuzzy lib, but it doesn't quite suit my needs since the description can be quite long and category can be described by one word therefore mismatch rate is quite high.

How I did it in excel (case sensitive):

```<code>=IFERROR(INDEX($B$2:$B$50,MATCH(1,--NOT(NOT(FIND($A$2:$A$50,B2))),0)),"N/A")
</code>```

The thing is in python my solutions return only exact matches and I'd like to return even partial matches (case insensitive if possible).

```<code>df = pd.DataFrame({'col1': {0: 'a', 1: "b", 2: "abc"}, 'col2': {0: np.nan, 1: np.nan, 2: np.nan}})
di = {"a": "1", "b":"2"}

    col1    col2
0   a   NaN
1   b   NaN
2   abc NaN

df.loc[df.col1.isin(di), 'col2'] = df['col1'].map(di)

col1    col2
0   a   1
1   b   2
2   abc NaN
</code>```

I'd like col2:2 to be populated with "1", since it's the first match (a).

edit:
dictionary - dict{"Hosp":"Hospital", "emerg":"Hospital", "Fire":"Fire Department"}

I'd like:

"Hospital emergency" to return "Hospital"

"Hospi_emrgncy." to return "Hospital"

"Hopsital emergency" to return "Hospital"

"Fire in Detroit" to return "Fire Department"

答:
```<code>for key, value in category_name.items():
    mask = np.column_stack([df['Description'].str.contains(key, na=False) for col in df])
    df2 = df.loc[mask.any(axis=1)]
    df2["Category"] = df2["Category"].fillna(value)
    df3 = df3.combine_first(df2)
</code>```

Finally found the solution. By no means perfect, but this does the job if I have good enough dictionary.

Body:
I'm working with excel file where one column contains "Description" (=strings i.e. "abc_123") and I need to create categories based on the description. I checked Fuzzywuzzy lib, but it doesn't quite suit my needs since the description can be quite long and category can be described by one word therefore mismatch rate is quite high.

How I did it in excel (case sensitive):

=IFERROR(INDEX($B$2:$B$50,MATCH(1,--NOT(NOT(FIND($A$2:$A$50,B2))),0)),"N/A")

The thing is in python my solutions return only exact matches and I'd like to return even partial matches (case insensitive if possible).

df = pd.DataFrame({'col1': {0: 'a', 1: "b", 2: "abc"}, 'col2': {0: np.nan, 1: np.nan, 2: np.nan}})
di = {"a": "1", "b":"2"}

    col1    col2
0   a   NaN
1   b   NaN
2   abc NaN

df.loc[df.col1.isin(di), 'col2'] = df['col1'].map(di)

col1    col2
0   a   1
1   b   2
2   abc NaN

I'd like col2:2 to be populated with "1", since it's the first match (a).

edit:
dictionary - dict{"Hosp":"Hospital", "emerg":"Hospital", "Fire":"Fire Department"}

I'd like:

"Hospital emergency" to return "Hospital"

"Hospi_emrgncy." to return "Hospital"

"Hopsital emergency" to return "Hospital"

"Fire in Detroit" to return "Fire Department"

Body:
for key, value in category_name.items():
    mask = np.column_stack([df['Description'].str.contains(key, na=False) for col in df])
    df2 = df.loc[mask.any(axis=1)]
    df2["Category"] = df2["Category"].fillna(value)
    df3 = df3.combine_first(df2)

Finally found the solution. By no means perfect, but this does the job if I have good enough dictionary.


问:
This rating option has been disabled by the Android Market team
I'm seeing this message

This rating option has been disabled
  by the Android Market team

next to the "All" rating option for my app.  This is showing up for my apps that need Internet access to serve up adMob ads.  I am not allowed to select the All option.  My app is suitable for little kids, and the ads don't show up on the main game screen.  Does anyone know of a way to get around this?

答:
Are you sure you don't have location enabled?

I have an app that just requires Internet, and I can select "all", but another app with internet + coarse location cannot be rated "all", with the same "error" message.


问:
Integrating Treant-js in Angular2 Project
I'm trying to make use of treant-js in an Angular2 project, and I'm struggling with how to properly integrate it.

I have a working vanilla JavaScript / HTML example that I'm trying to make work in Angular2.

I've created a component, added treant-js and raphael from npm, and imported them into the component.

```<code>import * as Raphael from 'raphael';
import * as Treant from 'treant-js';
</code>```

I've setup the html template and the corresponding css to match the standalone javascript project.

```<code><div class="tree-wrapper" >
    <div class="chart" id="test-tree"></div>
</div>
</code>```

And in the class I'm defining the tree-structure variable

```<code>   private tree_structure: any = {
        chart: {
            container: "#test-tree",
            levelSeparation: 20,
            siblingSeparation: 15,
            subTeeSeparation: 15,
            rootOrientation: "WEST",

            node: {
                HTMLclass: "tree-wrapper",
                drawLineThrough: true
            },
            connectors: {
                type: "straight",
                style: {
                    "stroke-width": 2,
                    "stroke": "#ccc"
                }
            }
        },

        nodeStructure: {
            text: {
                name: { val: "Djokovic, Novak", href: "http://... }
            },
            HTMLclass: "animal",
            image: "flags/can.jpg",
            children: [...
   *** the rest of the object graph continues ***
}
</code>```

In the JavaScript / HTML version, the tree is loaded in an inline script like this:

```<code><script>
   new Treant( tree_structure );
</script>
</code>```

What's the proper way to initialize this in Angular2?

I was thinking something like this:

```<code>private tree: Treant = new Treant();

ngOnInit() {
    tree ( this.tree_structure );
}
</code>```

However Treant isn't a function.

I'm sure I'm missing something obvious here, but I can't wrap my head around this.

答:
The solution is as follows:

Import the scripts into the index.html file - don't add them via npm, just load the js files into wherever you store your static import assets, in this case I have an assets directory at the root of the project that contains static CSS files (BootStrap) and static images, as well as a js subdirectory that contains the Treant and Raphael files.

```<code>  <script src="/assets/js/raphael.js"></script>
  <script src="/assets/js/Treant.js"></script>
</code>```

Then create a component, and turn off ViewEncapsulation so that the Treant CSS styles will work.

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

declare var Treant: any;

@Component({
    encapsulation: ViewEncapsulation.None,
    selector: 'treant-tree',
    styleUrls: ['treant-tree.component.scss'],
    template: `
<div class="treant-class" >
    <div class="chart" id="treant-id"></div>
</div>
  `
})
export class TreantTree {...}
</code>```

I used the Tennis Example, so create the nodeStructure as a variable in your class:

```<code>    private tree_structure: any = {
        chart: {
            container: "#treant-id",
            levelSeparation: 20,
            siblingSeparation: 15,
            subTeeSeparation: 15,
            rootOrientation: "WEST",

            node: {
                HTMLclass: "treant-class",
                drawLineThrough: true
            },
            connectors: {
                type: "straight",
                style: {
                    "stroke-width": 2,
                    "stroke": "#ccc"
                }
            }
        },

        nodeStructure: {
            text: {
                name: { val: "Djokovic, Novak", href: "http://www.atpworldtour.com/Tennis/Players/Top-Players/Novak-Djokovic.aspx" }
            },
            HTMLclass: "animal",
            image: "/assets/images/flags/can.jpg",
            children: []
        }
</code>```

(Watch your parentheses here - I've truncated the code above)

I've copied the flags directory with all the images into /assets/images/flags/ and changed the paths in the nodeStructure to reflect that.

I copied all the relevant CSS styles into the component's treant-tree.component.scss file.

If you log out Treant in your constructor, you should see and be able to expand/view the function object just to confirm that the script is loading properly, but this isn't necessary

```<code>    `console.log`("Treant",Treant);
</code>```

Then in ngOnInit, call Treant and pass in the tree-structure variable in an Immediately Invoked Function Expression. The syntax for this in TypeScript is as follows:

```<code>ngOnInit() {
    (() => {Treant(this.tree_structure)})();
}
</code>```

Obviously in order to make actual use of this, you'll want to abstract out the tree-structure data, probably construct it via a service and load it into the component as a parameter or @Input binding, but at least this gets everything working.

Body:
I'm trying to make use of treant-js in an Angular2 project, and I'm struggling with how to properly integrate it.

I have a working vanilla JavaScript / HTML example that I'm trying to make work in Angular2.

I've created a component, added treant-js and raphael from npm, and imported them into the component.

import * as Raphael from 'raphael';
import * as Treant from 'treant-js';

I've setup the html template and the corresponding css to match the standalone javascript project.

And in the class I'm defining the tree-structure variable

   private tree_structure: any = {
        chart: {
            container: "#test-tree",
            levelSeparation: 20,
            siblingSeparation: 15,
            subTeeSeparation: 15,
            rootOrientation: "WEST",

            node: {
                HTMLclass: "tree-wrapper",
                drawLineThrough: true
            },
            connectors: {
                type: "straight",
                style: {
                    "stroke-width": 2,
                    "stroke": "#ccc"
                }
            }
        },

        nodeStructure: {
            text: {
                name: { val: "Djokovic, Novak", href: "http://... }
            },
            HTMLclass: "animal",
            image: "flags/can.jpg",
            children: [...
   *** the rest of the object graph continues ***
}

In the JavaScript / HTML version, the tree is loaded in an inline script like this:

What's the proper way to initialize this in Angular2?

I was thinking something like this:

private tree: Treant = new Treant();

ngOnInit() {
    tree ( this.tree_structure );
}

However Treant isn't a function.

I'm sure I'm missing something obvious here, but I can't wrap my head around this.

Body:
The solution is as follows:

Import the scripts into the index.html file - don't add them via npm, just load the js files into wherever you store your static import assets, in this case I have an assets directory at the root of the project that contains static CSS files (BootStrap) and static images, as well as a js subdirectory that contains the Treant and Raphael files.

  <script src="/assets/js/raphael.js"></script>
  <script src="/assets/js/Treant.js"></script>

Then create a component, and turn off ViewEncapsulation so that the Treant CSS styles will work.

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

declare var Treant: any;

@Component({
    encapsulation: ViewEncapsulation.None,
    selector: 'treant-tree',
    styleUrls: ['treant-tree.component.scss'],
    template: `
<div class="treant-class" >
    <div class="chart" id="treant-id"></div>
</div>
  `
})
export class TreantTree {...}

I used the Tennis Example, so create the nodeStructure as a variable in your class:

    private tree_structure: any = {
        chart: {
            container: "#treant-id",
            levelSeparation: 20,
            siblingSeparation: 15,
            subTeeSeparation: 15,
            rootOrientation: "WEST",

            node: {
                HTMLclass: "treant-class",
                drawLineThrough: true
            },
            connectors: {
                type: "straight",
                style: {
                    "stroke-width": 2,
                    "stroke": "#ccc"
                }
            }
        },

        nodeStructure: {
            text: {
                name: { val: "Djokovic, Novak", href: "http://www.atpworldtour.com/Tennis/Players/Top-Players/Novak-Djokovic.aspx" }
            },
            HTMLclass: "animal",
            image: "/assets/images/flags/can.jpg",
            children: []
        }

(Watch your parentheses here - I've truncated the code above)

I've copied the flags directory with all the images into /assets/images/flags/ and changed the paths in the nodeStructure to reflect that.

I copied all the relevant CSS styles into the component's treant-tree.component.scss file.

If you log out Treant in your constructor, you should see and be able to expand/view the function object just to confirm that the script is loading properly, but this isn't necessary

    `console.log`("Treant",Treant);

Then in ngOnInit, call Treant and pass in the tree-structure variable in an Immediately Invoked Function Expression. The syntax for this in TypeScript is as follows:

ngOnInit() {
    (() => {Treant(this.tree_structure)})();
}

Obviously in order to make actual use of this, you'll want to abstract out the tree-structure data, probably construct it via a service and load it into the component as a parameter or @Input binding, but at least this gets everything working.


问:
recurring scheduler in RxJava
I wanna remove old stuff from the ListView, so I defined recurring scheduler as a handler in the Activity.

```<code>private Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
        doSomethingOnRecyclerView();
        handler.postDelayed(runnableCode, 2000);
    }
};
handler.post(runnableCode);
</code>```

It works, however, I'm refactoring the app to use RxJava, mvp and dagger. How to do recurring scheduler in RxJava?
Where to keep it in MVP architecture, in presenter?

答:
I'd have the handler live in the presenter class and call the appropriate view methods at each interval. With RX you can have an emitter (or flowable?) that fires every x seconds. This will accomplish the same thing that you have in your code.

Be sure to wire up the scheduler to the presenter's lifecycle

Title: recurring scheduler in RxJava

Body:
I wanna remove old stuff from the ListView, so I defined recurring scheduler as a handler in the Activity.

private Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
        doSomethingOnRecyclerView();
        handler.postDelayed(runnableCode, 2000);
    }
};
handler.post(runnableCode);

It works, however, I'm refactoring the app to use RxJava, mvp and dagger. How to do recurring scheduler in RxJava?
Where to keep it in MVP architecture, in presenter?


问:
Matrix multiplication speed issues
I am investigating how cache misses influence speed of computation. I know there are many algorithms better for multiplying two matrices (even simple exchange of two of the loops below would help), but please consider this code:

```<code>float a[N][N];
float b[N][N];
float c[N][N];
// ...
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            float sum = 0.0;
            for (int k = 0; k < N; k++) {
                sum = sum + a[i][k] * b[k][j];
            }
            c[i][j] = sum;
        }
    }
}
</code>```

I have recompiled this code for many values of N and measured time to run it. I expected to find a sudden increase of time at around N=1250, at which point matrix c no longer fits in cache (size of c is then 1250*1250*sizeof(float)=6250000, or roughly 6MB, which is the size of my L3 cache).

Indeed, the general trend is that after that point, the average time roughly triples compared to extrapolated time from before. But the value of N%8 seems to have a huge influence on the result. For example:

```<code>1601 - 11.237548
1602 - 7.679103
1603 - 12.216982
1604 - 6.283644
1605 - 11.360517
1606 - 7.486021
1607 - 11.292025
1608 - 5.794537
1609 - 11.469469
1610 - 7.581660
1611 - 11.367203
1612 - 6.126014
1613 - 11.730543
1614 - 7.632121
1615 - 11.773091
1616 - 5.778463
1617 - 11.556687
1618 - 7.682941
1619 - 11.576068
1620 - 6.273122
1621 - 11.635411
1622 - 7.804220
1623 - 12.053517
1624 - 6.008985
</code>```

For some time, I thought those might be alignment issues - rows of any matrix are aligned to 32 bytes when N%8==0 (first question - why 32 bytes in particular? SSE instructions, such as movaps can work on 16B aligned data).

Another idea was that this could be somehow connected to cache associativity (8-way for L1 and L2 and 12-way for L3 on my machine).

But then I noticed that for some values of N, such as 1536, there are unexpected spikes (even though the alignment should be excellent in those cases - 1536==256*6, the associativity being non-issue too - 1536==128*12==192*8). For example:

```<code>1504 - 4.644781
1512 - 4.794254
1520 - 4.768555
1528 - 4.884714
1536 - 7.949040
1544 - 5.162613
1552 - 5.083331
1560 - 5.388706
</code>```

The timing is pretty consistent, so spikes of processor load are not a problem. I compile the code with optimizations turned on (-O2). My ideas are unfortunately running out. What could be a reason of such behaviour?

答:
The most important for your example - CPU cache line size. For CPU it is typically 64 byte. Even if your program read or write 1 byte, CPU does read/write for all line (64 byte). That is why, if your program hit the cache lines, your performance is good. If it miss, there is an extra overhead for reading/writing memory. Size of L3 cache is not so critical.

for your code

```<code>// all your stack variables are good. Compiler will optimize them well.
for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
        float sum = 0.0;
        for (int k = 0; k < N; k++) {
            sum = sum +
                  a[i][k] *  // here you are good, you read memory sequentially
                  b[k][j]; // here, you are not good, every read comes from different cache line
        }
        c[i][j] = sum; // here doesn't matter, it is rare operation
    }
}
</code>```

Similar to your case is here. This presentation explain great how to optimize such code and why it works this way. I hope you will find everything you need.

Title: Matrix multiplication speed issues

Body:
I am investigating how cache misses influence speed of computation. I know there are many algorithms better for multiplying two matrices (even simple exchange of two of the loops below would help), but please consider this code:

float a[N][N];
float b[N][N];
float c[N][N];
// ...
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            float sum = 0.0;
            for (int k = 0; k < N; k++) {
                sum = sum + a[i][k] * b[k][j];
            }
            c[i][j] = sum;
        }
    }
}

I have recompiled this code for many values of N and measured time to run it. I expected to find a sudden increase of time at around N=1250, at which point matrix c no longer fits in cache (size of c is then 1250*1250*sizeof(float)=6250000, or roughly 6MB, which is the size of my L3 cache).

Indeed, the general trend is that after that point, the average time roughly triples compared to extrapolated time from before. But the value of N%8 seems to have a huge influence on the result. For example:

1601 - 11.237548
1602 - 7.679103
1603 - 12.216982
1604 - 6.283644
1605 - 11.360517
1606 - 7.486021
1607 - 11.292025
1608 - 5.794537
1609 - 11.469469
1610 - 7.581660
1611 - 11.367203
1612 - 6.126014
1613 - 11.730543
1614 - 7.632121
1615 - 11.773091
1616 - 5.778463
1617 - 11.556687
1618 - 7.682941
1619 - 11.576068
1620 - 6.273122
1621 - 11.635411
1622 - 7.804220
1623 - 12.053517
1624 - 6.008985

For some time, I thought those might be alignment issues - rows of any matrix are aligned to 32 bytes when N%8==0 (first question - why 32 bytes in particular? SSE instructions, such as movaps can work on 16B aligned data).

Another idea was that this could be somehow connected to cache associativity (8-way for L1 and L2 and 12-way for L3 on my machine).

But then I noticed that for some values of N, such as 1536, there are unexpected spikes (even though the alignment should be excellent in those cases - 1536==256*6, the associativity being non-issue too - 1536==128*12==192*8). For example:

1504 - 4.644781
1512 - 4.794254
1520 - 4.768555
1528 - 4.884714
1536 - 7.949040
1544 - 5.162613
1552 - 5.083331
1560 - 5.388706

The timing is pretty consistent, so spikes of processor load are not a problem. I compile the code with optimizations turned on (-O2). My ideas are unfortunately running out. What could be a reason of such behaviour?

Body:
The most important for your example - CPU cache line size. For CPU it is typically 64 byte. Even if your program read or write 1 byte, CPU does read/write for all line (64 byte). That is why, if your program hit the cache lines, your performance is good. If it miss, there is an extra overhead for reading/writing memory. Size of L3 cache is not so critical.

for your code

// all your stack variables are good. Compiler will optimize them well.
for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
        float sum = 0.0;
        for (int k = 0; k < N; k++) {
            sum = sum +
                  a[i][k] *  // here you are good, you read memory sequentially
                  b[k][j]; // here, you are not good, every read comes from different cache line
        }
        c[i][j] = sum; // here doesn't matter, it is rare operation
    }
}

Similar to your case is here. This presentation explain great how to optimize such code and why it works this way. I hope you will find everything you need.


问:
Minimization Procedure Decreases Quickly & then Increases
I running the "interior-point" algorithm of MATLAB's FMINCON. The algorithm uses BFGS and thus takes into account information in the numerical Hessian.

I am optimizing over a parameter space that is known to be non-convex with respect to a unique solution. I penalize those parameter-combinations that are not unique with an arctan function.

I'm finding the optimization procedure starts high (around 10), in a few iteration decreases 'til 4 (near the minimum), and then increases slowly back towards 10 over a few hundred iteration.

I have options set to rescale the problem and constraints.

I'm kind of stuck at this point. What do you think?

答: My particular problem I found was caused by fmincon's scale option which I had to set scale-Obj-Cons. I believe this was messing up the numerical gradient and hessian calculation as the determinant region is non-convex.


问:
android App closes with no error when imageview is clicked
I am creating a simple imageview with an id and trying to start an activity when it is clicked but when i click it in the emulator, the app just crashes and gives me (wait or close the app prompt)
here is my:

XML:

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

<ImageView
    android:id="@+id/about"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:background="@color/colorPrimaryDark"
    android:src="@drawable/twoth" />

</LinearLayout>
</code>```

and here is my java code

```<code>public class MainUi extends AppCompatActivity {

    //Variables Declaration.
    private Button btn1, btn2, btn3, btn4;
    private ImageView img;

    //Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_ui);
        //Variables Initialization and OnClick Method

        img = (ImageView) findViewById(R.id.about);
        img.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Start another activity
                Intent myIntent = new Intent(MainUi.this, Query.class);
                startActivity(myIntent);
            }
        });

    }

}
</code>```

答:
The 'wait or close' thing leads me to think there's something in Query activity that is doing a lot of work on the main thread.

Try to use an AsyncTask and put all your long running processes in the doInBackground part and later handle the response in the onPostExecute.

I guess it depends a lot of what you are actually doing, but AsyncTask should be a good start.

Body:
I am creating a simple imageview with an id and trying to start an activity when it is clicked but when i click it in the emulator, the app just crashes and gives me (wait or close the app prompt)
here is my:

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">

<ImageView
    android:id="@+id/about"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:background="@color/colorPrimaryDark"
    android:src="@drawable/twoth" />

</LinearLayout>

and here is my java code

public class MainUi extends AppCompatActivity {

    //Variables Declaration.
    private Button btn1, btn2, btn3, btn4;
    private ImageView img;

    //Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_ui);
        //Variables Initialization and OnClick Method

        img = (ImageView) findViewById(R.id.about);
        img.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Start another activity
                Intent myIntent = new Intent(MainUi.this, Query.class);
                startActivity(myIntent);
            }
        });

    }

}


问:
WPF Update view in loop
I'm using MVVM and when the model calculates a new background for a position it tells the viewmodel that it's changed. So what I want to do is update the view at every new background, but I think Thread.Sleep blocks the main UI thread.

```<code>private void New_Background(object sender, BackgroundEventArgs e)
    {
        Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            Fields[e.Position].Background = e.Background; //update this position's background at every step
            OnPropertyChanged("Background");
            Thread.Sleep(50);
        }));
    }
</code>```

Is there a way I can achieve this?
By the way, if I use MessageBox.Show(...) instead of Thread.Sleep, it updates the view at every messagebox.

答:
...but I think Thread.Sleep blocks the main UI thread.

Yes, it does. The delegate that you pass to the Application.Current.Dispatcher.InvokeAsync method is being executed on the UI thread.

how can I delay it so it gets slowed down a bit?

Slow down the loop:

```<code>private async void New_Background(object sender, BackgroundEventArgs e)
{
    await Task.Delay(1000);
    Application.Current.Dispatcher.Invoke(new Action(async () =>
    {
        Fields[e.Position].Background = e.Background; //update this position's background at every step
        OnPropertyChanged("Background");
    }));
}
</code>```

Title: WPF Update view in loop

Body:
I'm using MVVM and when the model calculates a new background for a position it tells the viewmodel that it's changed. So what I want to do is update the view at every new background, but I think Thread.Sleep blocks the main UI thread.

private void New_Background(object sender, BackgroundEventArgs e)
    {
        Application.Current.Dispatcher.InvokeAsync(new Action(() =>
        {
            Fields[e.Position].Background = e.Background; //update this position's background at every step
            OnPropertyChanged("Background");
            Thread.Sleep(50);
        }));
    }

Is there a way I can achieve this?
By the way, if I use MessageBox.Show(...) instead of Thread.Sleep, it updates the view at every messagebox.

Body:
...but I think Thread.Sleep blocks the main UI thread.

Yes, it does. The delegate that you pass to the Application.Current.Dispatcher.InvokeAsync method is being executed on the UI thread.

how can I delay it so it gets slowed down a bit?

Slow down the loop:

private async void New_Background(object sender, BackgroundEventArgs e)
{
    await Task.Delay(1000);
    Application.Current.Dispatcher.Invoke(new Action(async () =>
    {
        Fields[e.Position].Background = e.Background; //update this position's background at every step
        OnPropertyChanged("Background");
    }));
}


问:
Records by unique id and on a per minute boundary
In a mysql database table below, I have records as shown below. I have data for many ID's. In the given example, I want to be able to get the first record in the list which has the least distance value. Additionally, I have an entire timeline of such data for many hours. So the goal is that for each MINUTE in the timeline, I want to be able to pick records for each unique ID in that minute with the lowest distance value. I know it's going to take a couple of good group by queries with join's but I've been unable to come up with something. Please help!!</p>

```<code>| NAME    | ID    | TIME                    | TOTAL_TIME | DISTANCE
| chicago | 74    | 2017-02-26 23:17:39 GMT | 54         | 5
| new york| 74    | 2017-02-26 23:17:51 GMT | 42         | 3
| chicago | 74    | 2017-02-26 23:17:41 GMT | 56         | 11
| chicago | 74    | 2017-02-26 23:17:52 GMT | 67         | 12
| new york| 74    | 2017-02-26 23:17:53 GMT | 44         | 8
| new york| 74    | 2017-02-26 23:17:56 GMT | 47         | 8
</code>```

答:
Assuming the autoincrementing PK column is called id_pk in your table, you can find id_pk for each id and minute using a correlated subquery with limit.

```<code>select t.*
from your_table t
where id_pk = (
        select id_pk
        from your_table s
        where t.id = s.id
            and unix_timestamp(s.time) div 300
                = unix_timestamp(t.time) div 300
        order by distance limit 1
        )
</code>```

Demo

unix_timestamp(s.time) div 300 is to truncate the datetime to within 5 minutes (5 x 60 = 300 seconds).

Body:
In a mysql database table below, I have records as shown below. I have data for many ID's. In the given example, I want to be able to get the first record in the list which has the least distance value. Additionally, I have an entire timeline of such data for many hours. So the goal is that for each MINUTE in the timeline, I want to be able to pick records for each unique ID in that minute with the lowest distance value. I know it's going to take a couple of good group by queries with join's but I've been unable to come up with something. Please help!!

| NAME    | ID    | TIME                    | TOTAL_TIME | DISTANCE
| chicago | 74    | 2017-02-26 23:17:39 GMT | 54         | 5
| new york| 74    | 2017-02-26 23:17:51 GMT | 42         | 3
| chicago | 74    | 2017-02-26 23:17:41 GMT | 56         | 11
| chicago | 74    | 2017-02-26 23:17:52 GMT | 67         | 12
| new york| 74    | 2017-02-26 23:17:53 GMT | 44         | 8
| new york| 74    | 2017-02-26 23:17:56 GMT | 47         | 8

Body:
Assuming the autoincrementing PK column is called id_pk in your table, you can find id_pk for each id and minute using a correlated subquery with limit.

select t.*
from your_table t
where id_pk = (
        select id_pk
        from your_table s
        where t.id = s.id
            and unix_timestamp(s.time) div 300
                = unix_timestamp(t.time) div 300
        order by distance limit 1
        )

Demo

unix_timestamp(s.time) div 300 is to truncate the datetime to within 5 minutes (5 x 60 = 300 seconds).


问:
How to unpack a list?
When extracting data from a list this way

```<code>line[0:3], line[3][:2], line[3][2:]
</code>```

I receive an array and two variables after it, as should be expected:

```<code>(['a', 'b', 'c'], 'd', 'e')
</code>```

I need to manipulate the list so the end result is

```<code>('a', 'b', 'c', 'd', 'e')
</code>```

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

答:
```<code>from itertools import chain
print tuple(chain(['a', 'b', 'c'], 'd', 'e'))
</code>```

Output:

```<code>('a', 'b', 'c', 'd','e')
</code>```

Title: How to unpack a list?

Body:
When extracting data from a list this way

line[0:3], line[3][:2], line[3][2:]

I receive an array and two variables after it, as should be expected:

(['a', 'b', 'c'], 'd', 'e')

I need to manipulate the list so the end result is

('a', 'b', 'c', 'd', 'e')

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

Body:
from itertools import chain
print tuple(chain(['a', 'b', 'c'], 'd', 'e'))

Output:

('a', 'b', 'c', 'd','e')


问:
Why my getName() method is not starting from the first row in my csv file?
```<code>public int getRank(int auxYear, String auxName){
       //FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
         String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
         File auxFile = new File(resourceName);
         if(auxFile.exists()){
         FileResource auxFr = new FileResource(auxFile);
       //FileResource auxFr = new FileResource();
         int auxRank = 0;
         for (CSVRecord auxRec : auxFr.getCSVParser(false)){
             if (auxRec.get(1).contains(auxGender)){
                auxRank += 1;
                String auxN = auxRec.get(0);
                if (auxRec.get(0).contains(auxName)){
                   return auxRank;
                }
             }
         }
}
</code>```

the getName method is reading another csv file and not staring from the first row, below the code :

```<code> public String getName(int auxYear, int auxRank, String auxGender){
    ////FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
        String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
        File auxFile = new File(resourceName);
        if (auxFile.exists()){
        FileResource auxFr = new FileResource(auxFile);
        int auxCount = 0;
        for (CSVRecord auxRec : auxFr.getCSVParser()){
            String auxStr = auxRec.get(0);
            if (auxRec.get(1).contains(auxGender)){
                auxCount += 1;
                String auxStr1 = auxRec.get(0);
                if (auxCount == (auxRank-1)){
                    return auxRec.get(0);
                }
            }
        }
    }
</code>```

I use also :

```<code>public String yourNameInYear(String auxName, int auxYear, int auxNewYear, String auxGender){
    int auxRank = getRank(auxYear, auxName, auxGender);
    return getName(auxNewYear, auxRank, auxGender);
}

public void testYourNameInYear(){
    String auxName = yourNameInYear("Isabella", 2012, 2014, "F");
    System.out.println("Isabella" + " born in " + 2012 + " would be " + auxName + " in " + 2014);
}
</code>```

by default YourNameInYear will call getRank this one will open the yob2012short.csv then after processing, getName will be called and open yob2014short.csv. I don't know why this one is not starting from the first row ?

答:
try to use this

```<code>       if (auxRec.get(1).contains(auxGender)){
            String auxStr1 = auxRec.get(0);
            if (auxCount == (auxRank-1)){
                return auxRec.get(0);
            }
       auxCount += 1;
        }
</code>```

as I gess auxCaunt must be your current row so if you increment it from 0 to 1 then you do call the getName with an auxRank equals to 0 (first row may be 0 not 1) so 0 is not equal to 1 so it will loop until auxRank equals 2

Body:
public int getRank(int auxYear, String auxName){
       //FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
         String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
         File auxFile = new File(resourceName);
         if(auxFile.exists()){
         FileResource auxFr = new FileResource(auxFile);
       //FileResource auxFr = new FileResource();
         int auxRank = 0;
         for (CSVRecord auxRec : auxFr.getCSVParser(false)){
             if (auxRec.get(1).contains(auxGender)){
                auxRank += 1;
                String auxN = auxRec.get(0);
                if (auxRec.get(0).contains(auxName)){
                   return auxRank;
                }
             }
         }
}

the getName method is reading another csv file and not staring from the first row, below the code :

 public String getName(int auxYear, int auxRank, String auxGender){
    ////FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
        String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
        File auxFile = new File(resourceName);
        if (auxFile.exists()){
        FileResource auxFr = new FileResource(auxFile);
        int auxCount = 0;
        for (CSVRecord auxRec : auxFr.getCSVParser()){
            String auxStr = auxRec.get(0);
            if (auxRec.get(1).contains(auxGender)){
                auxCount += 1;
                String auxStr1 = auxRec.get(0);
                if (auxCount == (auxRank-1)){
                    return auxRec.get(0);
                }
            }
        }
    }

I use also :

public String yourNameInYear(String auxName, int auxYear, int auxNewYear, String auxGender){
    int auxRank = getRank(auxYear, auxName, auxGender);
    return getName(auxNewYear, auxRank, auxGender);
}

public void testYourNameInYear(){
    String auxName = yourNameInYear("Isabella", 2012, 2014, "F");
    System.out.println("Isabella" + " born in " + 2012 + " would be " + auxName + " in " + 2014);
}

by default YourNameInYear will call getRank this one will open the yob2012short.csv then after processing, getName will be called and open yob2014short.csv. I don't know why this one is not starting from the first row ?

Body:
try to use this

       if (auxRec.get(1).contains(auxGender)){
            String auxStr1 = auxRec.get(0);
            if (auxCount == (auxRank-1)){
                return auxRec.get(0);
            }
       auxCount += 1;
        }

as I gess auxCaunt must be your current row so if you increment it from 0 to 1 then you do call the getName with an auxRank equals to 0 (first row may be 0 not 1) so 0 is not equal to 1 so it will loop until auxRank equals 2


问:
Table doesnt automatically populate items when selected
I have two tables; ItemType and Item. Item has a property named ItemTypeId which holds a value from ItemType Id. Very basic.

ItemType

```<code>public class ItemType
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>();

    public enum ListTypes
    {
        Student = 1,
        Work = 2,
        Gamer = 3,
        Other = 4
    }
}
</code>```

Item

```<code>public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Graphic { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public int ItemTypeId { get; set; }
    public virtual ItemType ItemType { get; set; }
}
</code>```

DbContext

```<code>public class TechDbContext : DbContext
{
    public TechDbContext(DbContextOptions<TechDbContext> options) : base(options)
    {

    }

    public DbSet<ItemType> ItemTypes { get; set; }
    public DbSet<Item> Items { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ItemType>().ToTable("ItemType");
        modelBuilder.Entity<Item>().ToTable("Item");
    }
}
</code>```

and finally the view component that selects the ItemType object

```<code>public class ItemListViewComponent : ViewComponent
{
    private Data.TechDbContext _context;

    public ItemListViewComponent(Data.TechDbContext context)
    {
        _context = context;
    }

    public async Task<IViewComponentResult> InvokeAsync(Models.ItemType.ListTypes type)
    {
        var single = await (from t in _context.ItemTypes where t.Id == (int)type select t).FirstAsync<Models.ItemType>();

        return View(single);
    }
}
</code>```

Maybe I've misunderstood, but I thought when I used the correct naming convention the Items property would automatically be populated without any extra code?

Many thanks in advance!

答:
Lazy Loading doesn't exist. https://github.com/aspnet/EntityFramework/issues/3797</p>

```<code> _context.ItemTypes.Include(p => p.Items);
</code>```

Body:
I have two tables; ItemType and Item. Item has a property named ItemTypeId which holds a value from ItemType Id. Very basic.

ItemType

public class ItemType
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>();

    public enum ListTypes
    {
        Student = 1,
        Work = 2,
        Gamer = 3,
        Other = 4
    }
}

Item

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Graphic { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public int ItemTypeId { get; set; }
    public virtual ItemType ItemType { get; set; }
}

DbContext

public class TechDbContext : DbContext
{
    public TechDbContext(DbContextOptions<TechDbContext> options) : base(options)
    {

    }

    public DbSet<ItemType> ItemTypes { get; set; }
    public DbSet<Item> Items { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ItemType>().ToTable("ItemType");
        modelBuilder.Entity<Item>().ToTable("Item");
    }
}

and finally the view component that selects the ItemType object

public class ItemListViewComponent : ViewComponent
{
    private Data.TechDbContext _context;

    public ItemListViewComponent(Data.TechDbContext context)
    {
        _context = context;
    }

    public async Task<IViewComponentResult> InvokeAsync(Models.ItemType.ListTypes type)
    {
        var single = await (from t in _context.ItemTypes where t.Id == (int)type select t).FirstAsync<Models.ItemType>();

        return View(single);
    }
}

Maybe I've misunderstood, but I thought when I used the correct naming convention the Items property would automatically be populated without any extra code?

Many thanks in advance!

Body:
Lazy Loading doesn't exist. https://github.com/aspnet/EntityFramework/issues/3797

 _context.ItemTypes.Include(p => p.Items);


问:
What's the pythonic way to pass arguments between functions?
I have some arguments taken from the user and passed along function to function (each function in a different class), until it eventually gets to a function that does some processing and then the solution is returned up the chain. Up the chain, the functions become more and more abstract merging results from multiple runs of the lower functions.

Where should I use *args and **kwargs?

I think *args and *kwargs can be used for every function where the function doesn't use the arguments explicitly. But, the actual arguments need to be defined at the top_level so that the user knows what the function expects.

Where should I define what the inputs mean?

I think they should be defined at the top_level because that's the one the end-user might want to see the documentation for.

Where should I define what default values?

Again, I think they should be defined at the top_level because that's the one the end-user interacts with.

This is a simple example to demonstrate the passing of the arguments, where I haven't shown how the functions become more and more abstract or how they interact with different classes, as I felt it was unnecessary detail.

```<code>def top_level(a=1, b=1, c=1, d=1, e=1):
    """ Compute sum of five numbers.
    :param a: int, a
    :param b: int, b
    :param c: int, c
    :param d: int, d
    :param e: int, e
    :return: int, sum
    """
    return mid_level(a, b, c, d, e)

def mid_level(*args, **kwargs):
    return bottom_level(*args, **kwargs)

def bottom_level(a, b, c, d, e):
    return a + b + c + d + e

print top_level(1, 2, 3)
8
</code>```

Is there a Python convention for passing arguments like this?

答:
This isn't the most common pattern, but I've seen it for command line programs that have levels of nested commands: sub-commands, sub-sub-commands and so on. That's a model where "upper" level functions may be more or less dispatchers and not have information about what parameters are needed by the sub-functions within a given route. The purest scenario for this model is when the sub-commands are plugins and the "upper" layers have literally no information about the sub-functions, other than a calling convention the plug-ins are expected to adhere to.

In these cases, I'd argue the pythonic way is to pass parameters from higher-level to lower-level functions, and let the worker level decide which are useful. The range of possible parameters would be defined in the calling convention. This is pythonic on the basis of DRY -- don't repeat yourself. If the low-level / worker function defines what inputs are required or optional, it would often make sense to not repeat this information at the higher levels.

The same could be said for any inversion-of-control flow design, not just CLI applications w/ plug-ins. There are many application designs where I wouldn't use this approach, but it works here.

An input's meaning must be set at the topmost level it can arise in -- as an interface spec to lower levels (a convention, not programmatic). Otherwise the inputs would have no semantic meaning.

If an input can be used by multiple sub-functions, i.e. there's a chaining or pipeline concept in the control flow, then an input's default will also need to be defined at the topmost level for the input.

Body:
I have some arguments taken from the user and passed along function to function (each function in a different class), until it eventually gets to a function that does some processing and then the solution is returned up the chain. Up the chain, the functions become more and more abstract merging results from multiple runs of the lower functions.

Where should I use *args and **kwargs?

I think *args and *kwargs can be used for every function where the function doesn't use the arguments explicitly. But, the actual arguments need to be defined at the top_level so that the user knows what the function expects.

Where should I define what the inputs mean?

I think they should be defined at the top_level because that's the one the end-user might want to see the documentation for.

Where should I define what default values?

Again, I think they should be defined at the top_level because that's the one the end-user interacts with.

This is a simple example to demonstrate the passing of the arguments, where I haven't shown how the functions become more and more abstract or how they interact with different classes, as I felt it was unnecessary detail.

def top_level(a=1, b=1, c=1, d=1, e=1):
    """ Compute sum of five numbers.
    :param a: int, a
    :param b: int, b
    :param c: int, c
    :param d: int, d
    :param e: int, e
    :return: int, sum
    """
    return mid_level(a, b, c, d, e)

def mid_level(*args, **kwargs):
    return bottom_level(*args, **kwargs)

def bottom_level(a, b, c, d, e):
    return a + b + c + d + e

print top_level(1, 2, 3)
8

Is there a Python convention for passing arguments like this?


问:
How do I add a horizontal line in a html select control?
How do I add a horizontal line (
 tag) in the dropdown control or in select control in HTML?

答:
Generally speaking this is not a feature of <select>, most browsers have very poor styling control for that control.  In Firefox you can do the following (though doesn't work in other browsers):

```<code><select name="test">
    <option val="a">A</option>
    <option val="b" class="select-hr">B</option>
    <option val="c">C</option>
    <option val="d">D</option>
</select>
</code>```

with CSS:

```<code>option.select-hr { border-bottom: 1px dotted #000; }
</code>```

But generally speaking, the only method is to put an option in with dashes, and try to make it unselectable.

```<code><select name="test">
    <option val="a">A</option>
    <option val="b">B</option>
    <option disabled="disabled">----</option>
    <option val="c">C</option>
    <option val="d">D</option>
</select>
</code>```

See: http://jsfiddle.net/qM5BA/283/

Body:
Generally speaking this is not a feature of <select>, most browsers have very poor styling control for that control.  In Firefox you can do the following (though doesn't work in other browsers):

<select name="test">
    <option val="a">A</option>
    <option val="b" class="select-hr">B</option>
    <option val="c">C</option>
    <option val="d">D</option>
</select>

with CSS:

option.select-hr { border-bottom: 1px dotted #000; }

But generally speaking, the only method is to put an option in with dashes, and try to make it unselectable.

<select name="test">
    <option val="a">A</option>
    <option val="b">B</option>
    <option disabled="disabled">----</option>
    <option val="c">C</option>
    <option val="d">D</option>
</select>

See: http://jsfiddle.net/qM5BA/283/