问:
Why am I getting an ArrayIndexOutOfBounds error in my code? I do not set a default length to my ArrayAdapter
I'm creating my own Settings activity, and so far I have set one user option. It
is a spinner, and when the user changed the spinner value, the value will be saved to SharedPreferences. This will affect something in a different area of my app.

The idea is that whenever the user opens the Settings activity, it will read from SharedPreferences and set the selection to the value last selected by the user.

However, I am getting an "ArrayIndexOutOfBounds exception: length = 4" at the end of my onCreate() method. The logcat does not show any specific reason why this is happening. This is my first time using a Spinner and ArrayAdapter, so maybe I'm missing something, but I do not set a length for my ArrayAdapter, and the array that I pass it has a length of 4.

I'm thinking the crash might have something to do with the SharedPreferences aspect of thing, but I can't think of why. I also need to know how to stop the onItemSelected() method from firing without any user interaction.

Here is the code:

```<code>package groovinchip.com.callmanager;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Settings extends AppCompatActivity implements OnItemSelectedListener{

    SharedPreferences appPrefs;
    public final String APP_PREFS = "appPrefs";
    private boolean isChecked = false;
    Spinner chatPicker;
    String infoMsg;
    int chatSelection; // for saving
    int currentChat; // for displaying

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAppTheme();
        setContentView(R.layout.activity_settings);
        openAppPrefs();
        setChatSpinner();
    }

    // Set the app theme based on boolean value from
    // SharedPreferences
    private void setAppTheme() {
        openAppPrefs();
        Boolean isDark = appPrefs.getBoolean("themeVal", false);
        if(isDark==true){
            setTheme(R.style.AppThemeDark);
            isChecked = true;
        }
        else{
            setTheme(R.style.AppTheme);
            isChecked = false;
        }
    }

    public void openAppPrefs(){
        appPrefs = this.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
    }

    // Instantiate the 'custom chat' spinner;
    // Get the specified value from SharedPreferences
    // Based on the value retrieved, set the spinner choice
    public void setChatSpinner(){
        chatPicker = (Spinner)findViewById(R.id.chatPicker);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.custom_chats, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        chatPicker.setAdapter(adapter);
        chatPicker.setOnItemSelectedListener(this);

        currentChat = appPrefs.getInt("chatSelectionID", 0);
        switch (currentChat){
            case 0:
                chatPicker.setSelection(R.string.CA_optional_chat_default);
                break;
            case 1:
                chatPicker.setSelection(R.string.CA_optional_chat_whatsapp);
                break;
            case 2:
                chatPicker.setSelection(R.string.CA_optional_chat_telegram);
                break;
            case 3:
                chatPicker.setSelection(R.string.CA_optional_chat_facebook_messenger);
                break;
            default:
                chatPicker.setSelection(R.string.CA_optional_chat_default);
                break;
        }
    }

    // Do something when a spinner item is chosen
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
        switch (pos){
            case 0:
                infoMsg = "SMS option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(pos);
                break;
            case 1:
                infoMsg = "WhatsApp option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(chatSelection);
                break;
            case 2:
                infoMsg = "Telegram option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(chatSelection);
                break;
            case 3:
                infoMsg = "Facebook Messenger option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(chatSelection);
                break;
            default:
                break;
        }
    }

    // Create a toast message to the user to show which settings option they have chosen
    public void createUserInfoMessage(String message){
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        toast.show();
    }

    // Save user selection to SharedPreferences
    public void saveChatChange(int position){
        chatSelection = position;
        openAppPrefs();
        SharedPreferences.Editor editor = appPrefs.edit();
        editor.putInt("chatSelectionID", chatSelection);
        editor.commit();
    }

    // Required
    public void onNothingSelected(AdapterView<?> parent){
        // Do nothing
    }
}
</code>```

EDIT: Below is the stack trace

```<code>FATAL EXCEPTION: main
                                                 Process: groovinchip.com.callmanager, PID: 6702
                                                 java.lang.ArrayIndexOutOfBoundsException: length=4; index=2131623943
                                                     at java.util.Arrays$ArrayList.get(Arrays.java:3769)
                                                     at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:385)
                                                     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:441)
                                                     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:407)
                                                     at android.widget.Spinner.makeView(Spinner.java:712)
                                                     at android.widget.Spinner.layout(Spinner.java:660)
                                                     at android.widget.Spinner.onLayout(Spinner.java:622)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.support.constraint.ConstraintLayout.onLayout(ConstraintLayout.java:1197)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                     at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:443)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                     at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
                                                     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
                                                     at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                     at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                     at com.android.internal.policy.DecorView.onLayout(DecorView.java:758)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2484)
                                                     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2200)
                                                     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386)
                                                     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733)
                                                     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
                                                     at android.view.Choreographer.doCallbacks(Choreographer.java:723)
                                                     at android.view.Choreographer.doFrame(Choreographer.java:658)
                                                     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
                                                     at android.os.Handler.handleCallback(Handler.java:789)
                                                     at android.os.Handler.dispatchMessage(Handler.java:98)
                                                     at android.os.Looper.loop(Looper.java:164)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

答:
Your code includes this switch statement:

```<code>currentChat = appPrefs.getInt("chatSelectionID", 0);
switch (currentChat){
    case 0:
        chatPicker.setSelection(R.string.CA_optional_chat_default);
        break;
    case 1:
        chatPicker.setSelection(R.string.CA_optional_chat_whatsapp);
        break;
    case 2:
        chatPicker.setSelection(R.string.CA_optional_chat_telegram);
        break;
    case 3:
        chatPicker.setSelection(R.string.CA_optional_chat_facebook_messenger);
        break;
    default:
        chatPicker.setSelection(R.string.CA_optional_chat_default);
        break;
}
</code>```

The setSelection() method takes in a position argument, but you are passing it a resource identifier instead. If you open your R.string class, you'll see each of these constants defined, and they will have values that are much larger than 0-3 (or potentially values that are negative). Here's an example from one of my projects:

```<code>public static final class string {
    ...
    public static final int ANYTIME=0x7f110072;
    ...
}
</code>```

It turns out you can simplify your code drastically, considering that currentChat is itself a position. Try this:

```<code>currentChat = appPrefs.getInt("chatSelectionID", 0);
chatPicker.setSelection(currentChat);
</code>```

Update

To stop the item selection listener from firing without user interaction, move this line:

```<code>chatPicker.setOnItemSelectedListener(this);
</code>```

below the code where you call chatPicker.setSelection(). Calling setSelection() will trigger your listener.

The reason the selected position isn't being saved if you change the selection, leave the activity, and then return is due to this code:

```<code>public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
    switch (pos){
        case 0:
            infoMsg = "SMS option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(pos);
            break;
        case 1:
            infoMsg = "WhatsApp option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(chatSelection);
            break;
        case 2:
            infoMsg = "Telegram option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(chatSelection);
            break;
        case 3:
            infoMsg = "Facebook Messenger option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(chatSelection);
            break;
        default:
            break;
    }
}
</code>```

In every case other than 0, you're saving chatSelection instead of pos. You could simplify to this:

```<code>public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
    switch (pos){
        case 0:
            infoMsg = "SMS option chosen";
            break;
        case 1:
            infoMsg = "WhatsApp option chosen";
            break;
        case 2:
            infoMsg = "Telegram option chosen";
            break;
        case 3:
            infoMsg = "Facebook Messenger option chosen";
            break;
    }

    createUserInfoMessage(infoMsg);
    saveChatChange(pos);
}
</code>```

Body:
I'm creating my own Settings activity, and so far I have set one user option. It
is a spinner, and when the user changed the spinner value, the value will be saved to SharedPreferences. This will affect something in a different area of my app.

The idea is that whenever the user opens the Settings activity, it will read from SharedPreferences and set the selection to the value last selected by the user.

However, I am getting an "ArrayIndexOutOfBounds exception: length = 4" at the end of my onCreate() method. The logcat does not show any specific reason why this is happening. This is my first time using a Spinner and ArrayAdapter, so maybe I'm missing something, but I do not set a length for my ArrayAdapter, and the array that I pass it has a length of 4.

I'm thinking the crash might have something to do with the SharedPreferences aspect of thing, but I can't think of why. I also need to know how to stop the onItemSelected() method from firing without any user interaction.

Here is the code:

package groovinchip.com.callmanager;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Settings extends AppCompatActivity implements OnItemSelectedListener{

    SharedPreferences appPrefs;
    public final String APP_PREFS = "appPrefs";
    private boolean isChecked = false;
    Spinner chatPicker;
    String infoMsg;
    int chatSelection; // for saving
    int currentChat; // for displaying

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAppTheme();
        setContentView(R.layout.activity_settings);
        openAppPrefs();
        setChatSpinner();
    }

    // Set the app theme based on boolean value from
    // SharedPreferences
    private void setAppTheme() {
        openAppPrefs();
        Boolean isDark = appPrefs.getBoolean("themeVal", false);
        if(isDark==true){
            setTheme(R.style.AppThemeDark);
            isChecked = true;
        }
        else{
            setTheme(R.style.AppTheme);
            isChecked = false;
        }
    }

    public void openAppPrefs(){
        appPrefs = this.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
    }

    // Instantiate the 'custom chat' spinner;
    // Get the specified value from SharedPreferences
    // Based on the value retrieved, set the spinner choice
    public void setChatSpinner(){
        chatPicker = (Spinner)findViewById(R.id.chatPicker);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.custom_chats, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        chatPicker.setAdapter(adapter);
        chatPicker.setOnItemSelectedListener(this);

        currentChat = appPrefs.getInt("chatSelectionID", 0);
        switch (currentChat){
            case 0:
                chatPicker.setSelection(R.string.CA_optional_chat_default);
                break;
            case 1:
                chatPicker.setSelection(R.string.CA_optional_chat_whatsapp);
                break;
            case 2:
                chatPicker.setSelection(R.string.CA_optional_chat_telegram);
                break;
            case 3:
                chatPicker.setSelection(R.string.CA_optional_chat_facebook_messenger);
                break;
            default:
                chatPicker.setSelection(R.string.CA_optional_chat_default);
                break;
        }
    }

    // Do something when a spinner item is chosen
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
        switch (pos){
            case 0:
                infoMsg = "SMS option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(pos);
                break;
            case 1:
                infoMsg = "WhatsApp option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(chatSelection);
                break;
            case 2:
                infoMsg = "Telegram option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(chatSelection);
                break;
            case 3:
                infoMsg = "Facebook Messenger option chosen";
                createUserInfoMessage(infoMsg);
                saveChatChange(chatSelection);
                break;
            default:
                break;
        }
    }

    // Create a toast message to the user to show which settings option they have chosen
    public void createUserInfoMessage(String message){
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        toast.show();
    }

    // Save user selection to SharedPreferences
    public void saveChatChange(int position){
        chatSelection = position;
        openAppPrefs();
        SharedPreferences.Editor editor = appPrefs.edit();
        editor.putInt("chatSelectionID", chatSelection);
        editor.commit();
    }

    // Required
    public void onNothingSelected(AdapterView<?> parent){
        // Do nothing
    }
}

EDIT: Below is the stack trace

FATAL EXCEPTION: main
                                                 Process: groovinchip.com.callmanager, PID: 6702
                                                 java.lang.ArrayIndexOutOfBoundsException: length=4; index=2131623943
                                                     at java.util.Arrays$ArrayList.get(Arrays.java:3769)
                                                     at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:385)
                                                     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:441)
                                                     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:407)
                                                     at android.widget.Spinner.makeView(Spinner.java:712)
                                                     at android.widget.Spinner.layout(Spinner.java:660)
                                                     at android.widget.Spinner.onLayout(Spinner.java:622)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.support.constraint.ConstraintLayout.onLayout(ConstraintLayout.java:1197)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                     at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:443)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                     at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
                                                     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
                                                     at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                     at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                     at com.android.internal.policy.DecorView.onLayout(DecorView.java:758)
                                                     at android.view.View.layout(View.java:19590)
                                                     at android.view.ViewGroup.layout(ViewGroup.java:6053)
                                                     at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2484)
                                                     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2200)
                                                     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386)
                                                     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733)
                                                     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
                                                     at android.view.Choreographer.doCallbacks(Choreographer.java:723)
                                                     at android.view.Choreographer.doFrame(Choreographer.java:658)
                                                     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
                                                     at android.os.Handler.handleCallback(Handler.java:789)
                                                     at android.os.Handler.dispatchMessage(Handler.java:98)
                                                     at android.os.Looper.loop(Looper.java:164)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Body:
Your code includes this switch statement:

currentChat = appPrefs.getInt("chatSelectionID", 0);
switch (currentChat){
    case 0:
        chatPicker.setSelection(R.string.CA_optional_chat_default);
        break;
    case 1:
        chatPicker.setSelection(R.string.CA_optional_chat_whatsapp);
        break;
    case 2:
        chatPicker.setSelection(R.string.CA_optional_chat_telegram);
        break;
    case 3:
        chatPicker.setSelection(R.string.CA_optional_chat_facebook_messenger);
        break;
    default:
        chatPicker.setSelection(R.string.CA_optional_chat_default);
        break;
}

The setSelection() method takes in a position argument, but you are passing it a resource identifier instead. If you open your R.string class, you'll see each of these constants defined, and they will have values that are much larger than 0-3 (or potentially values that are negative). Here's an example from one of my projects:

public static final class string {
    ...
    public static final int ANYTIME=0x7f110072;
    ...
}

It turns out you can simplify your code drastically, considering that currentChat is itself a position. Try this:

currentChat = appPrefs.getInt("chatSelectionID", 0);
chatPicker.setSelection(currentChat);

Update

To stop the item selection listener from firing without user interaction, move this line:

chatPicker.setOnItemSelectedListener(this);

below the code where you call chatPicker.setSelection(). Calling setSelection() will trigger your listener.

The reason the selected position isn't being saved if you change the selection, leave the activity, and then return is due to this code:

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
    switch (pos){
        case 0:
            infoMsg = "SMS option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(pos);
            break;
        case 1:
            infoMsg = "WhatsApp option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(chatSelection);
            break;
        case 2:
            infoMsg = "Telegram option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(chatSelection);
            break;
        case 3:
            infoMsg = "Facebook Messenger option chosen";
            createUserInfoMessage(infoMsg);
            saveChatChange(chatSelection);
            break;
        default:
            break;
    }
}

In every case other than 0, you're saving chatSelection instead of pos. You could simplify to this:

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
    switch (pos){
        case 0:
            infoMsg = "SMS option chosen";
            break;
        case 1:
            infoMsg = "WhatsApp option chosen";
            break;
        case 2:
            infoMsg = "Telegram option chosen";
            break;
        case 3:
            infoMsg = "Facebook Messenger option chosen";
            break;
    }

    createUserInfoMessage(infoMsg);
    saveChatChange(pos);
}


来源: stackexchange

问:
unfortunately ___ has stopped , but logcat contains many errors
i have developped an application android that contains two activities , the first activity contains two Edittext and a login button , i have to enter the value 'abcd'  as a username and 'EFGH' as a password and validate with the button , the probleme is when i clicked login the application has crashed  ,

the error message is : unfortunately ___ is stopped

logcat:  errors 11-15 19:22:56.237 783-783/? E/Zygote: accessInfo : 0
  11-15 19:24:41.057 783-783/info.adem.tplogin E/AndroidRuntime: FATAL
  EXCEPTION: main
                                                                 Process: info.adem.tplogin, PID: 783
                                                                 java.lang.RuntimeException: Unable to start activity
  ComponentInfo{info.adem.tplogin/info.adem.tplogin.FriendActivity}:
  java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
  on a null object reference
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                                                                     at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:158)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:7224)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
  'void
  android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
  on a null object reference
                                                                     at info.adem.tplogin.FriendActivity.onCreate(FriendActivity.java:27)
                                                                     at android.app.Activity.performCreate(Activity.java:6876)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                                                                     at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:158)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:7224)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

答:
```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object
</code>```

Before you use a reference from your button to add an event, you need to retrieve the reference from it.

Like this:

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_your_layout)

        Button button = (Button)findViewById(R.id.your_button_id)
        //button.setOnClickListener........
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object

Before you use a reference from your button to add an event, you need to retrieve the reference from it.

Like this:

public class YourActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_your_layout)

        Button button = (Button)findViewById(R.id.your_button_id)
        //button.setOnClickListener........
    }

}


问:
Are arrays covariant in their size?
Is there a way to use the new std::array type polymorphically in the size of the array?  That is, if I have a function of the form

```<code>void DoSomething(std::array<int, 5>& myArray) {
    /* ... */
}
</code>```

Then is it mathematically well-defined to do the following (even if it's not legal C++ code?)

```<code>std::array<int, 10> arr;
DoSomething(arr);
</code>```

Imof this is mathematically well-defined, is there a way to write std::array such that its array elements are contiguous and this code compiles?  The only technique I could think of would be to have some weird template metaprogram where std::array<T, N+1> inherits from std::array<T, N>, but I don't believe that forces the array elements to be contiguous.

答:
Directly?  No.

You can, however, use compile-time polymorphism to achieve something very similar, and you can write a reference wrapper that makes it easier to work with in the code:

```<code>#include <array>
#include <cstddef>

template <typename T, std::size_t N>
struct ref_array_of_at_least
{
    template <std::size_t M>
    ref_array_of_at_least(T (&a)[M])
        : data_(a)
    {
        static_assert(M >= N, "Invalid size");
    }

    template <std::size_t M>
    ref_array_of_at_least(std::array<T, M>& a)
        : data_(&a[0])
    {
        static_assert(M >= N, "Invalid size");
    }

    T* data_;
};
</code>```

Used as:

```<code>void f(ref_array_of_at_least<int, 5>) { }

int main()
{
    std::array<int, 5> x;
    std::array<int, 6> y;
    std::array<int, 4> z;
    f(x); // ok
    f(y); // ok
    f(z); // fail
}
</code>```

(You'd need to add some operator[] overloads and such to ref_array_of_at_least, and it needs some work to make it const correct, but it's a start that demonstrates the possibility of what you are seeking.)

ContentLicense: CC BY-SA 2.5

Title: Are arrays covariant in their size?

Body:
Is there a way to use the new std::array type polymorphically in the size of the array?  That is, if I have a function of the form

void DoSomething(std::array<int, 5>& myArray) {
    /* ... */
}

Then is it mathematically well-defined to do the following (even if it's not legal C++ code?)

std::array<int, 10> arr;
DoSomething(arr);

Imof this is mathematically well-defined, is there a way to write std::array such that its array elements are contiguous and this code compiles?  The only technique I could think of would be to have some weird template metaprogram where std::array<T, N+1> inherits from std::array<T, N>, but I don't believe that forces the array elements to be contiguous.

Body:
Directly?  No.

You can, however, use compile-time polymorphism to achieve something very similar, and you can write a reference wrapper that makes it easier to work with in the code:

#include <array>
#include <cstddef>

template <typename T, std::size_t N>
struct ref_array_of_at_least
{
    template <std::size_t M>
    ref_array_of_at_least(T (&a)[M])
        : data_(a)
    {
        static_assert(M >= N, "Invalid size");
    }

    template <std::size_t M>
    ref_array_of_at_least(std::array<T, M>& a)
        : data_(&a[0])
    {
        static_assert(M >= N, "Invalid size");
    }

    T* data_;
};

Used as:

void f(ref_array_of_at_least<int, 5>) { }

int main()
{
    std::array<int, 5> x;
    std::array<int, 6> y;
    std::array<int, 4> z;
    f(x); // ok
    f(y); // ok
    f(z); // fail
}

(You'd need to add some operator[] overloads and such to ref_array_of_at_least, and it needs some work to make it const correct, but it's a start that demonstrates the possibility of what you are seeking.)


问:
Webgl full screen blending slowdown
I've tried to make an "overlay" effect in a 3d scene. After drawing stuff to the buffer, i tried to draw a full screen quad with blending enabled and the depth test disabled. On some android devices this seems to have caused a slow down.

I found this link:

The particularly slow point is the point where the drawing of a pixel needs to check what the color behind it was.

So instead of drawing a single full screen quad, i divided it up in tiles, and rendered with multiple draw calls, which seems to have caused some gain.

What may be happening here and how can this be profiled with webgl i.e. how does one come to the conclusion from the quote above?

答:
I guess that to profile it, you simply have to test with several blending function, with or without blending enabled, etc...

Blending is not a trivial operation, and indeed we can assume that blending function which need to read pixel on buffer could induce performance lose, like all "reading" operation in OpenGL, because this can block the pipeline. I guess most of modern desktop GPU have some specific design to optimize this, but on mobile phones, this is maybe more problematic.

Anyway, if you are about to draw a full screen quad, why don't you render your quad directly using two source texture, which you blend directly in the fragment shader using a custom equation ? this way, you don't need to use blending and you avoid any back buffer reading problem.

Title: Webgl full screen blending slowdown


问:
Reusing StorageClass in Kubernetes
Can I use the same storage class for different services - e.g. I am using persistent volumes for Redis, RabbitMQ , Elastic Search on Kubernetes.

Should I create only only storage class if they all require the same provisioner (GCEPersistentDisk) or what is the best practice for creating and managing storage class.

Can I change the storage class of a claim at a later time ?

Thanks,
Rajesh

答:
Let's look at the definition of StorageClass from the documentation:

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: standard
provisioner: kubernetes.io/aws-ebs
parameters:
  type: gp2
reclaimPolicy: Retain
mountOptions:
  - debug

So at a basic level, it defines - who is responsible for creating storage (provisioner) and what parameters need to pass and things such as reclaim policy and so on.

So the number of storage classes you need is dependent characteristics of the underlying storage. As a hypothetical example let's say you had HD and SSD as two types of storages then you would create corresponding two storage classes.

To answer specific questions:

Can I use the same storage class for different services - e.g. I am
  using persistent volumes for Redis, RabbitMQ , Elastic Search on
  Kubernetes.

Yes

Can I change the storage class of a claim at a later time ?

In practice, No

Title: Reusing StorageClass in Kubernetes


问:
Has anyone build form validation using YUI?
DUPE: Any Yahoo YUI validation framework that I can implement in asp.net MVC?

Has anyone built form validation functions using YUI that could mimick how asp.net handles form validation?

I know jquery has a nice validation addon, was hoping YUI would also.

答: I just took a quick look through the YUI toolkit and there doesn't seem to be anything that jumps out at me.  I know they have stuff for validation on the DataTable inputs, but it doesn't look like there is an equivalent for forms.</p>

OwnerDisplayName: Blankman

LastEditorDisplayName: Rich B

OwnerDisplayName: Nick Berardi


问:
Updating div page coordinates in the datastore
I'm currently making a webapp in App Engine where users can create multiple "boxes" (divs) with text inside of them.  These "boxes" can be dragged around the page.  I implemented the drag and drop functionality using the JQuery UI Draggable plugin.  I can easily display the current coordinate of each box on mouseup using:

```<code>$(this).offset();
</code>```

Each box has an entity in the datastore which contains it's respective content. I was planning on just creating another member for the box entity which contains it's coordinates. This way, every time the user logs in to his account on the webapp, the boxes will appear where they were last. My problem is, I'm not sure how to update the datastore each time a box is dragged about the page. To be honest, I'm not sure if I'm even approaching the problem correctly. I would appreciate any guidance on how I can achieve this.

This is how the page is being rendered, just to give further insight:

```<code> {% for box in boxes %}
 <div draggable="true" id="box" class="ui-widget-content draggable">
    <div id="title">
 {% if box.title %}
     {{ box.title }}<br>
 {% else %}
     Untitled<br>
 {% endif %}
 </div>
 <div id="content">
    {{ box.content }}<br>
 </div>
 <div id="menu">
    <a href="/edit/{{ box.key.id }}">View/Edit</a>
    <a href="/delete/{{ box.key.id }}">Delete</a>
 </div>
</div>
{% endfor %}
</code>```

Thanks again.

答: You need to use JQuery to capture the 'drop' event, and fire off an AJAX request to your app, POSTing the ID of the box and the new coordinates, so it can update them in the datastore.</p>

Body:
I'm currently making a webapp in App Engine where users can create multiple "boxes" (divs) with text inside of them.  These "boxes" can be dragged around the page.  I implemented the drag and drop functionality using the JQuery UI Draggable plugin.  I can easily display the current coordinate of each box on mouseup using:

$(this).offset();

Each box has an entity in the datastore which contains it's respective content. I was planning on just creating another member for the box entity which contains it's coordinates. This way, every time the user logs in to his account on the webapp, the boxes will appear where they were last. My problem is, I'm not sure how to update the datastore each time a box is dragged about the page. To be honest, I'm not sure if I'm even approaching the problem correctly. I would appreciate any guidance on how I can achieve this.

This is how the page is being rendered, just to give further insight:

 {% for box in boxes %}

 {% if box.title %}
     {{ box.title }}

 {% else %}
     Untitled

 {% endif %}

    {{ box.content }}

    View/Edit
    Delete

{% endfor %}

Thanks again.


问:
Parsing the HTML content in email
I'm trying to write a python script to read my emails.
I'm able to get most of the things properly like To, From, Subject.
But in the body, I get the text as well as it's HTML code too as shown below.

Below is the part of code that does the extraction of content from the email

```<code>email_message = email.message_from_string(raw_email)
print 'To:', email_message['To']
print 'Sent from:', email_message['From']
print 'Date:', email_message['Date']
print 'Subject:', email_message['Subject']
print '*'*30, 'MESSAGE', '*'*30
maintype = email_message.get_content_maintype()
#print maintype

if maintype == 'multipart':
    for part in email_message.get_payload():
            if part.get_content_maintype() == 'text':
                print part.get_payload()
elif maintype == 'text':
    print email_message.get_payload()
print '*'*69
</code>```

Git link for the complete code: Email-parser

How to get rid of that HTML code and get only the plain text?

答: The body of the message is MIME-encoded - that's why it contains the text in both plaintext and HTML formats.  In order to get just the plaintext of the body, you first need to MIME-decode the message.  You can use python's email package to do the MIME-decoding.  Also, see this question for more information.</p>

Title: Parsing the HTML content in email

Body:
I'm trying to write a python script to read my emails.
I'm able to get most of the things properly like To, From, Subject.
But in the body, I get the text as well as it's HTML code too as shown below.

Below is the part of code that does the extraction of content from the email

email_message = email.message_from_string(raw_email)
print 'To:', email_message['To']
print 'Sent from:', email_message['From']
print 'Date:', email_message['Date']
print 'Subject:', email_message['Subject']
print '*'*30, 'MESSAGE', '*'*30
maintype = email_message.get_content_maintype()
#print maintype

if maintype == 'multipart':
    for part in email_message.get_payload():
            if part.get_content_maintype() == 'text':
                print part.get_payload()
elif maintype == 'text':
    print email_message.get_payload()
print '*'*69

Git link for the complete code: Email-parser

How to get rid of that HTML code and get only the plain text?


问:
SML operator and operand don't agree [tycon mismatch]
I check other questions on the same error but answers aren't helpful for my problem. For I see no type mis-match!

The error I get is

```<code>  Error: operator and operand don't agree [tycon mismatch]
  operator domain: ?.expr list * ?.env
  operand:         expr list * env
  in expression:
    evallist (exprs,ev)
</code>```

I do not know what is this question mark in type is for or what does it mean! What I can see is that aside from the question mark part, the types are pretty similar. So I really do not get it.

My function is pretty simple

```<code>fun evallist(nil, _) = nil
  | evallist (e::exprs, ev) = eval(e,ev):: evallist(exprs,ev)
</code>```

It recursively evaluate expressions in the environment and creates a list of the result.

It is invoked simply as

```<code>vals = evallist(exprs, ev)
</code>```

Where eval is an expression evaluation function of this type val eval = fn : expr * env -> expr.

Any explanation/ideas on what is the problem? How ?.expr list * ?.env is different than expr list * env?

Thanks you!

This is the minimal code that will reproduce the error.

Updated Code

```<code>datatype
   expr = var of string
    | num of int
    | appfun of expr * expr list

type env = (string * expr) list

fun eval (appfun (e, exprs), ev:env) = evallist(exprs, ev)

fun evallist(nil, _) = nil
  | evallist (e::exprs, ev) =
    let
        val e' = eval(e,ev)
    in
        e':: evallist(exprs,ev)
    end
</code>```

答:
Your evallist function returns a list, and so does eval.  I can get your example to compile if I add the missing and and use list concatenation @ instead of consing:

```<code>datatype
   expr = var of string
    | num of int
    | appfun of expr * expr list

type env = (string * expr) list

fun eval (appfun (e, exprs), ev:env) = evallist(exprs, ev)
and evallist(nil, _) = nil
  | evallist (e::exprs, ev) =
    let
        val e' = eval(e,ev)
    in
        e' @ evallist(exprs,ev)
    end
</code>```

But I must admit I have no idea if this is what you want because the example has been reduced too far.

Body:
I check other questions on the same error but answers aren't helpful for my problem. For I see no type mis-match!

The error I get is

  Error: operator and operand don't agree [tycon mismatch]
  operator domain: ?.expr list * ?.env
  operand:         expr list * env
  in expression:
    evallist (exprs,ev)

I do not know what is this question mark in type is for or what does it mean! What I can see is that aside from the question mark part, the types are pretty similar. So I really do not get it.

My function is pretty simple

fun evallist(nil, _) = nil
  | evallist (e::exprs, ev) = eval(e,ev):: evallist(exprs,ev)

It recursively evaluate expressions in the environment and creates a list of the result.

It is invoked simply as

vals = evallist(exprs, ev)

Where eval is an expression evaluation function of this type val eval = fn : expr * env -> expr.

Any explanation/ideas on what is the problem? How ?.expr list * ?.env is different than expr list * env?

Thanks you!

This is the minimal code that will reproduce the error.

Updated Code

datatype
   expr = var of string
    | num of int
    | appfun of expr * expr list

type env = (string * expr) list

fun eval (appfun (e, exprs), ev:env) = evallist(exprs, ev)

fun evallist(nil, _) = nil
  | evallist (e::exprs, ev) =
    let
        val e' = eval(e,ev)
    in
        e':: evallist(exprs,ev)
    end

Body:
Your evallist function returns a list, and so does eval.  I can get your example to compile if I add the missing and and use list concatenation @ instead of consing:

datatype
   expr = var of string
    | num of int
    | appfun of expr * expr list

type env = (string * expr) list

fun eval (appfun (e, exprs), ev:env) = evallist(exprs, ev)
and evallist(nil, _) = nil
  | evallist (e::exprs, ev) =
    let
        val e' = eval(e,ev)
    in
        e' @ evallist(exprs,ev)
    end

But I must admit I have no idea if this is what you want because the example has been reduced too far.


问:
Losing Aria/accessibility when converting from HTML to PDF
I am using ABCpdf to generate a collection of PDFs from HTML markup, and am struggling with making it fully accessible.

The HTML pages include several graphs which are created by CSS, and which are completely ignored by the screenreader.

I have tried using aria-label to give a written explanation of the graphs, but it is lost in the conversion. I have tried configuring the Gecko engine within ABCpdf in numerous ways, including scaling back security options, altering markup options, and adding special tags to explicitly include an element. The PDF is tagged and is rated as fully accessible by our evaluation program.

I haven't been able to find a way to include "hidden" text in the PDF for the purpose of screenreaders. Any help is appreciated!

EDIT: Due to security concerns, I am unable to display the actual data behind the graphs. Manual steps are also not an option due to the sheer number of generated PDFs, and a short timeline.

答:
HTML-to-PDF conversion utilities are usually pretty basic and typically don't handle complex CSS very well at all. You may be better off taking a screen capture and then using alt-text to describe the intent of the graph. Sometimes the simplest approach is the most reliable.

Another way of approaching the issue would be to present the complete data set to users via a data table. That way, they can "see" everything contained in the graph, and it won't matter if the graph itself is inaccessible. If placing a giant data table in the middle of your document doesn't fit with your formatting, you can also include the data set in an appendix with a note or hyperlink in the text directing readers where they can go to access the entirety of information.


问:
Laravel Queues - how to assign specific number of workers to different queues
I've set up Laravel (5.5) queuing with Beanstalkd, and I'm using Supervisor. Laravel docs mention the following:

By pushing jobs to different queues, you may "categorize" your queued jobs and even prioritize how many workers you assign to various queues.

but it's never mentioned how to do that. If I have 2 queues on my beanstalkd connection, and I do the following:

```<code>php artisan queue:work beanstalkd --queue=high,low
</code>```

That will always process ALL of the jobs from high before it processes anything from low, if I'm understanding the docs correctly:

To start a worker that verifies that all of the high queue jobs are processed before continuing to any jobs on the low queue, pass a comma-delimited list of queue names to the work command

Let's say my queues are called apprequests and emails. How would I go about adding 1 dedicated worker for emails queue which won't care about the apprequests queue, and then 4 workers for the apprequests queue?

Here's my Supervisor laravel_worker.conf config:

```<code>[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/my_app/artisan queue:work beanstalkd --queue=apprequests --timeout=330
autostart=true
autorestart=true
user=root
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/my_app/worker.log
</code>```

Am I right to assume that I can just add another Supevisor config, for example laravel_email_worker.conf, with this command - command=php /var/www/my_app/artisan queue:work beanstalkd --queue=emails --timeout=30 and set numprocs to 1, and that should dedicate 1 worker to my emails queue which will process jobs from that queue regardless of the apprequests queue, or am I going all wrong about this?

答:
Yes, you can do as you wrote. You can set up one process that will look at email queue jobs and 4 processed that will look at apprequests queue.

But you might be also interested in Laravel Horizon that uses Redis as queue driver and can be set up to auto balance queue to increase number of workers for certain queues depending on current load.

Body:
I've set up Laravel (5.5) queuing with Beanstalkd, and I'm using Supervisor. Laravel docs mention the following:

By pushing jobs to different queues, you may "categorize" your queued jobs and even prioritize how many workers you assign to various queues.

but it's never mentioned how to do that. If I have 2 queues on my beanstalkd connection, and I do the following:

php artisan queue:work beanstalkd --queue=high,low

That will always process ALL of the jobs from high before it processes anything from low, if I'm understanding the docs correctly:

To start a worker that verifies that all of the high queue jobs are processed before continuing to any jobs on the low queue, pass a comma-delimited list of queue names to the work command

Let's say my queues are called apprequests and emails. How would I go about adding 1 dedicated worker for emails queue which won't care about the apprequests queue, and then 4 workers for the apprequests queue?

Here's my Supervisor laravel_worker.conf config:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/my_app/artisan queue:work beanstalkd --queue=apprequests --timeout=330
autostart=true
autorestart=true
user=root
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/my_app/worker.log

Am I right to assume that I can just add another Supevisor config, for example laravel_email_worker.conf, with this command - command=php /var/www/my_app/artisan queue:work beanstalkd --queue=emails --timeout=30 and set numprocs to 1, and that should dedicate 1 worker to my emails queue which will process jobs from that queue regardless of the apprequests queue, or am I going all wrong about this?


问:
React: Axios Network Error
This is my first time using axios and I have encountered an error.

```<code>  axios.get(
    `http://someurl.com/page1?param1=1&param2=${param2_id}`
  )
  .then(function(response) {
    alert();
  })
  .catch(function(error) {
    console.log(error);
  });
</code>```

With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn't call the callback, but instead it caught an error.

Error: Network Error
  Stack trace:
  createError@http://localhost:3000/static/js/bundle.js:2188:15
  handleError@http://localhost:3000/static/js/bundle.js:1717:14

答:
If Creating an API Using NodeJS

Your Express app needs to use CORS (Cross-Origin Resource Sharing). Add the following to your server file:

// This should already be declared in your API file
var app = express();

// ADD THIS
var cors = require('cors');
app.use(cors());
```

For fuller understanding of CORS, please read the Mozilla Documentation on CORS.

Title: React: Axios Network Error

Body:
This is my first time using axios and I have encountered an error.

  axios.get(
    `http://someurl.com/page1?param1=1&param2=${param2_id}`
  )
  .then(function(response) {
    alert();
  })
  .catch(function(error) {
    console.log(error);
  });

With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn't call the callback, but instead it caught an error.

Error: Network Error
  Stack trace:
  createError@http://localhost:3000/static/js/bundle.js:2188:15
  handleError@http://localhost:3000/static/js/bundle.js:1717:14

Body:
If Creating an API Using NodeJS

Your Express app needs to use CORS (Cross-Origin Resource Sharing). Add the following to your server file:

// This should already be declared in your API file
var app = express();

// ADD THIS
var cors = require('cors');
app.use(cors());

For fuller understanding of CORS, please read the Mozilla Documentation on CORS.


问:
'foo.bar.com.s3.amazonaws.com' doesn't match either of '*.s3.amazonaws.com', 's3.amazonaws.com'
I'm using django, and things like imgs I store at s3 (for this I'm using boto), but recently I got this error:

'foo.bar.com.s3.amazonaws.com' doesn't match either of
  '*.s3.amazonaws.com', 's3.amazonaws.com'

I'm searching for a possible solution for about two days, but the unique things that is suggested is to change boto's source code, however I can't do this on production.

Edit: Using Django 1.58, Boto 2.38.0

Any help would be appreciated.
Thx in advance.

答:
I had the same error when I moved from python3.4 to python3.5 (boto version remained the same).

The problem was solved by moving from boto to boto3 package.

Example:

```<code>import boto3
s3_client = boto3.client("s3", aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key)
body = open(local_filename, 'rb').read()
resp = s3_client.put_object(ACL="private", Body=body, Bucket=your_bucket_name, Key=path_to_the_file_inside_the_bucket)
if resp["ResponseMetadata"]["HTTPStatusCode"] != 200:
        raise Exception("Something went wrong...")
</code>```

Body:
I had the same error when I moved from python3.4 to python3.5 (boto version remained the same).

The problem was solved by moving from boto to boto3 package.

Example:

import boto3
s3_client = boto3.client("s3", aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key)
body = open(local_filename, 'rb').read()
resp = s3_client.put_object(ACL="private", Body=body, Bucket=your_bucket_name, Key=path_to_the_file_inside_the_bucket)
if resp["ResponseMetadata"]["HTTPStatusCode"] != 200:
        raise Exception("Something went wrong...")


问:
How to make dynamic main page content in WPF

I want to make change main panel content when I choice action in menu button.
Like main content page, setting page, content page on Main panel (in code used grid x:Name="main_~~~)
It for use just can make 3 and control visibility??
or Can use include like xml at Android and change include target??
( ex > includelayout="@layout/app_bar_main")

Mainwindow.xaml

```<code><Window x:Class="M_C.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
        xmlns:local="clr-namespace:M_C"
        mc:Ignorable="d"
        Title="MainWindow"
        Width="1024" Height="768"
        WindowStyle="None"
        WindowState="Maximized"
        WindowStartupLocation="CenterScreen">
    <Grid x:Name="wide_Out" Background="#000000">
        <Viewbox Stretch="Uniform">
            <Grid Width="1024" Height="768" VerticalAlignment="Top">
                <DockPanel x:Name="L_black" HorizontalAlignment="Left"
Height="768" LastChildFill="False" VerticalAlignment="Top" Width="62"
Background="#FF242424">
                    <Button Margin="15,8,0,0" Height="40"
VerticalAlignment="Top" Width="30"/>
                </DockPanel>
                <DockPanel x:Name="T_blue" HorizontalAlignment="Left"
Height="84" LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top"
Width="968" Background="#FF248BC7">
                    <TextBlock Margin="200,5,200,0" Height="70"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="554"/>
                </DockPanel>
                <DockPanel x:Name="L_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="62,83,0,0"
VerticalAlignment="Top" Width="82" Background="#FF248BC7"/>
                <DockPanel x:Name="R_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="940,83,0,0"
Background="#FF248BC7" Width="84"/>
                <DockPanel x:Name="B_blue" HorizontalAlignment="Left"
Height="90" LastChildFill="False" Margin="143,678,0,0"
VerticalAlignment="Top" Width="799" Background="#FF248BC7">
                    <Image Margin="250,15,250,15" Height="70"
VerticalAlignment="Top" Width="290" />
                </DockPanel>
                <!--<DockPanel x:Name="main_content_panel"
HorizontalAlignment="Left" Height="594" LastChildFill="False"
Margin="144,84,0,0" VerticalAlignment="Top" Width="790">-->
                <Grid x:Name="main_con_body" Margin="143,82,84,88"
Width="798" Height="594" Background="#ffffff">
                </Grid>
            <!--</DockPanel>-->
         </Grid>
     </Viewbox>
   </Grid>
</Window>
</code>```

答:
MVVM Approach

Make main_con_body be a ContentControl

Make Window's DataContext a viewmodel

Bind main_con_body's Content property to a viewmodel property of the data context

Define different DataTemplates for the various types of viewmodels that might be present

Body:
I want to make change main panel content when I choice action in menu button.
Like main content page, setting page, content page on Main panel (in code used grid x:Name="main_~~~)
It for use just can make 3 and control visibility??
or Can use include like xml at Android and change include target??
( ex > includelayout="@layout/app_bar_main")

Mainwindow.xaml

<Window x:Class="M_C.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
        xmlns:local="clr-namespace:M_C"
        mc:Ignorable="d"
        Title="MainWindow"
        Width="1024" Height="768"
        WindowStyle="None"
        WindowState="Maximized"
        WindowStartupLocation="CenterScreen">
    <Grid x:Name="wide_Out" Background="#000000">
        <Viewbox Stretch="Uniform">
            <Grid Width="1024" Height="768" VerticalAlignment="Top">
                <DockPanel x:Name="L_black" HorizontalAlignment="Left"
Height="768" LastChildFill="False" VerticalAlignment="Top" Width="62"
Background="#FF242424">
                    <Button Margin="15,8,0,0" Height="40"
VerticalAlignment="Top" Width="30"/>
                </DockPanel>
                <DockPanel x:Name="T_blue" HorizontalAlignment="Left"
Height="84" LastChildFill="False" Margin="62,0,0,0" VerticalAlignment="Top"
Width="968" Background="#FF248BC7">
                    <TextBlock Margin="200,5,200,0" Height="70"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="554"/>
                </DockPanel>
                <DockPanel x:Name="L_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="62,83,0,0"
VerticalAlignment="Top" Width="82" Background="#FF248BC7"/>
                <DockPanel x:Name="R_blue" HorizontalAlignment="Left"
Height="685" LastChildFill="False" Margin="940,83,0,0"
Background="#FF248BC7" Width="84"/>
                <DockPanel x:Name="B_blue" HorizontalAlignment="Left"
Height="90" LastChildFill="False" Margin="143,678,0,0"
VerticalAlignment="Top" Width="799" Background="#FF248BC7">
                    <Image Margin="250,15,250,15" Height="70"
VerticalAlignment="Top" Width="290" />
                </DockPanel>

                <Grid x:Name="main_con_body" Margin="143,82,84,88"
Width="798" Height="594" Background="#ffffff">
                </Grid>

         </Grid>
     </Viewbox>
   </Grid>
</Window>


问:
Only scroll UIScrollView, if the label in it is bigger than the View respectively
I have a little problem with the UIScrollView. It scrolls way to far. Is it possible to enable it only, if the label in it is bigger than the ScrollView?

Pictures (sorry, they are quite huge):

The Label, that is on the ScrollView, is in the ScrollView

答:
The easiest way this could be done is through the Storyboard (auto-layout enabled).

The main idea is to wrap your views (Labels) inside the UIScrollView with a UIView instead of directly inside the UIScrollView, then you need to set the constraints of the UIView to match the UIScrollView from all sides and add a height and width constraints equaling the UIScrollView. The height constraints priority should be lowered (lets say to 750 instead of 1000) so it will allow the scrollView to stretch when needed and the UILabel's button constraint should be set to greater or equal to allow the UILabel to take it's size and "push" the UIView when it needs to.

Last but not least, you need to lower the vertical content hugging priorityof the UIScrollView and the UIView to 249 and raise the vertical content compression resistance of the UILabel to 751.

Here is a full working example


问:
question number reordering
I have a list of question in my javascript file. Each question has a question number and question description and options. A question can be added anywhere in the list of questions. So if a question is added into the top of all questions, then i need to change the question numbers of all the below ones. How can achieve this. Can i use javascript for this?</p>

答:
I would suggest using an
 for each question, and let the page handle reflowing the numbers.

Otherwise you'll need to set a target number before inserting, and for each element in the list you'll check to see if it's number is greater than the target, and then if so increment the number by one.

```<code>var Target = //new number that I want the inserted question to be
foreach (element in list) {
  if (element.Number > Target) element.Number += 1;
}
list.add( //new question with # set to Target );
</code>```

Title: question number reordering

Body:
I would suggest using an <ol> for each question, and let the page handle reflowing the numbers.

Otherwise you'll need to set a target number before inserting, and for each element in the list you'll check to see if it's number is greater than the target, and then if so increment the number by one.

var Target = //new number that I want the inserted question to be
foreach (element in list) {
  if (element.Number > Target) element.Number += 1;
}
list.add( //new question with # set to Target );


问:
long wrapped flex item pushing others down
I've got 3 divs of different lengths in a flex box. Each div is 47% width. I am using flex wrap to have them wrap. The longest div is second in the order and pushes the third div all the way down to where it ends. Is there anyway to have the third div come right up under the first div.

CodePen

HTML

```<code><div class="flex-box">
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>
</div>
</code>```

CSS

```<code>.flex-box{
  display: flex;
  background: black;
  flex-wrap: wrap;
  width: 500px;
  justify-content: space-between;
  align-items: flex-start;

}
.flex-item{
  width: 47%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}
</code>```

答:
Rearrange the class="flex-item" in the below manner.

```<code><div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div> //Longest div container
</code>```

And then just give flex-direction:column to the container.
and not to forget to give max-height:(Anything less than your container height) to your container.

.flex-box {
  display: flex;
  flex-direction: column;
  background: black;
  flex-wrap: wrap;
  width: 500px;
  max-height: 520px;
  justify-content: space-between;
}

.flex-item {
  width: 47%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-box">
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>

  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
</div></code>```

Body:
I've got 3 divs of different lengths in a flex box. Each div is 47% width. I am using flex wrap to have them wrap. The longest div is second in the order and pushes the third div all the way down to where it ends. Is there anyway to have the third div come right up under the first div.

CodePen

HTML

CSS

.flex-box{
  display: flex;
  background: black;
  flex-wrap: wrap;
  width: 500px;
  justify-content: space-between;
  align-items: flex-start;

}
.flex-item{
  width: 47%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}

Body:
Rearrange the class="flex-item" in the below manner.

<div class="flex-item"></div>
<div class="flex-item"></div>
<div class="flex-item"></div> //Longest div container

And then just give flex-direction:column to the container.
and not to forget to give max-height:(Anything less than your container height) to your container.

.flex-box {
  display: flex;
  flex-direction: column;
  background: black;
  flex-wrap: wrap;
  width: 500px;
  max-height: 520px;
  justify-content: space-between;
}

.flex-item {
  width: 47%;
  background: red;
  border: 1px solid white;
  margin-bottom: 10px;
}

<div class="flex-box">
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>

  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
    </ul>
  </div>
  <div class="flex-item">
    <ul>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>
</div>


问:
Unable to install opencpu through CRAN
I have updated to Rstudio 1.1.383 (for Ubuntu 16.04 Xenial AMD64) and R 3.4.2.
Am trying to install opencpu package to test standalone R-code before pushing to the cloudserver version of opencpu, but without any luck. I am following the instructions from: OpenCPU instructions

trying URL 'http://cran.rstudio.com/src/contrib/opencpu_2.0.5.tar.gz' Content
    type 'application/x-gzip' length 372977 bytes (364 KB)
    ================================================== downloaded 364 KB

installing source package ‘opencpu’ ...
  ** package ‘opencpu’ successfully unpacked and MD5 sums checked
  ** R
  ** data
  *** moving datasets to lazyload DB
  ** inst
  ** preparing package for lazy loading Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :

  namespace ‘evaluate’ 0.10 is being loaded, but >= 0.10.1 is required
  ERROR: lazy loading failed for package ‘opencpu’

removing ‘/home/vmpdc/R/x86_64-pc-linux-gnu-library/3.4/opencpu’ Warning in install.packages :   installation of package ‘opencpu’ had
  non-zero exit status

Have tried using:

```<code>install.packages("opencpu",repos="http://cran.rstudio.com/")
</code>```

and

```<code>install.packages("opencpu",repos="http://cran.cnr.Berkeley.edu/")
</code>```

but no difference.

Not sure if this has any effect, but have installed the cloud server version of the opencpu on the same ubuntu box (which is under apache2).

I was able to follow the instructions from hereHow to install OpenCPU, which uses the github link (though did get an error for

configuration failed for package protolite

protobuf-compiler is not installed in my system for R3.4.2)

Not sure what to make of the namespace 'evaluate' error, though.

答:
It says the evaluate package is outdated. Try this:

```<code>update.packages(ask = FALSE)
</code>```

The opencpu package requires the latest version of the evaluate package.

Title: Unable to install opencpu through CRAN

Body:
I have updated to Rstudio 1.1.383 (for Ubuntu 16.04 Xenial AMD64) and R 3.4.2.
Am trying to install opencpu package to test standalone R-code before pushing to the cloudserver version of opencpu, but without any luck. I am following the instructions from: OpenCPU instructions

trying URL 'http://cran.rstudio.com/src/contrib/opencpu_2.0.5.tar.gz' Content
    type 'application/x-gzip' length 372977 bytes (364 KB)
    ================================================== downloaded 364 KB

installing source package ‘opencpu’ ...
  ** package ‘opencpu’ successfully unpacked and MD5 sums checked
  ** R
  ** data
  *** moving datasets to lazyload DB
  ** inst
  ** preparing package for lazy loading Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :

  namespace ‘evaluate’ 0.10 is being loaded, but >= 0.10.1 is required
  ERROR: lazy loading failed for package ‘opencpu’

removing ‘/home/vmpdc/R/x86_64-pc-linux-gnu-library/3.4/opencpu’ Warning in install.packages :   installation of package ‘opencpu’ had
  non-zero exit status

Have tried using:

install.packages("opencpu",repos="http://cran.rstudio.com/")

and

install.packages("opencpu",repos="http://cran.cnr.Berkeley.edu/")

but no difference.

Not sure if this has any effect, but have installed the cloud server version of the opencpu on the same ubuntu box (which is under apache2).

I was able to follow the instructions from hereHow to install OpenCPU, which uses the github link (though did get an error for

configuration failed for package protolite

protobuf-compiler is not installed in my system for R3.4.2)

Not sure what to make of the namespace 'evaluate' error, though.

Body:
It says the evaluate package is outdated. Try this:

update.packages(ask = FALSE)

The opencpu package requires the latest version of the evaluate package.


问:
process.traceDeprecation not working in webpack.config
There's a message that logged out in my command line when I compiled my JS files that says:

(node:3276) DeprecationWarning: loaderUtils.parseQuery() received a
  non-string value which oblematic, see
  https://github.com/webpack/loader-utils/issues/56 parseQuery() will be
  replaced with getOptions() in the next major version of loader-utils.

So I added the process.traceDeprecation = true as they advised, but it threw an error. How should I add it properly in my webpack.config.js?

答:
Suppose you're at the same directory as node_modules.

Run node --trace-deprecation node_modules/webpack/bin/webpack

Finally I found a way to set trace-deprecation to true.
It looks like simply set
process.traceDeprecation = true
doesn't work for me. Maybe it's been overwritten somewhere else.


问:
mobx contenful simple api call
I have a basic react app (CRA) with mobx and I simply would like to get all the entries of a contentful space.

with a simple store I can see my entries in the react console but I can't find a way to display it in my component.

```<code>class ProjetsStore {

@observable projets = {}

@action fetchAll(){
window.fetch(`${API_BASE_URL}/spaces/${API_SPACE_ID}/entries?
access_token=${API_KEY}&content_type=projet`)
.then(res => res.json())
.then(prj => this.projets = prj)
</code>```

The component is quite basic actually but whatever I try, I can't find a way to simply display anything even if everything is present in this.props.projetsStore in react tool.

```<code>@inject(['projetsStore'])
@observer

class Projets extends Component {

componentDidMount() {
  this.props.projetsStore.fetchAll()
}

render() {
  return (
    <div>
       ...
    </div>
)
}
}
</code>```

If someone can point me to some direction or ressource to simply fetch data from an api with mobx and make it dispo as props via provider, that would be awesome.

Thanks.

答:
You need to wrap your top level component with a <Provider> from mobx-react package.

```<code><Provider projetsStore={projetsStore}>
    <Projets />
</Provider>
</code>```

Then inject using a string, not array.

```<code>@inject('projetsStore')
@observer
class Projets extends Component {

componentDidMount() {
    this.props.projetsStore.fetchAll()
  }
</code>```

Title: mobx contenful simple api call

Body:
I have a basic react app (CRA) with mobx and I simply would like to get all the entries of a contentful space.

with a simple store I can see my entries in the react console but I can't find a way to display it in my component.

class ProjetsStore {

@observable projets = {}

@action fetchAll(){
window.fetch(`${API_BASE_URL}/spaces/${API_SPACE_ID}/entries?
access_token=${API_KEY}&content_type=projet`)
.then(res => res.json())
.then(prj => this.projets = prj)

The component is quite basic actually but whatever I try, I can't find a way to simply display anything even if everything is present in this.props.projetsStore in react tool.

@inject(['projetsStore'])
@observer

class Projets extends Component {

componentDidMount() {
  this.props.projetsStore.fetchAll()
}

render() {
  return (

       ...

)
}
}

If someone can point me to some direction or ressource to simply fetch data from an api with mobx and make it dispo as props via provider, that would be awesome.

Thanks.

Body:
You need to wrap your top level component with a <Provider> from mobx-react package.

<Provider projetsStore={projetsStore}>
    <Projets />
</Provider>

Then inject using a string, not array.

@inject('projetsStore')
@observer
class Projets extends Component {

componentDidMount() {
    this.props.projetsStore.fetchAll()
  }


问:
WPF Datagrid Cell Text Wrapping
I have a datagrid that has a custom style so I can reuse this format throughout my application.  It has a custom column headerstyle, row style, etc.  I was able to get the text wrapping to work on the column header and data binds to it correctly.  When I tried to use the same technique on the cell the binding does not appear to be working but the wrap does.  I have read the following posts but it looks like I'm required to set the style each time after I place the datagrid.  Can it not be done in a resource dictionary or am I applying the wrapping in the wrong spot?

wpf DataGrid change wrapping on cells

WPF toolkit datagrid cell text wrapping

WPF DataGrid Cell Text Wrapping - set to NoWrap (False)

Here is the datagrid definition (trimmed):

```<code><Style x:Key="EmbedDG" TargetType="{x:Type DataGrid}" >
    <Setter Property="ColumnHeaderStyle" Value="{DynamicResource DGCH}" />
    <Setter Property="CellStyle" Value="{DynamicResource EmbedDGCE}" />
</Style>
</code>```

Here is the working DGCH style showing the text wrapping:

```<code><Style x:Key="DGCH" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{Binding}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Here is the cellstyle that does not work (Picture 1 with contenttemplate, 2 without):

```<code><Style x:Key="EmbedDGCE" TargetType="{x:Type DataGridCell}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{Binding}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

EDIT:

```<code><DataGrid Style="{DynamicResource EmbedDG}" ItemsSource="{Binding Tags}" >
      <DataGrid.Columns>
          <DataGridTextColumn Header="Tag Type" Binding="{Binding TagType}" Width="180" />
          <DataGridTextColumn Header="Tag Comments" Binding="{Binding Message}" Width="300"/>
      </DataGrid.Columns>
</DataGrid>
</code>```

答:
I'd get rid of the cell style and use template columns. </p>

```<code><DataGrid Style="{DynamicResource EmbedDG}" ItemsSource="{Binding Tags}" >
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Tag Type" Width="180">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock
                        Text="{Binding TagType}"
                        TextWrapping="Wrap"
                        />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="Tag Comments" Width="300">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock
                        Text="{Binding Message}"
                        TextWrapping="Wrap"
                        />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

<p>I suppose it's giving you the fully qualified class name because your cell template is trying to display an object in a TextBlock. I don't have time to play with it, but whatever the issue is in your code, the above should work. </p>

Title: WPF Datagrid Cell Text Wrapping

Body:
I have a datagrid that has a custom style so I can reuse this format throughout my application.  It has a custom column headerstyle, row style, etc.  I was able to get the text wrapping to work on the column header and data binds to it correctly.  When I tried to use the same technique on the cell the binding does not appear to be working but the wrap does.  I have read the following posts but it looks like I'm required to set the style each time after I place the datagrid.  Can it not be done in a resource dictionary or am I applying the wrapping in the wrong spot?

wpf DataGrid change wrapping on cells

WPF toolkit datagrid cell text wrapping

WPF DataGrid Cell Text Wrapping - set to NoWrap (False)

Here is the datagrid definition (trimmed):

Here is the working DGCH style showing the text wrapping:

Here is the cellstyle that does not work (Picture 1 with contenttemplate, 2 without):

EDIT:

<DataGrid Style="{DynamicResource EmbedDG}" ItemsSource="{Binding Tags}" >
      <DataGrid.Columns>
          <DataGridTextColumn Header="Tag Type" Binding="{Binding TagType}" Width="180" />
          <DataGridTextColumn Header="Tag Comments" Binding="{Binding Message}" Width="300"/>
      </DataGrid.Columns>
</DataGrid>

Body:
I'd get rid of the cell style and use template columns.

<DataGrid Style="{DynamicResource EmbedDG}" ItemsSource="{Binding Tags}" >
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Tag Type" Width="180">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock
                        Text="{Binding TagType}"
                        TextWrapping="Wrap"
                        />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="Tag Comments" Width="300">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock
                        Text="{Binding Message}"
                        TextWrapping="Wrap"
                        />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

I suppose it's giving you the fully qualified class name because your cell template is trying to display an object in a TextBlock. I don't have time to play with it, but whatever the issue is in your code, the above should work.


问:
Windows Azure - Microsoft.IdentityModel not found
I installed WIF runtime and SDK on my machine. I added Microsoft.IdentityModel.dll to my azure web application and locally everything is running great. I build simple web application which use Azure AppFabric Access control. I follow azure labs for that and as I told, local everything is great. When I published my web application to Azure, I'm getting following error :

Unable to find assembly 'Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

I get it after Appfabric Relaying part is going to return url, after sign in on identity provider. The weird thing is that I set Copy Local to TRUE, because that .dll is not part of Azure GAC. I tried to publish it again, but I received same error. I found few same problems on the internet but with no concrete solution. Does anybody here had something similar and probably have a working solution? Thank you in advance

答: Create a new environment variable called: _CSPACK_FORCE_NOENCRYPT_ set the value to true.Restart your visual studio.</p>


问:
Need to create ArrayList method that fills with a Scanner
I'm trying to create a method that takes input from a data file (double type) using scanner and fills the Arraylist(double). I have a scanner created in my main class. I'm not sure how to get this to work correctly, though I feel like I'm almost there.

This is my main and public class

```<code>import java.util.Scanner;
import java.util.*;
public class Prog11{

public static void main(String [] args){

    Scanner inFile = new Scanner(System.in);
    readArr(inFile);
}
</code>```

Here is my method

```<code>public static double[] readArr(Scanner inFile){

    ArrayList <Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        input.add(inFile.nextDouble());
    }

    return examList;

}
</code>```

here are the two errors left

```<code>./Prog11.java:33: error: cannot find symbol
            input.add(inFile.nextDouble());
            ^
  symbol:   variable input
  location: class Prog11

./Prog11.java:36: error: incompatible types: ArrayList<Double> cannot be
converted to double[]
return examList;
</code>```

答:
Thats because you dont return that was expected, if you said that you are going double[] and in the method you return an arrayList<Double> so you need to decide what are you retrurning.

```<code>public static ArrayList <Double> readArr(Scanner inFile){
ArrayList <Double> examList = new ArrayList<Double>();

while(inFile.hasNextDouble()){
     input.add(inFile.nextDouble());
 }

 return examList;

 }
</code>```

Body:
I'm trying to create a method that takes input from a data file (double type) using scanner and fills the Arraylist(double). I have a scanner created in my main class. I'm not sure how to get this to work correctly, though I feel like I'm almost there.

This is my main and public class

import java.util.Scanner;
import java.util.*;
public class Prog11{

public static void main(String [] args){

    Scanner inFile = new Scanner(System.in);
    readArr(inFile);
}

Here is my method

public static double[] readArr(Scanner inFile){

    ArrayList <Double> examList = new ArrayList<Double>();

    while(inFile.hasNextDouble()){
        input.add(inFile.nextDouble());
    }

    return examList;

}

here are the two errors left

./Prog11.java:33: error: cannot find symbol
            input.add(inFile.nextDouble());
            ^
  symbol:   variable input
  location: class Prog11

./Prog11.java:36: error: incompatible types: ArrayList<Double> cannot be
converted to double[]
return examList;

Body:
Thats because you dont return that was expected, if you said that you are going double[] and in the method you return an arrayList<Double> so you need to decide what are you retrurning.

public static ArrayList <Double> readArr(Scanner inFile){
ArrayList <Double> examList = new ArrayList<Double>();

while(inFile.hasNextDouble()){
     input.add(inFile.nextDouble());
 }

 return examList;

 }


问:
Google Script for Uploading File Not Working
I wrote a script for uploading files to my Google Drive using the Google Script. I deployed it as a WebApp but it's not working and I don't know why. The button just gets stuck on "Subiendo..." and never changes anything inside my Drive. I'm sure I gave the script all the permissions and I already tried to see what's happening on my own without any sucess. Can you maybe help me find what should I do? I post the code here:

Code.gs

```<code>function doGet() {
    return    HtmlService.createHtmlOutputFromFile('main').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function serverFunc(theForm) {
    try{
        var folder_name = "publicaciones";
        var folder,folders = DriveApp.getFoldersByName(folder_name);

        if(folders.hasNext()){
             folder = folders.next();
        }else{
             folder = DriveApp.createFolder(folder_name);
        }
        Logger.log("TheForm", theForm == null);
        var blob = theForm.theFile;
        Logger.log("Blob!", blob == null);
        var file = folder.createFile(blob);
        Logger.log("File:", file.getName());
        return "Archivo subido exitosamente: " + file.getUrl();

     } catch(error){
        Logger.log("error: ", error.toString());
        return error.toString();
  }
}
</code>```

** main.html **

```<code><div>
<form id="myForm">
   <input type="file" name="theFile">
   <input type="hidden" name="anExample">
   <br>
   <input type="button" value="Subir Archivo" onclick="this.value='Subiendo...';
                                                       google.script.run.withSuccessHandler(fileUploaded).serverFunc(this.parentNode);
                                                       return false;">
</form>
</div>
<div id="output">
</div>

<script>
    function fileUploaded(status) {
        document.getElementById('myForm').style.display = 'none';
        document.getElementById('output').innerHTML = status;
    }
</script>
</code>```

I'd appreaciate any help or pointers you can give me. Thanks a lot!

答:
Google has turned of NATIVE for SandBoxMode. It is now set to IFRAME only.
See here</p>

Body:
I wrote a script for uploading files to my Google Drive using the Google Script. I deployed it as a WebApp but it's not working and I don't know why. The button just gets stuck on "Subiendo..." and never changes anything inside my Drive. I'm sure I gave the script all the permissions and I already tried to see what's happening on my own without any sucess. Can you maybe help me find what should I do? I post the code here:

Code.gs

function doGet() {
    return    HtmlService.createHtmlOutputFromFile('main').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function serverFunc(theForm) {
    try{
        var folder_name = "publicaciones";
        var folder,folders = DriveApp.getFoldersByName(folder_name);

        if(folders.hasNext()){
             folder = folders.next();
        }else{
             folder = DriveApp.createFolder(folder_name);
        }
        Logger.log("TheForm", theForm == null);
        var blob = theForm.theFile;
        Logger.log("Blob!", blob == null);
        var file = folder.createFile(blob);
        Logger.log("File:", file.getName());
        return "Archivo subido exitosamente: " + file.getUrl();

     } catch(error){
        Logger.log("error: ", error.toString());
        return error.toString();
  }
}

** main.html **

<form id="myForm">
   <input type="file" name="theFile">
   <input type="hidden" name="anExample">

   <input type="button" value="Subir Archivo" onclick="this.value='Subiendo...';
                                                       google.script.run.withSuccessHandler(fileUploaded).serverFunc(this.parentNode);
                                                       return false;">
</form>

I'd appreaciate any help or pointers you can give me. Thanks a lot!


问:
Oracle select data by contiguous date blocks
I am using an Oracle database and I have a table that has 2 columns with data like so:

```<code>HASH | DATE
-----------------
abcd | 2017-11-01
abcd | 2017-11-02
abcd | 2017-11-03
wxyz | 2017-11-04
wxyz | 2017-11-05
abcd | 2017-11-06
wxyz | 2017-11-07
abcd | 2017-11-08
abcd | 2017-11-09
lmno | 2017-11-10
lmno | 2017-11-11
</code>```

I want to know the windows of time that each hash is seen. So like

```<code>hash | start      | end
------------------------------
abcd | 2017-11-01 | 2017-11-03
wxyz | 2017-11-04 | 2017-11-05
abcd | 2017-11-06 | 2017-11-06
wxyz | 2017-11-07 | 2017-11-07
abcd | 2017-11-08 | 2017-11-09
lmno | 2017-11-10 | 2017-11-11
</code>```

What I have so far is basically this:

```<code>SELECT HASH, MIN(DATE) ST, MAX(DATE) ED
FROM HASH_TABLE
GROUP BY HASH
ORDER BY 3 DESC
</code>```

And this almost works but it will give me like "abcd" as a start of 2017-11-01 and an end of 2017-11-09 which "hides" the fact that it switched in the middle.

Is there some way to group these results by contiguous date/time "blocks"?

答:
desc hash_table

hash   varchar2(4)

   date_  date

```<code>select hash, min(date_) start_, max(date_) end_
  from
    (
     select h.hash, h.date_, row_number() over (partition by hash order by date_) rn
       from hash_table h
    )
  group by hash, date_ - rn
  order by 2;
</code>```

Body:
I am using an Oracle database and I have a table that has 2 columns with data like so:

HASH | DATE
-----------------
abcd | 2017-11-01
abcd | 2017-11-02
abcd | 2017-11-03
wxyz | 2017-11-04
wxyz | 2017-11-05
abcd | 2017-11-06
wxyz | 2017-11-07
abcd | 2017-11-08
abcd | 2017-11-09
lmno | 2017-11-10
lmno | 2017-11-11

I want to know the windows of time that each hash is seen. So like

hash | start      | end
------------------------------
abcd | 2017-11-01 | 2017-11-03
wxyz | 2017-11-04 | 2017-11-05
abcd | 2017-11-06 | 2017-11-06
wxyz | 2017-11-07 | 2017-11-07
abcd | 2017-11-08 | 2017-11-09
lmno | 2017-11-10 | 2017-11-11

What I have so far is basically this:

SELECT HASH, MIN(DATE) ST, MAX(DATE) ED
FROM HASH_TABLE
GROUP BY HASH
ORDER BY 3 DESC

And this almost works but it will give me like "abcd" as a start of 2017-11-01 and an end of 2017-11-09 which "hides" the fact that it switched in the middle.

Is there some way to group these results by contiguous date/time "blocks"?

Body:
desc hash_table

hash   varchar2(4)

   date_  date

select hash, min(date_) start_, max(date_) end_
  from
    (
     select h.hash, h.date_, row_number() over (partition by hash order by date_) rn
       from hash_table h
    )
  group by hash, date_ - rn
  order by 2;


问:
How to integrate the AppInvite in Android?
I want to integrate the Invite Functionality where a user can send a link(which is different for different user) to another user and user clicks and get some rewards.

I have tried the Myntra App and send the invitation link to my friend but I can't understand that the link created is like - https://mynt.to/somrandomstring.

Now I know that in order the App to open one must define it in the Android Manifest and with the host and scheme should like

```<code><data android:host="mynt.to" android:scheme="http"/>
                <data android:host="mynt.to" android:scheme="https"/>
</code>```

But I dig in the Myntra App and found out that there is no declaration like this above in Manifest File. They have used host="myntra.com"

I cant understand how the app is able to open even if the host is different.

I want to know how to create the Custom App Link like Myntra does.

Also, PhonePe also does the same the link is https://phon.pe/somerandomstring and many other apps.

答: Check this out Firebase Invites and this Dynamic links probably easiest way.</p>

Body:
I want to integrate the Invite Functionality where a user can send a link(which is different for different user) to another user and user clicks and get some rewards.

I have tried the Myntra App and send the invitation link to my friend but I can't understand that the link created is like - https://mynt.to/somrandomstring.

Now I know that in order the App to open one must define it in the Android Manifest and with the host and scheme should like

<data android:host="mynt.to" android:scheme="http"/>
                <data android:host="mynt.to" android:scheme="https"/>

But I dig in the Myntra App and found out that there is no declaration like this above in Manifest File. They have used host="myntra.com"

I cant understand how the app is able to open even if the host is different.

I want to know how to create the Custom App Link like Myntra does.

Also, PhonePe also does the same the link is https://phon.pe/somerandomstring and many other apps.