问:
android.view.inflateexception binary xml file line #306: error inflating class guideline
Hey guys I am using Android Studio to create a Brain Training Game.

The thing is that while running the app and then pressing on one of the buttons to choose a level. I get this error android.view.inflateexception binary xml file line #306: error inflating class guideline.

I am not sure what this error is. The Logcat says that this is the error line: setContentView(R.layout.activity_game);.

This is the activity_game xml file:

```<code><android.support.constraint.ConstraintLayout
    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:id="@+id/activitygame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.aadilhafesji.rcw1.Game">

    <TextView
        android:id="@+id/guess"
        android:layout_width="120dp"
        android:layout_height="50dp"
        android:text="Guess:"
        android:textSize="40dp"
        android:textStyle="bold"
        app:layout_constraintHorizontal_bias="0.033"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/showQuestion"
        android:layout_width="250dp"
        android:layout_height="60dp"
        android:gravity="right"
        android:textSize="25dp"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/showAnswer"
        android:layout_width="110dp"
        android:layout_height="50dp"
        android:text="= ?"
        android:textSize="25dp"
        android:textStyle="bold"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/one"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="1"
        android:text="1"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/four"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/two"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:tag="2"
        android:text="2"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/five"
        app:layout_constraintLeft_toRightOf="@+id/one" />

    <Button
        android:id="@+id/three"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="3"
        android:text="3"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/six"
        app:layout_constraintLeft_toRightOf="@+id/two" />

    <Button
        android:id="@+id/four"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="4"
        android:text="4"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/seven"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/five"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="5"
        android:text="5"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/eight"
        app:layout_constraintLeft_toRightOf="@+id/four" />

    <Button
        android:id="@+id/six"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="6"
        android:text="6"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/nine"
        app:layout_constraintLeft_toRightOf="@+id/five" />

    <Button
        android:id="@+id/seven"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="7"
        android:text="7"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/delete"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/eight"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="8"
        android:text="8"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/zero"
        app:layout_constraintLeft_toRightOf="@+id/seven" />

    <Button
        android:id="@+id/nine"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="9"
        android:text="9"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/hash"
        app:layout_constraintLeft_toRightOf="@+id/eight" />

    <Button
        android:id="@+id/zero"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="0"
        android:text="0"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/delete" />

    <Button
        android:id="@+id/delete"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:text="del"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/hash"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:text="#"
        android:textColor="#000000"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/zero" />

    <Button
        android:id="@+id/minus"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="-"
        android:text="-"
        android:textColor="#000000"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toRightOf="@+id/hash"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        tools:layout_editor_absoluteY="549dp" />

    <TextView
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="15dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text=""
        android:textSize="16dp"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="20dp"
        android:textAlignment="center"
        android:textSize="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.333"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/showQuestion"
        app:layout_constraintVertical_bias="0.14" />

    <Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="16dp" />

    <Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="360dp" />

    <ToggleButton
        android:id="@+id/qHint"
        android:layout_width="75dp"
        android:layout_height="60dp"
        android:layout_marginBottom="118dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:checked="false"
        android:textColor="#ffffff"
        android:textOff="Hint Off"
        android:textOn="Hint On"
        app:layout_constraintBottom_toTopOf="@+id/minus"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/guideline2" />

    <TextView
        android:id="@+id/dHint"
        android:layout_width="60dp"
        android:layout_height="20dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text="Hints left:"
        app:layout_constraintLeft_toLeftOf="@+id/qHint"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        app:layout_constraintTop_toBottomOf="@+id/qHint" />

    <TextView
        android:id="@+id/hintNum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text=""
        android:textAlignment="center"
        android:textSize="40dp"
        app:layout_constraintLeft_toLeftOf="@+id/dHint"
        app:layout_constraintRight_toRightOf="@+id/dHint"
        app:layout_constraintTop_toBottomOf="@+id/dHint" />

</android.support.constraint.ConstraintLayout>
</code>```

It would be great if someone could really help me out.
Many thanks

答:
Now you can use AndroidX instead of 'support' </p>

```<code>androidx.constraintlayout.widget.Guideline
</code>```

Body:
Hey guys I am using Android Studio to create a Brain Training Game.

The thing is that while running the app and then pressing on one of the buttons to choose a level. I get this error android.view.inflateexception binary xml file line #306: error inflating class guideline.

I am not sure what this error is. The Logcat says that this is the error line: setContentView(R.layout.activity_game);.

This is the activity_game xml file:

<android.support.constraint.ConstraintLayout
    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:id="@+id/activitygame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.aadilhafesji.rcw1.Game">

    <TextView
        android:id="@+id/guess"
        android:layout_width="120dp"
        android:layout_height="50dp"
        android:text="Guess:"
        android:textSize="40dp"
        android:textStyle="bold"
        app:layout_constraintHorizontal_bias="0.033"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/showQuestion"
        android:layout_width="250dp"
        android:layout_height="60dp"
        android:gravity="right"
        android:textSize="25dp"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/showAnswer"
        android:layout_width="110dp"
        android:layout_height="50dp"
        android:text="= ?"
        android:textSize="25dp"
        android:textStyle="bold"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/one"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="1"
        android:text="1"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/four"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/two"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:tag="2"
        android:text="2"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/five"
        app:layout_constraintLeft_toRightOf="@+id/one" />

    <Button
        android:id="@+id/three"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="3"
        android:text="3"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/six"
        app:layout_constraintLeft_toRightOf="@+id/two" />

    <Button
        android:id="@+id/four"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="4"
        android:text="4"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/seven"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/five"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="5"
        android:text="5"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/eight"
        app:layout_constraintLeft_toRightOf="@+id/four" />

    <Button
        android:id="@+id/six"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="6"
        android:text="6"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/nine"
        app:layout_constraintLeft_toRightOf="@+id/five" />

    <Button
        android:id="@+id/seven"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="7"
        android:text="7"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/delete"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/eight"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="8"
        android:text="8"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/zero"
        app:layout_constraintLeft_toRightOf="@+id/seven" />

    <Button
        android:id="@+id/nine"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="9"
        android:text="9"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/hash"
        app:layout_constraintLeft_toRightOf="@+id/eight" />

    <Button
        android:id="@+id/zero"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="0"
        android:text="0"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/delete" />

    <Button
        android:id="@+id/delete"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:text="del"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@+id/guideline" />

    <Button
        android:id="@+id/hash"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:text="#"
        android:textColor="#000000"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/zero" />

    <Button
        android:id="@+id/minus"
        android:layout_width="75dp"
        android:layout_height="50dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:padding="5dp"
        android:tag="-"
        android:text="-"
        android:textColor="#000000"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toRightOf="@+id/hash"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        tools:layout_editor_absoluteY="549dp" />

    <TextView
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="15dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text=""
        android:textSize="16dp"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="20dp"
        android:textAlignment="center"
        android:textSize="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.333"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/showQuestion"
        app:layout_constraintVertical_bias="0.14" />

    <Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="16dp" />

    <Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="360dp" />

    <ToggleButton
        android:id="@+id/qHint"
        android:layout_width="75dp"
        android:layout_height="60dp"
        android:layout_marginBottom="118dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:checked="false"
        android:textColor="#ffffff"
        android:textOff="Hint Off"
        android:textOn="Hint On"
        app:layout_constraintBottom_toTopOf="@+id/minus"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/guideline2" />

    <TextView
        android:id="@+id/dHint"
        android:layout_width="60dp"
        android:layout_height="20dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text="Hints left:"
        app:layout_constraintLeft_toLeftOf="@+id/qHint"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        app:layout_constraintTop_toBottomOf="@+id/qHint" />

    <TextView
        android:id="@+id/hintNum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text=""
        android:textAlignment="center"
        android:textSize="40dp"
        app:layout_constraintLeft_toLeftOf="@+id/dHint"
        app:layout_constraintRight_toRightOf="@+id/dHint"
        app:layout_constraintTop_toBottomOf="@+id/dHint" />

</android.support.constraint.ConstraintLayout>

It would be great if someone could really help me out.
Many thanks

Body:
Now you can use AndroidX instead of 'support'

androidx.constraintlayout.widget.Guideline


来源: stackexchange

问:
Angular-ui-grid pagination controls not being shown
I´m using the following controller and html configuration to have a paginated ui-grid:

```<code>   app.controller('AdminProspectGridCtrl', function ($scope, $http, uiGridConstants) {

        $scope.gridOptions = {
          data: 'myData',
          paginationPageSizes: [25, 50, 100, 500],
          paginationPageSize: 25,
          enablePagination: true,
          enablePaginationControls: true,
          enableFiltering: true,
          enableColumnResizing: true,
          enableGridMenu: true,
          columnDefs: [
            { field: 'company'},
            { field: 'email'},
            { field: 'country'},
            { field: 'companySize'},
            { field: 'phone' },
            { field: 'dateCreated', cellFilter: 'date:"medium"' },
          ]
        };

        // Retrieve server data
        $http.get('/api/admin/test').then(function (response) {
                $scope.myData = response.data;
            },
            function (error) {
                console.log(error);
        });
  });
</code>```

The HTML code:

```<code><link rel="stylesheet" href="/bower_components/angular-ui-grid/ui-grid.css" />
<script src="/bower_components/angular-ui-grid/ui-grid.js"></script>

  <div class="tile-body" ng-controller="AdminProspectGridCtrl">

    <div id="grid" ui-grid="gridOptions" ui-grid-pagination class="grid"></div>

  </div>
</code>```

The pagination controls simply does not appear on screen. Help appreciated.

答:
The similar issue I resolved by adding a 'ui.grid.pagination' dependency to the module

```<code>var app = angular.module('app', [
    'ui.grid',
    'ui.grid.pagination'
]);
</code>```

And my version is

```<code>"angular-ui-grid": "^4.8.0",
</code>```

same for another issue here angular-ui-grid pagination missing

hope its resolved

ContentLicense: CC BY-SA 3.0

Body:
I´m using the following controller and html configuration to have a paginated ui-grid:

   app.controller('AdminProspectGridCtrl', function ($scope, $http, uiGridConstants) {

        $scope.gridOptions = {
          data: 'myData',
          paginationPageSizes: [25, 50, 100, 500],
          paginationPageSize: 25,
          enablePagination: true,
          enablePaginationControls: true,
          enableFiltering: true,
          enableColumnResizing: true,
          enableGridMenu: true,
          columnDefs: [
            { field: 'company'},
            { field: 'email'},
            { field: 'country'},
            { field: 'companySize'},
            { field: 'phone' },
            { field: 'dateCreated', cellFilter: 'date:"medium"' },
          ]
        };

        // Retrieve server data
        $http.get('/api/admin/test').then(function (response) {
                $scope.myData = response.data;
            },
            function (error) {
                console.log(error);
        });
  });

The HTML code:

<link rel="stylesheet" href="/bower_components/angular-ui-grid/ui-grid.css" />

The pagination controls simply does not appear on screen. Help appreciated.

Body:
The similar issue I resolved by adding a 'ui.grid.pagination' dependency to the module

var app = angular.module('app', [
    'ui.grid',
    'ui.grid.pagination'
]);

And my version is

"angular-ui-grid": "^4.8.0",

same for another issue here angular-ui-grid pagination missing

hope its resolved

ContentLicense: CC BY-SA 4.0


问:
how to fix runtime error in C++ bad alloc
I have written a code using classes and it complies and runs however the full main is not executed as I obtain this message:

```<code>libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
Abort trap: 6
</code>```

The code is executed up to the very end the part of 'dealing out remaining cards:', then I get the error message.
I'm not sure why this is happening, this is my code:

```<code>class CardSet
{
    public:
        CardSet();
        CardSet(int);
        ~CardSet();
        int Size() const;
        bool IsEmpty() const;
        void Shuffle();
        int Deal();
        void Deal(int,CardSet&,CardSet&);
        void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
        void AddCard(int);
        void MergeShuffle(CardSet&);
        void Print() const;
    private:
        int* Card;
        int nCards;
};

void PrintCard(int);

void PrintCard(int c)
{
    int Rank = c%13;
    int Suit = c/13;
    const char NameSuit[5] = "SCDH";
    const char NameRank[14] = "23456789XJQKA";
    cout << NameRank[Rank] << NameSuit[Suit];
}

/*Default constructor that sets up a set of 0 cards*/
CardSet::CardSet()
{
    Card = NULL;
    nCards = 0;
}

/*Initialising constructor where the number of cards is the argument passed*/
CardSet::CardSet(int c)
{
    nCards=c;
    Card = new int[c]; /*Create memory in the array using the new operator*/
        for(int i = 0; i < c; i++) /*for loop to set each value*/
    {
    Card[i] = (i % 52); /*Uses mod operator to ensure number of cards never exceeds 51*/
    }
}

/*Destructor that deletes/cleans up the memory previously set in the array*/
CardSet::~CardSet()
{

    if (Card!=NULL)

        delete [] Card;

    Card = NULL;
}

/*If cardset is empty bool returns true*/
bool CardSet::IsEmpty() const
{
     if (Size() == 0) /*If the set of cards is empty*/

        return true;

    else

        return false;
}

/*Print function passes cards to PrintCard function to print out the contents of the set, 24 cards to a line*/
void CardSet::Print() const
{
    for (int i = 0; i < nCards; i++) /*Prints out the cards from i = 0 to i = ncards*/

    {
        if (i%24 == 0 && i != 0) /*when it hits the 24th card, start a new line*/
            cout << endl;

        else
            cout << " "; /*else enters space between cards*/

        PrintCard(Card[i]);
    }
    cout << endl; /*New line*/

}

/*Returns the number of cards in the set*/
int CardSet::Size() const
{

    return nCards;

}

/*rearranges the cards in the set in a random manner*/
void CardSet::Shuffle()
{

    int temp;

    for (int i = 0; i < nCards; i++){

        int j = rand() % (nCards - 1);

        if (i != j){

            temp = Card[i];

            Card[i] = Card[j];

            Card[j] = temp;

        }

    }

}

/*takes current set and set provided as an argument and makes current set contain contain all the cards from the two sets*/
void CardSet::MergeShuffle(CardSet& set)
{
    while(set.IsEmpty()==false){

        int dealCard = set.Deal();

        AddCard(dealCard);
    }

    Shuffle(); /*call to shuffle function*/

}

/*add a card to the current hand*/
void CardSet::AddCard(int c)
{
int *hand;

    hand = new int[nCards+1]; /*memory allocation to hand*/

    for(int i = 0; i<nCards; i++){ /*for each card i in the set nCards*/

        hand[i] = Card[i];

    }

    hand[nCards] = c;

    delete [] Card; /*delete memory in the array*/

    Card = hand;

    nCards++;
}

/*return the value of the first card in the set which is located in the 0th element of the array*/
int CardSet::Deal()
{
 int *nDeck;

    int temp = 0;

    nDeck = new int[nCards-1]; /*Make fresh memory*/

    temp = Card[0]; /*temp is the first card which we are returning*/

    if (IsEmpty()){ /*If the set is empty*/

        cout << "This set is empty." << endl;

        return -1;

    }

    int j = 0;

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

        nDeck[j] = Card[i]; /*Move the old memory to new memory*/

        j++;

    }

    delete []Card; /*Delete the old memory*/

    Card=nDeck;

    nCards--;

    return temp; /*return the value of the first card*/
}

/*deals two hands in the two CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2)
{
    for (int i = 0; i < c; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument passed*/

    }
}

/*deals four hands in the four CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2,CardSet& set3,CardSet& set4)
{
    for (int i = 0; i < c && IsEmpty()==false; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument and so on for 3rd and 4th set*/

        dealCard = Deal();

        set3.AddCard(dealCard);

        dealCard = Deal();

        set4.AddCard(dealCard);

    }
}

</code>```

and this is my main:

```<code>int main()
{
    cout << "BEGINNING OF CARDSET TESTS . . .  "<< endl << endl;

    //--------- STEP 1 TESTS ---------------------------------------------------

    cout << "Testing constructors, Print(), Size() & IsEmpty():" << endl;
    CardSet CardSet1; // empty cCardSet
    CardSet CardSet2(12); // CardSet with 12 cards
    if(CardSet1.IsEmpty()) cout<<"CardSet1 is empty"<<endl;
    else cout<<"CardSet1 has "<< CardSet1.Size() <<" cards" << endl;
    if(CardSet2.IsEmpty()) cout<<"CardSet2 is empty"<<endl;
    else cout<<"CardSet2 has "<< CardSet2.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet1.Print();
    cout << "Printout of CardSet2: ";
    CardSet2.Print();
    cout << endl;

    /*--------- STEP 2 TESTS ---------------------------------------------*/

    cout << "Testing Normal Shuffle: "<< endl;
    CardSet CardSet3(24); // CardSet with 24 cards
    cout << "Unshuffled CardSet: ";
    CardSet3.Print();
    CardSet3.Shuffle();
    cout << "Shuffled CardSet:   ";
    CardSet3.Print();
    cout << endl;

    cout << "Testing Merge Shuffle: "<< endl;
    CardSet CardSet4(12); // CardSet with 12 cards
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << "Merge shuffling both CardSets into CardSet1:\n";
    CardSet2.MergeShuffle(CardSet4);
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: " ;
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << endl;

    cout << "Testing Adding and removing cards to a CardSet:"<< endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    int Card = CardSet2.Deal();
    cout << "Dealing 1 card: ";
    PrintCard(Card);
    cout << endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Adding card: ";
    PrintCard(Card);
    cout << endl;
    CardSet2.AddCard(Card);
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into two other CardSets:" << endl;
    CardSet CardSet5,CardSet6(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Dealing 3 Cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into four other CardSets:" << endl;
    CardSet CardSet7,CardSet8(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing 3 cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing out remaining cards: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << endl;

    cout << ". . . END OF TESTS"<< endl;

    return 0;
}

</code>```

Any help would be greatly appreciated.

答: In Deal, you start by calling nDeck = new int[nCards-1], then a few lines later call IsEmpty().  If the deck you are dealing from is empty, the allocation will call new int[0-1], which is new int[-1], which, since the number of elements to allocate is unsigned, will be new int[0xFFFFFFFF] on a system with 32 bit integers.  This will be larger than you can possibly allocate, which results in the exception.

Body:
I have written a code using classes and it complies and runs however the full main is not executed as I obtain this message:

libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
Abort trap: 6

The code is executed up to the very end the part of 'dealing out remaining cards:', then I get the error message.
I'm not sure why this is happening, this is my code:

class CardSet
{
    public:
        CardSet();
        CardSet(int);
        ~CardSet();
        int Size() const;
        bool IsEmpty() const;
        void Shuffle();
        int Deal();
        void Deal(int,CardSet&,CardSet&);
        void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
        void AddCard(int);
        void MergeShuffle(CardSet&);
        void Print() const;
    private:
        int* Card;
        int nCards;
};

void PrintCard(int);

void PrintCard(int c)
{
    int Rank = c%13;
    int Suit = c/13;
    const char NameSuit[5] = "SCDH";
    const char NameRank[14] = "23456789XJQKA";
    cout << NameRank[Rank] << NameSuit[Suit];
}

/*Default constructor that sets up a set of 0 cards*/
CardSet::CardSet()
{
    Card = NULL;
    nCards = 0;
}

/*Initialising constructor where the number of cards is the argument passed*/
CardSet::CardSet(int c)
{
    nCards=c;
    Card = new int[c]; /*Create memory in the array using the new operator*/
        for(int i = 0; i < c; i++) /*for loop to set each value*/
    {
    Card[i] = (i % 52); /*Uses mod operator to ensure number of cards never exceeds 51*/
    }
}

/*Destructor that deletes/cleans up the memory previously set in the array*/
CardSet::~CardSet()
{

    if (Card!=NULL)

        delete [] Card;

    Card = NULL;
}

/*If cardset is empty bool returns true*/
bool CardSet::IsEmpty() const
{
     if (Size() == 0) /*If the set of cards is empty*/

        return true;

    else

        return false;
}

/*Print function passes cards to PrintCard function to print out the contents of the set, 24 cards to a line*/
void CardSet::Print() const
{
    for (int i = 0; i < nCards; i++) /*Prints out the cards from i = 0 to i = ncards*/

    {
        if (i%24 == 0 && i != 0) /*when it hits the 24th card, start a new line*/
            cout << endl;

        else
            cout << " "; /*else enters space between cards*/

        PrintCard(Card[i]);
    }
    cout << endl; /*New line*/

}

/*Returns the number of cards in the set*/
int CardSet::Size() const
{

    return nCards;

}

/*rearranges the cards in the set in a random manner*/
void CardSet::Shuffle()
{

    int temp;

    for (int i = 0; i < nCards; i++){

        int j = rand() % (nCards - 1);

        if (i != j){

            temp = Card[i];

            Card[i] = Card[j];

            Card[j] = temp;

        }

    }

}

/*takes current set and set provided as an argument and makes current set contain contain all the cards from the two sets*/
void CardSet::MergeShuffle(CardSet& set)
{
    while(set.IsEmpty()==false){

        int dealCard = set.Deal();

        AddCard(dealCard);
    }

    Shuffle(); /*call to shuffle function*/

}

/*add a card to the current hand*/
void CardSet::AddCard(int c)
{
int *hand;

    hand = new int[nCards+1]; /*memory allocation to hand*/

    for(int i = 0; i<nCards; i++){ /*for each card i in the set nCards*/

        hand[i] = Card[i];

    }

    hand[nCards] = c;

    delete [] Card; /*delete memory in the array*/

    Card = hand;

    nCards++;
}

/*return the value of the first card in the set which is located in the 0th element of the array*/
int CardSet::Deal()
{
 int *nDeck;

    int temp = 0;

    nDeck = new int[nCards-1]; /*Make fresh memory*/

    temp = Card[0]; /*temp is the first card which we are returning*/

    if (IsEmpty()){ /*If the set is empty*/

        cout << "This set is empty." << endl;

        return -1;

    }

    int j = 0;

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

        nDeck[j] = Card[i]; /*Move the old memory to new memory*/

        j++;

    }

    delete []Card; /*Delete the old memory*/

    Card=nDeck;

    nCards--;

    return temp; /*return the value of the first card*/
}

/*deals two hands in the two CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2)
{
    for (int i = 0; i < c; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument passed*/

    }
}

/*deals four hands in the four CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2,CardSet& set3,CardSet& set4)
{
    for (int i = 0; i < c && IsEmpty()==false; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument and so on for 3rd and 4th set*/

        dealCard = Deal();

        set3.AddCard(dealCard);

        dealCard = Deal();

        set4.AddCard(dealCard);

    }
}

and this is my main:

int main()
{
    cout << "BEGINNING OF CARDSET TESTS . . .  "<< endl << endl;

    //--------- STEP 1 TESTS ---------------------------------------------------

    cout << "Testing constructors, Print(), Size() & IsEmpty():" << endl;
    CardSet CardSet1; // empty cCardSet
    CardSet CardSet2(12); // CardSet with 12 cards
    if(CardSet1.IsEmpty()) cout<<"CardSet1 is empty"<<endl;
    else cout<<"CardSet1 has "<< CardSet1.Size() <<" cards" << endl;
    if(CardSet2.IsEmpty()) cout<<"CardSet2 is empty"<<endl;
    else cout<<"CardSet2 has "<< CardSet2.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet1.Print();
    cout << "Printout of CardSet2: ";
    CardSet2.Print();
    cout << endl;

    /*--------- STEP 2 TESTS ---------------------------------------------*/

    cout << "Testing Normal Shuffle: "<< endl;
    CardSet CardSet3(24); // CardSet with 24 cards
    cout << "Unshuffled CardSet: ";
    CardSet3.Print();
    CardSet3.Shuffle();
    cout << "Shuffled CardSet:   ";
    CardSet3.Print();
    cout << endl;

    cout << "Testing Merge Shuffle: "<< endl;
    CardSet CardSet4(12); // CardSet with 12 cards
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << "Merge shuffling both CardSets into CardSet1:\n";
    CardSet2.MergeShuffle(CardSet4);
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: " ;
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << endl;

    cout << "Testing Adding and removing cards to a CardSet:"<< endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    int Card = CardSet2.Deal();
    cout << "Dealing 1 card: ";
    PrintCard(Card);
    cout << endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Adding card: ";
    PrintCard(Card);
    cout << endl;
    CardSet2.AddCard(Card);
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into two other CardSets:" << endl;
    CardSet CardSet5,CardSet6(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Dealing 3 Cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into four other CardSets:" << endl;
    CardSet CardSet7,CardSet8(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing 3 cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing out remaining cards: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << endl;

    cout << ". . . END OF TESTS"<< endl;

    return 0;
}

Any help would be greatly appreciated.


问:
/usr/local/bin/ffmpeg: cannot execute binary file
Want to convert my m4a files into mp3 files using a script. It would save some time... I have over 100 GB of music files.

OS: OSX10.14 / Terminal vs Bash script

I can run ffmpeg -v 5 -y -i musicFile.m4a -acodec libmp3lame -ac 2 -b:a 320k musicFile.mp3 from the terminal. It converts the file and I can see and play the file from itunes.

When I run the same from a bash script it fails to convert.

ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME

My ipod nano just died and I got a new mp3 player. Now I need to convert my itunes files from AAC format to MP3.
ffmpeg is an established video and music file converter.

When I run it from the bash script I tried a few things.

I added ./ in front of the file, that failed because it was installed under /usr/local/bin and not under the same directory.

I also tried sh ffmpeg... and that gave me the cannot execute a binary file.

#!/usr/bin/env bash

# convert m4a file to mp3
set -e

file_convert() {
    ENTRY_FILE=$(printf %q "${entry}")
    FILE_NAME=$(printf %q "$(basename "${entry}")")
    DIR=$(printf %q "$(dirname "${entry}")")
    NAME="${FILE_NAME%.*}"
    EXT="${FILE_NAME##*.}"
    MP3NAME="${DIR}/${NAME}.mp3"

    printf "%*s%s\n"                    $((indent+2)) '' "$ENTRY_FILE"
    printf "%*s\tNew File :\t%s\n"      $((indent+2)) '' "$MP3NAME"

    if [ $EXT == "m4a" ]
    then
      printf "%*s\tConverting: \t%s\n" $((index+2)) '' "$ENTRY_FILE"
      ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME
    fi
}

walk() {
    local indent="${2:-0}"
    printf "\n%*s%s\n\n" "$indent" '' "$1"
    # If the entry is a file convert it
    for entry in "$1"/*; do [[ -f "$entry" ]] && file_convert; done
    # If the entry is a directory recurse
    for entry in "$1"/*; do [[ -d "$entry" ]] && walk "$entry" $((indent+2)); done
}

# If the path is empty use the current, otherwise convert relative to absolute; Exec walk()
[[ -z "${1}" ]] && ABS_PATH="${PWD}" || pushd "${1}" && ABS_PATH="${PWD}"
walk "${ABS_PATH}"
popd
echo

```

I expect >./aacToMp3.sh ./music to traverses the music directory and convert each m4a file to .mp3.

It is walking the file system and printing out correct files, with the spaces escaped. When it hits the ffmpeg line it halts. I put the set -e at the top of the file to force it to fail if the command fails. Without the set -e it happily walks all the music files and prints them to the stdout.

答:
Thanks for all the input.

After a while I ended up writing all the ffmpeg lines to a script file. Glad I did. I was able to quickly scan the file and see some errors and fix them.
This is what I came up with.
Basically I am writing straight text to stdout and directing it to a file. Which I converted to a shell script to convert each file. One at a time. Ran the generated script overnight.

file_convert() {
    ENTRY_FILE=$(printf %q "${entry}")
    FILE_NAME=$(printf %q "$(basename "${entry}")")
    DIR=$(printf %q "$(dirname "${entry}")")
    NAME="${FILE_NAME%.*}"
    EXT="${FILE_NAME##*.}"
    MP3NAME="${DIR}/${NAME}.mp3"

    if [ $EXT == "m4a" ]
    then
      printf 'echo "Converting %s ..."\n' "$FILE_NAME"
      printf 'ffmpeg -v 5 -y -i %s -acodec libmp3lame -ac 2 -b:a 320k %s\n\n' "$ENTRY_FILE" "$MP3NAME"
    fi
}
```

<p>The output looked like.</p>

```#!/usr/bin/env bash

echo "Converting 03\ It\'s\ Not\ My\ Time.m4a ..."
ffmpeg -v 5 -y -i /Users/arthuranderson/Documents/work/projects/mp3Convert/music/3\ Doors\ Down/3\ Doors\ Down\ \(Bonus\ Track\ Version\)/03\ It\'s\ Not\ My\ Time.m4a -acodec libmp3lame -ac 2 -b:a 320k /Users/arthuranderson/Documents/work/projects/mp3Convert/music/3\ Doors\ Down/3\ Doors\ Down\ \(Bonus\ Track\ Version\)/03\ It\'s\ Not\ My\ Time.mp3

echo "Converting 01\ Down.m4a ..."
ffmpeg -v 5 -y -i /Users/arthuranderson/Documents/work/projects/mp3Convert/music/311/Greatest\ Hits\ \'93-\'03/01\ Down.m4a -acodec libmp3lame -ac 2 -b:a 320k /Users/arthuranderson/Documents/work/projects/mp3Convert/music/311/Greatest\ Hits\ \'93-\'03/01\ Down.mp3

```

Mark I will try parallel when I purchase some more music next time.

Thanks everyone!

Body:
Want to convert my m4a files into mp3 files using a script. It would save some time... I have over 100 GB of music files.

OS: OSX10.14 / Terminal vs Bash script

I can run ffmpeg -v 5 -y -i musicFile.m4a -acodec libmp3lame -ac 2 -b:a 320k musicFile.mp3 from the terminal. It converts the file and I can see and play the file from itunes.

When I run the same from a bash script it fails to convert.

ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME

My ipod nano just died and I got a new mp3 player. Now I need to convert my itunes files from AAC format to MP3.
ffmpeg is an established video and music file converter.

When I run it from the bash script I tried a few things.

I added ./ in front of the file, that failed because it was installed under /usr/local/bin and not under the same directory.

I also tried sh ffmpeg... and that gave me the cannot execute a binary file.

#!/usr/bin/env bash

# convert m4a file to mp3
set -e

file_convert() {
    ENTRY_FILE=$(printf %q "${entry}")
    FILE_NAME=$(printf %q "$(basename "${entry}")")
    DIR=$(printf %q "$(dirname "${entry}")")
    NAME="${FILE_NAME%.*}"
    EXT="${FILE_NAME##*.}"
    MP3NAME="${DIR}/${NAME}.mp3"

    printf "%*s%s\n"                    $((indent+2)) '' "$ENTRY_FILE"
    printf "%*s\tNew File :\t%s\n"      $((indent+2)) '' "$MP3NAME"

    if [ $EXT == "m4a" ]
    then
      printf "%*s\tConverting: \t%s\n" $((index+2)) '' "$ENTRY_FILE"
      ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME
    fi
}

walk() {
    local indent="${2:-0}"
    printf "\n%*s%s\n\n" "$indent" '' "$1"
    # If the entry is a file convert it
    for entry in "$1"/*; do [[ -f "$entry" ]] && file_convert; done
    # If the entry is a directory recurse
    for entry in "$1"/*; do [[ -d "$entry" ]] && walk "$entry" $((indent+2)); done
}

# If the path is empty use the current, otherwise convert relative to absolute; Exec walk()
[[ -z "${1}" ]] && ABS_PATH="${PWD}" || pushd "${1}" && ABS_PATH="${PWD}"
walk "${ABS_PATH}"
popd
echo

I expect >./aacToMp3.sh ./music to traverses the music directory and convert each m4a file to .mp3.

It is walking the file system and printing out correct files, with the spaces escaped. When it hits the ffmpeg line it halts. I put the set -e at the top of the file to force it to fail if the command fails. Without the set -e it happily walks all the music files and prints them to the stdout.

Body:
Thanks for all the input.

After a while I ended up writing all the ffmpeg lines to a script file. Glad I did. I was able to quickly scan the file and see some errors and fix them.
This is what I came up with.
Basically I am writing straight text to stdout and directing it to a file. Which I converted to a shell script to convert each file. One at a time. Ran the generated script overnight.

file_convert() {
    ENTRY_FILE=$(printf %q "${entry}")
    FILE_NAME=$(printf %q "$(basename "${entry}")")
    DIR=$(printf %q "$(dirname "${entry}")")
    NAME="${FILE_NAME%.*}"
    EXT="${FILE_NAME##*.}"
    MP3NAME="${DIR}/${NAME}.mp3"

    if [ $EXT == "m4a" ]
    then
      printf 'echo "Converting %s ..."\n' "$FILE_NAME"
      printf 'ffmpeg -v 5 -y -i %s -acodec libmp3lame -ac 2 -b:a 320k %s\n\n' "$ENTRY_FILE" "$MP3NAME"
    fi
}

The output looked like.

#!/usr/bin/env bash

echo "Converting 03\ It\'s\ Not\ My\ Time.m4a ..."
ffmpeg -v 5 -y -i /Users/arthuranderson/Documents/work/projects/mp3Convert/music/3\ Doors\ Down/3\ Doors\ Down\ \(Bonus\ Track\ Version\)/03\ It\'s\ Not\ My\ Time.m4a -acodec libmp3lame -ac 2 -b:a 320k /Users/arthuranderson/Documents/work/projects/mp3Convert/music/3\ Doors\ Down/3\ Doors\ Down\ \(Bonus\ Track\ Version\)/03\ It\'s\ Not\ My\ Time.mp3

echo "Converting 01\ Down.m4a ..."
ffmpeg -v 5 -y -i /Users/arthuranderson/Documents/work/projects/mp3Convert/music/311/Greatest\ Hits\ \'93-\'03/01\ Down.m4a -acodec libmp3lame -ac 2 -b:a 320k /Users/arthuranderson/Documents/work/projects/mp3Convert/music/311/Greatest\ Hits\ \'93-\'03/01\ Down.mp3

Mark I will try parallel when I purchase some more music next time.

Thanks everyone!


问:
I have a DF with 2 columns. I wanna do a boolean check on it
I have a DF that has 3 columns and i wanna perform a Boolean check. The code is shown below.

```<code>import pandas as pd
df = pd.DataFrame({
    'Col1':[A,A,A,B,B,C,C,C],
    'Col2':[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3, 4, 5,6,7],[1, 2, 3, 4, 5,6,7] ]
    'Col3': [[1, 2, 3, 4],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9],[1, 2, 3, 4, 5],[1, 2, 3], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3],[1, 2, 3, 4] ]
})
</code>```

I want a DF that gives me for a unique value of Col1 and if one row of Col2, Col3 are equal, print True, else False.  The result i would like to see is:

```<code>'Col1' 'Col2'                         'Col3'          'Col4'
  A    [1,2,3,4,5,6,7,8,9,10,11,12]  [1,2,3,4]         False

print(map(type, df['Col2']) == map(type,df['Col3']))
</code>```

This returned me value true, but I want it as a new column Col4 in the df

For multiple codes i tried , I always found errors as unhashable type: 'list'

答:
Introduce a new way tuple

```<code>df.Col2.map(tuple)==df.Col3.map(tuple)
Out[646]:
0    False
1     True
2    False
3     True
4    False
5     True
6    False
7    False
dtype: bool
</code>```

Body:
I have a DF that has 3 columns and i wanna perform a Boolean check. The code is shown below.

import pandas as pd
df = pd.DataFrame({
    'Col1':[A,A,A,B,B,C,C,C],
    'Col2':[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3, 4, 5,6,7],[1, 2, 3, 4, 5,6,7] ]
    'Col3': [[1, 2, 3, 4],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9],[1, 2, 3, 4, 5],[1, 2, 3], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3],[1, 2, 3, 4] ]
})

I want a DF that gives me for a unique value of Col1 and if one row of Col2, Col3 are equal, print True, else False.  The result i would like to see is:

'Col1' 'Col2'                         'Col3'          'Col4'
  A    [1,2,3,4,5,6,7,8,9,10,11,12]  [1,2,3,4]         False

print(map(type, df['Col2']) == map(type,df['Col3']))

This returned me value true, but I want it as a new column Col4 in the df

For multiple codes i tried , I always found errors as unhashable type: 'list'

Body:
Introduce a new way tuple

df.Col2.map(tuple)==df.Col3.map(tuple)
Out[646]:
0    False
1     True
2    False
3     True
4    False
5     True
6    False
7    False
dtype: bool


问:
Django Rest Framework custom authentication
Django rest framework: Custom Authentication

I want to use custom authentication in my Django app but cannot find how to apply this. The example given in the documentation is clear to me but they did not mention where to create this new class and how to use this.

答:
I used the following way</p>

```<code>from rest_framework_jwt.settings import api_settings
from rest_framework import status, generics

 class UserLogin(generics.CreateAPIView):

    def post(self, request, *args, **kwargs):
        email = request.data['email']
        if email is None:
            return Response({'error': 'Email not informed'}, status=status.HTTP_403_FORBIDDEN)
        try:
            user = User.objects.get(email=email)
            if not user.check_password(request.data['password']):
                return Response({'error': 'Email ou senha incorreto'}, status=status.HTTP_400_BAD_REQUEST)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return Response({"token": token, "user":UserSessionSerializerAuth(user,
                        context={'request': request}).data}, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return Response({'error': 'User not found'}, status=status.HTTP_403_FORBIDDEN)
</code>```

Body:
I used the following way

from rest_framework_jwt.settings import api_settings
from rest_framework import status, generics

 class UserLogin(generics.CreateAPIView):

    def post(self, request, *args, **kwargs):
        email = request.data['email']
        if email is None:
            return Response({'error': 'Email not informed'}, status=status.HTTP_403_FORBIDDEN)
        try:
            user = User.objects.get(email=email)
            if not user.check_password(request.data['password']):
                return Response({'error': 'Email ou senha incorreto'}, status=status.HTTP_400_BAD_REQUEST)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return Response({"token": token, "user":UserSessionSerializerAuth(user,
                        context={'request': request}).data}, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return Response({'error': 'User not found'}, status=status.HTTP_403_FORBIDDEN)


问:
ActiveX Command Button that unhides next to a Cell if a value is entered, and hides if the cell is empty
I have 80 rows where the user can enter a predetermined value under column Ward. This unhides a button next to it. Upon clicking it, it empties the adjacent value and increments (+1) a particular cell in another sheet depending on the original value.

Currently, I have 80 ActiveX buttons next to the Ward cells that hides/unhides depending on the value of the Ward cells. I've noticed that adding more buttons slows down the spreadsheet because of the sheer volume of If Then statements I have.

```<code>If Range("F8").Value = 0 Then
  Sheets("Admissions").EDAdmit1.Visible = False
Else
  Sheets("Admissions").EDAdmit1.Visible = True
End If

If Range("L8").Value = 0 Then
  Sheets("Admissions").ElecAdmit1.Visible = False
Else
  Sheets("Admissions").ElecAdmit1.Visible = True
End If

If Range("F9").Value = 0 Then
  Sheets("Admissions").EDAdmit2.Visible = False
Else
  Sheets("Admissions").EDAdmit2.Visible = True
End If

If Range("L9").Value = 0 Then
  Sheets("Admissions").ElecAdmit2.Visible = False
Else
  Sheets("Admissions").ElecAdmit2.Visible = True
End If
</code>```

.. and so on.

Not to mention the If Then statements I have for every button click.

```<code>Private Sub EDAdmit1_Click()
If Range("F8") = "ICU" Then
    Worksheets("Overview").Range("AD11").Value = Worksheets("Overview").Range("AD11") + 1
ElseIf Range("F8") = "HDU" Then
    Worksheets("Overview").Range("AF11").Value = Worksheets("Overview").Range("AF11") + 1
ElseIf Range("F8") = "DPU" Or Range("F8") = "Other" Then
Else
    Col = WorksheetFunction.VLookup(Range("F8"), Range("U1:V27"), 2)
    Worksheets("Overview").Range(Col).Value = Worksheets("Overview").Range(Col).Value + 1
End If
Range("F8").ClearContents
End Sub
</code>```

Is there a more efficient way of doing this?

Admission List:

答:
At the beginning of your code put this line:

```<code>Application.ScreenUpdating = False
</code>```

this will disable all screen updates. Let your code do changes, and then enable screen updating, and all your changes will appear.

```<code>Application.ScreenUpdating = True
</code>```

Disabling screen updating usually makes the execution of code faster.

Body:
I have 80 rows where the user can enter a predetermined value under column Ward. This unhides a button next to it. Upon clicking it, it empties the adjacent value and increments (+1) a particular cell in another sheet depending on the original value.

Currently, I have 80 ActiveX buttons next to the Ward cells that hides/unhides depending on the value of the Ward cells. I've noticed that adding more buttons slows down the spreadsheet because of the sheer volume of If Then statements I have.

If Range("F8").Value = 0 Then
  Sheets("Admissions").EDAdmit1.Visible = False
Else
  Sheets("Admissions").EDAdmit1.Visible = True
End If

If Range("L8").Value = 0 Then
  Sheets("Admissions").ElecAdmit1.Visible = False
Else
  Sheets("Admissions").ElecAdmit1.Visible = True
End If

If Range("F9").Value = 0 Then
  Sheets("Admissions").EDAdmit2.Visible = False
Else
  Sheets("Admissions").EDAdmit2.Visible = True
End If

If Range("L9").Value = 0 Then
  Sheets("Admissions").ElecAdmit2.Visible = False
Else
  Sheets("Admissions").ElecAdmit2.Visible = True
End If

.. and so on.

Not to mention the If Then statements I have for every button click.

Private Sub EDAdmit1_Click()
If Range("F8") = "ICU" Then
    Worksheets("Overview").Range("AD11").Value = Worksheets("Overview").Range("AD11") + 1
ElseIf Range("F8") = "HDU" Then
    Worksheets("Overview").Range("AF11").Value = Worksheets("Overview").Range("AF11") + 1
ElseIf Range("F8") = "DPU" Or Range("F8") = "Other" Then
Else
    Col = WorksheetFunction.VLookup(Range("F8"), Range("U1:V27"), 2)
    Worksheets("Overview").Range(Col).Value = Worksheets("Overview").Range(Col).Value + 1
End If
Range("F8").ClearContents
End Sub

Is there a more efficient way of doing this?

Admission List:

Body:
At the beginning of your code put this line:

Application.ScreenUpdating = False

this will disable all screen updates. Let your code do changes, and then enable screen updating, and all your changes will appear.

Application.ScreenUpdating = True

Disabling screen updating usually makes the execution of code faster.


问:
How can I know if a jenkins build has started in Python?
I wrote a script in Python where I launch a Jenkins build via cli :

import subprocess
command = "curl -s -X POST  http://<user>:<token>@<server>/build"
subprocess.Popen(command)
```

<p>I need to find a way to check the build status like :</p>

```If not started : Wait to start
If started : on progress
If ended : Success / Failure
```

<p>by doing :</p>

<pre class="lang-py prettyprint-override"><code>while True:
    # Check the status of the build
    # ... <----- I don't know what to do here

    if STATUS == "on progress"
        break
</code>```

Thanks for your suggestions

答:
You could use this endpoint:

http://my-jenkins.com/job/job_name/lastBuild/api/json

Check this link to view the python implementation:

https://serverfault.com/a/309917/490115

Body:
I wrote a script in Python where I launch a Jenkins build via cli :

import subprocess
command = "curl -s -X POST  http://<user>:<token>@<server>/build"
subprocess.Popen(command)

I need to find a way to check the build status like :

If not started : Wait to start
If started : on progress
If ended : Success / Failure

by doing :

while True:
    # Check the status of the build
    # ... <----- I don't know what to do here

    if STATUS == "on progress"
        break

Thanks for your suggestions


问:
Ensuring that two column values are related in SQL Server
I'm using Microsoft SQL Server 2017 and was curious about how to constrain a specific relationship. I'm having a bit of trouble articulating so I'd prefer to share through an example.

Consider the following hypothetical database.

```<code>Customers
+---------------+
|  Id  |  Name  |
+---------------+
|  1   |  Sam   |
|  2   |  Jane  |
+---------------+
</code>```

```<code>Addresses
+----------------------------------------+
|  Id  |  CustomerId  |  Address         |
+----------------------------------------+
|  1   |  1           |  105 Easy St     |
|  2   |  1           |  9 Gale Blvd     |
|  3   |  2           |  717 Fourth Ave  |
+------+--------------+------------------+
</code>```

```<code>Orders
+-----------------------------------+
|  Id  |  CustomerId  |  AddressId  |
+-----------------------------------+
|  1   |  1           |  1          |
|  2   |  2           |  3          |
|  3   |  1           |  3          |  <--- Invalid Customer/Address Pair
+-----------------------------------+
</code>```

Notice that the final Order links a customer to an address that isn't theirs. I'm looking for a way to prevent this.

(You may ask why I need the CustomerId in the Orders table at all. To be clear, I recognize that the Address already offers me the same information without the possibility of invalid pairs. However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.)

From the related reading I was able to find, it seems that one method may be to enable a CHECK constraint targeting a User-Defined Function. This User-Defined Function would be something like the following:

```<code>WHERE EXISTS (SELECT 1 FROM Addresses WHERE Id = Order.AddressId AND CustomerId = Order.CustomerId)
</code>```

While I imagine this would work, given the somewhat "generality" of the articles I was able to find, I don't feel entirely confident that this is my best option.

An alternative might be to remove the CustomerId column from the Addresses table entirely, and instead add another table with Id, CustomerId, AddressId. The Order would then reference this Id instead. Again, I don't love the idea of having to channel through an auxiliary table to get a Customer or Address.

Is there a cleaner way to do this? Or am I simply going about this all wrong?

答:
Good question, however at the root it seems you are struggling with creating a foreign key constraint to something that is not a foreign key:

Orders.CustomerId -> Addresses.CustomerId

There is no simple built-in way to do this because it is normally not done. In ideal RDBMS practices you should strive to encapsulate data of specific types in their own tables only. In other words, try to avoid redundant data.

In the example case above the address ownership is redundant in both the address table and the orders table, because of this it is requiring additional checks to keep them synchronized. This can easily get out of hand with bigger datasets.

You mentioned:

However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.

But that is why a relational database is relational. It does this so that distinct data can be kept distinct and referenced with relative IDs.

I think the best solution would be to simply drop this requirement.

In other words, just go with:

```<code>Customers
+---------------+
|  Id  |  Name  |
+---------------+
|  1   |  Sam   |
|  2   |  Jane  |
+---------------+
</code>```

```<code>Addresses
+----------------------------------------+
|  Id  |  CustomerId  |  Address         |
+----------------------------------------+
|  1   |  1           |  105 Easy St     |
|  2   |  1           |  9 Gale Blvd     |
|  3   |  2           |  717 Fourth Ave  |
+------+--------------+------------------+
</code>```

```<code>Orders
+--------------------+
|  Id  |  AddressId  |
+--------------------+
|  1   |  1          |
|  2   |  3          |
|  3   |  3          |  <--- Valid Order/Address Pair
+--------------------+
</code>```

With that said, to accomplish your purpose exactly, you do have views available for this kind of thing:

```<code>create view CustomerOrders
as

select  o.Id OrderId,
        a.CustomerId,
        o.AddressId
from    Orders
join    Addresses a on a.Id = o.AddressId
</code>```

I know this is a pretty trivial use-case for a view but I wanted to put in a plug for it because they are often neglected and come in handy with organizing big data sets. Using WITH SCHEMABINDING they can also be indexed for performance.

Body:
I'm using Microsoft SQL Server 2017 and was curious about how to constrain a specific relationship. I'm having a bit of trouble articulating so I'd prefer to share through an example.

Consider the following hypothetical database.

Customers
+---------------+
|  Id  |  Name  |
+---------------+
|  1   |  Sam   |
|  2   |  Jane  |
+---------------+

Addresses
+----------------------------------------+
|  Id  |  CustomerId  |  Address         |
+----------------------------------------+
|  1   |  1           |  105 Easy St     |
|  2   |  1           |  9 Gale Blvd     |
|  3   |  2           |  717 Fourth Ave  |
+------+--------------+------------------+

Orders
+-----------------------------------+
|  Id  |  CustomerId  |  AddressId  |
+-----------------------------------+
|  1   |  1           |  1          |
|  2   |  2           |  3          |
|  3   |  1           |  3          |  <--- Invalid Customer/Address Pair
+-----------------------------------+

Notice that the final Order links a customer to an address that isn't theirs. I'm looking for a way to prevent this.

(You may ask why I need the CustomerId in the Orders table at all. To be clear, I recognize that the Address already offers me the same information without the possibility of invalid pairs. However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.)

From the related reading I was able to find, it seems that one method may be to enable a CHECK constraint targeting a User-Defined Function. This User-Defined Function would be something like the following:

WHERE EXISTS (SELECT 1 FROM Addresses WHERE Id = Order.AddressId AND CustomerId = Order.CustomerId)

While I imagine this would work, given the somewhat "generality" of the articles I was able to find, I don't feel entirely confident that this is my best option.

An alternative might be to remove the CustomerId column from the Addresses table entirely, and instead add another table with Id, CustomerId, AddressId. The Order would then reference this Id instead. Again, I don't love the idea of having to channel through an auxiliary table to get a Customer or Address.

Is there a cleaner way to do this? Or am I simply going about this all wrong?

Body:
Good question, however at the root it seems you are struggling with creating a foreign key constraint to something that is not a foreign key:

Orders.CustomerId -> Addresses.CustomerId

There is no simple built-in way to do this because it is normally not done. In ideal RDBMS practices you should strive to encapsulate data of specific types in their own tables only. In other words, try to avoid redundant data.

In the example case above the address ownership is redundant in both the address table and the orders table, because of this it is requiring additional checks to keep them synchronized. This can easily get out of hand with bigger datasets.

You mentioned:

However, I'd prefer to have an Order flattened such that I don't have to channel through an address to retrieve a customer.

But that is why a relational database is relational. It does this so that distinct data can be kept distinct and referenced with relative IDs.

I think the best solution would be to simply drop this requirement.

In other words, just go with:

Customers
+---------------+
|  Id  |  Name  |
+---------------+
|  1   |  Sam   |
|  2   |  Jane  |
+---------------+

Addresses
+----------------------------------------+
|  Id  |  CustomerId  |  Address         |
+----------------------------------------+
|  1   |  1           |  105 Easy St     |
|  2   |  1           |  9 Gale Blvd     |
|  3   |  2           |  717 Fourth Ave  |
+------+--------------+------------------+

Orders
+--------------------+
|  Id  |  AddressId  |
+--------------------+
|  1   |  1          |
|  2   |  3          |
|  3   |  3          |  <--- Valid Order/Address Pair
+--------------------+

With that said, to accomplish your purpose exactly, you do have views available for this kind of thing:

create view CustomerOrders
as

select  o.Id OrderId,
        a.CustomerId,
        o.AddressId
from    Orders
join    Addresses a on a.Id = o.AddressId

I know this is a pretty trivial use-case for a view but I wanted to put in a plug for it because they are often neglected and come in handy with organizing big data sets. Using WITH SCHEMABINDING they can also be indexed for performance.


问:
We can't find products matching the selection. error in megento 2
I'm using magento2 shopping website and I'm trying to upload some products and during that I'm getting "We can't find products matching the selection." on front each category and product page.

I'm trying to solve that issue but no success, anybody here to give me the best suggestion how to fix that or what command use to fix the issue.

https://www.awesomescreenshot.com/image/4049498/558ab4e971f1460f663d134cb64ca907

答:
Every time you add/edit/remove products, you need to perform a reindex.

```<code>php bin/magento indexer:reindex
</code>```

After re-indexing, everything should work now as intended.

Body:
Every time you add/edit/remove products, you need to perform a reindex.

php bin/magento indexer:reindex

After re-indexing, everything should work now as intended.


问:
How do I get Devise and JWT to work with my Versioned API Rails Controller?
I have a rails API using Devise. When you hit the POST /login endpoint, it logs the user in and provides a JWT. This was all working fine until I recently moved to namespace my controllers with a version. This is what my sessions#create method looks like:

```<code>def create
    self.resource = warden.authenticate!(auth_options)

    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?

    render json: current_user
  end
</code>```

When making a login request from the front end, this what my parameters look like:

```<code>{
    user: {
        email: 'john@gmail.com',
        password: 'password'
    }
}
</code>```

This was working before, but now that I've migrated to a Api::V1 namespace for my sessions controller, it requires the front end to submit credentials under :api_v1_user instead of :user.

Is there a way I can change my sessions#create function to look at the :user attribute and not :api_v1_user?

UPDATE

```<code>  namespace :api do
namespace :v1 do
    devise_for :users,
       path: '',
       path_names: {
         sign_in: 'login',
         sign_out: 'logout',
         registration: 'signup'
       },
       controllers: {
         sessions: 'api/v1/sessions',
         registrations: 'api/v1/registrations'
       }
</code>```

答:
Okay I figured it out. It feels hacky, but it works. Here is what I changed my Api::V1::SessionsController create method to:</p>

```<code>  def create
    # Changing scope from :api_v1_user to :user
    Devise.mappings[:user] = Devise.mappings[:api_v1_user]
    warden.config[:default_strategies][:user] =  warden.config[:default_strategies].delete(:api_v1_user)
    auth_opts = auth_options
    auth_opts[:scope] = :user

    self.resource = warden.authenticate!(auth_opts)

    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?

    render json: current_api_v1_user
  end
</code>```

Body:
I have a rails API using Devise. When you hit the POST /login endpoint, it logs the user in and provides a JWT. This was all working fine until I recently moved to namespace my controllers with a version. This is what my sessions#create method looks like:

def create
    self.resource = warden.authenticate!(auth_options)

    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?

    render json: current_user
  end

When making a login request from the front end, this what my parameters look like:

{
    user: {
        email: 'john@gmail.com',
        password: 'password'
    }
}

This was working before, but now that I've migrated to a Api::V1 namespace for my sessions controller, it requires the front end to submit credentials under :api_v1_user instead of :user.

Is there a way I can change my sessions#create function to look at the :user attribute and not :api_v1_user?

UPDATE

  namespace :api do
namespace :v1 do
    devise_for :users,
       path: '',
       path_names: {
         sign_in: 'login',
         sign_out: 'logout',
         registration: 'signup'
       },
       controllers: {
         sessions: 'api/v1/sessions',
         registrations: 'api/v1/registrations'
       }

Body:
Okay I figured it out. It feels hacky, but it works. Here is what I changed my Api::V1::SessionsController create method to:

  def create
    # Changing scope from :api_v1_user to :user
    Devise.mappings[:user] = Devise.mappings[:api_v1_user]
    warden.config[:default_strategies][:user] =  warden.config[:default_strategies].delete(:api_v1_user)
    auth_opts = auth_options
    auth_opts[:scope] = :user

    self.resource = warden.authenticate!(auth_opts)

    set_flash_message!(:notice, :signed_in)
    sign_in(resource_name, resource)
    yield resource if block_given?

    render json: current_api_v1_user
  end


问:
Looking for official docs for all Javascript (BOM, DOM, built-in) Objects
when I make Web Application.
As far as I know, There are three objects(BOM, DOM, built-in Objects) to javascript.
If I want to manipulate DOM object. I refer DOM official documentation in w3c.org following this.

https://www.w3.org/DOM/DOMTR

If I want to know built-in objects. I can refer ECMA-262 documentation. It's very hard to read but it's official documentation.

https://www.ecma-international.org/publications/standards/Ecma-262.htm

If I want to control browser. I am googleing about BOM. I wonder where is offical BOM Object documentation. I think Google and Mozilla have to provide official documentation. but I couldn't find Where it is.

first question :
Is there BOM standard like DOM?

Second question :
Where is Chrome official BOM documentation?

答:
I think maybe the closest thing to what you are looking for is a list of Web API interfaces - these are things like the Clipboard API and Navigator, which are implemented different on each browser, but accessible via a shared Javascript interface. The list on MDN Docs is pretty comprehensive.

Browsers can also expose extra internal controls, like adding extra options to the right click menu, by providing APIs that are callable from "extensions". However, unlike the Web APIs, these are often very different browser-to-browser, and it is best to refer to the documentation of that specific browser. For example, to add something to the right click menu in Chrome, that would be through the chrome.contextMenus API.

Chrome Extension APIs: here

Firefox Extension APIs: here

Finally, if you really want to go in-depth, you could always look at the source-code for Chromium or Firefox/Gecko. One of the great benefits of open-source!


问:
Remove directory from Google Cloud Compute Engine using serial console
The storage on my Google Cloud Compute Engine Instance (inadvertently) got completely used up. I can no longer SSH into my instance. I have increased the space on my instance, but it still will not allow me to SSH. My VM operating system is Ubuntu.

I have tried two things:

1.) I have tried creating a start script to remove a large directory to clear up some space. Under "custom metadata" I have set the key as "startup-script" and the value as

#! /bin/bash
rm /home/myusername/dir-to-rm
```

<p>I save and reset the instance, click "connect to serial console", but I still cannot SSH.</p>

<p>2.) I have tried to use a startup script to set a login username and password for the serial console by using the same method, but with the following script:</p>

<pre class="lang-sh prettyprint-override"><code>#! /bin/bash
sudo useradd tmpuser
echo 'tmpuser:password' | chpasswd
</code>```

答:
You can mount the disk in another instance, remove the directory and mount back.

Here are the details

Stop your current instance

Edit the instance, remove the disk from the instance.

Create a new instance, and attach above disk as a second disk

Start the new instance

Ssh into the new instance

Mount second disk mount /dev/sdb1 /mnt

Remove the directory: rm /mnt/home/myusername/dir-to-rm

umount the disk and stop the instance

Attach the disk back to original instance as the boot disk

Start

Body:
The storage on my Google Cloud Compute Engine Instance (inadvertently) got completely used up. I can no longer SSH into my instance. I have increased the space on my instance, but it still will not allow me to SSH. My VM operating system is Ubuntu.

I have tried two things:

1.) I have tried creating a start script to remove a large directory to clear up some space. Under "custom metadata" I have set the key as "startup-script" and the value as

#! /bin/bash
rm /home/myusername/dir-to-rm

I save and reset the instance, click "connect to serial console", but I still cannot SSH.

2.) I have tried to use a startup script to set a login username and password for the serial console by using the same method, but with the following script:

#! /bin/bash
sudo useradd tmpuser
echo 'tmpuser:password' | chpasswd


问:
Cannot detect SDK path in WebStorm 2016.3
I am trying to create a PhoneGap application using WebStorm 2016.3 IDE.

I am following this link link. I am able to create a project from the steps but while running the app I'm getting errors. While setting emulator I've found that Android SDK was not found.

I am unable to find how can I set that path here and the error I got is:

...and in log cat

```<code>"C:\Program Files (x86)\JetBrains\WebStorm 2016.3\bin\runnerw.exe" "C:\Users\Sa E\AppData\Roaming\npm\ionic.cmd" run --emulator android
âœ— You cannot run iOS unless you are on Mac OSX.
</code>```

I've tried some things by google but the data is for old IDE and I can't see such options with my current IDE.

答:
I faced the same problem with intellij idea ultimate on linux, while trying to run a cordova/phone gap project. Weirdly enough, the commands where running normally from the command prompt and the embedded terminal, however, trying to create a run configuration, I got the infamous errors.
I have the environment variables set correctly, but, I have them set in ~/.bashrc which intellijidea seems not t read.
I tried to add the variables manually in the same screenshot you included, with no success. The solution was to add ANDROID_HOME to the /etc/environment, rebooted, and everything worked as expected.</p>

Body:
I am trying to create a PhoneGap application using WebStorm 2016.3 IDE.

I am following this link link. I am able to create a project from the steps but while running the app I'm getting errors. While setting emulator I've found that Android SDK was not found.

I am unable to find how can I set that path here and the error I got is:

...and in log cat

"C:\Program Files (x86)\JetBrains\WebStorm 2016.3\bin\runnerw.exe" "C:\Users\Sa E\AppData\Roaming\npm\ionic.cmd" run --emulator android
âœ— You cannot run iOS unless you are on Mac OSX.

I've tried some things by google but the data is for old IDE and I can't see such options with my current IDE.


问:
Could not load the "" image referenced from a nib
I have no images called "" (nothing). I've gone through the .xib file of the screen where this pops up and can't find anything that would cause this. Anybody who have had the same issue? Here is the full warning:

Could not load the "" image referenced from a nib in the bundle with
  identifier "com.blah.Blah"

答:
Make sure the 'Target Membership' for the 'Assets.xcassets' has been selected.

Click 'Assets.xcassets'

In the 'File inspector', make sure 'Target Membership' selected.


问:
SSIS package xml destination
I have an SSIS package to get some sort of data from database and put it into an xml file destination. It is working under a foreach loop. While each loop is executing, the data is updated in the destination file. Currently the data is overwriting at each loop. Really I want to append the data.</p>

答:
You can import data to a RecordSet destination and use a Script Component to write the RecordSet to an XML file. The following link contains a step-by-step guide for this process:

Yet another SSIS XML Destination

Title: SSIS package xml destination


问:
RGB to XYZ , image conversion
original image
-- original image

xyz conversion image
-- xyz conversion image

I wish to convert an image from RGB to XYZ colour space.

Is this code right?

It makes the image darker.

```<code>for( int i = 0; i <= stripSize * stripMax; i++ )
{
    floatvalue[i] = buffer[i] / 255.0f;
    if( floatvalue[i] <= 0.04045f )
    {
        floatvalue[i] = floatvalue[i] / 12.92f;
    }
    else
    {
        floatvalue[i] = powf( (floatvalue[i] + 0.055) / (1.055), 2.4f );
    }

    floatvalue[i] = floatvalue[i] * 100.0f;
}

for( int i = 0; i <= stripSize * stripMax; i = i + 3 )
{
    conversion_x = 0.4124f * floatvalue[i] + 0.3576f * floatvalue[i + 1] + 0.1805f * floatvalue[i + 2];
    xyz_buffer[i] = conversion_x;

    conversion_y = 0.2126f * floatvalue[i] + 0.7152f * floatvalue[i + 1] + 0.0722f * floatvalue[i + 2];
    xyz_buffer[i + 1] = conversion_y;

    conversion_z = 0.0193f * floatvalue[i] + 0.1192f * floatvalue[i + 1] + 0.9505f * floatvalue[i + 2];
    xyz_buffer[i + 2] = conversion_z;
}
</code>```

答:
This should work.. I've used it many times before. I of course modified it slightly so it will convert from a raw buffer to xyz.. It is taken from code I've written here: https://github.com/Brandon-T/CMML/blob/master/src/color.c#L17</p>

```<code>#include <iostream>
#include <cstdint>
#include <cmath>

typedef struct rgb32_t
{
    std::uint8_t r;
    std::uint8_t g;
    std::uint8_t b;
    std::uint8_t a;
} rgb32;

typedef struct xyz_t
{
    float x, y, z;
} xyz;

void rgb_to_xyz(rgb32 *px, xyz *res)
{
    float r = (px->r / 255.0f);
    float g = (px->g / 255.0f);
    float b = (px->b / 255.0f);
    r = (r > 0.04045f) ? pow(((r + 0.055f) / 1.055f), 2.4f) * 100.0f : r / 12.92f;
    g = (g > 0.04045f) ? pow(((g + 0.055f) / 1.055f), 2.4f) * 100.0f : g / 12.92f;
    b = (b > 0.04045f) ? pow(((b + 0.055f) / 1.055f), 2.4f) * 100.0f : b / 12.92f;
    res->x = r * 0.4124f + g * 0.3576f + b * 0.1805f;
    res->y = r * 0.2126f + g * 0.7152f + b * 0.0722f;
    res->z = r * 0.0193f + g * 0.1192f + b * 0.9505f;
}

xyz* convert_to_xyz(std::uint8_t* pixels, std::size_t width, std::size_t height, std::uint16_t bpp = 24)
{
    if (pixels)
    {
        xyz* result = new xyz[width * height];
        for (std::size_t i = 0; i < height; ++i)
        {
            for (std::size_t j = 0; j < width; ++j)
            {
                rgb32 pixel;
                pixel.b = *(pixels++);
                pixel.g = *(pixels++);
                pixel.r = *(pixels++);
                pixel.a = (bpp > 24 ? * (pixels++) : 0xFF);

                rgb_to_xyz(&pixel, result);
                ++result;
            }

            if (bpp == 24)
                pixels += (-width * 3) & 3;
        }
        return result;
    }
    return nullptr;
}

int main() {
    int width = 100;
    int height = 100;
    int bits_per_pixel = 32;

    std::uint8_t *pixels = nullptr; //replace with correct buffer of pixels..

    xyz* xyz_buffer = convert_to_xyz(pixels, width, height, bits_per_pixel);

    //View the xyz pixels..

    delete[] xyz_buffer;

    return 0;
}
</code>```

Title: RGB to XYZ , image conversion

Body:
original image
-- original image

xyz conversion image
-- xyz conversion image

I wish to convert an image from RGB to XYZ colour space.

Is this code right?

It makes the image darker.

for( int i = 0; i <= stripSize * stripMax; i++ )
{
    floatvalue[i] = buffer[i] / 255.0f;
    if( floatvalue[i] <= 0.04045f )
    {
        floatvalue[i] = floatvalue[i] / 12.92f;
    }
    else
    {
        floatvalue[i] = powf( (floatvalue[i] + 0.055) / (1.055), 2.4f );
    }

    floatvalue[i] = floatvalue[i] * 100.0f;
}

for( int i = 0; i <= stripSize * stripMax; i = i + 3 )
{
    conversion_x = 0.4124f * floatvalue[i] + 0.3576f * floatvalue[i + 1] + 0.1805f * floatvalue[i + 2];
    xyz_buffer[i] = conversion_x;

    conversion_y = 0.2126f * floatvalue[i] + 0.7152f * floatvalue[i + 1] + 0.0722f * floatvalue[i + 2];
    xyz_buffer[i + 1] = conversion_y;

    conversion_z = 0.0193f * floatvalue[i] + 0.1192f * floatvalue[i + 1] + 0.9505f * floatvalue[i + 2];
    xyz_buffer[i + 2] = conversion_z;
}

Body:
This should work.. I've used it many times before. I of course modified it slightly so it will convert from a raw buffer to xyz.. It is taken from code I've written here: https://github.com/Brandon-T/CMML/blob/master/src/color.c#L17

#include <iostream>
#include <cstdint>
#include <cmath>

typedef struct rgb32_t
{
    std::uint8_t r;
    std::uint8_t g;
    std::uint8_t b;
    std::uint8_t a;
} rgb32;

typedef struct xyz_t
{
    float x, y, z;
} xyz;

void rgb_to_xyz(rgb32 *px, xyz *res)
{
    float r = (px->r / 255.0f);
    float g = (px->g / 255.0f);
    float b = (px->b / 255.0f);
    r = (r > 0.04045f) ? pow(((r + 0.055f) / 1.055f), 2.4f) * 100.0f : r / 12.92f;
    g = (g > 0.04045f) ? pow(((g + 0.055f) / 1.055f), 2.4f) * 100.0f : g / 12.92f;
    b = (b > 0.04045f) ? pow(((b + 0.055f) / 1.055f), 2.4f) * 100.0f : b / 12.92f;
    res->x = r * 0.4124f + g * 0.3576f + b * 0.1805f;
    res->y = r * 0.2126f + g * 0.7152f + b * 0.0722f;
    res->z = r * 0.0193f + g * 0.1192f + b * 0.9505f;
}

xyz* convert_to_xyz(std::uint8_t* pixels, std::size_t width, std::size_t height, std::uint16_t bpp = 24)
{
    if (pixels)
    {
        xyz* result = new xyz[width * height];
        for (std::size_t i = 0; i < height; ++i)
        {
            for (std::size_t j = 0; j < width; ++j)
            {
                rgb32 pixel;
                pixel.b = *(pixels++);
                pixel.g = *(pixels++);
                pixel.r = *(pixels++);
                pixel.a = (bpp > 24 ? * (pixels++) : 0xFF);

                rgb_to_xyz(&pixel, result);
                ++result;
            }

            if (bpp == 24)
                pixels += (-width * 3) & 3;
        }
        return result;
    }
    return nullptr;
}

int main() {
    int width = 100;
    int height = 100;
    int bits_per_pixel = 32;

    std::uint8_t *pixels = nullptr; //replace with correct buffer of pixels..

    xyz* xyz_buffer = convert_to_xyz(pixels, width, height, bits_per_pixel);

    //View the xyz pixels..

    delete[] xyz_buffer;

    return 0;
}