问:
Java Android - finding file extension
So I'm trying to get the extension from a file so that I can compare it to a string to see if the extension matches the extension I want to find. However, at the moment I think I am able to get the extension but then comparing it with the one I want to find is causing my app to crash and close immediately. Also, I want it to be able to cope with files that don't have extensions and just pass them off as files that don't match the wanted file extension. Below is the code snippet that performs this, hopefully someone can explain to me what I'm doing wrong here.

```<code>File directory =  getFilesDir();
File[] listOfFiles = directory.listFiles();
String[] fileArray;
ListView fileList = (ListView) findViewById(R.id.fileList);
fileArray = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; ++i){
    String extension = MimeTypeMap.getFileExtensionFromUrl(listOfFiles[i].getAbsolutePath());
    if (extension.equals("txt")) {
        fileArray[i] = listOfFiles[i].getName();
    }
</code>```

P.S: I'm new to Java and Android Development so please be nice to me. :)

EDIT:

Okay, I'm being asked to post my errors, I don't really know how to post them in a nice way but this is the best I can do.

03-29 15:39:32.437 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.479 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.522 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.571 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.618 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.671 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.724 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.766 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.809 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.884 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.887 7671-7671/? W/System: ClassLoader referenced unknown path: /data/app/com.removedforprivacy.appname-1/lib/arm64
03-29 15:39:32.894 7671-7671/? I/InstantRun: Starting Instant Run Server for com.removedforprivacy.appname
03-29 15:39:33.061 7671-7671/? I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl
03-29 15:39:33.276 7671-7671/? I/HwSecImmHelper: mSecurityInputMethodService is null
03-29 15:39:33.349 7671-7727/? I/OpenGLRenderer: Initialized EGL, version 1.4
03-29 15:39:33.396 7671-7671/? W/art: Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-29 15:39:34.694 7671-7677/? I/art: Ignoring second debugger -- accepting and dropping

The above is the log from when the app is started. This is before the problem area is loaded. The below is when I press the button that triggers the running of the problem area.

03-29 15:42:50.550 10762-10762/? I/art: Late-enabling -Xcheck:jni
03-29 15:42:50.654 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.808 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.851 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.895 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.953 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.008 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.072 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.151 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.197 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.241 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.315 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.318 10762-10762/com.removedforprivacy.appname W/System: ClassLoader referenced unknown path: /data/app/com.removedforprivacy.appname-1/lib/arm64
03-29 15:42:51.326 10762-10762/com.removedforprivacy.appname I/InstantRun: Starting Instant Run Server for com.removedforprivacy.appname

One last thing, when I press the button, there is another bit of logs shown which I think is different to the above but it very quickly disappears so I can't copy it in. Hope that helps.

答:
Find my solution, MimeTypeMap will not give some proper result. So, do your own method to find the file type from the URL. Check my solution.

```<code>  public static String getFileType(String fileName) {
    String fileExt = "";
    try {
        if (fileName != null) {
            fileExt = fileName.substring(fileName.lastIndexOf("."));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileExt;
}
</code>```

Hopes it will help. Happy Coding

UPDATE

See, I think your list file path is string which is URI. so you need to convert into URI . then get the path from that URI. Do the following.

```<code>   String filePath=String.valueOf(filePath);
   Uri.parse(filePath).getPath();//Here you can get the path of the file which contains the extension of the file.
</code>```

Title: Java Android - finding file extension

Body:
So I'm trying to get the extension from a file so that I can compare it to a string to see if the extension matches the extension I want to find. However, at the moment I think I am able to get the extension but then comparing it with the one I want to find is causing my app to crash and close immediately. Also, I want it to be able to cope with files that don't have extensions and just pass them off as files that don't match the wanted file extension. Below is the code snippet that performs this, hopefully someone can explain to me what I'm doing wrong here.

File directory =  getFilesDir();
File[] listOfFiles = directory.listFiles();
String[] fileArray;
ListView fileList = (ListView) findViewById(R.id.fileList);
fileArray = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; ++i){
    String extension = MimeTypeMap.getFileExtensionFromUrl(listOfFiles[i].getAbsolutePath());
    if (extension.equals("txt")) {
        fileArray[i] = listOfFiles[i].getName();
    }

P.S: I'm new to Java and Android Development so please be nice to me. :)

EDIT:

Okay, I'm being asked to post my errors, I don't really know how to post them in a nice way but this is the best I can do.

03-29 15:39:32.437 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.479 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.522 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.571 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.618 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.671 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.724 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.766 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.809 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.884 7671-7671/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
03-29 15:39:32.887 7671-7671/? W/System: ClassLoader referenced unknown path: /data/app/com.removedforprivacy.appname-1/lib/arm64
03-29 15:39:32.894 7671-7671/? I/InstantRun: Starting Instant Run Server for com.removedforprivacy.appname
03-29 15:39:33.061 7671-7671/? I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl
03-29 15:39:33.276 7671-7671/? I/HwSecImmHelper: mSecurityInputMethodService is null
03-29 15:39:33.349 7671-7727/? I/OpenGLRenderer: Initialized EGL, version 1.4
03-29 15:39:33.396 7671-7671/? W/art: Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-29 15:39:34.694 7671-7677/? I/art: Ignoring second debugger -- accepting and dropping

The above is the log from when the app is started. This is before the problem area is loaded. The below is when I press the button that triggers the running of the problem area.

03-29 15:42:50.550 10762-10762/? I/art: Late-enabling -Xcheck:jni
03-29 15:42:50.654 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.808 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.851 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.895 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:50.953 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.008 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.072 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.151 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.197 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.241 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.315 10762-10762/com.removedforprivacy.appname W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.removedforprivacy.appname-1/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.removedforprivacy.appname-1@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
03-29 15:42:51.318 10762-10762/com.removedforprivacy.appname W/System: ClassLoader referenced unknown path: /data/app/com.removedforprivacy.appname-1/lib/arm64
03-29 15:42:51.326 10762-10762/com.removedforprivacy.appname I/InstantRun: Starting Instant Run Server for com.removedforprivacy.appname

One last thing, when I press the button, there is another bit of logs shown which I think is different to the above but it very quickly disappears so I can't copy it in. Hope that helps.

Body:
Find my solution, MimeTypeMap will not give some proper result. So, do your own method to find the file type from the URL. Check my solution.

  public static String getFileType(String fileName) {
    String fileExt = "";
    try {
        if (fileName != null) {
            fileExt = fileName.substring(fileName.lastIndexOf("."));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileExt;
}

Hopes it will help. Happy Coding

UPDATE

See, I think your list file path is string which is URI. so you need to convert into URI . then get the path from that URI. Do the following.

   String filePath=String.valueOf(filePath);
   Uri.parse(filePath).getPath();//Here you can get the path of the file which contains the extension of the file.


来源: stackexchange

问:
C# - Prevent animation of a showing form
Is there any way of stopping the default opening animation of a form from Windows? I mean stopping it just for one form, not all of them. I need the showing of a form to be instantly, without that growing effect.

I tried to document about WinApi, but I couldn't find anything. Thank you!

答:
You have to take a couple of steps to achieve this:

In the constructor, set your BorderStyle to None. This will prevent the animation:

```<code>public Form1()
{
   InitializeComponent();
   this.FormBorderStyle = FormBorderStyle.None;
}
</code>```

Of course, now you want to show the border again, so you have to set it back as soon as your form is shown, so the user never sees this. Therefore create a method:

```<code>private void Form_Loaded(object sender, EventArgs e)
{
   this.FormBorderStyle = FormBorderStyle.Sizable;
}
</code>```

Now you have to set the Shown event of your form to your Form_Loaded method. You can do this from the form designer event properties window.

If you want to do it for the entire application you can change it using the SystemParametersInfo Method.

ContentLicense: CC BY-SA 3.0

Body:
You have to take a couple of steps to achieve this:

In the constructor, set your BorderStyle to None. This will prevent the animation:

public Form1()
{
   InitializeComponent();
   this.FormBorderStyle = FormBorderStyle.None;
}

Of course, now you want to show the border again, so you have to set it back as soon as your form is shown, so the user never sees this. Therefore create a method:

private void Form_Loaded(object sender, EventArgs e)
{
   this.FormBorderStyle = FormBorderStyle.Sizable;
}

Now you have to set the Shown event of your form to your Form_Loaded method. You can do this from the form designer event properties window.

If you want to do it for the entire application you can change it using the SystemParametersInfo Method.


问:
Interpolated string in database
Following interpolated string formation works well:

```<code>string BG="7263-2323";
string PG="2983-2323";

string interpolatedString = $"{BG};{PG}";
Console.WriteLine(interpolatedString);
</code>```

Result in variable interpolatedString:

```<code>7263-2323;2983-2323
</code>```

But, the problem is that I store interpolatedString in database, then it does not display values for BG and PG... Instead it displays string as it is:

```<code>$\"{BG};{PG}\"
</code>```

How can I solve this issue? Any idea?

答:
You can't do that. Interpolated strings are effectively just syntactic sugar for using string.Format. Instead you would need to store your strings like this:

```<code>Hello {0}, welcome to my app
</code>```

And then use string.Format:

```<code>var format = "Hello {0}, welcome to my app";
var output = string.format(format, "Bob");
</code>```

Alternatively you could roll your own, for example:

```<code>var format = "Hello {name}, welcome to my app";
var output = format.Replace("{name}", "Bob");
</code>```

Note that my example here isn't particularly efficient so you may want to use something like StringBuilder if you're doing a lot of this.

Title: Interpolated string in database

Body:
Following interpolated string formation works well:

string BG="7263-2323";
string PG="2983-2323";

string interpolatedString = $"{BG};{PG}";
Console.WriteLine(interpolatedString);

Result in variable interpolatedString:

7263-2323;2983-2323

But, the problem is that I store interpolatedString in database, then it does not display values for BG and PG... Instead it displays string as it is:

$\"{BG};{PG}\"

How can I solve this issue? Any idea?

Body:
You can't do that. Interpolated strings are effectively just syntactic sugar for using string.Format. Instead you would need to store your strings like this:

Hello {0}, welcome to my app

And then use string.Format:

var format = "Hello {0}, welcome to my app";
var output = string.format(format, "Bob");

Alternatively you could roll your own, for example:

var format = "Hello {name}, welcome to my app";
var output = format.Replace("{name}", "Bob");

Note that my example here isn't particularly efficient so you may want to use something like StringBuilder if you're doing a lot of this.


问:
How to optimize algorithm to be able to determine 10 digit long prime numbers in java
I am currently new to java and programming in general, I'm working on an algorithm that determines the prime numbers in specific given ranges. Currently it works with six ranges which are numbers under 1 billion, when I tried to determine a 10 digit long number it failed. I am aware it needs to be changed to long since the digit is out of range but I am not sure how.

this is the part of the code where it determines if the umber is prime:

```<code>public ArrayList<Integer> getPrimes(int StartPos, int n) {
    ArrayList<Integer> primeList = new ArrayList<>();

    boolean[] primes = new boolean[n + 1];
    for (int i = StartPos; i < primes.length; i++) {
        primes[i] = true;
    }
    int num = 2;
    while (true) {
         for (int i = 2;; i++) {
              int m = num * i;
              if (m > n) {
                    break;
              } else {
                    primes[m] = false;
              }
         }
         boolean nextNum = false;
         for (int i = num + 1; i < n + 1; i++) {
              if (primes[i]) {
                    num = i;
                    nextNum = true;
                    break;
              }
         }
         if (!nextNum) {
              break;
         }
    }
    for (int i = 0; i < primes.length; i++) {
         if (primes[i]) {
            primeList.add(i);
         }
    }
    return primeList;
}
</code>```

I was checking online and found that perhaps I could do it with vectors but I have no experience with them and Also they are relatively slower than an Array.

答:
You say you are learning, so I will give you an outline in pseudocode, not the answer.

In general the method to find a prime in a range is:

```<code>repeat
  pick a number in the range
until (the number is prime)
</code>```

You want a ten digit number. One way to generate a candidate while avoiding obvious non-primes is:

```<code>start with digit in [1..9]  // No leading zero.
repeat 8 times
  append a digit in [0..9]
endrepeat
append a digit in [1, 3, 7, 9]  // Final digits for large primes.
</code>```

That will give you a ten digit possible prime.

Now you need to test to check it is prime.

There are tests like Miller-Rabin that you could try, but probably not if you are a real beginner.  I would suggest setting up a Sieve of Eratosthenes covering numbers to to 10,000 which is the square root of your upper limit of 10,000,000,000.  That will give you fast access to all the primes below the square root of your number.  Set up the sieve once only at the start of your program.  Make it a separate Class, and include a int nextPrime(int n) method which returns the next prime after the supplied parameter.  Once that is in place, then you can write a trial division method to test your ten digit number:

```<code>boolean method isPrime(tenDigitNumber)
  testPrime <- 2
  limit <- square root of tenDigitNumber  // Only calculate this once.
  while (testPrime < limit)
    if (tenDigitNumber MOD testPrime == 0)
      return false  // Number is not prime.
    else
      testPrime <- sieve.nextPrime(testPrime)
    endif
  endwhile
  return true  // If we get here then the number is prime.
end isPrime
</code>```

Because you have set up the sieve in advance, this should run reasonably quickly.  If it is too slow, then it is time to look at coding Miller-Rabin or one of the other heavy-duty prime test methods.

As well as the Sieve of Eratosthenes class, another useful utility method is an iSqrt() method that returns an integer square root.  My own version uses the Newton-Raphson method, though no doubt there are other possibilities.

Body:
I am currently new to java and programming in general, I'm working on an algorithm that determines the prime numbers in specific given ranges. Currently it works with six ranges which are numbers under 1 billion, when I tried to determine a 10 digit long number it failed. I am aware it needs to be changed to long since the digit is out of range but I am not sure how.

this is the part of the code where it determines if the umber is prime:

public ArrayList<Integer> getPrimes(int StartPos, int n) {
    ArrayList<Integer> primeList = new ArrayList<>();

    boolean[] primes = new boolean[n + 1];
    for (int i = StartPos; i < primes.length; i++) {
        primes[i] = true;
    }
    int num = 2;
    while (true) {
         for (int i = 2;; i++) {
              int m = num * i;
              if (m > n) {
                    break;
              } else {
                    primes[m] = false;
              }
         }
         boolean nextNum = false;
         for (int i = num + 1; i < n + 1; i++) {
              if (primes[i]) {
                    num = i;
                    nextNum = true;
                    break;
              }
         }
         if (!nextNum) {
              break;
         }
    }
    for (int i = 0; i < primes.length; i++) {
         if (primes[i]) {
            primeList.add(i);
         }
    }
    return primeList;
}

I was checking online and found that perhaps I could do it with vectors but I have no experience with them and Also they are relatively slower than an Array.

Body:
You say you are learning, so I will give you an outline in pseudocode, not the answer.

In general the method to find a prime in a range is:

repeat
  pick a number in the range
until (the number is prime)

You want a ten digit number. One way to generate a candidate while avoiding obvious non-primes is:

start with digit in [1..9]  // No leading zero.
repeat 8 times
  append a digit in [0..9]
endrepeat
append a digit in [1, 3, 7, 9]  // Final digits for large primes.

That will give you a ten digit possible prime.

Now you need to test to check it is prime.

There are tests like Miller-Rabin that you could try, but probably not if you are a real beginner.  I would suggest setting up a Sieve of Eratosthenes covering numbers to to 10,000 which is the square root of your upper limit of 10,000,000,000.  That will give you fast access to all the primes below the square root of your number.  Set up the sieve once only at the start of your program.  Make it a separate Class, and include a int nextPrime(int n) method which returns the next prime after the supplied parameter.  Once that is in place, then you can write a trial division method to test your ten digit number:

boolean method isPrime(tenDigitNumber)
  testPrime <- 2
  limit <- square root of tenDigitNumber  // Only calculate this once.
  while (testPrime < limit)
    if (tenDigitNumber MOD testPrime == 0)
      return false  // Number is not prime.
    else
      testPrime <- sieve.nextPrime(testPrime)
    endif
  endwhile
  return true  // If we get here then the number is prime.
end isPrime

Because you have set up the sieve in advance, this should run reasonably quickly.  If it is too slow, then it is time to look at coding Miller-Rabin or one of the other heavy-duty prime test methods.

As well as the Sieve of Eratosthenes class, another useful utility method is an iSqrt() method that returns an integer square root.  My own version uses the Newton-Raphson method, though no doubt there are other possibilities.


问:
Windows Phone 7 Image Button
I need to create an Image Button for my application like web-oriented style.
I have an image 20x20 pixel and want an image button with the same dimension of the image.

I tried to set this inside my xaml but it doesn't work:

```<code><Button Grid.Row="0" Margin="0" Padding="0" Click="AddtoFavorite_Click" Width="20" Height="20"  VerticalAlignment="Top" HorizontalAlignment="Right">
   <Button.Content>
      <Image Source="/MyNamespace;component/images/star_yellow.png" Margin="0" Width="20" Height="20" />
   </Button.Content>
</Button>
</code>```

What is wrong?

SOLUTION

I found the best solution is:

```<code><Image Source="/MyNamespace;component/images/star_yellow.png" ManipulationStarted="Image_ManipulationStarted" Width="20" Height="20"></Image>
</code>```

Thanks to all!

答:
You don't even need to use a Button.

You can hook the MouseLeftButtonUp event on the Image control.

```<code> <Image
            Source='blue02.png'
            Width='26'
            Height='26'
            Margin='5'
            MouseLeftButtonUp='Image_MouseLeftButtonUp' />
</code>```

ContentLicense: CC BY-SA 2.5

Title: Windows Phone 7 Image Button

Body:
I need to create an Image Button for my application like web-oriented style.
I have an image 20x20 pixel and want an image button with the same dimension of the image.

I tried to set this inside my xaml but it doesn't work:

<Button Grid.Row="0" Margin="0" Padding="0" Click="AddtoFavorite_Click" Width="20" Height="20"  VerticalAlignment="Top" HorizontalAlignment="Right">
   <Button.Content>
      <Image Source="/MyNamespace;component/images/star_yellow.png" Margin="0" Width="20" Height="20" />
   </Button.Content>
</Button>

What is wrong?

SOLUTION

I found the best solution is:

<Image Source="/MyNamespace;component/images/star_yellow.png" ManipulationStarted="Image_ManipulationStarted" Width="20" Height="20"></Image>

Thanks to all!

Body:
You don't even need to use a Button.

You can hook the MouseLeftButtonUp event on the Image control.

 <Image
            Source='blue02.png'
            Width='26'
            Height='26'
            Margin='5'
            MouseLeftButtonUp='Image_MouseLeftButtonUp' />


问:
Change of property with numbered name in Java
I have a huge field of graphic elements in my GUI, and I need to change their property according to value I have.

I want to avoid writing out switch, although it will work, it seems stupid.
I have graphic properties in HBox named r0 - r200, and I want to change opacity of element corresponding with returned value from other functions.

Is there some clever way, better than:

```<code>switch(note.offGraphic()){

    case 0:
        flat6.setOpacity(1);
        break;
    case 1:
        flat5.setOpacity(1);
        break;
    case 2:
        flat4.setOpacity(1);
        break;
    case 3:
        flat3.setOpacity(1);
        break;
    case 4:
        flat2.setOpacity(1);
        break;
    case 5:
        flat1.setOpacity(1);
    case 6:
        ok.setOpacity(1);
        break;
` and on and on
</code>```

答:
You could create a Map instead, assign all the variables to a specific Integer (Key) and simply get the correct variable depending on the int entered and set that variable's opacity.

Assuming you always do the same thing in each case but on different variables of course

Body:
I have a huge field of graphic elements in my GUI, and I need to change their property according to value I have.

I want to avoid writing out switch, although it will work, it seems stupid.
I have graphic properties in HBox named r0 - r200, and I want to change opacity of element corresponding with returned value from other functions.

Is there some clever way, better than:

switch(note.offGraphic()){

    case 0:
        flat6.setOpacity(1);
        break;
    case 1:
        flat5.setOpacity(1);
        break;
    case 2:
        flat4.setOpacity(1);
        break;
    case 3:
        flat3.setOpacity(1);
        break;
    case 4:
        flat2.setOpacity(1);
        break;
    case 5:
        flat1.setOpacity(1);
    case 6:
        ok.setOpacity(1);
        break;
` and on and on


问:
I want to print alternate words in a string array
```<code>class Test3
{
    public static void main(String [] args)
    {
        String str[] = new String[] {"bharani"};
        for(int i = 0; i < 7; i += 2)
        {
            System.out.println(str[i]);
        }
}
</code>```

What is the error? I am getting error as invalid main.

答:
hi @ Munikotibharani Gopal. Your for loop condition is wrong. You have hardcoded i < 7. It won't work because your string array length is 1.
So, test the following code to design a for loop that depends on the length of your array.

```<code>public class Test3 {
    public static void main(String[] args)
    {
        String str[] = new String[] {"bharani","name1","name2","name3","name4","name5"};
        for(int i = 0; i<str.length; i++)
        {
          System.out.println(str[i]);
        }
    }
}
</code>```

Body:
class Test3
{
    public static void main(String [] args)
    {
        String str[] = new String[] {"bharani"};
        for(int i = 0; i < 7; i += 2)
        {
            System.out.println(str[i]);
        }
}

What is the error? I am getting error as invalid main.

Body:
hi @ Munikotibharani Gopal. Your for loop condition is wrong. You have hardcoded i < 7. It won't work because your string array length is 1.
So, test the following code to design a for loop that depends on the length of your array.

public class Test3 {
    public static void main(String[] args)
    {
        String str[] = new String[] {"bharani","name1","name2","name3","name4","name5"};
        for(int i = 0; i<str.length; i++)
        {
          System.out.println(str[i]);
        }
    }
}


问:
horizontal bar chart with color bar directly from a dataframe pandas object
I have the below code and I am wondering if I can produce a horizontal bar chart plot where the bars change colour horizontally (overtime in my case) according to a given colour map directly from a data frame object.

```<code>from matplotlib import pyplot as plt
from matplotlib import cm
import pandas as pd
import numpy as np

# generate dataframe
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=ndays), columns=list('ABCD'))
df = df.cumsum()

# plot dataframe
df.plot(figsize=(10,5))

# TODO
# make a plot with four horizontal bars each for one column (A, B, C, D)
# the bars represent the time variation and thus should change colour according to the values in the ABCD columns mapped to cmap colour map
</code>```

I also include below a temporary solution using scatter plot for the purpose of visualisation what I aim for.

```<code># this is what I would like plot to look like
# I use plt.scatter to show
fig = plt.figure(figsize=(15,2))
ax = fig.add_subplot(111)
cmap = cm.gnuplot
ax.scatter(x=df.index, y=[0]*df.A.shape[0], c=df.A, cmap=cmap)
ax.scatter(x=df.index, y=[1]*df.A.shape[0], c=df.B, cmap=cmap)
ax.scatter(x=df.index, y=[2]*df.A.shape[0], c=df.C, cmap=cmap)
cax = ax.scatter(x=df.index, y=[3]*df.A.shape[0], c=df.D, cmap=cmap)

# vertical color bar
clim = cax.get_clim()
cbar = fig.colorbar(cax, ticks=[min(clim),np.mean(clim),max(clim)], orientation='vertical')
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])
</code>```

Note: The question is not about scatter plot but if and how to make the result obtain with my current solution directly from the data frame object.

答:
You can kind of do this through pandas, but it is really ugly.  You need to make new columns just for scatter plotting, and then pass the color argument a list of colors based on the actual data.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors

df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000),
                  columns=list('ABCD')).cumsum()

# create color normalizer
cnormer = colors.Normalize(df.min().min(), df.max().max())

# add new columns for the scatter plot
df['i'] = np.arange(1000)
for x in range(4):
    df['z{}'.format(x)] = x

# create an axis to plot on
fig, ax = plt.subplots(1,1,figsize=(10,3))

# make scatter plots
for x in range(4):
    df.plot(x='i', y='z{}'.format(x), kind='scatter', marker='o', edgecolor='none',
            c=plt.cm.viridis(cnormer(df.iloc[:,x])), ax=ax)
</code>```

You would still need to reformat the labels and ticks.

Body:
I have the below code and I am wondering if I can produce a horizontal bar chart plot where the bars change colour horizontally (overtime in my case) according to a given colour map directly from a data frame object.

from matplotlib import pyplot as plt
from matplotlib import cm
import pandas as pd
import numpy as np

# generate dataframe
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=ndays), columns=list('ABCD'))
df = df.cumsum()

# plot dataframe
df.plot(figsize=(10,5))

# TODO
# make a plot with four horizontal bars each for one column (A, B, C, D)
# the bars represent the time variation and thus should change colour according to the values in the ABCD columns mapped to cmap colour map

I also include below a temporary solution using scatter plot for the purpose of visualisation what I aim for.

# this is what I would like plot to look like
# I use plt.scatter to show
fig = plt.figure(figsize=(15,2))
ax = fig.add_subplot(111)
cmap = cm.gnuplot
ax.scatter(x=df.index, y=[0]*df.A.shape[0], c=df.A, cmap=cmap)
ax.scatter(x=df.index, y=[1]*df.A.shape[0], c=df.B, cmap=cmap)
ax.scatter(x=df.index, y=[2]*df.A.shape[0], c=df.C, cmap=cmap)
cax = ax.scatter(x=df.index, y=[3]*df.A.shape[0], c=df.D, cmap=cmap)

# vertical color bar
clim = cax.get_clim()
cbar = fig.colorbar(cax, ticks=[min(clim),np.mean(clim),max(clim)], orientation='vertical')
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])

Note: The question is not about scatter plot but if and how to make the result obtain with my current solution directly from the data frame object.

Body:
You can kind of do this through pandas, but it is really ugly.  You need to make new columns just for scatter plotting, and then pass the color argument a list of colors based on the actual data.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors

df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000),
                  columns=list('ABCD')).cumsum()

# create color normalizer
cnormer = colors.Normalize(df.min().min(), df.max().max())

# add new columns for the scatter plot
df['i'] = np.arange(1000)
for x in range(4):
    df['z{}'.format(x)] = x

# create an axis to plot on
fig, ax = plt.subplots(1,1,figsize=(10,3))

# make scatter plots
for x in range(4):
    df.plot(x='i', y='z{}'.format(x), kind='scatter', marker='o', edgecolor='none',
            c=plt.cm.viridis(cnormer(df.iloc[:,x])), ax=ax)

You would still need to reformat the labels and ticks.


问:
runas command in windows 7
I'm trying to run a batch file as admin. I found that I can use runas command which corresponds sudo command in Linux I think.

I tried

runas /noprofile /user:computername\adminuser "blah.bat start"

But it gives an error, saying :

Logon failure: user account restriction.. (msdos window doesn't allow me to copy anything) is there any way I can run this batch file as admin? Right click doesn't work because I can't include any parameters.

答: Right-click the icon for the command-prompt and choose Run As Administrator.  Then run you batch file from that window.</p>

Title: runas command in windows 7


问:
How can i convert an input number say 032817103305 into a format 03/28/17 10 33 05 using perl?
I am trying to convert a 12 digit number e.g. 032817103305 into a format 03/28/17 10 33 05 using Perl?</p>

答:
A regex substitution is better for just reformatting the numbers, but unpack can also come in handy if you want to other things with the individual fields (eg, insert into a database etc):</p>

```<code>my $record = '032817103305';
my ($month, $day, $year, $hr, $min, $sec) = unpack 'A2' x 6, $record;
</code>```

Body:
A regex substitution is better for just reformatting the numbers, but unpack can also come in handy if you want to other things with the individual fields (eg, insert into a database etc):

my $record = '032817103305';
my ($month, $day, $year, $hr, $min, $sec) = unpack 'A2' x 6, $record;


问:
Adding a new Extension to my generated certificate
I need to add a new Extension of OID 1.3.6.1.5.5.7.1.26 in my certificate. I got this OID extension in my certificate but with the following error:

Certificate Extensions: 10
  [1]: ObjectId: 1.3.6.1.5.5.7.1.26 Criticality=false

  Extension unknown: DER encoded OCTET string =

  0000: 04 0C 30 0A 13 08 33 39   20 64 63 20 32 62        ..0...

  39 dc 2b

I want this OID to be recognized similar to other extensions like AuthorityInfoAccess, etc.

Do I need to edit the jar of Bouncy Castle X509 class?

Im using ACME4j as a client and Letsencrypt Boulder as my server.

Here is the CSR Builder code for signing up the certificate.

```<code>public void sign(KeyPair keypair) throws IOException {
    //Security.addProvider(new BouncyCastleProvider());
    Objects.requireNonNull(keypair, "keypair");
    if (namelist.isEmpty()) {
        throw new IllegalStateException("No domain was set");
    }

    try {
        GeneralName[] gns = new GeneralName[namelist.size()];
        for (int ix = 0; ix < namelist.size(); ix++) {
            gns[ix] = new GeneralName(GeneralName.dNSName,namelist.get(ix));
        }
        SignatureAlgorithmIdentifierFinder algFinder = new
                DefaultSignatureAlgorithmIdentifierFinder();
        GeneralNames subjectAltName = new GeneralNames(gns);

        PKCS10CertificationRequestBuilder p10Builder = new     JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());

        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName,     false, subjectAltName);
        //extensionsGenerator.addExtension(Extension.authorityInfoAccess,         true, subjectAltName);
        //extensionsGenerator.addExtension(new ASN1ObjectIdentifier("TBD"),     false, subjectAltName);
        //extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.24"), false, subjectAltName);
        extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26").intern(), false, subjectAltName);
        //extentionsGenerator.addExtension();
            p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,     extensionsGenerator.generate());

        PrivateKey pk = keypair.getPrivate();
        /*JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
                        pk instanceof ECKey ? EC_SIGNATURE_ALG :     EC_SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);*/

        if(pk instanceof ECKey)
        {
            AlgorithmIdentifier sigAlg = algFinder.find("SHA1withECDSA");
              AlgorithmIdentifier digAlg = new     DefaultDigestAlgorithmIdentifierFinder().
                    find(sigAlg);
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).setProvider(BOUNCY_CASTL    E_PROVIDER).build(keypair.getPrivate());

            csr=p10Builder.build(signer);
            System.out.println("ZIPED CSR ECDSA: "+csr);
        }
        else
        {
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).build(keypair.getPrivate    ());
            csr = p10Builder.build(signer);
            System.out.println("ZIPED CSR RSA: "+csr);
        }

        //csr = p10Builder.build(signer);
    } catch (Exception ex) {
        ex.printStackTrace();;
    }
}
</code>```

答:
Note: for these codes I used bcprov-jdk15on 1.56

Some comments about your code. First of all, note the ASN1 structure:

TNAuthorizationList ::= SEQUENCE SIZE (1..MAX) OF TNEntry

TNEntry ::= CHOICE {
  spc   [0] ServiceProviderCodeList,
  range [1] TelephoneNumberRange,
  one       E164Number
}
```

<p>Note that <code>TNEntry</code> is a <strong>choice</strong>, and <code>TNAuthorizationList</code> is a <strong>sequence</strong> of <code>TNEntry</code> objects. So your class name should be changed to <code>TNEntry</code>. In the code below, please remember that I've changed the class name to <code>TNEntry</code>. </p>

<p>I've also changed some things in this class. In <code>getInstance(Object obj)</code> method, the types of <strong>spc</strong> and <strong>range</strong> fields are incorrect (according to ASN1 definition, they are both <strong>sequences</strong>):</p>

<pre class="lang-java prettyprint-override"><code>switch (tag) {
    case spc:
    case range: // both are sequences
        return new TNEntry(tag, ASN1Sequence.getInstance(tagObj, false));
    // not sure about "one" field, as it's not tagged
}
</code>```

I just don't know how to handle the one field, as it's not tagged. Maybe it should be a DERIA5String, or maybe there's another type for "untagged" choices.

In this same class (remember, I've changed its name to TNEntry), I also removed the constructor public TNEntry(int tag, String name) because I'm not sure if it applies (at least I didn't need to use it, but you can keep it if you want), and I've changed toString method to return a more readable string:

public String toString() {
    String sep = System.getProperty("line.separator");
    StringBuffer buf = new StringBuffer();

    buf.append(this.getClass().getSimpleName());
    buf.append(" [").append(tag);
    buf.append("]: ");
    switch (tag) {
        case spc:
            buf.append("ServiceProviderCodeList: ").append(sep);
            ASN1Sequence seq = (ASN1Sequence) this.obj;
            int size = seq.size();
            for (int i = 0; i < size; i++) {
                // all elements are DERIA5Strings
                DERIA5String str = (DERIA5String) seq.getObjectAt(i);
                buf.append("    ");
                buf.append(str.getString());
                buf.append(sep);
            }
            break;

        case range:
            buf.append("TelephoneNumberRange: ").append(sep);

            // there are always 2 elements in TelephoneNumberRange
            ASN1Sequence s = (ASN1Sequence) this.obj;
            DERIA5String str = (DERIA5String) s.getObjectAt(0);
            buf.append("    start: ");
            buf.append(str.getString());
            buf.append(sep);
            ASN1Integer count = (ASN1Integer) s.getObjectAt(1);
            buf.append("    count: ");
            buf.append(count.toString());
            buf.append(sep);
            break;

        default:
            buf.append(obj.toString());
    }

    return buf.toString();
}
```

<p>And I also created a <code>TNAuthorizationList</code> class, which holds the <strong>sequence</strong> of <code>TNEntry</code> objects (remember that I've changed your class name to <code>TNEntry</code>, so this <code>TNAuthorizationList</code> class is a different one). Note that I also created a constant to hold the <strong>OID</strong> (just to make things a little bit easier):</p>

<pre class="lang-java prettyprint-override"><code>public class TNAuthorizationList extends ASN1Object {
    // put OID in a constant, so I don't have to remember it all the time
    public static final ASN1ObjectIdentifier TN_AUTH_LIST_OID = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26");

    private TNEntry[] entries;

    public TNAuthorizationList(TNEntry[] entries) {
        this.entries = entries;
    }

    public static TNAuthorizationList getInstance(Object obj) {
        if (obj instanceof TNAuthorizationList) {
            return (TNAuthorizationList) obj;
        }
        if (obj != null) {
            return new TNAuthorizationList(ASN1Sequence.getInstance(obj));
        }

        return null;
    }

    public static TNAuthorizationList getInstance(ASN1TaggedObject obj, boolean explicit) {
        return getInstance(ASN1Sequence.getInstance(obj, explicit));
    }

    private TNAuthorizationList(ASN1Sequence seq) {
        this.entries = new TNEntry[seq.size()];

        for (int i = 0; i != seq.size(); i++) {
            entries[i] = TNEntry.getInstance(seq.getObjectAt(i));
        }
    }

    public TNEntry[] getEntries() {
        TNEntry[] tmp = new TNEntry[entries.length];
        System.arraycopy(entries, 0, tmp, 0, entries.length);
        return tmp;
    }

    @Override
    public ASN1Primitive toASN1Primitive() {
        return new DERSequence(entries);
    }

    public String toString() {
        String sep = System.getProperty("line.separator");
        StringBuffer buf = new StringBuffer();

        buf.append(this.getClass().getSimpleName());
        buf.append(":").append(sep);
        for (TNEntry tnEntry : entries) {
            buf.append("  ");
            buf.append(tnEntry.toString());
            buf.append(sep);
        }
        return buf.toString();
    }
}
</code>```

Now, to add this extension to a certificate, I've done this code (with some sample data as I don't know what should be in each field in a real world situation):

X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(etc...);

// create TNEntries for TNAuthorizationList
TNEntry[] entries = new TNEntry[2];

// create a "spc" entry
DERIA5String[] cList = new DERIA5String[] { new DERIA5String("spc1"), new DERIA5String("spc2") };
DERSequence spc = new DERSequence(cList);
entries[0] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.spc, spc));

// create a "range" entry
DERSequence range = new DERSequence(new ASN1Encodable[] { new DERIA5String("123456"), new ASN1Integer(1) });
entries[1] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.range, range));

TNAuthorizationList tnAuthList = new TNAuthorizationList(entries);
builder.addExtension(TNAuthorizationList.TN_AUTH_LIST_OID, false, tnAuthList);
```

<p>Once you have the certificate object (a <code>X509Certificate</code> in my example), you can do:</p>

<pre class="lang-java prettyprint-override"><code>// cert is a X509Certificate instance
ASN1Primitive value = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue(TNAuthorizationList.TN_AUTH_LIST_OID.getId()));
TNAuthorizationList authList = TNAuthorizationList.getInstance(value);
System.out.println(authList.toString());
</code>```

The output will be:

TNAuthorizationList:
  TNEntry [0]: ServiceProviderCodeList:
    spc1
    spc2

  TNEntry [1]: TelephoneNumberRange:
    start: 123456
    count: 1
```

Notes:

As I said, this code is incomplete because I'm not sure how to handle the one field of TNEntry, because it's not tagged (I don't know if it must be a DERIA5String or if there's another type of object for an "untagged" field).

You could also do some improvements:

ServiceProviderCodeList can have 1 to 3 elements, so you could validate its size

TelephoneNumberRange: the start field has a specific format (FROM ("0123456789#*") which I think it means only these characters are accepted), so you could also validate it

To create the values for ServiceProviderCodeList and TelephoneNumberRange, I've created the DERSequence objects by hand, but you can create custom classes for them if you want: ServiceProviderCodeList could hold a list of DERIA5String and perform proper validations in its constructor (size from 1 to 3), and TelephoneNumberRange could have start and count fields (with proper validation of start value) - and toASN1Primitive just need to return a DERSequence of its fields in the right order

For your parsing issues, I've checked acme4j code and it uses a java.security.cert.X509Certificate class. The toString() method of this class (when using Sun's default provider) is generating this "extension unknown" output (according to the corresponding code).

So, in order to parse it correctly (show the formatted output as described above), you'll probably have to change acme4j's code (or write your own), creating a new toString() method and include the new TNAuthorizationList classes in this method.

When you provide the code showing how you're using acme4j, I'll update this answer accordingly, if needed.

Body:
I need to add a new Extension of OID 1.3.6.1.5.5.7.1.26 in my certificate. I got this OID extension in my certificate but with the following error:

Certificate Extensions: 10
  [1]: ObjectId: 1.3.6.1.5.5.7.1.26 Criticality=false

  Extension unknown: DER encoded OCTET string =

  0000: 04 0C 30 0A 13 08 33 39   20 64 63 20 32 62        ..0...

  39 dc 2b

I want this OID to be recognized similar to other extensions like AuthorityInfoAccess, etc.

Do I need to edit the jar of Bouncy Castle X509 class?

Im using ACME4j as a client and Letsencrypt Boulder as my server.

Here is the CSR Builder code for signing up the certificate.

public void sign(KeyPair keypair) throws IOException {
    //Security.addProvider(new BouncyCastleProvider());
    Objects.requireNonNull(keypair, "keypair");
    if (namelist.isEmpty()) {
        throw new IllegalStateException("No domain was set");
    }

    try {
        GeneralName[] gns = new GeneralName[namelist.size()];
        for (int ix = 0; ix < namelist.size(); ix++) {
            gns[ix] = new GeneralName(GeneralName.dNSName,namelist.get(ix));
        }
        SignatureAlgorithmIdentifierFinder algFinder = new
                DefaultSignatureAlgorithmIdentifierFinder();
        GeneralNames subjectAltName = new GeneralNames(gns);

        PKCS10CertificationRequestBuilder p10Builder = new     JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());

        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName,     false, subjectAltName);
        //extensionsGenerator.addExtension(Extension.authorityInfoAccess,         true, subjectAltName);
        //extensionsGenerator.addExtension(new ASN1ObjectIdentifier("TBD"),     false, subjectAltName);
        //extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.24"), false, subjectAltName);
        extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26").intern(), false, subjectAltName);
        //extentionsGenerator.addExtension();
            p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,     extensionsGenerator.generate());

        PrivateKey pk = keypair.getPrivate();
        /*JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
                        pk instanceof ECKey ? EC_SIGNATURE_ALG :     EC_SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);*/

        if(pk instanceof ECKey)
        {
            AlgorithmIdentifier sigAlg = algFinder.find("SHA1withECDSA");
              AlgorithmIdentifier digAlg = new     DefaultDigestAlgorithmIdentifierFinder().
                    find(sigAlg);
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).setProvider(BOUNCY_CASTL    E_PROVIDER).build(keypair.getPrivate());

            csr=p10Builder.build(signer);
            System.out.println("ZIPED CSR ECDSA: "+csr);
        }
        else
        {
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).build(keypair.getPrivate    ());
            csr = p10Builder.build(signer);
            System.out.println("ZIPED CSR RSA: "+csr);
        }

        //csr = p10Builder.build(signer);
    } catch (Exception ex) {
        ex.printStackTrace();;
    }
}

Body:
Note: for these codes I used bcprov-jdk15on 1.56

Some comments about your code. First of all, note the ASN1 structure:

TNAuthorizationList ::= SEQUENCE SIZE (1..MAX) OF TNEntry

TNEntry ::= CHOICE {
  spc   [0] ServiceProviderCodeList,
  range [1] TelephoneNumberRange,
  one       E164Number
}

Note that TNEntry is a choice, and TNAuthorizationList is a sequence of TNEntry objects. So your class name should be changed to TNEntry. In the code below, please remember that I've changed the class name to TNEntry.

I've also changed some things in this class. In getInstance(Object obj) method, the types of spc and range fields are incorrect (according to ASN1 definition, they are both sequences):

switch (tag) {
    case spc:
    case range: // both are sequences
        return new TNEntry(tag, ASN1Sequence.getInstance(tagObj, false));
    // not sure about "one" field, as it's not tagged
}

I just don't know how to handle the one field, as it's not tagged. Maybe it should be a DERIA5String, or maybe there's another type for "untagged" choices.

In this same class (remember, I've changed its name to TNEntry), I also removed the constructor public TNEntry(int tag, String name) because I'm not sure if it applies (at least I didn't need to use it, but you can keep it if you want), and I've changed toString method to return a more readable string:

public String toString() {
    String sep = System.getProperty("line.separator");
    StringBuffer buf = new StringBuffer();

    buf.append(this.getClass().getSimpleName());
    buf.append(" [").append(tag);
    buf.append("]: ");
    switch (tag) {
        case spc:
            buf.append("ServiceProviderCodeList: ").append(sep);
            ASN1Sequence seq = (ASN1Sequence) this.obj;
            int size = seq.size();
            for (int i = 0; i < size; i++) {
                // all elements are DERIA5Strings
                DERIA5String str = (DERIA5String) seq.getObjectAt(i);
                buf.append("    ");
                buf.append(str.getString());
                buf.append(sep);
            }
            break;

        case range:
            buf.append("TelephoneNumberRange: ").append(sep);

            // there are always 2 elements in TelephoneNumberRange
            ASN1Sequence s = (ASN1Sequence) this.obj;
            DERIA5String str = (DERIA5String) s.getObjectAt(0);
            buf.append("    start: ");
            buf.append(str.getString());
            buf.append(sep);
            ASN1Integer count = (ASN1Integer) s.getObjectAt(1);
            buf.append("    count: ");
            buf.append(count.toString());
            buf.append(sep);
            break;

        default:
            buf.append(obj.toString());
    }

    return buf.toString();
}

And I also created a TNAuthorizationList class, which holds the sequence of TNEntry objects (remember that I've changed your class name to TNEntry, so this TNAuthorizationList class is a different one). Note that I also created a constant to hold the OID (just to make things a little bit easier):

public class TNAuthorizationList extends ASN1Object {
    // put OID in a constant, so I don't have to remember it all the time
    public static final ASN1ObjectIdentifier TN_AUTH_LIST_OID = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26");

    private TNEntry[] entries;

    public TNAuthorizationList(TNEntry[] entries) {
        this.entries = entries;
    }

    public static TNAuthorizationList getInstance(Object obj) {
        if (obj instanceof TNAuthorizationList) {
            return (TNAuthorizationList) obj;
        }
        if (obj != null) {
            return new TNAuthorizationList(ASN1Sequence.getInstance(obj));
        }

        return null;
    }

    public static TNAuthorizationList getInstance(ASN1TaggedObject obj, boolean explicit) {
        return getInstance(ASN1Sequence.getInstance(obj, explicit));
    }

    private TNAuthorizationList(ASN1Sequence seq) {
        this.entries = new TNEntry[seq.size()];

        for (int i = 0; i != seq.size(); i++) {
            entries[i] = TNEntry.getInstance(seq.getObjectAt(i));
        }
    }

    public TNEntry[] getEntries() {
        TNEntry[] tmp = new TNEntry[entries.length];
        System.arraycopy(entries, 0, tmp, 0, entries.length);
        return tmp;
    }

    @Override
    public ASN1Primitive toASN1Primitive() {
        return new DERSequence(entries);
    }

    public String toString() {
        String sep = System.getProperty("line.separator");
        StringBuffer buf = new StringBuffer();

        buf.append(this.getClass().getSimpleName());
        buf.append(":").append(sep);
        for (TNEntry tnEntry : entries) {
            buf.append("  ");
            buf.append(tnEntry.toString());
            buf.append(sep);
        }
        return buf.toString();
    }
}

Now, to add this extension to a certificate, I've done this code (with some sample data as I don't know what should be in each field in a real world situation):

X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(etc...);

// create TNEntries for TNAuthorizationList
TNEntry[] entries = new TNEntry[2];

// create a "spc" entry
DERIA5String[] cList = new DERIA5String[] { new DERIA5String("spc1"), new DERIA5String("spc2") };
DERSequence spc = new DERSequence(cList);
entries[0] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.spc, spc));

// create a "range" entry
DERSequence range = new DERSequence(new ASN1Encodable[] { new DERIA5String("123456"), new ASN1Integer(1) });
entries[1] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.range, range));

TNAuthorizationList tnAuthList = new TNAuthorizationList(entries);
builder.addExtension(TNAuthorizationList.TN_AUTH_LIST_OID, false, tnAuthList);

Once you have the certificate object (a X509Certificate in my example), you can do:

// cert is a X509Certificate instance
ASN1Primitive value = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue(TNAuthorizationList.TN_AUTH_LIST_OID.getId()));
TNAuthorizationList authList = TNAuthorizationList.getInstance(value);
System.out.println(authList.toString());

The output will be:

TNAuthorizationList:
  TNEntry [0]: ServiceProviderCodeList:
    spc1
    spc2

  TNEntry [1]: TelephoneNumberRange:
    start: 123456
    count: 1

Notes:

As I said, this code is incomplete because I'm not sure how to handle the one field of TNEntry, because it's not tagged (I don't know if it must be a DERIA5String or if there's another type of object for an "untagged" field).

You could also do some improvements:

ServiceProviderCodeList can have 1 to 3 elements, so you could validate its size

TelephoneNumberRange: the start field has a specific format (FROM ("0123456789#*") which I think it means only these characters are accepted), so you could also validate it

To create the values for ServiceProviderCodeList and TelephoneNumberRange, I've created the DERSequence objects by hand, but you can create custom classes for them if you want: ServiceProviderCodeList could hold a list of DERIA5String and perform proper validations in its constructor (size from 1 to 3), and TelephoneNumberRange could have start and count fields (with proper validation of start value) - and toASN1Primitive just need to return a DERSequence of its fields in the right order

For your parsing issues, I've checked acme4j code and it uses a java.security.cert.X509Certificate class. The toString() method of this class (when using Sun's default provider) is generating this "extension unknown" output (according to the corresponding code).

So, in order to parse it correctly (show the formatted output as described above), you'll probably have to change acme4j's code (or write your own), creating a new toString() method and include the new TNAuthorizationList classes in this method.

When you provide the code showing how you're using acme4j, I'll update this answer accordingly, if needed.


问:
Custom file parser slows down with every next file
I have built a simple file parser that reads a csv file line by line and adds it to the DB.

i dont commit changes to the DB till after the file is completely parsed.

It works fine but for some reason with every next file - the parsing becomes slower and slower
here is the code any suggestions on how to speed it up are very welcome.

```<code>using Microsoft.VisualBasic.FileIO;
using System;
using System.IO;

namespace CsvToSQL
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            TransactionsEntities entities = new TransactionsEntities();

            string targetFolderPath = "C:\\Transactions\\";
            string[] allFiles = Directory.GetFiles(targetFolderPath);

            //Loop through files in folder
            foreach (var file in allFiles)
            {
                //parse file
                Console.WriteLine(file);
                using (TextFieldParser parser = new TextFieldParser(file))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int lineNo = 0;

                    while (!parser.EndOfData)
                    {

                        TransactionList transaction = new TransactionList();
                        //processing row
                        string[] fields = parser.ReadFields();
                        try
                        {
                         if(lineNo % 20 == 0)
                            {
                                Console.WriteLine(file + " Parsed line no: " + lineNo);
                            }
                            transaction.Account = fields[0];
                            transaction.Timestamp = fields[1];
                            transaction.TransactionType = fields[2];
                            transaction.Status = fields[3];
                            transaction.Product = fields[4];
                            transaction.Price = fields[5];
                            transaction.BuySell = fields[6];
                            transaction.Series = fields[7];
                            transaction.Volume = fields[8];
                            transaction.FillVolume = fields[9];
                            transaction.OrderID = fields[10];
                            transaction.BestBid = fields[11];
                            transaction.BestAsk = fields[12];

                            entities.TransactionLists.Add(transaction);

                            lineNo++;

                        }
                        catch(Exception e)
                        {
                            Console.WriteLine(e.ToString());
                            Console.ReadKey();
                        }

                    }
                    try
                    {
                        entities.SaveChanges();
                    }catch(Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.ReadKey();
                    }

                }

            }
        }
    }
}
</code>```

答:
Your problem is:

```<code>TransactionsEntities entities = new TransactionsEntities();
</code>```

Because Entity framework was not designed to work with bulk data in mind, it caches the entries in memory to minimize requeries etc. But adding lots of entries in a single context makes maintaining/checking cached data slow, which is your case.

You should better use SQLBulkCopy if you're using SQL server. It will add 100x more speed to your process.

Body:
I have built a simple file parser that reads a csv file line by line and adds it to the DB.

i dont commit changes to the DB till after the file is completely parsed.

It works fine but for some reason with every next file - the parsing becomes slower and slower
here is the code any suggestions on how to speed it up are very welcome.

using Microsoft.VisualBasic.FileIO;
using System;
using System.IO;

namespace CsvToSQL
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            TransactionsEntities entities = new TransactionsEntities();

            string targetFolderPath = "C:\\Transactions\\";
            string[] allFiles = Directory.GetFiles(targetFolderPath);

            //Loop through files in folder
            foreach (var file in allFiles)
            {
                //parse file
                Console.WriteLine(file);
                using (TextFieldParser parser = new TextFieldParser(file))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    int lineNo = 0;

                    while (!parser.EndOfData)
                    {

                        TransactionList transaction = new TransactionList();
                        //processing row
                        string[] fields = parser.ReadFields();
                        try
                        {
                         if(lineNo % 20 == 0)
                            {
                                Console.WriteLine(file + " Parsed line no: " + lineNo);
                            }
                            transaction.Account = fields[0];
                            transaction.Timestamp = fields[1];
                            transaction.TransactionType = fields[2];
                            transaction.Status = fields[3];
                            transaction.Product = fields[4];
                            transaction.Price = fields[5];
                            transaction.BuySell = fields[6];
                            transaction.Series = fields[7];
                            transaction.Volume = fields[8];
                            transaction.FillVolume = fields[9];
                            transaction.OrderID = fields[10];
                            transaction.BestBid = fields[11];
                            transaction.BestAsk = fields[12];

                            entities.TransactionLists.Add(transaction);

                            lineNo++;

                        }
                        catch(Exception e)
                        {
                            Console.WriteLine(e.ToString());
                            Console.ReadKey();
                        }

                    }
                    try
                    {
                        entities.SaveChanges();
                    }catch(Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.ReadKey();
                    }

                }

            }
        }
    }
}

Body:
Your problem is:

TransactionsEntities entities = new TransactionsEntities();

Because Entity framework was not designed to work with bulk data in mind, it caches the entries in memory to minimize requeries etc. But adding lots of entries in a single context makes maintaining/checking cached data slow, which is your case.

You should better use SQLBulkCopy if you're using SQL server. It will add 100x more speed to your process.


问:
Update a column with the result-dataset-count of a stored procedure
I have a table #data which has the columns Id and Count. In addition I have a stored procedure MyProc which accepts a parameter @id (equals the Id column) and returns a dataset (the count equals the Count column).

My goal is to assign the Count column from Id with MyProc without a cursor.

I know, something like this does not work:

```<code>UPDATE d
SET Count = (SELECT COUNT(*) FROM (EXEC MyProc d.Id))
FROM #data AS d
</code>```

Is there a syntax I do not know or is a cursor the only option to achieve this?

PS: It is a code quality and performance problem for me. Calling the stored procedure would be the easiest way without repeating 50 lines of SQL but a cursor slows it down.

答:
To do what you say, you need a function, not a procedure.

```<code>CREATE FUNCTION dbo.myFunc (@Id INT)
    RETURNS INT
AS
BEGIN

  UPDATE someTable
     SET someCol = 'someValue'
   WHERE id = @Id;

  RETURN @@ROWCOUNT;
END
GO
</code>```

Then call the function in your update statement;

```<code>UPDATE d
   SET d.Count = dbo.myFunc(d.Id)
  FROM #data AS d;
</code>```

However, row-based operations is bad practice. You should always strive to perform set-based operations, but as I don't know what your procedure does, I cannot provide more than a wild guess to what you should do (not using a procedure at all):

```<code>DECLARE @data TABLE (Id INT);

UPDATE x
   SET x.someCol = 'SomeVal'
OUTPUT INSERTED.id INTO @data
  FROM someTable AS x
 INNER JOIN #data AS d
         ON d.Id = x.Id;

WITH cte (Id, myCount) AS (
    SELECT d.Id
          ,COUNT(d.Id) AS myCount
      FROM @data AS d
     GROUP BY d.Id
)
UPDATE d
   SET d.[Count] = c.myCount
  FROM #data AS d
 INNER JOIN cte AS c
         ON c.Id = d.Id;
</code>```

Body:
I have a table #data which has the columns Id and Count. In addition I have a stored procedure MyProc which accepts a parameter @id (equals the Id column) and returns a dataset (the count equals the Count column).

My goal is to assign the Count column from Id with MyProc without a cursor.

I know, something like this does not work:

UPDATE d
SET Count = (SELECT COUNT(*) FROM (EXEC MyProc d.Id))
FROM #data AS d

Is there a syntax I do not know or is a cursor the only option to achieve this?

PS: It is a code quality and performance problem for me. Calling the stored procedure would be the easiest way without repeating 50 lines of SQL but a cursor slows it down.

Body:
To do what you say, you need a function, not a procedure.

CREATE FUNCTION dbo.myFunc (@Id INT)
    RETURNS INT
AS
BEGIN

  UPDATE someTable
     SET someCol = 'someValue'
   WHERE id = @Id;

  RETURN @@ROWCOUNT;
END
GO

Then call the function in your update statement;

UPDATE d
   SET d.Count = dbo.myFunc(d.Id)
  FROM #data AS d;

However, row-based operations is bad practice. You should always strive to perform set-based operations, but as I don't know what your procedure does, I cannot provide more than a wild guess to what you should do (not using a procedure at all):

DECLARE @data TABLE (Id INT);

UPDATE x
   SET x.someCol = 'SomeVal'
OUTPUT INSERTED.id INTO @data
  FROM someTable AS x
 INNER JOIN #data AS d
         ON d.Id = x.Id;

WITH cte (Id, myCount) AS (
    SELECT d.Id
          ,COUNT(d.Id) AS myCount
      FROM @data AS d
     GROUP BY d.Id
)
UPDATE d
   SET d.[Count] = c.myCount
  FROM #data AS d
 INNER JOIN cte AS c
         ON c.Id = d.Id;


问:
WebBrowser font-face request abort weirdness
I've built an WPF application (.NET 4.5) which runs on Win7 IE11 machines. The main window has a webbrowser control on it and nothing else (its a very simplified version of my actual app which is experiencing issues).

On some machines when browsing to a given web site the font-face fonts (WOFF and TTF) are not working, even though they do work in IE11 on the same machine. I have used a reg punch to get the webrowser to run in IE11/ edge mode, this does not fix the issue.

Using Fiddler2 I have seen that the request for the font gets aborted after the whole font was downloaded. Repeating the request with Fiddler works and doesn't get aborted, so I know the issue must be with the webbrowser control.

All the machines affected are on a certain domain. Does anyone know of any permissions at domain/policy level which would cause the font to work in IE but be aborted/rejected in a WPF webbrowser control?

This only happens for fonts delivered over HTTPS

答: Check if any cache invalidating headers are possibly returned by the server; IExplorer doesn't cope well with it and will not show fonts: See here</p>


问:
Subclipse- single programmer usage
I just started using subclipse for my class projects after a re-writing half of a project due to going off on the wrong logical branch.  Since I'm using it on my home systems, I have a couple questions whose answers I haven't found in searching.

Say I have  local separate repositories on my computers.  First, can I use a file sync to keep them synced until I figure out what I need to do to access the university's network?  (aside- only information available is about accessing the network remotely is thru PUTTY and FTP, which are not valid URL strings)

Second, in the same local system, am I correct in that once I check out a project and apply commits regularly, I don't have to keep checking out the project?

答: I ended up using SlikSVN for hosting the repository, since it is free for <100MB storage, which is perfect for my classwork.  Also, I don't have to bother with tunneling through the school's network.</p>

Title: Subclipse- single programmer usage