问:
how to use scrollview in layout with toolbar and bottomnavigationview?
I have a screen in which there is a toolbar, a bottomNavigationView and some data between them including a textView and an imageView. I want to scroll the inner data that is between the toolbar and bottomNavigationView.

I want to scroll the design.xml inside of main.xml. Please suggest a way I can achieve this.

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar1"
        android:layout_width="match_parent"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<include
    layout="@layout/design"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</ScrollView>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/colorPrimary"
    app:itemIconTint="#FFFFFF"
    app:itemTextColor="#FFFFFF"
    app:menu="@menu/bottom_navigation_main" />
</code>```

design.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true"
xmlns:app="http://schemas.android.com/apk/res-auto">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginTop="?android:attr/actionBarSize"
    tools:context="com.example.chaitanya.pg.Pgdata">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/relative">

        <Button
            android:id="@+id/btt1"
            android:background="@drawable/tprevoius"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="100dp" />

        <Button
            android:background="@drawable/tnext"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignTop="@+id/btt1"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:id="@+id/btt2" />
        <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:id="@+id/viewPager"/>

        <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            xmlns:app="http://schemas.android.com/tools"
            android:id="@+id/cardview1"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            card_view:cardElevation="5dp"
            android:layout_below="@id/viewPager"
            android:layout_margin="6dp"
            card_view:cardBackgroundColor="#FFF"
            card_view:cardCornerRadius="7dp"
            card_view:cardMaxElevation="5dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Facilities"
                android:textColor="@color/colorPrimary"
                android:textAllCaps="true"
                android:id="@+id/facilities"
                android:textSize="20dp"
                android:gravity="center"
                android:layout_below="@+id/viewPager"
                android:textColorHighlight="@color/colorPrimary"
                android:textStyle="bold|italic" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:orientation="horizontal"
                >
                <TextView
                    android:layout_width="120dp"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:paddingLeft="10dp"
                    android:textSize="15dp"
                    android:id="@+id/wifi"
                    />
                <TextView
                    android:layout_width="120dp"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:foregroundGravity="center"
                    android:textSize="15dp"
                    android:id="@+id/ac"
                    />
                <TextView
                    android:layout_width="120dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:foregroundGravity="right"
                    android:paddingLeft="20dp"
                    android:id="@+id/food"
                    android:textStyle="bold"
                    android:textSize="15dp"
                    />

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            xmlns:app="http://schemas.android.com/tools"
            android:id="@+id/cardview12"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            card_view:cardElevation="5dp"
            android:layout_below="@id/cardview1"
            android:layout_margin="6dp"
            card_view:cardBackgroundColor="#FFF"
            card_view:cardCornerRadius="7dp"
            card_view:cardMaxElevation="5dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Accomodation"
                    android:textColor="@color/colorPrimary"
                    android:textAllCaps="true"
                    android:textSize="20dp"
                    android:gravity="center"
                    android:textColorHighlight="@color/colorPrimary"
                    android:textStyle="bold|italic" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="2dp"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:foregroundGravity="center"
                    android:textSize="20dp"
                    android:id="@+id/accomodation"
                    />
            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            xmlns:app="http://schemas.android.com/tools"
            android:id="@+id/cardview123"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            card_view:cardElevation="5dp"
            android:layout_below="@id/cardview12"
            android:layout_margin="6dp"
            card_view:cardBackgroundColor="#FFF"
            card_view:cardCornerRadius="7dp"
            card_view:cardMaxElevation="5dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Price"
                    android:textColor="@color/colorPrimary"
                    android:textAllCaps="true"
                    android:textSize="20dp"
                    android:gravity="center"
                    android:textColorHighlight="@color/colorPrimary"
                    android:textStyle="bold|italic" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="2dp"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:foregroundGravity="center"
                    android:textSize="20dp"
                    android:id="@+id/pricee"
                    />
            </LinearLayout>
        </android.support.v7.widget.CardView>
        <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="200dp"
         android:id="@+id/name"
         android:textColor="#FFFFFF"
         android:textStyle="italic"
         android:textSize="20dp"
         android:layout_marginLeft="10dp"
         android:paddingLeft="20dp"

         />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/name"
            android:id="@+id/addr"
            android:textColor="#FFFFFF"
            android:textStyle="italic"
            android:layout_marginLeft="10dp"
            android:textSize="20dp"

           />
    </RelativeLayout>

</LinearLayout>
</code>```

答:
from design.xml remove parent <ScrollView> because outsie you already define the scrollview so there is no use of scrollview inside the design.xml

design.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true"
xmlns:app="http://schemas.android.com/apk/res-auto">
</code>```

Body:
I have a screen in which there is a toolbar, a bottomNavigationView and some data between them including a textView and an imageView. I want to scroll the inner data that is between the toolbar and bottomNavigationView.

I want to scroll the design.xml inside of main.xml. Please suggest a way I can achieve this.

main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar1"
        android:layout_width="match_parent"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<include
    layout="@layout/design"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</ScrollView>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemBackground="@color/colorPrimary"
    app:itemIconTint="#FFFFFF"
    app:itemTextColor="#FFFFFF"
    app:menu="@menu/bottom_navigation_main" />

design.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true"
xmlns:app="http://schemas.android.com/apk/res-auto">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginTop="?android:attr/actionBarSize"
    tools:context="com.example.chaitanya.pg.Pgdata">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/relative">

        <Button
            android:id="@+id/btt1"
            android:background="@drawable/tprevoius"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="100dp" />

        <Button
            android:background="@drawable/tnext"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignTop="@+id/btt1"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:id="@+id/btt2" />
        <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:id="@+id/viewPager"/>

        <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            xmlns:app="http://schemas.android.com/tools"
            android:id="@+id/cardview1"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            card_view:cardElevation="5dp"
            android:layout_below="@id/viewPager"
            android:layout_margin="6dp"
            card_view:cardBackgroundColor="#FFF"
            card_view:cardCornerRadius="7dp"
            card_view:cardMaxElevation="5dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Facilities"
                android:textColor="@color/colorPrimary"
                android:textAllCaps="true"
                android:id="@+id/facilities"
                android:textSize="20dp"
                android:gravity="center"
                android:layout_below="@+id/viewPager"
                android:textColorHighlight="@color/colorPrimary"
                android:textStyle="bold|italic" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:orientation="horizontal"
                >
                <TextView
                    android:layout_width="120dp"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:paddingLeft="10dp"
                    android:textSize="15dp"
                    android:id="@+id/wifi"
                    />
                <TextView
                    android:layout_width="120dp"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:foregroundGravity="center"
                    android:textSize="15dp"
                    android:id="@+id/ac"
                    />
                <TextView
                    android:layout_width="120dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:foregroundGravity="right"
                    android:paddingLeft="20dp"
                    android:id="@+id/food"
                    android:textStyle="bold"
                    android:textSize="15dp"
                    />

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            xmlns:app="http://schemas.android.com/tools"
            android:id="@+id/cardview12"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            card_view:cardElevation="5dp"
            android:layout_below="@id/cardview1"
            android:layout_margin="6dp"
            card_view:cardBackgroundColor="#FFF"
            card_view:cardCornerRadius="7dp"
            card_view:cardMaxElevation="5dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Accomodation"
                    android:textColor="@color/colorPrimary"
                    android:textAllCaps="true"
                    android:textSize="20dp"
                    android:gravity="center"
                    android:textColorHighlight="@color/colorPrimary"
                    android:textStyle="bold|italic" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="2dp"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:foregroundGravity="center"
                    android:textSize="20dp"
                    android:id="@+id/accomodation"
                    />
            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            xmlns:app="http://schemas.android.com/tools"
            android:id="@+id/cardview123"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            card_view:cardElevation="5dp"
            android:layout_below="@id/cardview12"
            android:layout_margin="6dp"
            card_view:cardBackgroundColor="#FFF"
            card_view:cardCornerRadius="7dp"
            card_view:cardMaxElevation="5dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Price"
                    android:textColor="@color/colorPrimary"
                    android:textAllCaps="true"
                    android:textSize="20dp"
                    android:gravity="center"
                    android:textColorHighlight="@color/colorPrimary"
                    android:textStyle="bold|italic" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="2dp"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:foregroundGravity="center"
                    android:textSize="20dp"
                    android:id="@+id/pricee"
                    />
            </LinearLayout>
        </android.support.v7.widget.CardView>
        <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginTop="200dp"
         android:id="@+id/name"
         android:textColor="#FFFFFF"
         android:textStyle="italic"
         android:textSize="20dp"
         android:layout_marginLeft="10dp"
         android:paddingLeft="20dp"

         />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/name"
            android:id="@+id/addr"
            android:textColor="#FFFFFF"
            android:textStyle="italic"
            android:layout_marginLeft="10dp"
            android:textSize="20dp"

           />
    </RelativeLayout>

</LinearLayout>

Body:
from design.xml remove parent <ScrollView> because outsie you already define the scrollview so there is no use of scrollview inside the design.xml

design.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fillViewport="true"
xmlns:app="http://schemas.android.com/apk/res-auto">


来源: stackexchange

问:
Laravel get post categories with pivot table as BelongsToMany()
in my database i have contents_categories and content table with BelongsToMany() relation ship

Contents:

```<code>class Contents extends Model
{
    protected $table = 'contents';
    protected $guarded = ['id'];

    public function categories()
    {
        return $this->belongsToMany(ContentCategories::class);
    }
}
</code>```

ContentCategories:

```<code>class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];

    public function contents()
    {
        return $this->belongsToMany(Contents::class);
    }
}
</code>```

using this code to store data in contents table with selected multiple category work fine and that can be save into database and pivot table as content_categories_contents

```<code>public function store(RequestContents $request)
{
    $data = Contents::create([
        'title' => $request->title,
        'lang' => $request->_language,
        'type' => $request->type,
        'description' => $request->description,
        'featured_images' => '',
        'visit' => 0,
    ]);

    $data->categories()->attach($request->categories);
}
</code>```

now! unfortunately when i try to use this code to get categories of content i dont have them in result:

```<code>public function show($id)
{
    $content = Contents::find($id);
    $selected_categories = $content->categories();
    dd($selected_categories);
}
</code>```

result:

```<code>BelongsToMany {#208 ▼
  #table: "content_categories_contents"
  #foreignPivotKey: "contents_id"
  #relatedPivotKey: "content_categories_id"
  #parentKey: "id"
  #relatedKey: "id"
  #relationName: "categories"
  #pivotColumns: []
  #pivotWheres: []
  #pivotWhereIns: []
  #pivotCreatedAt: null
  #pivotUpdatedAt: null
  #using: null
  #accessor: "pivot"
  #query: Builder {#217 ▼
    #query: Builder {#209 ▶}
    #model: ContentCategories {#213 ▼
      #table: "contents_categories"
      #guarded: array:1 [▶]
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: false
      +wasRecentlyCreated: false
      #attributes: []
      #original: []
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
    }
    #eagerLoad: []
    #localMacros: []
    #onDelete: null
    #passthru: array:11 [▶]
    #scopes: []
    #removedScopes: []
  }
  #parent: Contents {#218 ▼
    #table: "contents"
    #guarded: array:1 [▶]
    #connection: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: false
    +wasRecentlyCreated: false
    #attributes: []
    #original: []
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #fillable: []
  }
  #related: ContentCategories {#213 ▶}
}
</code>```

答:
This is because that method you defined is returning exactly what you have defined it to return a BelongsToMany object. These are builder type objects so you can query the relationship. They are no the result of it.

You are expecting the loaded relationship it would seem. You would have to query the relationship yourself, or hit the "dynamic property" for the relationship which will load it if it isn't already loaded and return the result.

```<code>$model->categories();   // returns what you defined it to return
$model->categories()->where(...)->get();

$model->categories;   // loaded relationship via dynamic property
</code>```

Laravel 5.5 Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties

ContentLicense: CC BY-SA 3.0

Body:
in my database i have contents_categories and content table with BelongsToMany() relation ship

Contents:

class Contents extends Model
{
    protected $table = 'contents';
    protected $guarded = ['id'];

    public function categories()
    {
        return $this->belongsToMany(ContentCategories::class);
    }
}

ContentCategories:

class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];

    public function contents()
    {
        return $this->belongsToMany(Contents::class);
    }
}

using this code to store data in contents table with selected multiple category work fine and that can be save into database and pivot table as content_categories_contents

public function store(RequestContents $request)
{
    $data = Contents::create([
        'title' => $request->title,
        'lang' => $request->_language,
        'type' => $request->type,
        'description' => $request->description,
        'featured_images' => '',
        'visit' => 0,
    ]);

    $data->categories()->attach($request->categories);
}

now! unfortunately when i try to use this code to get categories of content i dont have them in result:

public function show($id)
{
    $content = Contents::find($id);
    $selected_categories = $content->categories();
    dd($selected_categories);
}

result:

BelongsToMany {#208 ▼
  #table: "content_categories_contents"
  #foreignPivotKey: "contents_id"
  #relatedPivotKey: "content_categories_id"
  #parentKey: "id"
  #relatedKey: "id"
  #relationName: "categories"
  #pivotColumns: []
  #pivotWheres: []
  #pivotWhereIns: []
  #pivotCreatedAt: null
  #pivotUpdatedAt: null
  #using: null
  #accessor: "pivot"
  #query: Builder {#217 ▼
    #query: Builder {#209 ▶}
    #model: ContentCategories {#213 ▼
      #table: "contents_categories"
      #guarded: array:1 [▶]
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: false
      +wasRecentlyCreated: false
      #attributes: []
      #original: []
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
    }
    #eagerLoad: []
    #localMacros: []
    #onDelete: null
    #passthru: array:11 [▶]
    #scopes: []
    #removedScopes: []
  }
  #parent: Contents {#218 ▼
    #table: "contents"
    #guarded: array:1 [▶]
    #connection: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: false
    +wasRecentlyCreated: false
    #attributes: []
    #original: []
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #fillable: []
  }
  #related: ContentCategories {#213 ▶}
}

Body:
This is because that method you defined is returning exactly what you have defined it to return a BelongsToMany object. These are builder type objects so you can query the relationship. They are no the result of it.

You are expecting the loaded relationship it would seem. You would have to query the relationship yourself, or hit the "dynamic property" for the relationship which will load it if it isn't already loaded and return the result.

$model->categories();   // returns what you defined it to return
$model->categories()->where(...)->get();

$model->categories;   // loaded relationship via dynamic property

Laravel 5.5 Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties


问:
In React, onclick in child component is not bindin
In my child compenent, I'm trying to add an onclick event to my html and when I transpile I get an error:

"bundle.min.js:35884 Uncaught (in promise) TypeError: Cannot read property 'bind' of undefined".

I've tried defining the called function in the parent component but that doesn't work either. It's the onClick={playMusic} bit that's giving me the bother.

```<code>import {Component} from 'react'
import {Link} from 'react-router';

class Thumbs extends Component {
    constructor(props){
        super(props)
        this.playMusic = this.Playmusic.bind(this);
    }

    playMusic() {
        var audio = new Audio(media_item.href);
        audio.play();
    }

render() {
        const {href, nasa_id} = this.props
        if (nasa_id !== '000') {
            return <Link to={`/asset/${nasa_id}`}><img src={href} width="100" height="100"/></Link>
        } else {
            return <img
                    src="https://www.collinsdictionary.com/images/thumb/gramophone_108546017_250.jpg?version=3.1.118"
                    width="100" height="100"
                    onClick={playMusic}
                    />
        }
    }
}

export default Thumbs
</code>```

答:
You can use the fat arrow function and get rid of the function binding in the constructor. Change the playMusic() method as below

```<code>playMusic = () => {
    var audio = new Audio(media_item.href);
    audio.play();
}
</code>```

After that remove this.playMusic = this.Playmusic.bind(this); from the constructor and in the render method use onClick={this.playMusic}.

Body:
In my child compenent, I'm trying to add an onclick event to my html and when I transpile I get an error:

"bundle.min.js:35884 Uncaught (in promise) TypeError: Cannot read property 'bind' of undefined".

I've tried defining the called function in the parent component but that doesn't work either. It's the onClick={playMusic} bit that's giving me the bother.

import {Component} from 'react'
import {Link} from 'react-router';

class Thumbs extends Component {
    constructor(props){
        super(props)
        this.playMusic = this.Playmusic.bind(this);
    }

    playMusic() {
        var audio = new Audio(media_item.href);
        audio.play();
    }

render() {
        const {href, nasa_id} = this.props
        if (nasa_id !== '000') {
            return <Link to={`/asset/${nasa_id}`}></Link>
        } else {
            return
        }
    }
}

export default Thumbs

Body:
You can use the fat arrow function and get rid of the function binding in the constructor. Change the playMusic() method as below

playMusic = () => {
    var audio = new Audio(media_item.href);
    audio.play();
}

After that remove this.playMusic = this.Playmusic.bind(this); from the constructor and in the render method use onClick={this.playMusic}.


问:
Fuel, Kotlin, Gson, Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1
I'm trying to parse a JSON string like this:

```<code>{
    "count": 1,
    "items": [
        {
            "organization_id": 6972979,
            "organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
        }
    ]
}
</code>```

And the Kotlin class:

```<code>class LoremModel {
    var count: Int? = null
    var items: List<Lorem>? = null

    class Lorem {
        var organization_id: Int? = null
        var organization_name: String? = null

        constructor(organization_id: Int?,  organization_name: String?) {
            this.organization_id = organization_id
            this.organization_name = organization_name
        }
    }

    class ListDeserializer : ResponseDeserializable<List<LoremModel>> {
        override fun deserialize(content: String) = Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)
    }
}
</code>```

The Fuel part:

```<code>Fuel.get("/lorem/search", listOf("keywords" to  keyword, "category" to category, "pageNum" to "1", "pageSize" to "10")).
        responseObject(LoremModel.ListDeserializer()) { request, _, item ->
        }
</code>```

But I am getting an error:

[Failure: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $]

How do I solve it?

答:
Your json

```<code>{
    "count": 1,
    "items": [
        {
            "organization_id": 6972979,
            "organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
        }
    ]
}
</code>```

represents a JSON Object and not a JSON Array.

So instead of trying to deserialize it into a type of List of LoremModel objects

```<code>Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)
</code>```

You should deserialize it to an object of type LoremModel. So you can do this:

```<code>Gson().fromJson(content, LoremModel::class.java)
</code>```

Body:
I'm trying to parse a JSON string like this:

{
    "count": 1,
    "items": [
        {
            "organization_id": 6972979,
            "organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
        }
    ]
}

And the Kotlin class:

class LoremModel {
    var count: Int? = null
    var items: List<Lorem>? = null

    class Lorem {
        var organization_id: Int? = null
        var organization_name: String? = null

        constructor(organization_id: Int?,  organization_name: String?) {
            this.organization_id = organization_id
            this.organization_name = organization_name
        }
    }

    class ListDeserializer : ResponseDeserializable<List<LoremModel>> {
        override fun deserialize(content: String) = Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)
    }
}

The Fuel part:

Fuel.get("/lorem/search", listOf("keywords" to  keyword, "category" to category, "pageNum" to "1", "pageSize" to "10")).
        responseObject(LoremModel.ListDeserializer()) { request, _, item ->
        }

But I am getting an error:

[Failure: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $]

How do I solve it?

Body:
Your json

{
    "count": 1,
    "items": [
        {
            "organization_id": 6972979,
            "organization_name": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
        }
    ]
}

represents a JSON Object and not a JSON Array.

So instead of trying to deserialize it into a type of List of LoremModel objects

Gson().fromJson<List<LoremModel>>(content, object : TypeToken<List<LoremModel>>() {}.type)

You should deserialize it to an object of type LoremModel. So you can do this:

Gson().fromJson(content, LoremModel::class.java)


问:
how to create HTML5 playlist loop feature
I'm trying to create a playlist like youtube but I have a problem with autoplay all videos one by one, i created an on ended event to play the next video when the current playback ends
This is the code

$('video').on('ended', function() {
  // Remove .active class from the active li, select next li sibling.
  var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
  var tabNext = $('.tab-content .active').removeClass('active').next('div');
  var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

  // Did we reach the last element? if so: select first sibling
  if (!next.length) next = next.prevObject.siblings(':first');
  if (!tabNext.length) next = next.prevObject.siblings(':first');
  if (!tabNextIn.length) next = next.prevObject.siblings(':first');

  // Add .active class to the li next in line.
  next.addClass('active');
  tabNext.addClass('active');
  tabNextIn.addClass('in');
});

if ($('.tab-pane').hasClass('active')) {
  $('.active video').attr('autoplay', '');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

I don't understand why the next video not play

I just need to add autoplay attribute to the next video!

https://codepen.io/kemozzz/full/gXEzrp/

答:
You can add in your click function something like this:</p>

```<code>$('.tabs-container.active video')[0].play();
</code>```

Body:
I'm trying to create a playlist like youtube but I have a problem with autoplay all videos one by one, i created an on ended event to play the next video when the current playback ends
This is the code

$('video').on('ended', function() {
  // Remove .active class from the active li, select next li sibling.
  var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
  var tabNext = $('.tab-content .active').removeClass('active').next('div');
  var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

  // Did we reach the last element? if so: select first sibling
  if (!next.length) next = next.prevObject.siblings(':first');
  if (!tabNext.length) next = next.prevObject.siblings(':first');
  if (!tabNextIn.length) next = next.prevObject.siblings(':first');

  // Add .active class to the li next in line.
  next.addClass('active');
  tabNext.addClass('active');
  tabNextIn.addClass('in');
});

if ($('.tab-pane').hasClass('active')) {
  $('.active video').attr('autoplay', '');
}

I don't understand why the next video not play

I just need to add autoplay attribute to the next video!

https://codepen.io/kemozzz/full/gXEzrp/

Body:
You can add in your click function something like this:

$('.tabs-container.active video')[0].play();


问:
Is it possible to extract inline CSS from HTML?
Using http://simplehtmldom.sourceforge.net/manual.htm, is it possible to extract the inline CSS of a HTML file?

This parser if pure html, assuming (just correct me if I'm wrong) it can't parse CSS tags.Is there any other way to extract inline CSS in the html file?

答:
This should work:</p>

```<code>$doc = new DOMDocument();
$doc->loadHTML('<html><body style="color: red"></body></html>');

$els = $doc->getElementsByTagName('*');

for($i = 0; $i < $els->length; $i++)
  echo $els->item($i)->getAttribute('style'); // color: red
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This should work:

$doc = new DOMDocument();
$doc->loadHTML('<html><body style="color: red"></body></html>');

$els = $doc->getElementsByTagName('*');

for($i = 0; $i < $els->length; $i++)
  echo $els->item($i)->getAttribute('style'); // color: red


问:
More concise '&&' operator javascript
My project is littered with things like :

```<code>if(selectedDestination.modeOfTransport && selectedDestination.modeOfTransport.value === 'Driving'"){
  // Do something
}
</code>```

Ideally I'd like to just have:

```<code>if(selectedDestination.modeOfTransport.value === 'Driving'")
</code>```

and let it just be false if there's no 'modeOfTransport' property.

答:
something like that should suit:

(selectedDestination.modeOfTransport || {}).value === 'Driving'

// or (to avoid prototype inheritance)
(selectedDestination.modeOfTransport || Object.create(null)).value === 'Driving'
```

<p>If you're using <code>babel</code>, you can have a look at: Nullish Coalescing for JavaScript</p>

<pre class="lang-js prettyprint-override"><code>selectedDestination.modeOfTransport?.value === 'Driving'
</code>```

Tim's edit: Here is another option:

This is a common problem in JavaScript.  One cop out answer might be to define a variable which referenced the lengthy expression you want to avoid:

```<code>var mode = selectedDestination.modeOfTransport;
if (mode && mode.value === 'Driving') {
    // Do something
}
</code>```

Title: More concise '&&' operator javascript

Body:
My project is littered with things like :

if(selectedDestination.modeOfTransport && selectedDestination.modeOfTransport.value === 'Driving'"){
  // Do something
}

Ideally I'd like to just have:

if(selectedDestination.modeOfTransport.value === 'Driving'")

and let it just be false if there's no 'modeOfTransport' property.

Body:
something like that should suit:

(selectedDestination.modeOfTransport || {}).value === 'Driving'

// or (to avoid prototype inheritance)
(selectedDestination.modeOfTransport || Object.create(null)).value === 'Driving'

If you're using babel, you can have a look at: Nullish Coalescing for JavaScript

selectedDestination.modeOfTransport?.value === 'Driving'

Tim's edit: Here is another option:

This is a common problem in JavaScript.  One cop out answer might be to define a variable which referenced the lengthy expression you want to avoid:

var mode = selectedDestination.modeOfTransport;
if (mode && mode.value === 'Driving') {
    // Do something
}


问:
Error while loading coverage session (code 5001)
I got the following error when I am trying to check coverage using EclEmma, please help me out:

Error while loading coverage session (code 5001). Error while
  analyzing package fragment root java at
  F/solo-repository/target/test-classes (code 5007). File not found:
  D:\RDM
  Services\solo-repository\target\test-classes\com\charter\solo\account\repository\AccountBillInformationRepositoryTest.class.
  D:\RDM
  Services\solo-repository\target\test-classes\com\charter\solo\account\repository\AccountBillInformationRepositoryTest.class
  (The system cannot find the path specified)

答:
I had the same error. The suggestions in this answer did not fix it for me. The thing that finally did fix it was:

Right click a source folder and select Build Path > Configure Output Folder...

Select "Project's default output folder" (even if it happens to be the same path entered in "Specific output folder")

Click OK

Refresh the project

It seems a bit nonsensical, but did the trick for me.


问:
How to set 2 different urls for opencpu?
I want to set 2 different urls for OpenCpu. Is it possible?</p>

```<code>ocpu.seturl("https://public.opencpu.org/ocpu/library/igraph/R");

ocpu.seturl("https://public.opencpu.org/ocpu/library/customlibrary/R");
</code>```

答:
No, each OpenCPU app calls out to a single API package endpoint. There can be no ambiguity about which function gets called.

If you are building an app customlibrary but also want to call functions from igraph you can import + export these igraph functions in your customlibrary package NAMESPACE file.

You can also write wrapper functions in customlibrary that call out to igraph functions. Either way make sure to imports: igraph in the DESCRIPTION file in customlibrary.

Body:
I want to set 2 different urls for OpenCpu. Is it possible?

ocpu.seturl("https://public.opencpu.org/ocpu/library/igraph/R");

ocpu.seturl("https://public.opencpu.org/ocpu/library/customlibrary/R");


问:
How to remove relations from MongoDB models
Is there any possible way to list relations between models in Mongodb and remove or edit them?

update Schema:
company:

```<code>{
  "company": "string",
  "name": "string",
  "tel": "string",
  "id": "string"
}
</code>```

product:

```<code>{
  "name": "string",
  "qty": 0,
  "exp": "string",
  "id": "string"
}
</code>```

update 2:

```<code>"relations": {
    "products": {
      "type": "hasMany",
      "model": "product",
      "foreignKey": "comp_id"
    }
  },
</code>```

答:
I'm still not utterly sure what you are trying to accomplish. But I have an advice for you on how to design your Schemata and add your foreign keys

If I was you, I would design my company collection like this:

```<code>{
    "_id" : ObjectId("5a291fd838f4fb1fc057bbbc"), // _id is automatically generated if you don't provide any
    "name" : "ABC",
    "tel" : "1234567"
}
{
    "_id" : ObjectId("5a29208838f4fb1fc057bbbf"),
    "name" : "DEF",
    "tel" : "5556667"
}
</code>```

And this is how I would design my product collection:

```<code>{
    "_id" : ObjectId("5a29211838f4fb1fc057bbc4"),
    "name" : "ProductA",
    "qty" : NumberInt(1),
    "exp" : "exp1",
    "companyIds" : [
        ObjectId("5a291fd838f4fb1fc057bbbc"), // the foreign keys of the each company
        ObjectId("5a29208838f4fb1fc057bbbf")
    ]
}
</code>```

This way it would be easier to delete and or update your collections.

Body:
Is there any possible way to list relations between models in Mongodb and remove or edit them?

update Schema:
company:

{
  "company": "string",
  "name": "string",
  "tel": "string",
  "id": "string"
}

product:

{
  "name": "string",
  "qty": 0,
  "exp": "string",
  "id": "string"
}

update 2:

"relations": {
    "products": {
      "type": "hasMany",
      "model": "product",
      "foreignKey": "comp_id"
    }
  },

Body:
I'm still not utterly sure what you are trying to accomplish. But I have an advice for you on how to design your Schemata and add your foreign keys

If I was you, I would design my company collection like this:

{
    "_id" : ObjectId("5a291fd838f4fb1fc057bbbc"), // _id is automatically generated if you don't provide any
    "name" : "ABC",
    "tel" : "1234567"
}
{
    "_id" : ObjectId("5a29208838f4fb1fc057bbbf"),
    "name" : "DEF",
    "tel" : "5556667"
}

And this is how I would design my product collection:

{
    "_id" : ObjectId("5a29211838f4fb1fc057bbc4"),
    "name" : "ProductA",
    "qty" : NumberInt(1),
    "exp" : "exp1",
    "companyIds" : [
        ObjectId("5a291fd838f4fb1fc057bbbc"), // the foreign keys of the each company
        ObjectId("5a29208838f4fb1fc057bbbf")
    ]
}

This way it would be easier to delete and or update your collections.


问:
Why do MVCs tend to convert objects into arrays when passing them off to a view?
Why do MVCs tend to convert objects into arrays when passing them off to a view?

Just curious if there is a reason for this.

答:
If by arrays, you mean sets, then the reason is because there is no guarantee that you only want to pass one object to the view.

Sure, you could have a context object that does pass all of your data to the view, but the frameworks would rather provide a mechanism for doing so that doesn't require you to aggregate your data, especially since it could take vastly different shapes.


问:
Convert Java Math.random to Swift 4
I was wondering how I can convert the below java code to Swift 4.

```<code>int randomNoteIndex = myArray[0] + (int) (Math.random() * (myArray[1] - myArray[0] + 1));
</code>```

Here is what i tried but I always get the same number myArray[0] everytime

```<code> let randomNoteIndex = myArray[0] +  Int(arc4random_uniform(1) * (UInt32(myArray[1]) - UInt32(myArray[0]) + UInt32(1)))
</code>```

答:
arc4random_uniform returns a random value between 0 and the argument passed in -1. Therefore if you pass in 1, you'll only ever get 0 out.

The behaviour you want can be achieved by passing in the array count. For example:

let randomIndex = Int(arc4random_uniform(Int32(myArray.count)))

Note the casts, this is because arc4random_uniform is C derived so requires explicit typing.

Title: Convert Java Math.random to Swift 4

Body:
I was wondering how I can convert the below java code to Swift 4.

int randomNoteIndex = myArray[0] + (int) (Math.random() * (myArray[1] - myArray[0] + 1));

Here is what i tried but I always get the same number myArray[0] everytime

 let randomNoteIndex = myArray[0] +  Int(arc4random_uniform(1) * (UInt32(myArray[1]) - UInt32(myArray[0]) + UInt32(1)))


问:
How to run this code in series using verilog
The following code is compiled and is working in parallel, Please help me to make these code work sequentially, i.e after stage1 counter should reset itself and starts from 0 for the stage2. The following codes has Module1- stage1 and module2-stage2. This is the process flow in which one stage occur after completion of another. For example when stage 1 is done then counter reset itself and then stage 2 starts with count zero.Here stage 1 module has counter that counts till 18 and stage 2 counter counts 8.  </p>

```<code>    module stage1(
                input Clk, //50 Hz clock
                input x0,
                input reset,
                output reg y0,y1,y2,y3,y5,y7,y10,y15,
                output reg stage1_done
                );
        reg [15:0] counter = 0;
        parameter F = 50;
        always@ (posedge Clk or posedge reset)
            if(reset) begin
                counter <= 0;
                {y0,y1,y2,y3,y5,y7,y10,y15} <= 8'b00000000;
                stage1_done <= 0;
            end else begin
                if(x0 == 1) begin
                    if(counter == 18*F)
                        stage1_done <= 1;
                    else begin
                        counter <= counter + 1;
                        stage1_done <= 0;
                    end
                    if(counter >= 1*F && counter < 10*F)
                        y0 <= 1;
                    else
                        y0 <= 0;
                    if(counter >= 1*F && counter < 17*F)
                        y1 <= 1;
                    else
                        y1 <= 0;
                    if(counter >= 1*F && counter < 9*F)
                        y2 <= 1;
                    else
                        y2 <= 0;
                    if(counter >= 11*F && counter < 16*F)
                        y3 <= 1;
                    else
                        y3 <= 0;
                    if(counter >= 1*F && counter < 18*F)
                        y5 <= 1;
                    else
                        y5 <= 0;
                    if(counter >= 1*F && counter < 5*F)
                        y7 <= 1;
                    else
                        y7 <= 0;
                    if(counter >= 1*F && counter < 5*F)
                        y10 <= 1;
                    else
                        y10 <= 0;
                    if((counter >= 2*F && counter < 9*F) || (counter >= 13*F && counter < 17*F))
                        y15 <= 1;
                    else
                        y15 <= 0;
                end
            end

        endmodule
</code>```

<p>//Module for stage 2;</p>

```<code>    module stage2(
            input x0,
            input Clk, //50 Hz clock
            input reset,
            output reg y1,y3,y5,
            output reg stage2_done
            );
    reg [15:0] counter = 0;
    parameter F = 50;
    always@ (posedge Clk or posedge reset)
        if(reset) begin
            counter <= 0;
            {y1,y3,y5} <= 3'b000;
            stage2_done <= 0;
        end
    else begin   if(x0 == 1) begin
            if(counter == 8*F)
                stage2_done <= 1;
            else begin
                counter <= counter + 1;
                stage2_done <= 0;
            end
            if(counter >= 1*F && counter < 8*F)
                y1 <= 1;
            else
                y1 <= 0;
            if(counter >= 1*F && counter < 8*F)
                y3 <= 1;
            else
                y3 <= 0;
            if(counter >= 1*F && counter < 8*F)
                y5 <= 1;
            else
                y5 <= 0;
            end
        end

    endmodule
</code>```

答: If you want a counter from stage2 module to start counting after counter from stage1 finishes, then you have to "inform" it that the other one finished counting. In your case you can use stage1_done signal and feed it to stage2 module. Use this signal as a condition for counter to start counting initially. Also, shouldn't you reset the counter from stage1 back to 0 when you assert stage1_done?

Body:
The following code is compiled and is working in parallel, Please help me to make these code work sequentially, i.e after stage1 counter should reset itself and starts from 0 for the stage2. The following codes has Module1- stage1 and module2-stage2. This is the process flow in which one stage occur after completion of another. For example when stage 1 is done then counter reset itself and then stage 2 starts with count zero.Here stage 1 module has counter that counts till 18 and stage 2 counter counts 8.

    module stage1(
                input Clk, //50 Hz clock
                input x0,
                input reset,
                output reg y0,y1,y2,y3,y5,y7,y10,y15,
                output reg stage1_done
                );
        reg [15:0] counter = 0;
        parameter F = 50;
        always@ (posedge Clk or posedge reset)
            if(reset) begin
                counter <= 0;
                {y0,y1,y2,y3,y5,y7,y10,y15} <= 8'b00000000;
                stage1_done <= 0;
            end else begin
                if(x0 == 1) begin
                    if(counter == 18*F)
                        stage1_done <= 1;
                    else begin
                        counter <= counter + 1;
                        stage1_done <= 0;
                    end
                    if(counter >= 1*F && counter < 10*F)
                        y0 <= 1;
                    else
                        y0 <= 0;
                    if(counter >= 1*F && counter < 17*F)
                        y1 <= 1;
                    else
                        y1 <= 0;
                    if(counter >= 1*F && counter < 9*F)
                        y2 <= 1;
                    else
                        y2 <= 0;
                    if(counter >= 11*F && counter < 16*F)
                        y3 <= 1;
                    else
                        y3 <= 0;
                    if(counter >= 1*F && counter < 18*F)
                        y5 <= 1;
                    else
                        y5 <= 0;
                    if(counter >= 1*F && counter < 5*F)
                        y7 <= 1;
                    else
                        y7 <= 0;
                    if(counter >= 1*F && counter < 5*F)
                        y10 <= 1;
                    else
                        y10 <= 0;
                    if((counter >= 2*F && counter < 9*F) || (counter >= 13*F && counter < 17*F))
                        y15 <= 1;
                    else
                        y15 <= 0;
                end
            end

        endmodule

//Module for stage 2;

    module stage2(
            input x0,
            input Clk, //50 Hz clock
            input reset,
            output reg y1,y3,y5,
            output reg stage2_done
            );
    reg [15:0] counter = 0;
    parameter F = 50;
    always@ (posedge Clk or posedge reset)
        if(reset) begin
            counter <= 0;
            {y1,y3,y5} <= 3'b000;
            stage2_done <= 0;
        end
    else begin   if(x0 == 1) begin
            if(counter == 8*F)
                stage2_done <= 1;
            else begin
                counter <= counter + 1;
                stage2_done <= 0;
            end
            if(counter >= 1*F && counter < 8*F)
                y1 <= 1;
            else
                y1 <= 0;
            if(counter >= 1*F && counter < 8*F)
                y3 <= 1;
            else
                y3 <= 0;
            if(counter >= 1*F && counter < 8*F)
                y5 <= 1;
            else
                y5 <= 0;
            end
        end

    endmodule


问:
Removal of an iFrame after internal submit has been clicked
Hope people can help - been using 'Stack Over Flow' for reference for many years now, but this is the first time I'm stuck on some coding. Below is the iFrame, what I would like to happen is when the submit button on the form has been clicked is for it to disappear, but instead the iFrame is still there and within the iFrame it goes to 'How can we help you today?'

Also, when the iFrame disappears a line of text should appear.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="overflow: hidden;position: relative;height: 970px; width:150%;" onclick="removeIFrame();">
<iframe id="myIframe" src="https://sheersense.freshdesk.com/support/tickets/new" scrolling="no" width="100%" height="1125px" frameborder="0" style="position: absolute; top:-150px"></iframe>

<div id="text_display" style="">Thank you for your ticket, a member of the Sheersense team will be in touch with you shortly.</div>
</div></code>```

Many thanks for the help!

答:
try this </p>

```<code>function removeIFrame() {
        var frame = document.getElementById("myIframe");
        frame.remove();
    }

    window.onload = function() {
            var frame = window.myIframe;
            var innerDocument = (frame.contentWindow || frame.contentDocument);
            if (innerDocument.document) innerDocument = innerDocument.document;
            innerDocument.onclick =function() {
                 removeIFrame();
            }
    }
</code>```

Body:
Hope people can help - been using 'Stack Over Flow' for reference for many years now, but this is the first time I'm stuck on some coding. Below is the iFrame, what I would like to happen is when the submit button on the form has been clicked is for it to disappear, but instead the iFrame is still there and within the iFrame it goes to 'How can we help you today?'

Also, when the iFrame disappears a line of text should appear.

Thank you for your ticket, a member of the Sheersense team will be in touch with you shortly.

Many thanks for the help!

Body:
try this

function removeIFrame() {
        var frame = document.getElementById("myIframe");
        frame.remove();
    }

    window.onload = function() {
            var frame = window.myIframe;
            var innerDocument = (frame.contentWindow || frame.contentDocument);
            if (innerDocument.document) innerDocument = innerDocument.document;
            innerDocument.onclick =function() {
                 removeIFrame();
            }
    }


问:
Why lodash uses switch-case in negate function?
The following code is the source code of negate function in lodash. As we can see that when the length of parameters less than 4, it uses switch-case instead of using apply directly. What magic about this code? Does it make the performance better? And why the split point is 4?

```<code>function negate(predicate) {
  if (typeof predicate != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  return function() {
    var args = arguments;
    switch (args.length) {
      case 0: return !predicate.call(this);
      case 1: return !predicate.call(this, args[0]);
      case 2: return !predicate.call(this, args[0], args[1]);
      case 3: return !predicate.call(this, args[0], args[1], args[2]);
    }
    return !predicate.apply(this, args);
  };
}
</code>```

答:
Sry, but my crystal ball is still in repair. So I can only give you my best guess about the intentions of the author.

I think the point here is not about the switch but rather to enable the optimizer to convert this whole construct into a a single one of these paths, assuming the function will be called with a consistent set of arguments.

basically optimizing this whole constuct away and even inlining the function body of the predicate into something like this pseudocode.

assuming the function was always called with 2 arguments

```<code>function(){
    //a gate to ensure the optimization is still correct/applicable
    //probably more complex than this
    if(arguments.length === 2){
        //assign predicate function args
        var value = arguments[0], index = arguments[1];
        [function body of predicate]
    }else{
        [de-optimize]
        //execute the de-optimized version of this function
    }
}
</code>```

Why 0..3 arguments? imo, these are the most common cases. And the default case is only there for completeness and (again, my opinion) should never/rarely been hit.

Another point may be, that Function#call() is in my experience a bit faster than Function#apply(). Rarely enough to even think about it, but this is a lib that will be used by other libraries, so every performance issue may increase exponetially.

Body:
The following code is the source code of negate function in lodash. As we can see that when the length of parameters less than 4, it uses switch-case instead of using apply directly. What magic about this code? Does it make the performance better? And why the split point is 4?

function negate(predicate) {
  if (typeof predicate != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  return function() {
    var args = arguments;
    switch (args.length) {
      case 0: return !predicate.call(this);
      case 1: return !predicate.call(this, args[0]);
      case 2: return !predicate.call(this, args[0], args[1]);
      case 3: return !predicate.call(this, args[0], args[1], args[2]);
    }
    return !predicate.apply(this, args);
  };
}

Body:
Sry, but my crystal ball is still in repair. So I can only give you my best guess about the intentions of the author.

I think the point here is not about the switch but rather to enable the optimizer to convert this whole construct into a a single one of these paths, assuming the function will be called with a consistent set of arguments.

basically optimizing this whole constuct away and even inlining the function body of the predicate into something like this pseudocode.

assuming the function was always called with 2 arguments

function(){
    //a gate to ensure the optimization is still correct/applicable
    //probably more complex than this
    if(arguments.length === 2){
        //assign predicate function args
        var value = arguments[0], index = arguments[1];
        [function body of predicate]
    }else{
        [de-optimize]
        //execute the de-optimized version of this function
    }
}

Why 0..3 arguments? imo, these are the most common cases. And the default case is only there for completeness and (again, my opinion) should never/rarely been hit.

Another point may be, that Function#call() is in my experience a bit faster than Function#apply(). Rarely enough to even think about it, but this is a lib that will be used by other libraries, so every performance issue may increase exponetially.


问:
Modify django Admin forms
I have the following model form which I inherit in the majority of my models.

```<code>class UserStamp(models.Model):
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
                                   related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE)

    class Meta:
        abstract = True
</code>```

Where I construct my own forms I use

```<code>form.instance.created_by = self.request.user
</code>```

and everything is ok.

But not in admin (expecting staff users) because he uses his own forms.
What is the simplest way to make the admin forms work properly(something tha I don't need to do each of them from zero).

答:
You can override save_model in your ModelAdmin class.

```<code>class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        obj.save()
</code>```

Title: Modify django Admin forms

Body:
I have the following model form which I inherit in the majority of my models.

class UserStamp(models.Model):
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
                                   related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE)

    class Meta:
        abstract = True

Where I construct my own forms I use

form.instance.created_by = self.request.user

and everything is ok.

But not in admin (expecting staff users) because he uses his own forms.
What is the simplest way to make the admin forms work properly(something tha I don't need to do each of them from zero).

Body:
You can override save_model in your ModelAdmin class.

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        obj.save()


问:
Remove the characters from string
```
SubClient          Status
POD5_vcprd01
POD4_vcprd01
POD15_VCPRD01_New
POD11_2_vcprd01
POD11_1_vcprd01
POD12_vcprd01
POD13_vcprd01_new
POD10_vcprd01_NEW
```

I am trying to remove _new & _New from the above table which is in CSV. I wrote the below script:

```<code>$report = @()
$Pod_SC = Import-csv "above table"

foreach($Podclient in $pod_sc)
{
$Client = $Podclient.Subclient
$Subclient = $Client.Substring(0,$Client.IndexOf('_N'))
$Status = $Podclient.Status

$object = New-Object -TypeName PSobject

$object | Add-Member -MemberType NoteProperty -Name "Subclient" -Value $SubClient

$object | Add-Member -MemberType NoteProperty -Name "Status" -Value $Status

$report += $object
}
</code>```

But its not working. the expected output is

```
SubClient          Status
POD5_vcprd01
POD4_vcprd01
POD15_VCPRD01
POD11_2_vcprd01
POD11_1_vcprd01
POD12_vcprd01
POD13_vcprd01
POD10_vcprd01
```

答:
Just treat it as a text replace, if you use ireplace which is case-insensitive you can deal with both _New and _new together.

```<code>(Get-Content file.csv) -ireplace "_new","" | Set-Content file.csv
</code>```

You can actually use just -ireplace "_new", but if you wanted to replace rather than remove the syntax is the same as in my example -ireplace "_new","_old"

Title: Remove the characters from string

Body:
SubClient          Status
POD5_vcprd01
POD4_vcprd01
POD15_VCPRD01_New
POD11_2_vcprd01
POD11_1_vcprd01
POD12_vcprd01
POD13_vcprd01_new
POD10_vcprd01_NEW

I am trying to remove _new & _New from the above table which is in CSV. I wrote the below script:

$report = @()
$Pod_SC = Import-csv "above table"

foreach($Podclient in $pod_sc)
{
$Client = $Podclient.Subclient
$Subclient = $Client.Substring(0,$Client.IndexOf('_N'))
$Status = $Podclient.Status

$object = New-Object -TypeName PSobject

$object | Add-Member -MemberType NoteProperty -Name "Subclient" -Value $SubClient

$object | Add-Member -MemberType NoteProperty -Name "Status" -Value $Status

$report += $object
}

But its not working. the expected output is

SubClient          Status
POD5_vcprd01
POD4_vcprd01
POD15_VCPRD01
POD11_2_vcprd01
POD11_1_vcprd01
POD12_vcprd01
POD13_vcprd01
POD10_vcprd01

Body:
Just treat it as a text replace, if you use ireplace which is case-insensitive you can deal with both _New and _new together.

(Get-Content file.csv) -ireplace "_new","" | Set-Content file.csv

You can actually use just -ireplace "_new", but if you wanted to replace rather than remove the syntax is the same as in my example -ireplace "_new","_old"


问:
Copy non empty struct values in Golang for updating Datastore
I'm writing a PATCH API and it is not necessary to send all the fields in request. I'd like to update only the new fields.
I'm using Datastore, and I think, I need to send entire struct that contains the final value I intend to save, as it replaces all the values.
I retrieve existing values from DB in one struct and I have the request in another struct.

```<code>type product struct {
    TITLE    string `json:"title"`
    SUMMARY  string `json:"summary"`
    IMAGEURL string `json:"imageUrl"`
    CATEGORY string `json:"category"`
    TYPE     int    `json:"type"`
}

var dbVal product // Holds the existing DB values
var formVal product // Holds the values received from web form (api request)
</code>```

formVal need not have all the values. It is empty if the field is not sent in the request.

I want the dbVal struct to be updated with the values in formVal ONLY if formVal field is not empty (!= "" for string or != 0 for int).

PS: I searched for more than a day and tried different examples and tried to use reflect from some of the other answers, but not able to find out how to assign values to another struct. If this is already answered, I'm sorry for reposting this - please share the link.

答:
I would propose to slightly change the struct to use pointers:

```<code>type product struct {
    TITLE    *string `json:"title"`
    SUMMARY  *string `json:"summary"`
    IMAGEURL *string `json:"imageUrl"`
    CATEGORY *string `json:"category"`
    TYPE     *int    `json:"type"`
}
</code>```

And then you can iterate through the patch entity using reflect and replace non-nil values. Check example in Go Playground.

Body:
I'm writing a PATCH API and it is not necessary to send all the fields in request. I'd like to update only the new fields.
I'm using Datastore, and I think, I need to send entire struct that contains the final value I intend to save, as it replaces all the values.
I retrieve existing values from DB in one struct and I have the request in another struct.

type product struct {
    TITLE    string `json:"title"`
    SUMMARY  string `json:"summary"`
    IMAGEURL string `json:"imageUrl"`
    CATEGORY string `json:"category"`
    TYPE     int    `json:"type"`
}

var dbVal product // Holds the existing DB values
var formVal product // Holds the values received from web form (api request)

formVal need not have all the values. It is empty if the field is not sent in the request.

I want the dbVal struct to be updated with the values in formVal ONLY if formVal field is not empty (!= "" for string or != 0 for int).

PS: I searched for more than a day and tried different examples and tried to use reflect from some of the other answers, but not able to find out how to assign values to another struct. If this is already answered, I'm sorry for reposting this - please share the link.

Body:
I would propose to slightly change the struct to use pointers:

type product struct {
    TITLE    *string `json:"title"`
    SUMMARY  *string `json:"summary"`
    IMAGEURL *string `json:"imageUrl"`
    CATEGORY *string `json:"category"`
    TYPE     *int    `json:"type"`
}

And then you can iterate through the patch entity using reflect and replace non-nil values. Check example in Go Playground.

ContentLicense: CC BY-SA 4.0


问:
Background image not loading
I am new to html/css and I do not understand why my background image is not showing up. This is part of a simple test CSS sheet and HTML code for a simple site. I am trying to add a background-image and I have done this once and it worked and I do not know why it does not work now.</p>

```<code>.timeline{
    width: 100%;
    height: 400px;
    display: inline-flex;
    background-image:url("img/back.jpg");
}
</code>```

答:
Try replace this code

```display:inline-flex;```

to this code

```display:flex;```

Title: Background image not loading

Body:
I am new to html/css and I do not understand why my background image is not showing up. This is part of a simple test CSS sheet and HTML code for a simple site. I am trying to add a background-image and I have done this once and it worked and I do not know why it does not work now.

.timeline{
    width: 100%;
    height: 400px;
    display: inline-flex;
    background-image:url("img/back.jpg");
}

Body:
Try replace this code

display:inline-flex;

to this code

display:flex;


问:
TYPO3 Extension: 'Unknown column in field list' error
Basically: Every time I add a new class/model with the extension_builder and then want to create a record of that class I get the following error message:

2: SQL error: 'Unknown column 'edited' in 'field list''
  (tx_icingaconfgen_domain_model_checkperiod:NEW5a27f9da8a41d636846075)

The interesting thing is: "edited" is NOT a property of that class, but the property of other classes in that extension. I've searched through the TCA of the class that throws the error and also the MySql table itself, but the field "edited" is indeed not part of that class. What's going on here?

Edit: What I find interesting is the fact that when I add a column "edited" to MySql table manually, the record can be created. But in no way I'm using this property in my Model. Why does it require a MySql column of that name then?

答:
Without seeing the code I can only guess whats going on. Surely the field is requiered when a record is persisted. So it is possible that you referenced it in your TCA. If not in the columns maybe in the ctrl section:

```<code>'ctrl' => [
    'tstamp' => 'tstamp',
    'crdate' => 'crdate',
    'cruser_id' => 'cruser_id',
    ...
],
</code>```

These fields are updated automatically if a recods is changed or created. There are more of those fields. So check your ctrl section.

It is also possible that you map another property (possibly even of another class) to that database field in your TypoScript like this:

```<code>plugin.tx_myextension {
    persistence {
        classes {
            MyVendor\MyExtension\Domain\Model\Person {
                mapping {
                    tableName = tt_address
                    recordType = \MyVendor\MyExtension\Domain\Model\Person
                    columns {
                        birthday.mapOnProperty = dateOfBirth
                    }
                }
            }
        }
    }
}
</code>```

Example taken from here.

Body:
Without seeing the code I can only guess whats going on. Surely the field is requiered when a record is persisted. So it is possible that you referenced it in your TCA. If not in the columns maybe in the ctrl section:

'ctrl' => [
    'tstamp' => 'tstamp',
    'crdate' => 'crdate',
    'cruser_id' => 'cruser_id',
    ...
],

These fields are updated automatically if a recods is changed or created. There are more of those fields. So check your ctrl section.

It is also possible that you map another property (possibly even of another class) to that database field in your TypoScript like this:

plugin.tx_myextension {
    persistence {
        classes {
            MyVendor\MyExtension\Domain\Model\Person {
                mapping {
                    tableName = tt_address
                    recordType = \MyVendor\MyExtension\Domain\Model\Person
                    columns {
                        birthday.mapOnProperty = dateOfBirth
                    }
                }
            }
        }
    }
}

Example taken from here.


问:
VirtualProtect Size
So i was playing around with function hooking on Windows and everything was pretty much working as expected. By overriding the value my LoadLibrary Pointer points to with a jmp instruction and the offset to my Hook Function, i am able to execute my own Code on every call to LoadLibrary. To override the bytes in memory i obviously need to change the protection flags for the specific memory. Even though this works fine i got an unexpected result.

```<code>HMODULE APIENTRY hLoadLibrary(LPCWSTR lpFileName) {
    MessageBox(NULL, "NOT LOADING A LIBRA1RY!", "YO", MB_OK);

    return NULL;
};

BOOL APIENTRY DllMain(HANDLE hModule, DWORD  fdwReason, LPVOID lpReserved)
{
    DWORD* hookPointer = (DWORD*)&hLoadLibrary;
    DWORD* originPointer = (DWORD*)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryW");

    DWORD offset = (DWORD)hookPointer - (DWORD)originPointer - 5;

    DWORD oldProtect;
    VirtualProtect((LPVOID)originPointer, sizeof(char) * 5, PAGE_EXECUTE_READWRITE, &oldProtect);

    char* p = (char*)originPointer;
    *p = '\xE9';
    p++;
    DWORD* q = (DWORD*)p;
    *q = offset;

    VirtualProtect((LPVOID)originPointer, sizeof(char) * 5, oldProtect, &oldProtect);

    return TRUE;
}
</code>```

Where this

```<code>VirtualProtect((LPVOID)originPointer, sizeof(char) * 5, PAGE_EXECUTE_READWRITE, &oldProtect);
</code>```

is what i expected to work

This

```<code>VirtualProtect((LPVOID)originPointer, 0, PAGE_EXECUTE_READWRITE, &oldProtect);
</code>```

obviously failing

But this

```<code>VirtualProtect((LPVOID)originPointer, 1, PAGE_EXECUTE_READWRITE, &oldProtect);
</code>```

i found to also work, even though i only change the Protection for one byte.

Can someone explain why this works?

答: Page protection attributes necessarily have a granularity equal to the size of a page.  4096 bytes.  You should never lie about the size you need, bummer if the address you pass happens to be located near the end of the page.</p>

Title: VirtualProtect Size

Body:
So i was playing around with function hooking on Windows and everything was pretty much working as expected. By overriding the value my LoadLibrary Pointer points to with a jmp instruction and the offset to my Hook Function, i am able to execute my own Code on every call to LoadLibrary. To override the bytes in memory i obviously need to change the protection flags for the specific memory. Even though this works fine i got an unexpected result.

HMODULE APIENTRY hLoadLibrary(LPCWSTR lpFileName) {
    MessageBox(NULL, "NOT LOADING A LIBRA1RY!", "YO", MB_OK);

    return NULL;
};

BOOL APIENTRY DllMain(HANDLE hModule, DWORD  fdwReason, LPVOID lpReserved)
{
    DWORD* hookPointer = (DWORD*)&hLoadLibrary;
    DWORD* originPointer = (DWORD*)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryW");

    DWORD offset = (DWORD)hookPointer - (DWORD)originPointer - 5;

    DWORD oldProtect;
    VirtualProtect((LPVOID)originPointer, sizeof(char) * 5, PAGE_EXECUTE_READWRITE, &oldProtect);

    char* p = (char*)originPointer;
    *p = '\xE9';
    p++;
    DWORD* q = (DWORD*)p;
    *q = offset;

    VirtualProtect((LPVOID)originPointer, sizeof(char) * 5, oldProtect, &oldProtect);

    return TRUE;
}

Where this

VirtualProtect((LPVOID)originPointer, sizeof(char) * 5, PAGE_EXECUTE_READWRITE, &oldProtect);

is what i expected to work

This

VirtualProtect((LPVOID)originPointer, 0, PAGE_EXECUTE_READWRITE, &oldProtect);

obviously failing

But this

VirtualProtect((LPVOID)originPointer, 1, PAGE_EXECUTE_READWRITE, &oldProtect);

i found to also work, even though i only change the Protection for one byte.

Can someone explain why this works?


问:
The Django make ORM query
```<code>class Task(models.Model):
    subject = models.CharField(max_length=256)
    description = models.TextField(max_length=1024)
    reward = models.PositiveIntegerField()
    begin_date = models.DateField()
    number_of_people = models.PositiveIntegerField(default=1)

class TaskDetail(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    task = models.ForeignKey(Task, related_name='tasks')
</code>```

This is a simple task assignment system model designed by me.
and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query.

```<code>users = User.objects.all
</code>```

Does anyone know how to solve this issue? Thx

答:
There is no need of giving related_name with user column in TaskDetail model.
by using foreign_key there is no need to build another query. You can use chain concept:

```<code>users = User.objects.all()
task_details = TaskDetail.objects.filter(user=users)
for task_detail in task_details:
    subject = task_detail.task.subject
</code>```

Title: The Django make ORM query

Body:
class Task(models.Model):
    subject = models.CharField(max_length=256)
    description = models.TextField(max_length=1024)
    reward = models.PositiveIntegerField()
    begin_date = models.DateField()
    number_of_people = models.PositiveIntegerField(default=1)

class TaskDetail(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    task = models.ForeignKey(Task, related_name='tasks')

This is a simple task assignment system model designed by me.
and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query.

users = User.objects.all

Does anyone know how to solve this issue? Thx

Body:
There is no need of giving related_name with user column in TaskDetail model.
by using foreign_key there is no need to build another query. You can use chain concept:

users = User.objects.all()
task_details = TaskDetail.objects.filter(user=users)
for task_detail in task_details:
    subject = task_detail.task.subject


问:
Fetching Single Client Data - Laravel
In my code below,

I request for the ids of selected products (by checking a checkbox).

Now, i find the clients of whom the products belong to. Then i get the name and phone number of the clients.

Now the query string below is an API to send messages to these clients.

but When i send a message, i am not able to seperate the product numbers for the respective clients.

For instance, if Mark and Bill are the clients, the message should be like

Dear Customer, your products with number #343fr3 has been shipped - For Mark`

Dear Customer, your products with number #22543 has been shipped - For Bill

But what happens with mine is, one clients (Mark or Bill) gets the product number of another in the message.

What am i doing wrong or could it be from how the api is structured?

```<code> public function sendAll(Request $request)
 {
     $ids      = $request->ids;
     $split    = explode(",",$ids);
     $shipment = Shipment::findOrFail($split);

     if(request()->ajax()) {
         $clients = Client::whereHas('products', function($find_clients)use($split)
        {
            $find_clients->whereIn('id',$split);
        })->get();

        foreach($shipment as $check_shipment)
        {
            if($check_shipment->status == 0 )
            {
                //do something
            }
            else
            {
                $get_client_name  = [];
                $get_client_phone = [];

                foreach($clients as $key => $client)
                {
                    $get_client_name[]  = $client->name;
                    $get_client_phone[] = $client->phone;
                }

                $query = "?key=something&to=".implode(',',$get_client_phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";
           }
       }
   }
}
</code>```

答:
The problem is that the data you are trying to loop through doesn't not have a relationship between them. what you can do is,

```<code> public function sendAll(Request $request)
 {
  $ids      = $request->ids;
  $split    = explode(",",$ids);
  $shipment = Shipment::with('client')->findOrFail($split);

   foreach($shipment as $check_shipment)
    {
      if($check_shipment->status == 0 )
     {
       //do something
     }
     else
     {
       $get_client_name []= $check_shipment->client->name;
       $get_client_phone [] = $check_shipment->client->phone_no;
     }
   }

 $query = "?key=something&to=".implode(',',$get_client_phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";

}
</code>```

Hope this helps.

Title: Fetching Single Client Data - Laravel

Body:
In my code below,

I request for the ids of selected products (by checking a checkbox).

Now, i find the clients of whom the products belong to. Then i get the name and phone number of the clients.

Now the query string below is an API to send messages to these clients.

but When i send a message, i am not able to seperate the product numbers for the respective clients.

For instance, if Mark and Bill are the clients, the message should be like

Dear Customer, your products with number #343fr3 has been shipped - For Mark`

Dear Customer, your products with number #22543 has been shipped - For Bill

But what happens with mine is, one clients (Mark or Bill) gets the product number of another in the message.

What am i doing wrong or could it be from how the api is structured?

 public function sendAll(Request $request)
 {
     $ids      = $request->ids;
     $split    = explode(",",$ids);
     $shipment = Shipment::findOrFail($split);

     if(request()->ajax()) {
         $clients = Client::whereHas('products', function($find_clients)use($split)
        {
            $find_clients->whereIn('id',$split);
        })->get();

        foreach($shipment as $check_shipment)
        {
            if($check_shipment->status == 0 )
            {
                //do something
            }
            else
            {
                $get_client_name  = [];
                $get_client_phone = [];

                foreach($clients as $key => $client)
                {
                    $get_client_name[]  = $client->name;
                    $get_client_phone[] = $client->phone;
                }

                $query = "?key=something&to=".implode(',',$get_client_phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";
           }
       }
   }
}

Body:
The problem is that the data you are trying to loop through doesn't not have a relationship between them. what you can do is,

 public function sendAll(Request $request)
 {
  $ids      = $request->ids;
  $split    = explode(",",$ids);
  $shipment = Shipment::with('client')->findOrFail($split);

   foreach($shipment as $check_shipment)
    {
      if($check_shipment->status == 0 )
     {
       //do something
     }
     else
     {
       $get_client_name []= $check_shipment->client->name;
       $get_client_phone [] = $check_shipment->client->phone_no;
     }
   }

 $query = "?key=something&to=".implode(',',$get_client_phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";

}

Hope this helps.


问:
Query top spring
I want to view 4 products on page. but I tried with query:

```<code>Select * Form table Limit 4
</code>```

but my page has err:

Request processing failed; nested exception is
  org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
  * near line 1, column 7 [SELECT*FROM Book Limit 4]

答:
When you create the query from HQL

```<code>Query query = entityManager.createQuery(the hql here);
</code>```

you can use query.setMaxResults(4) method rather than limit

Title: Query top spring

Body:
I want to view 4 products on page. but I tried with query:

Select * Form table Limit 4

but my page has err:

Request processing failed; nested exception is
  org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
  * near line 1, column 7 [SELECT*FROM Book Limit 4]

Body:
When you create the query from HQL

Query query = entityManager.createQuery(the hql here);

you can use query.setMaxResults(4) method rather than limit


问:
What version control system should I use?
I'm working by myself on a project.  I'd like an easy to use, free, version control system that integrates with IntelliJ IDEA nicely.  I'd prefer if the whole repository was isolated to a single file, or folder, so that I could back it up on a USB stick easily and transfer it to another computer.</p>

答:
Amongst the various IntelliJ IDEA VCS support, the one for git is fine and easy to use.

Plus, with git bundle, you can export your repo to one file, very easy to copy around (on a backup storage for instance).

See the SO question "Backup a Local Git Repository"


问:
How to validate date in laravel
In validate method I have following :

```<code>$this->validate($request, ['test_date' => 'required|unique:test_db']);
</code>```

The test_date in test_db is stored as unix time.
On submission of form, I get $request->get('test_date') in mm/dd/Y

The unique validation does not work because I get date in mm/dd/Y which is different from db (unix time).

How to make it unique in this validation?

答:
I think if you change the date format then everything will be fine, so try this:

```<code>$date = $request->get('test_date');

$newDate = date('d-m-Y', strtotime($date ));
</code>```

use this $newDate in the validation.

Title: How to validate date in laravel

Body:
In validate method I have following :

$this->validate($request, ['test_date' => 'required|unique:test_db']);

The test_date in test_db is stored as unix time.
On submission of form, I get $request->get('test_date') in mm/dd/Y

The unique validation does not work because I get date in mm/dd/Y which is different from db (unix time).

How to make it unique in this validation?

Body:
I think if you change the date format then everything will be fine, so try this:

$date = $request->get('test_date');

$newDate = date('d-m-Y', strtotime($date ));

use this $newDate in the validation.


问:
Get the 1st and next value inside an array
Lets say I have an array like this

var data = [1,2,3,4,5,6,7,8,9,0];

How can I get the output like this?

```<code>console.log(1,2);
console.log(2,3);
console.log(3,4);
</code>```

and so on.. as of now this is my code

```<code>for (var i = 0; i < data.length; i++) {
 /* Dont know what to do */
}
</code>```

答:
You just need to stop one step before the end of the array in your cycle and print the current and next value</p>

```<code>var data = [1,2,3,4,5,6,7,8,9,0]
for (var i = 0; i < data.length -1; i++) {
    console.log(data[i], data[i+1]);
}
</code>```

Body:
Lets say I have an array like this

var data = [1,2,3,4,5,6,7,8,9,0];

How can I get the output like this?

console.log(1,2);
console.log(2,3);
console.log(3,4);

and so on.. as of now this is my code

for (var i = 0; i < data.length; i++) {
 /* Dont know what to do */
}

Body:
You just need to stop one step before the end of the array in your cycle and print the current and next value

var data = [1,2,3,4,5,6,7,8,9,0]
for (var i = 0; i < data.length -1; i++) {
    console.log(data[i], data[i+1]);
}


问:
Fluid: if - then - elseif - else
I'm a bit new to fluid and I want to make a the following php statement in Fluid.

```<code>if ($var == 'something') {
   // do something
} elseif ($other-var == 'something else') {
   // do something else
} else {
   // do then the other thin
}
</code>```

How can I make this in Fluid? I don't see the elseif statement in the documentation.

答:
There's a possibility for AND and OR in Typo3 7 LTS:

http://typo3blogger.de/fluid-ifviewhelper-conditions-verknupfen/

AND:

```<code><f:if condition="{0: value1, 1: value2} == {0: myValue1, 2: myValue2}">
    <!-- your code-->
</f:if>
</code>```

OR (in the example for checking that at least one variable is not null):

```<code><f:if condition="{0: value1, 1: value2} != {0: 0, 2: 0}">
    <!-- your code-->
</f:if>
</code>```

Hope that helps someone.

Title: Fluid: if - then - elseif - else

Body:
I'm a bit new to fluid and I want to make a the following php statement in Fluid.

if ($var == 'something') {
   // do something
} elseif ($other-var == 'something else') {
   // do something else
} else {
   // do then the other thin
}

How can I make this in Fluid? I don't see the elseif statement in the documentation.

Body:
There's a possibility for AND and OR in Typo3 7 LTS:

http://typo3blogger.de/fluid-ifviewhelper-conditions-verknupfen/

AND:

<f:if condition="{0: value1, 1: value2} == {0: myValue1, 2: myValue2}">
    <!-- your code-->
</f:if>

OR (in the example for checking that at least one variable is not null):

<f:if condition="{0: value1, 1: value2} != {0: 0, 2: 0}">
    <!-- your code-->
</f:if>

Hope that helps someone.


问:
Persisting UUID in PostgreSQL using JPA
I'm trying to persist an entity in PostgreSQL that uses UUID as primary key. I've tried persisting it as a plain UUID:

```<code>@Id
@Column(name = "customer_id")
private UUID id;
</code>```

With the above, I get this error:

```<code>ERROR: column "customer_id" is of type uuid but expression is of type bytea
Hint: You will need to rewrite or cast the expression.
Position: 137
</code>```

I also tried persisting the UUID as byte[] to no avail:

```<code>@Transient
private UUID id;

@Id
@Column(name = "customer_id")
@Access(AccessType.PROPERTY)
@Lob
protected byte[] getRowId() {
    return id.toString().getBytes();
}

protected void setRowId(byte[] rowId) {
    id = UUID.fromString(new String(rowId));
}
</code>```

If I remove @Lob, the error I get is the same as the one posted above. But with @Lob applied, the error changes slightly to:

```<code>ERROR: column "customer_id" is of type uuid but expression is of type bigint
Hint: You will need to rewrite or cast the expression.
Position: 137
</code>```

I'm feeling extremely bad being unable to do something as simple as this!

I'm using Hibernate 4.1.3.Final with PostgreSQL 9.1.

I've seen numerous questions on SO more or less with the same issue but they are all old and none seems to have a straight forward answer.

I'd like to achieve this in a standard way without resorting to ugly hacks. But if this can be achieved only though (ugly) hacks, then may be that's what I'll do. However, I don't want to store the UUID as a varchar in the database as that's not good for performance. Also, I'd want to not introduce a Hibernate dependency in my code if possible.

Any help would be greatly appreciated.

UPDATE 1 (2012-07-03 12:15 pm)

Well, well, well... It's kinda interesting that I tested the exact same code (plain UUID, no conversion -- the first version of the code posted above) with SQL server 2008 R2 using the JTDS driver (v1.2.5) and, guess what, it worked as a charm (of course I had to change connection-related info in persistence.xml).

Now, is it a PostgreSQL-specific issue or what?

答:
Adds this flag on postgresql url connection: ?stringtype=unspecified

like that

jdbc:postgresql://localhost:5432/yourdatabase?stringtype=unspecified

Title: Persisting UUID in PostgreSQL using JPA

Body:
I'm trying to persist an entity in PostgreSQL that uses UUID as primary key. I've tried persisting it as a plain UUID:

@Id
@Column(name = "customer_id")
private UUID id;

With the above, I get this error:

ERROR: column "customer_id" is of type uuid but expression is of type bytea
Hint: You will need to rewrite or cast the expression.
Position: 137

I also tried persisting the UUID as byte[] to no avail:

@Transient
private UUID id;

@Id
@Column(name = "customer_id")
@Access(AccessType.PROPERTY)
@Lob
protected byte[] getRowId() {
    return id.toString().getBytes();
}

protected void setRowId(byte[] rowId) {
    id = UUID.fromString(new String(rowId));
}

If I remove @Lob, the error I get is the same as the one posted above. But with @Lob applied, the error changes slightly to:

ERROR: column "customer_id" is of type uuid but expression is of type bigint
Hint: You will need to rewrite or cast the expression.
Position: 137

I'm feeling extremely bad being unable to do something as simple as this!

I'm using Hibernate 4.1.3.Final with PostgreSQL 9.1.

I've seen numerous questions on SO more or less with the same issue but they are all old and none seems to have a straight forward answer.

I'd like to achieve this in a standard way without resorting to ugly hacks. But if this can be achieved only though (ugly) hacks, then may be that's what I'll do. However, I don't want to store the UUID as a varchar in the database as that's not good for performance. Also, I'd want to not introduce a Hibernate dependency in my code if possible.

Any help would be greatly appreciated.

UPDATE 1 (2012-07-03 12:15 pm)

Well, well, well... It's kinda interesting that I tested the exact same code (plain UUID, no conversion -- the first version of the code posted above) with SQL server 2008 R2 using the JTDS driver (v1.2.5) and, guess what, it worked as a charm (of course I had to change connection-related info in persistence.xml).

Now, is it a PostgreSQL-specific issue or what?