问:
Android FirebaseException: Failed to bounce to type
I have created android chat application and when I want to open chat I get error application has stopped working and inside log I get exception:
'Firebase exception : failed to bounce to type'
 Why is this error happening?

```<code>public class Chat extends AppCompatActivity
{
    LinearLayout layout;
    RelativeLayout layout_2;
    ImageView sendButton;
    EditText messageArea;
    ScrollView scrollView;
    Firebase reference1, reference2;
    boolean timerProcessing = false;
    String date = "";
    String message;
    String userName;

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

        layout = (LinearLayout) findViewById(R.id.layout1);
        layout_2 = (RelativeLayout)findViewById(R.id.layout2);
        sendButton = (ImageView)findViewById(R.id.sendButton);
        messageArea = (EditText)findViewById(R.id.messageArea);
        scrollView = (ScrollView)findViewById(R.id.scrollView);

        Firebase.setAndroidContext(this);

        reference1 = new Firebase("https://zipa1x.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
        reference2 = new Firebase("https://zipa1x.firebaseio.com/messages/" + UserDetails.chatWith + "_" + UserDetails.username);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageText = messageArea.getText().toString();

                if(!messageText.equals("")){
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("message", messageText);
                    map.put("user", UserDetails.username);
                    reference1.push().setValue(map);
                    reference2.push().setValue(map);
                    messageArea.setText("");
                }
            }
        });

        reference1.addChildEventListener(new ChildEventListener()
        {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s)
            {
                    Map map = dataSnapshot.getValue(Map.class);
                    message = map.get("message").toString();
                    userName = map.get("user").toString();

                    if (userName.equals(UserDetails.username))
                    {
                        //addMessageBox("You:\n" + message, 1);
                        addMessageBox(message, 1);

                        //sendNotification(message,userName);
                    } else
                    {
                        //addMessageBox(UserDetails.chatWith + ":\n" + message, 2);
                        addMessageBox(message, 2);

                        //sendNotification(message,userName);
                    }
            }

            @Override
            public void onChildChanged(final DataSnapshot dataSnapshot, String s)
            {
                Bundle extras = getIntent().getExtras();
                if (extras != null)
                {
                    int value = extras.getInt("time");

                    final CountDownTimer timer = new CountDownTimer(value, 1)
                    {
                        public void onTick(long millisUntilFinished)
                        {
                        }

                        public void onFinish()
                        {
                            timerProcessing = false;

                            for (DataSnapshot child: dataSnapshot.getChildren())
                            {
                                dataSnapshot.getRef().removeValue();
                            }
                        }
                    };
                }
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });

        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    public void addMessageBox(String message, int type)
    {
        sendNotification(message);

        DateFormat df = new SimpleDateFormat("h:mm a");
        date = df.format(Calendar.getInstance().getTime());

        TextView textView1 = new TextView(Chat.this);
        textView1.setText(date);
        textView1.setTextSize(10);

        TextView textView = new TextView(Chat.this);
        textView.setText(message);

        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp2.weight = 1.0f;

        if(type == 1) {
            lp2.gravity = Gravity.RIGHT;
            textView.setBackgroundResource(R.drawable.left_bubble);
        }
        else{
            lp2.gravity = Gravity.LEFT;
            textView.setBackgroundResource(R.drawable.right_bubble);
        }
        textView.setLayoutParams(lp2);
        layout.addView(textView);

        textView1.setLayoutParams(lp2);
        layout.addView(textView1);

        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    private void sendNotification(String message)
    {
        Intent intent = new Intent(this,Chat.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                //.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(userName)
                .setContentText(message)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, builder.build());
    }
</code>```

Logcat:

```<code>    05-30 23:52:56.264 31908-31908/audiophileradio.example.com.audiophileradio
    E/AndroidRuntime: FATAL EXCEPTION: main Process: audiophileradio.example.com.audiophileradio, PID: 31908
                                                                                com.firebase.client.FirebaseException: Failed to bounce to type
    at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:185)
    at audiophileradio.example.com.audiophileradio.Chat$2.onChildAdded(Chat.java:99)
    at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:61)
    at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
    at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5476)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
    at dalvik.system.NativeStart.main(Native Method)

    Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [map type; class java.util.LinkedHashMap, [simple type, class java.lang.Object] -> [simple type, class java.lang.Object]] from String value; no single-String constructor/factory method
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:428)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:299)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:308)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
    at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
    at audiophileradio.example.com.audiophileradio.Chat$2.onChildAdded(Chat.java:99)
    at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:61)
    at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
    at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5476)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
    at dalvik.system.NativeStart.main(Native Method)
    android firebase
    shareeditflag
</code>```

https://postimg.org/image/3wn46dxzr/

https://postimg.org/image/5pq0upj6f/

```<code>06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: VFY: replacing opcode 0x5b at 0x005d
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: DexOpt: couldn't find field Landroid/app/Notification;.headsUpContentView
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio W/dalvikvm: VFY: unable to resolve instance field 20
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: VFY: replacing opcode 0x5b at 0x004c
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: DexOpt: couldn't find field Landroid/app/Notification;.headsUpContentView
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio I/dalvikvm: DexOpt: unable to optimize instance field ref 0x0014 at 0x54 in Landroid/support/v7/app/NotificationCompat;.addHeadsUpToBuilderLollipop
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: DexOpt: couldn't find field Landroid/app/Notification;.headsUpContentView
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio I/dalvikvm: DexOpt: unable to optimize instance field ref 0x0014 at 0x61 in Landroid/support/v7/app/NotificationCompat;.addHeadsUpToBuilderLollipop
06-07 00:23:47.699 8103-8103/audiophileradio.example.com.audiophileradio I/System.out: datasnaphot: DataSnapshot { key = -KlzVQr5A15Y6Is3qKCE, value = {message=b, user=} }
06-07 00:23:47.699 8103-8103/audiophileradio.example.com.audiophileradio E/datasnaphot:: DataSnapshot { key = -KlzVQr5A15Y6Is3qKCE, value = {message=b, user=} }
06-07 00:23:52.089 8103-8103/audiophileradio.example.com.audiophileradio I/System.out: datasnaphot: DataSnapshot { key = -KlzVRvdHnLr3MYweJ0x, value = {message=v, user=} }
06-07 00:23:52.089 8103-8103/audiophileradio.example.com.audiophileradio E/datasnaphot:: DataSnapshot { key = -KlzVRvdHnLr3MYweJ0x, value = {message=v, user=} }
</code>```

答:
Firebase guy gives a comprehensive explanation here to this kinda problems when casting JSON objects.

So i guess yours is with casting Map object types.

I didn't try but replacing below lines

```<code>Map map = dataSnapshot.getValue(Map.class);

message = map.get("message").toString();
userName = map.get("user").toString();
</code>```

with

```<code>Map<String, String> map = (Map<String, String>) dataSnapshot.getValue();

message = map.get("message");
userName = map.get("user");
</code>```

should work.

Body:
I have created android chat application and when I want to open chat I get error application has stopped working and inside log I get exception:
'Firebase exception : failed to bounce to type'
 Why is this error happening?

public class Chat extends AppCompatActivity
{
    LinearLayout layout;
    RelativeLayout layout_2;
    ImageView sendButton;
    EditText messageArea;
    ScrollView scrollView;
    Firebase reference1, reference2;
    boolean timerProcessing = false;
    String date = "";
    String message;
    String userName;

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

        layout = (LinearLayout) findViewById(R.id.layout1);
        layout_2 = (RelativeLayout)findViewById(R.id.layout2);
        sendButton = (ImageView)findViewById(R.id.sendButton);
        messageArea = (EditText)findViewById(R.id.messageArea);
        scrollView = (ScrollView)findViewById(R.id.scrollView);

        Firebase.setAndroidContext(this);

        reference1 = new Firebase("https://zipa1x.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
        reference2 = new Firebase("https://zipa1x.firebaseio.com/messages/" + UserDetails.chatWith + "_" + UserDetails.username);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageText = messageArea.getText().toString();

                if(!messageText.equals("")){
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("message", messageText);
                    map.put("user", UserDetails.username);
                    reference1.push().setValue(map);
                    reference2.push().setValue(map);
                    messageArea.setText("");
                }
            }
        });

        reference1.addChildEventListener(new ChildEventListener()
        {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s)
            {
                    Map map = dataSnapshot.getValue(Map.class);
                    message = map.get("message").toString();
                    userName = map.get("user").toString();

                    if (userName.equals(UserDetails.username))
                    {
                        //addMessageBox("You:\n" + message, 1);
                        addMessageBox(message, 1);

                        //sendNotification(message,userName);
                    } else
                    {
                        //addMessageBox(UserDetails.chatWith + ":\n" + message, 2);
                        addMessageBox(message, 2);

                        //sendNotification(message,userName);
                    }
            }

            @Override
            public void onChildChanged(final DataSnapshot dataSnapshot, String s)
            {
                Bundle extras = getIntent().getExtras();
                if (extras != null)
                {
                    int value = extras.getInt("time");

                    final CountDownTimer timer = new CountDownTimer(value, 1)
                    {
                        public void onTick(long millisUntilFinished)
                        {
                        }

                        public void onFinish()
                        {
                            timerProcessing = false;

                            for (DataSnapshot child: dataSnapshot.getChildren())
                            {
                                dataSnapshot.getRef().removeValue();
                            }
                        }
                    };
                }
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });

        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    public void addMessageBox(String message, int type)
    {
        sendNotification(message);

        DateFormat df = new SimpleDateFormat("h:mm a");
        date = df.format(Calendar.getInstance().getTime());

        TextView textView1 = new TextView(Chat.this);
        textView1.setText(date);
        textView1.setTextSize(10);

        TextView textView = new TextView(Chat.this);
        textView.setText(message);

        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp2.weight = 1.0f;

        if(type == 1) {
            lp2.gravity = Gravity.RIGHT;
            textView.setBackgroundResource(R.drawable.left_bubble);
        }
        else{
            lp2.gravity = Gravity.LEFT;
            textView.setBackgroundResource(R.drawable.right_bubble);
        }
        textView.setLayoutParams(lp2);
        layout.addView(textView);

        textView1.setLayoutParams(lp2);
        layout.addView(textView1);

        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    private void sendNotification(String message)
    {
        Intent intent = new Intent(this,Chat.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                //.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(userName)
                .setContentText(message)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, builder.build());
    }

Logcat:

    05-30 23:52:56.264 31908-31908/audiophileradio.example.com.audiophileradio
    E/AndroidRuntime: FATAL EXCEPTION: main Process: audiophileradio.example.com.audiophileradio, PID: 31908
                                                                                com.firebase.client.FirebaseException: Failed to bounce to type
    at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:185)
    at audiophileradio.example.com.audiophileradio.Chat$2.onChildAdded(Chat.java:99)
    at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:61)
    at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
    at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5476)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
    at dalvik.system.NativeStart.main(Native Method)

    Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [map type; class java.util.LinkedHashMap, [simple type, class java.lang.Object] -> [simple type, class java.lang.Object]] from String value; no single-String constructor/factory method
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:428)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:299)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:308)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
    at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
    at audiophileradio.example.com.audiophileradio.Chat$2.onChildAdded(Chat.java:99)
    at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:61)
    at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
    at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5476)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
    at dalvik.system.NativeStart.main(Native Method)
    android firebase
    shareeditflag

https://postimg.org/image/3wn46dxzr/

https://postimg.org/image/5pq0upj6f/

06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: VFY: replacing opcode 0x5b at 0x005d
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: DexOpt: couldn't find field Landroid/app/Notification;.headsUpContentView
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio W/dalvikvm: VFY: unable to resolve instance field 20
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: VFY: replacing opcode 0x5b at 0x004c
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: DexOpt: couldn't find field Landroid/app/Notification;.headsUpContentView
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio I/dalvikvm: DexOpt: unable to optimize instance field ref 0x0014 at 0x54 in Landroid/support/v7/app/NotificationCompat;.addHeadsUpToBuilderLollipop
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio D/dalvikvm: DexOpt: couldn't find field Landroid/app/Notification;.headsUpContentView
06-07 00:23:47.679 8103-8103/audiophileradio.example.com.audiophileradio I/dalvikvm: DexOpt: unable to optimize instance field ref 0x0014 at 0x61 in Landroid/support/v7/app/NotificationCompat;.addHeadsUpToBuilderLollipop
06-07 00:23:47.699 8103-8103/audiophileradio.example.com.audiophileradio I/System.out: datasnaphot: DataSnapshot { key = -KlzVQr5A15Y6Is3qKCE, value = {message=b, user=} }
06-07 00:23:47.699 8103-8103/audiophileradio.example.com.audiophileradio E/datasnaphot:: DataSnapshot { key = -KlzVQr5A15Y6Is3qKCE, value = {message=b, user=} }
06-07 00:23:52.089 8103-8103/audiophileradio.example.com.audiophileradio I/System.out: datasnaphot: DataSnapshot { key = -KlzVRvdHnLr3MYweJ0x, value = {message=v, user=} }
06-07 00:23:52.089 8103-8103/audiophileradio.example.com.audiophileradio E/datasnaphot:: DataSnapshot { key = -KlzVRvdHnLr3MYweJ0x, value = {message=v, user=} }

Body:
Firebase guy gives a comprehensive explanation here to this kinda problems when casting JSON objects.

So i guess yours is with casting Map object types.

I didn't try but replacing below lines

Map map = dataSnapshot.getValue(Map.class);

message = map.get("message").toString();
userName = map.get("user").toString();

with

Map<String, String> map = (Map<String, String>) dataSnapshot.getValue();

message = map.get("message");
userName = map.get("user");

should work.


来源: stackexchange

问:
Using Async/Await with Pickle
I am new to async/await, and I came across a bit of confusion. Should pickle be awaited somehow?

For example, say I have the following async class methods:

async def get(self, key):
    redis = await self.getRedis()
    data = await redis.get(key)
    if not data:
        return None

    return pickle.loads(data)

async def set(self, key, value, ttlInSeconds):
    pickled = pickle.dumps(value)

    redis = await self.getRedis()
    await redis.setex(key, pickled, ttlInSeconds)
```

If I'm serializing or unserializing a large object, won't the entire loop block on pickle? For practical purposes, with smaller objects, is this momentary blocking acceptable? Thanks!

答:
You should block on pickling because if another method in your class could then execute and modify value while set() is still processing pickle.dumps(), the pickled data will be corrupt.

This applies even if that object will definitely only ever have one instance at a time.

Btw in get(), you could put await for return pickle.loads(data) since you're not likely to modify data that hasn't been returned out of that method yet.

ContentLicense: CC BY-SA 3.0

Title: Using Async/Await with Pickle

Body:
I am new to async/await, and I came across a bit of confusion. Should pickle be awaited somehow?

For example, say I have the following async class methods:

async def get(self, key):
    redis = await self.getRedis()
    data = await redis.get(key)
    if not data:
        return None

    return pickle.loads(data)

async def set(self, key, value, ttlInSeconds):
    pickled = pickle.dumps(value)

    redis = await self.getRedis()
    await redis.setex(key, pickled, ttlInSeconds)

If I'm serializing or unserializing a large object, won't the entire loop block on pickle? For practical purposes, with smaller objects, is this momentary blocking acceptable? Thanks!


问:
Database Modeling: Shipping Rules
I'm working on an e-commerce type web application and need to somehow handle calculation of shipping costs. Some rules I've found:

Free shipping

Free shipping with minimum purchase

Free shipping within a certain geographic area

Flat rate shipping

Flat rate + set amount per product

Various rates depending on speed of shipping (shipped immediately and/or how soon it gets to customer)

Based on height, width, depth, weight + shipping distance

Based on rates of various shippers

... and so on.

Any suggestions how to tackle such a problem?

答: Create a framework where your eCommerce system accepts modules that define shipping rules (and interfaces and calculations, etc). Design it such that you expect these modules to be able to provide all those functions. Let the end users decide which modules to use based on their own needs, as which shipping rules to use is a business decision and not a technology one. </p>

ContentLicense: CC BY-SA 4.0

Title: Database Modeling: Shipping Rules

ContentLicense: CC BY-SA 2.5


问:
Error when read Column value from excel with java using POI
I need to read the excel file, so I can reference the column index by name, and I do like that :

```<code>package main;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ReadExcel {

public static void main(String[] args) {

    try {

        InputStream fs = new FileInputStream("/.../ListProducts.xls");
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Map<String, Integer> map = new HashMap<String,Integer>(); //Create map
        HSSFRow row = sheet.getRow(0); //Get first row
        //following is boilerplate from the java doc
        short minColIx = row.getFirstCellNum(); //get the first column index for a row
        short maxColIx = row.getLastCellNum(); //get the last column index for a row
        for(short colIx=minColIx; colIx<maxColIx; colIx++) { //loop from first to last index
        HSSFCell cell = row.getCell(colIx); //get the cell
        map.put(cell.getStringCellValue(),cell.getColumnIndex()); //add the cell contents (name of column) and cell index to the map
        }

        List<ReportRow> listOfDataFromReport = new ArrayList<ReportRow>();
        for(int x = 1; x<=sheet.getPhysicalNumberOfRows(); x++){
         ReportRow rr = new ReportRow();
         HSSFRow dataRow = sheet.getRow(x);

         int idxForColumn1 = map.get("Id");
         int idxForColumn2 = map.get("Name");
         int idxForColumn3 = map.get("Price");

         HSSFCell cell1 = dataRow.getCell(idxForColumn1);
         HSSFCell cell2 = dataRow.getCell(idxForColumn2);
         HSSFCell cell3 = dataRow.getCell(idxForColumn3);

         rr.setColumn1(cell1.getStringCellValue());
         rr.setColumn2(cell2.getStringCellValue());
         rr.setColumn3(cell3.getStringCellValue());

         listOfDataFromReport.add(rr);

        }

        for(int j = 0; j< listOfDataFromReport.size();j++){
               System.out.println("Column 1 Value: " +   listOfDataFromReport.get(j).getColumn1());
            //etc...
            }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}
</code>```

When I run the program, I get this in output :

```<code>null
</code>```

I have already the excel file in the correct destination and with the right name of column.

EDIT

When I add e.printStackTrace();, I get this:

```<code>java.lang.NullPointerException
at main.ReadExcel.main(ReadExcel.java:51)

null
</code>```

EDIT2

I notice that variables of setColumn1,setColumn2,... methods are double.

I do this :

```<code>rr.setColumn1(cell1.getNumericCellValue());
rr.setColumn2(cell2.getNumericCellValue());
rr.setColumn3(cell3.getNumericCellValue());
</code>```

I get the following error when I try to run the program to read data:

```<code> Exception in thread "main" java.lang.IllegalStateException: Cannot get
 a NUMERIC value from a STRING cell at
 org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:654)
 at org.apache.poi.hssf.usermodel.HSSFCell.getNumericCellValue(HSSFCell.java:679)
</code>```

答:
Well I got kinda different opinion than @maytham-ɯɐɥʇʎɐɯ. Assuming names of the columns are correct in your code, I think that this may be the problem:

for(int x = 1; x<=sheet.getPhysicalNumberOfRows(); x++){

Let's say number of physical rows is 3, so they are numbered 0, 1, 2 and you are iterating till 3, thus when you trying to get the cell later it throws the NullPointerException, because there is no such row.

Try doing x < sheet.getPhysicalNumberOfRows(); (less than, not less/equal than) in the for loop I mentioned earlier.

Body:
I need to read the excel file, so I can reference the column index by name, and I do like that :

package main;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ReadExcel {

public static void main(String[] args) {

    try {

        InputStream fs = new FileInputStream("/.../ListProducts.xls");
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Map<String, Integer> map = new HashMap<String,Integer>(); //Create map
        HSSFRow row = sheet.getRow(0); //Get first row
        //following is boilerplate from the java doc
        short minColIx = row.getFirstCellNum(); //get the first column index for a row
        short maxColIx = row.getLastCellNum(); //get the last column index for a row
        for(short colIx=minColIx; colIx<maxColIx; colIx++) { //loop from first to last index
        HSSFCell cell = row.getCell(colIx); //get the cell
        map.put(cell.getStringCellValue(),cell.getColumnIndex()); //add the cell contents (name of column) and cell index to the map
        }

        List<ReportRow> listOfDataFromReport = new ArrayList<ReportRow>();
        for(int x = 1; x<=sheet.getPhysicalNumberOfRows(); x++){
         ReportRow rr = new ReportRow();
         HSSFRow dataRow = sheet.getRow(x);

         int idxForColumn1 = map.get("Id");
         int idxForColumn2 = map.get("Name");
         int idxForColumn3 = map.get("Price");

         HSSFCell cell1 = dataRow.getCell(idxForColumn1);
         HSSFCell cell2 = dataRow.getCell(idxForColumn2);
         HSSFCell cell3 = dataRow.getCell(idxForColumn3);

         rr.setColumn1(cell1.getStringCellValue());
         rr.setColumn2(cell2.getStringCellValue());
         rr.setColumn3(cell3.getStringCellValue());

         listOfDataFromReport.add(rr);

        }

        for(int j = 0; j< listOfDataFromReport.size();j++){
               System.out.println("Column 1 Value: " +   listOfDataFromReport.get(j).getColumn1());
            //etc...
            }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

When I run the program, I get this in output :

null

I have already the excel file in the correct destination and with the right name of column.

EDIT

When I add e.printStackTrace();, I get this:

java.lang.NullPointerException
at main.ReadExcel.main(ReadExcel.java:51)

null

EDIT2

I notice that variables of setColumn1,setColumn2,... methods are double.

I do this :

rr.setColumn1(cell1.getNumericCellValue());
rr.setColumn2(cell2.getNumericCellValue());
rr.setColumn3(cell3.getNumericCellValue());

I get the following error when I try to run the program to read data:

 Exception in thread "main" java.lang.IllegalStateException: Cannot get
 a NUMERIC value from a STRING cell at
 org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:654)
 at org.apache.poi.hssf.usermodel.HSSFCell.getNumericCellValue(HSSFCell.java:679)


问:
git fetch works but checkout branch doesn't work
I'm trying to checkout a branch that I've just fetched from my upstream remote repo but it doesn't seem to work.

```<code>$ git fetch upstream
Fetching upstream
From github.com:group/repo
* [new branch]      feature-branch -> upstream/feature-branch

$ git checkout feature-branch
error: pathspec 'feature-branch' did not match any file(s) known to git.
</code>```

Am I doing something wrong?

答: When you run git checkout feature-branch git try to remove all unsaved changes in file named feature-branch. For checkout your branch use -b option like this git checkout -b feature-branch.

Body:
I'm trying to checkout a branch that I've just fetched from my upstream remote repo but it doesn't seem to work.

$ git fetch upstream
Fetching upstream
From github.com:group/repo
* [new branch]      feature-branch -> upstream/feature-branch

$ git checkout feature-branch
error: pathspec 'feature-branch' did not match any file(s) known to git.

Am I doing something wrong?


问:
npm install error: saveError: cannot install react native checkbox
I am currently building a cellphone application with react native. To create checkbox list, I was trying to install the component through npm.

```<code>npm install react-native-checkbox --save
</code>```

However, I got two errors and I had no idea how to solve them. I have tried to clean the cache or reinstall the node but they didn't solve the problem. Could some give me some suggestions? Would appreciate any help.

答:
It means there is no package.json in that location... Make sure you're in the right directory. You seem to be in your home directory.

To install and save a package you need to have a package.json, which there should already be one in your projects folder.

After navigating to the right folder, repeat your npm install and everything should be fine and dandy.

Body:
I am currently building a cellphone application with react native. To create checkbox list, I was trying to install the component through npm.

npm install react-native-checkbox --save

However, I got two errors and I had no idea how to solve them. I have tried to clean the cache or reinstall the node but they didn't solve the problem. Could some give me some suggestions? Would appreciate any help.


问:
How to deal with white spaces in osascript
I'm in need of your assistance on how to deal with white space in a path.

In my example below, I'm setting some variables in a Terminal bash shell and executing, "osascript" from command line, utilizing these variables to run ['do shell script'] & ['display dialog']. When I run these from command line, I'm getting different results. My ultimate goal here is to be able to execute ['do shell script'] and it execute the bash shell script based on the path. In this case, the path has spaces in it.

NOTE: The INSTALLER_PATH variable defined below is set like this because the path is generated from an Apple Script I wrote that basically takes a path [ with white spaces in it ] and combines that path with another variable. Because this path has spaces in the name, I'm using the [ to quoted form of ] setting that puts the path in quotes.

APPLE SCRIPT EXAMPLE:

```<code>set pathToApp to POSIX path of ((path to me) as text)
set dragonFrame to ("_DRAGONFRAME/")
set INSTALLER_PATH to quoted form of pathToApp & dragonFrame
display dialog INSTALLER_PATH
</code>```

GENERATES THIS PATH {notice the ticks}:

```<code>'/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/'_DRAGONFRAME/
</code>```

Instead of testing this through the Apple Script to find the exact syntax I would need, I figured it would be easier to test this from command line. This is exactly what I'm setting and executing from my Terminal command line. In the examples below, executing [ 'display dialog' ] works and [ 'do shell script' ] fails. I think if there's a way to enclose the entire path in double quotation marks, my problem would be solved although all attempts at getting the path enclosed in double quotation marks has failed:

```<code>%> INSTALLER_PATH='/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/'_DRAGONFRAME/

%> ADMIN_USER_PROC="_Python_PySide_QT_Installer/Scripts/AdminUserProcesses.sh"

%> osascript -e 'do shell script ("'"${INSTALLER_PATH}"'" & "'"${ADMIN_USER_PROC}"'")'
</code>```

GENERATES THIS ERROR:

```<code>0:217: execution error: sh: /Volumes/Free.Space/Shotgun: No such file or directory (127)
</code>```

```<code>%> osascript -e 'display dialog ("'"${INSTALLER_PATH}"'" & "'"${ADMIN_USER_PROC}"'")'
</code>```

GENERATES THIS PATH:

```<code>/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/_DRAGONFRAME/_Python_PySide_QT_Installer/Scripts/AdminUserProcesses.sh
</code>```

Thank you in advance for any help you can offer.

答:
I think you're looking for something similar to this syntax:

```<code>set dragonFrame to ("/_DRAGONFRAME/")
set INSTALLER_PATH to path of (pathToApp & dragonFrame)
</code>```

Result:

```<code>'/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/_DRAGONFRAME/'
</code>```

If you need double-quotes around the path you can use:

```<code>("\"" & pathToApp & dragonFrame & "\"")
</code>```

and get rid of the quoted form argument leaving you with:

```<code>set INSTALLER_PATH to ("\"" & pathToApp & dragonFrame & "\"")
</code>```

Body:
I'm in need of your assistance on how to deal with white space in a path.

In my example below, I'm setting some variables in a Terminal bash shell and executing, "osascript" from command line, utilizing these variables to run ['do shell script'] & ['display dialog']. When I run these from command line, I'm getting different results. My ultimate goal here is to be able to execute ['do shell script'] and it execute the bash shell script based on the path. In this case, the path has spaces in it.

NOTE: The INSTALLER_PATH variable defined below is set like this because the path is generated from an Apple Script I wrote that basically takes a path [ with white spaces in it ] and combines that path with another variable. Because this path has spaces in the name, I'm using the [ to quoted form of ] setting that puts the path in quotes.

APPLE SCRIPT EXAMPLE:

set pathToApp to POSIX path of ((path to me) as text)
set dragonFrame to ("_DRAGONFRAME/")
set INSTALLER_PATH to quoted form of pathToApp & dragonFrame
display dialog INSTALLER_PATH

GENERATES THIS PATH {notice the ticks}:

'/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/'_DRAGONFRAME/

Instead of testing this through the Apple Script to find the exact syntax I would need, I figured it would be easier to test this from command line. This is exactly what I'm setting and executing from my Terminal command line. In the examples below, executing [ 'display dialog' ] works and [ 'do shell script' ] fails. I think if there's a way to enclose the entire path in double quotation marks, my problem would be solved although all attempts at getting the path enclosed in double quotation marks has failed:

%> INSTALLER_PATH='/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/'_DRAGONFRAME/

%> ADMIN_USER_PROC="_Python_PySide_QT_Installer/Scripts/AdminUserProcesses.sh"

%> osascript -e 'do shell script ("'"${INSTALLER_PATH}"'" & "'"${ADMIN_USER_PROC}"'")'

GENERATES THIS ERROR:

0:217: execution error: sh: /Volumes/Free.Space/Shotgun: No such file or directory (127)

%> osascript -e 'display dialog ("'"${INSTALLER_PATH}"'" & "'"${ADMIN_USER_PROC}"'")'

GENERATES THIS PATH:

/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/_DRAGONFRAME/_Python_PySide_QT_Installer/Scripts/AdminUserProcesses.sh

Thank you in advance for any help you can offer.

Body:
I think you're looking for something similar to this syntax:

set dragonFrame to ("/_DRAGONFRAME/")
set INSTALLER_PATH to path of (pathToApp & dragonFrame)

Result:

'/Volumes/Free.Space/Shotgun Python Dragon Project 2017/DRAGONFRAME_SCRIPTS_MASTER_V1.02/Dragonframe_Scripts_Installer.app/_DRAGONFRAME/'

If you need double-quotes around the path you can use:

("\"" & pathToApp & dragonFrame & "\"")

and get rid of the quoted form argument leaving you with:

set INSTALLER_PATH to ("\"" & pathToApp & dragonFrame & "\"")


问:
Gradle and Android : pom configuration with multiple Maven artifacts publication
Working on an Android library with Gradle (v 1.7) as the building tool, I've used the maven plugin and configured the task uploadArchives to publish both release and debug version of the lib to the local maven repository.

The code below works ok :

```<code>// [...]
apply plugin: 'android-library'

// [...] nothing unusual

/*
 * Define name of the apk output file (build/apk/<outputFile>)
 */
    android.libraryVariants.all
    {
        variant ->
        def outputName = "MyModule-${android.defaultConfig.versionName}-${variant.baseName}.aar"
        variant.outputFile = new File("$buildDir/libs", outputName)
     }

/*
 * Publish to maven local repo (older style maven plugin)
 * Used while android plugin is not fixed regarding maven-publish plugin
 *
 * type command "gradle uploadArchives" to publish the module into the
 * local .m2 repository
 */
apply plugin: 'maven'

android.libraryVariants.all
{
    variant ->
    // add final apk to the 'archives' configuration
    project.artifacts
    {
        archives variant.outputFile
    }
}

def localRepoPath = "file://" +  new File(
    System.getProperty("user.home"), ".m2/repository").absolutePath

uploadArchives
{
    repositories.mavenDeployer
    {
        repository(url: localRepoPath)

        addFilter('debug') { artifact, file ->
            artifact.name.contains("debug")
        }
        addFilter('release') { artifact, file ->
            artifact.name.contains("release")
        }

        pom('debug').groupId = 'com.company'
        pom('release').groupId = 'com.company'
        pom('debug').artifactId = 'id'
        pom('release').artifactId = 'id'
        pom('debug').version = android.defaultConfig.versionName + "d"
        pom('release').version = android.defaultConfig.versionName
        pom.packaging = 'aar'
    }
}
uploadArchives.dependsOn(assemble)
</code>```

However, when trying to refactor the pom configuration :

```<code>uploadArchives
{
    repositories.mavenDeployer
    {
        repository(url: localRepoPath)

        addFilter('debug') { artifact, file ->
            artifact.name.contains("debug")
        }
        addFilter('release') { artifact, file ->
            artifact.name.contains("release")
        }

        pom.groupId = 'com.company'
        pom.artifactId = 'id'
        pom('debug').version = android.defaultConfig.versionName + "d"
        pom('release').version = android.defaultConfig.versionName
        pom.packaging = 'aar'
    }
}
</code>```

artifactId is expanded as the name of the output file, and groupId as the name of the root directory ; thus giving bad paths in the maven repo.

I'd like to know why is that, and maybe if there is a cleaner way to achieve what I need.

答:
As a reference, this is how we upload multiple APKs. It may not be exactly what you needed since we are uploading multiple APKs after APK splits, while you were trying to upload multiple APKs from different build types (debug & release). But in theory, they should be the same.</p>

```<code>//declare some Variables for later use
def projectName = "ProjectName"
def versionString = "1.0.0"
def baseVersionCode = 1

// Values based on https://developer.android.com/ndk/guides/abis.html#sa
ext.abiCodes = ['armeabi-v7a': 1,
                'arm64-v8a'  : 2,
                'x86'        : 3,
                'x86_64'     : 4]

// collect artifacts, important for the `uploadArchives` to work
artifacts {
  if (new File('app/build/outputs/apk').exists()) {
    new File('app/build/outputs/apk').eachFile() { file ->
      if (file.toString().contains("productionRelease")) {
        archives file: file
      }
    }
  }
}

uploadArchives {
  repositories {
    mavenDeployer {
      repository(url: "http://...")

      project.ext.abiCodes.values().each{ abiVersionCode ->
        def version = "${versionString}.${baseVersionCode + abiVersionCode}"
        addFilter(version) { artifact, file -> artifact.name.contains(version) }

        pom(version).artifactId = projectName.toLowerCase()
        pom(version).groupId = 'com.yourcompanyname'
        pom(version).version = version
      }
    }
  }
}

android {
  defaultPublishConfig "productionRelease"

  buildTypes {
      productionRelease {
          minifyEnabled false
          zipAlignEnabled true
          //...more Config like proguard or signing
      }
  }

  applicationVariants.all { variant ->
    variant.outputs.each { output ->
      def abiName = output.getFilter(com.android.build.OutputFile.ABI)
      def abiVersionCode = project.ext.abiCodes.get(abiName)
      output.versionCodeOverride = variant.versionCode + abiVersionCode
      output.versionNameOverride = "$versionString (${output.versionCodeOverride})"
      def apkName = "$projectName-${variant.name}-v${versionString}.${output.versionCodeOverride}.apk"
      output.outputFile = new File(output.outputFile.parent, apkName)
    }
  }
</code>```

Body:
Working on an Android library with Gradle (v 1.7) as the building tool, I've used the maven plugin and configured the task uploadArchives to publish both release and debug version of the lib to the local maven repository.

The code below works ok :

// [...]
apply plugin: 'android-library'

// [...] nothing unusual

/*
 * Define name of the apk output file (build/apk/<outputFile>)
 */
    android.libraryVariants.all
    {
        variant ->
        def outputName = "MyModule-${android.defaultConfig.versionName}-${variant.baseName}.aar"
        variant.outputFile = new File("$buildDir/libs", outputName)
     }

/*
 * Publish to maven local repo (older style maven plugin)
 * Used while android plugin is not fixed regarding maven-publish plugin
 *
 * type command "gradle uploadArchives" to publish the module into the
 * local .m2 repository
 */
apply plugin: 'maven'

android.libraryVariants.all
{
    variant ->
    // add final apk to the 'archives' configuration
    project.artifacts
    {
        archives variant.outputFile
    }
}

def localRepoPath = "file://" +  new File(
    System.getProperty("user.home"), ".m2/repository").absolutePath

uploadArchives
{
    repositories.mavenDeployer
    {
        repository(url: localRepoPath)

        addFilter('debug') { artifact, file ->
            artifact.name.contains("debug")
        }
        addFilter('release') { artifact, file ->
            artifact.name.contains("release")
        }

        pom('debug').groupId = 'com.company'
        pom('release').groupId = 'com.company'
        pom('debug').artifactId = 'id'
        pom('release').artifactId = 'id'
        pom('debug').version = android.defaultConfig.versionName + "d"
        pom('release').version = android.defaultConfig.versionName
        pom.packaging = 'aar'
    }
}
uploadArchives.dependsOn(assemble)

However, when trying to refactor the pom configuration :

uploadArchives
{
    repositories.mavenDeployer
    {
        repository(url: localRepoPath)

        addFilter('debug') { artifact, file ->
            artifact.name.contains("debug")
        }
        addFilter('release') { artifact, file ->
            artifact.name.contains("release")
        }

        pom.groupId = 'com.company'
        pom.artifactId = 'id'
        pom('debug').version = android.defaultConfig.versionName + "d"
        pom('release').version = android.defaultConfig.versionName
        pom.packaging = 'aar'
    }
}

artifactId is expanded as the name of the output file, and groupId as the name of the root directory ; thus giving bad paths in the maven repo.

I'd like to know why is that, and maybe if there is a cleaner way to achieve what I need.

Body:
As a reference, this is how we upload multiple APKs. It may not be exactly what you needed since we are uploading multiple APKs after APK splits, while you were trying to upload multiple APKs from different build types (debug & release). But in theory, they should be the same.

//declare some Variables for later use
def projectName = "ProjectName"
def versionString = "1.0.0"
def baseVersionCode = 1

// Values based on https://developer.android.com/ndk/guides/abis.html#sa
ext.abiCodes = ['armeabi-v7a': 1,
                'arm64-v8a'  : 2,
                'x86'        : 3,
                'x86_64'     : 4]

// collect artifacts, important for the `uploadArchives` to work
artifacts {
  if (new File('app/build/outputs/apk').exists()) {
    new File('app/build/outputs/apk').eachFile() { file ->
      if (file.toString().contains("productionRelease")) {
        archives file: file
      }
    }
  }
}

uploadArchives {
  repositories {
    mavenDeployer {
      repository(url: "http://...")

      project.ext.abiCodes.values().each{ abiVersionCode ->
        def version = "${versionString}.${baseVersionCode + abiVersionCode}"
        addFilter(version) { artifact, file -> artifact.name.contains(version) }

        pom(version).artifactId = projectName.toLowerCase()
        pom(version).groupId = 'com.yourcompanyname'
        pom(version).version = version
      }
    }
  }
}

android {
  defaultPublishConfig "productionRelease"

  buildTypes {
      productionRelease {
          minifyEnabled false
          zipAlignEnabled true
          //...more Config like proguard or signing
      }
  }

  applicationVariants.all { variant ->
    variant.outputs.each { output ->
      def abiName = output.getFilter(com.android.build.OutputFile.ABI)
      def abiVersionCode = project.ext.abiCodes.get(abiName)
      output.versionCodeOverride = variant.versionCode + abiVersionCode
      output.versionNameOverride = "$versionString (${output.versionCodeOverride})"
      def apkName = "$projectName-${variant.name}-v${versionString}.${output.versionCodeOverride}.apk"
      output.outputFile = new File(output.outputFile.parent, apkName)
    }
  }


问:
Angular 2 Material Datepicker Value
I want to use Angular Material Datepicker to get a date into my page.
I use this code, but cannot figure out how to access the selected value correctly.

```<code><md-input-container>
  <input mdInput [mdDatepicker]="myDatepicker">
  <button mdSuffix [mdDatepickerToggle]="myDatepicker"></button>
</md-input-container>
<md-datepicker #myDatepicker></md-datepicker>
</code>```

I tried the [value] field in input but how can I get the date to send it to my backend?
Thanks.

答: You can access the datepicker value by using ngModel. The ngModel needs to be in the input tag. See the Plunker demo.

Title: Angular 2 Material Datepicker Value

Body:
I want to use Angular Material Datepicker to get a date into my page.
I use this code, but cannot figure out how to access the selected value correctly.

<md-input-container>
  <input mdInput [mdDatepicker]="myDatepicker">
  <button mdSuffix [mdDatepickerToggle]="myDatepicker"></button>
</md-input-container>
<md-datepicker #myDatepicker></md-datepicker>

I tried the [value] field in input but how can I get the date to send it to my backend?
Thanks.


问:
Pass array from js for loop to highcharts series data
I've created an array (myData) from a for loop and stored it in a variable, however I'm unable to plot the data via highcharts.

I've added an array (arr) containing numbers (i.e not via the for loop) to test and it works when using this array.

Example in http://jsfiddle.net/o22uk7Lb/

HTML

```<code>myData<p id="demo"></p>
arr<p id="demo2"></p>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
</code>```

Javascript

```<code>var mp = 300;
var yp = (mp * 12);
var year = new Array(12);
var myData = [];
for (var i = 1; i <= year.length; i++){
    myData +=  (i * yp.toFixed(2)) + ",";
};
document.getElementById("demo").innerHTML = myData;

 var arr = [100,200,300,400,500];
 document.getElementById("demo2").innerHTML = arr;
 Highcharts.chart('container', {
    chart: {
        type: 'column'
    },

    plotOptions: {
        bar: {
            dataLabels: {
                enabled: true
            }
        }
    },
    series: [{
        data: myData
    },]
 })
</code>```

答:
Your for loop is not populating an array, it's creating a string.

Try this:

```<code>for (var i = 1; i <= year.length; i++){
    myData.push(i * yp.toFixed(2));
};
</code>```

Updated fiddle

Body:
I've created an array (myData) from a for loop and stored it in a variable, however I'm unable to plot the data via highcharts.

I've added an array (arr) containing numbers (i.e not via the for loop) to test and it works when using this array.

Example in http://jsfiddle.net/o22uk7Lb/

HTML

myData

arr

Javascript

var mp = 300;
var yp = (mp * 12);
var year = new Array(12);
var myData = [];
for (var i = 1; i <= year.length; i++){
    myData +=  (i * yp.toFixed(2)) + ",";
};
document.getElementById("demo").innerHTML = myData;

 var arr = [100,200,300,400,500];
 document.getElementById("demo2").innerHTML = arr;
 Highcharts.chart('container', {
    chart: {
        type: 'column'
    },

    plotOptions: {
        bar: {
            dataLabels: {
                enabled: true
            }
        }
    },
    series: [{
        data: myData
    },]
 })

Body:
Your for loop is not populating an array, it's creating a string.

Try this:

for (var i = 1; i <= year.length; i++){
    myData.push(i * yp.toFixed(2));
};

Updated fiddle


问:
What is the cleverest UI feature you have seen in a website?
What is the cleverest UI feature you have seen in a website?  Something that:

Made the user experience more intuitive

Added significantly to the usefulness of the app.

Added to the 'wow factor' of the application

or... anything else you consider important ;)

Could be also something standard, but particularly well implemented.

Please restrict this to standard web technologies (HTML, AJAX etc.), no Flash or plugins please!

Thank you

答: The new HTML5 interface of Grooveshark is excellent.</p>


问:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 14738 path $.nodes[3].node.image
I have a JSON output but when I want to read with Retrofit it I am receiving

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 14738 path
  $.nodes[3].node.image

and but I cannot solve it whatever I do. I don't know where I make mistake.

JSON output

```<code>{   "nodes": [
    {
      "node": {
        "body": "text",
        "category": "category",
        "created": "1495941856",
        "id": "2974",
        **"image": [
          {
            "alt": "",
            "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/05/calisma-atasesi_1.jpg",
            "title": "Fazil Arslan Düsseldorf"
          },
          {
            "alt": "",
            "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/05/calisma-atasesi_3.jpg",
            "title": "Türkiye'ye araç götürecek emeklilerin dikkatine! "
          },
          {
            "alt": "",
            "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/05/calisma-atasesi_belge_2.jpg",
            "title": "Türkiye'ye araç götürecek emeklilerin dikkatine! "
          }
        ],**
        "title": "Türkiye'ye araç götürecek emeklilerin dikkatine! ",
        "url": "http://www.muhabirce.de/2017-05-28/turkiyeye-arac-goturecek-emeklilerin-dikkatine"
      }
    },
    {
      "node": {
        "body": "text",
        "category": "category",
        "created": "1496544951",
        "id": "3002",
        **"image": {
          "alt": "",
          "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/06/mustafa_yeneroglu.jpg",
          "title": "Ak Parti İstanbul Milletvekili Mustafa Yeneroğlu "
        },**
        "title": "Köln'de iftar yemeğinde PKK eleştirisi",
        "url": "http://www.muhabirce.de/2017-06-04/kolnde-iftar-yemeginde-pkk-elestirisi"
      }
    },
    ...
</code>```

My Class are like

```<code>public class MainNode {
    public Nodes[] nodes;

    public Nodes[] getNodes() {
        return nodes;
    }

    public void setNodes(Nodes[] nodes) {
        this.nodes = nodes;
    }
}

public class Node {
    public String body;
    public String category;
    public String title;
    public String created;
    public Image[] image;
    public String url;

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }

    public Image[] getImage() {
        return image;
    }

    public void setImage(Image[] image) {
        this.image = image;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

public class Nodes {
    public Node node;

    public Node getNode() {
        return node;
    }

    public void setNode(Node node) {
        this.node = node;
    }
}

public class Image {
    private String src;

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }
}

interface NewsService {
    String BASE_URL = "url";

    @GET
    Call<MainNode> holderNode(@Url String url);
}
</code>```

答:
Your Node object contains an array of Image objects. In the second node of your JSON the image-node is a JSON-object instead of a JSON-array. GSON throws this exception because it is not possible to map it properly.

If you have created the API you should alter it, so it will always return an json-array, with zero objects, one object, or more objects.

A second solution is to create a custom TypeAdapter for GSON to automatically convert that one object into an Array. It is explained in the accepted answer of this question

Body:
I have a JSON output but when I want to read with Retrofit it I am receiving

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 14738 path
  $.nodes[3].node.image

and but I cannot solve it whatever I do. I don't know where I make mistake.

JSON output

{   "nodes": [
    {
      "node": {
        "body": "text",
        "category": "category",
        "created": "1495941856",
        "id": "2974",
        **"image": [
          {
            "alt": "",
            "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/05/calisma-atasesi_1.jpg",
            "title": "Fazil Arslan Düsseldorf"
          },
          {
            "alt": "",
            "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/05/calisma-atasesi_3.jpg",
            "title": "Türkiye'ye araç götürecek emeklilerin dikkatine! "
          },
          {
            "alt": "",
            "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/05/calisma-atasesi_belge_2.jpg",
            "title": "Türkiye'ye araç götürecek emeklilerin dikkatine! "
          }
        ],**
        "title": "Türkiye'ye araç götürecek emeklilerin dikkatine! ",
        "url": "http://www.muhabirce.de/2017-05-28/turkiyeye-arac-goturecek-emeklilerin-dikkatine"
      }
    },
    {
      "node": {
        "body": "text",
        "category": "category",
        "created": "1496544951",
        "id": "3002",
        **"image": {
          "alt": "",
          "src": "http://www.muhabirce.de/sites/default/files/images/news/2017/06/mustafa_yeneroglu.jpg",
          "title": "Ak Parti İstanbul Milletvekili Mustafa Yeneroğlu "
        },**
        "title": "Köln'de iftar yemeğinde PKK eleştirisi",
        "url": "http://www.muhabirce.de/2017-06-04/kolnde-iftar-yemeginde-pkk-elestirisi"
      }
    },
    ...

My Class are like

public class MainNode {
    public Nodes[] nodes;

    public Nodes[] getNodes() {
        return nodes;
    }

    public void setNodes(Nodes[] nodes) {
        this.nodes = nodes;
    }
}

public class Node {
    public String body;
    public String category;
    public String title;
    public String created;
    public Image[] image;
    public String url;

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }

    public Image[] getImage() {
        return image;
    }

    public void setImage(Image[] image) {
        this.image = image;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

public class Nodes {
    public Node node;

    public Node getNode() {
        return node;
    }

    public void setNode(Node node) {
        this.node = node;
    }
}

public class Image {
    private String src;

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }
}

interface NewsService {
    String BASE_URL = "url";

    @GET
    Call<MainNode> holderNode(@Url String url);
}


问:
I have a list of integers. I am performing some action on the items of list and then print the result in a file

There is a list t with some temperatures in it. If the temperature is
  greater than -273, then convert it to Fahrenheit and write the result
  in a separate text file named tmp.txt

Below is my code.

```<code>t=[10,-20,-289,100]
def writer(input):
    with open("tmp.txt","w+") as f:
        for i in t:
            if i>-273.15:
                f=i*9/5+32
                f.write(f)
        f.close()
print(writer(t))
</code>```

Traceback:

```<code>Traceback (most recent call last):

  File "lst_input.py", line 9, in <module>
    print(writer(t))
  File "lst_input.py", line 7, in writer
    f.write(f)
AttributeError: 'float' object has no attribute 'write'
</code>```

How to write the result to tmp.txt file?

答:
Print the value directly, don't save it in the variable called f, because you are reference to a float instead to the file, also convert it as string with str, and don't close it, I forget, and finally read it like this:</p>

```<code>t=[10,-20,-289,100]
def writer(input):
    with open("tmp.txt","w+") as f:
        for i in t:
            if i>-273.15:
                f.write(str(i*9/5+32))

text_file = open('tmp.txt', 'r')
file_contents = text_file.read()
print(file_contents)
</code>```

Body:
There is a list t with some temperatures in it. If the temperature is
  greater than -273, then convert it to Fahrenheit and write the result
  in a separate text file named tmp.txt

Below is my code.

t=[10,-20,-289,100]
def writer(input):
    with open("tmp.txt","w+") as f:
        for i in t:
            if i>-273.15:
                f=i*9/5+32
                f.write(f)
        f.close()
print(writer(t))

Traceback:

Traceback (most recent call last):

  File "lst_input.py", line 9, in <module>
    print(writer(t))
  File "lst_input.py", line 7, in writer
    f.write(f)
AttributeError: 'float' object has no attribute 'write'

How to write the result to tmp.txt file?

Body:
Print the value directly, don't save it in the variable called f, because you are reference to a float instead to the file, also convert it as string with str, and don't close it, I forget, and finally read it like this:

t=[10,-20,-289,100]
def writer(input):
    with open("tmp.txt","w+") as f:
        for i in t:
            if i>-273.15:
                f.write(str(i*9/5+32))

text_file = open('tmp.txt', 'r')
file_contents = text_file.read()
print(file_contents)


问:
Visual Studio never makes a new line when receiving from Arduino
I made a simple serial monitor using WinForms with C#, and it works completely fine except that data received all goes to the same line, even if they are not sent at the same time.

RXWindow is my textbox where I plan to read out the serial data it gives.

```<code>String RxString;
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) {
    RxString = serialPort1.ReadExisting();
    this.Invoke(new EventHandler(DisplayText));
}

private void DisplayText(object sender, EventArgs e) {
    RXWindow.AppendText(RxString);
}
</code>```

It always comes through like this (if I just send "testing" repeatedly).

What can I change so that it inserts newlines with all new data. Do I just need to adapt the Arduino code to send a newline character as well? I figured that since the Arduino IDE's serial monitor receives with newlines fine, that I wouldn't need to change anything either though.

答:
You could use:

```<code>RXWindow.AppendText(RxString + Environment.NewLine);
</code>```

or

```<code>RXWindow.AppendText(RxString + "\r\n");
</code>```

Body:
I made a simple serial monitor using WinForms with C#, and it works completely fine except that data received all goes to the same line, even if they are not sent at the same time.

RXWindow is my textbox where I plan to read out the serial data it gives.

String RxString;
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) {
    RxString = serialPort1.ReadExisting();
    this.Invoke(new EventHandler(DisplayText));
}

private void DisplayText(object sender, EventArgs e) {
    RXWindow.AppendText(RxString);
}

It always comes through like this (if I just send "testing" repeatedly).

What can I change so that it inserts newlines with all new data. Do I just need to adapt the Arduino code to send a newline character as well? I figured that since the Arduino IDE's serial monitor receives with newlines fine, that I wouldn't need to change anything either though.

Body:
You could use:

RXWindow.AppendText(RxString + Environment.NewLine);

or

RXWindow.AppendText(RxString + "\r\n");


问:
Cassandra CQL alternative to OR in WHERE clause
Here's the code I used to create the table:

```<code>CREATE TABLE test.packages (
     packageuuid timeuuid,
     ruserid text,
     suserid text,
     timestamp int,
     PRIMARY KEY (ruserid, suserid, packageuuid, timestamp)
);
</code>```

and then I create a materialized view:

```<code>CREATE MATERIALIZED VIEW test.packages_by_userid
    AS SELECT * FROM test.packages
    WHERE ruserid IS NOT NULL
       AND suserid IS NOT NULL
       AND TIMESTAMP IS NOT NULL
       AND packageuuid IS NOT NULL
    PRIMARY KEY (ruserid, suserid, timestamp, packageuuid)
    WITH CLUSTERING ORDER BY (packageuuid DESC);
</code>```

I want to be able to search for packages sent between two IDs

so I would need something like this:

```<code>SELECT * FROM test.packages_by_userid WHERE (ruserid = '1' AND suserid = '2' AND suserid = '1' AND ruserid = '2') AND timestamp > 1496601553;
</code>```

How would I accomplish something like this with CQL?

I've searched a bit but I can't figure it out.

I'm willing to change the structure of the table if it will make something like this possible.

If it's doable without a materialized view that would also be good.

答:
Use In Clause:

```<code>SELECT * FROM test.packages_by_userid WHERE ruserid IN ( '1', '2') AND suserid IN ( '1','2') AND timestamp > 1496601553;
</code>```

Note : Keep the in clause size smaller, Large in clause in the partition can cause GC pauses and heap pressure that leads to overall slower performance

In practical terms this means you’re waiting on this single coordinator node to give you a response, it’s keeping all those queries and their responses in the heap, and if one of those queries fails, or the coordinator fails, you have to retry the whole thing.

If the multiple partition in clause larger try to use separate query, for each partition (ruserid) with executeAsync.

```<code>SELECT * FROM test.packages_by_userid WHERE ruserid = '1' AND suserid IN ( '1','2') AND timestamp > 1496601553;
SELECT * FROM test.packages_by_userid WHERE ruserid = '2' AND suserid IN ( '1','2') AND timestamp > 1496601553;
</code>```

Learn More : https://lostechies.com/ryansvihla/2014/09/22/cassandra-query-patterns-not-using-the-in-query-for-multiple-partitions/

Body:
Here's the code I used to create the table:

CREATE TABLE test.packages (
     packageuuid timeuuid,
     ruserid text,
     suserid text,
     timestamp int,
     PRIMARY KEY (ruserid, suserid, packageuuid, timestamp)
);

and then I create a materialized view:

CREATE MATERIALIZED VIEW test.packages_by_userid
    AS SELECT * FROM test.packages
    WHERE ruserid IS NOT NULL
       AND suserid IS NOT NULL
       AND TIMESTAMP IS NOT NULL
       AND packageuuid IS NOT NULL
    PRIMARY KEY (ruserid, suserid, timestamp, packageuuid)
    WITH CLUSTERING ORDER BY (packageuuid DESC);

I want to be able to search for packages sent between two IDs

so I would need something like this:

SELECT * FROM test.packages_by_userid WHERE (ruserid = '1' AND suserid = '2' AND suserid = '1' AND ruserid = '2') AND timestamp > 1496601553;

How would I accomplish something like this with CQL?

I've searched a bit but I can't figure it out.

I'm willing to change the structure of the table if it will make something like this possible.

If it's doable without a materialized view that would also be good.

Body:
Use In Clause:

SELECT * FROM test.packages_by_userid WHERE ruserid IN ( '1', '2') AND suserid IN ( '1','2') AND timestamp > 1496601553;

Note : Keep the in clause size smaller, Large in clause in the partition can cause GC pauses and heap pressure that leads to overall slower performance

In practical terms this means you’re waiting on this single coordinator node to give you a response, it’s keeping all those queries and their responses in the heap, and if one of those queries fails, or the coordinator fails, you have to retry the whole thing.

If the multiple partition in clause larger try to use separate query, for each partition (ruserid) with executeAsync.

SELECT * FROM test.packages_by_userid WHERE ruserid = '1' AND suserid IN ( '1','2') AND timestamp > 1496601553;
SELECT * FROM test.packages_by_userid WHERE ruserid = '2' AND suserid IN ( '1','2') AND timestamp > 1496601553;

Learn More : https://lostechies.com/ryansvihla/2014/09/22/cassandra-query-patterns-not-using-the-in-query-for-multiple-partitions/


问:
How to set a view's outlets' values from within another class
In xcode, If we have a view controller that has some subviews' (eg: label) outlets, and we want to change its text from the AppDelegate.swift class whenever an app is becoming active after suspended, How can this be done? I have tried making an instance of this view controller class from the AppDelegate class, but that didn't work because it made another view instance instead of the view itself, and we can't set the outlet as static. I have also thought of making a static ViewController property observer, but since it is static I still can't set the outlet from inside it. So, how can we do such a thing?</p>

答:
If we have a view controller that has some subviews' (eg: label) outlets, and we want to change its text from the AppDelegate.swift class whenever an app is becoming active after suspended, How can this be done?

Don't. Never speak directly to another class's outlets. Give that class a method that you can call where that class will respond to the calling of that method by speaking to its own outlet.

I have tried making an instance of this view controller class from the AppDelegate class, but that didn't work because it made another view instance

Correct. You need to get a reference to the existing instance of the other class. To do that, you need to know your own view controller hierarchy / structure or else provide one class with a delegate / reference to the other class at the time of creation.


问:
Spark: error when reading dataframe
I am trying to read the first rows of a Spark DataFrame I created as below:

```<code>#read file
datasetDF = sqlContext.read.format('com.databricks.spark.csv').options(delimiter=';', header='true',inferschema='true').load(dataset)
#vectorize
ignore = ['value']
vecAssembler = VectorAssembler(inputCols=[x for x in datasetDF.columns if x not in ignore], outputCol="features")
#split training - test set
(split20DF, split80DF) = datasetDF.randomSplit([1.0, 4.0],seed)
testSetDF = split20DF.cache()
trainingSetDF = split80DF.cache()

print trainingSetDF.take(5)
</code>```

However if I run this code I get the following error (cause by the last line print trainingSetDF.take(5)):

```<code>: org.apache.spark.SparkException: Job aborted due to stage failure:
Task 0 in stage 3.0 failed 4 times, most recent failure:
Lost task 0.3 in stage 3.0 (TID 7, 192.168.101.102): java.util.concurrent.ExecutionException: java.lang.Exception: failed to compile:
org.codehaus.janino.JaninoRuntimeException:
 Code of method "
(Lorg/apache/spark/sql/catalyst/InternalRow;Lorg/apache/spark/sql/catalyst/InternalRow;)I" of class
 **"org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificOrdering" grows beyond 64 KB**
</code>```

I need to add that this happen only when I have quite a lot of features (more than 256).
What am I doing wrong?

Thanks,
Florent

答:
If you have an ID variable that you can use to join the data I found a work around for the randomSplit() error on wide data (if you don't you can easily make one before splitting and still use the workaround). Make sure you make separate variable names for the split part and don't use the same ones (I used train1/valid1), otherwise you'll get the same error as I think its just making some pointer to the same RDD. This is probably one of the stupidest bugs I've ever I seen. Our data wasn't even that wide.</p>

```<code>Y            = 'y'
ID_VAR       = 'ID'
DROPS        = [ID_VAR]

train = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('s3n://emr-related-files/train.csv')
test = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('s3n://emr-related-files/test.csv')
train.show()
print(train.count)

(train1,valid1) = train.select(ID_VAR).randomSplit([0.7,0.3], seed=123)
train = train1.join(train,ID_VAR,'inner')
valid = valid1.join(train, ID_VAR,'inner')

train.show()
</code>```

Title: Spark: error when reading dataframe

Body:
I am trying to read the first rows of a Spark DataFrame I created as below:

#read file
datasetDF = sqlContext.read.format('com.databricks.spark.csv').options(delimiter=';', header='true',inferschema='true').load(dataset)
#vectorize
ignore = ['value']
vecAssembler = VectorAssembler(inputCols=[x for x in datasetDF.columns if x not in ignore], outputCol="features")
#split training - test set
(split20DF, split80DF) = datasetDF.randomSplit([1.0, 4.0],seed)
testSetDF = split20DF.cache()
trainingSetDF = split80DF.cache()

print trainingSetDF.take(5)

However if I run this code I get the following error (cause by the last line print trainingSetDF.take(5)):

: org.apache.spark.SparkException: Job aborted due to stage failure:
Task 0 in stage 3.0 failed 4 times, most recent failure:
Lost task 0.3 in stage 3.0 (TID 7, 192.168.101.102): java.util.concurrent.ExecutionException: java.lang.Exception: failed to compile:
org.codehaus.janino.JaninoRuntimeException:
 Code of method "
(Lorg/apache/spark/sql/catalyst/InternalRow;Lorg/apache/spark/sql/catalyst/InternalRow;)I" of class
 **"org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificOrdering" grows beyond 64 KB**

I need to add that this happen only when I have quite a lot of features (more than 256).
What am I doing wrong?

Thanks,
Florent

Body:
If you have an ID variable that you can use to join the data I found a work around for the randomSplit() error on wide data (if you don't you can easily make one before splitting and still use the workaround). Make sure you make separate variable names for the split part and don't use the same ones (I used train1/valid1), otherwise you'll get the same error as I think its just making some pointer to the same RDD. This is probably one of the stupidest bugs I've ever I seen. Our data wasn't even that wide.

Y            = 'y'
ID_VAR       = 'ID'
DROPS        = [ID_VAR]

train = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('s3n://emr-related-files/train.csv')
test = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('s3n://emr-related-files/test.csv')
train.show()
print(train.count)

(train1,valid1) = train.select(ID_VAR).randomSplit([0.7,0.3], seed=123)
train = train1.join(train,ID_VAR,'inner')
valid = valid1.join(train, ID_VAR,'inner')

train.show()


问:
PHP - Session doesnt work on mobile
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

```<code>session_start();
if (isset($_SESSION['username'])){
    session_id();
}
</code>```

Whole code for login.php file

```<code><?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>

        <span class="placeholder">username</span>
        <input type="text" name="username" placeholder="username" required>

        <span class="placeholder">password</span>
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        <a class="form-link" href="register.php">Register</a>
    </form>

<?php } ?>
</code>```

答:
Going by your last comment I guess it is due to the query string you are using. Basically using password as a column name sometimes breaks the query as password is also a mysql keyword.
Also, regarding your session you can refer to session_id() vs session_regenerate_id() for further details regarding the functions. Session_id('login') basically sets the session id to login which works on your mobile device as this creates the session with the specific static id. However, you can try using session_regenerate_id(true) to see if it helps.

Also i tried executing the code by putting static value as username as follows

login.php

```<code> <?php
    $username = "deadlock";
    if (isset($_SESSION))
    {
        $_SESSION['username'] = $username;
    }
    else
    {
        session_start();
        $_SESSION['username'] = $username;
    }
     print_r($_SESSION);
</code>```

index.php

```<code><?php
if (isset($_SESSION['username'])){
    session_regenerate_id(true);
} else if (!isset($_SESSION)){
    session_start();
}
print_r(session_id());
</code>```

I started using index.php directly using the phone which printed the output as array() with no values.turned out that the Login.php file is not executed.after I explicitly executed Login.php the index.php printed the session array. Can you make sure that the login php file is properly executed.
Regards

Title: PHP - Session doesnt work on mobile

Body:
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

session_start();
if (isset($_SESSION['username'])){
    session_id();
}

Whole code for login.php file

<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?>
 <?php echo $error_message; ?>
<?php } ?>

        username
        <input type="text" name="username" placeholder="username" required>

        password
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        Register
    </form>

<?php } ?>

Body:
Going by your last comment I guess it is due to the query string you are using. Basically using password as a column name sometimes breaks the query as password is also a mysql keyword.
Also, regarding your session you can refer to session_id() vs session_regenerate_id() for further details regarding the functions. Session_id('login') basically sets the session id to login which works on your mobile device as this creates the session with the specific static id. However, you can try using session_regenerate_id(true) to see if it helps.

Also i tried executing the code by putting static value as username as follows

login.php

 <?php
    $username = "deadlock";
    if (isset($_SESSION))
    {
        $_SESSION['username'] = $username;
    }
    else
    {
        session_start();
        $_SESSION['username'] = $username;
    }
     print_r($_SESSION);

index.php

<?php
if (isset($_SESSION['username'])){
    session_regenerate_id(true);
} else if (!isset($_SESSION)){
    session_start();
}
print_r(session_id());

I started using index.php directly using the phone which printed the output as array() with no values.turned out that the Login.php file is not executed.after I explicitly executed Login.php the index.php printed the session array. Can you make sure that the login php file is properly executed.
Regards


问:
Stopping a blinking cursor at end of css animation
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

```<code>   <div id = "Header"> <b>Real Estate Agent</b> </div>
</code>```

CSS:

```<code>#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }
</code>```

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

答:
Remove the word infinite from the animation for #Header:

```<code>animation: typing 3.5s steps(60, end), blink-caret .65s step-end;
</code>```

Body:
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

 Real Estate Agent

CSS:

#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

Body:
Remove the word infinite from the animation for #Header:

animation: typing 3.5s steps(60, end), blink-caret .65s step-end;