问:
Binary XML file line #0: Error inflating class
My application stop and I ge Binary XML file error on line #0. It`s kinda weird, because I didn't see problem like this with line 0, so I need your help, everyone. Thanks!
This Works Fine On API greater than 20 only lower than API devices is crashing the application

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.vickyy.iwasframed, PID: 7818
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vickyy.iwasframed/com.example.vickyy.iwasframed.ImageSize}: android.view.InflateException: Binary XML file line #0: Error inflating class com.example.vickyy.iwasframed.CustomFrame
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                  at android.app.ActivityThread.access$900(ActivityThread.java:161)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5356)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.example.vickyy.iwasframed.CustomFrame
                  at android.view.LayoutInflater.createView(LayoutInflater.java:609)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
                  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                  at com.example.vickyy.iwasframed.ImageSize.onCreate(ImageSize.java:31)
                  at android.app.Activity.performCreate(Activity.java:5426)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                  at android.app.ActivityThread.access$900(ActivityThread.java:161)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5356)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
                  at java.lang.Class.getConstructorOrMethod(Class.java:472)
                  at java.lang.Class.getConstructor(Class.java:446)
                  at android.view.LayoutInflater.createView(LayoutInflater.java:574)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
                  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                  at com.example.vickyy.iwasframed.ImageSize.onCreate(ImageSize.java:31)
                  at android.app.Activity.performCreate(Activity.java:5426)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                  at android.app.ActivityThread.access$900(ActivityThread.java:161)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5356)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                  at dalvik.system.NativeStart.main(Native Method)
</code>```

I/Process: Sending signal. PID: 7818 SIG: 9
Application terminated.

this is xmlFile

```<code><LinearLayout 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:orientation="vertical"
android:background="@color/AppColor"
tools:context="com.example.vickyy.iwasframed.FrameActivity">

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:id="@+id/toolbar"
    android:background="@color/ActionBarColor">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ActionBarColor">

        <Button
            android:id="@+id/btnDone"
            android:layout_width="45dp"
            android:layout_height="30dp"
            android:text="Done"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:backgroundTint="@color/ButtonColor"
            android:layout_alignParentLeft="true"
            android:textSize="8sp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="USE IMAGE SIZE"
            android:textColor="@android:color/white"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:textStyle="bold"
            android:textSize="16sp"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:orientation="horizontal"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="WIDTH:"
            android:layout_weight="1"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="HEIGHT:"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MAT OVERLAP:"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"/>

    </LinearLayout>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="0dp"
    android:layout_marginRight="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:orientation="horizontal">
    <EditText
        android:layout_weight="1"
        android:id="@+id/edtWidth"
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:paddingLeft="10dp"
        android:layout_toLeftOf="@+id/txtX"
        android:textSize="10sp"

        android:textStyle="bold"
        android:textCursorDrawable="@null"
        android:background="@drawable/custom_edittext"
        android:inputType="numberDecimal"
        android:layout_marginRight="10dp">

    </EditText>

    <EditText
        android:layout_weight="1"
        android:id="@+id/edtHeight"
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:layout_toRightOf="@+id/txtX"
        android:textCursorDrawable="@null"
        android:layout_marginLeft="10dp"
        android:textSize="10sp"
        android:paddingLeft="10dp"

        android:textStyle="bold"
        android:inputType="numberDecimal"
        android:background="@drawable/custom_edittext"
        android:layout_alignParentRight="true">

    </EditText>

        <EditText
            android:layout_weight="1"
            android:id="@+id/edtOverlap"
            android:layout_width="match_parent"
            android:layout_height="25dp"
            android:layout_toRightOf="@+id/txtX"
            android:textCursorDrawable="@null"
            android:layout_marginLeft="10dp"
            android:textSize="10sp"
            android:paddingLeft="10dp"

            android:textStyle="bold"
            android:inputType="numberDecimal"
            android:background="@drawable/custom_edittext"
            android:layout_alignParentRight="true"></EditText>

    </LinearLayout>

</RelativeLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:id="@+id/frameLayout">

    <com.example.vickyy.iwasframed.CustomFrame
        android:id="@+id/imgFrame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="255dp"
        android:layout_height="360dp"
        android:scaleType="fitXY"
        android:layout_gravity="center"
        android:src="@drawable/flower"
        />

</FrameLayout>
</code>```

and this is the custom class that i code for draw rectangle with double and triple Mat

```<code>public class CustomFrame extends AppCompatImageView{

Paint paint;
int top,left,right,bottom;
Context context;
public CustomFrame(Context context) {
    super(context);
    paint = new Paint();
    this.context=context;
}

CustomFrame(Context context, AttributeSet attrs) {
    super(context, attrs);
}

CustomFrame(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    SharedPreferences sharedPreferences = getContext().getSharedPreferences("Params", Context.MODE_PRIVATE);
    int color = sharedPreferences.getInt("color",R.color.black);
    int canvasW = getWidth();
    int canvasH = getHeight();
    Point centerOfCanvas = new Point(canvasW / 2, canvasH / 2);
    int width = sharedPreferences.getInt("width",0);
    int height = sharedPreferences.getInt("height",0);
    int overLap=sharedPreferences.getInt("OverLap",0);
    boolean start=sharedPreferences.getBoolean("start",false);

    int rectW = width*75;  //convert to pixel
    int rectH = height*75;
    left = centerOfCanvas.x - (rectW / 2);
    top = centerOfCanvas.y - (rectH / 2);
    right = centerOfCanvas.x + (rectW / 2);
    bottom = centerOfCanvas.y + (rectH / 2);
    paint = new Paint();
    paint.setColor(color);
    paint.setStyle(Paint.Style.STROKE);
/*    if(start) {
        paint.setStrokeWidth(20);
    }
    else{

    }*/
    paint.setStrokeWidth(overLap);
    int l,t,r,b;
    int tripleLeft,tripleTop,tripleRight,tripleBottom;

    boolean doubleMat = sharedPreferences.getBoolean("DoubleMat",false);
    boolean tripleMat = sharedPreferences.getBoolean("TripleMat",false);

    if(doubleMat){
        int matHeight = sharedPreferences.getInt("MatHeight",0);
        int matWidth = sharedPreferences.getInt("MatWidth",0);
        int thickness=sharedPreferences.getInt("Doublethickness",0);
        int matW = (width)*75;
        int matH = (height)*75;
        int matw=matW-overLap;
        int math=matH-overLap;
         l = centerOfCanvas.x - (matw / 2);
         t = centerOfCanvas.y - (math / 2);
         r = centerOfCanvas.x + (matw / 2);
         b = centerOfCanvas.y + (math / 2);
        Paint paint1 = new Paint();
        paint1.setColor(color);
        paint1.setStyle(Paint.Style.STROKE);

        paint1.setStrokeWidth(thickness);      //inside

        paint.setStrokeWidth(overLap);  //mat

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("MatHeight",math);
        editor.putInt("MatWidth",matw);
        editor.commit();

        canvas.drawRect(left, top, right, bottom, paint);
        canvas.drawRect(l, t, r, b, paint1);

    }
    else if(tripleMat){
        int matHeight = sharedPreferences.getInt("MatHeight",0);
        int matWidth = sharedPreferences.getInt("MatWidth",0);
        int dThickness=sharedPreferences.getInt("Doublethickness",0);
        int tThickness=sharedPreferences.getInt("Triplethickness",0);

        int matW = (width)*75;  //-2 here
        int matH = (height)*75;

        int matw=matW-overLap;
        int math=matH-overLap;

        l = centerOfCanvas.x - (matw / 2);
        t = centerOfCanvas.y - (math / 2);
        r = centerOfCanvas.x + (matw / 2);
        b = centerOfCanvas.y + (math / 2);  //inside

        int tripleWidth=(width)*75;
        int tripleHeight=(height)*75;

        int tmatw=tripleWidth-dThickness-overLap;
        int tmath=tripleHeight-dThickness-overLap;

        tripleLeft=centerOfCanvas.x-(tmatw/2);
        tripleTop=centerOfCanvas.y-(tmath/2);
        tripleRight=centerOfCanvas.x+(tmatw/2);
        tripleBottom=centerOfCanvas.y+(tmath/2);

        Paint triplePaint=new Paint();
        triplePaint.setColor(color);
        triplePaint.setStyle(Paint.Style.STROKE);

        triplePaint.setStrokeWidth(overLap);

        Paint paint1 = new Paint();
        paint1.setColor(color);
        paint1.setStyle(Paint.Style.STROKE);

        paint1.setStrokeWidth(dThickness);      //inside
        paint.setStrokeWidth((int)tThickness);  //mat

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("MatHeight",tmath);
        editor.putInt("MatWidth",tmatw);
        editor.commit();

        canvas.drawRect(left, top, right, bottom, triplePaint); //outer
        canvas.drawRect(l, t, r, b, paint1);  //inside
       canvas.drawRect(tripleLeft,tripleTop,tripleRight,tripleBottom,paint); //outside

    }
    else {

   /*     Rect r=new Rect(left,top,right,bottom);
        //left
        canvas.drawLine(r.left,r.top,r.left,r.bottom,paint);
        //top
        canvas.drawLine(r.left,r.top,r.right,r.top,paint2);
        //right
        canvas.drawLine(r.right,r.top,r.right,r.bottom,paint);
        //bottom
        canvas.drawLine(r.left,r.bottom,r.right,r.bottom,paint2);*/

       // canvas.drawLine();
       // String text=String.valueOf(overLap);
       canvas.drawRect(left, top, right, bottom, paint);
    //   canvas.drawText(text,left,bottom,paint);
     }

   }

 }
</code>```

答: Your constructors need to be public.  It can't access a private constructor when inflating.  Particularly the 2 variable one (your one variable is the only public one right now).</p>

Body:
My application stop and I ge Binary XML file error on line #0. It`s kinda weird, because I didn't see problem like this with line 0, so I need your help, everyone. Thanks!
This Works Fine On API greater than 20 only lower than API devices is crashing the application

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.vickyy.iwasframed, PID: 7818
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vickyy.iwasframed/com.example.vickyy.iwasframed.ImageSize}: android.view.InflateException: Binary XML file line #0: Error inflating class com.example.vickyy.iwasframed.CustomFrame
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                  at android.app.ActivityThread.access$900(ActivityThread.java:161)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5356)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.example.vickyy.iwasframed.CustomFrame
                  at android.view.LayoutInflater.createView(LayoutInflater.java:609)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
                  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                  at com.example.vickyy.iwasframed.ImageSize.onCreate(ImageSize.java:31)
                  at android.app.Activity.performCreate(Activity.java:5426)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                  at android.app.ActivityThread.access$900(ActivityThread.java:161)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5356)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
                  at java.lang.Class.getConstructorOrMethod(Class.java:472)
                  at java.lang.Class.getConstructor(Class.java:446)
                  at android.view.LayoutInflater.createView(LayoutInflater.java:574)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
                  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                  at com.example.vickyy.iwasframed.ImageSize.onCreate(ImageSize.java:31)
                  at android.app.Activity.performCreate(Activity.java:5426)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                  at android.app.ActivityThread.access$900(ActivityThread.java:161)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5356)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                  at dalvik.system.NativeStart.main(Native Method)

I/Process: Sending signal. PID: 7818 SIG: 9
Application terminated.

this is xmlFile

<LinearLayout 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:orientation="vertical"
android:background="@color/AppColor"
tools:context="com.example.vickyy.iwasframed.FrameActivity">

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:id="@+id/toolbar"
    android:background="@color/ActionBarColor">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ActionBarColor">

        <Button
            android:id="@+id/btnDone"
            android:layout_width="45dp"
            android:layout_height="30dp"
            android:text="Done"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:backgroundTint="@color/ButtonColor"
            android:layout_alignParentLeft="true"
            android:textSize="8sp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="USE IMAGE SIZE"
            android:textColor="@android:color/white"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:textStyle="bold"
            android:textSize="16sp"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:orientation="horizontal"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="WIDTH:"
            android:layout_weight="1"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="HEIGHT:"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MAT OVERLAP:"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"/>

    </LinearLayout>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="0dp"
    android:layout_marginRight="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:orientation="horizontal">
    <EditText
        android:layout_weight="1"
        android:id="@+id/edtWidth"
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:paddingLeft="10dp"
        android:layout_toLeftOf="@+id/txtX"
        android:textSize="10sp"

        android:textStyle="bold"
        android:textCursorDrawable="@null"
        android:background="@drawable/custom_edittext"
        android:inputType="numberDecimal"
        android:layout_marginRight="10dp">

    </EditText>

    <EditText
        android:layout_weight="1"
        android:id="@+id/edtHeight"
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:layout_toRightOf="@+id/txtX"
        android:textCursorDrawable="@null"
        android:layout_marginLeft="10dp"
        android:textSize="10sp"
        android:paddingLeft="10dp"

        android:textStyle="bold"
        android:inputType="numberDecimal"
        android:background="@drawable/custom_edittext"
        android:layout_alignParentRight="true">

    </EditText>

        <EditText
            android:layout_weight="1"
            android:id="@+id/edtOverlap"
            android:layout_width="match_parent"
            android:layout_height="25dp"
            android:layout_toRightOf="@+id/txtX"
            android:textCursorDrawable="@null"
            android:layout_marginLeft="10dp"
            android:textSize="10sp"
            android:paddingLeft="10dp"

            android:textStyle="bold"
            android:inputType="numberDecimal"
            android:background="@drawable/custom_edittext"
            android:layout_alignParentRight="true"></EditText>

    </LinearLayout>

</RelativeLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:id="@+id/frameLayout">

    <com.example.vickyy.iwasframed.CustomFrame
        android:id="@+id/imgFrame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="255dp"
        android:layout_height="360dp"
        android:scaleType="fitXY"
        android:layout_gravity="center"
        android:src="@drawable/flower"
        />

</FrameLayout>

and this is the custom class that i code for draw rectangle with double and triple Mat

public class CustomFrame extends AppCompatImageView{

Paint paint;
int top,left,right,bottom;
Context context;
public CustomFrame(Context context) {
    super(context);
    paint = new Paint();
    this.context=context;
}

CustomFrame(Context context, AttributeSet attrs) {
    super(context, attrs);
}

CustomFrame(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    SharedPreferences sharedPreferences = getContext().getSharedPreferences("Params", Context.MODE_PRIVATE);
    int color = sharedPreferences.getInt("color",R.color.black);
    int canvasW = getWidth();
    int canvasH = getHeight();
    Point centerOfCanvas = new Point(canvasW / 2, canvasH / 2);
    int width = sharedPreferences.getInt("width",0);
    int height = sharedPreferences.getInt("height",0);
    int overLap=sharedPreferences.getInt("OverLap",0);
    boolean start=sharedPreferences.getBoolean("start",false);

    int rectW = width*75;  //convert to pixel
    int rectH = height*75;
    left = centerOfCanvas.x - (rectW / 2);
    top = centerOfCanvas.y - (rectH / 2);
    right = centerOfCanvas.x + (rectW / 2);
    bottom = centerOfCanvas.y + (rectH / 2);
    paint = new Paint();
    paint.setColor(color);
    paint.setStyle(Paint.Style.STROKE);
/*    if(start) {
        paint.setStrokeWidth(20);
    }
    else{

    }*/
    paint.setStrokeWidth(overLap);
    int l,t,r,b;
    int tripleLeft,tripleTop,tripleRight,tripleBottom;

    boolean doubleMat = sharedPreferences.getBoolean("DoubleMat",false);
    boolean tripleMat = sharedPreferences.getBoolean("TripleMat",false);

    if(doubleMat){
        int matHeight = sharedPreferences.getInt("MatHeight",0);
        int matWidth = sharedPreferences.getInt("MatWidth",0);
        int thickness=sharedPreferences.getInt("Doublethickness",0);
        int matW = (width)*75;
        int matH = (height)*75;
        int matw=matW-overLap;
        int math=matH-overLap;
         l = centerOfCanvas.x - (matw / 2);
         t = centerOfCanvas.y - (math / 2);
         r = centerOfCanvas.x + (matw / 2);
         b = centerOfCanvas.y + (math / 2);
        Paint paint1 = new Paint();
        paint1.setColor(color);
        paint1.setStyle(Paint.Style.STROKE);

        paint1.setStrokeWidth(thickness);      //inside

        paint.setStrokeWidth(overLap);  //mat

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("MatHeight",math);
        editor.putInt("MatWidth",matw);
        editor.commit();

        canvas.drawRect(left, top, right, bottom, paint);
        canvas.drawRect(l, t, r, b, paint1);

    }
    else if(tripleMat){
        int matHeight = sharedPreferences.getInt("MatHeight",0);
        int matWidth = sharedPreferences.getInt("MatWidth",0);
        int dThickness=sharedPreferences.getInt("Doublethickness",0);
        int tThickness=sharedPreferences.getInt("Triplethickness",0);

        int matW = (width)*75;  //-2 here
        int matH = (height)*75;

        int matw=matW-overLap;
        int math=matH-overLap;

        l = centerOfCanvas.x - (matw / 2);
        t = centerOfCanvas.y - (math / 2);
        r = centerOfCanvas.x + (matw / 2);
        b = centerOfCanvas.y + (math / 2);  //inside

        int tripleWidth=(width)*75;
        int tripleHeight=(height)*75;

        int tmatw=tripleWidth-dThickness-overLap;
        int tmath=tripleHeight-dThickness-overLap;

        tripleLeft=centerOfCanvas.x-(tmatw/2);
        tripleTop=centerOfCanvas.y-(tmath/2);
        tripleRight=centerOfCanvas.x+(tmatw/2);
        tripleBottom=centerOfCanvas.y+(tmath/2);

        Paint triplePaint=new Paint();
        triplePaint.setColor(color);
        triplePaint.setStyle(Paint.Style.STROKE);

        triplePaint.setStrokeWidth(overLap);

        Paint paint1 = new Paint();
        paint1.setColor(color);
        paint1.setStyle(Paint.Style.STROKE);

        paint1.setStrokeWidth(dThickness);      //inside
        paint.setStrokeWidth((int)tThickness);  //mat

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("MatHeight",tmath);
        editor.putInt("MatWidth",tmatw);
        editor.commit();

        canvas.drawRect(left, top, right, bottom, triplePaint); //outer
        canvas.drawRect(l, t, r, b, paint1);  //inside
       canvas.drawRect(tripleLeft,tripleTop,tripleRight,tripleBottom,paint); //outside

    }
    else {

   /*     Rect r=new Rect(left,top,right,bottom);
        //left
        canvas.drawLine(r.left,r.top,r.left,r.bottom,paint);
        //top
        canvas.drawLine(r.left,r.top,r.right,r.top,paint2);
        //right
        canvas.drawLine(r.right,r.top,r.right,r.bottom,paint);
        //bottom
        canvas.drawLine(r.left,r.bottom,r.right,r.bottom,paint2);*/

       // canvas.drawLine();
       // String text=String.valueOf(overLap);
       canvas.drawRect(left, top, right, bottom, paint);
    //   canvas.drawText(text,left,bottom,paint);
     }

   }

 }


来源: stackexchange

问:
how to separated One column to two with cases
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

```<code> select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number
</code>```

答:
```<code>BEGIN TRAN

CREATE TABLE #Data (
    Doc_Type VARCHAR(10),
    Batch INT,
    Qty DECIMAL(4,2)
    );
INSERT INTO #Data VALUES
('AA', 1, 20.5),
('BB', 2, 10  ),
('AA', 3, 6   ),
('BB', 4, 7   ),
('AA', 5, 8   );

SELECT ISNULL(CASE WHEN Doc_Type='AA'THEN CONVERT(NVARCHAR(10),QTY) END,'') Soaking_In ,
ISNULL(CASE WHEN Doc_Type='BB'THEN CONVERT(NVARCHAR(10),QTY) END,'')  Soaking_Out
FROM #Data

ROLLBACK TRAN
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

 select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number


问:
Uber's API returning 404 during CORS preflight request
I'm attempting to use the Uber API in my JavaScript client.

I'm aware that this involves CORS, since my client will be accessing the Uber API directly via AJAX.

In the Uber Developers Dashboard, I set my Origin URI correctly. Then, I set up the most simple example I could find. This came from Uber's docs:

```<code><!DOCTYPE html>
<html>

<head>
    <title>Uber API Demo</title>
</head>

<body>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://api.uber.com/v1.2/products?latitude=37.7759792&longitude=-122.41823');
        xhr.setRequestHeader("Authorization", "Token <ServerToken>");
        xhr.send();
    </script>
</body>

</html>
</code>```

Looking at the Console in Chrome Dev Tools, this is what I see:

And, most interesting, the Network tab:

My browser is changing my HTTP POST into an HTTP OPTIONS request (part of the CORS preflight defined in the fetch spec), which it looks like Uber does not support. Uber's server should reply with the response headers, authorizing my client to finish its API request. Instead, they are returning a 404.

In summary:

Uber's docs say they support CORS.

I have my Origin URI set correctly in Uber's Developer Dashboard

The CORS spec says if I'm doing an HTTP POST with Authorization header, that's a non-simple request and requires the HTTP OPTIONS preflight.

My browser is doing exactly that, sending a request using HTTP method OPTIONS that includes the Origin header (which matches the Origin URI set in my Uber Developer Dashboard.)

Uber is returning status 404 (not found)

Anyone know what's going on here?

答:
When making requests to Uber API endpoints from frontend JavaScript code running in a browser, instead of adding an Authorization header to the request, you need to add an access_token query parameter to the request URL, like this:

```<code>https://api.uber.com/v1.2/products?access_token=<TOKEN>&latitude=XXX&longitude=XXX
</code>```

See https://developer.uber.com/docs/trip-experiences/guides/authentication#use-bearer-token

Uber's docs say they support CORS

Yeah, the docs aren’t completely accurate in making that  claim.

My browser is changing my HTTP POST into an HTTP OPTIONS request…

To be more precise: The browser’s not changing the POST into an OPTIONS; instead the browser’s doing an OPTIONS request before trying your POST request. And the reason the browser’s doing that is because your code adds an Authorization header to the request.

(part of the CORS preflight defined in the fetch spec), which it looks like Uber does not support

Right. And that’s where the claim in the Uber API docs that they support CORS isn’t completely accurate. They don’t actually fully support CORS; specifically, their API endpoints don’t support handling of CORS preflight OPTIONS requests at all.

And adding an Authorization header to a request from frontend JavaScript running in a browser causes the browser to do a preflight OPTIONS request.

So because the Uber API endpoints don’t support that, you can’t make requests from frontend JavaScript code to Uber API endpoints using an Authorization request header to provide the credentials. You need to instead add the access_token query parameter to the request URL.

Body:
I'm attempting to use the Uber API in my JavaScript client.

I'm aware that this involves CORS, since my client will be accessing the Uber API directly via AJAX.

In the Uber Developers Dashboard, I set my Origin URI correctly. Then, I set up the most simple example I could find. This came from Uber's docs:

<!DOCTYPE html>

    <title>Uber API Demo</title>

Looking at the Console in Chrome Dev Tools, this is what I see:

And, most interesting, the Network tab:

My browser is changing my HTTP POST into an HTTP OPTIONS request (part of the CORS preflight defined in the fetch spec), which it looks like Uber does not support. Uber's server should reply with the response headers, authorizing my client to finish its API request. Instead, they are returning a 404.

In summary:

Uber's docs say they support CORS.

I have my Origin URI set correctly in Uber's Developer Dashboard

The CORS spec says if I'm doing an HTTP POST with Authorization header, that's a non-simple request and requires the HTTP OPTIONS preflight.

My browser is doing exactly that, sending a request using HTTP method OPTIONS that includes the Origin header (which matches the Origin URI set in my Uber Developer Dashboard.)

Uber is returning status 404 (not found)

Anyone know what's going on here?

Body:
When making requests to Uber API endpoints from frontend JavaScript code running in a browser, instead of adding an Authorization header to the request, you need to add an access_token query parameter to the request URL, like this:

https://api.uber.com/v1.2/products?access_token=<TOKEN>&latitude=XXX&longitude=XXX

See https://developer.uber.com/docs/trip-experiences/guides/authentication#use-bearer-token

Uber's docs say they support CORS

Yeah, the docs aren’t completely accurate in making that  claim.

My browser is changing my HTTP POST into an HTTP OPTIONS request…

To be more precise: The browser’s not changing the POST into an OPTIONS; instead the browser’s doing an OPTIONS request before trying your POST request. And the reason the browser’s doing that is because your code adds an Authorization header to the request.

(part of the CORS preflight defined in the fetch spec), which it looks like Uber does not support

Right. And that’s where the claim in the Uber API docs that they support CORS isn’t completely accurate. They don’t actually fully support CORS; specifically, their API endpoints don’t support handling of CORS preflight OPTIONS requests at all.

And adding an Authorization header to a request from frontend JavaScript running in a browser causes the browser to do a preflight OPTIONS request.

So because the Uber API endpoints don’t support that, you can’t make requests from frontend JavaScript code to Uber API endpoints using an Authorization request header to provide the credentials. You need to instead add the access_token query parameter to the request URL.


问:
Cannot edit embedded Google Calendar when opening browser with geckodriver
So I am making a Magic Mirror for my CPS class, and I made it so it will have multiple displays using browser tabs in fullscreen mode. For one of the displays, I wanted to have the embedded Google Calendar scaled to fit my 27 inch monitor (which Google supplies from the Calendar settings). The calendar works when I open it in Firefox normally, but when Firefox is opened with geckodriver using selenium, the calendar shows up, but in its generic state, and there is no way to edit it. I have tried opening the .html page in other browsers and they all work. This is what it looks like:
GeckoDriver Display, FireFox Display.
The Calendar involves using an iframe tag, which I have tried changing to an object tag with the same result. Here is the iframe code:

```<code><iframe src="https://calendar.google.com/calendar/embed?showTitle=0&showDate=0&showPrint=0&showTabs=0&
showCalendars=0&height=1810&wkst=1&bgcolor=%23000000&src=tvanderlinden8%40gmail.com&color=%2329527A&
src=%23contacts%40group.v.calendar.google.com&color=%2329527A&src=en.usa%23holiday%40group.v.calendar.google.com&
color=%2329527A&ctz=America%2FNew_York" style="border-width:0"width="1000" height="1800" frameborder="0" scrolling="no"></iframe>
</code>```

Along with my Python opening each html file:

```<code># Imports
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Create new browser and open all display tabs

# Open Firefox dir
driver = webdriver.Firefox()

# Open google tab
driver.get('http://google.com')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')

# Open MagicMirror.html, MagicMirror2.html, and MagicMirror3.html (all 3 displays)
driver.get('/home/pi/Desktop/MagicMirror/MagicMirror.html')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.get('/home/pi/Desktop/MagicMirror/MagicMirror2.html')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.get('/home/pi/Desktop/MagicMirror/MagicMirror3.html')

# Close google tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
# Set webpage to full screen
driver.find_element_by_tag_name('body').send_keys(Keys.F11)

# Variable used to determine if display is showing 1st or 3rd display
disNum = 1

# Input to change display
while(True):
    display = int(input("Please select a display: "))

    # Moves right a display unless it is at the last display
    if (display == 1 and disNum != 3):
         driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
         disNum += 1

    # Moves left a display unless it is at the first display
    if (display == 2 and disNum != 1):
        driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.SHIFT + Keys.TAB)
        disNum -= 1
</code>```

There are no Errors since it does "work" in a way. It just doesn't work the way I need it to.

答:
I figured out a solution that works perfectly.

```<code><object data="https://calendar.google.com/calendar/embed?showTitle=0&showNav=0&
showDate=0&showPrint=0&showTabs=0&showCalendars=0&showTz=0&height=1400&
wkst=1&bgcolor=%23000000&src=tvanderlinden8%40gmail.com&color=%2329527A&
data=%23contacts%40group.v.calendar.google.com&color=%2329527A&
src=en.usa%23holiday%40group.v.calendar.google.com&color=%2329527A&
ctz=America%2FNew_York" style="border-width:0" width="1000" height="1820"></object>
</code>```

You're suppose to change all 'src's to 'data', but I found if you only change the beginning and for %23contacts%... to 'data' fixes the problem. Make sure you are logged into your Google acount as well so it can retrieve your Calendar data.

Body:
So I am making a Magic Mirror for my CPS class, and I made it so it will have multiple displays using browser tabs in fullscreen mode. For one of the displays, I wanted to have the embedded Google Calendar scaled to fit my 27 inch monitor (which Google supplies from the Calendar settings). The calendar works when I open it in Firefox normally, but when Firefox is opened with geckodriver using selenium, the calendar shows up, but in its generic state, and there is no way to edit it. I have tried opening the .html page in other browsers and they all work. This is what it looks like:
GeckoDriver Display, FireFox Display.
The Calendar involves using an iframe tag, which I have tried changing to an object tag with the same result. Here is the iframe code:

Along with my Python opening each html file:

# Imports
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Create new browser and open all display tabs

# Open Firefox dir
driver = webdriver.Firefox()

# Open google tab
driver.get('http://google.com')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')

# Open MagicMirror.html, MagicMirror2.html, and MagicMirror3.html (all 3 displays)
driver.get('/home/pi/Desktop/MagicMirror/MagicMirror.html')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.get('/home/pi/Desktop/MagicMirror/MagicMirror2.html')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.get('/home/pi/Desktop/MagicMirror/MagicMirror3.html')

# Close google tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
# Set webpage to full screen
driver.find_element_by_tag_name('body').send_keys(Keys.F11)

# Variable used to determine if display is showing 1st or 3rd display
disNum = 1

# Input to change display
while(True):
    display = int(input("Please select a display: "))

    # Moves right a display unless it is at the last display
    if (display == 1 and disNum != 3):
         driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
         disNum += 1

    # Moves left a display unless it is at the first display
    if (display == 2 and disNum != 1):
        driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.SHIFT + Keys.TAB)
        disNum -= 1

There are no Errors since it does "work" in a way. It just doesn't work the way I need it to.

Body:
I figured out a solution that works perfectly.

<object data="https://calendar.google.com/calendar/embed?showTitle=0&amp;showNav=0&amp;
showDate=0&amp;showPrint=0&amp;showTabs=0&amp;showCalendars=0&amp;showTz=0&amp;height=1400&amp;
wkst=1&amp;bgcolor=%23000000&amp;src=tvanderlinden8%40gmail.com&amp;color=%2329527A&amp;
data=%23contacts%40group.v.calendar.google.com&amp;color=%2329527A&amp;
src=en.usa%23holiday%40group.v.calendar.google.com&amp;color=%2329527A&amp;
ctz=America%2FNew_York" style="border-width:0" width="1000" height="1820"></object>

You're suppose to change all 'src's to 'data', but I found if you only change the beginning and for %23contacts%... to 'data' fixes the problem. Make sure you are logged into your Google acount as well so it can retrieve your Calendar data.


问:
Code to generate pdf from text in iphone
Can anybody tell me Code to generate pdf from text  in iphone. Thanks in advance.</p>

答:
Did you try reading the documentation that outlines this?

http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html#//apple_ref/doc/uid/TP40010156-CH10-SW1

ContentLicense: CC BY-SA 2.5


问:
how to deserialize Gson with empty list of custom object
Recently, I got an issue with Gson deserialization. This is my object:

```<code>class Foo{
    public List<Donation> donations;
    class Donation{
         // SerializedName here.
    }
}
</code>```

This is my json:

```<code>{
   "donations": [] // sometimes, this array is empty.
}
// this is none empty one.
{
"donations": [
        {
          "doner_id": 4,
          "name": "abc",
          "donate": "103"
        }
    ]
}
</code>```

When parsing this JSON with the above object, I always got the error: Expected a com.google.gson.JsonObject but was com.google.gson.JsonArray. If the donations above is not empty, everything works well. How can I do to resolve it?

答:
Here I compiled your json and it works fine for empty as well as non empty donations, check if it what you are looking for.

```<code>String json  = "{\n" +
            "\"donations\": [\n" +
            "        {\n" +
            "          \"doner_id\": 4,\n" +
            "          \"name\": \"abc\",\n" +
            "          \"donate\": \"103\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    JsonParser jsonParser = new JsonParser();
    JsonObject object = jsonParser.parse(json).getAsJsonObject();
    Gson gson = new Gson();
    SampleModel sampleModels1 =  gson.fromJson(object, SampleModel.class);
    assertNotNull(sampleModels1);
</code>```

SampleModel.java

```<code>   public class SampleModel {
    @SerializedName("donations")
    @Expose
    private List<Donations> mDonationsList;

    public List<Donations> getDonationsList() {
        return mDonationsList;
    }

    public void setDonationsList(final List<Donations> donationsList) {
        mDonationsList = donationsList;
    }

    public class Donations {
        @SerializedName("doner_id")
        @Expose
        private String doner_id;
        @SerializedName("name")
        @Expose
        private String name;
        @SerializedName("donate")
        @Expose
        private String donate;

        public String getDoner_id() {
            return doner_id;
        }

        public void setDoner_id(final String doner_id) {
            this.doner_id = doner_id;
        }

        public String getName() {
            return name;
        }

        public void setName(final String name) {
            this.name = name;
        }

        public String getDonate() {
            return donate;
        }

        public void setDonate(final String donate) {
            this.donate = donate;
        }

    }
}
</code>```

Body:
Recently, I got an issue with Gson deserialization. This is my object:

class Foo{
    public List<Donation> donations;
    class Donation{
         // SerializedName here.
    }
}

This is my json:

{
   "donations": [] // sometimes, this array is empty.
}
// this is none empty one.
{
"donations": [
        {
          "doner_id": 4,
          "name": "abc",
          "donate": "103"
        }
    ]
}

When parsing this JSON with the above object, I always got the error: Expected a com.google.gson.JsonObject but was com.google.gson.JsonArray. If the donations above is not empty, everything works well. How can I do to resolve it?

Body:
Here I compiled your json and it works fine for empty as well as non empty donations, check if it what you are looking for.

String json  = "{\n" +
            "\"donations\": [\n" +
            "        {\n" +
            "          \"doner_id\": 4,\n" +
            "          \"name\": \"abc\",\n" +
            "          \"donate\": \"103\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    JsonParser jsonParser = new JsonParser();
    JsonObject object = jsonParser.parse(json).getAsJsonObject();
    Gson gson = new Gson();
    SampleModel sampleModels1 =  gson.fromJson(object, SampleModel.class);
    assertNotNull(sampleModels1);

SampleModel.java

   public class SampleModel {
    @SerializedName("donations")
    @Expose
    private List<Donations> mDonationsList;

    public List<Donations> getDonationsList() {
        return mDonationsList;
    }

    public void setDonationsList(final List<Donations> donationsList) {
        mDonationsList = donationsList;
    }

    public class Donations {
        @SerializedName("doner_id")
        @Expose
        private String doner_id;
        @SerializedName("name")
        @Expose
        private String name;
        @SerializedName("donate")
        @Expose
        private String donate;

        public String getDoner_id() {
            return doner_id;
        }

        public void setDoner_id(final String doner_id) {
            this.doner_id = doner_id;
        }

        public String getName() {
            return name;
        }

        public void setName(final String name) {
            this.name = name;
        }

        public String getDonate() {
            return donate;
        }

        public void setDonate(final String donate) {
            this.donate = donate;
        }

    }
}


问:
Which of these codes is better, and would you change anything in the code to improve it, to make it better?
Of these 3 CSS codes, which code set up is better to use and why?

All 3 codes are set up differently, but they all accomplish the same thing.

I'm trying to figure out which one I should use.

https://jsfiddle.net/75tu065b/2/

http://testing45435.blogspot.com/

Code 1

https://jsfiddle.net/3fcc4cn5/1/

```<code>.link div {
    margin: 0 0 12px 0;
    height: 50px;
  }

 .link div:last-child {
    margin-bottom: 0;
  }
</code>```

Code 2

https://jsfiddle.net/x7s124jc/3/

```<code>  .link div {
    margin: 0 0 12px 0;
    font-size: 0;
  }

  .link a:first-child {
    margin-left: 0px;
  }

  .link div:last-child {
    margin-bottom: 0;
  }
</code>```

Code 3

https://jsfiddle.net/v4yrd6dq/1/

```<code>  .link div {
    margin: 0 0 12px 0;
  }

  .link div:last-child {
    margin-bottom: 0;
  }

  .myLink a {
    vertical-align: top;
  }
</code>```

答: As far as I'm concerned, Code 1 is the best. If they all do the same thing, use the shortest one: It means less for the user to download, and your file is smaller.</p>

Body:
Of these 3 CSS codes, which code set up is better to use and why?

All 3 codes are set up differently, but they all accomplish the same thing.

I'm trying to figure out which one I should use.

https://jsfiddle.net/75tu065b/2/

http://testing45435.blogspot.com/

Code 1

https://jsfiddle.net/3fcc4cn5/1/

.link div {
    margin: 0 0 12px 0;
    height: 50px;
  }

 .link div:last-child {
    margin-bottom: 0;
  }

Code 2

https://jsfiddle.net/x7s124jc/3/

  .link div {
    margin: 0 0 12px 0;
    font-size: 0;
  }

  .link a:first-child {
    margin-left: 0px;
  }

  .link div:last-child {
    margin-bottom: 0;
  }

Code 3

https://jsfiddle.net/v4yrd6dq/1/

  .link div {
    margin: 0 0 12px 0;
  }

  .link div:last-child {
    margin-bottom: 0;
  }

  .myLink a {
    vertical-align: top;
  }


问:
Google Services Conflict Error
Am trying to build my project but suddenly started getting this frustrating error on my log cat about google services version conflict. I have tried all the possible solutions online to fix things yet its not working. I have updated my google-services.json file, even upgraded my google-servies dependencies, cleaned and rebuild my project even invalidated caches yet still getting same error.

Build.gradle(app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(path: ':Material-Color-Picker-master')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    apply plugin: 'com.google.gms.google-services'
    compile files('libs/YouTubeAndroidPlayerApi.jar')

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.android.gms:play-services-maps:11.6.0'
    compile 'com.google.firebase:firebase-crash:11.6.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Build.gradle (Project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.1'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Error

```<code>Error:Execution failed for task ':app:processDebugGoogleServices'.
> Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.
</code>```

答:
I finally solved this problem by removing this line from my build.gradle(project) module.

```<code>  classpath 'com.google.gms:google-services:3.1.1'
</code>```

Title: Google Services Conflict Error

Body:
Am trying to build my project but suddenly started getting this frustrating error on my log cat about google services version conflict. I have tried all the possible solutions online to fix things yet its not working. I have updated my google-services.json file, even upgraded my google-servies dependencies, cleaned and rebuild my project even invalidated caches yet still getting same error.

Build.gradle(app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(path: ':Material-Color-Picker-master')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    apply plugin: 'com.google.gms.google-services'
    compile files('libs/YouTubeAndroidPlayerApi.jar')

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.android.gms:play-services-maps:11.6.0'
    compile 'com.google.firebase:firebase-crash:11.6.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Build.gradle (Project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.1'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Error

Error:Execution failed for task ':app:processDebugGoogleServices'.
> Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.

Body:
I finally solved this problem by removing this line from my build.gradle(project) module.

  classpath 'com.google.gms:google-services:3.1.1'


问:
Scraping different style of Json
I am familiar with scraping data in this format.

```<code>  {"data":[{"assists":0,"assistsPerGame":0.0000,"evAssists":0,"evPoints":0,"gamesPlayed":1,"goals":0,"penaltyMinutes":0,"playerBirthCity":"Windsor","playerBirthCountry":"CAN","playerBirthDate":"1996-02-07",

import csv
import requests

outfile = open("NHL_Recent.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Player","Pos","GP","G","A","P","+/-","PIM","PPG","PPP","SHG","SHP","GWG","OTG","S","S%","TOI","Shifts/PG","FOW%"])

req = requests.get('http://www.nhl.com/stats/rest/skaters?isAggregate=true&reportType=basic&isGame=true&reportName=skatersummary&sort=[{%22property%22:%22shots%22,%22direction%22:%22DESC%22}]&cayenneExp=gameDate%3E=%222017-11-4%22%20and%20gameDate%3C=%222017-11-10%22%20and%20gameTypeId=2')
data = req.json()['data']
for item in data:
    Player = item['playerName']
    Pos = item['playerPositionCode']
    GP = item['gamesPlayed']
</code>```

But not in this manner.

```<code>"totalItems" : 600,
          "totalEvents" : 0,
          "totalGames" : 600,
          "totalMatches" : 0,
          "wait" : 10,
          "dates" : [ {
            "date" : "2017-10-04",
            "totalItems" : 4,
            "totalEvents" : 0,
            "totalGames" : 4,
            "totalMatches" : 0,
            "games" : [ {
              "gamePk" : 2017020001,
              "link" : "/api/v1/game/2017020001/feed/live",
              "gameType" : "R",
              "season" : "20172018",
              "gameDate" : "2017-10-04T23:00:00Z",
              "status" : {
                "abstractGameState" : "Final",
                "codedGameState" : "7",
                "detailedState" : "Final",
                "statusCode" : "7",
                "startTimeTBD" : false
              },
              "teams" : {
                "away" : {
                  "leagueRecord" : {
                    "wins" : 1,
                    "losses" : 0,
                    "ot" : 0,
                    "type" : "league"
                  },
                  "score" : 7,
                  "team" : {
                    "id" : 10,
                    "name" : "Toronto Maple Leafs",
                    "link" : "/api/v1/teams/10",
                    "venue" : {
                      "name" : "Air Canada Centre",
                      "link" : "/api/v1/venues/null",
                      "city" : "Toronto",
                      "timeZone" : {
                        "id" : "America/Toronto",
                        "offset" : -5,
                        "tz" : "EST"
                      }
                    },
                    "abbreviation" : "TOR",
                    "teamName" : "Maple Leafs",
                    "locationName" : "Toronto",
                    "firstYearOfPlay" : "1926",
                    "division" : {
                      "id" : 17,
                      "name" : "Atlantic",
                      "link" : "/api/v1/divisions/17"
                    },
                    "conference" : {
                      "id" : 6,
                      "name" : "Eastern",
                      "link" : "/api/v1/conferences/6"
                    },
                    "franchise" : {
                      "franchiseId" : 5,
                      "teamName" : "Maple Leafs",
                      "link" : "/api/v1/franchises/5
</code>```

This is what I have so far with no success.

```<code>import csv
import requests
import os

outfile = open("NHL DIF JSON.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Date","Game","gamep"])

req = requests.get('https://statsapi.web.nhl.com/api/v1/schedule?startDate=2017-10-04&endDate=2018-04-30&expand=schedule.teams,schedule.linescore,schedule.broadcasts.all,schedule.ticket,schedule.game.content.media.epg,schedule.radioBroadcasts,schedule.metadata,schedule.game.seriesSummary,seriesSummary.series&leaderCategories=&leaderGameTypes=R&site=en_nhl&teamId=&gameType=&timecode=')

data = req.json()['dates']

    for item in data:
        Date = item['date']
    ##for item in games:
        Game = item['0']
        gamep = item['gamePk']

        print(Date,Game)

        writer.writerow([Date,Game,gamep])
    outfile.close()

    os.system("taskkill /f /im pythonw.exe")
</code>```

I Would like to pull the "gamePk", "gameDate" from totalGames along with the teamNames within "teams" and other categories. I eventually would like to put that into a csv with the gamePk, gameDate, teams, score, etc. I'm just not sure how to get through the individual categories, any help would be greatly appreciated! Thanks!

答:
It's normal json data, just a bit complicated.  You can get the date from data['dates'][i]['date']. For the teams, score, etc you have to iterate over data['dates'][i]['games'].

```<code>req = requests.get('https://statsapi.web.nhl.com/api/v1/schedule?startDate=2017-10-04&endDate=2018-04-30&expand=schedule.teams,schedule.linescore,schedule.broadcasts.all,schedule.ticket,schedule.game.content.media.epg,schedule.radioBroadcasts,schedule.metadata,schedule.game.seriesSummary,seriesSummary.series&leaderCategories=&leaderGameTypes=R&site=en_nhl&teamId=&gameType=&timecode=')
data = req.json()

my_data =[]
for item in data['dates']:
    date = item['date']
    games = item['games']
    for game in games:
        gamePk = game['gamePk']
        gameDate = game['gameDate']
        team_away, team_home  = game['teams']['away'], game['teams']['home']
        team_away_score = team_away['score']
        team_home_score = team_home['score']
        team_away_name = team_away['team']['name']
        team_home_name = team_home['team']['name']
        my_data.append([date, gamePk, gameDate, team_away_name, team_home_name, team_away_score, team_home_score])

headers = ["Date","Game","gamep","gameDate","team_away_name","team_home_name","team_away_score","team_home_score"]

with open("my_file.csv", "a", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(my_data)
</code>```

As for your last question, you can get the 'pk' from data['gameData']['game']['pk'].  The player, event, triCode and coordinates values are a little harder to get because some items don't have 'players' and 'team' keys, or the 'coordinates' dict is empty.

In this case the dict.get method can be helpful because it will return None (or you can set a default value) if you try to access a non-existent key.

Still you have to design your code according to the structure of the json data, example:

```<code>req = requests.get('https://statsapi.web.nhl.com/api/v1/game/2017020001/feed/live?site=en_nhl')
data = req.json()
my_data = []

pk = data['gameData']['game']['pk']
for item in data['liveData']['plays']['allPlays']:
    players = item.get('players')
    if players:
        player_a = players[0]['player']['fullName'] if len(players) > 0 else None
        player_b = players[1]['player']['fullName'] if len(players) > 1 else None
    else:
        player_a, player_b = None, None
    event = item['result']['event']
    triCode = item.get('team', {}).get('triCode')
    coordinates_x, coordinates_y = item['coordinates'].get('x'), item['coordinates'].get('y')
    my_data.append([pk, player_a, player_b, event, triCode, coordinates_x, coordinates_y])

for row in my_data:
    print(row)
</code>```

Title: Scraping different style of Json

Body:
I am familiar with scraping data in this format.

  {"data":[{"assists":0,"assistsPerGame":0.0000,"evAssists":0,"evPoints":0,"gamesPlayed":1,"goals":0,"penaltyMinutes":0,"playerBirthCity":"Windsor","playerBirthCountry":"CAN","playerBirthDate":"1996-02-07",

import csv
import requests

outfile = open("NHL_Recent.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Player","Pos","GP","G","A","P","+/-","PIM","PPG","PPP","SHG","SHP","GWG","OTG","S","S%","TOI","Shifts/PG","FOW%"])

req = requests.get('http://www.nhl.com/stats/rest/skaters?isAggregate=true&reportType=basic&isGame=true&reportName=skatersummary&sort=[{%22property%22:%22shots%22,%22direction%22:%22DESC%22}]&cayenneExp=gameDate%3E=%222017-11-4%22%20and%20gameDate%3C=%222017-11-10%22%20and%20gameTypeId=2')
data = req.json()['data']
for item in data:
    Player = item['playerName']
    Pos = item['playerPositionCode']
    GP = item['gamesPlayed']

But not in this manner.

"totalItems" : 600,
          "totalEvents" : 0,
          "totalGames" : 600,
          "totalMatches" : 0,
          "wait" : 10,
          "dates" : [ {
            "date" : "2017-10-04",
            "totalItems" : 4,
            "totalEvents" : 0,
            "totalGames" : 4,
            "totalMatches" : 0,
            "games" : [ {
              "gamePk" : 2017020001,
              "link" : "/api/v1/game/2017020001/feed/live",
              "gameType" : "R",
              "season" : "20172018",
              "gameDate" : "2017-10-04T23:00:00Z",
              "status" : {
                "abstractGameState" : "Final",
                "codedGameState" : "7",
                "detailedState" : "Final",
                "statusCode" : "7",
                "startTimeTBD" : false
              },
              "teams" : {
                "away" : {
                  "leagueRecord" : {
                    "wins" : 1,
                    "losses" : 0,
                    "ot" : 0,
                    "type" : "league"
                  },
                  "score" : 7,
                  "team" : {
                    "id" : 10,
                    "name" : "Toronto Maple Leafs",
                    "link" : "/api/v1/teams/10",
                    "venue" : {
                      "name" : "Air Canada Centre",
                      "link" : "/api/v1/venues/null",
                      "city" : "Toronto",
                      "timeZone" : {
                        "id" : "America/Toronto",
                        "offset" : -5,
                        "tz" : "EST"
                      }
                    },
                    "abbreviation" : "TOR",
                    "teamName" : "Maple Leafs",
                    "locationName" : "Toronto",
                    "firstYearOfPlay" : "1926",
                    "division" : {
                      "id" : 17,
                      "name" : "Atlantic",
                      "link" : "/api/v1/divisions/17"
                    },
                    "conference" : {
                      "id" : 6,
                      "name" : "Eastern",
                      "link" : "/api/v1/conferences/6"
                    },
                    "franchise" : {
                      "franchiseId" : 5,
                      "teamName" : "Maple Leafs",
                      "link" : "/api/v1/franchises/5

This is what I have so far with no success.

import csv
import requests
import os

outfile = open("NHL DIF JSON.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Date","Game","gamep"])

req = requests.get('https://statsapi.web.nhl.com/api/v1/schedule?startDate=2017-10-04&endDate=2018-04-30&expand=schedule.teams,schedule.linescore,schedule.broadcasts.all,schedule.ticket,schedule.game.content.media.epg,schedule.radioBroadcasts,schedule.metadata,schedule.game.seriesSummary,seriesSummary.series&leaderCategories=&leaderGameTypes=R&site=en_nhl&teamId=&gameType=&timecode=')

data = req.json()['dates']

    for item in data:
        Date = item['date']
    ##for item in games:
        Game = item['0']
        gamep = item['gamePk']

        print(Date,Game)

        writer.writerow([Date,Game,gamep])
    outfile.close()

    os.system("taskkill /f /im pythonw.exe")

I Would like to pull the "gamePk", "gameDate" from totalGames along with the teamNames within "teams" and other categories. I eventually would like to put that into a csv with the gamePk, gameDate, teams, score, etc. I'm just not sure how to get through the individual categories, any help would be greatly appreciated! Thanks!

Body:
It's normal json data, just a bit complicated.  You can get the date from data['dates'][i]['date']. For the teams, score, etc you have to iterate over data['dates'][i]['games'].

req = requests.get('https://statsapi.web.nhl.com/api/v1/schedule?startDate=2017-10-04&endDate=2018-04-30&expand=schedule.teams,schedule.linescore,schedule.broadcasts.all,schedule.ticket,schedule.game.content.media.epg,schedule.radioBroadcasts,schedule.metadata,schedule.game.seriesSummary,seriesSummary.series&leaderCategories=&leaderGameTypes=R&site=en_nhl&teamId=&gameType=&timecode=')
data = req.json()

my_data =[]
for item in data['dates']:
    date = item['date']
    games = item['games']
    for game in games:
        gamePk = game['gamePk']
        gameDate = game['gameDate']
        team_away, team_home  = game['teams']['away'], game['teams']['home']
        team_away_score = team_away['score']
        team_home_score = team_home['score']
        team_away_name = team_away['team']['name']
        team_home_name = team_home['team']['name']
        my_data.append([date, gamePk, gameDate, team_away_name, team_home_name, team_away_score, team_home_score])

headers = ["Date","Game","gamep","gameDate","team_away_name","team_home_name","team_away_score","team_home_score"]

with open("my_file.csv", "a", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(my_data)

As for your last question, you can get the 'pk' from data['gameData']['game']['pk'].  The player, event, triCode and coordinates values are a little harder to get because some items don't have 'players' and 'team' keys, or the 'coordinates' dict is empty.

In this case the dict.get method can be helpful because it will return None (or you can set a default value) if you try to access a non-existent key.

Still you have to design your code according to the structure of the json data, example:

req = requests.get('https://statsapi.web.nhl.com/api/v1/game/2017020001/feed/live?site=en_nhl')
data = req.json()
my_data = []

pk = data['gameData']['game']['pk']
for item in data['liveData']['plays']['allPlays']:
    players = item.get('players')
    if players:
        player_a = players[0]['player']['fullName'] if len(players) > 0 else None
        player_b = players[1]['player']['fullName'] if len(players) > 1 else None
    else:
        player_a, player_b = None, None
    event = item['result']['event']
    triCode = item.get('team', {}).get('triCode')
    coordinates_x, coordinates_y = item['coordinates'].get('x'), item['coordinates'].get('y')
    my_data.append([pk, player_a, player_b, event, triCode, coordinates_x, coordinates_y])

for row in my_data:
    print(row)


问:
Is it possible to roll back CREATE TABLE and ALTER TABLE statements in major SQL databases?
I am working on a program that issues DDL. I would like to know whether CREATE TABLE and similar DDL can be rolled back in

Postgres

MySQL

SQLite

et al

Describe how each database handles transactions with DDL.

答:
http://wiki.postgresql.org/wiki/Transactional_DDL_in_PostgreSQL:_A_Competitive_Analysis provides an overview of this issue from PostgreSQL's perspective.

Is DDL transactional according to this document?

PostgreSQL - yes

MySQL - no; DDL causes an implicit commit

Oracle Database 11g Release 2 and above - by default, no, but an alternative called edition-based redefinition exists

Older versions of Oracle - no; DDL causes an implicit commit

SQL Server - yes

Sybase Adaptive Server - yes

DB2 - yes

Informix - yes

Firebird (Interbase) - yes

SQLite also appears to have transactional DDL as well. I was able to ROLLBACK a CREATE TABLE statement in SQLite. Its CREATE TABLE documentation does not mention any special transactional 'gotchas'.


问:
a simple typographical error in .c
i was just writing a program to change a decimal number to another base(2<=radix<=16).

 after running the program and printing the correct answer, I encountered an error that reads : "program has stopped working" . could you please take a look at my code and find where it dangles???!!! i am really confused.

this is my code:

```<code>int decimal, radix, pow = 1, temp;
printf("enter your number and the 2 <= radix <= 16\n");
scanf("%d%d",&decimal, &radix);
temp = decimal;
for(; temp >= radix; temp /= radix)// finding the greatest exponent of radix in decimal
    pow *= radix;
while(pow >= 1){
    decimal -= temp * pow;
    if(temp == 10)
        printf("A");
    else if(temp == 11)
        printf("B");
    else if(temp == 12)
        printf("C");
    else if(temp == 13)
        printf("D");
    else if(temp == 14)
        printf("E");
    else if(temp == 15)
        printf("F");
    else
        printf("%d",temp);
    pow /= radix;
    temp = decimal / pow;
}
puts("");
</code>```

i think the problem is because of "temp = decimal / pow" but how can I fix it??

答:
Check if pow is 0 when you are calculating temp = decimal / pow; at the end of while loop

```<code>    pow /= radix;
    if (pow > 0)
    {
        temp = decimal / pow;
    }
</code>```

Title: a simple typographical error in .c

Body:
i was just writing a program to change a decimal number to another base(2<=radix<=16).

 after running the program and printing the correct answer, I encountered an error that reads : "program has stopped working" . could you please take a look at my code and find where it dangles???!!! i am really confused.

this is my code:

int decimal, radix, pow = 1, temp;
printf("enter your number and the 2 <= radix <= 16\n");
scanf("%d%d",&decimal, &radix);
temp = decimal;
for(; temp >= radix; temp /= radix)// finding the greatest exponent of radix in decimal
    pow *= radix;
while(pow >= 1){
    decimal -= temp * pow;
    if(temp == 10)
        printf("A");
    else if(temp == 11)
        printf("B");
    else if(temp == 12)
        printf("C");
    else if(temp == 13)
        printf("D");
    else if(temp == 14)
        printf("E");
    else if(temp == 15)
        printf("F");
    else
        printf("%d",temp);
    pow /= radix;
    temp = decimal / pow;
}
puts("");

i think the problem is because of "temp = decimal / pow" but how can I fix it??

Body:
Check if pow is 0 when you are calculating temp = decimal / pow; at the end of while loop

    pow /= radix;
    if (pow > 0)
    {
        temp = decimal / pow;
    }


问:
R plot function gives out weird answer
I tried to use R plot to get the curve for some functions. Sometimes, I got very weird results. Here is an example

```<code>u=c(2,2,2,2,2)
elas=function(P){
  prob=P/sum(u,P)
  return(prob)
}
plot(elas,0,6)
</code>```

This code gives out the plot like this:

It is obviously not right. The right code should be like this:

I know that if I change the 3rd line of the code to be

```<code>  prob=P/(sum(u)+P)
</code>```

It would work. But I do not understand why my original code does not work. Does it mean that I cannot plot a function which embeds another function?

Title: R plot function gives out weird answer

Body:
I tried to use R plot to get the curve for some functions. Sometimes, I got very weird results. Here is an example

u=c(2,2,2,2,2)
elas=function(P){
  prob=P/sum(u,P)
  return(prob)
}
plot(elas,0,6)

This code gives out the plot like this:

It is obviously not right. The right code should be like this:

I know that if I change the 3rd line of the code to be

  prob=P/(sum(u)+P)

It would work. But I do not understand why my original code does not work. Does it mean that I cannot plot a function which embeds another function?

Body:
sum(u+P) = sum of each value in u plus P

sum(u) + P = sum of values in u plus P.

Example: u = c(1,2,3), P = 5

sum(u+P) = (1+5) + (2+5) + (3+5) = 6+7+8 = 21
sum(u) + P = (1+2+3) + 5 = 6 + 5 = 11

For

elas <- function(P){
    prob=P/(sum(u+P)
    return(prob)
}

with u <- c(2,2,2,2,2):

y <- elas(0:6)
print(y)
#output of print y:
0.00000000 0.03225806 0.06451613 0.09677419 0.12903226 0.16129032
0.19354839
plot(0:6,y)

For

elas <- function(P){
    prob=P/(sum(u) + P)
    return(prob)
}
y <- elas(0:6)
print(y)
#Output of print(y)
plot(0:6,y)
0.00000000 0.09090909 0.16666667 0.23076923 0.28571429 0.33333333 0.37500000


问:
Write an extension for the Double type that adds an absoluteValue property
Does anyone know why the last line outputs -4.0 instead of 4.0?</p>

```<code>extension Double {
    var absoluteValue: Double {
    if self > 0.0 {
        return self
    }
    else {
        return -1 * self
        }
    }
}

var minusTwo = -2.0
minusTwo.absoluteValue  // 2.0

let minusThree = -3.0
minusThree.absoluteValue    // 3.0

-4.0.absoluteValue  // -4.0
</code>```

答:
Tested with Swift 4.0.2:</p>

```<code>extension Double {
    var absoluteValue: Double {
        return abs(self)
    }
}

var x = -75.34
print(x.absoluteValue) // Prints 75.34
print((-31.337).absoluteValue) // Prints 31.337
</code>```

Body:
Does anyone know why the last line outputs -4.0 instead of 4.0?

extension Double {
    var absoluteValue: Double {
    if self > 0.0 {
        return self
    }
    else {
        return -1 * self
        }
    }
}

var minusTwo = -2.0
minusTwo.absoluteValue  // 2.0

let minusThree = -3.0
minusThree.absoluteValue    // 3.0

-4.0.absoluteValue  // -4.0

Body:
Tested with Swift 4.0.2:

extension Double {
    var absoluteValue: Double {
        return abs(self)
    }
}

var x = -75.34
print(x.absoluteValue) // Prints 75.34
print((-31.337).absoluteValue) // Prints 31.337


问:
I need help making a random number generator as a lock in a simple game
Basically, I wanted to be able to make a code that would generate a random number and have the user try and guess that number by putting in an input. I thought it would work, but it just runs the else statement everytime even if I do guess the right number.</p>

```<code>import random
def main():
  values = [1, 2, 3, 5, 7, 10]
  a = random.choice(values)
  print (a) ##########To see what the number is#########
  b = input('Enter a number: ')
  if b == a:
    print('You have guessed the number!')
  else:
    print('Try again')
    main()
main()
</code>```

答:
Assuming you're using Python 3, the problem is that you're comparing a string to a number, so it's always false.  Just change:

```<code>b = input('Enter a number: ')
</code>```

To:

```<code>b = int(input('Enter a number: '))
</code>```

Then b will be a number (as long as the user enters a number).

Body:
Basically, I wanted to be able to make a code that would generate a random number and have the user try and guess that number by putting in an input. I thought it would work, but it just runs the else statement everytime even if I do guess the right number.

import random
def main():
  values = [1, 2, 3, 5, 7, 10]
  a = random.choice(values)
  print (a) ##########To see what the number is#########
  b = input('Enter a number: ')
  if b == a:
    print('You have guessed the number!')
  else:
    print('Try again')
    main()
main()

Body:
Assuming you're using Python 3, the problem is that you're comparing a string to a number, so it's always false.  Just change:

b = input('Enter a number: ')

To:

b = int(input('Enter a number: '))

Then b will be a number (as long as the user enters a number).


问:
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers.

To the creator could you please adjust the code so it looks like the code you have in your editor? I cannot read this.

```<code> import sys
</code>```

Binary To Decimal

```<code>def bintodec(binnum):
     l = len(binnum)
     s = binnum
     dec = 0
     for i in range(0,l):
         b = s[l-i-1]
         dec = dec + int(b)*(2**i)
         return dec
</code>```

Decimal To Binary

```<code> def dectobin(decnum):
     if decnum==0:
         return "00000000"
     bin=""
     while decnum>0:
         bin = str(decnum%2) + bin
         decnum = decnum/2

     if len(bin)%8 != 0:
         n = 8*(len(bin)/8 + 1) - len(bin)
         bin = "0" + bin
         return bin

 def show_menu():
     print ("What do you want to do?")
     print ("1. Enter the first number")
     print ("2. Enter the second number")
     print ("3. Add the two numbers together")
     print ("4. Subtract the second number from the first")
     print ("5. Exit the program\n")
     show_menu()
      inp = input()
      n1 = ""
      n2 = ""
      while inp !=5:
     if inp=="1":
         n1 = str(input("Enter the first number\n"))
         print ("The first number chosen is: " + str(n1) + "\n")
         show_menu()
     if inp=="2":
         n2= str(input("Enter the second number\n"))
         print ("The first number chosen is: " + str(n1))
         print ("The second number chosen is: " + str(n2) +"\n")
         show_menu()
     if inp=="3":
         print ("The sum of the two numbers is: " + dectobin(bintodec(n1) + bintodec(n2)) + "\n")
     exit()
     if inp=="4":
         if bintodec(n2)<bintodec(n1):
             print ("For this selection second number should be greater than or equal to first")
         else:
             print ("The difference beween the two numbers is: " + dectobin(bintodec(n2) - bintodec(n1)) + "\n")
         exit()
     inp = input()
</code>```

答:
Well, there you go :P Decided to use a switch object because it was interesting. However i'm finding it tough to exit the switch with input '5'

```<code>class switch(object):
    value = None
    def __new__(class_, value):
        class_.value = value
        return True

def case(*args):
    return any((arg == switch.value for arg in args))

def bintodec(binnum):
    return int(str(binnum), 2)

def add(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass
    print('result')
    print(int(first) + int(second))
    print('')

def sub(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass
    print('result')
    print(int(second) - int(first))
    print('')

def show_menu():

    while True:
        print ("What do you want to do?")
        print ("1. Enter the first number")
        print ("2. Enter the second number")
        print ("3. Add the two numbers together")
        print ("4. Subtract the second number from the first")
        print ("5. Exit the program\n")
        ask_for_input = input('Enter Switch\n')
        ask_for_input = int(ask_for_input)

        while switch(ask_for_input):
            if case(1):
                ask_for_1_num = input("Enter the first number\n")
                break
            if case(2):
                ask_for_2_num = input("Enter the second number\n")
                break
            if case(3):
                add(ask_for_1_num, ask_for_2_num)
                break
            if case(4):
                sub(ask_for_1_num, ask_for_2_num)
                break
            if case(5):
                break
            break

def main():
    show_menu()

if __name__ == '__main__':
    main()
</code>```

Hopefully this is solved now? Might need some work in some places, i'll leave that to you.

Body:
Python program: a tool to convert binary numbers to decimal, and decimal numbers to binary, and a simple text-only menu to add or subtract numbers.

To the creator could you please adjust the code so it looks like the code you have in your editor? I cannot read this.

 import sys

Binary To Decimal

def bintodec(binnum):
     l = len(binnum)
     s = binnum
     dec = 0
     for i in range(0,l):
         b = s[l-i-1]
         dec = dec + int(b)*(2**i)
         return dec

Decimal To Binary

 def dectobin(decnum):
     if decnum==0:
         return "00000000"
     bin=""
     while decnum>0:
         bin = str(decnum%2) + bin
         decnum = decnum/2

     if len(bin)%8 != 0:
         n = 8*(len(bin)/8 + 1) - len(bin)
         bin = "0" + bin
         return bin

 def show_menu():
     print ("What do you want to do?")
     print ("1. Enter the first number")
     print ("2. Enter the second number")
     print ("3. Add the two numbers together")
     print ("4. Subtract the second number from the first")
     print ("5. Exit the program\n")
     show_menu()
      inp = input()
      n1 = ""
      n2 = ""
      while inp !=5:
     if inp=="1":
         n1 = str(input("Enter the first number\n"))
         print ("The first number chosen is: " + str(n1) + "\n")
         show_menu()
     if inp=="2":
         n2= str(input("Enter the second number\n"))
         print ("The first number chosen is: " + str(n1))
         print ("The second number chosen is: " + str(n2) +"\n")
         show_menu()
     if inp=="3":
         print ("The sum of the two numbers is: " + dectobin(bintodec(n1) + bintodec(n2)) + "\n")
     exit()
     if inp=="4":
         if bintodec(n2)<bintodec(n1):
             print ("For this selection second number should be greater than or equal to first")
         else:
             print ("The difference beween the two numbers is: " + dectobin(bintodec(n2) - bintodec(n1)) + "\n")
         exit()
     inp = input()

Body:
Well, there you go :P Decided to use a switch object because it was interesting. However i'm finding it tough to exit the switch with input '5'

class switch(object):
    value = None
    def __new__(class_, value):
        class_.value = value
        return True

def case(*args):
    return any((arg == switch.value for arg in args))

def bintodec(binnum):
    return int(str(binnum), 2)

def add(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass
    print('result')
    print(int(first) + int(second))
    print('')

def sub(first, second):
    try:
        first = int(first,2)
        second = int(second,2)
    except:
        pass
    print('result')
    print(int(second) - int(first))
    print('')

def show_menu():

    while True:
        print ("What do you want to do?")
        print ("1. Enter the first number")
        print ("2. Enter the second number")
        print ("3. Add the two numbers together")
        print ("4. Subtract the second number from the first")
        print ("5. Exit the program\n")
        ask_for_input = input('Enter Switch\n')
        ask_for_input = int(ask_for_input)

        while switch(ask_for_input):
            if case(1):
                ask_for_1_num = input("Enter the first number\n")
                break
            if case(2):
                ask_for_2_num = input("Enter the second number\n")
                break
            if case(3):
                add(ask_for_1_num, ask_for_2_num)
                break
            if case(4):
                sub(ask_for_1_num, ask_for_2_num)
                break
            if case(5):
                break
            break

def main():
    show_menu()

if __name__ == '__main__':
    main()

Hopefully this is solved now? Might need some work in some places, i'll leave that to you.