问:
java.lang.OutOfMemoryError - How do I fix this?
I am trying to implement paging in one activity but I keep running out of memory. The app runs till the 4th page but when it gets to the 5th it crashes. I've tried increasing the JVM heap size but the app still crashes at this one point where it runs out of memory to allocate.

This is my main file:

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

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

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.intro_panels);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
}

Intent intent = new Intent(S1Intro.this,S2CharacterIntro.class);

public void nextScreen(View view){
    startActivity(intent);
}
</code>```

This is the PageAdapter Class:

```<code>public class MyPagerAdapter extends PagerAdapter {

public int getCount() {
    return 5;
}

public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position) {
        case 0:
            resId = R.layout.s1a;
            break;
        case 1:
            resId = R.layout.s1b;
            break;
        case 2:
            resId = R.layout.s1c;
            break;
        case 3:
            resId = R.layout.s1d;
            break;
        case 4:
            resId = R.layout.s1e;
            break;
    }

    View view = inflater.inflate(resId, null);

    ((ViewPager) collection).addView(view, 0);

    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);

}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);

}

@Override
public Parcelable saveState() {
    return null;
}
</code>```

}

This is the 1st page's xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/a"/>
</LinearLayout>
</code>```

All the other pages are just like this with different drawables. Except the 5th page, which looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_screen2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.miniproject32.writeup.S1Intro">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/e"/>
<Button
    style="@style/buttonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button_s1"
    android:text="@string/start"
    android:onClick="nextScreen"/>
</RelativeLayout>
</code>```

This is the logcat:

```<code>03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.896 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 1003(75KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/89MB, paused 885us total 33.721ms
03-30 12:17:31.896 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.906 1139-1139/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.916 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 71(2848B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 823us total 17.333ms
03-30 12:17:31.916 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 498-498/? I/art: Alloc concurrent mark sweep GC freed 115(20KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.108ms
03-30 12:17:31.946 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:31.946 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.966 498-504/? W/art: Suspending all threads took: 19.805ms
03-30 12:17:31.966 498-498/? I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.434ms total 23.834ms
03-30 12:17:31.966 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.986 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 3(1264B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 915us total 10.620ms
03-30 12:17:31.986 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.986 612-612/? I/IntowowAdapter: not wifi, stop request intowow ad
03-30 12:17:31.996 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 10(320B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 13.458ms
03-30 12:17:31.996 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.026 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.068ms total 25.024ms
03-30 12:17:32.026 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:32.026 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.056 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.536ms
03-30 12:17:32.056 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:32.056 498-498/? D/skia: --- allocation failed for scaled bitmap
03-30 12:17:32.056 612-612/? I/KBattery: [PLACE] at com.ijinshan.kbatterydoctor.cloud.NewRemoteCloudConfigHelper.b(NewRemoteCloudConfigHelper.java:600)
                                     [NewRemoteCloudConfigHelper]isPackedNotification lastAid = 9
03-30 12:17:32.056 498-498/? E/InputEventReceiver: Exception dispatching input event.
03-30 12:17:32.066 498-498/? E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
03-30 12:17:32.086 612-612/? I/Choreographer: Skipped 81 frames!  The application may be doing too much work on its main thread.
03-30 12:17:32.096 498-498/? E/MessageQueue-JNI: java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                                 at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                 at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                 at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                                 at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                                 at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                                 at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                                 at android.widget.ImageView.<init>(ImageView.java:157)
                                                 at android.widget.ImageView.<init>(ImageView.java:145)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                                 at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                                 at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                                 at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                                 at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                                 at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                                 at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                                 at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                                 at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                                 at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                                 at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2827)
                                                a
03-30 12:17:32.096 498-498/? D/AndroidRuntime: Shutting down VM
03-30 12:17:32.106 498-498/? E/AndroidRuntime: FATAL EXCEPTION: main
                                           Process: com.miniproject32.writeup, PID: 498
                                           java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                               at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                               at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                               at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                               at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                               at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                               at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                               at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                               at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                               at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                               at android.widget.ImageView.<init>(ImageView.java:157)
                                               at android.widget.ImageView.<init>(ImageView.java:145)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                               at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                               at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                               at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                               at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                               at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                               at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                               at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                               at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                               at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                               at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                               at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                               at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                               at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                               at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                               at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                            at com.android.internal.policy.P
</code>```

How do I fix this? Please help

答:
You add this code android:largeHeap="true"  in your manifest.
Then, you can follow this step

Go to Run -> Run Configurations

Select project under maven build

Select tab "JRE"

Enter -Xmx1024m

Alternatively, you could do

Go to Run -> Run Configurations

Select tab "JRE"

Enter -Xmx1024m

This should increase the memory heap for all the builds/projects. You can optimize it the way you want.

Body:
I am trying to implement paging in one activity but I keep running out of memory. The app runs till the 4th page but when it gets to the 5th it crashes. I've tried increasing the JVM heap size but the app still crashes at this one point where it runs out of memory to allocate.

This is my main file:

public class S1Intro extends AppCompatActivity {

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

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.intro_panels);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
}

Intent intent = new Intent(S1Intro.this,S2CharacterIntro.class);

public void nextScreen(View view){
    startActivity(intent);
}

This is the PageAdapter Class:

public class MyPagerAdapter extends PagerAdapter {

public int getCount() {
    return 5;
}

public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position) {
        case 0:
            resId = R.layout.s1a;
            break;
        case 1:
            resId = R.layout.s1b;
            break;
        case 2:
            resId = R.layout.s1c;
            break;
        case 3:
            resId = R.layout.s1d;
            break;
        case 4:
            resId = R.layout.s1e;
            break;
    }

    View view = inflater.inflate(resId, null);

    ((ViewPager) collection).addView(view, 0);

    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);

}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);

}

@Override
public Parcelable saveState() {
    return null;
}

}

This is the 1st page's xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/a"/>
</LinearLayout>

All the other pages are just like this with different drawables. Except the 5th page, which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_screen2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.miniproject32.writeup.S1Intro">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/e"/>
<Button
    style="@style/buttonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button_s1"
    android:text="@string/start"
    android:onClick="nextScreen"/>
</RelativeLayout>

This is the logcat:

03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.896 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 1003(75KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/89MB, paused 885us total 33.721ms
03-30 12:17:31.896 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.906 1139-1139/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.916 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 71(2848B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 823us total 17.333ms
03-30 12:17:31.916 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 498-498/? I/art: Alloc concurrent mark sweep GC freed 115(20KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.108ms
03-30 12:17:31.946 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:31.946 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.966 498-504/? W/art: Suspending all threads took: 19.805ms
03-30 12:17:31.966 498-498/? I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.434ms total 23.834ms
03-30 12:17:31.966 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.986 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 3(1264B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 915us total 10.620ms
03-30 12:17:31.986 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.986 612-612/? I/IntowowAdapter: not wifi, stop request intowow ad
03-30 12:17:31.996 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 10(320B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 13.458ms
03-30 12:17:31.996 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.026 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.068ms total 25.024ms
03-30 12:17:32.026 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:32.026 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.056 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.536ms
03-30 12:17:32.056 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:32.056 498-498/? D/skia: --- allocation failed for scaled bitmap
03-30 12:17:32.056 612-612/? I/KBattery: [PLACE] at com.ijinshan.kbatterydoctor.cloud.NewRemoteCloudConfigHelper.b(NewRemoteCloudConfigHelper.java:600)
                                     [NewRemoteCloudConfigHelper]isPackedNotification lastAid = 9
03-30 12:17:32.056 498-498/? E/InputEventReceiver: Exception dispatching input event.
03-30 12:17:32.066 498-498/? E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
03-30 12:17:32.086 612-612/? I/Choreographer: Skipped 81 frames!  The application may be doing too much work on its main thread.
03-30 12:17:32.096 498-498/? E/MessageQueue-JNI: java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                                 at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                 at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                 at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                                 at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                                 at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                                 at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                                 at android.widget.ImageView.<init>(ImageView.java:157)
                                                 at android.widget.ImageView.<init>(ImageView.java:145)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                                 at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                                 at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                                 at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                                 at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                                 at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                                 at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                                 at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                                 at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                                 at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                                 at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2827)
                                                a
03-30 12:17:32.096 498-498/? D/AndroidRuntime: Shutting down VM
03-30 12:17:32.106 498-498/? E/AndroidRuntime: FATAL EXCEPTION: main
                                           Process: com.miniproject32.writeup, PID: 498
                                           java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                               at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                               at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                               at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                               at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                               at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                               at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                               at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                               at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                               at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                               at android.widget.ImageView.<init>(ImageView.java:157)
                                               at android.widget.ImageView.<init>(ImageView.java:145)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                               at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                               at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                               at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                               at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                               at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                               at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                               at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                               at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                               at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                               at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                               at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                               at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                               at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                               at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                               at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                            at com.android.internal.policy.P

How do I fix this? Please help


来源: stackexchange

问:
Binary Semaphore not working if release() comes before acquire()
I am writing a test code where i found if we put release() before acquire() then Binary Semaphore functionality is broken.

I checked and found more then one thread passes acquire() and increase the count to N where N is number of threads and thus contradicting binary semaphore.

```<code>import java.util.concurrent.Semaphore;

/**
 * Consider an ATM cubicle with 1 ATM, Semaphore can make sure only 1 person
 * can access simultaneously.
 *
 * Here if relese() comes before then this binary semaphore is not working.
 */
public class SemaphoreTest {

    // max 4 people
    static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {

        System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

        MyATMThread t1 = new MyATMThread("A",semaphore);
        t1.start();

        MyATMThread t2 = new MyATMThread("B",semaphore);
        t2.start();

        MyATMThread t3 = new MyATMThread("C",semaphore);
        t3.start();

        MyATMThread t4 = new MyATMThread("D",semaphore);
        t4.start();

        MyATMThread t5 = new MyATMThread("E",semaphore);
        t5.start();

        MyATMThread t6 = new MyATMThread("F",semaphore);
        t6.start();

    }
}

class MyATMThread extends Thread {

    String name = "";
    Semaphore semaphore = null;

    MyATMThread(String name,Semaphore s) {
        this.name = name;
        this.semaphore=s;
    }

    public void run() {

        try {

            System.out.println(name + " : acquiring lock...");
            System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());
            semaphore.release();
            semaphore.acquire();
            System.out.println(name + " : got the permit!");

            try {

                for (int i = 1; i <= 5; i++) {

                    System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : "
                            + semaphore.availablePermits());

                    // sleep 1 second
                    Thread.sleep(1000);

                }

            } finally {

                // calling release() after a successful acquire()
                System.out.println(name + " : releasing lock...");
                semaphore.release();
                System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());

            }

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}
</code>```

Can some one explain this behavior ?

答:
Yes, you're writing broken code (at least by your expectations) by releasing (increasing permits) before acquiring. This is perfectly valid, but if you intend to have a single permit, you shouldn't be increasing them by calling release() before acquire().

Semaphore allows you to increase the permits beyond what was given as the initial amount. This can be used for example throttling. Worker threads will do acquire()/release() and a throttler will decrease/increase permits depending on some logic.

ContentLicense: CC BY-SA 3.0

Body:
I am writing a test code where i found if we put release() before acquire() then Binary Semaphore functionality is broken.

I checked and found more then one thread passes acquire() and increase the count to N where N is number of threads and thus contradicting binary semaphore.

import java.util.concurrent.Semaphore;

/**
 * Consider an ATM cubicle with 1 ATM, Semaphore can make sure only 1 person
 * can access simultaneously.
 *
 * Here if relese() comes before then this binary semaphore is not working.
 */
public class SemaphoreTest {

    // max 4 people
    static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {

        System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

        MyATMThread t1 = new MyATMThread("A",semaphore);
        t1.start();

        MyATMThread t2 = new MyATMThread("B",semaphore);
        t2.start();

        MyATMThread t3 = new MyATMThread("C",semaphore);
        t3.start();

        MyATMThread t4 = new MyATMThread("D",semaphore);
        t4.start();

        MyATMThread t5 = new MyATMThread("E",semaphore);
        t5.start();

        MyATMThread t6 = new MyATMThread("F",semaphore);
        t6.start();

    }
}

class MyATMThread extends Thread {

    String name = "";
    Semaphore semaphore = null;

    MyATMThread(String name,Semaphore s) {
        this.name = name;
        this.semaphore=s;
    }

    public void run() {

        try {

            System.out.println(name + " : acquiring lock...");
            System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());
            semaphore.release();
            semaphore.acquire();
            System.out.println(name + " : got the permit!");

            try {

                for (int i = 1; i <= 5; i++) {

                    System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : "
                            + semaphore.availablePermits());

                    // sleep 1 second
                    Thread.sleep(1000);

                }

            } finally {

                // calling release() after a successful acquire()
                System.out.println(name + " : releasing lock...");
                semaphore.release();
                System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());

            }

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}

Can some one explain this behavior ?


问:
Dynamically create sql where condition on textbox entry
I am working on a C# desktop application. I want to create a search functionality. Now the problem is that i am using around 8 textboxes. Different permutations of textboxes could be populated and the resulting 'sql where' condition should only include those textboxes values which are not null. Now one pathetic way is to use a zillion 'if and else' which obviously is laborious. Any other way to do this?</p>

答:
I would like to make a point of first checking is the paramtere null, then use it to compare with column values.

Since you are generating query in C#, try old-Chinese approach from Ming period of using default condition where 1=1 just to avoid checking did you already had first condition :)

```<code>string query = "select ... from ... join ... on ... where 1=1";
//suposedly you have value of one search box in variable called "item_name"
if(string.IsNullOrWhiteSpace(item_name) == false)
{
  query += " and Order_Line.Name ='" + item_name + "'";
}
</code>```

and so on for other fields.

What you are trying to do in order to avoid ifs is not really a good approach. Look at this:

```<code>string query = " select ... where Order_Line.Name = '" + item_name + "'";
</code>```

What will be the resulting string if item_name is actually null?

EDIT: the resulting query would be

```<code>where Order_Line.Name = '' or Order_Line.Name is null
</code>```

which is not what you want. You want every row if that search field is empty, menaing it shouldn't have anu effect on search. That's why you need condition to see will you include this column in where clause in the first place.

Body:
I would like to make a point of first checking is the paramtere null, then use it to compare with column values.

Since you are generating query in C#, try old-Chinese approach from Ming period of using default condition where 1=1 just to avoid checking did you already had first condition :)

string query = "select ... from ... join ... on ... where 1=1";
//suposedly you have value of one search box in variable called "item_name"
if(string.IsNullOrWhiteSpace(item_name) == false)
{
  query += " and Order_Line.Name ='" + item_name + "'";
}

and so on for other fields.

What you are trying to do in order to avoid ifs is not really a good approach. Look at this:

string query = " select ... where Order_Line.Name = '" + item_name + "'";

What will be the resulting string if item_name is actually null?

EDIT: the resulting query would be

where Order_Line.Name = '' or Order_Line.Name is null

which is not what you want. You want every row if that search field is empty, menaing it shouldn't have anu effect on search. That's why you need condition to see will you include this column in where clause in the first place.


问:
How to run Shell in background from controller and update database on execution in CakePHP
I am working on CakePHP 3.4 project.

I have to execute some command to scan through the files and directories of a particular directory.
This might take long time depending on the size of the directory, therefore I want to run it in background and mark running label in view until it executed successfully.

How can I run a Shell Task in the background from Controller and update database on execution?

I'm new to Shell tasks.

答:
You can dispatch a Shell task from the controller. If you want to run this in the background you could, for example, run this controller action via JavaScript/Ajax.

```<code>// maybe this task runs looooong
set_time_limit(0);

$shell = new ShellDispatcher();
$output = $shell->run(['cake', 'bake', 'model', 'Products']);

if ($output === 0) {
    $this->Flash->success('Yep!');
} else {
    $this->Flash->error('Nope!');
}
</code>```

But you could indeed have googled this at least. ;-)

EDIT Forget this one, go for drmonkeyninja’s answer.

Body:
You can dispatch a Shell task from the controller. If you want to run this in the background you could, for example, run this controller action via JavaScript/Ajax.

// maybe this task runs looooong
set_time_limit(0);

$shell = new ShellDispatcher();
$output = $shell->run(['cake', 'bake', 'model', 'Products']);

if ($output === 0) {
    $this->Flash->success('Yep!');
} else {
    $this->Flash->error('Nope!');
}

But you could indeed have googled this at least. ;-)

EDIT Forget this one, go for drmonkeyninja’s answer.


问:
No resource found that matches the given name 'MaterialTheme'
i added
circleimageview-2.1.0 glide-3.7.0 google-material-typeface-3.0.1.0.original materialdrawer-5.8.2 to dependencies.

This's my buid.gradle :

```<code>compile 'com.android.support:appcompat-v7:25.2.0'
testCompile 'junit:junit:4.12'
compile project(':circleimageview-2.1.0')
compile project(':glide-3.7.0')
compile project(':google-material-typeface-3.0.1.0.original')
compile project(':materialdrawer-5.8.2')
</code>```

Here's my error's:

答:
If you have Android Studio : link
Or Xamarin                 : link

Try this examples and watch out for the syntax of it.

Body:
i added
circleimageview-2.1.0 glide-3.7.0 google-material-typeface-3.0.1.0.original materialdrawer-5.8.2 to dependencies.

This's my buid.gradle :

compile 'com.android.support:appcompat-v7:25.2.0'
testCompile 'junit:junit:4.12'
compile project(':circleimageview-2.1.0')
compile project(':glide-3.7.0')
compile project(':google-material-typeface-3.0.1.0.original')
compile project(':materialdrawer-5.8.2')

Here's my error's:


问:
Python subprocess Popen parameter difference
What's the difference between

```<code>subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)
</code>```

and

```<code>subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)
</code>```

?
I'm doing this in ipython.
For the first one, ipython just hang. Maybe not hang, but it's significantly slower.
The second is just OK.

Just don't know why.

答:
The first one is actually only running cat (because of the way that the command is parsed if you use shell = True), and thus hanging because it's waiting for input.  The second one is running cat /path/to/file.  You can see this by doing:

```<code>>>> subprocess.Popen(['ls', '-l'])
<subprocess.Popen object at 0x10048bdd0>
>>> total 8
-rw-------  1 root     wheel  652 Nov 29 09:07 000d94cfc78b4
srwxr-xr-x  1 nbastin  wheel    0 Nov 29 09:06 ics179
srwxr-xr-x  1 nbastin  wheel    0 Nov 29 09:06 icssuis501
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launch-3ZniHd
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launch-8QRgz2
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launch-M5ppWp
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launchd-137.ztQAmI
drwx------  2 nbastin  wheel   68 Nov 29 09:57 ssh-LreGlOZPAR
</code>```

Versus doing it with shell = True:

```<code>>>> subprocess.Popen(['ls', '-l'], shell = True)
<subprocess.Popen object at 0x10048bd90>
>>> 000d94cfc78b4       ics179          icssuis501      launch-3ZniHd       launch-8QRgz2       launch-M5ppWp       launchd-137.ztQAmI  ssh-LreGlOZPAR
</code>```

If you set shell = True, passing a list as args won't get you the behaviour you want - you need to pass a string.

Body:
What's the difference between

subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)

and

subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)

?
I'm doing this in ipython.
For the first one, ipython just hang. Maybe not hang, but it's significantly slower.
The second is just OK.

Just don't know why.

Body:
The first one is actually only running cat (because of the way that the command is parsed if you use shell = True), and thus hanging because it's waiting for input.  The second one is running cat /path/to/file.  You can see this by doing:

>>> subprocess.Popen(['ls', '-l'])
<subprocess.Popen object at 0x10048bdd0>
>>> total 8
-rw-------  1 root     wheel  652 Nov 29 09:07 000d94cfc78b4
srwxr-xr-x  1 nbastin  wheel    0 Nov 29 09:06 ics179
srwxr-xr-x  1 nbastin  wheel    0 Nov 29 09:06 icssuis501
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launch-3ZniHd
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launch-8QRgz2
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launch-M5ppWp
drwx------  3 nbastin  wheel  102 Nov 29 09:06 launchd-137.ztQAmI
drwx------  2 nbastin  wheel   68 Nov 29 09:57 ssh-LreGlOZPAR

Versus doing it with shell = True:

>>> subprocess.Popen(['ls', '-l'], shell = True)
<subprocess.Popen object at 0x10048bd90>
>>> 000d94cfc78b4       ics179          icssuis501      launch-3ZniHd       launch-8QRgz2       launch-M5ppWp       launchd-137.ztQAmI  ssh-LreGlOZPAR

If you set shell = True, passing a list as args won't get you the behaviour you want - you need to pass a string.

ContentLicense: CC BY-SA 2.5


问:
Find the previous element in other TR, finding it only by class name
I need when I click on a button to find the nearest TD with a class name searching it in back.

I'll try to be more specific:

My code is:

    LATO A

 Efficency

70%

 Real time efficency

98%

   A
   1
   1
   Lorem ipsum

   70%
   96%

   <input type="checkbox" />

   2
   Lorem ipsum

   87%
   77%

   <input type="checkbox" />

   2
   3
   Lorem ipsum

   93%
   88%

   <input type="checkbox" />

   B
   1
   1
   Lorem ipsum

   98%
   83%

   <input type="checkbox" />

   2
   Lorem ipsum

   83%
   98%

   <input type="checkbox" />

```

Clicking on some "TD" with class ".toClick" , i need to find the first previuos element with class "matriceTR".

I've tried this:

$('table .toClick').click(function() {

  $(this).parents().find('.matriceTR:first') })

but isn't the correct solution.
Help please :)

答:
$(".toClick").click(function(){

alert($(this).siblings(".matriceTR").text())
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class="latoTR" rowspan="5">
        LATO A<br><br> Efficency
        <br>
        <div class="modale">70%</div><br><br> Real time efficency<br>
        <div class="modale">98%</div>
      </td>
      <td class="matriceTR" rowspan="3">A</td>
      <td class="rigaTR" rowspan="2">1</td>
      <td>1</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledGreen"></i></td>
      <td>70%</td>
      <td>96%</td>
      <td class="toClick"><i class="fa fa-caret-down">click me</i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart01" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledYellow"></i></td>
      <td>87%</td>
      <td>77%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart02" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td>3</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledRed"></i></td>
      <td>93%</td>
      <td>88%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart03" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td class="matriceTR" rowspan="2">B</td>
      <td class="rigaTR" rowspan="2">1</td>
      <td>1</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledGreen"></i></td>
      <td>98%</td>
      <td>83%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart04" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledRed"></i></td>
      <td>83%</td>
      <td>98%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart05" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
  </tbody>
</table></code>```

use .siblings()

Body:
I need when I click on a button to find the nearest TD with a class name searching it in back.

I'll try to be more specific:

My code is:

    LATO A

 Efficency

70%

 Real time efficency

98%

   A
   1
   1
   Lorem ipsum

   70%
   96%

   <input type="checkbox" />

   2
   Lorem ipsum

   87%
   77%

   <input type="checkbox" />

   2
   3
   Lorem ipsum

   93%
   88%

   <input type="checkbox" />

   B
   1
   1
   Lorem ipsum

   98%
   83%

   <input type="checkbox" />

   2
   Lorem ipsum

   83%
   98%

   <input type="checkbox" />

Clicking on some "TD" with class ".toClick" , i need to find the first previuos element with class "matriceTR".

I've tried this:

$('table .toClick').click(function() {

  $(this).parents().find('.matriceTR:first') })

but isn't the correct solution.
Help please :)

Body:
$(".toClick").click(function(){

alert($(this).siblings(".matriceTR").text())
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class="latoTR" rowspan="5">
        LATO A<br><br> Efficency
        <br>
        <div class="modale">70%</div><br><br> Real time efficency<br>
        <div class="modale">98%</div>
      </td>
      <td class="matriceTR" rowspan="3">A</td>
      <td class="rigaTR" rowspan="2">1</td>
      <td>1</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledGreen"></i></td>
      <td>70%</td>
      <td>96%</td>
      <td class="toClick"><i class="fa fa-caret-down">click me</i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart01" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledYellow"></i></td>
      <td>87%</td>
      <td>77%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart02" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td>3</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledRed"></i></td>
      <td>93%</td>
      <td>88%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart03" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td class="matriceTR" rowspan="2">B</td>
      <td class="rigaTR" rowspan="2">1</td>
      <td>1</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledGreen"></i></td>
      <td>98%</td>
      <td>83%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart04" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
    <tr>
      <td>2</td>
      <td>Lorem ipsum</td>
      <td><i class="fa fa-circle ledRed"></i></td>
      <td>83%</td>
      <td>98%</td>
      <td class="toClick"><i class="fa fa-caret-down"></i></td>
      <td><input type="checkbox" /></td>
    </tr>
    <tr class="toHide">
      <td colspan="7">
        <div class="col-md-6">

        </div>
        <div class="col-md-6">
          <div id="pieChart05" class="pieChartCSS" style="height:250px;"></div>
        </div>
      </td>
    </tr>
  </tbody>
</table>

use .siblings()


问:
Methods of testing Simplex (Linear Programming) calculation output
I have been tasked with created a web-based machine for solving real-world issues using Linear Programming techniques, specifically at present, Danzig's Simplex Method. With this in mind I've found a rather nifty bit of C++ code that calculates the results, and with some considerable speed even on this particularly low-end machine.

However, I currently have nothing other than the console output itself attesting the result to be anywhere close to the correct solution for the given problem. Which is an issue if people are being asked to trust the result as being indicative of anything significantly more important than that some digits can be made to flash up on a computer screen.

I will spare you from the full details of the entire program, as it's fairly long, but here's the function responsible for taking the data, just for reference:

```<code>void Data() {
    double R1, R2;
    char R;
    int I, J;
    printf("\n LINEAR PROGRAMMING\n\n");
    printf(" MAXIMIZE (Y/N) ? "); scanf("%c", &R);
    printf("\n NUMBER OF VARIABLES OF ECONOMIC FUNCTION ? "); scanf("%d", &NV);
    printf("\n NUMBER OF CONSTRAINTS ? "); scanf("%d", &NC);
    if (R == 'Y' || R == 'y')
        R1 = 1.0;
    else
        R1 = -1.0;
    printf("\n INPUT COEFFICIENTS OF ECONOMIC FUNCTION:\n");
    for (J = 1; J <= NV; J++) {
        printf("       #%d ? ", J); scanf("%lf", &R2);
        TS[1][J + 1] = R2 * R1;
    }
    printf("       Right hand side ? "); scanf("%lf", &R2);
    TS[1][1] = R2 * R1;
    for (I = 1; I <= NC; I++) {
        printf("\n CONSTRAINT #%d:\n", I);
        for (J = 1; J <= NV; J++) {
            printf("       #%d ? ", J); scanf("%lf", &R2);
            TS[I + 1][J + 1] = -R2;
        }
        printf("       Right hand side ? "); scanf("%lf", &TS[I + 1][1]);
    }
    printf("\n\n RESULTS:\n\n");
    for (J = 1; J <= NV; J++)  TS[0][J + 1] = J;
    for (I = NV + 1; I <= NV + NC; I++)  TS[I - NV + 1][0] = I;
}
</code>```

I can also include the pivot table, formulation and optimisation functions if need be.

I would like to ask for specific techniques which might be employed to ensure that, given a set of coefficients and constraints, the C++ program returns the economic function correctly (I'll have to implement additional checking stages later when the data gets output to the web, but I'll cross that bridge when I come to it).

(For reasons of attribution, I note that the above code was created by Jean-Pierre Moreau in 1982. Coincidentally, 1982 happens to be my birth year, but that's probably not important right now.)

答: Proving the optimality of a solution to a linear programming problem is actually fairly easy. You need to check the solution for both primal and dual feasibility. This concept of duality is explained in any work about the simplex method or linear programming in general. For starters: https://en.wikipedia.org/wiki/Linear_programming</p>

Body:
I have been tasked with created a web-based machine for solving real-world issues using Linear Programming techniques, specifically at present, Danzig's Simplex Method. With this in mind I've found a rather nifty bit of C++ code that calculates the results, and with some considerable speed even on this particularly low-end machine.

However, I currently have nothing other than the console output itself attesting the result to be anywhere close to the correct solution for the given problem. Which is an issue if people are being asked to trust the result as being indicative of anything significantly more important than that some digits can be made to flash up on a computer screen.

I will spare you from the full details of the entire program, as it's fairly long, but here's the function responsible for taking the data, just for reference:

void Data() {
    double R1, R2;
    char R;
    int I, J;
    printf("\n LINEAR PROGRAMMING\n\n");
    printf(" MAXIMIZE (Y/N) ? "); scanf("%c", &R);
    printf("\n NUMBER OF VARIABLES OF ECONOMIC FUNCTION ? "); scanf("%d", &NV);
    printf("\n NUMBER OF CONSTRAINTS ? "); scanf("%d", &NC);
    if (R == 'Y' || R == 'y')
        R1 = 1.0;
    else
        R1 = -1.0;
    printf("\n INPUT COEFFICIENTS OF ECONOMIC FUNCTION:\n");
    for (J = 1; J <= NV; J++) {
        printf("       #%d ? ", J); scanf("%lf", &R2);
        TS[1][J + 1] = R2 * R1;
    }
    printf("       Right hand side ? "); scanf("%lf", &R2);
    TS[1][1] = R2 * R1;
    for (I = 1; I <= NC; I++) {
        printf("\n CONSTRAINT #%d:\n", I);
        for (J = 1; J <= NV; J++) {
            printf("       #%d ? ", J); scanf("%lf", &R2);
            TS[I + 1][J + 1] = -R2;
        }
        printf("       Right hand side ? "); scanf("%lf", &TS[I + 1][1]);
    }
    printf("\n\n RESULTS:\n\n");
    for (J = 1; J <= NV; J++)  TS[0][J + 1] = J;
    for (I = NV + 1; I <= NV + NC; I++)  TS[I - NV + 1][0] = I;
}

I can also include the pivot table, formulation and optimisation functions if need be.

I would like to ask for specific techniques which might be employed to ensure that, given a set of coefficients and constraints, the C++ program returns the economic function correctly (I'll have to implement additional checking stages later when the data gets output to the web, but I'll cross that bridge when I come to it).

(For reasons of attribution, I note that the above code was created by Jean-Pierre Moreau in 1982. Coincidentally, 1982 happens to be my birth year, but that's probably not important right now.)


问:
SceneKit game architecture
I am trying to design an architecture for a SceneKit iOS game. I've shown below two rough high level object diagrams/graphs of my current preferred ideas.

I am only looking at the high level architecture at the moment, i.e. managing transition between Menu/GameLevel/Config/Paused app states and making the app data-driven, so that it can handle multiple levels, etc. Once I get this working, then I'll address lower level architecture, e.g. for the GameLevel state I'll have a GameLevelModel object to represent an actual game level logic.

Would be great to hear which one looks more promising, any obvious pitfalls or things to avoid?

Version A) MVC based, with Custom Container & Nested VCs

I'm trying to stay close to the MVC paradigm with this version.

The behaviour of the app changes significantly between its different states (Menu/GameLevel/Config/etc) so I'll be using a permanent container view controller that will manage/transition between several nested VCs, in a parent-child relationship as per Apple's "View Controller Programming Guide for iOS". These will be effectively entire MVCs.

Because none of Apple's container controllers (UINavigation-, UISplitScreen-, UITabBar-) are suitable (I need the entire screen) I'll have a custom container VC (RootViewController) that will have one nested child VC at all times. The View of each child VC will be fully covering the container's one at all times. The transition between child VCs will be managed by the RootVC and driven by its StateMachine.

Each child VC (effectively entire MVC) is created each time when its corresponding state becomes current and then deallocated when it is replaced with next state's one and no longer needed. Similar to how UINavigationController deals with it's contained VCs.

My only worry with this architecture is that it seems a bit heavy. SceneKit looks like it's designed to work with a single SCNView and to transition between multiple SCNScenes when we need to change the 3D content. This gives more transition options as well.

```<code>                         --------------------------
                         |   RootViewController   |
                         --------------------------
                           |  |   |        |    |
     ------------------    |  |   |        |    |      ------------------
     | GameLevelsData |-----  |   |        |    -------|     SCNView    |
     ------------------       |   |        |           ------------------
     ------------------       |   |        |
     |   PlayerData   |--------   |        |
     ------------------           |        |
                                  |        |
                       ----------------    |
                       | StateMachine |    |
                       ----------------    |
                         |                 |
                         |-(*MenuState)    |
                         |-(LevelState)    |
                         |-(ConfigState)   |
                                           |
                                           |
                         ------------------------
                         |  MenuViewController  |
                         ------------------------
      -----------------     |                |      ------------------
      |   MenuData    |------                -------|  MenuSCNView   |
      -----------------                             ------------------

   (child VCs for other States, Level-/Config-/etc are created as needed)
                                           |
                         ------------------------
                         |  LevelViewController |
                         ------------------------
     ------------------     |                |      ------------------
     | GameLevelModel |------                -------|  LevelSCNView  |
     ------------------                             ------------------
</code>```

Version B) Scene-based (one VC, multiple Scenes)

I'll have only one View Controller (GameViewController) with its View (SCNView) and they will last for the entire app lifecycle.
(I will not have container and nested VCs here.)

The change in behaviour and content between app states (Menu/GameLevel/Config/etc) is achieved by the only View transitioning between Scenes and different TouchHandlers (UIResponder subclasses for each state) given First Responder status when relevant.

The (Menu-, GameLevel-, etc) TouchHandler classes will only override touchesBegan/Moved/Ended and canBecomeFirstResponder so that I can intercept touch events without bloating the single controller and view. None of my other objects are UIResponders. I've not tested exactly this part yet.

With each app state the required objects for that state will be created, like corresponding Scene, TouchHandler, (GameLevelModel with game level logic when in GameLevelState), etc and deallocated when next state is entered.

My current issue with this one is, that when using SKTransition to transition between multile SCNScenes on the single SCNView, after 5-20 transitions there is memory leakage. I tried resolving by simplifying the scene, removing all actions, nodes before deallocating but nothing helps. The only way to avoid leakage is avoiding SKTransition and directly assigning scenes to the View's scene property scnView.scene = scnScene. So this will require me to animate my own transitions.

```<code>                         --------------------------
                         |   GameViewController   |
                         --------------------------
                           |  |   |             |
     ------------------    |  |   |             |      ------------------
     | GameLevelsData |-----  |   |             -------|     SCNView    |
     ------------------       |   |                    ------------------
     ------------------       |   |                            |
     |   PlayerData   |--------   |                            |
     ------------------           |                            |
                                  |                            |
                       ----------------                        |
                       | StateMachine |                        |
                       ----------------                        |
                         |                            ------------------
                         |-(*MenuState)---------      |  MenuSCNScene  |
                         |-(LevelState)     |  |      ------------------
                         |-(ConfigState)    |  |
                                            |  |
                     --------------------   |  |
                     | MenuTouchHandler |---|  |
                     --------------------      |
                      -----------------        |
                      |   MenuData    |---------
                      -----------------

              (When entering, each state creates objects of corresponding
              dedicated subclasses for its Model, TouchHandler and Scene)
                                            |  |              |
                    --------------------    |  |     -------------------
                    | LevelTouchHandler |---|  |     |  LevelSCNScene  |
                    --------------------       |     -------------------
                     ------------------        |
                     | GameLevelModel |---------
                     ------------------
</code>```

Thanks in advance.

答:
I will explain a real game design that I am actually working on and was based on the design of the sample codes provided by Apple for SceneKit.

As @HalMuelller correctly points out, you need to extract the game logic into a platform independent layer, and that is a good idea even if you are writing the game for one platform as that will help you in testing.

As you can see in the class diagram above:

On the right side is the entire game logic starting with a Game class which actually works as the scene and physics delegate. This is just a plain old ObjC or Swift class.

One of the main responsibility of the Game class is to build scenes SCNScene either from files supported by SceneKit/Model IO or programmatically as your case may be.

The Game class also refers to other Model classes such as Animation which loads 3D skeletal animations and Player class which contains the player data such as his statistics, the Player in here refers to some player like a baseball player in the game.

You can also see that there is a PlayerEntity class which is made up of BatterComponent, this is based off the Entity-Component design from GamePlayKit. Now the BatterComponent has a StateMachine which handles the batter's transitions between various states.

The other important component is BatterControlComponent which you add to the entity only when the user is batting. This is also a platform dependent component, so you can write this independently in your macOs/iOS targets. Again the batter control component is backed by a state machine as State machine can also be used for handling controls transitions. This control is implemented as a SpriteKit scene as an overlay on top of the SCNScene.

If you are pitching, then you configure the player entity with the PitcherComponent backed by another state machine and so on.

On the left side of the class diagram, you can see sits a GameViewController which sets up an SCNView and also instantiates a Game object and this game object's scene is what your game view controllers scene view renders. You also ensure that you set the scene view delegate to be the game object.

You must seriously refer to the Apple sample codes for SceneKit and the samples for GameKit. In Apple developer, Sample Code section search for: SceneKit and GameplayKit.

Overall you must design a platform independent game logic layer using plain old Swift/ObjC classes and the appropriate patterns from GamePlayKit based on your game requirements.

A note on production usage. See this memory leak issue and animation issues, so I am not really sure if SceneKit is yet ready for prime time, but Google is your friend. Having said that, SceneKit is really great if you are already working on Apple platform so the turn around time vis a vis learning a new game engine is lesser if you have not used any game engine and are writing games as a hobby or to learn game programming. I believe that SceneKit has been improving every year and in the next 2 releases (WWDC 17, 18) it should be a really  polished game engine for Apple platforms. These are my 2$ based on my experience, YMMV.

Title: SceneKit game architecture

Body:
I am trying to design an architecture for a SceneKit iOS game. I've shown below two rough high level object diagrams/graphs of my current preferred ideas.

I am only looking at the high level architecture at the moment, i.e. managing transition between Menu/GameLevel/Config/Paused app states and making the app data-driven, so that it can handle multiple levels, etc. Once I get this working, then I'll address lower level architecture, e.g. for the GameLevel state I'll have a GameLevelModel object to represent an actual game level logic.

Would be great to hear which one looks more promising, any obvious pitfalls or things to avoid?

Version A) MVC based, with Custom Container & Nested VCs

I'm trying to stay close to the MVC paradigm with this version.

The behaviour of the app changes significantly between its different states (Menu/GameLevel/Config/etc) so I'll be using a permanent container view controller that will manage/transition between several nested VCs, in a parent-child relationship as per Apple's "View Controller Programming Guide for iOS". These will be effectively entire MVCs.

Because none of Apple's container controllers (UINavigation-, UISplitScreen-, UITabBar-) are suitable (I need the entire screen) I'll have a custom container VC (RootViewController) that will have one nested child VC at all times. The View of each child VC will be fully covering the container's one at all times. The transition between child VCs will be managed by the RootVC and driven by its StateMachine.

Each child VC (effectively entire MVC) is created each time when its corresponding state becomes current and then deallocated when it is replaced with next state's one and no longer needed. Similar to how UINavigationController deals with it's contained VCs.

My only worry with this architecture is that it seems a bit heavy. SceneKit looks like it's designed to work with a single SCNView and to transition between multiple SCNScenes when we need to change the 3D content. This gives more transition options as well.

                         --------------------------
                         |   RootViewController   |
                         --------------------------
                           |  |   |        |    |
     ------------------    |  |   |        |    |      ------------------
     | GameLevelsData |-----  |   |        |    -------|     SCNView    |
     ------------------       |   |        |           ------------------
     ------------------       |   |        |
     |   PlayerData   |--------   |        |
     ------------------           |        |
                                  |        |
                       ----------------    |
                       | StateMachine |    |
                       ----------------    |
                         |                 |
                         |-(*MenuState)    |
                         |-(LevelState)    |
                         |-(ConfigState)   |
                                           |
                                           |
                         ------------------------
                         |  MenuViewController  |
                         ------------------------
      -----------------     |                |      ------------------
      |   MenuData    |------                -------|  MenuSCNView   |
      -----------------                             ------------------

   (child VCs for other States, Level-/Config-/etc are created as needed)
                                           |
                         ------------------------
                         |  LevelViewController |
                         ------------------------
     ------------------     |                |      ------------------
     | GameLevelModel |------                -------|  LevelSCNView  |
     ------------------                             ------------------

Version B) Scene-based (one VC, multiple Scenes)

I'll have only one View Controller (GameViewController) with its View (SCNView) and they will last for the entire app lifecycle.
(I will not have container and nested VCs here.)

The change in behaviour and content between app states (Menu/GameLevel/Config/etc) is achieved by the only View transitioning between Scenes and different TouchHandlers (UIResponder subclasses for each state) given First Responder status when relevant.

The (Menu-, GameLevel-, etc) TouchHandler classes will only override touchesBegan/Moved/Ended and canBecomeFirstResponder so that I can intercept touch events without bloating the single controller and view. None of my other objects are UIResponders. I've not tested exactly this part yet.

With each app state the required objects for that state will be created, like corresponding Scene, TouchHandler, (GameLevelModel with game level logic when in GameLevelState), etc and deallocated when next state is entered.

My current issue with this one is, that when using SKTransition to transition between multile SCNScenes on the single SCNView, after 5-20 transitions there is memory leakage. I tried resolving by simplifying the scene, removing all actions, nodes before deallocating but nothing helps. The only way to avoid leakage is avoiding SKTransition and directly assigning scenes to the View's scene property scnView.scene = scnScene. So this will require me to animate my own transitions.

                         --------------------------
                         |   GameViewController   |
                         --------------------------
                           |  |   |             |
     ------------------    |  |   |             |      ------------------
     | GameLevelsData |-----  |   |             -------|     SCNView    |
     ------------------       |   |                    ------------------
     ------------------       |   |                            |
     |   PlayerData   |--------   |                            |
     ------------------           |                            |
                                  |                            |
                       ----------------                        |
                       | StateMachine |                        |
                       ----------------                        |
                         |                            ------------------
                         |-(*MenuState)---------      |  MenuSCNScene  |
                         |-(LevelState)     |  |      ------------------
                         |-(ConfigState)    |  |
                                            |  |
                     --------------------   |  |
                     | MenuTouchHandler |---|  |
                     --------------------      |
                      -----------------        |
                      |   MenuData    |---------
                      -----------------

              (When entering, each state creates objects of corresponding
              dedicated subclasses for its Model, TouchHandler and Scene)
                                            |  |              |
                    --------------------    |  |     -------------------
                    | LevelTouchHandler |---|  |     |  LevelSCNScene  |
                    --------------------       |     -------------------
                     ------------------        |
                     | GameLevelModel |---------
                     ------------------

Thanks in advance.


问:
Javascript question: about variable definition
I have no idea why it didn't work if I specify a variable with 'var':
like this:

```<code>var mytool = function(){
      return {
         method: function(){}
     }
}();
</code>```

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

```<code>     mytool = function(){
          return {
             method: function(){}
         }
    }();
</code>```

Then it works.

答: The code you have doesn't show enough to demonstrate the problem. var makes the variable being defined 'local' so it will only be available within the same function (javascript has function level scoping). Not using var makes it global, this is almost always not what you want. You might need to rearrange your code to fix the scope issues.

Body:
I have no idea why it didn't work if I specify a variable with 'var':
like this:

var mytool = function(){
      return {
         method: function(){}
     }
}();

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

     mytool = function(){
          return {
             method: function(){}
         }
    }();

Then it works.


问:
Python file reading and writing is not working
I am making a game for Python and in it there is code to write to a file the answer for when I am running it myself to prevent myself having to actually play the game.
I have already coded for writing and reading a file which works fine, but for the cheat .txt file, printing its contents returns only [].

Here's a shortened example of what is happening.

```<code>file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
text = file.readlines()
print(text)
[]
file.close()

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "r+")
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']
</code>```

It appears now on a network machine that the a+ does not work, but r+. I fully understand the functionality of each mode, but can anyone suggest why it cannot read (or write, which returns the argument's length) when in a+ mode?

Note a+ is the required mode as it needs to be appended to the file.

Edit: as I am typing file.write(), the small box assisting you apply arguments reads 'See source or doc'.

答:
Take a look at opening modes (python uses same modes as C fopen) http://www.manpagez.com/man/3/fopen/

```<code> ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate to zero length or create text file for writing.  The
         stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.
</code>```

You can clearly see in descrpition of 'a+' mode that stream is positioned at the end of the file. So at this point if you perform reading it wil lcontinue from current position (end of the file), and thus your output.

To have proper output in this case you can use file.seek() function like this:

```<code>with open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+") as file:
    file.seek(0)
    text = file.readlines()
    print(text)

['actual output']
</code>```

Body:
I am making a game for Python and in it there is code to write to a file the answer for when I am running it myself to prevent myself having to actually play the game.
I have already coded for writing and reading a file which works fine, but for the cheat .txt file, printing its contents returns only [].

Here's a shortened example of what is happening.

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+")
text = file.readlines()
print(text)
[]
file.close()

file = open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "r+")
text = file.readlines()
print(text)
['xcfghujiosdfnonoooooowhello']

It appears now on a network machine that the a+ does not work, but r+. I fully understand the functionality of each mode, but can anyone suggest why it cannot read (or write, which returns the argument's length) when in a+ mode?

Note a+ is the required mode as it needs to be appended to the file.

Edit: as I am typing file.write(), the small box assisting you apply arguments reads 'See source or doc'.

Body:
Take a look at opening modes (python uses same modes as C fopen) http://www.manpagez.com/man/3/fopen/

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate to zero length or create text file for writing.  The
         stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

You can clearly see in descrpition of 'a+' mode that stream is positioned at the end of the file. So at this point if you perform reading it wil lcontinue from current position (end of the file), and thus your output.

To have proper output in this case you can use file.seek() function like this:

with open("E:\\ICT and Computer Science\\Python\\GCSE\\cheat.txt", "a+") as file:
    file.seek(0)
    text = file.readlines()
    print(text)

['actual output']


问:
PHPMailer sent message, but returned CLIENT/SERVER dialog to browser
So I've searched Google and Stackoverflow and I'm a bit surprised I could not find this problem.

I'm using XAMPP/localhost and PHPmailer sending an email to my yahoo account using my gmail email account.  Everything worked perfectly with the email being send and received, including a sample attachment.

The problem is my browser is displaying what appears to be a dialog of the SERVER/CLIENT for each step of the behind the scene processing just before the "Sent successful" message.

Sample output here:

```<code>2014-02-04 05:44:36 SERVER -> CLIENT: 220 mx.google.com
ESMTP xv2sm62192389pbb.39 - gsmtp
2014-02-04 05:44:36 CLIENT -> SERVER: EHLO localhost
2014-02-04 05:44:36 SERVER -> CLIENT: 250-mx.google.com at your service, [171.6.91.113] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN 250-ENHANCEDSTATUSCODES 250 CHUNKING
2014-02-04 05:44:36 CLIENT -> SERVER: AUTH LOGIN
2014-02-04 05:44:36 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2014-02-04 05:44:36 CLIENT -> SERVER: a2hyZng0NDRAZ21haWwuY29t
2014-02-04 05:44:37 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2014-02-04 05:44:37 CLIENT -> SERVER: RnV0dXJlMTA=
2014-02-04 05:44:38 SERVER -> CLIENT: 235 2.7.0 Accepted
.
.  25 more lines of this stuff
.
2014-02-04 05:44:40 CLIENT -> SERVER: QUIT
2014-02-04 05:44:40 SERVER -> CLIENT: 221 2.0.0 closing connection xv2sm62192389pbb.39 - gsmtp
Message has been sent
</code>```

I put line breaks in to make it more readable, but it comes out as one long string on the screen.

Here is the code.  How do I suppress this output?

```<code>require_once "../phpmailer/class.phpmailer.php";

$mail = new \PHPMailer(true);

$mail->IsSMTP();
$mail->Host       = "smtp.gmail.com";
$mail->Port       = 465;
$mail->SMTPDebug  = 2;
$mail->SMTPAuth   = true;
$mail->SMTPSecure = 'ssl';
$mail->Username   = "xxx@gmail.com";
$mail->Password   = "xxx";
$mail->SetFrom('xxx@gmail.com', 'Randy S');
$mail->WordWrap = 50;

$mail->AddAddress('xxx@yahoo.com', 'Randy');
$mail->Subject = 'PHPMailer Test Subject';
$mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->AddAttachment('upload/names.txt');      // attachment

if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
</code>```

答:
I was facing the same problem,
add

```<code>$mail->SMTPDebug = false;
</code>```

in the mail sending script, after

```<code>$mail->WordWrap = 50;
</code>```

It will work

Body:
So I've searched Google and Stackoverflow and I'm a bit surprised I could not find this problem.

I'm using XAMPP/localhost and PHPmailer sending an email to my yahoo account using my gmail email account.  Everything worked perfectly with the email being send and received, including a sample attachment.

The problem is my browser is displaying what appears to be a dialog of the SERVER/CLIENT for each step of the behind the scene processing just before the "Sent successful" message.

Sample output here:

2014-02-04 05:44:36 SERVER -> CLIENT: 220 mx.google.com
ESMTP xv2sm62192389pbb.39 - gsmtp
2014-02-04 05:44:36 CLIENT -> SERVER: EHLO localhost
2014-02-04 05:44:36 SERVER -> CLIENT: 250-mx.google.com at your service, [171.6.91.113] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN 250-ENHANCEDSTATUSCODES 250 CHUNKING
2014-02-04 05:44:36 CLIENT -> SERVER: AUTH LOGIN
2014-02-04 05:44:36 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2014-02-04 05:44:36 CLIENT -> SERVER: a2hyZng0NDRAZ21haWwuY29t
2014-02-04 05:44:37 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2014-02-04 05:44:37 CLIENT -> SERVER: RnV0dXJlMTA=
2014-02-04 05:44:38 SERVER -> CLIENT: 235 2.7.0 Accepted
.
.  25 more lines of this stuff
.
2014-02-04 05:44:40 CLIENT -> SERVER: QUIT
2014-02-04 05:44:40 SERVER -> CLIENT: 221 2.0.0 closing connection xv2sm62192389pbb.39 - gsmtp
Message has been sent

I put line breaks in to make it more readable, but it comes out as one long string on the screen.

Here is the code.  How do I suppress this output?

require_once "../phpmailer/class.phpmailer.php";

$mail = new \PHPMailer(true);

$mail->IsSMTP();
$mail->Host       = "smtp.gmail.com";
$mail->Port       = 465;
$mail->SMTPDebug  = 2;
$mail->SMTPAuth   = true;
$mail->SMTPSecure = 'ssl';
$mail->Username   = "xxx@gmail.com";
$mail->Password   = "xxx";
$mail->SetFrom('xxx@gmail.com', 'Randy S');
$mail->WordWrap = 50;

$mail->AddAddress('xxx@yahoo.com', 'Randy');
$mail->Subject = 'PHPMailer Test Subject';
$mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->AddAttachment('upload/names.txt');      // attachment

if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}

Body:
I was facing the same problem,
add

$mail->SMTPDebug = false;

in the mail sending script, after

$mail->WordWrap = 50;

It will work