问:
Custom dialog with a RecyclerView is inflated really small on screen
I have created a dialog function which creates a dialog on screen where you can choose something from a RecyclerView (RView adapter code at the bottom):

```<code>fun showSelectACategoryDialog(context: Context,allCategories: LiveData<List<NotesCategory>>, owner: Fragment,chosenCategoryID: (categoryID: Long) -> Unit) {

    val dialog = Dialog(context)

    val adapter = DialogCategoriesRecyclerViewAdapter(context, chosenCategoryID)

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(true)
    dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    dialog.setContentView(R.layout.dialog_select_category)

    dialog.dialog_select_a_category_recyclerView.adapter = adapter

    allCategories.observe(owner, Observer {
        adapter.submitList(it)
    })

// Click listeners

   dialog.show()
</code>```

The dialog function is then called with:

```<code> binding.notesCategoryTextView.setOnClickListener {
            showSelectACategoryDialog(
                context!!,
                notesEditViewModel.allCategories,
                NotesEditFragment(),
                selectedCategory(notesCategory)
            )
        }
</code>```

But when the dialog is called, it looks like this:

Here is the code of the dialog's recycler view adapter, in case it's relevant:

```<code>
class DialogCategoriesRecyclerViewAdapter(
    var context: Context,
    var chosenCategoryID: (categoryID: Long) -> Unit
) : ListAdapter<NotesCategory, DialogCategoriesRecyclerViewAdapter.ViewHolder>(SingleCategoryDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder.from(parent)

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.bind(getItem(position), context)

        holder.itemView.setOnClickListener {
            chosenCategoryID(getItem(position).categoryID)
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val categoryNameTextView: TextView = itemView.findViewById(R.id.dialog_select_a_category_textView)

        fun bind(item: NotesCategory, context: Context) {
            categoryNameTextView.text = item.categoryName
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val view = LayoutInflater.from(parent.context).inflate(
                    R.layout.row_dialog_select_category_all_categories, parent, false
                )
                return ViewHolder(view)
            }
        }
    }
}
</code>```

Here's the XML layout of the dialog that does not work:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:layout_margin = "16dp"
    android:background = "@drawable/dialog_rounded_background">

    <TextView
        android:id = "@+id/dialog_select_a_category_title"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_marginTop = "16dp"
        android:text = "@string/dialog_categories_title"
        android:textColor = "@color/Black"
        android:textSize = "25sp"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id = "@+id/create_new_category_button"
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "16dp"
        android:layout_marginEnd = "16dp"
        android:background = "@drawable/border_square_transparent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_select_a_category_title"
        tools:ignore = "RtlSymmetry">

        <ImageView
            android:id = "@+id/_imageview"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_marginStart = "16dp"
            app:layout_constraintBottom_toBottomOf = "parent"
            app:layout_constraintStart_toStartOf = "parent"
            app:layout_constraintTop_toTopOf = "parent"
            app:srcCompat = "@drawable/dialog_plus"
            tools:ignore = "ContentDescription" />

        <TextView
            android:id = "@+id/_textview"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_margin = "16dp"
            android:layout_marginStart = "56dp"
            android:text = "@string/dialog_create_new_category_button"
            android:textColor = "@color/Black"
            android:textSize = "20sp"
            app:layout_constraintBottom_toBottomOf = "parent"
            app:layout_constraintEnd_toEndOf = "parent"
            app:layout_constraintStart_toEndOf = "@+id/_imageview"
            app:layout_constraintTop_toTopOf = "parent"
            app:layout_constraintVertical_bias = "0.506" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id = "@+id/dialog_select_a_category_recyclerView"
        android:layout_width = "0dp"
        android:layout_height = "0dp"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "16dp"
        android:layout_marginEnd = "16dp"
        android:layout_marginBottom = "20dp"
        android:background = "@drawable/border_square_transparent"
        app:layoutManager = "androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toBottomOf = "@+id/create_new_category_button"
        tools:listitem = "@layout/row_dialog_select_category_all_categories" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And here's the XML layout of the dialog that does work:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:layout_margin = "16dp"
    android:background = "@drawable/dialog_rounded_background">

    <ImageButton
        android:id = "@+id/dialog_create_category_confirm"
        android:layout_width = "50dp"
        android:layout_height = "50dp"
        android:layout_marginStart = "208dp"
        android:layout_marginTop = "64dp"
        android:layout_marginEnd = "16dp"
        android:layout_marginBottom = "16dp"
        android:background = "@android:color/transparent"
        android:src = "@drawable/dialog_check"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "@+id/dialog_create_category_category_name"
        app:layout_constraintStart_toEndOf = "@+id/dialog_create_category_cancel"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_create_category_category_name"
        tools:ignore = "ContentDescription" />

    <ImageButton
        android:id = "@+id/dialog_create_category_cancel"
        android:layout_width = "50dp"
        android:layout_height = "50dp"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "64dp"
        android:layout_marginBottom = "16dp"
        android:background = "@android:color/transparent"
        android:src = "@drawable/dialog_cancel"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintStart_toStartOf = "@+id/dialog_create_category_category_name"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_create_category_category_name"
        tools:ignore = "ContentDescription" />

    <EditText
        android:id = "@+id/dialog_create_category_category_name"
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "32dp"
        android:layout_marginEnd = "16dp"
        android:ems = "10"
        android:hint = "@string/dialog_create_category_hint"
        android:importantForAutofill = "no"
        android:inputType = "textPersonName|textCapSentences"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.487"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_create_category_title" />

    <TextView
        android:id = "@+id/dialog_create_category_title"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_marginTop = "16dp"
        android:text = "@string/dialog_create_a_category_title"
        android:textColor = "@color/Black"
        android:textSize = "30sp"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The second dialog is called by clicking "@+id/create_new_category_button" (which is the only thing that shows on the screen) and it fills the screen width minus margin just fine

答:
You've to define fixed size to dialog's layout or just create a full width dialog.

Try this:

```<code>dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
</code>```

Body:
I have created a dialog function which creates a dialog on screen where you can choose something from a RecyclerView (RView adapter code at the bottom):

fun showSelectACategoryDialog(context: Context,allCategories: LiveData<List<NotesCategory>>, owner: Fragment,chosenCategoryID: (categoryID: Long) -> Unit) {

    val dialog = Dialog(context)

    val adapter = DialogCategoriesRecyclerViewAdapter(context, chosenCategoryID)

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(true)
    dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    dialog.setContentView(R.layout.dialog_select_category)

    dialog.dialog_select_a_category_recyclerView.adapter = adapter

    allCategories.observe(owner, Observer {
        adapter.submitList(it)
    })

// Click listeners

   dialog.show()

The dialog function is then called with:

 binding.notesCategoryTextView.setOnClickListener {
            showSelectACategoryDialog(
                context!!,
                notesEditViewModel.allCategories,
                NotesEditFragment(),
                selectedCategory(notesCategory)
            )
        }

But when the dialog is called, it looks like this:

Here is the code of the dialog's recycler view adapter, in case it's relevant:

class DialogCategoriesRecyclerViewAdapter(
    var context: Context,
    var chosenCategoryID: (categoryID: Long) -> Unit
) : ListAdapter<NotesCategory, DialogCategoriesRecyclerViewAdapter.ViewHolder>(SingleCategoryDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder.from(parent)

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.bind(getItem(position), context)

        holder.itemView.setOnClickListener {
            chosenCategoryID(getItem(position).categoryID)
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val categoryNameTextView: TextView = itemView.findViewById(R.id.dialog_select_a_category_textView)

        fun bind(item: NotesCategory, context: Context) {
            categoryNameTextView.text = item.categoryName
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val view = LayoutInflater.from(parent.context).inflate(
                    R.layout.row_dialog_select_category_all_categories, parent, false
                )
                return ViewHolder(view)
            }
        }
    }
}

Here's the XML layout of the dialog that does not work:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:layout_margin = "16dp"
    android:background = "@drawable/dialog_rounded_background">

    <TextView
        android:id = "@+id/dialog_select_a_category_title"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_marginTop = "16dp"
        android:text = "@string/dialog_categories_title"
        android:textColor = "@color/Black"
        android:textSize = "25sp"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id = "@+id/create_new_category_button"
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "16dp"
        android:layout_marginEnd = "16dp"
        android:background = "@drawable/border_square_transparent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_select_a_category_title"
        tools:ignore = "RtlSymmetry">

        <ImageView
            android:id = "@+id/_imageview"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_marginStart = "16dp"
            app:layout_constraintBottom_toBottomOf = "parent"
            app:layout_constraintStart_toStartOf = "parent"
            app:layout_constraintTop_toTopOf = "parent"
            app:srcCompat = "@drawable/dialog_plus"
            tools:ignore = "ContentDescription" />

        <TextView
            android:id = "@+id/_textview"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:layout_margin = "16dp"
            android:layout_marginStart = "56dp"
            android:text = "@string/dialog_create_new_category_button"
            android:textColor = "@color/Black"
            android:textSize = "20sp"
            app:layout_constraintBottom_toBottomOf = "parent"
            app:layout_constraintEnd_toEndOf = "parent"
            app:layout_constraintStart_toEndOf = "@+id/_imageview"
            app:layout_constraintTop_toTopOf = "parent"
            app:layout_constraintVertical_bias = "0.506" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id = "@+id/dialog_select_a_category_recyclerView"
        android:layout_width = "0dp"
        android:layout_height = "0dp"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "16dp"
        android:layout_marginEnd = "16dp"
        android:layout_marginBottom = "20dp"
        android:background = "@drawable/border_square_transparent"
        app:layoutManager = "androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toBottomOf = "@+id/create_new_category_button"
        tools:listitem = "@layout/row_dialog_select_category_all_categories" />
</androidx.constraintlayout.widget.ConstraintLayout>

And here's the XML layout of the dialog that does work:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:layout_margin = "16dp"
    android:background = "@drawable/dialog_rounded_background">

    <ImageButton
        android:id = "@+id/dialog_create_category_confirm"
        android:layout_width = "50dp"
        android:layout_height = "50dp"
        android:layout_marginStart = "208dp"
        android:layout_marginTop = "64dp"
        android:layout_marginEnd = "16dp"
        android:layout_marginBottom = "16dp"
        android:background = "@android:color/transparent"
        android:src = "@drawable/dialog_check"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "@+id/dialog_create_category_category_name"
        app:layout_constraintStart_toEndOf = "@+id/dialog_create_category_cancel"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_create_category_category_name"
        tools:ignore = "ContentDescription" />

    <ImageButton
        android:id = "@+id/dialog_create_category_cancel"
        android:layout_width = "50dp"
        android:layout_height = "50dp"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "64dp"
        android:layout_marginBottom = "16dp"
        android:background = "@android:color/transparent"
        android:src = "@drawable/dialog_cancel"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintStart_toStartOf = "@+id/dialog_create_category_category_name"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_create_category_category_name"
        tools:ignore = "ContentDescription" />

    <EditText
        android:id = "@+id/dialog_create_category_category_name"
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_marginStart = "16dp"
        android:layout_marginTop = "32dp"
        android:layout_marginEnd = "16dp"
        android:ems = "10"
        android:hint = "@string/dialog_create_category_hint"
        android:importantForAutofill = "no"
        android:inputType = "textPersonName|textCapSentences"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.487"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toBottomOf = "@+id/dialog_create_category_title" />

    <TextView
        android:id = "@+id/dialog_create_category_title"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_marginTop = "16dp"
        android:text = "@string/dialog_create_a_category_title"
        android:textColor = "@color/Black"
        android:textSize = "30sp"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

The second dialog is called by clicking "@+id/create_new_category_button" (which is the only thing that shows on the screen) and it fills the screen width minus margin just fine

Body:
You've to define fixed size to dialog's layout or just create a full width dialog.

Try this:

dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);


来源: stackexchange

问:
How to push two Arrays(having json objects) into a new Array
I Want These two arrays into a new array and then i want to print the final array along with all json objects.

var z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

var y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];```
</div>
</div>

This is what i tried so far</p>

```z.push(y);

for (var i=0 ; i<=z.length;i++)
{
document.getElementById("sa").innerHTML+="appId  :"  + z[i].appId + "
" + " appName  : "+ z[i].appName + "
" + "envId  :"  + z[i].envId + "
" + " envName  : "+ z[i].envName;
}```

</code>```

答:
you can use this trick</p>

```<code>         z.push(...y);

         const filteredArray = z.filter(each => each.appName == 'CapLogix');
          console.log(filteredArray);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I Want These two arrays into a new array and then i want to print the final array along with all json objects.

var z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

var y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];

This is what i tried so far

z.push(y);

for (var i=0 ; i<=z.length;i++)
{
document.getElementById("sa").innerHTML+="appId  :"  + z[i].appId + "
" + " appName  : "+ z[i].appName + "
" + "envId  :"  + z[i].envId + "
" + " envName  : "+ z[i].envName;
}```

Body:
you can use this trick

         z.push(...y);

         const filteredArray = z.filter(each => each.appName == 'CapLogix');
          console.log(filteredArray);


问:
how I make object value as key of another object of array?
I'm getting data in form of array of objects like this...

```<code> let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
</code>```

I want this this array in this form please anyone help...

```<code> let arrayIWant = [
                    {
                      2:[{serviceId:2,name:'ahsan'},{serviceId:2,name:'john'}],
                      5:[{serviceId:5,name:'majeed'},{serviceId:5,name:'ziyad'}]
                    }
                  ]
</code>```

Please help

答:
you can try like this to get your expected result</p>

```<code>    const array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
                  {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
    const iteratedArray = array.reduce((acc,val) => {
      const key = val.serviceId;
       if (!acc[key]) acc[key] = [];
       acc[key].push(val);
       return acc;
    },{});
    const arrayIWant = [iteratedArray];
    console.log(arrayIWant);

</code>```

Body:
I'm getting data in form of array of objects like this...

 let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];

I want this this array in this form please anyone help...

 let arrayIWant = [
                    {
                      2:[{serviceId:2,name:'ahsan'},{serviceId:2,name:'john'}],
                      5:[{serviceId:5,name:'majeed'},{serviceId:5,name:'ziyad'}]
                    }
                  ]

Please help

Body:
you can try like this to get your expected result

    const array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
                  {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
    const iteratedArray = array.reduce((acc,val) => {
      const key = val.serviceId;
       if (!acc[key]) acc[key] = [];
       acc[key].push(val);
       return acc;
    },{});
    const arrayIWant = [iteratedArray];
    console.log(arrayIWant);


问:
expo keeps stopping android emulator
I am running an expo app on windows 10 using the android emulator.  The tunnel builds, and the simulator starts.  but expo keeps crashing on the simulator.

I tried uninstalling expo off the simulator, and rebooting the machine.  Any ideas?

答: When use wrong style like you see image in styled component you used color in squat('') so, check your style then run your project

Title: expo keeps stopping android emulator


问:
How to update the json data (i.e using Id value) in python django?
I want Update the data to use put request
update the data by using Employee Id Value
first retrieve the data which we pass id number and update that particular Id data

```<code>        def put(self, request, pk):
        employeeid = self.get_object(pk)
        serializer = employeeSerializer(employeeid, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

</code>```

I have this sample code but I didn't get update at particular id number.
can anyone help for that ques.

```<code>path('employees/<int:id>/',views.employeeList.as_view())
</code>```

The above one is url

答:
You can write in following way to update the values.
refer the below link https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields</p>

```<code>    def update(self, instance, validated_data):
        '''
        employee updation
        '''
        super(self.__class__, self).update(instance, validated_data)
        return instance

        class Meta:

            model = Employee
            fields = ('__all__')
</code>```

Body:
I want Update the data to use put request
update the data by using Employee Id Value
first retrieve the data which we pass id number and update that particular Id data

        def put(self, request, pk):
        employeeid = self.get_object(pk)
        serializer = employeeSerializer(employeeid, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I have this sample code but I didn't get update at particular id number.
can anyone help for that ques.

path('employees/<int:id>/',views.employeeList.as_view())

The above one is url

Body:
You can write in following way to update the values.
refer the below link https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

    def update(self, instance, validated_data):
        '''
        employee updation
        '''
        super(self.__class__, self).update(instance, validated_data)
        return instance

        class Meta:

            model = Employee
            fields = ('__all__')


答:
As far as I understand you want to group the array of objects by the serviceId.
To do this you can either use groupBy method from lodash https://lodash.com/docs/#groupBy

or write your own implementation like this:

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var data = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
          {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
console.log(groupBy(data, 'serviceId'));```

I hope that will help you.

Title: how I make object value as key of another object of array?

Body:
As far as I understand you want to group the array of objects by the serviceId.
To do this you can either use groupBy method from lodash https://lodash.com/docs/#groupBy

or write your own implementation like this:

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var data = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
          {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
console.log(groupBy(data, 'serviceId'));

I hope that will help you.


问:
how to solve date was not recognized as valid date time?
I am using parsexcact method to convert data into a specific format, but it throws an exception that date is not invalid.

```<code>DateTime t = DateTime.UtcNow;
DateTime t1 = DateTime.ParseExact(t.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
</code>```

答:
Try this:

(I changed t.ToString() to t.ToString("dd/MM/yyyy"))

```<code>DateTime t = DateTime.UtcNow;
DateTime t1 = DateTime.ParseExact(t.ToString("dd/MM/yyyy"), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
</code>```

Body:
I am using parsexcact method to convert data into a specific format, but it throws an exception that date is not invalid.

DateTime t = DateTime.UtcNow;
DateTime t1 = DateTime.ParseExact(t.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Body:
Try this:

(I changed t.ToString() to t.ToString("dd/MM/yyyy"))

DateTime t = DateTime.UtcNow;
DateTime t1 = DateTime.ParseExact(t.ToString("dd/MM/yyyy"), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);


问:
Hiding DataTables columns at specific breakpoints

Problem

I have two DataTables — one is five columns and the other is four columns — and I'm looking for a way to hide columns at specific screen widths.

What I've tried

When I resize the browser, both tables automatically appear to drop down to a two-column chart at 480 pixels in width, but I need additional breakpoints in-between where I'm dropping additional columns since they don't fit inside viewport.

Adding a class of responsive to the table as seen in this example

I've tried using column control helper classes to remove columns at certain breakpoints, but even adding the class none did not hide a column

Adding classes to the  in the thead to take advantage of their responsive breakpoints

I've include responsive: true in my DataTables options

scripts.js

```<code>$('#test-scores').dataTable({
        initComplete: function () {
            this.api().columns([0,1,2]).every( function () {
                var column = this;
                var colIdx = column.index();
                // adjust label for dropdown according to index
                // TODO - colIdx is producing 0
                if (colIdx === 0) {
                    var label = 'districts';
                }
                else if (colIdx === 1) {
                    var label = 'schools';
                }
                else {
                    var label = 'subjects';
                }

                var select = $('.select--map-' + label)
                    .on( 'change', function () {
                        var val = $(this).val();
                        if ( val == '*' ) {
                            column
                                .search( '' )
                                .draw();
                        }
                        else {
                            val = $.fn.dataTable.util.escapeRegex( val );
                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        }
                    });

                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                });
            });
        },
        "pageLength": 25, // The number of entries per page
        "order": [0, 'asc'], // First column in ascending order, previous "3, desc"
        "responsive": true,
        "searching": true,
        "columns": [
        { "data": "district",
            "render": function (data, type, row, meta) {
                return '<a href="/schools/' + makeSlug(data) + '">' + data + '</a>';
            }
        },
        { "data": "school",
            "render": function (data, type, row, meta) {
                return '<a href="/schools/' + makeSlug(row['district']) + '/' + makeSlug(data) + '">' + data + '</a>';
            }
        },
        { "data": "subject" },
        {
            "data": "rate",
            // https://datatables.net/manual/data/renderers#Built-in-helpers
            // Render.number() parameters: thousands separator, decimal separator, decimal places, prefix, suffix
            "render": $.fn.dataTable.render.number( ',', '.', 1, '', '%' )
        },
        {
            "data": "test_takers",
            // Render.number() parameters: thousands separator, decimal separator, decimal places, prefix, suffix
            "render": $.fn.dataTable.render.number( ',', '.', 0, '', '' )
        }
        ],
        "ajax": {
            "url": "{% static 'schools/json/school_map_scores.json' %}"
                }
    });
</code>```

index.html

```<code><table id="test-scores" class="table table-striped responsive" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th class="table-district none">District</th>
            <th class="table-school none">School</th>
            <th class="table-subject none">Subject</th>
            <th class="table-proficiency none">Pct. proficient</th>
            <th class="table-testtakers none">No. of test takers</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>
</code>```

答:
Since you are already using the Responsive extension of DataTable, you can use the responsivePriority option to obtain the desired behavior, it will automatically calculate what columns should be hidden based on the space available for the table and the defined priority

Note: the priority is reversed, meaning a higher priority column will
  be hidden before a lower priority

$('#test-scores').dataTable({
  //...
  responsive: true,
  columns: [
    { data: "district", responsivePriority: 1 },
    { data: "school", responsivePriority: 2 },
    { data: "subject", responsivePriority: 3 },
    { data: "rate", responsivePriority: 4 },
    { data: "test_takers", responsivePriority: 5 },
  ],
  //...
});
```

<h1>Example</h1>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var table = $('#example').DataTable({
  responsive: true
});</code>```

<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css" rel="stylesheet" />

      Seq.
      Name
      Position
      Office
      Start date
      Salary

      Seq.
      Name
      Position
      Office
      Start date
      Salary

      2
      Tiger Nixon
      System Architect
      Edinburgh
      2011/04/25
      $320,800

      22
      Garrett Winters
      Accountant
      Tokyo
      2011/07/25
      $170,750

      6
      Ashton Cox
      Junior Technical Author
      San Francisco
      2009/01/12
      $86,000

      41
      Cedric Kelly
      Senior Javascript Developer
      Edinburgh
      2012/03/29
      $433,060

      55
      Airi Satou
      Accountant
      Tokyo
      2008/11/28
      $162,700

      21
      Brielle Williamson
      Integration Specialist
      New York
      2012/12/02
      $372,000

      46
      Herrod Chandler
      Sales Assistant
      San Francisco
      2012/08/06
      $137,500

      13
      Jena Gaines
      Office Manager
      London
      2008/12/19
      $90,560

      23
      Quinn Flynn
      Support Lead
      Edinburgh
      2013/03/03
      $342,000

      14
      Charde Marshall
      Regional Director
      San Francisco
      2008/10/16
      $470,600

      12
      Haley Kennedy
      Senior Marketing Designer
      London
      2012/12/18
      $313,500

      54
      Tatyana Fitzpatrick
      Regional Director
      London
      2010/03/17
      $385,750

      37
      Michael Silva
      Marketing Designer
      London
      2012/11/27
      $198,500

      32
      Paul Byrd
      Chief Financial Officer (CFO)
      New York
      2010/06/09
      $725,000

      35
      Gloria Little
      Systems Administrator
      New York
      2009/04/10
      $237,500

      48
      Bradley Greer
      Software Engineer
      London
      2012/10/13
      $132,000

      29
      Caesar Vance
      Pre-Sales Support
      New York
      2011/12/12
      $106,450

      56
      Doris Wilder
      Sales Assistant
      Sidney
      2010/09/20
      $85,600

```

ContentLicense: CC BY-SA 3.0

Body:
Problem

I have two DataTables — one is five columns and the other is four columns — and I'm looking for a way to hide columns at specific screen widths.

What I've tried

When I resize the browser, both tables automatically appear to drop down to a two-column chart at 480 pixels in width, but I need additional breakpoints in-between where I'm dropping additional columns since they don't fit inside viewport.

Adding a class of responsive to the table as seen in this example

I've tried using column control helper classes to remove columns at certain breakpoints, but even adding the class none did not hide a column

Adding classes to the  in the thead to take advantage of their responsive breakpoints

I've include responsive: true in my DataTables options

scripts.js

$('#test-scores').dataTable({
        initComplete: function () {
            this.api().columns([0,1,2]).every( function () {
                var column = this;
                var colIdx = column.index();
                // adjust label for dropdown according to index
                // TODO - colIdx is producing 0
                if (colIdx === 0) {
                    var label = 'districts';
                }
                else if (colIdx === 1) {
                    var label = 'schools';
                }
                else {
                    var label = 'subjects';
                }

                var select = $('.select--map-' + label)
                    .on( 'change', function () {
                        var val = $(this).val();
                        if ( val == '*' ) {
                            column
                                .search( '' )
                                .draw();
                        }
                        else {
                            val = $.fn.dataTable.util.escapeRegex( val );
                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        }
                    });

                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                });
            });
        },
        "pageLength": 25, // The number of entries per page
        "order": [0, 'asc'], // First column in ascending order, previous "3, desc"
        "responsive": true,
        "searching": true,
        "columns": [
        { "data": "district",
            "render": function (data, type, row, meta) {
                return '' + data + '';
            }
        },
        { "data": "school",
            "render": function (data, type, row, meta) {
                return '' + data + '';
            }
        },
        { "data": "subject" },
        {
            "data": "rate",
            // https://datatables.net/manual/data/renderers#Built-in-helpers
            // Render.number() parameters: thousands separator, decimal separator, decimal places, prefix, suffix
            "render": $.fn.dataTable.render.number( ',', '.', 1, '', '%' )
        },
        {
            "data": "test_takers",
            // Render.number() parameters: thousands separator, decimal separator, decimal places, prefix, suffix
            "render": $.fn.dataTable.render.number( ',', '.', 0, '', '' )
        }
        ],
        "ajax": {
            "url": "{% static 'schools/json/school_map_scores.json' %}"
                }
    });

index.html

            District
            School
            Subject
            Pct. proficient
            No. of test takers

Body:
Since you are already using the Responsive extension of DataTable, you can use the responsivePriority option to obtain the desired behavior, it will automatically calculate what columns should be hidden based on the space available for the table and the defined priority

Note: the priority is reversed, meaning a higher priority column will
  be hidden before a lower priority

$('#test-scores').dataTable({
  //...
  responsive: true,
  columns: [
    { data: "district", responsivePriority: 1 },
    { data: "school", responsivePriority: 2 },
    { data: "subject", responsivePriority: 3 },
    { data: "rate", responsivePriority: 4 },
    { data: "test_takers", responsivePriority: 5 },
  ],
  //...
});

Example

var table = $('#example').DataTable({
  responsive: true
});

<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
<table id="example" class="nowrap" width="100%">
  <thead>
    <tr>
      <th data-priority="0">Seq.</th> <!-- The first column should always be visible or the collapsed data will not be visible -->
      <th data-priority="1">Name</th>
      <th data-priority="3">Position</th>
      <th data-priority="4">Office</th>
      <th data-priority="5">Start date</th>
      <th data-priority="1">Salary</th>
    </tr>
  </thead>

  <tfoot>
    <tr>
      <th>Seq.</th>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </tfoot>

  <tbody>
    <tr>
      <td>2</td>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>2011/04/25</td>
      <td>$320,800</td>
    </tr>
    <tr>
      <td>22</td>
      <td>Garrett Winters</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>2011/07/25</td>
      <td>$170,750</td>
    </tr>
    <tr>
      <td>6</td>
      <td>Ashton Cox</td>
      <td>Junior Technical Author</td>
      <td>San Francisco</td>
      <td>2009/01/12</td>
      <td>$86,000</td>
    </tr>
    <tr>
      <td>41</td>
      <td>Cedric Kelly</td>
      <td>Senior Javascript Developer</td>
      <td>Edinburgh</td>
      <td>2012/03/29</td>
      <td>$433,060</td>
    </tr>
    <tr>
      <td>55</td>
      <td>Airi Satou</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>2008/11/28</td>
      <td>$162,700</td>
    </tr>
    <tr>
      <td>21</td>
      <td>Brielle Williamson</td>
      <td>Integration Specialist</td>
      <td>New York</td>
      <td>2012/12/02</td>
      <td>$372,000</td>
    </tr>
    <tr>
      <td>46</td>
      <td>Herrod Chandler</td>
      <td>Sales Assistant</td>
      <td>San Francisco</td>
      <td>2012/08/06</td>
      <td>$137,500</td>
    </tr>
    <tr>
      <td>13</td>
      <td>Jena Gaines</td>
      <td>Office Manager</td>
      <td>London</td>
      <td>2008/12/19</td>
      <td>$90,560</td>
    </tr>
    <tr>
      <td>23</td>
      <td>Quinn Flynn</td>
      <td>Support Lead</td>
      <td>Edinburgh</td>
      <td>2013/03/03</td>
      <td>$342,000</td>
    </tr>
    <tr>
      <td>14</td>
      <td>Charde Marshall</td>
      <td>Regional Director</td>
      <td>San Francisco</td>
      <td>2008/10/16</td>
      <td>$470,600</td>
    </tr>
    <tr>
      <td>12</td>
      <td>Haley Kennedy</td>
      <td>Senior Marketing Designer</td>
      <td>London</td>
      <td>2012/12/18</td>
      <td>$313,500</td>
    </tr>
    <tr>
      <td>54</td>
      <td>Tatyana Fitzpatrick</td>
      <td>Regional Director</td>
      <td>London</td>
      <td>2010/03/17</td>
      <td>$385,750</td>
    </tr>
    <tr>
      <td>37</td>
      <td>Michael Silva</td>
      <td>Marketing Designer</td>
      <td>London</td>
      <td>2012/11/27</td>
      <td>$198,500</td>
    </tr>
    <tr>
      <td>32</td>
      <td>Paul Byrd</td>
      <td>Chief Financial Officer (CFO)</td>
      <td>New York</td>
      <td>2010/06/09</td>
      <td>$725,000</td>
    </tr>
    <tr>
      <td>35</td>
      <td>Gloria Little</td>
      <td>Systems Administrator</td>
      <td>New York</td>
      <td>2009/04/10</td>
      <td>$237,500</td>
    </tr>
    <tr>
      <td>48</td>
      <td>Bradley Greer</td>
      <td>Software Engineer</td>
      <td>London</td>
      <td>2012/10/13</td>
      <td>$132,000</td>
    </tr>
    <tr>
      <td>29</td>
      <td>Caesar Vance</td>
      <td>Pre-Sales Support</td>
      <td>New York</td>
      <td>2011/12/12</td>
      <td>$106,450</td>
    </tr>
    <tr>
      <td>56</td>
      <td>Doris Wilder</td>
      <td>Sales Assistant</td>
      <td>Sidney</td>
      <td>2010/09/20</td>
      <td>$85,600</td>
    </tr>
  </tbody>
</table>


问:
HttpClient not sending basic authentication after redirect
My code is making an HTTP GET to a web service URL that requires basic authentication.

I've implemented this using an HttpClient with an HttpClientHandler that has the Credentials property defined.

This all works perfectly.. Except for one of my use-cases where I'm making the authenticated GET to:
http://somedomain.com which redirects to http://www.somedomain.com.

It seems that the HttpClientHandler clears the authentication header during the redirect. How can I prevent this? I want the credentials to be sent regardless of redirects.

This is my code:

```<code>// prepare the request
var request = new HttpRequestMessage(method, url);
using (var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) , PreAuthenticate = true })
using (var client = new HttpClient(handler))
{
    // send the request
    var response = await client.SendAsync(request);
</code>```

Note: this is a related question:
Keeping HTTP Basic Authentification alive while being redirected
But since I'm using different classes for making the request, there might be a better, more specific solution

答:
I used @DarrelMiller 's solution and it works. However, I did some improvements

I refactored the code so everything is in CopyRequest which now takes the response as an argument.

```<code>var newRequest = CopyRequest(response);

base.SendAsync(newRequest, cancellationToken)
    .ContinueWith(t2 => tcs.SetResult(t2.Result));
</code>```

This is the CopyRequest method with my improvements

Instead of creating a new StreamContent and set it to null for Redirect / Found / SeeOther the content is only set if necesarry.

RequestUri is only set if Location is set and takes into account that it may not be a relative uri.

Most important: I check for the new Uri and if the host does not match I do not copy the autorization header, to prevent leaking your credentials to an external host.

```<code>private static HttpRequestMessage CopyRequest(HttpResponseMessage response)
{
    var oldRequest = response.RequestMessage;

    var newRequest = new HttpRequestMessage(oldRequest.Method, oldRequest.RequestUri);

    if (response.Headers.Location != null)
    {
        if (response.Headers.Location.IsAbsoluteUri)
        {
            newRequest.RequestUri = response.Headers.Location;
        }
        else
        {
            newRequest.RequestUri = new Uri(newRequest.RequestUri, response.Headers.Location);
        }
    }

    foreach (var header in oldRequest.Headers)
    {
        if (header.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase) && !(oldRequest.RequestUri.Host.Equals(newRequest.RequestUri.Host)))
        {
            //do not leak Authorization Header to other hosts
            continue;
        }
        newRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
    }

    foreach (var property in oldRequest.Properties)
    {
        newRequest.Properties.Add(property);
    }

    if (response.StatusCode == HttpStatusCode.Redirect
        || response.StatusCode == HttpStatusCode.Found
        || response.StatusCode == HttpStatusCode.SeeOther)
    {
        newRequest.Content = null;
        newRequest.Method = HttpMethod.Get;
    }
    else if (oldRequest.Content != null)
    {
        newRequest.Content = new StreamContent(oldRequest.Content.ReadAsStreamAsync().Result);
    }

    return newRequest;
}
</code>```

Body:
My code is making an HTTP GET to a web service URL that requires basic authentication.

I've implemented this using an HttpClient with an HttpClientHandler that has the Credentials property defined.

This all works perfectly.. Except for one of my use-cases where I'm making the authenticated GET to:
http://somedomain.com which redirects to http://www.somedomain.com.

It seems that the HttpClientHandler clears the authentication header during the redirect. How can I prevent this? I want the credentials to be sent regardless of redirects.

This is my code:

// prepare the request
var request = new HttpRequestMessage(method, url);
using (var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) , PreAuthenticate = true })
using (var client = new HttpClient(handler))
{
    // send the request
    var response = await client.SendAsync(request);

Note: this is a related question:
Keeping HTTP Basic Authentification alive while being redirected
But since I'm using different classes for making the request, there might be a better, more specific solution

Body:
I used @DarrelMiller 's solution and it works. However, I did some improvements

I refactored the code so everything is in CopyRequest which now takes the response as an argument.

var newRequest = CopyRequest(response);

base.SendAsync(newRequest, cancellationToken)
    .ContinueWith(t2 => tcs.SetResult(t2.Result));

This is the CopyRequest method with my improvements

Instead of creating a new StreamContent and set it to null for Redirect / Found / SeeOther the content is only set if necesarry.

RequestUri is only set if Location is set and takes into account that it may not be a relative uri.

Most important: I check for the new Uri and if the host does not match I do not copy the autorization header, to prevent leaking your credentials to an external host.

private static HttpRequestMessage CopyRequest(HttpResponseMessage response)
{
    var oldRequest = response.RequestMessage;

    var newRequest = new HttpRequestMessage(oldRequest.Method, oldRequest.RequestUri);

    if (response.Headers.Location != null)
    {
        if (response.Headers.Location.IsAbsoluteUri)
        {
            newRequest.RequestUri = response.Headers.Location;
        }
        else
        {
            newRequest.RequestUri = new Uri(newRequest.RequestUri, response.Headers.Location);
        }
    }

    foreach (var header in oldRequest.Headers)
    {
        if (header.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase) && !(oldRequest.RequestUri.Host.Equals(newRequest.RequestUri.Host)))
        {
            //do not leak Authorization Header to other hosts
            continue;
        }
        newRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
    }

    foreach (var property in oldRequest.Properties)
    {
        newRequest.Properties.Add(property);
    }

    if (response.StatusCode == HttpStatusCode.Redirect
        || response.StatusCode == HttpStatusCode.Found
        || response.StatusCode == HttpStatusCode.SeeOther)
    {
        newRequest.Content = null;
        newRequest.Method = HttpMethod.Get;
    }
    else if (oldRequest.Content != null)
    {
        newRequest.Content = new StreamContent(oldRequest.Content.ReadAsStreamAsync().Result);
    }

    return newRequest;
}


问:
How to change style in specific row in Element UI Table
I'm using Element UI for my web app.
In my app, there is a table component, that is made by el-table component provided by Element UI.

And I would like to change style for the only specific row.

Firstly, please take a look at the screenshot and my code, later, I will explain what I would like to do specifically with them.

These are the screenshot of table in my app and my code.

```<code><template>
  <el-table
    :data="tableData"
    height="250"
    style="width: 100%">
    <el-table-column
      prop="date"
      label="Date"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="Name"
      width="180">
    </el-table-column>
    <el-table-column
      prop="address"
      label="Address">
    </el-table-column>
  </el-table>
</template>

<script>
  export default {
    data() {
      return {
        tableData: [{
          date: '2016-05-03',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-02',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-04',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-01',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-08',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-06',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-07',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }],
      }
    }
  }
</script>
</code>```

I would like to change background color blue for the row that's Data is 2016-05-03 and 2016-05-04 in the case above.

答:
You should have a look at this https://element.eleme.io/#/en-US/component/table#table-with-status. based on the property row-class-name you can apply some logic to add an class to the row.

```<code><el-table
    :data="tableData"
    style="width: 100%"
    :row-class-name="tableRowClassName">
</code>```

JS

```<code>methods: {
  tableRowClassName({row, rowIndex}) {
    if (row.date >= new Date()) {
      return 'warning-row';
    } else if (rowIndex === 3) {
      return 'success-row';
    }
    return '';
  }
},
</code>```

Of course you've to customize this to your needs

Body:
I'm using Element UI for my web app.
In my app, there is a table component, that is made by el-table component provided by Element UI.

And I would like to change style for the only specific row.

Firstly, please take a look at the screenshot and my code, later, I will explain what I would like to do specifically with them.

These are the screenshot of table in my app and my code.

<template>
  <el-table
    :data="tableData"
    height="250"
    style="width: 100%">
    <el-table-column
      prop="date"
      label="Date"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="Name"
      width="180">
    </el-table-column>
    <el-table-column
      prop="address"
      label="Address">
    </el-table-column>
  </el-table>
</template>

I would like to change background color blue for the row that's Data is 2016-05-03 and 2016-05-04 in the case above.

Body:
You should have a look at this https://element.eleme.io/#/en-US/component/table#table-with-status. based on the property row-class-name you can apply some logic to add an class to the row.

<el-table
    :data="tableData"
    style="width: 100%"
    :row-class-name="tableRowClassName">

JS

methods: {
  tableRowClassName({row, rowIndex}) {
    if (row.date >= new Date()) {
      return 'warning-row';
    } else if (rowIndex === 3) {
      return 'success-row';
    }
    return '';
  }
},

Of course you've to customize this to your needs


问:
Problem updating RCurl to source version 1.98-1.1 source in Windows 10
I am try to update the package RCurl from the version 1.95-4.12 to the source version 1.98-1.1 with R 3.6.2 (64 bits) in Windows 10, but I get an error:

```<code>** package 'RCurl' successfully unpacked and MD5 sums checked
ERROR: cannot remove earlier installation, is it in use?
* removing 'C:/Program Files/R/R-3.6.2/library/RCurl'
* restoring previous 'C:/Program Files/R/R-3.6.2/library/RCurl'
</code>```

Someone has any idea why this happens?
Thank you!

答: After proceeding as explained in the answer solving the question in https://community.rstudio.com/t/error-in-shlib-internal-args-c-14-standard-requested-but-cxx14-is-not-defined/16819 I could install RCurl 1.98-1.1 without problems

Body:
I am try to update the package RCurl from the version 1.95-4.12 to the source version 1.98-1.1 with R 3.6.2 (64 bits) in Windows 10, but I get an error:

** package 'RCurl' successfully unpacked and MD5 sums checked
ERROR: cannot remove earlier installation, is it in use?
* removing 'C:/Program Files/R/R-3.6.2/library/RCurl'
* restoring previous 'C:/Program Files/R/R-3.6.2/library/RCurl'

Someone has any idea why this happens?
Thank you!


问:
Instance is not defined despite being instantiated
I am trying to create a Box2D body, and I need to do it in a function, so I have this very simple function:

```<code>def create_car():
    my_Car = Car("Interesting parameters"))
    return my_Car
create_car()
</code>```

and then I have this main PyGame loop

```<code>running = True
while running:
    my_Car.steer()
</code>```

steer() as the definition suggests is a method written in class Car
But when I try to run the code this error is raised

```<code>my_Car() is not defined
</code>```

What am I doing wrong and how can I fix this?
Thank you very much

答:
From your code my_Car is local variable inside create_car function. You have to do something like my_Car = create_car().

```<code> my_Car = create_car()
 running = True
 while running:
     my_Car.steer()
</code>```

First googled link with the explanation: https://www.techbeamers.com/python-namespace-scope/

Body:
I am trying to create a Box2D body, and I need to do it in a function, so I have this very simple function:

def create_car():
    my_Car = Car("Interesting parameters"))
    return my_Car
create_car()

and then I have this main PyGame loop

running = True
while running:
    my_Car.steer()

steer() as the definition suggests is a method written in class Car
But when I try to run the code this error is raised

my_Car() is not defined

What am I doing wrong and how can I fix this?
Thank you very much

Body:
From your code my_Car is local variable inside create_car function. You have to do something like my_Car = create_car().

 my_Car = create_car()
 running = True
 while running:
     my_Car.steer()

First googled link with the explanation: https://www.techbeamers.com/python-namespace-scope/


问:
Express JS map /$metadata
In my UI5 application I am using ODataModel. The model is getting data from nodeJS server. First request of oDataModel is getting metadata, which looks like this:

```<code>http://localhost:3000/$metadata
</code>```

I am unable to map the path in my router.

I tried:

```<code>app.get('$metadata', (req, res) => {
});

app.get('/$metadata', (req, res) => {
});

app.get('/metadata', (req, res) => {
});
</code>```

It is working with

```<code>app.get('*metadata', (req, res) => {
});
</code>```

But I'd like to avoid that.
How should the mapping be defined?

答:
You need to escape the dollar sign between regular and square brackets ([ and ]). Example:

```<code>/odata/$metadata
</code>```

would be

```<code>app.get('/odata/([\$])metadata', (req, res)=>{
  //your code
})
</code>```

Using a dollar sign unescaped will be interpreted as the end of the string.

Source

Title: Express JS map /$metadata

Body:
In my UI5 application I am using ODataModel. The model is getting data from nodeJS server. First request of oDataModel is getting metadata, which looks like this:

http://localhost:3000/$metadata

I am unable to map the path in my router.

I tried:

app.get('$metadata', (req, res) => {
});

app.get('/$metadata', (req, res) => {
});

app.get('/metadata', (req, res) => {
});

It is working with

app.get('*metadata', (req, res) => {
});

But I'd like to avoid that.
How should the mapping be defined?

Body:
You need to escape the dollar sign between regular and square brackets ([ and ]). Example:

/odata/$metadata

would be

app.get('/odata/([\$])metadata', (req, res)=>{
  //your code
})

Using a dollar sign unescaped will be interpreted as the end of the string.

Source


问:
Laravel get value from 2 column with relationship one to one
I have 2 tables and have relationship one to one. Second table use a FK from first one, and I want to display a list with all values .

```<code>public function index(Request $request)
{
   $listOfPersons = new Person();
   $listOfRegisters = new  Register();

   $listOfRegisters->listOfPersons()->associate();
   return $listOfRegisters;
}
</code>```

In Register Model

```<code>public function people(){
    return $this->hasOne(Person::class);
}
</code>```

In Person Model

```<code>public function register(){
    return $this->hasOne(Register::class);
}
</code>```

答:
I think you have to use leftjoin. (not foreach and php loop)

Because:

The alternative of handling this inside your PHP code with a foreach
  loop is unattractive for several reasons. First, you would probably
  need to bring in all information from both tables, which is wasteful
  from both a memory and network usage point of view. Then, even after
  you have brought in the data, you would be relying on PHP to perform
  the join. PHP wasn't really designed for in house database operations,
  and cannot use something like an index to speed up the process.

So you can write your query like:

```<code>User::leftJoin('register', 'register.user_id', '=', 'id');
</code>```

However, I prefer to add a scope in my model for this situation

```<code><?php

class User extends Authenticatable
{
    public function scopeRegister($builder)
    {
       $query = $query->leftJoin('register', 'register.user_id', '=', 'id');
       return $query;

    }
</code>```

and in my controller

```<code>public function index(Request $request)
{
    $records = User::register()->get();
}
</code>```

Body:
I have 2 tables and have relationship one to one. Second table use a FK from first one, and I want to display a list with all values .

public function index(Request $request)
{
   $listOfPersons = new Person();
   $listOfRegisters = new  Register();

   $listOfRegisters->listOfPersons()->associate();
   return $listOfRegisters;
}

In Register Model

public function people(){
    return $this->hasOne(Person::class);
}

In Person Model

public function register(){
    return $this->hasOne(Register::class);
}

Body:
I think you have to use leftjoin. (not foreach and php loop)

Because:

The alternative of handling this inside your PHP code with a foreach
  loop is unattractive for several reasons. First, you would probably
  need to bring in all information from both tables, which is wasteful
  from both a memory and network usage point of view. Then, even after
  you have brought in the data, you would be relying on PHP to perform
  the join. PHP wasn't really designed for in house database operations,
  and cannot use something like an index to speed up the process.

So you can write your query like:

User::leftJoin('register', 'register.user_id', '=', 'id');

However, I prefer to add a scope in my model for this situation

<?php

class User extends Authenticatable
{
    public function scopeRegister($builder)
    {
       $query = $query->leftJoin('register', 'register.user_id', '=', 'id');
       return $query;

    }

and in my controller

public function index(Request $request)
{
    $records = User::register()->get();
}


问:
SignalR - get prompted for username and password on connect
I've got a self-hosted SignalR server which has IntegratedWindowsAuthentication turned on.
During the negotiate phase of the connection (from Chrome) the browser throws up a username/password prompt. If I click Sign In without filling in any details then it connects me to the hub as ANONYMOUS LOGON.
How can I configure things so that my Windows identity is seamlessly passed through so the hub knows who am I and that the browser doesn't prompt me?
This is a non-Core implementation of the SignalR server.
Thanks!</p>

答:
On your Main method try this:

connection.Credentials = CredentialCache.DefaultCredentials;
```

Read more about this here.

Body:
On your Main method try this:

connection.Credentials = CredentialCache.DefaultCredentials;

Read more about this here.


问:
Finding common words in Pandas dataframe
I have set of words

```<code>{'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada',...}
</code>```

I tried to find whether the word in the set contained in the bigramPMITable dataframe that I had

```<code>    bigram         PMI
0  (itu, adalah)   11.487338
1  (DNA, pada)     6.386371
2  (pada, oleh)    6.386371
3  (pada, basa)    1.105795
4  (yang, satu)    1.105795
5  (gula, yang)    1.044394
6  (yang, tidak)   1.044394
7  (pada, DNA)     0.986496
8  (unting, dalam) 0.931790
9  (DNA, tidak)    0.925095
10 (DNA, menjadi)  0.925095
11 (dan, sebagai)  0.905196
12 (pada, unting)  0.834493
</code>```

If so, then the expected output will be like this:

```<code>(itu, adalah) 11.487338
(DNA, pada) 6.386371
(pada, oleh) 6.386371
(pada, basa) 1.105795
(pada, DNA) 0.986496
(pada, unting) 0.834493
</code>```

They found the word 'adalah' and 'pada' at the bigramPMITable dataframe. How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

答:
First solution with sets and isdisjoint and filter by boolean indexing with inverted mask by ~:

```<code>df1 = df[~df.bigram.map(s.isdisjoint)]
</code>```

Or you can create helper DataFrame with isin:

```<code>df1 = df[pd.DataFrame(df['bigram'].tolist(), index=df.index).isin(s).any(axis=1)]
</code>```

```<code>print (df1)
            bigram        PMI
0    (itu, adalah)  11.487338
1      (DNA, pada)   6.386371
2     (pada, oleh)   6.386371
3     (pada, basa)   1.105795
7      (pada, DNA)   0.986496
12  (pada, unting)   0.834493
</code>```

Setup:

```<code>s = {'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada'}
</code>```

Performance:

```<code>df = pd.concat([df] * 10000, ignore_index=True)

In [41]: %timeit df[~df.bigram.map(s.isdisjoint)]
21 ms ± 359 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [42]: %timeit df[pd.DataFrame(df['bigram'].tolist(), index=df.index).isin(s).any(axis=1)]
41.6 ms ± 5.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

#yatu solutions
In [43]: %timeit df[df.bigram.map(s.intersection).ne(set())]
73.4 ms ± 4.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [44]: %timeit df[df.bigram.map(s.intersection).str.len().gt(0)]
127 ms ± 6.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Body:
I have set of words

{'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada',...}

I tried to find whether the word in the set contained in the bigramPMITable dataframe that I had

    bigram         PMI
0  (itu, adalah)   11.487338
1  (DNA, pada)     6.386371
2  (pada, oleh)    6.386371
3  (pada, basa)    1.105795
4  (yang, satu)    1.105795
5  (gula, yang)    1.044394
6  (yang, tidak)   1.044394
7  (pada, DNA)     0.986496
8  (unting, dalam) 0.931790
9  (DNA, tidak)    0.925095
10 (DNA, menjadi)  0.925095
11 (dan, sebagai)  0.905196
12 (pada, unting)  0.834493

If so, then the expected output will be like this:

(itu, adalah) 11.487338
(DNA, pada) 6.386371
(pada, oleh) 6.386371
(pada, basa) 1.105795
(pada, DNA) 0.986496
(pada, unting) 0.834493

They found the word 'adalah' and 'pada' at the bigramPMITable dataframe. How do I find?. Can anyone can help? Thanks. Any help is much appreciated.

Body:
First solution with sets and isdisjoint and filter by boolean indexing with inverted mask by ~:

df1 = df[~df.bigram.map(s.isdisjoint)]

Or you can create helper DataFrame with isin:

df1 = df[pd.DataFrame(df['bigram'].tolist(), index=df.index).isin(s).any(axis=1)]

print (df1)
            bigram        PMI
0    (itu, adalah)  11.487338
1      (DNA, pada)   6.386371
2     (pada, oleh)   6.386371
3     (pada, basa)   1.105795
7      (pada, DNA)   0.986496
12  (pada, unting)   0.834493

Setup:

s = {'adalah',
 'akan',
 'akhir',
 'algoritme',
 'alur',
 'antar',
 'antisense',
 'asam',
 'atas',
 'atau',
 'bahwa',
 'bakteriofag',
 'baru',
 'basa',
 'beranggota',
 'berdasarkan',
 'berikatan',
 'berupa',
 'pada'}

Performance:

df = pd.concat([df] * 10000, ignore_index=True)

In [41]: %timeit df[~df.bigram.map(s.isdisjoint)]
21 ms ± 359 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [42]: %timeit df[pd.DataFrame(df['bigram'].tolist(), index=df.index).isin(s).any(axis=1)]
41.6 ms ± 5.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

#yatu solutions
In [43]: %timeit df[df.bigram.map(s.intersection).ne(set())]
73.4 ms ± 4.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [44]: %timeit df[df.bigram.map(s.intersection).str.len().gt(0)]
127 ms ± 6.99 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


问:
How to change the location of an object key value pair in JavaScript
I've seen similar questions to this one but in different languages and I am struggling to create a JavaScript equivalent.

I am receiving an object and through a function I want to change the location of one (or more) of the properties. For example,

With the original object of

```<code>{
  individual: [
    {
      dob: '2017-01-01',
      isAuthorized: true,
    },
  ],
  business: [
    {
     taxId: '123',
    },
  ],
  product: {
    code: '123',
  },
}
</code>```

I would like to change the location of isAuthorized to be in the first object inside of the business array instead of individual.

Like so

```<code>{
  individual: [
    {
      dob: '2017-01-01',
    },
  ],
  business: [
    {
     taxId: '123',
     isAuthorized: true,
    },
  ],
  product: {
    code: '123',
  },
}
</code>```

So far I was trying to create an object that would contain the key name and location to change it to, e.g.

```<code>{
  isAuthorized: obj.business[0]
}
</code>```

And then loop over the original object as well as the object with the location values and then set the location of that key value pair.

Basically, in this function I want to see that if the original object contains a certain value (in this case isAuthorized) that it will take that key value pair and move it to the desired location.

答:
What you want can easily be achieved by using loadsh, here's a working snippet of how to restructure based on defined structure map. Extended this example to match what you want.

The example is doing a deep clone, if you are fine modifying the original object then skip that step to avoid the overhead.

// input data
const data = {
  individual: [
    {
      dob: '2017-01-01',
      isAuthorized: true,
    },
  ],
  business: [
    {
     taxId: '123',
    },
  ],
  product: {
    code: '123',
  },
};

// the structure change map
const keyMap = {
 'individual[0].isAuthorized': 'business[0].isAuthorized'
};

function parseData(data,keyMap) {
  const newData = _.cloneDeep(data);
  for( let [source,dest] of Object.entries(keyMap) ) {
    _.set(newData,dest,_.get(newData,source));
    _.unset(newData,source);
  }
  return newData;
}

console.log(parseData(data, keyMap));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script></code>```

Note: loadsh's set consider any numeric value as an array index so if you are using a numeric object key then use loadash.setWith. I recommend reading examples in doc for a better understanding.
https://lodash.com/docs/4.17.15#set

Body:
I've seen similar questions to this one but in different languages and I am struggling to create a JavaScript equivalent.

I am receiving an object and through a function I want to change the location of one (or more) of the properties. For example,

With the original object of

{
  individual: [
    {
      dob: '2017-01-01',
      isAuthorized: true,
    },
  ],
  business: [
    {
     taxId: '123',
    },
  ],
  product: {
    code: '123',
  },
}

I would like to change the location of isAuthorized to be in the first object inside of the business array instead of individual.

Like so

{
  individual: [
    {
      dob: '2017-01-01',
    },
  ],
  business: [
    {
     taxId: '123',
     isAuthorized: true,
    },
  ],
  product: {
    code: '123',
  },
}

So far I was trying to create an object that would contain the key name and location to change it to, e.g.

{
  isAuthorized: obj.business[0]
}

And then loop over the original object as well as the object with the location values and then set the location of that key value pair.

Basically, in this function I want to see that if the original object contains a certain value (in this case isAuthorized) that it will take that key value pair and move it to the desired location.

Body:
What you want can easily be achieved by using loadsh, here's a working snippet of how to restructure based on defined structure map. Extended this example to match what you want.

The example is doing a deep clone, if you are fine modifying the original object then skip that step to avoid the overhead.

// input data
const data = {
  individual: [
    {
      dob: '2017-01-01',
      isAuthorized: true,
    },
  ],
  business: [
    {
     taxId: '123',
    },
  ],
  product: {
    code: '123',
  },
};

// the structure change map
const keyMap = {
 'individual[0].isAuthorized': 'business[0].isAuthorized'
};

function parseData(data,keyMap) {
  const newData = _.cloneDeep(data);
  for( let [source,dest] of Object.entries(keyMap) ) {
    _.set(newData,dest,_.get(newData,source));
    _.unset(newData,source);
  }
  return newData;
}

console.log(parseData(data, keyMap));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Note: loadsh's set consider any numeric value as an array index so if you are using a numeric object key then use loadash.setWith. I recommend reading examples in doc for a better understanding.
https://lodash.com/docs/4.17.15#set


问:
android how to save captured image into phones gallery
I have two activities. In one activity, I have an ImageView and an camera button.
When I press camera button it goes to other activity where two buttons are there Capture and another is Select button. When I press capture it captures an image. But question is how to save this capture image to gallery. And after pressing the Select button the captured image should display on 1st activity's ImageView.
How can I do that.

答: See http://blog.kupriyanov.com/2010/02/solved-android-save-image-to-media.html to save to gallery, and see Get/pick an image from Android's built-in Gallery app programmatically for displaying the gallery image.</p>


问:
How works returning an object by reference
As i understand it is my reference SomeClass &ref=b; After that b = ref; Then c = b; SomeClass &ref2=c; then c=ref2 . But am I calling the operator = witch i have reloaded  when b=ref or c = ref2 ? Something like that a.operator=(ref) ? </p>

```<code>class SomeClass
{
public:
    SomeClass()
    {
        a = 5;
    }
    SomeClass(int l_a)
    {
        a = l_a;
    }

    SomeClass& operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
        return *this;
    }

    int a;
};

int main()
{
    SomeClass a;
    SomeClass b(1);
    SomeClass с(6);
    с = b = a;

}
</code>```

答: By overloading the operator = in SomeClass, you are doing copy-assignment lhs = rhs (Eg : c = b, c is lhs and b is rhs). Because it returns a reference matching SomeClass& operator= expected parameter type, you can chain multiple copy-assignments such as c = b = a.

Body:
As i understand it is my reference SomeClass &ref=b; After that b = ref; Then c = b; SomeClass &ref2=c; then c=ref2 . But am I calling the operator = witch i have reloaded  when b=ref or c = ref2 ? Something like that a.operator=(ref) ?

class SomeClass
{
public:
    SomeClass()
    {
        a = 5;
    }
    SomeClass(int l_a)
    {
        a = l_a;
    }

    SomeClass& operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
        return *this;
    }

    int a;
};

int main()
{
    SomeClass a;
    SomeClass b(1);
    SomeClass с(6);
    с = b = a;

}


问:
Solidity Function Signature - question about part of signature
I'm looking at examples of Smart Contracts written in Solidity and I found a constructor with the signature:

```<code>constructor() ERC721Full("<Token name>", "<Token Symbol>") public {

}
</code>```

what is the ERC721Full("", "") part of the signature? And how am I able to pass arguments into it?

答:
You can hardcode it, or modify your constructor to have more parameters.

Code example:

```<code>contract A {
    string public name;
    constructor(string tokenName) public {
        name = tokenName;
    }
}

// Hardcode
contract B is A {
    constructor() A("My tokenName") public {

    }
}

// Add params to constructor
contract C is A {
    constructor(string tokenName) A(tokenName) public {

    }
}
</code>```

Body:
I'm looking at examples of Smart Contracts written in Solidity and I found a constructor with the signature:

constructor() ERC721Full("<Token name>", "<Token Symbol>") public {

}

what is the ERC721Full("", "") part of the signature? And how am I able to pass arguments into it?

Body:
You can hardcode it, or modify your constructor to have more parameters.

Code example:

contract A {
    string public name;
    constructor(string tokenName) public {
        name = tokenName;
    }
}

// Hardcode
contract B is A {
    constructor() A("My tokenName") public {

    }
}

// Add params to constructor
contract C is A {
    constructor(string tokenName) A(tokenName) public {

    }
}


问:
Creating EKEvent with Unique Identifier(Not Editable)
I want to create an EKEvent to add it in device calendar. Is there any way to set a unique id (which a user can not edit in Calendar app) to this event so that I can identify or match it with my event.

I am creating event like this

```<code>let event = EKEvent.init(eventStore: eventStore)
event.title = "My location"
event.location = "Location Address"

// Setting Start - End Date
event.startDate = Date()
event.endDate = Date()

do {
    // Saving Events
    try eventStore.save(event, span: .thisEvent, commit: true)
    let message = "Schedule has been added to your device's calendar."
    showAlert(title: kFVApplicationTitle, message: message)
} catch {
    let message = "Schedule could not be added to your device's calendar."
    showAlert(title: kFVApplicationTitle, message: message)
}
</code>```

答: Creating a Category for EKEvent and adding additional properties in it solves my problem.</p>

Body:
I want to create an EKEvent to add it in device calendar. Is there any way to set a unique id (which a user can not edit in Calendar app) to this event so that I can identify or match it with my event.

I am creating event like this

let event = EKEvent.init(eventStore: eventStore)
event.title = "My location"
event.location = "Location Address"

// Setting Start - End Date
event.startDate = Date()
event.endDate = Date()

do {
    // Saving Events
    try eventStore.save(event, span: .thisEvent, commit: true)
    let message = "Schedule has been added to your device's calendar."
    showAlert(title: kFVApplicationTitle, message: message)
} catch {
    let message = "Schedule could not be added to your device's calendar."
    showAlert(title: kFVApplicationTitle, message: message)
}


问:
How to access class method within class but outside class methods or member functions?
Say, the code is

```<code>class A():
    @staticmethod
    getB():
        return ['B', 'BB']

    list_B = A.getB()
</code>```

How would I access function B() within the class that's outside of any function? In the code snippet, A isn't being recognized as a valid variable/class.

答:
You have 2 possibilities :

use getB.__func__()

use A.getB() in another function within the class

Try this :

```<code>class A():
    @staticmethod
    def getB():
        return ['B', 'BB']

    list_B = getB.__func__()
    print("list_B_1", list_B)

    def foobar(self):
        list_B_2 = A.getB()
        print("list_B_2", list_B_2)

a = A()
a.foobar()
</code>```

Body:
Say, the code is

class A():
    @staticmethod
    getB():
        return ['B', 'BB']

    list_B = A.getB()

How would I access function B() within the class that's outside of any function? In the code snippet, A isn't being recognized as a valid variable/class.

Body:
You have 2 possibilities :

use getB.__func__()

use A.getB() in another function within the class

Try this :

class A():
    @staticmethod
    def getB():
        return ['B', 'BB']

    list_B = getB.__func__()
    print("list_B_1", list_B)

    def foobar(self):
        list_B_2 = A.getB()
        print("list_B_2", list_B_2)

a = A()
a.foobar()


问:
Spring Boot how execute stored procedure multiple times?
I need to execute a procedure multiple times with the requestbody. For now, i am using for loop to do that, but it is not a good way. For example, when the one request is failed, catching that request is a problem. See for the example usage.

Implementation of stored procedure with for-loop;

```<code>**Controller**
public void runSP(
   @RequestBody List<IdNoteModel> idNotes
){
   getService().runSP(idNotes);
}

</code>```

```<code>**Service**
public void runSP(List<IdNoteModel> idNotes){
   for (IdNoteModel idNote : idNotes){
      getRepository().runSP(idNote);
   }
}

</code>```

```<code>**Repository**
@Query(nativeQuery = true, value = "EXECUTE PROCEDURE SP_RUN_ID_NOTE(:id, :note)")
void runSP(Long id, String note);
</code>```

Is there a better way to run stored procedures multiple times? or do you have an idea to catch the failed requests?

答: You can use @Retryable for this purpose and also you can catch exceptions and log requests with @Recover

Body:
I need to execute a procedure multiple times with the requestbody. For now, i am using for loop to do that, but it is not a good way. For example, when the one request is failed, catching that request is a problem. See for the example usage.

Implementation of stored procedure with for-loop;

**Controller**
public void runSP(
   @RequestBody List<IdNoteModel> idNotes
){
   getService().runSP(idNotes);
}

**Service**
public void runSP(List<IdNoteModel> idNotes){
   for (IdNoteModel idNote : idNotes){
      getRepository().runSP(idNote);
   }
}

**Repository**
@Query(nativeQuery = true, value = "EXECUTE PROCEDURE SP_RUN_ID_NOTE(:id, :note)")
void runSP(Long id, String note);

Is there a better way to run stored procedures multiple times? or do you have an idea to catch the failed requests?


问:
how I make object value as key of another object of array?
I'm getting data in form of array of objects like this...

```<code> let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
</code>```

I want this this array in this form please anyone help...

```<code> let arrayIWant = [
                    {
                      2:[{serviceId:2,name:'ahsan'},{serviceId:2,name:'john'}],
                      5:[{serviceId:5,name:'majeed'},{serviceId:5,name:'ziyad'}]
                    }
                  ]
</code>```

Please help

答:
You can use lodash library's _.keyBy method

_.keyBy(array, 'serviceId');

```<code>const _ = require('lodash')
let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];

result = _.keyBy(array, 'serviceId');

console.log([result])
</code>```

check this out. It should give you the desired result.

Body:
I'm getting data in form of array of objects like this...

 let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];

I want this this array in this form please anyone help...

 let arrayIWant = [
                    {
                      2:[{serviceId:2,name:'ahsan'},{serviceId:2,name:'john'}],
                      5:[{serviceId:5,name:'majeed'},{serviceId:5,name:'ziyad'}]
                    }
                  ]

Please help

Body:
You can use lodash library's _.keyBy method

_.keyBy(array, 'serviceId');

const _ = require('lodash')
let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
              {serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];

result = _.keyBy(array, 'serviceId');

console.log([result])

check this out. It should give you the desired result.


问:
filter array based on IDs available in another array
I have two arrays. The first array has only id objects:

```<code>arr1 = [
  { id: 1 },
  { id: 2 }
];
</code>```

and another array has list:

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];
</code>```

I need to write arr2 filter function which result as, based on ID available in first array

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];
</code>```

答:
const needle = [{
    id: 1
  },
  {
    id: 2
  }
];

const haystack = [{
  id: 1,
  name: 'kedar'
}, {
  id: 2,
  name: 'murli'
}, {
  id: 3,
  name: 'krishnadas'
}];

const filterByIdArray = (ids, arr) =>
  arr.filter(item =>
    ids.find(i =>
      i.id === item.id));

const result = filterByIdArray(needle, haystack);

console.log(result);```

Body:
I have two arrays. The first array has only id objects:

arr1 = [
  { id: 1 },
  { id: 2 }
];

and another array has list:

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];

I need to write arr2 filter function which result as, based on ID available in first array

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];


问:
how to check 2D array for duplicates
I am trying to remove duplicates from my 2D array but no success.

Here is what I am doing any idea where am making mistake?

function Remove_duplicates_from_2d_array(data_array) {
  if (data_array.length > 0) {
    let unique_index_counter = 0;
    // loop on target array
    for (var a = 0; a < data_array.length; a++) {
      var unique_array = data_array[unique_index_counter];

      if (a === unique_index_counter) {
        continue;
      }
      console.log('comparing index: ' + a + ' ( ' + data_array[a] + ' ) -- index: ' + a + ' ( ' + data_array[a] + ' )');
      if (data_array[a].sort().join(',') === unique_array.sort().join(',')) {
        console.log('match it index ' + a + ' - ' + unique_index_counter);
        // same arrays
        data_array.splice(a, 1);
        a = 0; // reset for loop as splice will rebuilt array
      }
      // a will be equal to data_array length incase there is no match found
      if (a === data_array.length) {
        unique_index_counter++;
      }
   if(unique_index_counter != data_array.length) {
  a = 0; // reset for loop because we have not checked all items
   }
    }

    return data_array;
  } else {
    return [];
  }
}

var a1 = [1, 2, 3];
b1 = [4, 4, 5];
c1 = [3, 4, 5];
d1 = [4, 4, 5];
var data_array = [];
data_array.push(a1);
data_array.push(b1);
data_array.push(c1);
data_array.push(d1);
console.log('original array.');
console.log(data_array);

var r = Remove_duplicates_from_2d_array(data_array);
console.log('unique array.');
console.log(r);  // [[1,2,3],[4,4,5],[3,4,5]]```

答:
Sets are nice and all, but you may benefit from seeing a simple for-based approach too:

var orig = [[1, 2, 3],
            [4, 4, 5],
            [3, 4, 5],
            [4, 4, 5]];

function undupe(arr){
  let ret=[];
  for(let candidate of arr){
    let found=false;
    for(let line of ret){
      let linematch=true;
      for(let i=0;i<line.length;i++){
        if(candidate[i]!==line[i]){
          linematch=false;               // if one element does not match, the lines are different
          break;                         // and the rest does not matter
        }
      }
      if(linematch){
        found=true;                      // if all elements matched, candidate is a duplicate
        break;                           // remaining lines do not matter
      }
    }
    if(!found){
      ret.push(candidate);               // candidate is unique, add it to the result
    }
  }
  return ret;
}

console.log(undupe(orig));```
</div>
</div>
</p>

<ul>
<li><code>candidate</code> loop gets all items in the input array</li>
<li><code>line</code> loop gets all items from <code>ret</code> array, so the items which are unique so far</li>
<li><code>i</code> loop compares the actual numbers (one from <code>candidate</code> with the corresponding one from <code>line</code>)</li>
<li>these loop things are slow at large data sizes, so it is a good idea to terminate them as soon as possible. Like when the first elements do not match in a pair of lines, they are different for sure, there is no need to check the rest.</li>
</ul>

<p>Of course it could be more structured, like</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var orig = [[1, 2, 3],
            [4, 4, 5],
            [3, 4, 5],
            [4, 4, 5]];

function linesmatch(line1,line2){
  for(let i=0;i<line1.length;i++)
    if(line1[i]!==line2[i])
      return false;
  return true;
}

function isdupe(arr,line){
  for(let l of arr)
    if(linesmatch(l,line))
      return true;
  return false;
}

function undupe(arr){
  let ret=[];
  for(let candidate of arr)
    if(!isdupe(ret,candidate))
      ret.push(candidate);
  return ret;
}

console.log(undupe(orig));</code>```

This would be the more textbook-like variant with small, readable functions built on top of each other.

Title: how to check 2D array for duplicates

Body:
Sets are nice and all, but you may benefit from seeing a simple for-based approach too:

var orig = [[1, 2, 3],
            [4, 4, 5],
            [3, 4, 5],
            [4, 4, 5]];

function undupe(arr){
  let ret=[];
  for(let candidate of arr){
    let found=false;
    for(let line of ret){
      let linematch=true;
      for(let i=0;i<line.length;i++){
        if(candidate[i]!==line[i]){
          linematch=false;               // if one element does not match, the lines are different
          break;                         // and the rest does not matter
        }
      }
      if(linematch){
        found=true;                      // if all elements matched, candidate is a duplicate
        break;                           // remaining lines do not matter
      }
    }
    if(!found){
      ret.push(candidate);               // candidate is unique, add it to the result
    }
  }
  return ret;
}

console.log(undupe(orig));

candidate loop gets all items in the input array

line loop gets all items from ret array, so the items which are unique so far

i loop compares the actual numbers (one from candidate with the corresponding one from line)

these loop things are slow at large data sizes, so it is a good idea to terminate them as soon as possible. Like when the first elements do not match in a pair of lines, they are different for sure, there is no need to check the rest.

Of course it could be more structured, like

var orig = [[1, 2, 3],
            [4, 4, 5],
            [3, 4, 5],
            [4, 4, 5]];

function linesmatch(line1,line2){
  for(let i=0;i<line1.length;i++)
    if(line1[i]!==line2[i])
      return false;
  return true;
}

function isdupe(arr,line){
  for(let l of arr)
    if(linesmatch(l,line))
      return true;
  return false;
}

function undupe(arr){
  let ret=[];
  for(let candidate of arr)
    if(!isdupe(ret,candidate))
      ret.push(candidate);
  return ret;
}

console.log(undupe(orig));

This would be the more textbook-like variant with small, readable functions built on top of each other.


问:
How to upload file using Ajax In Laravel I am getting error 419 (unknown status)
How to upload file using Ajax In Laravel I am getting error  419 (unknown status).
1.Javascript Code.
2.Controller Code.
3.Router Code.

Javascript Code

```<code>$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
      type: "POST",
      url:'/up',
      data:{"_token": $('meta[name="csrf-token"]').attr('content'),"formdata":formData},
      cache:false,
      contentType: false,
      processData: false,
      success:function(data){
          console.log("success");
         console.log(data);
      },
      error: function(data){
          console.log("error");
          console.log(data);
      }
  });
});
</code>```

Controller Code

```<code>public function Image(Request $request) {
  return $request->get('names');
}
</code>```

Router Code

```<code>Route::POST('/up', 'Controller@Image')
</code>```

答:
Try to add the CSRF-Token to your header like this:

```<code>$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
    type: "POST",
    url: '/up',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
      console.log("success");
      console.log(data);
    },
    error: function(data){
      console.log("error");
      console.log(data);
    }
  });
});
</code>```

Furthermore i would prefer to add the formData like this example above. So you can access it the way you did in your controller.

Body:
How to upload file using Ajax In Laravel I am getting error  419 (unknown status).
1.Javascript Code.
2.Controller Code.
3.Router Code.

Javascript Code

$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
      type: "POST",
      url:'/up',
      data:{"_token": $('meta[name="csrf-token"]').attr('content'),"formdata":formData},
      cache:false,
      contentType: false,
      processData: false,
      success:function(data){
          console.log("success");
         console.log(data);
      },
      error: function(data){
          console.log("error");
          console.log(data);
      }
  });
});

Controller Code

public function Image(Request $request) {
  return $request->get('names');
}

Router Code

Route::POST('/up', 'Controller@Image')

Body:
Try to add the CSRF-Token to your header like this:

$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
    type: "POST",
    url: '/up',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
      console.log("success");
      console.log(data);
    },
    error: function(data){
      console.log("error");
      console.log(data);
    }
  });
});

Furthermore i would prefer to add the formData like this example above. So you can access it the way you did in your controller.


问:
ggplot2 plot an angle between two lines
I would like to plot an angle between two lines using ggplot2, meaning something similar to the bold red line in the plot below. Is there an easy solution to this?

Data and code to make the plot without the red line:

```<code>library(tidyverse)

df <- tibble(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5))

ggplot(
  df, aes(x, y, group = line))+
  geom_path()
</code>```

答:
have a look at geom_curve, e.g. :

```<code>ggplot(  df, aes(x, y, group = line))+
  geom_path() +
  geom_curve(aes(x = 1.5, y = 2, xend = 2, yend = 1.5), curvature = -0.5, color = "red", size = 3)
</code>```

You will have to tweak it a bit to use it in a more robust, automatic way, for example:

```<code>red_curve <- df %>%
  group_by(line) %>%
  summarise( avg_x = mean(x),
             avg_y = mean(y))

ggplot(  df, aes(x, y, group = line))+
  geom_path() +
  geom_curve( data = red_curve, aes(x = avg_x[1], y = avg_y[1], xend = avg_x[2], yend = avg_y[2]), curvature = 0.5, color = "red", size = 3)
</code>```

Title: ggplot2 plot an angle between two lines

Body:
I would like to plot an angle between two lines using ggplot2, meaning something similar to the bold red line in the plot below. Is there an easy solution to this?

Data and code to make the plot without the red line:

library(tidyverse)

df <- tibble(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5))

ggplot(
  df, aes(x, y, group = line))+
  geom_path()

Body:
have a look at geom_curve, e.g. :

ggplot(  df, aes(x, y, group = line))+
  geom_path() +
  geom_curve(aes(x = 1.5, y = 2, xend = 2, yend = 1.5), curvature = -0.5, color = "red", size = 3)

You will have to tweak it a bit to use it in a more robust, automatic way, for example:

red_curve <- df %>%
  group_by(line) %>%
  summarise( avg_x = mean(x),
             avg_y = mean(y))

ggplot(  df, aes(x, y, group = line))+
  geom_path() +
  geom_curve( data = red_curve, aes(x = avg_x[1], y = avg_y[1], xend = avg_x[2], yend = avg_y[2]), curvature = 0.5, color = "red", size = 3)