问:
android.view.InflateException: Binary XML file line #976: Error inflating class android.widget.ToggleButton
I've got this this app which I'm developing, it perfectly works on android Emulator nexus 5  device, but when I'm trying it out on a real physical device, it crashes!
there are two activities, the first one (the main) has no problem, but there is a button, which I use to go to the next activity, when I click it, the app crashes and goes out!
so I used the USB debugging tool, and here is the Logcat:

```<code>11-17 13:04:31.898 3096-3096/com.dall.filmanlevel1 E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dall.filmanlevel1/com.dall.filmanlevel1.FilManInShop}: android.view.InflateException: Binary XML file line #976: Error inflating class android.widget.ToggleButton
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: android.view.InflateException: Binary XML file line #976: Error inflating class android.widget.ToggleButton
     at android.view.LayoutInflater.createView(LayoutInflater.java:613)
     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
     at com.dall.filmanlevel1.FilManInShop.onCreate(FilManInShop.java:35)
     at android.app.Activity.performCreate(Activity.java:5122)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: java.lang.reflect.InvocationTargetException
     at java.lang.reflect.Constructor.constructNative(Native Method)
     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
     at com.dall.filmanlevel1.FilManInShop.onCreate(FilManInShop.java:35)
     at android.app.Activity.performCreate(Activity.java:5122)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f02009e a=-1 r=0x7f02009e}
     at android.content.res.Resources.loadDrawable(Resources.java:1967)
     at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
     at android.view.View.<init>(View.java:3341)
     at android.widget.TextView.<init>(TextView.java:591)
     at android.widget.Button.<init>(Button.java:107)
     at android.widget.CompoundButton.<init>(CompoundButton.java:68)
     at android.widget.ToggleButton.<init>(ToggleButton.java:51)
     at android.widget.ToggleButton.<init>(ToggleButton.java:64)
     at java.lang.reflect.Constructor.constructNative(Native Method)
     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
     at com.dall.filmanlevel1.FilManInShop.onCreate(FilManInShop.java:35)
     at android.app.Activity.performCreate(Activity.java:5122)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)
</code>```

any kind of help will be appreciated!

here is the XML file, thank you guys.

```<code><?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context="com.dall.filmanlevel1.FilManInShop">

<TextView
    android:id="@+id/textView0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="in the shop"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="20sp" />

<ScrollView
    android:id="@+id/theScroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/tableRow"
    android:layout_alignLeft="@+id/tableRow"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignStart="@+id/tableRow"
    android:layout_below="@+id/textView0">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="I am a doctor at the London hospital. "
            android:textSize="16sp" />

        <TextView
            android:id="@+id/filamnCInshoptt1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text=""
            android:textColor="@color/colorPrimary"
            android:textSize="16sp" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="5dp"
            app:srcCompat="@drawable/filmanpic1" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="I read the writing under the picture."
            android:textSize="16sp" />

        <TextView
            android:id="@+id/filamnCInshoptt2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text=""
            android:textColor="@color/colorPrimary"
            android:textSize="16sp" />

    </LinearLayout>
</ScrollView>

<TableRow
    android:id="@+id/tableRow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical">

    <CheckBox
        android:id="@+id/tarjomeBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_margin="3dp"
        android:layout_weight=".8"
        android:text="translate" />

    <SeekBar
        android:id="@+id/seekVoice"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_margin="3dp"
        android:layout_weight="1.5" />

    <ToggleButton
        android:id="@+id/playStopVoice"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical"
        android:layout_margin="3dp"
        android:layout_weight=".5"
        android:background="@drawable/toggle_button_background"
        android:text="ToggleButton"
        android:textOff=""
        android:textOn="" />

</TableRow>
</code>```

the Picture i added is JPEG format 350*350 pixels and 25kb in size.

here is the Button_bkackground :

```<code><?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_pause_black_48dp" android:state_checked="true"/>

<item android:drawable="@drawable/ic_play_arrow_black_48dp" android:state_checked="false"/>
</code>```

答:
Problem solved! thank you guys for providing answers and help.
for other people who may encounter such a thing, the story is I had a toggle Button, and tried to customize it by defining an Xml file for its Background. this file @drawable/toggle_button_background:

```<code><?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_pause_black_48dp" android:state_checked="true" />

<item android:drawable="@drawable/ic_play_arrow_black_48dp" android:state_checked="false" />
</code>```

The problem was I put that file in the drawable folder and totally ignored the drawable-v21 folder, that's it! what it did just copied the that file into the drawable-v21 folder as well and then things went smoothly and solved! here  how it looks:

Body:
I've got this this app which I'm developing, it perfectly works on android Emulator nexus 5  device, but when I'm trying it out on a real physical device, it crashes!
there are two activities, the first one (the main) has no problem, but there is a button, which I use to go to the next activity, when I click it, the app crashes and goes out!
so I used the USB debugging tool, and here is the Logcat:

11-17 13:04:31.898 3096-3096/com.dall.filmanlevel1 E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dall.filmanlevel1/com.dall.filmanlevel1.FilManInShop}: android.view.InflateException: Binary XML file line #976: Error inflating class android.widget.ToggleButton
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: android.view.InflateException: Binary XML file line #976: Error inflating class android.widget.ToggleButton
     at android.view.LayoutInflater.createView(LayoutInflater.java:613)
     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
     at com.dall.filmanlevel1.FilManInShop.onCreate(FilManInShop.java:35)
     at android.app.Activity.performCreate(Activity.java:5122)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: java.lang.reflect.InvocationTargetException
     at java.lang.reflect.Constructor.constructNative(Native Method)
     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
     at com.dall.filmanlevel1.FilManInShop.onCreate(FilManInShop.java:35)
     at android.app.Activity.performCreate(Activity.java:5122)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f02009e a=-1 r=0x7f02009e}
     at android.content.res.Resources.loadDrawable(Resources.java:1967)
     at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
     at android.view.View.<init>(View.java:3341)
     at android.widget.TextView.<init>(TextView.java:591)
     at android.widget.Button.<init>(Button.java:107)
     at android.widget.CompoundButton.<init>(CompoundButton.java:68)
     at android.widget.ToggleButton.<init>(ToggleButton.java:51)
     at android.widget.ToggleButton.<init>(ToggleButton.java:64)
     at java.lang.reflect.Constructor.constructNative(Native Method)
     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
     at android.view.LayoutInflater.createView(LayoutInflater.java:587)
     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
     at com.dall.filmanlevel1.FilManInShop.onCreate(FilManInShop.java:35)
     at android.app.Activity.performCreate(Activity.java:5122)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
     at android.app.ActivityThread.access$600(ActivityThread.java:162)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
     at android.os.Handler.dispatchMessage(Handler.java:107)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5392)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:525)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
     at dalvik.system.NativeStart.main(Native Method)

any kind of help will be appreciated!

here is the XML file, thank you guys.

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context="com.dall.filmanlevel1.FilManInShop">

<TextView
    android:id="@+id/textView0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="in the shop"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="20sp" />

<ScrollView
    android:id="@+id/theScroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/tableRow"
    android:layout_alignLeft="@+id/tableRow"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignStart="@+id/tableRow"
    android:layout_below="@+id/textView0">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="I am a doctor at the London hospital. "
            android:textSize="16sp" />

        <TextView
            android:id="@+id/filamnCInshoptt1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text=""
            android:textColor="@color/colorPrimary"
            android:textSize="16sp" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="5dp"
            app:srcCompat="@drawable/filmanpic1" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="I read the writing under the picture."
            android:textSize="16sp" />

        <TextView
            android:id="@+id/filamnCInshoptt2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text=""
            android:textColor="@color/colorPrimary"
            android:textSize="16sp" />

    </LinearLayout>
</ScrollView>

<TableRow
    android:id="@+id/tableRow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical">

    <CheckBox
        android:id="@+id/tarjomeBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_margin="3dp"
        android:layout_weight=".8"
        android:text="translate" />

    <SeekBar
        android:id="@+id/seekVoice"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_margin="3dp"
        android:layout_weight="1.5" />

    <ToggleButton
        android:id="@+id/playStopVoice"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical"
        android:layout_margin="3dp"
        android:layout_weight=".5"
        android:background="@drawable/toggle_button_background"
        android:text="ToggleButton"
        android:textOff=""
        android:textOn="" />

</TableRow>

the Picture i added is JPEG format 350*350 pixels and 25kb in size.

here is the Button_bkackground :

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_pause_black_48dp" android:state_checked="true"/>

<item android:drawable="@drawable/ic_play_arrow_black_48dp" android:state_checked="false"/>

Body:
Problem solved! thank you guys for providing answers and help.
for other people who may encounter such a thing, the story is I had a toggle Button, and tried to customize it by defining an Xml file for its Background. this file @drawable/toggle_button_background:

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_pause_black_48dp" android:state_checked="true" />

<item android:drawable="@drawable/ic_play_arrow_black_48dp" android:state_checked="false" />

The problem was I put that file in the drawable folder and totally ignored the drawable-v21 folder, that's it! what it did just copied the that file into the drawable-v21 folder as well and then things went smoothly and solved! here  how it looks:


来源: stackexchange

问:
High concurrency on PgPool + PostgreSQL Cluster
I have a PgPool II cluster with 2 PostreSQL 9.5 backends (4vCores, 8gb ram) doing loadbalacing+replication. My use case is a website that provides just SSO-login/Registration, is a relative small database, the queries are very simple but it needs to support very high concurrency (several thousand concurrent users).

Before adding more backends, i want to make sure that the configuration of the current Cluster is optimal. Ran some test with pgbench (regular SELECT queries simulating the normal behaviour of the website) and i was able to overload the connection pool without too much effort (pgbench -c 64 -j 4 -t 1000 -f queries.sql) even when there was plenty of CPU/RAM available in the LB and the backends.

This are the relevant settings:

pgPool II

```<code>listen_backlog_multiplier = 3
connection_cache = on
num_init_children = 62
max_pool = 4
child_life_time = 0
child_max_connections = 0
connection_life_time = 0
client_idle_limit = 0
</code>```

PostgreSQL

```<code>max_connections = 256
shared_buffers = 2GB
effective_cache_size = 6GB
work_mem = 8MB
maintenance_work_mem = 512MB
min_wal_size = 1GB
max_wal_size = 2GB
checkpoint_completion_target = 0.7
wal_buffers = 16MB
default_statistics_target = 100
</code>```

Increasing the num_init_children/max_pool will force me to increase the max_connections on the backends, and that doesn't seems to be recommended. Any suggestions? Thanks!

答:
There is no way to achieve more concurrent connections through Pgpool-II than the value of num_init_children.

num_init_children in Pgpool-II directly corresponds to the maximum number of concurrent client connections Pgpool-II can handle, So you can not set the num_init_children value lower than the maximum concurrent connection you want to support.

But to save the max_connections on PG side, you can use the lower value for max_pool config. As a Pgpool-II child process opens a new backend connection only if the requested [user,database] pair is not already in the cache. And if the application uses only one user to connect to only one database, Say [user1,db1], then you can set max_pool to 1, and can have max_connection in PG backend equal to (num_init_children +1).

ContentLicense: CC BY-SA 3.0

Body:
I have a PgPool II cluster with 2 PostreSQL 9.5 backends (4vCores, 8gb ram) doing loadbalacing+replication. My use case is a website that provides just SSO-login/Registration, is a relative small database, the queries are very simple but it needs to support very high concurrency (several thousand concurrent users).

Before adding more backends, i want to make sure that the configuration of the current Cluster is optimal. Ran some test with pgbench (regular SELECT queries simulating the normal behaviour of the website) and i was able to overload the connection pool without too much effort (pgbench -c 64 -j 4 -t 1000 -f queries.sql) even when there was plenty of CPU/RAM available in the LB and the backends.

This are the relevant settings:

pgPool II

listen_backlog_multiplier = 3
connection_cache = on
num_init_children = 62
max_pool = 4
child_life_time = 0
child_max_connections = 0
connection_life_time = 0
client_idle_limit = 0

PostgreSQL

max_connections = 256
shared_buffers = 2GB
effective_cache_size = 6GB
work_mem = 8MB
maintenance_work_mem = 512MB
min_wal_size = 1GB
max_wal_size = 2GB
checkpoint_completion_target = 0.7
wal_buffers = 16MB
default_statistics_target = 100

Increasing the num_init_children/max_pool will force me to increase the max_connections on the backends, and that doesn't seems to be recommended. Any suggestions? Thanks!


问:
windowing functions ms access
I am working on a class scheduling database in MS Access. There are a variety of classes, each of which is taught multiple times, sometimes multiple times in a day, but not necessarily every day. Each course has a unique set of software and data that is stored on a laptop. there is a set of laptops for each course with that software loaded.

For any given training day I need to assign a range of laptop IDs to the right classes in different rooms, depending on how many people will be taking that class in that room, so that the instructors know which laptops to take to the room with them to teach the class that day.

For example, I have the raw data:

```<code>Date   Room   ClassName      HeadCount
----   ----   ---------      ---------
11/30   101   Intro            10
11/30   102   Intro            15
11/30   103   Course 2          5
12/1    101   Intro            10
12/1    102   Course 2         15
12/1    103   Course 3         10
</code>```

I also know the following about the laptops:

```<code>ClassName    LaptopID
---------   ---------
Intro       LT.Intro_1
Intro        ...
Intro       LT.Intro_30
Course 2    LT.Course 2_1
Course 2      ...
Course 2    LT.Course 2_30
Course 3    LT.Course 3_1
Course 3    ...
Course 3    LT.Course 3_30
</code>```

Based on the above two tables, I would want to output:

```<code>Date   Room   ClassName     HeadCount  First Laptop   Last Laptop
----   ----   ---------     ---------  ------------   -----------
11/30   101   Intro           10       LT.Intro_1     LT.Intro_10
11/30   102   Intro           15       LT.Intro_11    LT.Intro_25
11/30   103   Course 2         5       LT.Course 2_1  LT.Course 2_5
12/1    101   Intro           10       LT.Intro_1     LT.Intro_10
12/1    102   Course 2        15       LT.Course 2_1  LT.Course 2_15
12/1    103   Course 3        10       LT.Course 3_1  LT.Course 3_10
</code>```

I know this is a windowing function, but MS Access doesn't have lead or lag. Is there a workaround?

答:
You might want to change your table definitions for better performance. I have recreated two tables as you've mentioned.

You know your laptop ids are in sequence and you know the headcount per class. In order to follow a lead, you must know the last headcount.
which would be toal attendees on the same date, for the same class, before current class/event.

x = sum(headCount) where id < currentID & classname = currentClassname & date = currentDate. (Current means currentRow.)

Now you know total laptops used before the current row and the headCount for current row. The First laptop would be

```<code>f = min(laptopid) where laptopid > x (x being totaLaptopUsedBefore this Row)
</code>```

for the Last laptop, you must also add the current headcount.

```<code>l = min(laptopid) where laptopid >= currentHeadCount + x
</code>```

Note f checks laptopid is greater and L checks >=.

Here is a working demo which you can improve on:

Table1: tbl_ClassEvents

```<code>+----+------------+------+-----------+-----------+
| ID |    date    | Room | ClassName | HeadCount |
+----+------------+------+-----------+-----------+
|  1 | 30/11/2017 |  101 | Intro     |        10 |
|  2 | 30/11/2017 |  102 | intro     |        15 |
|  3 | 30/11/2017 |  103 | Course 2  |         5 |
|  4 | 01/12/2017 |  101 | Intro     |        10 |
|  5 | 01/12/2017 |  102 | Course 2  |        15 |
|  6 | 01/12/2017 |  103 | Course 3  |        10 |
|  7 | 17/11/2017 |  101 | Intro     |        16 |
+----+------------+------+-----------+-----------+

Table2: Tbl_ClassVsLaptop
+----+-----------+----------------+
| Id | ClassName |    LaptopId    |
+----+-----------+----------------+
|  1 | Intro     | LT.Intro_1     |
|  2 | Intro     | LT.Intro_2     |
|  3 | Intro     | LT.Intro_3     |
|  4 | Intro     | LT.Intro_4     |
|  5 | Intro     | LT.Intro_5     |
|  6 | Intro     | LT.Intro_6     |
|  7 | Intro     | LT.Intro_7     |
|  8 | Intro     | LT.Intro_8     |
|  9 | Intro     | LT.Intro_9     |
| 10 | Intro     | LT.Intro_10    |
| 11 | Intro     | LT.Intro_11    |
| 12 | Intro     | LT.Intro_12    |
| 13 | Intro     | LT.Intro_13    |
| 14 | Intro     | LT.Intro_14    |
| 15 | Intro     | LT.Intro_15    |
| 16 | Intro     | LT.Intro_16    |
| 17 | Intro     | LT.Intro_17    |
| 18 | Intro     | LT.Intro_18    |
| 19 | Intro     | LT.Intro_19    |
| 20 | Intro     | LT.Intro_20    |
| 21 | Intro     | LT.Intro_21    |
| 22 | Intro     | LT.Intro_22    |
| 23 | Intro     | LT.Intro_23    |
| 24 | Intro     | LT.Intro_24    |
| 25 | Intro     | LT.Intro_25    |
| 26 | Intro     | LT.Intro_26    |
| 27 | Intro     | LT.Intro_27    |
| 28 | Intro     | LT.Intro_28    |
| 29 | Intro     | LT.Intro_29    |
| 30 | Intro     | LT.Intro_30    |
| 31 | Course 2  | LT.Course 2_1  |
| 32 | Course 2  | LT.Course 2_2  |
| 33 | Course 2  | LT.Course 2_3  |
| 34 | Course 2  | LT.Course 2_4  |
| 35 | Course 2  | LT.Course 2_5  |
| 36 | Course 2  | LT.Course 2_6  |
| 37 | Course 2  | LT.Course 2_7  |
| 38 | Course 2  | LT.Course 2_8  |
| 39 | Course 2  | LT.Course 2_9  |
| 40 | Course 2  | LT.Course 2_10 |
| 41 | Course 2  | LT.Course 2_11 |
| 42 | Course 2  | LT.Course 2_12 |
| 43 | Course 2  | LT.Course 2_13 |
| 44 | Course 2  | LT.Course 2_14 |
| 45 | Course 2  | LT.Course 2_15 |
| 46 | Course 2  | LT.Course 2_16 |
| 47 | Course 2  | LT.Course 2_17 |
| 48 | Course 2  | LT.Course 2_18 |
| 49 | Course 2  | LT.Course 2_19 |
| 50 | Course 2  | LT.Course 2_20 |
| 51 | Course 2  | LT.Course 2_21 |
| 52 | Course 2  | LT.Course 2_22 |
| 53 | Course 2  | LT.Course 2_23 |
| 54 | Course 2  | LT.Course 2_24 |
| 55 | Course 2  | LT.Course 2_25 |
| 56 | Course 2  | LT.Course 2_26 |
| 57 | Course 2  | LT.Course 2_27 |
| 58 | Course 2  | LT.Course 2_28 |
| 59 | Course 2  | LT.Course 2_29 |
| 60 | Course 2  | LT.Course 2_30 |
| 61 | Course 3  | LT.Course 3_1  |
| 62 | Course 3  | LT.Course 3_2  |
| 63 | Course 3  | LT.Course 3_3  |
| 64 | Course 3  | LT.Course 3_4  |
| 65 | Course 3  | LT.Course 3_5  |
| 66 | Course 3  | LT.Course 3_6  |
| 67 | Course 3  | LT.Course 3_7  |
| 68 | Course 3  | LT.Course 3_8  |
| 69 | Course 3  | LT.Course 3_9  |
| 70 | Course 3  | LT.Course 3_10 |
| 71 | Course 3  | LT.Course 3_11 |
| 72 | Course 3  | LT.Course 3_12 |
| 73 | Course 3  | LT.Course 3_13 |
| 74 | Course 3  | LT.Course 3_14 |
| 75 | Course 3  | LT.Course 3_15 |
| 76 | Course 3  | LT.Course 3_16 |
| 77 | Course 3  | LT.Course 3_17 |
| 78 | Course 3  | LT.Course 3_18 |
| 79 | Course 3  | LT.Course 3_19 |
| 80 | Course 3  | LT.Course 3_20 |
| 81 | Course 3  | LT.Course 3_21 |
| 82 | Course 3  | LT.Course 3_22 |
| 83 | Course 3  | LT.Course 3_23 |
| 84 | Course 3  | LT.Course 3_24 |
| 85 | Course 3  | LT.Course 3_25 |
| 86 | Course 3  | LT.Course 3_26 |
| 87 | Course 3  | LT.Course 3_27 |
| 88 | Course 3  | LT.Course 3_28 |
| 89 | Course 3  | LT.Course 3_29 |
| 90 | Course 3  | LT.Course 3_30 |
+----+-----------+----------------+
</code>```

Here is the query:

```<code>SELECT tbl_classEvents.ID
    ,tbl_classEvents.DATE
    ,tbl_classEvents.Room
    ,tbl_classEvents.ClassName
    ,tbl_classEvents.HeadCount
    ,(
        SELECT min(laptopId)
        FROM tbl_ClassVsLaptop T1
        WHERE T1.ClassName = tbl_ClassEvents.ClassNAme
            AND Mid([T1.LaptopID], InStrRev([T1.LaptopID], "_") + 1, 3) > (
                + Nz((
                        SELECT sum(headCount)
                        FROM tbl_classEvents T2
                        WHERE T2.ID < Tbl_ClassEvents.ID
                            AND T2.[DATE] = [Tbl_ClassEvents].[DATE]
                            AND T2.[ClassName] = [Tbl_ClassEvents].[ClassName]
                        ), 0)
                )
        ) AS FirstLaptop
    ,(
        SELECT min(laptopId)
        FROM tbl_ClassVsLaptop T1
        WHERE T1.ClassName = tbl_ClassEvents.ClassNAme
            AND Mid([T1.LaptopID], InStrRev([T1.LaptopID], "_") + 1, 3) >= (
                + [tbl_classEvents].[HeadCount] + Nz((
                        SELECT sum(headCount)
                        FROM tbl_classEvents T2
                        WHERE T2.ID < Tbl_ClassEvents.ID
                            AND T2.[DATE] = [Tbl_ClassEvents].[DATE]
                            AND T2.[ClassName] = [Tbl_ClassEvents].[ClassName]
                        ), 0)
                )
        ) AS LastLaptop
FROM tbl_classEvents
ORDER BY tbl_classEvents.DATE
    ,tbl_classEvents.Room
    ,tbl_classEvents.ClassNAme;
</code>```

And the output:

```<code>+----+------------+------+-----------+-----------+---------------+----------------+
| ID |    DATE    | Room | ClassName | HeadCount |  FirstLaptop  |   LastLaptop   |
+----+------------+------+-----------+-----------+---------------+----------------+
|  7 | 17/11/2017 |  101 | Intro     |        16 | LT.Intro_1    | LT.Intro_16    |
|  1 | 30/11/2017 |  101 | Intro     |        10 | LT.Intro_1    | LT.Intro_10    |
|  2 | 30/11/2017 |  102 | intro     |        15 | LT.Intro_11   | LT.Intro_25    |
|  3 | 30/11/2017 |  103 | Course 2  |         5 | LT.Course 2_1 | LT.Course 2_5  |
|  4 | 01/12/2017 |  101 | Intro     |        10 | LT.Intro_1    | LT.Intro_10    |
|  5 | 01/12/2017 |  102 | Course 2  |        15 | LT.Course 2_1 | LT.Course 2_15 |
|  6 | 01/12/2017 |  103 | Course 3  |        10 | LT.Course 3_1 | LT.Course 3_10 |
+----+------------+------+-----------+-----------+---------------+----------------+
</code>```

Title: windowing functions ms access

Body:
I am working on a class scheduling database in MS Access. There are a variety of classes, each of which is taught multiple times, sometimes multiple times in a day, but not necessarily every day. Each course has a unique set of software and data that is stored on a laptop. there is a set of laptops for each course with that software loaded.

For any given training day I need to assign a range of laptop IDs to the right classes in different rooms, depending on how many people will be taking that class in that room, so that the instructors know which laptops to take to the room with them to teach the class that day.

For example, I have the raw data:

Date   Room   ClassName      HeadCount
----   ----   ---------      ---------
11/30   101   Intro            10
11/30   102   Intro            15
11/30   103   Course 2          5
12/1    101   Intro            10
12/1    102   Course 2         15
12/1    103   Course 3         10

I also know the following about the laptops:

ClassName    LaptopID
---------   ---------
Intro       LT.Intro_1
Intro        ...
Intro       LT.Intro_30
Course 2    LT.Course 2_1
Course 2      ...
Course 2    LT.Course 2_30
Course 3    LT.Course 3_1
Course 3    ...
Course 3    LT.Course 3_30

Based on the above two tables, I would want to output:

Date   Room   ClassName     HeadCount  First Laptop   Last Laptop
----   ----   ---------     ---------  ------------   -----------
11/30   101   Intro           10       LT.Intro_1     LT.Intro_10
11/30   102   Intro           15       LT.Intro_11    LT.Intro_25
11/30   103   Course 2         5       LT.Course 2_1  LT.Course 2_5
12/1    101   Intro           10       LT.Intro_1     LT.Intro_10
12/1    102   Course 2        15       LT.Course 2_1  LT.Course 2_15
12/1    103   Course 3        10       LT.Course 3_1  LT.Course 3_10

I know this is a windowing function, but MS Access doesn't have lead or lag. Is there a workaround?

Body:
You might want to change your table definitions for better performance. I have recreated two tables as you've mentioned.

You know your laptop ids are in sequence and you know the headcount per class. In order to follow a lead, you must know the last headcount.
which would be toal attendees on the same date, for the same class, before current class/event.

x = sum(headCount) where id < currentID & classname = currentClassname & date = currentDate. (Current means currentRow.)

Now you know total laptops used before the current row and the headCount for current row. The First laptop would be

f = min(laptopid) where laptopid > x (x being totaLaptopUsedBefore this Row)

for the Last laptop, you must also add the current headcount.

l = min(laptopid) where laptopid >= currentHeadCount + x

Note f checks laptopid is greater and L checks >=.

Here is a working demo which you can improve on:

Table1: tbl_ClassEvents

+----+------------+------+-----------+-----------+
| ID |    date    | Room | ClassName | HeadCount |
+----+------------+------+-----------+-----------+
|  1 | 30/11/2017 |  101 | Intro     |        10 |
|  2 | 30/11/2017 |  102 | intro     |        15 |
|  3 | 30/11/2017 |  103 | Course 2  |         5 |
|  4 | 01/12/2017 |  101 | Intro     |        10 |
|  5 | 01/12/2017 |  102 | Course 2  |        15 |
|  6 | 01/12/2017 |  103 | Course 3  |        10 |
|  7 | 17/11/2017 |  101 | Intro     |        16 |
+----+------------+------+-----------+-----------+

Table2: Tbl_ClassVsLaptop
+----+-----------+----------------+
| Id | ClassName |    LaptopId    |
+----+-----------+----------------+
|  1 | Intro     | LT.Intro_1     |
|  2 | Intro     | LT.Intro_2     |
|  3 | Intro     | LT.Intro_3     |
|  4 | Intro     | LT.Intro_4     |
|  5 | Intro     | LT.Intro_5     |
|  6 | Intro     | LT.Intro_6     |
|  7 | Intro     | LT.Intro_7     |
|  8 | Intro     | LT.Intro_8     |
|  9 | Intro     | LT.Intro_9     |
| 10 | Intro     | LT.Intro_10    |
| 11 | Intro     | LT.Intro_11    |
| 12 | Intro     | LT.Intro_12    |
| 13 | Intro     | LT.Intro_13    |
| 14 | Intro     | LT.Intro_14    |
| 15 | Intro     | LT.Intro_15    |
| 16 | Intro     | LT.Intro_16    |
| 17 | Intro     | LT.Intro_17    |
| 18 | Intro     | LT.Intro_18    |
| 19 | Intro     | LT.Intro_19    |
| 20 | Intro     | LT.Intro_20    |
| 21 | Intro     | LT.Intro_21    |
| 22 | Intro     | LT.Intro_22    |
| 23 | Intro     | LT.Intro_23    |
| 24 | Intro     | LT.Intro_24    |
| 25 | Intro     | LT.Intro_25    |
| 26 | Intro     | LT.Intro_26    |
| 27 | Intro     | LT.Intro_27    |
| 28 | Intro     | LT.Intro_28    |
| 29 | Intro     | LT.Intro_29    |
| 30 | Intro     | LT.Intro_30    |
| 31 | Course 2  | LT.Course 2_1  |
| 32 | Course 2  | LT.Course 2_2  |
| 33 | Course 2  | LT.Course 2_3  |
| 34 | Course 2  | LT.Course 2_4  |
| 35 | Course 2  | LT.Course 2_5  |
| 36 | Course 2  | LT.Course 2_6  |
| 37 | Course 2  | LT.Course 2_7  |
| 38 | Course 2  | LT.Course 2_8  |
| 39 | Course 2  | LT.Course 2_9  |
| 40 | Course 2  | LT.Course 2_10 |
| 41 | Course 2  | LT.Course 2_11 |
| 42 | Course 2  | LT.Course 2_12 |
| 43 | Course 2  | LT.Course 2_13 |
| 44 | Course 2  | LT.Course 2_14 |
| 45 | Course 2  | LT.Course 2_15 |
| 46 | Course 2  | LT.Course 2_16 |
| 47 | Course 2  | LT.Course 2_17 |
| 48 | Course 2  | LT.Course 2_18 |
| 49 | Course 2  | LT.Course 2_19 |
| 50 | Course 2  | LT.Course 2_20 |
| 51 | Course 2  | LT.Course 2_21 |
| 52 | Course 2  | LT.Course 2_22 |
| 53 | Course 2  | LT.Course 2_23 |
| 54 | Course 2  | LT.Course 2_24 |
| 55 | Course 2  | LT.Course 2_25 |
| 56 | Course 2  | LT.Course 2_26 |
| 57 | Course 2  | LT.Course 2_27 |
| 58 | Course 2  | LT.Course 2_28 |
| 59 | Course 2  | LT.Course 2_29 |
| 60 | Course 2  | LT.Course 2_30 |
| 61 | Course 3  | LT.Course 3_1  |
| 62 | Course 3  | LT.Course 3_2  |
| 63 | Course 3  | LT.Course 3_3  |
| 64 | Course 3  | LT.Course 3_4  |
| 65 | Course 3  | LT.Course 3_5  |
| 66 | Course 3  | LT.Course 3_6  |
| 67 | Course 3  | LT.Course 3_7  |
| 68 | Course 3  | LT.Course 3_8  |
| 69 | Course 3  | LT.Course 3_9  |
| 70 | Course 3  | LT.Course 3_10 |
| 71 | Course 3  | LT.Course 3_11 |
| 72 | Course 3  | LT.Course 3_12 |
| 73 | Course 3  | LT.Course 3_13 |
| 74 | Course 3  | LT.Course 3_14 |
| 75 | Course 3  | LT.Course 3_15 |
| 76 | Course 3  | LT.Course 3_16 |
| 77 | Course 3  | LT.Course 3_17 |
| 78 | Course 3  | LT.Course 3_18 |
| 79 | Course 3  | LT.Course 3_19 |
| 80 | Course 3  | LT.Course 3_20 |
| 81 | Course 3  | LT.Course 3_21 |
| 82 | Course 3  | LT.Course 3_22 |
| 83 | Course 3  | LT.Course 3_23 |
| 84 | Course 3  | LT.Course 3_24 |
| 85 | Course 3  | LT.Course 3_25 |
| 86 | Course 3  | LT.Course 3_26 |
| 87 | Course 3  | LT.Course 3_27 |
| 88 | Course 3  | LT.Course 3_28 |
| 89 | Course 3  | LT.Course 3_29 |
| 90 | Course 3  | LT.Course 3_30 |
+----+-----------+----------------+

Here is the query:

SELECT tbl_classEvents.ID
    ,tbl_classEvents.DATE
    ,tbl_classEvents.Room
    ,tbl_classEvents.ClassName
    ,tbl_classEvents.HeadCount
    ,(
        SELECT min(laptopId)
        FROM tbl_ClassVsLaptop T1
        WHERE T1.ClassName = tbl_ClassEvents.ClassNAme
            AND Mid([T1.LaptopID], InStrRev([T1.LaptopID], "_") + 1, 3) > (
                + Nz((
                        SELECT sum(headCount)
                        FROM tbl_classEvents T2
                        WHERE T2.ID < Tbl_ClassEvents.ID
                            AND T2.[DATE] = [Tbl_ClassEvents].[DATE]
                            AND T2.[ClassName] = [Tbl_ClassEvents].[ClassName]
                        ), 0)
                )
        ) AS FirstLaptop
    ,(
        SELECT min(laptopId)
        FROM tbl_ClassVsLaptop T1
        WHERE T1.ClassName = tbl_ClassEvents.ClassNAme
            AND Mid([T1.LaptopID], InStrRev([T1.LaptopID], "_") + 1, 3) >= (
                + [tbl_classEvents].[HeadCount] + Nz((
                        SELECT sum(headCount)
                        FROM tbl_classEvents T2
                        WHERE T2.ID < Tbl_ClassEvents.ID
                            AND T2.[DATE] = [Tbl_ClassEvents].[DATE]
                            AND T2.[ClassName] = [Tbl_ClassEvents].[ClassName]
                        ), 0)
                )
        ) AS LastLaptop
FROM tbl_classEvents
ORDER BY tbl_classEvents.DATE
    ,tbl_classEvents.Room
    ,tbl_classEvents.ClassNAme;

And the output:

+----+------------+------+-----------+-----------+---------------+----------------+
| ID |    DATE    | Room | ClassName | HeadCount |  FirstLaptop  |   LastLaptop   |
+----+------------+------+-----------+-----------+---------------+----------------+
|  7 | 17/11/2017 |  101 | Intro     |        16 | LT.Intro_1    | LT.Intro_16    |
|  1 | 30/11/2017 |  101 | Intro     |        10 | LT.Intro_1    | LT.Intro_10    |
|  2 | 30/11/2017 |  102 | intro     |        15 | LT.Intro_11   | LT.Intro_25    |
|  3 | 30/11/2017 |  103 | Course 2  |         5 | LT.Course 2_1 | LT.Course 2_5  |
|  4 | 01/12/2017 |  101 | Intro     |        10 | LT.Intro_1    | LT.Intro_10    |
|  5 | 01/12/2017 |  102 | Course 2  |        15 | LT.Course 2_1 | LT.Course 2_15 |
|  6 | 01/12/2017 |  103 | Course 3  |        10 | LT.Course 3_1 | LT.Course 3_10 |
+----+------------+------+-----------+-----------+---------------+----------------+


问:
Using GMock to verify a Destructor Call
Using GMock, how can I verify that a class's destructor is called? Is there a way, other than to wrap it in another class?

The obvious method, EXPECT_CALL(object, ~classtype()) yields a compiler error (gmock cannot produce a mock method called gmock_~classtype).

答:
An easy way to check for a destructor call:

```<code>class MockFoo : public Foo {
  ...
  // Add the following two lines to the mock class.
  MOCK_METHOD0(Die, void());
  virtual ~MockFoo() { Die(); }
};
</code>```

In your test function:

```<code> MockFoo* foo = new MockFoo;
  ...
  {
    EXPECT_CALL(*foo, Die());
  }
</code>```

More Details can be found here:
Mocking Destructors

ContentLicense: CC BY-SA 2.5

Title: Using GMock to verify a Destructor Call

Body:
An easy way to check for a destructor call:

class MockFoo : public Foo {
  ...
  // Add the following two lines to the mock class.
  MOCK_METHOD0(Die, void());
  virtual ~MockFoo() { Die(); }
};

In your test function:

 MockFoo* foo = new MockFoo;
  ...
  {
    EXPECT_CALL(*foo, Die());
  }

More Details can be found here:
Mocking Destructors

ContentLicense: CC BY-SA 4.0


问:
How to pass data between activities using static variables on a public class?
I'm trying to use static variables on a public class for passing them between activities.

I'm having a rare problem doing that. I'm giving values to the static variables on a activity. This activity calls a GLSurfaceView and listen for screen orientation changes.

If i give values to the static variables on the GLSurfaceView, then, all works fine, the values are stored and i can retrieve them when the onCreate method is called again after a screen orientation change.

The problem is when i store values on the static variables outside the GLSurfaceView class, inside the onTouchListener methods of the activity. These values are not stored properly on the static variables, because when i try to access them on the GLSurfaceView those values are not what they were supossed to be.

This is my static variables class:

```<code>public class MagazineStatus {
//clase utilizada para almacenar variables estáticas.
static int currentPage=1; //página actual
//Valores originales cuando pasamos de un modo a otro, por ejemplo, de portrait a landscape.
static float oScale=0.0f;
static float oX=0.0f;
static float oY=0.0f;
static float oZrot=0;
static boolean modeChanged=false; //indica si hemos cambiado de modo
(landscape/portrait)
}
</code>```

Here i'm storing the values on my activity class (i did a debug and aparently they are being stored correctly):

```<code>        for (int i=0;i<thumbnailLinearLayouts.size();i++){
        final int auxIndex=i;
        thumbnailLinearLayouts.get(i).setOnTouchListener(new OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                MagazineStatus.currentPage=auxIndex;
                System.out.println("MagazineStatus.currentPage: "+MagazineStatus.currentPage);
                return true;
            }
        });
    }
</code>```

And here i'm trying to retrieve these values on the GLSurfaceView class, and the values are not correct, It is retrieving the original initial value, 1, instead of the value stored before.

```<code>currentPage=MagazineStatus.currentPage;     //cargo datos guardados antes del cambio de orientación
</code>```

What i am doing wrong?

答:
Second Activity  :-

In xml File take one textview field

Java Code

```<code>public static String name;

TextView t=(TextView)findViewById(R.id.tv);

t.setText(name);
</code>```

First Activity:-

in xml file take one edittext and one button

Java Code

```<code>button.setOnClickListener(new View.onClickListener){

    @override
    public void onClick(View v){

    SecondActivity.name=editText.getText().toString();

    Intent i=new Intent(firstActivity.this,SecondActivity.class);

    startActivity(i);

    }
}
</code>```

Body:
I'm trying to use static variables on a public class for passing them between activities.

I'm having a rare problem doing that. I'm giving values to the static variables on a activity. This activity calls a GLSurfaceView and listen for screen orientation changes.

If i give values to the static variables on the GLSurfaceView, then, all works fine, the values are stored and i can retrieve them when the onCreate method is called again after a screen orientation change.

The problem is when i store values on the static variables outside the GLSurfaceView class, inside the onTouchListener methods of the activity. These values are not stored properly on the static variables, because when i try to access them on the GLSurfaceView those values are not what they were supossed to be.

This is my static variables class:

public class MagazineStatus {
//clase utilizada para almacenar variables estáticas.
static int currentPage=1; //página actual
//Valores originales cuando pasamos de un modo a otro, por ejemplo, de portrait a landscape.
static float oScale=0.0f;
static float oX=0.0f;
static float oY=0.0f;
static float oZrot=0;
static boolean modeChanged=false; //indica si hemos cambiado de modo
(landscape/portrait)
}

Here i'm storing the values on my activity class (i did a debug and aparently they are being stored correctly):

        for (int i=0;i<thumbnailLinearLayouts.size();i++){
        final int auxIndex=i;
        thumbnailLinearLayouts.get(i).setOnTouchListener(new OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                MagazineStatus.currentPage=auxIndex;
                System.out.println("MagazineStatus.currentPage: "+MagazineStatus.currentPage);
                return true;
            }
        });
    }

And here i'm trying to retrieve these values on the GLSurfaceView class, and the values are not correct, It is retrieving the original initial value, 1, instead of the value stored before.

currentPage=MagazineStatus.currentPage;     //cargo datos guardados antes del cambio de orientación

What i am doing wrong?

Body:
Second Activity  :-

In xml File take one textview field

Java Code

public static String name;

TextView t=(TextView)findViewById(R.id.tv);

t.setText(name);

First Activity:-

in xml file take one edittext and one button

Java Code

button.setOnClickListener(new View.onClickListener){

    @override
    public void onClick(View v){

    SecondActivity.name=editText.getText().toString();

    Intent i=new Intent(firstActivity.this,SecondActivity.class);

    startActivity(i);

    }
}


问:
Unix - Sort from child blocking
I was trying to complete an exercise when I found some problems that I cannot understand.
First one:
I'm trying to sort a file using system(string), where the string contains: /usr/bin/sort -n -o %s %s. %s is the path which I read from the parent through a pipe, and printing the string I see that is correct. Everything seems working if I remove the -o %s. If I add it, the program gets stucked on the sort.
Here the code:

```<code>str=strcat(dir, str);
printf("    %s       \n", str);
sprintf(ssys, "/usr/bin/sort -n -o %s %s", str, str);
printf("     1111    \n");
system(ssys);
printf("     2222   \n");
</code>```

And the output is:

/home/dio/Desktop/Operating-System-PoliTo/Lab6/ex2/texts/1.txt

1111

As you can see, it doesn't reach the third printf, but just when I press CTRL+c to kill the process, even if the file isn't sorted. I cannot understand why, because if I run it and check with ps I get the sort process running.Seems like it is waiting for the parent to finish but it doesn't sort anyway.

This is the whole code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>

static void sig_handler (int);

static void sig_handler (int signo)
{
        if (signo == SIGPIPE)
                exit(0);
}

int main (int argc, char **argv)
{

        signal(SIGPIPE, sig_handler);

        if (argc<3)
        {
                printf("Too little arguments");
                return 1;
        }

        int c=atoi(argv[1]);
        int *pids=malloc(sizeof(int)*c);
        int i=0, num_char_str, id, line_sort, request_pipe[c][2], data_pipe[c][2], answer_pipe[c][2];
        pid_t pid;
        char cR, cW;
        char *dir=malloc(strlen(argv[2])+1);
        char *str=malloc(strlen(argv[2])*10);
        char *ssys=malloc(strlen(argv[2])*10);
        FILE* fpp;
        FILE* fp;

        strcpy(dir, argv[2]);
        sprintf(str, "ls %s > list.txt",  dir);
        system(str);
        for(i=0; i<c; i++)
        {
                if (pipe(request_pipe[i]) == -1)
                        return 2;
                if (pipe(data_pipe[i]) == -1)
                        return 2;
                if (pipe(answer_pipe[i]) == -1)
                        return 2;
        }
        for(i=0; i<c; i++)
        {
                pid=fork();
                if(pid>0)
                        pids[i]=pid;
                if (pid == -1)
                {
                        printf("error forking");
                        return 3;
                }
                if (pid==0)
                        break;
        }
    if (pid>0) /// parent
        {
                for(i=0; i<c; i++)
                {
                        close(answer_pipe[i][1]);  /// close answer pipe on writing
                        close(request_pipe[i][1]);  /// close request pipe on writing
                        close(data_pipe[i][0]);  /// close data pipe on reading
                }
                fp=fopen("list.txt", "r");
                if (fp==NULL)
                        return 3;
                i=0;
                while (fgets(str, sizeof(str), fp)!=NULL)
                {
                        /// wait for ask
                        read(request_pipe[i][0], &cR, 1);
                        /// sending first the number of characters to read
                        /// and then the file name
                        num_char_str=(strlen(str) +1);
                        write(data_pipe[i][1], &num_char_str, sizeof(int));
                        write(data_pipe[i][1], str, num_char_str);
                        /// read the answer
                        read(answer_pipe[i][0], &id, sizeof(int));
                        //pids[i]=id;
                        read(answer_pipe[i][0], &line_sort, sizeof(int));
                        if (i==c-1)
                                i=-1;
                        i++;
                }
                /// sending termination signal to children
                for (i=0; i<c; i++)
                        kill(pids[i], SIGPIPE);
                /// producing all_sorted.txt
                strcpy(str, "touch all_sorted.txt");
                system(str);
                sprintf(str, "find %s -name \"*.txt\" -exec cat \"{}\"\";\" > all_sorted.txt", dir);
                system(str);
                /// sorting all_sorted

        }
        if (pid == 0) /// child
        {
                close(answer_pipe[i][0]);  /// close answer pipe on reading
                close(request_pipe[i][0]);  /// close request pipe on reading
                close(data_pipe[i][1]);  /// close data pipe on writing
                while (1)
                {
                        /// send request to parent
                        write(request_pipe[i][1], &cW, 1);
                        /// read length of string
                        read(data_pipe[i][0], &num_char_str, sizeof(int));
                        /// read the file name
                        read(data_pipe[i][0], str, num_char_str);
                        /// sorting
                        str=strcat(dir, str);
                        sprintf(ssys, "/usr/bin/sort -n -o %s %s", str, str);
printf("     1111    \n");
                        system(ssys);
printf("     2222   \n");
                        /// sending back data
                        id=getpid();
                        write(answer_pipe[i][1], &id, sizeof(int));
                        //sprintf(str, "wc -l %s/%s", dir, str);
                        //fpp=popen(str, "r");
                        //fscanf(fpp, "%d", &line_sort);
                        //pclose(fpp);
                        line_sort=1;
                        write(answer_pipe[i][1], &line_sort, sizeof(int));
                }
        }

        return 0;

}
</code>```

答:
Thank you, I didn't know about strace.
Btw seems the problem was the "\n" that fgets read and gave some problem to the sort call

Title: Unix - Sort from child blocking

Body:
I was trying to complete an exercise when I found some problems that I cannot understand.
First one:
I'm trying to sort a file using system(string), where the string contains: /usr/bin/sort -n -o %s %s. %s is the path which I read from the parent through a pipe, and printing the string I see that is correct. Everything seems working if I remove the -o %s. If I add it, the program gets stucked on the sort.
Here the code:

str=strcat(dir, str);
printf("    %s       \n", str);
sprintf(ssys, "/usr/bin/sort -n -o %s %s", str, str);
printf("     1111    \n");
system(ssys);
printf("     2222   \n");

And the output is:

/home/dio/Desktop/Operating-System-PoliTo/Lab6/ex2/texts/1.txt

1111

As you can see, it doesn't reach the third printf, but just when I press CTRL+c to kill the process, even if the file isn't sorted. I cannot understand why, because if I run it and check with ps I get the sort process running.Seems like it is waiting for the parent to finish but it doesn't sort anyway.

This is the whole code:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>

static void sig_handler (int);

static void sig_handler (int signo)
{
        if (signo == SIGPIPE)
                exit(0);
}

int main (int argc, char **argv)
{

        signal(SIGPIPE, sig_handler);

        if (argc<3)
        {
                printf("Too little arguments");
                return 1;
        }

        int c=atoi(argv[1]);
        int *pids=malloc(sizeof(int)*c);
        int i=0, num_char_str, id, line_sort, request_pipe[c][2], data_pipe[c][2], answer_pipe[c][2];
        pid_t pid;
        char cR, cW;
        char *dir=malloc(strlen(argv[2])+1);
        char *str=malloc(strlen(argv[2])*10);
        char *ssys=malloc(strlen(argv[2])*10);
        FILE* fpp;
        FILE* fp;

        strcpy(dir, argv[2]);
        sprintf(str, "ls %s > list.txt",  dir);
        system(str);
        for(i=0; i<c; i++)
        {
                if (pipe(request_pipe[i]) == -1)
                        return 2;
                if (pipe(data_pipe[i]) == -1)
                        return 2;
                if (pipe(answer_pipe[i]) == -1)
                        return 2;
        }
        for(i=0; i<c; i++)
        {
                pid=fork();
                if(pid>0)
                        pids[i]=pid;
                if (pid == -1)
                {
                        printf("error forking");
                        return 3;
                }
                if (pid==0)
                        break;
        }
    if (pid>0) /// parent
        {
                for(i=0; i<c; i++)
                {
                        close(answer_pipe[i][1]);  /// close answer pipe on writing
                        close(request_pipe[i][1]);  /// close request pipe on writing
                        close(data_pipe[i][0]);  /// close data pipe on reading
                }
                fp=fopen("list.txt", "r");
                if (fp==NULL)
                        return 3;
                i=0;
                while (fgets(str, sizeof(str), fp)!=NULL)
                {
                        /// wait for ask
                        read(request_pipe[i][0], &cR, 1);
                        /// sending first the number of characters to read
                        /// and then the file name
                        num_char_str=(strlen(str) +1);
                        write(data_pipe[i][1], &num_char_str, sizeof(int));
                        write(data_pipe[i][1], str, num_char_str);
                        /// read the answer
                        read(answer_pipe[i][0], &id, sizeof(int));
                        //pids[i]=id;
                        read(answer_pipe[i][0], &line_sort, sizeof(int));
                        if (i==c-1)
                                i=-1;
                        i++;
                }
                /// sending termination signal to children
                for (i=0; i<c; i++)
                        kill(pids[i], SIGPIPE);
                /// producing all_sorted.txt
                strcpy(str, "touch all_sorted.txt");
                system(str);
                sprintf(str, "find %s -name \"*.txt\" -exec cat \"{}\"\";\" > all_sorted.txt", dir);
                system(str);
                /// sorting all_sorted

        }
        if (pid == 0) /// child
        {
                close(answer_pipe[i][0]);  /// close answer pipe on reading
                close(request_pipe[i][0]);  /// close request pipe on reading
                close(data_pipe[i][1]);  /// close data pipe on writing
                while (1)
                {
                        /// send request to parent
                        write(request_pipe[i][1], &cW, 1);
                        /// read length of string
                        read(data_pipe[i][0], &num_char_str, sizeof(int));
                        /// read the file name
                        read(data_pipe[i][0], str, num_char_str);
                        /// sorting
                        str=strcat(dir, str);
                        sprintf(ssys, "/usr/bin/sort -n -o %s %s", str, str);
printf("     1111    \n");
                        system(ssys);
printf("     2222   \n");
                        /// sending back data
                        id=getpid();
                        write(answer_pipe[i][1], &id, sizeof(int));
                        //sprintf(str, "wc -l %s/%s", dir, str);
                        //fpp=popen(str, "r");
                        //fscanf(fpp, "%d", &line_sort);
                        //pclose(fpp);
                        line_sort=1;
                        write(answer_pipe[i][1], &line_sort, sizeof(int));
                }
        }

        return 0;

}


问:
Generating Braintree client token in advance
I'm looking to reduce the response time for a payment page using the Braintree Drop-In UI (JS v3 SDK).

When a user visits the payment page, I'm generating the client token in PHP as per the docs here:

https://developers.braintreepayments.com/reference/request/client-token/generate/php

This request seems to be slowing things down with the token sometimes taking a while to generate.

I was wondering if there are any issues with generating tokens in advance and storing them on my server to speed things up?

I'm aware that tokens can not be re-used from this question here:

Braintree client token expiration

Is anyone aware of any issues as long as the token is discarded from the server once used. I can't seem to find any details of expiration of client tokens in the Braintree docs.

Thanks.

答:
Include Braintree class and write below code to generate client token.This code will generate client token only if you will set merchant details and secret key details .

```<code>Braintree_ClientToken::generate();
</code>```

Body:
Include Braintree class and write below code to generate client token.This code will generate client token only if you will set merchant details and secret key details .

Braintree_ClientToken::generate();


问:
How to add values/names of checkbox to a variable on form submit?
I have a set of checkboxes in a form that has a submit button.

```<code><form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...
</code>```

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.

答:
HTML:

<input type="checkbox" name="checkboxarr[]" value="3">

PHP:

<?php if (isset($_REQUEST['submit-form']))
  {    print_r($_POST); }
  ?>

Body:
I have a set of checkboxes in a form that has a submit button.

<form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.


问:
error "test_input_xml: input file not opened or empty" when run quantum espresso examples
I install quantum espresso 6.2 and use cygwin.
I run example01 to test quantum espresso, which calculate energy and band structure for Si, Al, Cu and Ni. I get an error message as follows:

```<code>running the scf calculation for Si...from test_input_xml: input file not opened or empty
At line 1999 of file read_namelists.f90 (unit = 9, file = 'input_tmp.in')
Fortran runtime error: End of file

Error termination. Backtrace:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
from test_input_xml: input file not opened or empty
At line 1999 of file read_namelists.f90 (unit = 9, file = 'input_tmp.in')
Fortran runtime error: End of file
</code>```

Could you help me to overcome this problem ?

答:
What is PARA_PREFIX in your environment_variables file set to?

Try running with

```<code>PARA_PREFIX=" "
</code>```

or if you have MPI you can try

```<code>PARA_PREFIX=" mpirun -np 1 "
</code>```

Most tests and examples are meant to be run serially.

Body:
I install quantum espresso 6.2 and use cygwin.
I run example01 to test quantum espresso, which calculate energy and band structure for Si, Al, Cu and Ni. I get an error message as follows:

running the scf calculation for Si...from test_input_xml: input file not opened or empty
At line 1999 of file read_namelists.f90 (unit = 9, file = 'input_tmp.in')
Fortran runtime error: End of file

Error termination. Backtrace:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
from test_input_xml: input file not opened or empty
At line 1999 of file read_namelists.f90 (unit = 9, file = 'input_tmp.in')
Fortran runtime error: End of file

Could you help me to overcome this problem ?

Body:
What is PARA_PREFIX in your environment_variables file set to?

Try running with

PARA_PREFIX=" "

or if you have MPI you can try

PARA_PREFIX=" mpirun -np 1 "

Most tests and examples are meant to be run serially.


问:
Randomly selecting one episode per ID in long dataset
I have a long format dataset where each ID has multiple episodes, and multiple rows per episode. I would like to select at random just one episode per ID, and all its associated rows.

For example:

```<code>df <- data.frame(id = c(1,1,1,2,2,2,2),
    episode = c(1,2,2,1,1,1,2))
df
  id episode
 1  1       1
 2  1       2
 3  1       2
 4  2       1
 5  2       1
 6  2       1
 7  2       2
</code>```

... And I want to be left with this dataset:

```<code>df2
  id episode
1  1       2
2  1       2
3  2       1
4  2       1
5  2       1
</code>```

答:
Using dplyr:

```<code>set.seed(123)
df%>%group_by(id)%>%
mutate(new=sample(episode,1))%>%
filter(episode!=new)%>%
select(id,episode)

# A tibble: 5 x 2
# Groups:   id [2]
#     id    episode
#    <dbl>   <dbl>
#1     1       2
#2     1       2
#3     2       1
#4     2       1
#5     2       1
</code>```

Body:
I have a long format dataset where each ID has multiple episodes, and multiple rows per episode. I would like to select at random just one episode per ID, and all its associated rows.

For example:

df <- data.frame(id = c(1,1,1,2,2,2,2),
    episode = c(1,2,2,1,1,1,2))
df
  id episode
 1  1       1
 2  1       2
 3  1       2
 4  2       1
 5  2       1
 6  2       1
 7  2       2

... And I want to be left with this dataset:

df2
  id episode
1  1       2
2  1       2
3  2       1
4  2       1
5  2       1

Body:
Using dplyr:

set.seed(123)
df%>%group_by(id)%>%
mutate(new=sample(episode,1))%>%
filter(episode!=new)%>%
select(id,episode)

# A tibble: 5 x 2
# Groups:   id [2]
#     id    episode
#    <dbl>   <dbl>
#1     1       2
#2     1       2
#3     2       1
#4     2       1
#5     2       1


问:
Retrieve specific value if set, or general if not
I have to write a query which will import some data from table. Table structure is like:

Item_ID

Plant

Price

I have second table with

Item_ID

Plant

Second table is a key, and I have to match rows from first table to get valid price. Seems to be easy, however:
In first table column plant might determinate specific plant, or have value 'ALL'. What I want to do is retrieve price for given plant, if it is set, or get price for value 'ALL' if there is no row for given plant. In other words:

```<code>If first.Plant = second.Plant
  return price
Else If first.Plant = 'ALL'
  return price
Else
  return NULL
</code>```

I can't use simple ON first.Plant = second.Plant OR first.Plant = 'ALL', because there might be two rows: one for given plant and second for rest with value 'ALL'. I need to return only first price in that case. E.g.

```<code>Item_ID  | Plant  | Price
  2      |   M1   |  10,0
  2      |  All   |  12,0
  1      |  All   |  9,0
</code>```

In that case for Item_ID = 2 and Plant = M1 the only valid price = 10, but for Item_ID = 2 and Plant = M2 price =  12, and for any Item_ID = 1 price = 9

I hope You understood something after my explanation ;)

答:
Using ROW_Number and a Common Table Expression you can ensure that ROW_NUMBER is partitioned by Item_ID and Plant and ordered such that if there are two rows then 'All' is second. You then simple select the rows with a row number = 1:

Setup

```<code>CREATE TABLE #Price
(
    Item_ID int,
    Plant Varchar(20),
    Price Decimal(6,2)
)

CREATE TABLE #Plant
(
    Item_ID int,
    Plant VARCHAR(20)
)

INSERT INTO #Price
VALUES  (2,  'M1', 10.0),
        (2, 'All', 12.0),
        (1, 'All', 9.0)

INSERT INTO #Plant
VALUES (2,  'M1'),
        (2, 'M2'),
        (1, 'M1'),
        (1, 'M2')
</code>```

Here's the query for SQL Server >= 2012

```<code>;WITH CTE
AS
(
    SELECT PL.Item_ID, PL.Plant, PR.PRice, ROW_NUMBER() OVER (PARTITION BY Pl.Item_ID, Pl.Plant ORDER BY IIF(PR.Plant = 'All', 1, 0)) AS RN
    FROM #Plant PL
    INNER JOIN #Price PR
        ON PL.Item_Id = PR.Item_Id AND  (PL.Plant = PR.Plant OR PR.Plant = 'ALL')
)
SELECT Item_Id, Plant, Price
FROM CTE
WHERE RN = 1
</code>```

And here's a version using CASE which will work for all SQL Server >= 2008 R2

```<code>;WITH CTE
AS
(
    SELECT PL.Item_ID, PL.Plant, PR.PRice, ROW_NUMBER() OVER (PARTITION BY Pl.Item_ID, Pl.Plant ORDER BY CASE WHEN PR.Plant = 'All' Then 1 Else 0 End) AS RN
    FROM #Plant PL
    INNER JOIN #Price PR
        ON PL.Item_Id = PR.Item_Id AND  (PL.Plant = PR.Plant OR PR.Plant = 'ALL')
)
SELECT Item_Id, Plant, Price
FROM CTE
WHERE RN = 1
</code>```

Body:
I have to write a query which will import some data from table. Table structure is like:

Item_ID

Plant

Price

I have second table with

Item_ID

Plant

Second table is a key, and I have to match rows from first table to get valid price. Seems to be easy, however:
In first table column plant might determinate specific plant, or have value 'ALL'. What I want to do is retrieve price for given plant, if it is set, or get price for value 'ALL' if there is no row for given plant. In other words:

If first.Plant = second.Plant
  return price
Else If first.Plant = 'ALL'
  return price
Else
  return NULL

I can't use simple ON first.Plant = second.Plant OR first.Plant = 'ALL', because there might be two rows: one for given plant and second for rest with value 'ALL'. I need to return only first price in that case. E.g.

Item_ID  | Plant  | Price
  2      |   M1   |  10,0
  2      |  All   |  12,0
  1      |  All   |  9,0

In that case for Item_ID = 2 and Plant = M1 the only valid price = 10, but for Item_ID = 2 and Plant = M2 price =  12, and for any Item_ID = 1 price = 9

I hope You understood something after my explanation ;)

Body:
Using ROW_Number and a Common Table Expression you can ensure that ROW_NUMBER is partitioned by Item_ID and Plant and ordered such that if there are two rows then 'All' is second. You then simple select the rows with a row number = 1:

Setup

CREATE TABLE #Price
(
    Item_ID int,
    Plant Varchar(20),
    Price Decimal(6,2)
)

CREATE TABLE #Plant
(
    Item_ID int,
    Plant VARCHAR(20)
)

INSERT INTO #Price
VALUES  (2,  'M1', 10.0),
        (2, 'All', 12.0),
        (1, 'All', 9.0)

INSERT INTO #Plant
VALUES (2,  'M1'),
        (2, 'M2'),
        (1, 'M1'),
        (1, 'M2')

Here's the query for SQL Server >= 2012

;WITH CTE
AS
(
    SELECT PL.Item_ID, PL.Plant, PR.PRice, ROW_NUMBER() OVER (PARTITION BY Pl.Item_ID, Pl.Plant ORDER BY IIF(PR.Plant = 'All', 1, 0)) AS RN
    FROM #Plant PL
    INNER JOIN #Price PR
        ON PL.Item_Id = PR.Item_Id AND  (PL.Plant = PR.Plant OR PR.Plant = 'ALL')
)
SELECT Item_Id, Plant, Price
FROM CTE
WHERE RN = 1

And here's a version using CASE which will work for all SQL Server >= 2008 R2

;WITH CTE
AS
(
    SELECT PL.Item_ID, PL.Plant, PR.PRice, ROW_NUMBER() OVER (PARTITION BY Pl.Item_ID, Pl.Plant ORDER BY CASE WHEN PR.Plant = 'All' Then 1 Else 0 End) AS RN
    FROM #Plant PL
    INNER JOIN #Price PR
        ON PL.Item_Id = PR.Item_Id AND  (PL.Plant = PR.Plant OR PR.Plant = 'ALL')
)
SELECT Item_Id, Plant, Price
FROM CTE
WHERE RN = 1


问:
Is it possible to loop over subfolders in Jekyll?
I'm currently trying to loop over a subfolder in Jekyll but I don't know whether this is possible.

My folder structure looks like this:

```<code>_includes
_layouts
_pages
   folder_1
   folder_2
index.html
</code>```

For example, I want to reach folder_1 by a loop how can I do this?

```<code>{% for page in pages.folder_1 %}

//xyz

{% endfor %}
</code>```

What I want is that I've a static page and on this page I want to display the title and the description of each page in one of the subfolders.

Could you please help me?

答:
Avoid naming main folder with an underscore unless you are using the _posts folder.

Then filter posts or pages checking their path:

```<code>{% assign folder1 = site.pages | where_exp: "item" , "item.path contains 'folder1'"%}
{% for item in folder1 %}
{{item.title}}
{% endfor %}
</code>```

Body:
I'm currently trying to loop over a subfolder in Jekyll but I don't know whether this is possible.

My folder structure looks like this:

_includes
_layouts
_pages
   folder_1
   folder_2
index.html

For example, I want to reach folder_1 by a loop how can I do this?

{% for page in pages.folder_1 %}

//xyz

{% endfor %}

What I want is that I've a static page and on this page I want to display the title and the description of each page in one of the subfolders.

Could you please help me?

Body:
Avoid naming main folder with an underscore unless you are using the _posts folder.

Then filter posts or pages checking their path:

{% assign folder1 = site.pages | where_exp: "item" , "item.path contains 'folder1'"%}
{% for item in folder1 %}
{{item.title}}
{% endfor %}


问:
No specs found Reshaper(2017.2.2) TypeScript(2.6.1) Jasmine(2.7.0) when using import {}
Setup:

Visual Studio 2017

Reshaper(2017.2.2)

TypeScript(2.6.1)

Jasmine(2.7.0)

Problem:

The browser show the web test launcher with the message "No specs found"

Console error visible: Uncaught ReferenceError: exports is not defined at referenceFile:2

Uncaught ReferenceError: exports is not defined at Tests.js:2

Other information:

From the developement tool if i click on referenceFile:2 I can see the source JS code of the file, with this content:

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var User = (function () {
    function User(name, surname) {
        this._name = name;
        this._surname = surname;
    }
    Object.defineProperty(User.prototype, "Name", {
        get: function () {
            return this._name;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(User.prototype, "Surname", {
        get: function () {
            return this._surname;
        },
        enumerable: true,
        configurable: true
    });
    return User;
}());
exports.User = User;
//# sourceMappingURL=User.js.map
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "lib": ["es5"],
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

package.json

```<code>{
  "name": "nodejs-console-app",
  "version": "0.0.0",
  "description": "NodejsConsoleApp",
  "main": "app.js",
  "author": {
    "name": "ms"
  },
  "devDependencies": {
    "@types/node": "^6.0.87",
    "jasmine": "^2.8.0"
  },
  "dependencies": {
    "@types/jasmine": "^2.8.2"
  }
}
</code>```

Any idea on how I can solve the problem?

UPDATE:
The problem is caused by the commonJs module type specified in tsconfig.json.
This is the default value proposed by many templates and is the one I use the most.
CommonJS unfortunately cannot be executed in the browser straight away, it needs to be packed/browserified in order to be executable in a browser.
For the source code I use Gulp>browserify and everything works correctly.

My expectation would be to have resharper doing the dirty job for me, but it is not.
How can I use resharper to run those tests with no error, in my case I wouldn't even need the browser to open so it could run in node.

答:
TypeScript module compilation does matter, I was using CommonJS but this is not supported by browsers and R# is not doing anything about it.

In tsconfig.json > compilerOptions > module, you can specify one of the following option: commonjs, amd, system, umd, es6.

With R# you can and should use es6

For more information about this:
Typescript Modules
Typescript Module Resolution

Body:
Setup:

Visual Studio 2017

Reshaper(2017.2.2)

TypeScript(2.6.1)

Jasmine(2.7.0)

Problem:

The browser show the web test launcher with the message "No specs found"

Console error visible: Uncaught ReferenceError: exports is not defined at referenceFile:2

Uncaught ReferenceError: exports is not defined at Tests.js:2

Other information:

From the developement tool if i click on referenceFile:2 I can see the source JS code of the file, with this content:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var User = (function () {
    function User(name, surname) {
        this._name = name;
        this._surname = surname;
    }
    Object.defineProperty(User.prototype, "Name", {
        get: function () {
            return this._name;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(User.prototype, "Surname", {
        get: function () {
            return this._surname;
        },
        enumerable: true,
        configurable: true
    });
    return User;
}());
exports.User = User;
//# sourceMappingURL=User.js.map

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "lib": ["es5"],
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

package.json

{
  "name": "nodejs-console-app",
  "version": "0.0.0",
  "description": "NodejsConsoleApp",
  "main": "app.js",
  "author": {
    "name": "ms"
  },
  "devDependencies": {
    "@types/node": "^6.0.87",
    "jasmine": "^2.8.0"
  },
  "dependencies": {
    "@types/jasmine": "^2.8.2"
  }
}

Any idea on how I can solve the problem?

UPDATE:
The problem is caused by the commonJs module type specified in tsconfig.json.
This is the default value proposed by many templates and is the one I use the most.
CommonJS unfortunately cannot be executed in the browser straight away, it needs to be packed/browserified in order to be executable in a browser.
For the source code I use Gulp>browserify and everything works correctly.

My expectation would be to have resharper doing the dirty job for me, but it is not.
How can I use resharper to run those tests with no error, in my case I wouldn't even need the browser to open so it could run in node.


问:
Bootstrap 4 navbar doesn't show Toggler
I created an Angular 5 application and included Bootstrap 4 via index.html. I made a basic navbar component and tried to include it in my app. But in responsive mode, I am not able to see the toggler, it appears white but when inspecting I can see it as well as clicking on it also shows the menu. Why is it not being displayed properly?

I am using a simple navbar like below:

```<code><nav class="navbar navbar-expand-lg shift">
  <a class="navbar-brand" href="#">
    <img src="logo.png" alt="Brand Logo" />
  </a>
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
    aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="nav nav-pills ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Exams</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Contact</a>
      </li>
    </ul>
  </div>
</nav>
</code>```

Here is my fiddle: jsfiddle

答:
Try this one : I just added bar's and little bit css style

```<code><nav class="navbar navbar-expand-lg shift">
  <a class="navbar-brand" href="#">
    <img src="logo.png" alt="Brand Logo" />
  </a>
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
    aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon">
      <div class="bar1"></div>
      <div class="bar1"></div>
      <div class="bar1"></div>
    </span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="nav nav-pills ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Exams</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Contact</a>
      </li>
    </ul>
  </div>
</nav>
</code>```

CSS STYLE

```<code>/* NAVIGATION */
nav ul li {
    display: inline-block;
}
nav ul li a {
    display: block;
    padding: 15px;
    text-decoration: none;
    color: #343b40;
    font-weight: 800;
    text-transform: uppercase;
    margin: 0 10px;
}
nav ul li a,
nav ul li a:after,
nav ul li a:before {
    transition: all .5s;
}
nav ul li a:hover {
    color: white;
}
/* SHIFT */
nav.shift ul li a {
    position:relative;
    z-index: 1;
}
nav.shift ul li a:hover {
    color: white;
}
nav.shift ul li a:after {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 100%;
    height: 1px;
    content: '.';
    color: transparent;
    background: #34caf7;
    visibility: none;
    opacity: 0;
    z-index: -1;
}
nav.shift ul li a:hover:after {
    opacity: 1;
    visibility: visible;
    height: 100%;
}

.navbar-toggler-right{
  background-color:red;
}

.navbar-toggler-icon{
 background-color:white;
  }

  .bar1{
       width: 30px;
    height: 2px;
    background-color: #000;
    margin: 6px 0;
    transition: 0.4s;
    }
  }
</code>```

Change the colors and styles as yours wish !
Check this out ! https://jsfiddle.net/t4h0w4pw/3/

Title: Bootstrap 4 navbar doesn't show Toggler

Body:
I created an Angular 5 application and included Bootstrap 4 via index.html. I made a basic navbar component and tried to include it in my app. But in responsive mode, I am not able to see the toggler, it appears white but when inspecting I can see it as well as clicking on it also shows the menu. Why is it not being displayed properly?

I am using a simple navbar like below:

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
    aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Features

        Exams

        Contact

Here is my fiddle: jsfiddle

Body:
Try this one : I just added bar's and little bit css style

<nav class="navbar navbar-expand-lg shift">
  <a class="navbar-brand" href="#">
    <img src="logo.png" alt="Brand Logo" />
  </a>
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
    aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon">
      <div class="bar1"></div>
      <div class="bar1"></div>
      <div class="bar1"></div>
    </span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="nav nav-pills ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Exams</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Contact</a>
      </li>
    </ul>
  </div>
</nav>

CSS STYLE

/* NAVIGATION */
nav ul li {
    display: inline-block;
}
nav ul li a {
    display: block;
    padding: 15px;
    text-decoration: none;
    color: #343b40;
    font-weight: 800;
    text-transform: uppercase;
    margin: 0 10px;
}
nav ul li a,
nav ul li a:after,
nav ul li a:before {
    transition: all .5s;
}
nav ul li a:hover {
    color: white;
}
/* SHIFT */
nav.shift ul li a {
    position:relative;
    z-index: 1;
}
nav.shift ul li a:hover {
    color: white;
}
nav.shift ul li a:after {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 100%;
    height: 1px;
    content: '.';
    color: transparent;
    background: #34caf7;
    visibility: none;
    opacity: 0;
    z-index: -1;
}
nav.shift ul li a:hover:after {
    opacity: 1;
    visibility: visible;
    height: 100%;
}

.navbar-toggler-right{
  background-color:red;
}

.navbar-toggler-icon{
 background-color:white;
  }

  .bar1{
       width: 30px;
    height: 2px;
    background-color: #000;
    margin: 6px 0;
    transition: 0.4s;
    }
  }

Change the colors and styles as yours wish !
Check this out ! https://jsfiddle.net/t4h0w4pw/3/


问:
Set a div expandable on small device
I try to expand a div while hovering it but only when the website is displayed on a small or x-small device. Is that possible ? See a picture below of what I try to achieve :

So far I have been able to only hide the yellow div when displaying the page on small device, but I have no idea about how to only reduce it and make it expandable.

Should I create a new div with those specifications and display it only on small device instead of the yellow div ? Any help and advices welcome !

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has.

Sed ut perspiciatis...

Sed ut perspiciatis...

```

答:
Try something like this with jquery

```<code>$(document).ready(function(){
if ($(window).width() < 800)
 $('.testblock').bind({
  mouseenter: function(e) {
   $(".testblock").addClass("col-sm-2");
   $(".testblock").removeClass("col-sm-1");
  },
  mouseleave: function(e) {
  $(".testblock").removeClass("col-sm-2");
   $(".testblock").addClass("col-sm-1");
  }
 });
});
</code>```

Fiddle : https://jsfiddle.net/wL7snqxe/

Title: Set a div expandable on small device

Body:
Try something like this with jquery

$(document).ready(function(){
if ($(window).width() < 800)
 $('.testblock').bind({
  mouseenter: function(e) {
   $(".testblock").addClass("col-sm-2");
   $(".testblock").removeClass("col-sm-1");
  },
  mouseleave: function(e) {
  $(".testblock").removeClass("col-sm-2");
   $(".testblock").addClass("col-sm-1");
  }
 });
});

Fiddle : https://jsfiddle.net/wL7snqxe/


问:
How to manage shutdown of ExecutorService when we allow to inject it?
Suppose I am writing a service, which needs some executor service/separate thread. I give ability to use factory method to not worry about executor service, but still want to allow passing existing executor service (dependency injection).

How can I manage for executorService.shutdown()?

Example code:

```<code>public class ThingsScheduler {

    private final ExecutorService executorService;

    public ThingsScheduler(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public static ThingsScheduler createDefaultSingleThreaded() {
        return new ThingsScheduler(Executors.newSingleThreadExecutor());
    }

    public scheduleThing() {
        executorService.submit(new SomeTask());
    }

    // implement Closeable?
    // @PreDestory?
    // .shutdown() + JavaDoc?
}
</code>```

There are several problems

We should have ability to shutdown internally created executor, or in best case handle it automatically (Spring @PreDestory, or in worst case finalize())

We shold rather not shutdown executor if it's externally managed (injected)

We could create some attribute stating if executor is created by our class or if it's injected, and then on finalize/@PreDestroy/shutdown hook we could shut down it, but it not feels elegant for me.

Maybe we should completely resign from factory method and always require injection pushing executor lifecycle management to the client?

答: I would say that solution in fully up to you. Third-party libraries like spring widely use a dedicated attribute to understand who should release a particular resource depending on its creator. mongoInstanceCreated in SimpleMongoDbFactory, localServer in SimpleHttpServerJaxWsServiceExporter, etc. But they do it because these classes are created only for external usage. If your class is only used in your application code than you can either inject executorService and don't care about its releasing or create and release it inside the class which uses it. This choice depends on your class/application design (does your class work with any executorService, whether executorService is shared and used by other classes, etc). Otherwise i don't see other option than the dedicated flag.

Body:
Suppose I am writing a service, which needs some executor service/separate thread. I give ability to use factory method to not worry about executor service, but still want to allow passing existing executor service (dependency injection).

How can I manage for executorService.shutdown()?

Example code:

public class ThingsScheduler {

    private final ExecutorService executorService;

    public ThingsScheduler(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public static ThingsScheduler createDefaultSingleThreaded() {
        return new ThingsScheduler(Executors.newSingleThreadExecutor());
    }

    public scheduleThing() {
        executorService.submit(new SomeTask());
    }

    // implement Closeable?
    // @PreDestory?
    // .shutdown() + JavaDoc?
}

There are several problems

We should have ability to shutdown internally created executor, or in best case handle it automatically (Spring @PreDestory, or in worst case finalize())

We shold rather not shutdown executor if it's externally managed (injected)

We could create some attribute stating if executor is created by our class or if it's injected, and then on finalize/@PreDestroy/shutdown hook we could shut down it, but it not feels elegant for me.

Maybe we should completely resign from factory method and always require injection pushing executor lifecycle management to the client?