问:
Firebase Google causes java.lang.StackOverflowError
I am trying to use google firebase realtime database. My users can create events which I want to have on the database as a separate table as well as in the user class as a list. This is what I use to write the events to the database and where the exception occurs:

```<code>mDatabase.child("users").child(ResourceManager.getUser().getId()).child("events").setValue(event);

mDatabase.child("events").setValue(ResourceManager.getAllEvents());
</code>```

The problem is that when I try to save the created event I start getting messages that the garbage collection is working few times and after that the same exception printed 100 times at the end of it the app restarts.

```<code>06-30 18:38:19.555 15005-15005/tvfriends.kolio.com.tvproba E/AndroidRuntime:     at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzav(Unknown Source)
                                                                             at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
                                                                             at com.google.firebase.database.DatabaseReference.setValue(Unknown Source)
                                                                             at tvfriends.kolio.com.tvproba.HostActivity.onClick(HostActivity.java:109)
                                                                             at android.view.View.performClick(View.java:5609)
                                                                             at android.view.View$PerformClick.run(View.java:22238)
                                                                             at android.os.Handler.handleCallback(Handler.java:751)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6044)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

Also at the end of the top Exception I get another one

```<code>06-30 18:38:21.478 15005-15005/tvfriends.kolio.com.tvproba D/Error: ERR: TOTAL BYTES WRITTEN: 13034964
06-30 18:38:21.484 15005-15005/tvfriends.kolio.com.tvproba E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 13035048)
06-30 18:38:21.485 15005-15005/tvfriends.kolio.com.tvproba E/AndroidRuntime: Error reporting crash
                                                                            android.os.TransactionTooLargeException: data parcel size 13035048 bytes
                                                                             at android.os.BinderProxy.transactNative(Native Method)
                                                                             at android.os.BinderProxy.transact(Binder.java:615)
                                                                             at android.app.ActivityManagerProxy.handleApplicationCrash(ActivityManagerNative.java:5100)
                                                                             at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:97)
                                                                             at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1068)
                                                                             at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1063)
</code>```

In my Event class I have this variables which I try to store:

```<code>private TVEvent tvEvent;
private User host;
private long date;
private String location;
private TVSet tvSet;
private List<User> attending;
private int eventStatus;
</code>```

TVEvent, TVSet and User have one bitmap each in them and mostle primitive data. So what is the problem here? Any help is deeply appreciated.

EDIT

Here is the stackoverflow error:

```<code> D/Error: ERR: stack=java.lang.StackOverflowError: stack size 8MB
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zz
06-30 18:38:21.447 15005-15012/tvfriends.kolio.com.tvproba W/art: Suspending all threads took: 64.352ms
06-30 18:38:21.478 15005-15005/tvfriends.kolio.com.tvproba D/Error: ERR: TOTAL BYTES WRITTEN: 13034964
</code>```

答:
In case if your file is of less size and if it is still happening, get Uri global variable of the download uri in that.
mediaUri = taskSnapshot.getDownloadUrl();
attri.put("media_dwnld_url", mediaUri.toString());</p>

Body:
I am trying to use google firebase realtime database. My users can create events which I want to have on the database as a separate table as well as in the user class as a list. This is what I use to write the events to the database and where the exception occurs:

mDatabase.child("users").child(ResourceManager.getUser().getId()).child("events").setValue(event);

mDatabase.child("events").setValue(ResourceManager.getAllEvents());

The problem is that when I try to save the created event I start getting messages that the garbage collection is working few times and after that the same exception printed 100 times at the end of it the app restarts.

06-30 18:38:19.555 15005-15005/tvfriends.kolio.com.tvproba E/AndroidRuntime:     at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                             at com.google.android.gms.internal.zzaix.zzav(Unknown Source)
                                                                             at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
                                                                             at com.google.firebase.database.DatabaseReference.setValue(Unknown Source)
                                                                             at tvfriends.kolio.com.tvproba.HostActivity.onClick(HostActivity.java:109)
                                                                             at android.view.View.performClick(View.java:5609)
                                                                             at android.view.View$PerformClick.run(View.java:22238)
                                                                             at android.os.Handler.handleCallback(Handler.java:751)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6044)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Also at the end of the top Exception I get another one

06-30 18:38:21.478 15005-15005/tvfriends.kolio.com.tvproba D/Error: ERR: TOTAL BYTES WRITTEN: 13034964
06-30 18:38:21.484 15005-15005/tvfriends.kolio.com.tvproba E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 13035048)
06-30 18:38:21.485 15005-15005/tvfriends.kolio.com.tvproba E/AndroidRuntime: Error reporting crash
                                                                            android.os.TransactionTooLargeException: data parcel size 13035048 bytes
                                                                             at android.os.BinderProxy.transactNative(Native Method)
                                                                             at android.os.BinderProxy.transact(Binder.java:615)
                                                                             at android.app.ActivityManagerProxy.handleApplicationCrash(ActivityManagerNative.java:5100)
                                                                             at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:97)
                                                                             at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1068)
                                                                             at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1063)

In my Event class I have this variables which I try to store:

private TVEvent tvEvent;
private User host;
private long date;
private String location;
private TVSet tvSet;
private List<User> attending;
private int eventStatus;

TVEvent, TVSet and User have one bitmap each in them and mostle primitive data. So what is the problem here? Any help is deeply appreciated.

EDIT

Here is the stackoverflow error:

 D/Error: ERR: stack=java.lang.StackOverflowError: stack size 8MB
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                    at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                    at com.google.android.gms.internal.zz
06-30 18:38:21.447 15005-15012/tvfriends.kolio.com.tvproba W/art: Suspending all threads took: 64.352ms
06-30 18:38:21.478 15005-15005/tvfriends.kolio.com.tvproba D/Error: ERR: TOTAL BYTES WRITTEN: 13034964


来源: stackexchange

问:
The method onReceive in BroadcastReceiver is never called
My task is to turn the Bluetooth ON & OFF from my app and then search for any paired devices. If any paired device is found, connect to it; otherwise, discover the available devices in vicinity and list them along with their signal strengths; update these signals strengths every N seconds. When the user selects a particular device, connection should be established.

```<code>package surendra.example.com.mybluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.camera2.params.BlackLevelPattern;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    protected static final int DISCOVERY_REQUEST = 1;

    private BluetoothDevice device;

    //Variable for text display
    public TextView statusUpdate;
    public TextView BTHostDetails;
    public TextView BTDevicesAvailable;

    //List of buttons
    public Button turnONBT;
    public Button turnOFFBT;
    public Button scanBTDevices;
    public Button seeRSSI;
    public Button back;

    ArrayAdapter<String> btArrayAdapter;
    //BluetoothAdapter object that initializes the BT hardware on the device
    private BluetoothAdapter mBluetoothAdapter;

    //Broadcast the Bluetooth activities
    BroadcastReceiver bluetoothState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String prevStateExtra  = BluetoothAdapter.EXTRA_PREVIOUS_STATE;
            String stateExtra = BluetoothAdapter.EXTRA_STATE;

            int state = intent.getIntExtra(stateExtra, -1);
            int previousState = intent.getIntExtra(prevStateExtra, -1);

            String toastText = "";

            switch (state) {
                case(BluetoothAdapter.STATE_TURNING_ON) : {
                    //Already turned ON
                    toastText = "Turning ON Bluetooth";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_ON): {
                    //Turned ON
                    toastText = "Bluetooth turned ON";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    break;
                }
                case(BluetoothAdapter.STATE_TURNING_OFF) : {
                    //Already turned OFF
                    toastText = "Turning OFF Bluetooth";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_OFF) : {
                    //Turned OFF
                    toastText = "Bluetooth turned OFF";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    break;
                }
            }
        }
    };

    //Represents a remote BT device
    private BluetoothDevice remoteDevice;

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

        //Get default BT adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        setupUI();
    } //end onCreate method

    //Method to setup UI
    private void setupUI() {
        //Get references of each button and text view from the UI
        final TextView statusUpdate = (TextView) findViewById(R.id.statusUpdate);
        final TextView BTHostDetails = (TextView) findViewById(R.id.BTHostDetails);
        final Button turnONBT = (Button) findViewById(R.id.turnONBT);
        final Button turnOFFBT = (Button) findViewById(R.id.turnOFFBT);
        final Button scanBTDevices = (Button) findViewById(R.id.scanBTDevices);
        final Button seeRSSI = (Button) findViewById(R.id.seeRSSI);
        final Button back = (Button) findViewById(R.id.back);

        //Set visibilities of each button
        turnOFFBT.setVisibility(View.GONE);
        seeRSSI.setVisibility(View.GONE);
        back.setVisibility(View.GONE);
        scanBTDevices.setVisibility(View.GONE);
        BTHostDetails.setVisibility(View.GONE);

        //Check if the BT adapter is enabled
        if(mBluetoothAdapter.isEnabled()) {

            //If the BT adapter is enabled, get the name & address of the device
            String devName = mBluetoothAdapter.getName();
            String devAddr = mBluetoothAdapter.getAddress();

            String statusText = devName + " : " + devAddr;
            BTHostDetails.setText(statusText);

            //set the visibilities of the buttons based upon BT status
            BTHostDetails.setVisibility(View.VISIBLE);
            turnONBT.setVisibility(View.GONE);
            turnOFFBT.setVisibility(View.VISIBLE);
            seeRSSI.setVisibility(View.GONE);
            back.setVisibility(View.VISIBLE);
            scanBTDevices.setVisibility(View.VISIBLE);
        } else {
            String tmp = "Bluetooth turned OFF";
            statusUpdate.setText(tmp);
        }

        // We should keep on listening to the TURN ON BLUETOOTH button.
        // When the button turn on bluetooth is clicked, we should proceed to turn Bluetooth ON
        turnONBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //This makes our device discoverable
                String beDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;

                //Intent is the pop up that we see when requesting for permission to use
                //certain interface on the device just like permission for location access etc.
                //Using the intent filter, we can filter the devices whose permissions are changed
                //when the user updates on the intent
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

                //This registers a broadcast receiver
                registerReceiver(bluetoothState, filter);

                //If the intent changes from non-discoverable to discoverable, with the filter
                // DISCOVERY_REQUEST, then start the activity.
                startActivityForResult(new Intent(beDiscoverable), DISCOVERY_REQUEST);

                //Change the buttons views
                BTHostDetails.setVisibility(View.VISIBLE);
                turnOFFBT.setVisibility(View.VISIBLE);
                turnONBT.setVisibility(View.INVISIBLE);
                scanBTDevices.setVisibility(View.VISIBLE);
                seeRSSI.setVisibility(View.VISIBLE);
                back.setVisibility(View.INVISIBLE);

                String tmp = "Bluetooth turned ON";
                statusUpdate.setText(tmp);
            }
        });

        //scan devices
        scanBTDevices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //start discovery of new devices
                mBluetoothAdapter.startDiscovery();

                //see if this device is in a list of paired available devices
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                //Toast.makeText(MainActivity.this, "Debug text 0", Toast.LENGTH_SHORT).show();
                if(pairedDevices.size() > 0) {
                    //This means that there are paired devices.
                    // Get the name & address of each device.
                    for(BluetoothDevice device : pairedDevices) {
                        String devName = device.getName();
                        String devAddr = device.getAddress();
                    }

                    List<String> s = new ArrayList<String>();
                    for(BluetoothDevice bt : pairedDevices) {
                        s.add(bt.getName());
                    }
                }
                BroadcastReceiver discoveryResult = new BroadcastReceiver() {

                    @Override
                    public void onReceive(Context context, Intent intent) {
                        String action = intent.getAction();

                        if(BluetoothDevice.ACTION_FOUND.equals(action)) {

                            //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
                            String devName = device.getName();
                            String devAddr = device.getAddress();

                            String tmp = devName + " : " + devAddr + " - " + rssi;
                            statusUpdate.setText(tmp);
                        }
                    }
                };
            }
        });

        //Setup a listener for turning of Bluetooth i.e., for TURN OFF BLUETOOTH button
        turnOFFBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Change the buttons views
                BTHostDetails.setVisibility(View.INVISIBLE);
                turnOFFBT.setVisibility(View.INVISIBLE);
                turnONBT.setVisibility(View.VISIBLE);
                scanBTDevices.setVisibility(View.INVISIBLE);
                seeRSSI.setVisibility(View.INVISIBLE);
                back.setVisibility(View.INVISIBLE);

                String tmp = "Bluetooth turned OFF";
                statusUpdate.setText(tmp);

                mBluetoothAdapter.disable();
            }
        });

        //Back button activity
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setupUI();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == DISCOVERY_REQUEST) {
            String tmp = "Discovery is in progress";
            Toast.makeText(MainActivity.this, tmp , Toast.LENGTH_SHORT).show();
            setupUI();
        }
    }
}
</code>```

Upon debug, I found that the onReceive method of BroadcastReceiver is never called. However, Bluetooth is enabled. What am I missing?

PS: I want to confine all the BT activities into MainActivity alone.

答:
Upon debug, I found that the onReceive method of BroadcastReceiver is never called. However, Bluetooth is enabled.

First, if Bluetooth is enabled, and nothing is changing the state of Bluetooth, I would not expect to receive any broadcast. The BluetoothAdapter.ACTION_STATE_CHANGED broadcast is documented to be sent when "The state of the local Bluetooth adapter has been changed." No changes means no broadcast.

Second, you only register bluetoothState as a BroadcastReceiver if the user clicks turnONBT. So, if there is a state change before that, you would not receive the broadcast.

Third, you register bluetoothState for the wrong action. You are registering it for BluetoothDevice.ACTION_FOUND. That action is for Bluetooth discovery, as is covered in the documentation. The action for changes in the Bluetooth state is BluetoothAdapter.ACTION_STATE_CHANGED. Your discoveryResult would seem to be for discovery, and you never seem to register that receiver.

as this is the first ever code I'm doing either in Java or Android

I would not recommend anything involving Bluetooth be your first project in Java or Android.

ContentLicense: CC BY-SA 3.0

Body:
My task is to turn the Bluetooth ON & OFF from my app and then search for any paired devices. If any paired device is found, connect to it; otherwise, discover the available devices in vicinity and list them along with their signal strengths; update these signals strengths every N seconds. When the user selects a particular device, connection should be established.

package surendra.example.com.mybluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.camera2.params.BlackLevelPattern;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    protected static final int DISCOVERY_REQUEST = 1;

    private BluetoothDevice device;

    //Variable for text display
    public TextView statusUpdate;
    public TextView BTHostDetails;
    public TextView BTDevicesAvailable;

    //List of buttons
    public Button turnONBT;
    public Button turnOFFBT;
    public Button scanBTDevices;
    public Button seeRSSI;
    public Button back;

    ArrayAdapter<String> btArrayAdapter;
    //BluetoothAdapter object that initializes the BT hardware on the device
    private BluetoothAdapter mBluetoothAdapter;

    //Broadcast the Bluetooth activities
    BroadcastReceiver bluetoothState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String prevStateExtra  = BluetoothAdapter.EXTRA_PREVIOUS_STATE;
            String stateExtra = BluetoothAdapter.EXTRA_STATE;

            int state = intent.getIntExtra(stateExtra, -1);
            int previousState = intent.getIntExtra(prevStateExtra, -1);

            String toastText = "";

            switch (state) {
                case(BluetoothAdapter.STATE_TURNING_ON) : {
                    //Already turned ON
                    toastText = "Turning ON Bluetooth";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_ON): {
                    //Turned ON
                    toastText = "Bluetooth turned ON";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    break;
                }
                case(BluetoothAdapter.STATE_TURNING_OFF) : {
                    //Already turned OFF
                    toastText = "Turning OFF Bluetooth";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_OFF) : {
                    //Turned OFF
                    toastText = "Bluetooth turned OFF";
                    Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    break;
                }
            }
        }
    };

    //Represents a remote BT device
    private BluetoothDevice remoteDevice;

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

        //Get default BT adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        setupUI();
    } //end onCreate method

    //Method to setup UI
    private void setupUI() {
        //Get references of each button and text view from the UI
        final TextView statusUpdate = (TextView) findViewById(R.id.statusUpdate);
        final TextView BTHostDetails = (TextView) findViewById(R.id.BTHostDetails);
        final Button turnONBT = (Button) findViewById(R.id.turnONBT);
        final Button turnOFFBT = (Button) findViewById(R.id.turnOFFBT);
        final Button scanBTDevices = (Button) findViewById(R.id.scanBTDevices);
        final Button seeRSSI = (Button) findViewById(R.id.seeRSSI);
        final Button back = (Button) findViewById(R.id.back);

        //Set visibilities of each button
        turnOFFBT.setVisibility(View.GONE);
        seeRSSI.setVisibility(View.GONE);
        back.setVisibility(View.GONE);
        scanBTDevices.setVisibility(View.GONE);
        BTHostDetails.setVisibility(View.GONE);

        //Check if the BT adapter is enabled
        if(mBluetoothAdapter.isEnabled()) {

            //If the BT adapter is enabled, get the name & address of the device
            String devName = mBluetoothAdapter.getName();
            String devAddr = mBluetoothAdapter.getAddress();

            String statusText = devName + " : " + devAddr;
            BTHostDetails.setText(statusText);

            //set the visibilities of the buttons based upon BT status
            BTHostDetails.setVisibility(View.VISIBLE);
            turnONBT.setVisibility(View.GONE);
            turnOFFBT.setVisibility(View.VISIBLE);
            seeRSSI.setVisibility(View.GONE);
            back.setVisibility(View.VISIBLE);
            scanBTDevices.setVisibility(View.VISIBLE);
        } else {
            String tmp = "Bluetooth turned OFF";
            statusUpdate.setText(tmp);
        }

        // We should keep on listening to the TURN ON BLUETOOTH button.
        // When the button turn on bluetooth is clicked, we should proceed to turn Bluetooth ON
        turnONBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //This makes our device discoverable
                String beDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;

                //Intent is the pop up that we see when requesting for permission to use
                //certain interface on the device just like permission for location access etc.
                //Using the intent filter, we can filter the devices whose permissions are changed
                //when the user updates on the intent
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

                //This registers a broadcast receiver
                registerReceiver(bluetoothState, filter);

                //If the intent changes from non-discoverable to discoverable, with the filter
                // DISCOVERY_REQUEST, then start the activity.
                startActivityForResult(new Intent(beDiscoverable), DISCOVERY_REQUEST);

                //Change the buttons views
                BTHostDetails.setVisibility(View.VISIBLE);
                turnOFFBT.setVisibility(View.VISIBLE);
                turnONBT.setVisibility(View.INVISIBLE);
                scanBTDevices.setVisibility(View.VISIBLE);
                seeRSSI.setVisibility(View.VISIBLE);
                back.setVisibility(View.INVISIBLE);

                String tmp = "Bluetooth turned ON";
                statusUpdate.setText(tmp);
            }
        });

        //scan devices
        scanBTDevices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //start discovery of new devices
                mBluetoothAdapter.startDiscovery();

                //see if this device is in a list of paired available devices
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                //Toast.makeText(MainActivity.this, "Debug text 0", Toast.LENGTH_SHORT).show();
                if(pairedDevices.size() > 0) {
                    //This means that there are paired devices.
                    // Get the name & address of each device.
                    for(BluetoothDevice device : pairedDevices) {
                        String devName = device.getName();
                        String devAddr = device.getAddress();
                    }

                    List<String> s = new ArrayList<String>();
                    for(BluetoothDevice bt : pairedDevices) {
                        s.add(bt.getName());
                    }
                }
                BroadcastReceiver discoveryResult = new BroadcastReceiver() {

                    @Override
                    public void onReceive(Context context, Intent intent) {
                        String action = intent.getAction();

                        if(BluetoothDevice.ACTION_FOUND.equals(action)) {

                            //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
                            String devName = device.getName();
                            String devAddr = device.getAddress();

                            String tmp = devName + " : " + devAddr + " - " + rssi;
                            statusUpdate.setText(tmp);
                        }
                    }
                };
            }
        });

        //Setup a listener for turning of Bluetooth i.e., for TURN OFF BLUETOOTH button
        turnOFFBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Change the buttons views
                BTHostDetails.setVisibility(View.INVISIBLE);
                turnOFFBT.setVisibility(View.INVISIBLE);
                turnONBT.setVisibility(View.VISIBLE);
                scanBTDevices.setVisibility(View.INVISIBLE);
                seeRSSI.setVisibility(View.INVISIBLE);
                back.setVisibility(View.INVISIBLE);

                String tmp = "Bluetooth turned OFF";
                statusUpdate.setText(tmp);

                mBluetoothAdapter.disable();
            }
        });

        //Back button activity
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setupUI();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == DISCOVERY_REQUEST) {
            String tmp = "Discovery is in progress";
            Toast.makeText(MainActivity.this, tmp , Toast.LENGTH_SHORT).show();
            setupUI();
        }
    }
}

Upon debug, I found that the onReceive method of BroadcastReceiver is never called. However, Bluetooth is enabled. What am I missing?

PS: I want to confine all the BT activities into MainActivity alone.


问:
Build string from another strings in loop using stringstream
I want to build one string from strings that are typed in loop by getline()

```<code>cin >> n;
string all,line;
stringstream ss;

for (int i = 0; i < n; i++)
    {
        ss.clear();
        line.clear();
        cin.ignore();
        getline(cin, line, '\n');
        ss.str(line);
        all += ss.str();

    }
    cout << all << endl;;
</code>```

I expected:

```<code>input:
2
word
word

output:
wordword
</code>```

Instead of this I get:

```<code>input:
2
word
word

output:
wordord
</code>```

I can't find solution for that. Could someone help me?

答: cin.ignore() is ignoring the first character in the second input word. Get rid of it.

Body:
I want to build one string from strings that are typed in loop by getline()

cin >> n;
string all,line;
stringstream ss;

for (int i = 0; i < n; i++)
    {
        ss.clear();
        line.clear();
        cin.ignore();
        getline(cin, line, '\n');
        ss.str(line);
        all += ss.str();

    }
    cout << all << endl;;

I expected:

input:
2
word
word

output:
wordword

Instead of this I get:

input:
2
word
word

output:
wordord

I can't find solution for that. Could someone help me?


问:
JavaScript Function that creates 4 random numbers that push to an array?
Instead of doing this:

```<code>var crystalValues = [];
crystalValues[0] = Math.floor(Math.random()*12+1),
crystalValues[1] = Math.floor(Math.random()*12+1),
crystalValues[2] = Math.floor(Math.random()*12+1),
crystalValues[3] = Math.floor(Math.random()*12+1),
</code>```

How can I create a function that returns 4 random numbers?

答:
You can simply use Array.from()

var gen = () => {
 return Array.from({length: 4}, () => Math.floor( Math.floor(Math.random()*12+1)));
}

console.log(gen());```

Body:
Instead of doing this:

var crystalValues = [];
crystalValues[0] = Math.floor(Math.random()*12+1),
crystalValues[1] = Math.floor(Math.random()*12+1),
crystalValues[2] = Math.floor(Math.random()*12+1),
crystalValues[3] = Math.floor(Math.random()*12+1),

How can I create a function that returns 4 random numbers?


答:
A for loop would do the trick if you're trying to save time typing the function out. </p>

```<code>random4() {
    var crystalValues = [];
    for (var i=0; i < 4 ; i++) {
        randomNumber = Math.floor(Math.random()*12+1);
        while (crystalValues.indexOf(randomNumber) !== -1) {
            randomNumber = Math.floor(Math.random()*12+1);
        }
        crystalValues[i] = randomNumber;
    }
    return crystalValues;
}
</code>```

Title: JavaScript Function that creates 4 random numbers that push to an array?

Body:
A for loop would do the trick if you're trying to save time typing the function out.

random4() {
    var crystalValues = [];
    for (var i=0; i < 4 ; i++) {
        randomNumber = Math.floor(Math.random()*12+1);
        while (crystalValues.indexOf(randomNumber) !== -1) {
            randomNumber = Math.floor(Math.random()*12+1);
        }
        crystalValues[i] = randomNumber;
    }
    return crystalValues;
}


问:
Makefile: order of dependency evaluation
Assume a target foo.tar, that depends on a list of files foo.files, e.g.

```<code>FOO_FILES := $(shell cat foo.files)

foo.tar: foo.files $(FOO_FILES)
    tar -cf foo $(FOO_FILES)
</code>```

Now suppose that foo.files need to be generated e.g.:

```<code>foo.files: foo.files.template
    sed -e "s/@{VERSION}/$(VERSION)/" < $< > $@
</code>```

It is clear that foo.files depends on foo.files.template, but how can one make sure that FOO_FILES is evaluated after foo.files is generated?

答:
It can't be done in one pass; Make determines which targets must be rebuilt before it actually executes any rule, and in this case the full list of targets doesn't exist until one of the rules is executed.

This should do it:

```<code>FOO_FILES := $(shell cat foo.files)

foo.tar: foo.files
    $(MAKE) foo-tarball

.PHONY: foo-tarball
foo-tarball: $(FOO_FILES)
    tar -cf foo $^
</code>```

EDIT:

As the OP points out, this will not work as written; I left out a prerequisite:

```<code>foo.tar: foo.files $(FOO_FILES)
    ...
</code>```

Note that this will recurse even if foo.files has not changed, which is not strictly necessary; it is possible to correct this, but not elegantly. (For comparison, the selected solution, which I admit is cleaner than mine, recurses even if the target has nothing to do with foo.tar.)

ContentLicense: CC BY-SA 2.5

Body:
Assume a target foo.tar, that depends on a list of files foo.files, e.g.

FOO_FILES := $(shell cat foo.files)

foo.tar: foo.files $(FOO_FILES)
    tar -cf foo $(FOO_FILES)

Now suppose that foo.files need to be generated e.g.:

foo.files: foo.files.template
    sed -e "s/@{VERSION}/$(VERSION)/" < $< > $@

It is clear that foo.files depends on foo.files.template, but how can one make sure that FOO_FILES is evaluated after foo.files is generated?

Body:
It can't be done in one pass; Make determines which targets must be rebuilt before it actually executes any rule, and in this case the full list of targets doesn't exist until one of the rules is executed.

This should do it:

FOO_FILES := $(shell cat foo.files)

foo.tar: foo.files
    $(MAKE) foo-tarball

.PHONY: foo-tarball
foo-tarball: $(FOO_FILES)
    tar -cf foo $^

EDIT:

As the OP points out, this will not work as written; I left out a prerequisite:

foo.tar: foo.files $(FOO_FILES)
    ...

Note that this will recurse even if foo.files has not changed, which is not strictly necessary; it is possible to correct this, but not elegantly. (For comparison, the selected solution, which I admit is cleaner than mine, recurses even if the target has nothing to do with foo.tar.)


问:
How to downgrade AWS SDK in Spring-integration-aws
Is there anyway we can leverage the massaging handler capability that is part of spring-integration-aws-1.1.0-RC1 we just downgrade the AWS SDK version to aws-sdk-core-1.4.x ?

As I would like to integrate with a proprietary CMS application [Hitachi Content Platform], which support old version AWS S3 API (i.e. AWS SDK 1.4.x ).

Meantime I still want do have to leverage the S3MessageHandler for my service call handling. Is there any middle path to the problem.

Note:- The AWS SDK that is part of spring-integration-aws-1.1.0-RC1 is not supported by CMS application.

答:
With upgraded AWD SDK the difference in my case was the Authentication cookie names and few other cookie. These difference was set by the Signer. So in my ClientConfiguration I set the signer to S3SignerType that resolved my issue. See AmazonS3Client registered signer. </p>

```<code>ClientConfiguration.setSignerOverride("S3SignerType");
</code>```

Body:
With upgraded AWD SDK the difference in my case was the Authentication cookie names and few other cookie. These difference was set by the Signer. So in my ClientConfiguration I set the signer to S3SignerType that resolved my issue. See AmazonS3Client registered signer.

ClientConfiguration.setSignerOverride("S3SignerType");


问:
Why am I getting the error: 'int' object has no attribute 'create'?
code:

 @api.multi
    def open_second_class(self):
        ac = self.env['ir.model.data'].xmlid_to_res_id('account.invoice_form', raise_if_not_found=True)
        write_obj = ac.create({'partner_id': self.name_id})
        accountant = False
        for o in self:
            accountant = o.id
        result = {
            'name': '2nd class',
            'view_type': 'form',
            'res_model': 'account.invoice',
            'res_id': write_obj.id,
            'view_id': False,
            'context': {'default_id_tbl1': accountant},
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'domain': '[]'
        }
        return result
```

<p><strong>Error:</strong></p>

```Traceback (most recent call last):
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 650, in _handle_exception
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 687, in dispatch
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 323, in _call_function
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\service\model.py", line 118, in wrapper
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 316, in checked_call
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 966, in __call__
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 516, in response_wrap
          File "C:\Program Files\Odoo 9.0-20170919\server\openerp\addons\web\controllers\main.py", line 899, in call_button
          File "C:\Program Files\Odoo 9.0-20170919\server\openerp\addons\web\controllers\main.py", line 887, in _call_kw
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\api.py", line 250, in wrapper
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\api.py", line 381, in old_api
          File "C:\Users\Amandnoever\AppData\Local\OpenERP S.A.\Odoo\addons\9.0\accountant\models\models.py", line 48, in open_second_class
        AttributeError: 'int' object has no attribute 'create'
```

答:
Use self.env.ref('external_id') instead of the xmlid_to_res_id method. But I think what you want to do is something like this:

@api.multi
def open_second_class(self):
    self.ensure_one()
    ac = self.env.ref('account.invoice_form')
    invoice = self.env['account.invoice'].create({
        'partner_id': self.name_id.id
    })

    return {
        'name': '2nd class',
        'type': 'ir.actions.act_window',
        'res_model': 'account.invoice',
        'res_id': invoice.id,
        'view_type': 'form',
        'view_mode': 'form',
        'target': 'new',
        'context': {'default_id_tbl1': self.env.id },
    }
```

Body:
code:

 @api.multi
    def open_second_class(self):
        ac = self.env['ir.model.data'].xmlid_to_res_id('account.invoice_form', raise_if_not_found=True)
        write_obj = ac.create({'partner_id': self.name_id})
        accountant = False
        for o in self:
            accountant = o.id
        result = {
            'name': '2nd class',
            'view_type': 'form',
            'res_model': 'account.invoice',
            'res_id': write_obj.id,
            'view_id': False,
            'context': {'default_id_tbl1': accountant},
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'domain': '[]'
        }
        return result

Error:

Traceback (most recent call last):
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 650, in _handle_exception
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 687, in dispatch
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 323, in _call_function
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\service\model.py", line 118, in wrapper
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 316, in checked_call
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 966, in __call__
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\http.py", line 516, in response_wrap
          File "C:\Program Files\Odoo 9.0-20170919\server\openerp\addons\web\controllers\main.py", line 899, in call_button
          File "C:\Program Files\Odoo 9.0-20170919\server\openerp\addons\web\controllers\main.py", line 887, in _call_kw
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\api.py", line 250, in wrapper
          File "C:\Program Files\Odoo 9.0-20170919\server\.\openerp\api.py", line 381, in old_api
          File "C:\Users\Amandnoever\AppData\Local\OpenERP S.A.\Odoo\addons\9.0\accountant\models\models.py", line 48, in open_second_class
        AttributeError: 'int' object has no attribute 'create'


问:
How to detect from within Python whether packages are managed with conda
I would like to detect in a general way from within a Python session whether it is managed by conda.

A few ideas that are not general enough to be useful:

1: Use environment variables

As mentioned in How do I find the name of the conda environment in which my code is running?

```<code>import os
is_conda = 'CONDA_PREFIX' in os.system or 'CONDA_DEFAULT_ENV' in os.system
</code>```

This seems not to work in the root conda environment, where these variables are not always defined. It also has potential false positives if conda happens to be activated while you are using another Python installation.

2: Check the executable path

```<code>import sys
is_conda = ('anaconda' in sys.executable) or ('miniconda' in sys.executable)
</code>```

This will work in the case that users install anaconda/miniconda in the default path. It may fail otherwise. It's also easy to imagine false-positives.

3. Check the version info

As noted in the answers to any way to tell if user's python environment is anaconda, you can check the Python version string in some cases:

```<code>import sys
is_conda = ('Continuum Analytics' in sys.version) or ('Anaconda' in sys.version)
</code>```

This works currently for Python installed from the default channel, but this is quite brittle and may break in the future, particularly with Continuum's company name change. It also probably fails if Python is installed from a third-party source like conda-forge.

4. Check the conda import

```<code>try:
    import conda
except:
    is_conda = False
else:
    is_conda = True
</code>```

This works as long as you're in the root conda environment, but generally fails if you're in another conda env where the conda package is not installed by default.

5: Try conda to see if it works

Suggestion from Atto Allas below:

```<code>import subprocess
try:
    retcode = subprocess.call(['conda', 'install', '-y', 'pip'])
except:
    is_conda = False
else:
    is_conda = (retcode == 0)
</code>```

This works in the simplest cases, but fails in the common case of using multiple kernels in Jupyter, where the conda executable may or may not be connected to the current Python kernel.

Is there any entirely general way to detect from Python whether that Python installation is managed by conda?

答:
I think the best approach is a variation on Ross Hynten's answer: in the build process, conda creates a file called {sys.prefix}/conda-meta/history, so checking for its presence should tell you if you're using conda in a reasonably robust manner:

```<code>import sys, os
is_conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta', 'history'))
</code>```

It remains possible to have false-positives with this approach, but seems to me very unlikely unless done deliberately.

Body:
I would like to detect in a general way from within a Python session whether it is managed by conda.

A few ideas that are not general enough to be useful:

1: Use environment variables

As mentioned in How do I find the name of the conda environment in which my code is running?

import os
is_conda = 'CONDA_PREFIX' in os.system or 'CONDA_DEFAULT_ENV' in os.system

This seems not to work in the root conda environment, where these variables are not always defined. It also has potential false positives if conda happens to be activated while you are using another Python installation.

2: Check the executable path

import sys
is_conda = ('anaconda' in sys.executable) or ('miniconda' in sys.executable)

This will work in the case that users install anaconda/miniconda in the default path. It may fail otherwise. It's also easy to imagine false-positives.

3. Check the version info

As noted in the answers to any way to tell if user's python environment is anaconda, you can check the Python version string in some cases:

import sys
is_conda = ('Continuum Analytics' in sys.version) or ('Anaconda' in sys.version)

This works currently for Python installed from the default channel, but this is quite brittle and may break in the future, particularly with Continuum's company name change. It also probably fails if Python is installed from a third-party source like conda-forge.

4. Check the conda import

try:
    import conda
except:
    is_conda = False
else:
    is_conda = True

This works as long as you're in the root conda environment, but generally fails if you're in another conda env where the conda package is not installed by default.

5: Try conda to see if it works

Suggestion from Atto Allas below:

import subprocess
try:
    retcode = subprocess.call(['conda', 'install', '-y', 'pip'])
except:
    is_conda = False
else:
    is_conda = (retcode == 0)

This works in the simplest cases, but fails in the common case of using multiple kernels in Jupyter, where the conda executable may or may not be connected to the current Python kernel.

Is there any entirely general way to detect from Python whether that Python installation is managed by conda?

Body:
I think the best approach is a variation on Ross Hynten's answer: in the build process, conda creates a file called {sys.prefix}/conda-meta/history, so checking for its presence should tell you if you're using conda in a reasonably robust manner:

import sys, os
is_conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta', 'history'))

It remains possible to have false-positives with this approach, but seems to me very unlikely unless done deliberately.


问:
stop execution script within condition
I have the following code in the script test.R:

```<code>if (x==2){
  stop("the script ends")
}
</code>```

Now I source this script

```<code>source(test.R)
t <- 2
</code>```

I would like the code to stop if x==2 and does not go further. However, it continues and assigns t <- 2. I can use the function warnings(options) but I want to avoid this option and implement a condition within the if. Any suggestion?

答:
A while loop can create a condition that you can escape from as you are suggesting:

```<code>while (TRUE){
    if (x==2) {
        break
    }
}
</code>```

This is assuming that your code is 'all the way to the left' when executing. Seeing a little more might help, or better understanding how x is being set or being used. Note that using something like while(TRUE) might not be best practice, and can lead to infinite execution if you do not exit properly.

Title: stop execution script within condition

Body:
I have the following code in the script test.R:

if (x==2){
  stop("the script ends")
}

Now I source this script

source(test.R)
t <- 2

I would like the code to stop if x==2 and does not go further. However, it continues and assigns t <- 2. I can use the function warnings(options) but I want to avoid this option and implement a condition within the if. Any suggestion?

Body:
A while loop can create a condition that you can escape from as you are suggesting:

while (TRUE){
    if (x==2) {
        break
    }
}

This is assuming that your code is 'all the way to the left' when executing. Seeing a little more might help, or better understanding how x is being set or being used. Note that using something like while(TRUE) might not be best practice, and can lead to infinite execution if you do not exit properly.


问:
How to find Time taken for doing a mathematical operation?
I am trying to do an program where i need to find the time take for doing a mathematical function. Suppose i am doing a calculation a/b, then how can i find the time taken to finish that calculation in millisecond??
Please help me</p>

答:
The usual process is to do it many times (say, N) then divide the time taken by that N.

For example, in pseudo-code:

```<code>count = 100000
startTime = secondsSinceStartOfDay()
for i = 1 to count
    do nothing
duration = secondsSinceStartOfDay() - startTime
print "Milliseconds per NOP = ", (duration * 1000 / count)
startTime = secondsSinceStartOfDay()
for i = 1 to count
    x = a/b
duration = secondsSinceStartOfDay() - startTime
print "Milliseconds per division = ", (duration * 1000 / count)
</code>```

This allows you to discount the cost of the loop itself since you measure both with and without the operation being measured.

You do have to be careful with agressive optimisers which may decide, since you don't actually use any of the stuff you calculate, that it is free to optimise the loop code out of existence. I've actually seen this happen. Needless to say, you should understand what is happening under the covers if you're doing performance measurements.

Body:
The usual process is to do it many times (say, N) then divide the time taken by that N.

For example, in pseudo-code:

count = 100000
startTime = secondsSinceStartOfDay()
for i = 1 to count
    do nothing
duration = secondsSinceStartOfDay() - startTime
print "Milliseconds per NOP = ", (duration * 1000 / count)
startTime = secondsSinceStartOfDay()
for i = 1 to count
    x = a/b
duration = secondsSinceStartOfDay() - startTime
print "Milliseconds per division = ", (duration * 1000 / count)

This allows you to discount the cost of the loop itself since you measure both with and without the operation being measured.

You do have to be careful with agressive optimisers which may decide, since you don't actually use any of the stuff you calculate, that it is free to optimise the loop code out of existence. I've actually seen this happen. Needless to say, you should understand what is happening under the covers if you're doing performance measurements.


问:
Length of a string in PL/SQL
Why is this script producing an error? </p>

```<code> SET serveroutput ON
  BEGIN
   v_size INTEGER(20);
   v_myName VARCHAR2(50) := 'My name is Ashish Ramtri';

   v_size := LENGTH(v_myName);

   DBMS_OUTPUT.PUT_LINE(v_size);

  END;
  /
</code>```

答:
As documented in the manual variables need to be declared with the declare keyword

```<code>SET serveroutput ON
declare
  v_size INTEGER(20);
  v_myName VARCHAR2(50) := 'My name is Ashish Ramtri';
BEGIN
   v_size := LENGTH(v_myName);
   DBMS_OUTPUT.PUT_LINE(v_size);
END;
/
</code>```

Title: Length of a string in PL/SQL

Body:
Why is this script producing an error?

 SET serveroutput ON
  BEGIN
   v_size INTEGER(20);
   v_myName VARCHAR2(50) := 'My name is Ashish Ramtri';

   v_size := LENGTH(v_myName);

   DBMS_OUTPUT.PUT_LINE(v_size);

  END;
  /

Body:
As documented in the manual variables need to be declared with the declare keyword

SET serveroutput ON
declare
  v_size INTEGER(20);
  v_myName VARCHAR2(50) := 'My name is Ashish Ramtri';
BEGIN
   v_size := LENGTH(v_myName);
   DBMS_OUTPUT.PUT_LINE(v_size);
END;
/


问:
Firefox ignoring document.getElementById(id).style.background?
I'm creating a checklist so that when an item is complete, it can be clicked and background turns "red". If it was marked "red" in error, it can be clicked again and background goes to "none". It works great in Chrome and Safari. In Firefox, it works well except when you try to undo the "red" to make it go to "none". I suspect it may be something to do with the color name instead of specific values, though I had problems trying that as well with FireFox. Here's the JS I'm using to do that none->red->none as needed.</p>

```<code>    function onMouseDown(id) {
      var squareColor = document.getElementById(id).style.background;
      if (squareColor === "red") {
        document.getElementById(id).style.background = "none";
        document.getElementById(id).style.color = "black";
      } else {
        document.getElementById(id).style.background = "red";
        document.getElementById(id).style.color = "white";
      }
    }
</code>```

答: Try using the Hex color code of red in the if statement instead of writing the name of the color. Good Luck</p>

Body:
I'm creating a checklist so that when an item is complete, it can be clicked and background turns "red". If it was marked "red" in error, it can be clicked again and background goes to "none". It works great in Chrome and Safari. In Firefox, it works well except when you try to undo the "red" to make it go to "none". I suspect it may be something to do with the color name instead of specific values, though I had problems trying that as well with FireFox. Here's the JS I'm using to do that none->red->none as needed.

    function onMouseDown(id) {
      var squareColor = document.getElementById(id).style.background;
      if (squareColor === "red") {
        document.getElementById(id).style.background = "none";
        document.getElementById(id).style.color = "black";
      } else {
        document.getElementById(id).style.background = "red";
        document.getElementById(id).style.color = "white";
      }
    }


答:
Unlike the >> operator, getline() consumes the newline. Your next iteration then ignore()s the w of the following line.

Just moving the ignore out of the loop should produce the desired result.

You're overcomplicating this a bit, though – you don't need to "detour" through a stringstream:

```<code>cin >> n;
cin.ignore();
string all;
for (int i = 0; i < n; i++)
{
    string line;
    getline(cin, line);
    all += line;
}
cout << all << endl;
</code>```

But, you can accumulate the entire thing into a stream, and convert afterwards (which is more efficient):

```<code>cin >> n;
cin.ignore();
ostringstream all_stream;
for (int i = 0; i < n; i++)
{
    string line;
    getline(cin, line);
    all_stream << line;
}
string all = all_stream.str();
cout << all << endl;
</code>```

Title: Build string from another strings in loop using stringstream

Body:
Unlike the >> operator, getline() consumes the newline. Your next iteration then ignore()s the w of the following line.

Just moving the ignore out of the loop should produce the desired result.

You're overcomplicating this a bit, though – you don't need to "detour" through a stringstream:

cin >> n;
cin.ignore();
string all;
for (int i = 0; i < n; i++)
{
    string line;
    getline(cin, line);
    all += line;
}
cout << all << endl;

But, you can accumulate the entire thing into a stream, and convert afterwards (which is more efficient):

cin >> n;
cin.ignore();
ostringstream all_stream;
for (int i = 0; i < n; i++)
{
    string line;
    getline(cin, line);
    all_stream << line;
}
string all = all_stream.str();
cout << all << endl;


问:
Java design strucutre
If I want to write bunch of sort classes (insertion, merge, etc) with void sort() method common in all of them, then I was hoping to have an interface or abstract class that these classes can implement or extend from.

However, if I plan on using the sort method as static and can not keep static method in abstract super class.

What would be proper way for such implementation?

答:
Well, I think you are trying to make it complicated. Your problem is straight forward. You just need to code few sort functions. You can't try to apply object oriented thinking on everywhere. This is just implementation of different reusable algorithms. If you really need to DESIGN this. You can try this way:</p>

```<code>interface Sorter<T> {

    // This method accepts any type of object and sorts it and return it in sorted order
    //Used Generics to support all types. You can read T as List or Array if you want to understand it in a simple way
    public T sort(T t);
}

class MergeSort implements Sorter<int[]> {

    @Override
    public int[] sort(int[] numbersToSort) {
    //algorithm goes here

    }

}

class BubbleSort implements Sorter<int[]> {

    @Override
    public int[] sort(int[] numbersToSort) {
        //algorithm goes here
    }

}

class InsertionSort implements Sorter<int[]> {

    @Override
    public int[] sort(int[] numbersToSort) {
        //algorithm goes here
    }

}

enum SortingAlgorithms{
INSERTIONSORT,
BUBBLESORT,
MERGESORT;

}

class SorterFactory {
    public static Sorter<int[]> getSortingAlgorithm(SortingAlgorithms alg) {
        switch(alg) {
        case INSERTIONSORT :
            return new InsertionSort();

        case BUBBLESORT :
            return new BubbleSort();

        case MERGESORT :
            return new MergeSort();

        default:
            return new BubbleSort();
        }
    }
}

public class SortingExecutor {
    public static void main (String... cmdArgs) {

        int[] toBeSorted = {6, 7, 1, 0, 3};

        //get a bubble sort algorith which can take int[] as input and return the sorted int[] as output
        Sorter<int[]> bubbleSort = SorterFactory.getSortingAlgorithm(SortingAlgorithms.BUBBLESORT);
        bubbleSort.sort(toBeSorted);

    }
}
</code>```

Title: Java design strucutre

Body:
Well, I think you are trying to make it complicated. Your problem is straight forward. You just need to code few sort functions. You can't try to apply object oriented thinking on everywhere. This is just implementation of different reusable algorithms. If you really need to DESIGN this. You can try this way:

interface Sorter<T> {

    // This method accepts any type of object and sorts it and return it in sorted order
    //Used Generics to support all types. You can read T as List or Array if you want to understand it in a simple way
    public T sort(T t);
}

class MergeSort implements Sorter<int[]> {

    @Override
    public int[] sort(int[] numbersToSort) {
    //algorithm goes here

    }

}

class BubbleSort implements Sorter<int[]> {

    @Override
    public int[] sort(int[] numbersToSort) {
        //algorithm goes here
    }

}

class InsertionSort implements Sorter<int[]> {

    @Override
    public int[] sort(int[] numbersToSort) {
        //algorithm goes here
    }

}

enum SortingAlgorithms{
INSERTIONSORT,
BUBBLESORT,
MERGESORT;

}

class SorterFactory {
    public static Sorter<int[]> getSortingAlgorithm(SortingAlgorithms alg) {
        switch(alg) {
        case INSERTIONSORT :
            return new InsertionSort();

        case BUBBLESORT :
            return new BubbleSort();

        case MERGESORT :
            return new MergeSort();

        default:
            return new BubbleSort();
        }
    }
}

public class SortingExecutor {
    public static void main (String... cmdArgs) {

        int[] toBeSorted = {6, 7, 1, 0, 3};

        //get a bubble sort algorith which can take int[] as input and return the sorted int[] as output
        Sorter<int[]> bubbleSort = SorterFactory.getSortingAlgorithm(SortingAlgorithms.BUBBLESORT);
        bubbleSort.sort(toBeSorted);

    }
}


问:
Redirect form based on radio selection
So, i have a form with 3 radio buttons. Depending on which option the user selects (he can only choose one), there can be 3 situations:

if he selects the first one, when he submits the form, he gets redirected to a new URL.

if he selects the second one, a div appears (and then disappears).

if he selects the third one, a div appears (different from the previous one), and then it also disappears.

My HTML:

```<code><form>
      <div class="radio">
        <label><input type="radio" name="paypal" value="paypal"</label>
      </div>
      <div class="radio">
        <label><input type="radio" name="money" value="money"></label>
      </div>
      <div class="radio">
        <label><input type="radio" name="mastercard" value="mastercard"></label>
      </div>
</form>
<button type="button" id="button1" name="button">Check</button>
</code>```

My JQuery:

```<code>$('#button1').click(function() {
  var value = $(this).val();
  if (value == 'paypal') {
    window.location.assign("http://www.paypal.com");
}
  else if (value == 'money') {
    $('.div2').show('slow');
      $('.div2').fadeOut(4000);
}
}
  else if (value == 'mastercard') {
    $('.div1').show('slow');
       $('.div1').fadeOut(4000);
}
</code>```

But something is not working in here, and I can't figure out what or where.
EDIT: No error, the JQuery code just doesn't work. Whatever option I choose, when I submit nothing happens.

答:
By using var value = $(this).val(); inside the button click, you are actually taking the value of the button itself which is not you are intending to do.

Make all radio button name same. Try the following code:

$('#button1').click(function() {
  var value = $('input[name=myRadio]:checked').val();
  if (value == 'paypal') {
    console.log(value);
    window.location.assign("http://www.paypal.com");
  }
  else if (value == 'money') {
    console.log(value);
    $('.div2').show('slow');
    $('.div2').fadeOut(4000);
  }

  else if (value == 'mastercard') {
    console.log(value);
    $('.div1').show('slow');
    $('.div1').fadeOut(4000);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="radio">
    <label><input type="radio" name="myRadio" value="paypal">Pay Pal</label>
  </div>
  <div class="radio">
    <label><input type="radio" name="myRadio" value="money">Money</label>
  </div>
  <div class="radio">
    <label><input type="radio" name="myRadio" value="mastercard">Master Card</label>
  </div>
</form>
<button type="button" id="button1" name="button">Check</button></code>```

Title: Redirect form based on radio selection

Body:
So, i have a form with 3 radio buttons. Depending on which option the user selects (he can only choose one), there can be 3 situations:

if he selects the first one, when he submits the form, he gets redirected to a new URL.

if he selects the second one, a div appears (and then disappears).

if he selects the third one, a div appears (different from the previous one), and then it also disappears.

My HTML:

<form>

        <input type="radio" name="paypal" value="paypal"

        <input type="radio" name="money" value="money">

        <input type="radio" name="mastercard" value="mastercard">

</form>
<button type="button" id="button1" name="button">Check</button>

My JQuery:

$('#button1').click(function() {
  var value = $(this).val();
  if (value == 'paypal') {
    window.location.assign("http://www.paypal.com");
}
  else if (value == 'money') {
    $('.div2').show('slow');
      $('.div2').fadeOut(4000);
}
}
  else if (value == 'mastercard') {
    $('.div1').show('slow');
       $('.div1').fadeOut(4000);
}

But something is not working in here, and I can't figure out what or where.
EDIT: No error, the JQuery code just doesn't work. Whatever option I choose, when I submit nothing happens.

Body:
By using var value = $(this).val(); inside the button click, you are actually taking the value of the button itself which is not you are intending to do.

Make all radio button name same. Try the following code:

$('#button1').click(function() {
  var value = $('input[name=myRadio]:checked').val();
  if (value == 'paypal') {
    console.log(value);
    window.location.assign("http://www.paypal.com");
  }
  else if (value == 'money') {
    console.log(value);
    $('.div2').show('slow');
    $('.div2').fadeOut(4000);
  }

  else if (value == 'mastercard') {
    console.log(value);
    $('.div1').show('slow');
    $('.div1').fadeOut(4000);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="radio">
    <label><input type="radio" name="myRadio" value="paypal">Pay Pal</label>
  </div>
  <div class="radio">
    <label><input type="radio" name="myRadio" value="money">Money</label>
  </div>
  <div class="radio">
    <label><input type="radio" name="myRadio" value="mastercard">Master Card</label>
  </div>
</form>
<button type="button" id="button1" name="button">Check</button>


问:
How do I plot a function with different values of various parameters on gnuplot?
I want to plot this parametric funtion

```<code> x(t)=a+(n/w)*(cos(w*t)-1)-((g/w**2)*sin(l)-m/w)*(sin(w*t)+(g*t/w)*sin(l))

 y(t)=b+((g/w**2)*sin(l)-m/w)*(cos(w*t)-1)+(n/w)*sin(w*t)
</code>```

But I have various parameters a,b,m,n,w,k,g y I want to vary a,b,m,n,w,k parameters. g=7

I don't know how do it.

However i intended:

plot for [a=1:0],[b=1:0],[n=0:1],[m=1:0],[g=7:7],[w=2*pi*3:2*pi*2] x(t),y(t)

I appreciate your help. thanks!

答:
For what regards multiple for in a single plot command, the syntax is documented in the inline help of gnuplot

```<code> Nested iteration is supported:

       set for [i=1:9] for [j=1:9] label i*10+j sprintf("%d",i*10+j) at i,j
</code>```

E.g.,

```<code>gnuplot> plot for[a=0:1] for[b=0:1] 1+a*x+b*x*x
</code>```

You could do now what you want except for a further problem: in gnuplot numeric loops variables have only integer values, e.g.,

```<code>gnuplot> plot for [s=3.2:9.3:2.9] x title sprintf("%f", s)
</code>```

so your loop on w is impossible, you have to devise a different strategy.

With the provision that I don't know what value you want to assign to l (I've used l=1) and also that I don't know the step on w, here it is a possible implementation where the tricks are ❶ define a function that gives you the values of w in terms of an integer variable and ❷ define x and y also in terms of this auxiliary variable

```<code>gnuplot> set parametric
gnuplot> w(k) = 2*pi*k
gnuplot> x(t, k)=a+(n/w(k))*(cos(w(k)*t)-1)-((g/w(k)**2)*sin(l)-m/w(k))*(sin(w(k)*t)+(g*t/w(k))*sin(l))
gnuplot> y(t, k) = b + ((g/w(k)**2)*sin(l)-m/w(k))*(cos(w(k)*t)-1)+(n/w(k))*sin(w(k)*t)
gnuplot> g = 7 ; l = 1
gnuplot> plot for[a=0:1] for[b=0:1] for[m=0:1] for[n=0:1] for[k=2:3] x(t,k), y(t,k) title sprintf("%d,%d,%d,%d,%d", a,b,n,m,k)
</code>```

Body:
I want to plot this parametric funtion

 x(t)=a+(n/w)*(cos(w*t)-1)-((g/w**2)*sin(l)-m/w)*(sin(w*t)+(g*t/w)*sin(l))

 y(t)=b+((g/w**2)*sin(l)-m/w)*(cos(w*t)-1)+(n/w)*sin(w*t)

But I have various parameters a,b,m,n,w,k,g y I want to vary a,b,m,n,w,k parameters. g=7

I don't know how do it.

However i intended:

plot for [a=1:0],[b=1:0],[n=0:1],[m=1:0],[g=7:7],[w=2*pi*3:2*pi*2] x(t),y(t)

I appreciate your help. thanks!

Body:
For what regards multiple for in a single plot command, the syntax is documented in the inline help of gnuplot

 Nested iteration is supported:

       set for [i=1:9] for [j=1:9] label i*10+j sprintf("%d",i*10+j) at i,j

E.g.,

gnuplot> plot for[a=0:1] for[b=0:1] 1+a*x+b*x*x

You could do now what you want except for a further problem: in gnuplot numeric loops variables have only integer values, e.g.,

gnuplot> plot for [s=3.2:9.3:2.9] x title sprintf("%f", s)

so your loop on w is impossible, you have to devise a different strategy.

With the provision that I don't know what value you want to assign to l (I've used l=1) and also that I don't know the step on w, here it is a possible implementation where the tricks are ❶ define a function that gives you the values of w in terms of an integer variable and ❷ define x and y also in terms of this auxiliary variable

gnuplot> set parametric
gnuplot> w(k) = 2*pi*k
gnuplot> x(t, k)=a+(n/w(k))*(cos(w(k)*t)-1)-((g/w(k)**2)*sin(l)-m/w(k))*(sin(w(k)*t)+(g*t/w(k))*sin(l))
gnuplot> y(t, k) = b + ((g/w(k)**2)*sin(l)-m/w(k))*(cos(w(k)*t)-1)+(n/w(k))*sin(w(k)*t)
gnuplot> g = 7 ; l = 1
gnuplot> plot for[a=0:1] for[b=0:1] for[m=0:1] for[n=0:1] for[k=2:3] x(t,k), y(t,k) title sprintf("%d,%d,%d,%d,%d", a,b,n,m,k)