问:
Get rid of Python private indicating prefixes
I have a custom class like this:

```<code>import json

class Config:
    def __init__(self):
        self._field1 = None
        self._field2 = None

    @property
    def field1(self):
        return self._field1

    @field1.setter
    def field1(self, value):
        self._field1 = value

    @property
    def field2(self):
        return self._field2

    @field2.setter
    def field2(self, value):
        self._field2 = value

    def validate(self):
        fields = [attribute for attribute in dir(self) if not attribute.startswith('__') and not callable(getattr(self, attribute))]
        for field in fields:
            if getattr(self, field) == None:
                raise AttributeError("You must set all fields, " + str(field) + " is not set")

    def toJSON(self):
        return json.dumps(self, default=lambda o: vars(o),
            sort_keys=True, indent=4)
</code>```

As you can see I try to JSON serialize my class, but it will always include the _ prefix in the json (since vars will return that)

Question 1: How can I get rid of it?

Question 2: I tried to delete the _ prefixes from the class but then I will get a "Error: maximum recursion depth exceeded while calling a Python object" when calling the constructor. Why is that happening?

Later on I might add validation logic to the setters.

Also if you have any suggestions how to refactor my code, please don't keep it to yourself.

答:
It might be overkill, but this works:

```<code>import json

class _ConfigSerializable:
    __dict__ = {}
    def __init__(self, config):
        for x, y in config.__dict__.items():
            while x.startswith("_"):
                x = x[1:]
            self.__dict__[x] = y

class Config:
    def __init__(self):
        self._field1 = None
        self._field2 = None

    @property
    def field1(self):
        return self._field1

    @field1.setter
    def field1(self, value):
        self._field1 = value

    @property
    def field2(self):
        return self._field2

    @field2.setter
    def field2(self, value):
        self._field2 = value

    def validate(self):
        fields = [attribute for attribute in dir(self) if not attribute.startswith('__') and not callable(getattr(self, attribute))]
        for field in fields:
            if getattr(self, field) == None:
                raise AttributeError("You must set all fields, " + str(field) + " is not set")

    def toJSON(self):
        s = _ConfigSerializable(self)
        return json.dumps(s, default=lambda o: vars(o),
            sort_keys=True, indent=4)

print(Config().toJSON())
</code>```

Output:

```<code>{
    "field1": null,
    "field2": null
}
</code>```

Basically, we create a new class which takes the attributes of the config instance, and creates a dictionary, removing the _ at the start of any attribute names.  We then serialise that class instance instead.

Body:
I have a custom class like this:

import json

class Config:
    def __init__(self):
        self._field1 = None
        self._field2 = None

    @property
    def field1(self):
        return self._field1

    @field1.setter
    def field1(self, value):
        self._field1 = value

    @property
    def field2(self):
        return self._field2

    @field2.setter
    def field2(self, value):
        self._field2 = value

    def validate(self):
        fields = [attribute for attribute in dir(self) if not attribute.startswith('__') and not callable(getattr(self, attribute))]
        for field in fields:
            if getattr(self, field) == None:
                raise AttributeError("You must set all fields, " + str(field) + " is not set")

    def toJSON(self):
        return json.dumps(self, default=lambda o: vars(o),
            sort_keys=True, indent=4)

As you can see I try to JSON serialize my class, but it will always include the _ prefix in the json (since vars will return that)

Question 1: How can I get rid of it?

Question 2: I tried to delete the _ prefixes from the class but then I will get a "Error: maximum recursion depth exceeded while calling a Python object" when calling the constructor. Why is that happening?

Later on I might add validation logic to the setters.

Also if you have any suggestions how to refactor my code, please don't keep it to yourself.

Body:
It might be overkill, but this works:

import json

class _ConfigSerializable:
    __dict__ = {}
    def __init__(self, config):
        for x, y in config.__dict__.items():
            while x.startswith("_"):
                x = x[1:]
            self.__dict__[x] = y

class Config:
    def __init__(self):
        self._field1 = None
        self._field2 = None

    @property
    def field1(self):
        return self._field1

    @field1.setter
    def field1(self, value):
        self._field1 = value

    @property
    def field2(self):
        return self._field2

    @field2.setter
    def field2(self, value):
        self._field2 = value

    def validate(self):
        fields = [attribute for attribute in dir(self) if not attribute.startswith('__') and not callable(getattr(self, attribute))]
        for field in fields:
            if getattr(self, field) == None:
                raise AttributeError("You must set all fields, " + str(field) + " is not set")

    def toJSON(self):
        s = _ConfigSerializable(self)
        return json.dumps(s, default=lambda o: vars(o),
            sort_keys=True, indent=4)

print(Config().toJSON())

Output:

{
    "field1": null,
    "field2": null
}

Basically, we create a new class which takes the attributes of the config instance, and creates a dictionary, removing the _ at the start of any attribute names.  We then serialise that class instance instead.


来源: stackexchange

问:
Disable past date in DatePickerDialog
I want to add code .getDatePicker().setMinDate(newDate.getTime() - (newDate.getTime()%(24*60*60*1000)))for disable the past date but suddenly .show() cannot be used.

Can someone teach me how to solve this kind of problem?

Code:

```<code>btnDate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectDate();
                        }
                    });

private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

    new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}
</code>```

答:
You can convert your method like this in order to set a minimum date</p>

```<code>private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

DatePickerDialog dialog= new DatePickerDialog(this,  dateSetListener,
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
dialog.getDatePicker().setMinDate(Calendar.getInstance().getTimeInMillis());
        dialog.show();
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Disable past date in DatePickerDialog

Body:
I want to add code .getDatePicker().setMinDate(newDate.getTime() - (newDate.getTime()%(24*60*60*1000)))for disable the past date but suddenly .show() cannot be used.

Can someone teach me how to solve this kind of problem?

Code:

btnDate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectDate();
                        }
                    });

private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

    new DatePickerDialog(TutorAddNewTimeSlotActivity.this,  dateSetListener,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}

Body:
You can convert your method like this in order to set a minimum date

private void selectDate()
{
    DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String selectedDate = dateFormat.format(calendar.getTime());

            btnDate.setText(selectedDate);
            btnDate.setTextColor(getResources().getColor(colorPrimaryDark));
        }
    };

    Date newDate = calendar.getTime();

DatePickerDialog dialog= new DatePickerDialog(this,  dateSetListener,
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
dialog.getDatePicker().setMinDate(Calendar.getInstance().getTimeInMillis());
        dialog.show();
}


问:
Persisting form data in Java Beans
When I send a data through a form, I use reusable component JavaBean to store the data and retrieve it using get property and pass that data where ever I need it in the application.

But if I restart the web server, whatever data I had passed to that JavaBean will be lost and again I need pass the data to that Java Bean. Is there anyway to pass the data to the JavaBean and store (set) it permanently, so that i can access it even in the case of server restart?

答: After you restart the server , the session of that client will be killed automatically, so you cannot hold the data in bean.</p>

ContentLicense: CC BY-SA 3.0

Title: Persisting form data in Java Beans


问:
How to Insert & Update Multiple Record in Django
I want to know how to deal with this task.
here are the details:
this is product_feature model

```<code>class Feature(models.Model):
    has_value_choice = [
        ('y', 'Yes'),
        ('n', 'No'),
    ]
    feature_id = models.AutoField(primary_key=True)
    feature_name = models.CharField(max_length=255, null = False)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    feature_has_value = models.CharField(choices=has_value_choice, max_length = 1, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    product_feature_value = models.CharField(max_length=255, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

</code>```

here, I'm passing features data to the template to save features of the specific product in the product_feature model.

```<code>                  <form>
                        <table class="table table-bordered">
                            <thead>
                              <tr>
                                <th>Features</th>
                                <th>Value</th>
                              </tr>
                            </thead>
                            <tbody>
                                {% for data in features_data %}
                                    <tr>
                                        {% if data.feature_has_value != 'n' %}
                                            <td>{{ data.feature_name }}</td>
                                            <td><input type="text" name="{{ data.feature_name }}" id="{{ data.feature_name }}" placeholder="Enter {{ data.feature_name }}" class="form-control" required/></td>
                                        {% else %}
                                            <td>{{ data.feature_name }}</td>
                                            <td>
                                                <select id="{{ data.feature_name }}" name="{{ data.feature_name }}" class="form-control" required>
                                                    <option selected id="select" value="yes">Yes</option>
                                                    <option value="no">No</option>
                                                </select>
                                            </td>
                                        {% endif %}
                                    </tr>
                                {% endfor %}
                            </tbody>
                          </table>
                       </form>
</code>```

Now, the thing is how to insert this form data to the product features table( product_feature model at the starting of the question).

I want to insert multiple records in the product features a table with each record have it's feature_id, product_id & product_feature value.

I'm really confused about how to do this I'm new in Django development.

答:
You can use a django admin which defaults adds to your url
In admin.py register models , you can use default ui

```<code>from django.contrib import admin

 # Register your models here.
 from medicine.models import Address,Shop

 class ShopAdmin(admin.ModelAdmin):
  list_display = ('name', 'phone', 'address')

 class AddressAdmin(admin.ModelAdmin):
  list_display = ('line_1', 'line_2', 'city', 'state', 'lat', 'lng')

 admin.site.register(Shop, ShopAdmin)
 admin.site.register(Address, AddressAdmin)
</code>```

./manage.py make migrations
./manage.py createsuperuser
and your app in insatlled apps

For cutsomized ui you need to have a another form that takes data and give it to backed using a request.body as json

The best practice is using django rest framework where you can define your end points and use seriizarers which gives the way to communicate in json/xml any  supportable format

For inserting of data take everything as query param or payload body

For just creating objects to your model use this

```<code>obj = MyModel.objects.create(value)
</code>```

Body:
I want to know how to deal with this task.
here are the details:
this is product_feature model

class Feature(models.Model):
    has_value_choice = [
        ('y', 'Yes'),
        ('n', 'No'),
    ]
    feature_id = models.AutoField(primary_key=True)
    feature_name = models.CharField(max_length=255, null = False)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    feature_has_value = models.CharField(choices=has_value_choice, max_length = 1, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    product_feature_value = models.CharField(max_length=255, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

here, I'm passing features data to the template to save features of the specific product in the product_feature model.

                  <form>

                                Features
                                Value

                                {% for data in features_data %}

                                        {% if data.feature_has_value != 'n' %}
                                            {{ data.feature_name }}
                                            <input type="text" name="{{ data.feature_name }}" id="{{ data.feature_name }}" placeholder="Enter {{ data.feature_name }}" class="form-control" required/>
                                        {% else %}
                                            {{ data.feature_name }}

                                                <select id="{{ data.feature_name }}" name="{{ data.feature_name }}" class="form-control" required>
                                                    <option selected id="select" value="yes">Yes</option>
                                                    <option value="no">No</option>
                                                </select>

                                        {% endif %}

                                {% endfor %}

                       </form>

Now, the thing is how to insert this form data to the product features table( product_feature model at the starting of the question).

I want to insert multiple records in the product features a table with each record have it's feature_id, product_id & product_feature value.

I'm really confused about how to do this I'm new in Django development.

Body:
You can use a django admin which defaults adds to your url
In admin.py register models , you can use default ui

from django.contrib import admin

 # Register your models here.
 from medicine.models import Address,Shop

 class ShopAdmin(admin.ModelAdmin):
  list_display = ('name', 'phone', 'address')

 class AddressAdmin(admin.ModelAdmin):
  list_display = ('line_1', 'line_2', 'city', 'state', 'lat', 'lng')

 admin.site.register(Shop, ShopAdmin)
 admin.site.register(Address, AddressAdmin)

./manage.py make migrations
./manage.py createsuperuser
and your app in insatlled apps

For cutsomized ui you need to have a another form that takes data and give it to backed using a request.body as json

The best practice is using django rest framework where you can define your end points and use seriizarers which gives the way to communicate in json/xml any  supportable format

For inserting of data take everything as query param or payload body

For just creating objects to your model use this

obj = MyModel.objects.create(value)


问:
Video capture doesn't work with all supported caps
I am using Python 3.6 on Ubuntu 18.04 on an NVIDIA Jetson TX2. All software is up to date. The Linux kernel is 4.9.140-tegra. GStreamer is version 1.14.1.

I have a UVC Capable webcam that shows the following capabilities and I need to stream with the Y16 ( GRAY16_LE ) format:

```<code>root@nvidia:/tmp# v4l2-ctl --list-formats-ext -d /dev/video1
ioctl: VIDIOC_ENUM_FMT
        Index       : 0
        Type        : Video Capture
        Pixel Format: 'UYVY'
        Name        : UYVY 4:2:2
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 1
        Type        : Video Capture
        Pixel Format: 'Y16 '
        Name        : 16-bit Greyscale
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)
                Size: Discrete 160x122
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 2
        Type        : Video Capture
        Pixel Format: 'GREY'
        Name        : 8-bit Greyscale
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 3
        Type        : Video Capture
        Pixel Format: 'RGBP'
        Name        : 16-bit RGB 5-6-5
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 4
        Type        : Video Capture
        Pixel Format: 'BGR3'
        Name        : 24-bit BGR 8-8-8
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)
</code>```

With GStreamer from the command line, I can successfully get the device into the PLAYING state with gst-launch in the format I want:

```<code>root@nvidia:/tmp# gst-launch-1.0 v4l2src device=/dev/video1 ! video/x-raw,width=160,height=122,format='GRAY16_LE',framerate=9/1 ! fakesink
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
</code>```

I am trying to open the device with the GRAY16_LE format with Python OpenCV:

```<code>import cv2
cap = cv2.VideoCapture("v4l2src device=/dev/video1 ! video/x-raw, format=(string)GRAY16_LE, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1 ! appsink")
ret, frame = cap.read()
</code>```

During elevated GStreamer debug, the capabilities are probed and printed below:

```<code>0:00:00.260383826 15768      0x49a9850 INFO                    v4l2 gstv4l2object.c:4136:gst_v4l2_object_probe_caps:<v4l2src0:src> probed caps: video/x-raw, format=(string)UYVY, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)BGR, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)RGB16, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)GRAY8, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)GRAY16_LE, width=(int)160, height=(int)122, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)GRAY16_LE, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1
</code>```

With GStreamer debug on, the errors are shown as below:

```<code>0:00:00.260385266 15768      0x4744c00 INFO              GST_STATES gstelement.c:2579:_priv_gst_element_state_changed:<v4l2src0> notifying about state-changed PAUSED to PLAYING (VOID_PENDING pending)
0:00:00.260529393 15768      0x49a9850 WARN                 basesrc gstbasesrc.c:3055:gst_base_src_loop:<v4l2src0> error: Internal data stream error.
0:00:00.260531697 15768      0x4744c00 INFO              GST_STATES gstbin.c:2952:gst_bin_change_state_func:<pipeline0> child 'v4l2src0' changed state to 4(PLAYING) successfully
0:00:00.260589009 15768      0x49a9850 WARN                 basesrc gstbasesrc.c:3055:gst_base_src_loop:<v4l2src0> error: streaming stopped, reason not-negotiated (-4)
0:00:00.260660881 15768      0x4744c00 INFO              GST_STATES gstbin.c:2087:gst_bin_get_state_func:<pipeline0> getting state
0:00:00.260748913 15768      0x49a9850 INFO        GST_ERROR_SYSTEM gstelement.c:2145:gst_element_message_full_with_details:<v4l2src0> posting message: Internal data stream error.
0:00:00.260762833 15768      0x4744c00 INFO              GST_STATES gstelement.c:2392:gst_element_get_state_func:<pipeline0> waiting for element to commit state
0:00:00.260909520 15768      0x49a9850 INFO        GST_ERROR_SYSTEM gstelement.c:2172:gst_element_message_full_with_details:<v4l2src0> posted error message: Internal data stream error.
0:00:00.261064816 15768      0x4744c00 INFO              GST_STATES gstbin.c:2504:gst_bin_element_set_state:<appsink0> current PAUSED pending VOID_PENDING, desired next READY
0:00:00.261189072 15768      0x49a9850 INFO                    task gsttask.c:316:gst_task_func:<v4l2src0:src> Task going to paused
</code>```

I am using the identical format that the probe returns but the error indicates "format negotiation error". How can I fix this so my frames appear in Python?

答:
I had a similar objective to yours and I was able de capture the Y16 raw frames using OpenCV without patching the .cpp

```<code>capture = cv2.VideoCapture(0)
capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"Y16 "))
capture.set(cv2.CAP_PROP_CONVERT_RGB, False)
</code>```

The frames I get are directly in uint16 format :)

Body:
I am using Python 3.6 on Ubuntu 18.04 on an NVIDIA Jetson TX2. All software is up to date. The Linux kernel is 4.9.140-tegra. GStreamer is version 1.14.1.

I have a UVC Capable webcam that shows the following capabilities and I need to stream with the Y16 ( GRAY16_LE ) format:

root@nvidia:/tmp# v4l2-ctl --list-formats-ext -d /dev/video1
ioctl: VIDIOC_ENUM_FMT
        Index       : 0
        Type        : Video Capture
        Pixel Format: 'UYVY'
        Name        : UYVY 4:2:2
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 1
        Type        : Video Capture
        Pixel Format: 'Y16 '
        Name        : 16-bit Greyscale
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)
                Size: Discrete 160x122
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 2
        Type        : Video Capture
        Pixel Format: 'GREY'
        Name        : 8-bit Greyscale
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 3
        Type        : Video Capture
        Pixel Format: 'RGBP'
        Name        : 16-bit RGB 5-6-5
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)

        Index       : 4
        Type        : Video Capture
        Pixel Format: 'BGR3'
        Name        : 24-bit BGR 8-8-8
                Size: Discrete 160x120
                        Interval: Discrete 0.111s (9.000 fps)

With GStreamer from the command line, I can successfully get the device into the PLAYING state with gst-launch in the format I want:

root@nvidia:/tmp# gst-launch-1.0 v4l2src device=/dev/video1 ! video/x-raw,width=160,height=122,format='GRAY16_LE',framerate=9/1 ! fakesink
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock

I am trying to open the device with the GRAY16_LE format with Python OpenCV:

import cv2
cap = cv2.VideoCapture("v4l2src device=/dev/video1 ! video/x-raw, format=(string)GRAY16_LE, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1 ! appsink")
ret, frame = cap.read()

During elevated GStreamer debug, the capabilities are probed and printed below:

0:00:00.260383826 15768      0x49a9850 INFO                    v4l2 gstv4l2object.c:4136:gst_v4l2_object_probe_caps:<v4l2src0:src> probed caps: video/x-raw, format=(string)UYVY, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)BGR, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)RGB16, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)GRAY8, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)GRAY16_LE, width=(int)160, height=(int)122, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1; video/x-raw, format=(string)GRAY16_LE, width=(int)160, height=(int)120, pixel-aspect-ratio=(fraction)1/1, framerate=(fraction)9/1

With GStreamer debug on, the errors are shown as below:

0:00:00.260385266 15768      0x4744c00 INFO              GST_STATES gstelement.c:2579:_priv_gst_element_state_changed:<v4l2src0> notifying about state-changed PAUSED to PLAYING (VOID_PENDING pending)
0:00:00.260529393 15768      0x49a9850 WARN                 basesrc gstbasesrc.c:3055:gst_base_src_loop:<v4l2src0> error: Internal data stream error.
0:00:00.260531697 15768      0x4744c00 INFO              GST_STATES gstbin.c:2952:gst_bin_change_state_func:<pipeline0> child 'v4l2src0' changed state to 4(PLAYING) successfully
0:00:00.260589009 15768      0x49a9850 WARN                 basesrc gstbasesrc.c:3055:gst_base_src_loop:<v4l2src0> error: streaming stopped, reason not-negotiated (-4)
0:00:00.260660881 15768      0x4744c00 INFO              GST_STATES gstbin.c:2087:gst_bin_get_state_func:<pipeline0> getting state
0:00:00.260748913 15768      0x49a9850 INFO        GST_ERROR_SYSTEM gstelement.c:2145:gst_element_message_full_with_details:<v4l2src0> posting message: Internal data stream error.
0:00:00.260762833 15768      0x4744c00 INFO              GST_STATES gstelement.c:2392:gst_element_get_state_func:<pipeline0> waiting for element to commit state
0:00:00.260909520 15768      0x49a9850 INFO        GST_ERROR_SYSTEM gstelement.c:2172:gst_element_message_full_with_details:<v4l2src0> posted error message: Internal data stream error.
0:00:00.261064816 15768      0x4744c00 INFO              GST_STATES gstbin.c:2504:gst_bin_element_set_state:<appsink0> current PAUSED pending VOID_PENDING, desired next READY
0:00:00.261189072 15768      0x49a9850 INFO                    task gsttask.c:316:gst_task_func:<v4l2src0:src> Task going to paused

I am using the identical format that the probe returns but the error indicates "format negotiation error". How can I fix this so my frames appear in Python?

Body:
I had a similar objective to yours and I was able de capture the Y16 raw frames using OpenCV without patching the .cpp

capture = cv2.VideoCapture(0)
capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"Y16 "))
capture.set(cv2.CAP_PROP_CONVERT_RGB, False)

The frames I get are directly in uint16 format :)


问:
Save large pandas dataframe to excel
I'm generating a large dataframe (1.5 GB when saved in CSV format) and need to store it an worksheet of an Excel file along with a second (much smaller) dataframe which is saved in a separate worksheet.

```<code>print('Reading temporaty files for variable {}:'.format(Var))
print(' Reading stations')
s=pd.read_csv(StatFile,sep=':',dtype={'ID': 'str'},encoding='utf-8')
print(' Reading data')
d=pd.read_csv(DataFile,sep=':',dtype='str',encoding='utf-8').transpose()
d.columns = d.iloc[0]
d=d[1:].astype('float')
d.reindex_axis(sorted(d.columns), axis=1)
print('Writing out Excel file for variable {}'.format(Var))
writer = pd.ExcelWriter(Path + Var + '.xlsx', engine='xlsxwriter')
d.to_excel(writer, sheet_name='Data')
OutStatCol=['ID','Name','Longitude','Latitude','GRS','OriginalVariable','VariableUnits','URL','JsonNode']
s.to_excel(writer, columns=OutStatCol, index=False, sheet_name='Stations')
writer.save()
</code>```

My code works fine for smaller dataframes, but with the large ones I get the following error:

```<code>Traceback (most recent call last):
  File "./Test2.py", line 29, in <module>
    writer.save()
  File "/home/user/miniconda2/lib/python2.7/site-packages/pandas/io/excel.py", line 1413, in save
    return self.book.close()
  File "/home/user/miniconda2/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 297, in close
    self._store_workbook()
  File "/home/user/miniconda2/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 624, in _store_workbook
    xlsx_file.write(os_filename, xml_filename)
  File "/home/user/miniconda2/lib/python2.7/zipfile.py", line 1148, in write
    self._writecheck(zinfo)
  File "/home/user/miniconda2/lib/python2.7/zipfile.py", line 1114, in _writecheck
    " would require ZIP64 extensions")
zipfile.LargeZipFile: Filesize would require ZIP64 extensions
</code>```

Is there any way I can specify something like allowZip64=True in the ExcelWriter declaration or in the to_excel() method?

Thanks!

答: I just added engine='xlsxwriter' to the function .to_excel() and it's fixed the problem.

Title: Save large pandas dataframe to excel

Body:
I'm generating a large dataframe (1.5 GB when saved in CSV format) and need to store it an worksheet of an Excel file along with a second (much smaller) dataframe which is saved in a separate worksheet.

print('Reading temporaty files for variable {}:'.format(Var))
print(' Reading stations')
s=pd.read_csv(StatFile,sep=':',dtype={'ID': 'str'},encoding='utf-8')
print(' Reading data')
d=pd.read_csv(DataFile,sep=':',dtype='str',encoding='utf-8').transpose()
d.columns = d.iloc[0]
d=d[1:].astype('float')
d.reindex_axis(sorted(d.columns), axis=1)
print('Writing out Excel file for variable {}'.format(Var))
writer = pd.ExcelWriter(Path + Var + '.xlsx', engine='xlsxwriter')
d.to_excel(writer, sheet_name='Data')
OutStatCol=['ID','Name','Longitude','Latitude','GRS','OriginalVariable','VariableUnits','URL','JsonNode']
s.to_excel(writer, columns=OutStatCol, index=False, sheet_name='Stations')
writer.save()

My code works fine for smaller dataframes, but with the large ones I get the following error:

Traceback (most recent call last):
  File "./Test2.py", line 29, in <module>
    writer.save()
  File "/home/user/miniconda2/lib/python2.7/site-packages/pandas/io/excel.py", line 1413, in save
    return self.book.close()
  File "/home/user/miniconda2/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 297, in close
    self._store_workbook()
  File "/home/user/miniconda2/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 624, in _store_workbook
    xlsx_file.write(os_filename, xml_filename)
  File "/home/user/miniconda2/lib/python2.7/zipfile.py", line 1148, in write
    self._writecheck(zinfo)
  File "/home/user/miniconda2/lib/python2.7/zipfile.py", line 1114, in _writecheck
    " would require ZIP64 extensions")
zipfile.LargeZipFile: Filesize would require ZIP64 extensions

Is there any way I can specify something like allowZip64=True in the ExcelWriter declaration or in the to_excel() method?

Thanks!


问:
Docker composer parsing error for docker-compose.yml, at line 1, and column 1
I'm trying to setup selenoid and I'm having trouble with dockercomposer, it throws exception as below:

yaml.parser.ParserError: while parsing a flow mapping in "./docker-compose.yml", line 1, column 1 expected ',' or '}', but got '{' in "./docker-compose.yml", line 2, column 1

```<code>when I try to run docker command "$ sudo docker-compose up -d"

I'm in the terminal with same folder where docker-compose.yml present and content is as below,

version: '3'
services:
 selenoid:
   network_mode: bridge
   image: aerokube/selenoid
   volumes:
     - "/docker:/etc/selenoid"
     - "/var/run/docker.sock:/var/run/docker.sock"
     - "/docker/video:/opt/selenoid/video"
   environment:
     - OVERRIDE_VIDEO_OUTPUT_DIR=/opt/selenium/video
     - TZ=Europe/Amsterdam
   command: ["-conf", "/etc/selenoid/browsers.json", "-video-output-dir", "/opt/selenoid/video"]
   ports:
     - "4444:4444"

I've also tried many online yml parsers and there is nothing wrong with yml file. Any help would be much appreciated.

Thanks
</code>```

答: Sorry being late to answer my own post, there was nothing wrong with YML file, I should have created/edited it using programming editors such as IntelliJ, but I was editing and saving it using EditText. All worked fine after editing them and saving using IntelliJ in mac.</p>

Body:
I'm trying to setup selenoid and I'm having trouble with dockercomposer, it throws exception as below:

yaml.parser.ParserError: while parsing a flow mapping in "./docker-compose.yml", line 1, column 1 expected ',' or '}', but got '{' in "./docker-compose.yml", line 2, column 1

when I try to run docker command "$ sudo docker-compose up -d"

I'm in the terminal with same folder where docker-compose.yml present and content is as below,

version: '3'
services:
 selenoid:
   network_mode: bridge
   image: aerokube/selenoid
   volumes:
     - "/docker:/etc/selenoid"
     - "/var/run/docker.sock:/var/run/docker.sock"
     - "/docker/video:/opt/selenoid/video"
   environment:
     - OVERRIDE_VIDEO_OUTPUT_DIR=/opt/selenium/video
     - TZ=Europe/Amsterdam
   command: ["-conf", "/etc/selenoid/browsers.json", "-video-output-dir", "/opt/selenoid/video"]
   ports:
     - "4444:4444"

I've also tried many online yml parsers and there is nothing wrong with yml file. Any help would be much appreciated.

Thanks


问:
Accessing private instances of Github and Gitlab through their respective Python APIs
Can I access private instances of Github and Gitlab through API wrappers in python such as pygithub and python-gitlab. For example, if I want to access my company's private server of Github and Gitlab, is it possible? Any help on the matter would be really appreciated!</p>

答:
When using python-gitlab, use:

```<code>import gitlab
gl = gitlab.Gitlab('http://your_gitlab_instance_url.com', private_token='token')
</code>```

Mentioning the url of the private instance does the job. The method may fail though, if there is some other secondary forms of security authenticators.

When using pygithub, use:

```<code>from github import Github
g = Github(base_url="https://{hostname}/api/v3", login_or_token="access_token")
</code>```

Works fine with the Rest API for github api v3

Body:
When using python-gitlab, use:

import gitlab
gl = gitlab.Gitlab('http://your_gitlab_instance_url.com', private_token='token')

Mentioning the url of the private instance does the job. The method may fail though, if there is some other secondary forms of security authenticators.

When using pygithub, use:

from github import Github
g = Github(base_url="https://{hostname}/api/v3", login_or_token="access_token")

Works fine with the Rest API for github api v3


答:
Java beans stays in the memory and particularly within some scope (i.e. request, session, application , etc..)

Now if you restart the app server it is definitely going to kill all scope and so the result.

if you want to persist data then use DBMS

Title: Persisting form data in Java Beans

Body:
When I send a data through a form, I use reusable component JavaBean to store the data and retrieve it using get property and pass that data where ever I need it in the application.

But if I restart the web server, whatever data I had passed to that JavaBean will be lost and again I need pass the data to that Java Bean. Is there anyway to pass the data to the JavaBean and store (set) it permanently, so that i can access it even in the case of server restart?


问:
Can I change all my http:// links to just //?
Dave Ward says,

It’s not exactly light reading, but section 4.2 of RFC 3986 provides for fully qualified URLs that omit protocol (the HTTP or HTTPS) altogether. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead.

Put simply, these “protocol-less” URLs allow a reference like this to work in every browser you’ll try it in:

//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js

It looks strange at first, but this “protocol-less” URL is the best way to reference third party content that’s available via both HTTP and HTTPS.

This would certainly solve a bunch of mixed-content errors we're seeing on HTTP pages -- assuming that our assets are available via both HTTP and HTTPS.

Is this completely cross-browser compatible? Are there any other caveats?

答:
If you would like to make sure all requests are upgraded to secure protocol then there is simple option to use Content Security Policy header upgrade-insecure-requests

```<code>Content-Security-Policy: upgrade-insecure-requests;
</code>```

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Body:
If you would like to make sure all requests are upgraded to secure protocol then there is simple option to use Content Security Policy header upgrade-insecure-requests

Content-Security-Policy: upgrade-insecure-requests;

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests


问:
Using Docker SDK for loading image from a file
I use the ImageLoad function for loading an image:

```<code>    file, err := os.OpenFile(fileName, os.O_RDONLY, 0666)
    if err != nil {
        log.Debugf("Error loading image %s, %s", fileName, err)
    } else {
        defer file.Close()
        resp, err := client.api.ImageLoad(ctx, file, false)
        if err != nil {
            log.Debugf("Error loading image %s, %s", fileName, err)
        }
        if resp.Body == nil {
            err = errors.New("Error loading image")
        } else {
            defer resp.Body.Close()
        }
    }
</code>```

But I have no error if I load a file which is not image.
If I use the console it works as expected:

```<code>$ docker load -i s.tar
open /var/lib/docker/tmp/docker-import-075289246/repositories: no such file or directory
</code>```

So, why I dont have a error in case of SDK?

答:
I've added working example for me:

```<code>package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"

    "github.com/docker/docker/client"
    "golang.org/x/net/context"
)

func main() {
    cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
    if err != nil {
        panic(err)
    }
    input := bytes.NewReader([]byte("dummy content\n"))
    imageLoadResponse, err := cli.ImageLoad(context.Background(), input, true)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(imageLoadResponse.Body)
    fmt.Println(string(body))
}
//Output:
// {"errorDetail":{"message":"Error processing tar file(exit status 1): unexpected EOF"},"error":"Error processing tar file(exit status 1): unexpected EOF"}

</code>```

Also you can review how docker load command

Body:
I use the ImageLoad function for loading an image:

    file, err := os.OpenFile(fileName, os.O_RDONLY, 0666)
    if err != nil {
        log.Debugf("Error loading image %s, %s", fileName, err)
    } else {
        defer file.Close()
        resp, err := client.api.ImageLoad(ctx, file, false)
        if err != nil {
            log.Debugf("Error loading image %s, %s", fileName, err)
        }
        if resp.Body == nil {
            err = errors.New("Error loading image")
        } else {
            defer resp.Body.Close()
        }
    }

But I have no error if I load a file which is not image.
If I use the console it works as expected:

$ docker load -i s.tar
open /var/lib/docker/tmp/docker-import-075289246/repositories: no such file or directory

So, why I dont have a error in case of SDK?

Body:
I've added working example for me:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"

    "github.com/docker/docker/client"
    "golang.org/x/net/context"
)

func main() {
    cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
    if err != nil {
        panic(err)
    }
    input := bytes.NewReader([]byte("dummy content\n"))
    imageLoadResponse, err := cli.ImageLoad(context.Background(), input, true)
    if err != nil {
        log.Fatal(err)
    }
    body, err := ioutil.ReadAll(imageLoadResponse.Body)
    fmt.Println(string(body))
}
//Output:
// {"errorDetail":{"message":"Error processing tar file(exit status 1): unexpected EOF"},"error":"Error processing tar file(exit status 1): unexpected EOF"}

Also you can review how docker load command


问:
Drop the columns in pandas dataframe
col_exclusions = ['numerator','Numerator' 'Denominator', "denominator"]

dataframe

```<code>id prim_numerator sec_Numerator tern_Numerator tern_Denominator final_denominator Result

1       12                23           45          54                      56         Fail
</code>```

Final output is id and Result

答:
using regex

```<code>import re

pat = re.compile('|'.join(col_exclusions),flags=re.IGNORECASE)

final_cols = [c for c in df.columns if not re.search(pat,c)]

#out:

['id', 'Result']
</code>```

```<code>print(df[final_cols])

   id Result
0   1   Fail
</code>```

if you want to drop

```<code>df = df.drop([c for c in df.columns if re.search(pat,c)],axis=1)
</code>```

or the pure pandas approach thanks to @Anky_91

```<code>df.loc[:,~df.columns.str.contains('|'.join(col_exclusions),case=False)]
</code>```

Title: Drop the columns in pandas dataframe

Body:
col_exclusions = ['numerator','Numerator' 'Denominator', "denominator"]

dataframe

id prim_numerator sec_Numerator tern_Numerator tern_Denominator final_denominator Result

1       12                23           45          54                      56         Fail

Final output is id and Result

Body:
using regex

import re

pat = re.compile('|'.join(col_exclusions),flags=re.IGNORECASE)

final_cols = [c for c in df.columns if not re.search(pat,c)]

#out:

['id', 'Result']

print(df[final_cols])

   id Result
0   1   Fail

if you want to drop

df = df.drop([c for c in df.columns if re.search(pat,c)],axis=1)

or the pure pandas approach thanks to @Anky_91

df.loc[:,~df.columns.str.contains('|'.join(col_exclusions),case=False)]


问:
Making a deep related field searchable in OctoberCMS
My my columns.yaml file for the Invoice model I have the following column:

```<code>transaction[user][email]:
    label: Login email
    type: text
    searchable: true // doesn't work!
</code>```

Unfortunately, the searchable bit doesn't work and I understand that this is because I am using transaction[user][email] instead of having a relation and select as part of the column.

My question is, can I somehow use relation and select when I'm going 2 relations deep, like this, or do I need a different approach?

My Invoice model has this relation defined:

```<code>public $morphOne = [
    'transaction' => ['Namespace\Plugin\Models\Transaction', 'name' => 'transactionable']
];
</code>```

And my Transaction model has this relation defined:

```<code>public $belongsTo = [
    'user' => ['Rainlab\User\Models\User'],
];
</code>```

So, essentially, I want to be able have a backend list of invoices with the user's email address showing in one of the columns, and also make it possible for an email address to be entered in the search box in order to filter the list only for invoices associated with the user with that email address.

答:
There is a problem with this solution, when you try to search, it runs query for count records and throws exception "column not found", because in count query it doesn't have select statement but only "select count  ..." in my case it looks like -
Column not found: 1054 Unknown column 'cruises.pagetitle' in 'where clause' (SQL: select count(*) as aggregate from cruises left join cr_cab as crc on crc.cab_id = cruises.id left join chartercruise as chrc on chrc.id = crc.cruise_id where ... or (lower(cruises.pagetitle) LIKE %thaty%))))" on line 664 of C:\xampp\htdocs\12knots_october\vendor\laravel\framework\src\Illuminate\Database\Connection.php

columns.yaml
        pagetitle:
        label: 'Connected Cruise'
        type: text
        default: none
        searchable: true
        sortable: true

```<code>    public function listExtendQueryBefore($query) {

    $query->addSelect('chrc.pagetitle');
    $query->leftJoin('cr_cab as crc', 'crc.cab_id', '=', 'cruises.id');
    $query->leftJoin('chartercruise as chrc', 'chrc.id', '=',
                                                         'crc.cruise_id');

     }
</code>```

Body:
My my columns.yaml file for the Invoice model I have the following column:

transaction[user][email]:
    label: Login email
    type: text
    searchable: true // doesn't work!

Unfortunately, the searchable bit doesn't work and I understand that this is because I am using transaction[user][email] instead of having a relation and select as part of the column.

My question is, can I somehow use relation and select when I'm going 2 relations deep, like this, or do I need a different approach?

My Invoice model has this relation defined:

public $morphOne = [
    'transaction' => ['Namespace\Plugin\Models\Transaction', 'name' => 'transactionable']
];

And my Transaction model has this relation defined:

public $belongsTo = [
    'user' => ['Rainlab\User\Models\User'],
];

So, essentially, I want to be able have a backend list of invoices with the user's email address showing in one of the columns, and also make it possible for an email address to be entered in the search box in order to filter the list only for invoices associated with the user with that email address.

Body:
There is a problem with this solution, when you try to search, it runs query for count records and throws exception "column not found", because in count query it doesn't have select statement but only "select count  ..." in my case it looks like -
Column not found: 1054 Unknown column 'cruises.pagetitle' in 'where clause' (SQL: select count(*) as aggregate from cruises left join cr_cab as crc on crc.cab_id = cruises.id left join chartercruise as chrc on chrc.id = crc.cruise_id where ... or (lower(cruises.pagetitle) LIKE %thaty%))))" on line 664 of C:\xampp\htdocs\12knots_october\vendor\laravel\framework\src\Illuminate\Database\Connection.php

columns.yaml
        pagetitle:
        label: 'Connected Cruise'
        type: text
        default: none
        searchable: true
        sortable: true

    public function listExtendQueryBefore($query) {

    $query->addSelect('chrc.pagetitle');
    $query->leftJoin('cr_cab as crc', 'crc.cab_id', '=', 'cruises.id');
    $query->leftJoin('chartercruise as chrc', 'chrc.id', '=',
                                                         'crc.cruise_id');

     }


问:
Unable to locate element for the drop down input field in my application
Unable to locate element for the drop-down input field and I am trying to locate the element using id (caction-3) and class name and its is displayed inside the  tag in the row.

So, kindly give me the solution.

Selenium script:

List < WebElement > findtags = d.findElements(By.className("rejected_row"));
System.out.println("Find tags list " + findtags);

for (WebElement searchtags: findtags) {
  String taglist = searchtags.getText().toString();
  //System.out.println("TAG DATA");
  System.out.println(taglist);
  //int i = 0;
  if (taglist.equals("Inactive")) {
    ele.setElement("caction-3");
    ele.AccessWebElementById(d).sendKeys(action);
    ele.AccessWebElementById(d).click();
  } else {
    System.out.println("No such Inactive task");
  }
}
```

Thanks,
Vairamuthu

答:
Probably, more information is required before helping you out. Element location screenshot, error from selenium etc...because you may be locating element incorrectly or some wait may require until element is loaded. A general example is below.</p>

```<code>Select test = new Select(driver.findElement(By.id("testing")));
drpCountry.selectByVisibleText("dropdown");
selectByValue("value")
selectByIndex(anyIndex)
</code>```

Body:
Unable to locate element for the drop-down input field and I am trying to locate the element using id (caction-3) and class name and its is displayed inside the  tag in the row.

So, kindly give me the solution.

Selenium script:

List < WebElement > findtags = d.findElements(By.className("rejected_row"));
System.out.println("Find tags list " + findtags);

for (WebElement searchtags: findtags) {
  String taglist = searchtags.getText().toString();
  //System.out.println("TAG DATA");
  System.out.println(taglist);
  //int i = 0;
  if (taglist.equals("Inactive")) {
    ele.setElement("caction-3");
    ele.AccessWebElementById(d).sendKeys(action);
    ele.AccessWebElementById(d).click();
  } else {
    System.out.println("No such Inactive task");
  }
}

Thanks,
Vairamuthu

Body:
Probably, more information is required before helping you out. Element location screenshot, error from selenium etc...because you may be locating element incorrectly or some wait may require until element is loaded. A general example is below.

Select test = new Select(driver.findElement(By.id("testing")));
drpCountry.selectByVisibleText("dropdown");
selectByValue("value")
selectByIndex(anyIndex)


问:
DbContext - Many to Many reliationship between three tables
Well i've been tring for some time to make Many-to-Many relationship between three tables.
Forum, Role, AccessMask.
In SQL It would like this:

```<code>ForumID | RoleID | AccessMaskID
--------------------------------
1       | 1      | 2
2       | 2      | 1
</code>```

And so on. You got the idea. ForumID and RoleID is primary key for table. Question is.. how to do it in DbContext ?
It alawys screaming that entity is missing key. (really ?). I found a way to make and many-to-many relationship between two tables with modelBuilder, but as you see I still will be missing one more table

答:
This will not be many-to-many relationship. You must expose this table as separate entity and map three one-to-many relationships. Many-to-many relationship works only between two tables if junction table contains only keys of these tables.</p>

```<code>public class Forum
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; }
}

public class Role
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; }
}

public class AccessMask
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; }
}

public class ForumRole
{
    [Key, Column(Order = 0)]
    public int ForumId { get; set; }
    [Key, Column(Order = 1)]
    public int RoleId { get; set; }
    public int AccessMaskId { get; set; }

    public virtual Forum Forum { get; set; }
    public virtual Role Role { get; set; }
    public virtual AccessMask AccssMask { get; set; }
}
</code>```

Body:
Well i've been tring for some time to make Many-to-Many relationship between three tables.
Forum, Role, AccessMask.
In SQL It would like this:

ForumID | RoleID | AccessMaskID
--------------------------------
1       | 1      | 2
2       | 2      | 1

And so on. You got the idea. ForumID and RoleID is primary key for table. Question is.. how to do it in DbContext ?
It alawys screaming that entity is missing key. (really ?). I found a way to make and many-to-many relationship between two tables with modelBuilder, but as you see I still will be missing one more table

Body:
This will not be many-to-many relationship. You must expose this table as separate entity and map three one-to-many relationships. Many-to-many relationship works only between two tables if junction table contains only keys of these tables.

public class Forum
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; }
}

public class Role
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; }
}

public class AccessMask
{
    public int Id { get; set; }
    ...
    public virtual ICollection<ForumRole> ForumRoles { get; set; }
}

public class ForumRole
{
    [Key, Column(Order = 0)]
    public int ForumId { get; set; }
    [Key, Column(Order = 1)]
    public int RoleId { get; set; }
    public int AccessMaskId { get; set; }

    public virtual Forum Forum { get; set; }
    public virtual Role Role { get; set; }
    public virtual AccessMask AccssMask { get; set; }
}


问:
Python Regex: Apostrophes only when placed within letters, not as quotation marks
define each word to be the longest contiguous sequence of alphabetic characters (or just letters), including up to one apostrophe if that apostrophe is sandwiched between two letters. </p>

```<code>[a-z]+[a-z/'?a-z]*[a-z$]
</code>```

<p>It doesn't match the letter 'a'. </p>

答:
You seem to misunderstand the character class notation. The stuff between [ and ] is a list of characters to match. It does not make sense to list the same character multiple times, and basically all characters except ] and - (and initial ^ for negation) simply match themselves, i.e. lose their regex special meaning.

Lets's rephrase your requirement. You want an alphabetic [a-z] repeated one or more times +, optionally followed by an apostrophe and another sequence of alphabetics.

```<code>[a-z]+('[a-z]+)?
</code>```

In some regex dialects, you might prefer the non-capturing opening parenthesis (?: instead of plain (.

Body:
define each word to be the longest contiguous sequence of alphabetic characters (or just letters), including up to one apostrophe if that apostrophe is sandwiched between two letters.

[a-z]+[a-z/'?a-z]*[a-z$]

It doesn't match the letter 'a'.

Body:
You seem to misunderstand the character class notation. The stuff between [ and ] is a list of characters to match. It does not make sense to list the same character multiple times, and basically all characters except ] and - (and initial ^ for negation) simply match themselves, i.e. lose their regex special meaning.

Lets's rephrase your requirement. You want an alphabetic [a-z] repeated one or more times +, optionally followed by an apostrophe and another sequence of alphabetics.

[a-z]+('[a-z]+)?

In some regex dialects, you might prefer the non-capturing opening parenthesis (?: instead of plain (.


问:
html2canvs how to loop or reuse for multiple div/html dom elements
I am trying to use html2canvas integrating with jspdf for printing multiple tabs.

```<code>  printTabsManual() {
    let tabs = document.querySelectorAll('*[id^="GRID_ID-pane"]');
    console.log(tabs.length);
    //const pdf = new jsPDF();
    //console.log(max_h);
    //console.log(max_w);
    let pdf = new jsPDF('l', 'px', [max_h, max_w]);
    for (i = 0; i < tabs.length; i++) {
      html2canvas(tabs[i])
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        pdf.addImage(imgData, 'JPEG', 0, 0);
      });
    }
    pdf.save("Download.pdf");
  }
</code>```

I am able to get the tab's div using the query selector, and this code without the loop works really fine if you are dealing with a single div, but it breaks or maybe the implementation is not right for the multiple looping.

I tried to see the logs, it's not able to get the image for second tab's div.

Not sure where I am getting this wrong.

答:
The loop executing an async operation... I believe you untended to execute all of your async tasks and only then to proceed.. so.. let's use Promise.all for that purpose:

```<code>const tasks = tabs.map(tab => html2canvas(tab))

Promise.all(tasks).then(canvases =>
{
   for (const canvas of canvases)
   {
       const imgData = canvas.toDataURL('image/png');
       pdf.addImage(imgData, 'JPEG', 0, 0);
   }

   pdf.save("Download.pdf");
})
</code>```

Which means: execute all async tasks, then manipulate their results and save pdf

Body:
I am trying to use html2canvas integrating with jspdf for printing multiple tabs.

  printTabsManual() {
    let tabs = document.querySelectorAll('*[id^="GRID_ID-pane"]');
    console.log(tabs.length);
    //const pdf = new jsPDF();
    //console.log(max_h);
    //console.log(max_w);
    let pdf = new jsPDF('l', 'px', [max_h, max_w]);
    for (i = 0; i < tabs.length; i++) {
      html2canvas(tabs[i])
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        pdf.addImage(imgData, 'JPEG', 0, 0);
      });
    }
    pdf.save("Download.pdf");
  }

I am able to get the tab's div using the query selector, and this code without the loop works really fine if you are dealing with a single div, but it breaks or maybe the implementation is not right for the multiple looping.

I tried to see the logs, it's not able to get the image for second tab's div.

Not sure where I am getting this wrong.

Body:
The loop executing an async operation... I believe you untended to execute all of your async tasks and only then to proceed.. so.. let's use Promise.all for that purpose:

const tasks = tabs.map(tab => html2canvas(tab))

Promise.all(tasks).then(canvases =>
{
   for (const canvas of canvases)
   {
       const imgData = canvas.toDataURL('image/png');
       pdf.addImage(imgData, 'JPEG', 0, 0);
   }

   pdf.save("Download.pdf");
})

Which means: execute all async tasks, then manipulate their results and save pdf


问:
how to show pdf from Internal Storage Custom folder in xmarine android c# App?
I want to show pdf file after downloading (from Internal Storage Custom folder) in my app. I want users can choice their preferred apps to open it. I have used the below mention code but it is not working. How can I do this?

```<code>string fileName = "qdummy.pdf";
Android.Net.Uri uri = Android.Net.Uri.Parse("file:///storage/emulated/0/TESTFOLDER/" + fileName);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, "application/pdf");
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

try
{
    Application.Context.StartActivity(intent);
}
catch (Exception)
{
    Toast.MakeText(Application.Context, "No hay aplicacion instalada para ver PDF", ToastLength.Long).Show();
}
</code>```

答:
issue reolved by,</p>

```<code>try
                    {
                        string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                        string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                        Android.Net.Uri path = FileProvider.GetUriForFile(Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
                        intent.SetDataAndType(path, mimeType);
                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                        Application.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }
</code>```

Body:
I want to show pdf file after downloading (from Internal Storage Custom folder) in my app. I want users can choice their preferred apps to open it. I have used the below mention code but it is not working. How can I do this?

string fileName = "qdummy.pdf";
Android.Net.Uri uri = Android.Net.Uri.Parse("file:///storage/emulated/0/TESTFOLDER/" + fileName);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, "application/pdf");
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

try
{
    Application.Context.StartActivity(intent);
}
catch (Exception)
{
    Toast.MakeText(Application.Context, "No hay aplicacion instalada para ver PDF", ToastLength.Long).Show();
}

Body:
issue reolved by,

try
                    {
                        string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                        string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                        Android.Net.Uri path = FileProvider.GetUriForFile(Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
                        intent.SetDataAndType(path, mimeType);
                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                        Application.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }


问:
i am getting error when i am fetching user data from database in laravel through API
Hello Guys nowadays am working on laravel api everything is perfect just one issue am facing that is when i write wrong username and password so i am able to get user data but when i enter correct user information so i am getting exception that is invalid credentials. please help me

here is my model code

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class email extends Model
{
    protected $table = 'users';
}
</code>```

&
Here is my Controller Code

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\email;

class EmailController extends Controller
{
   public function databyemail(Request $request){
       $data = email::where('email', $request->email)->first();
       if($data->password === bcrypt($request->password))
       {
           return response()->json($data);
       }
       else
       {
           return response()->json(['error' => 'Incorrect credentials!']);
           }
           }

}
</code>```

答:
Can you try Hash::check method for matching password.

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use App\email;

class EmailController extends Controller
{
   public function databyemail(Request $request){
        $data = email::where('email', $request->email)->first();

        if( Hash::check( $request->password, $data->password ) ) {
            return response()->json($data);
        }else{
            return response()->json(['error' => 'Incorrect credentials!']);
        }
    }
}
</code>```

Body:
Hello Guys nowadays am working on laravel api everything is perfect just one issue am facing that is when i write wrong username and password so i am able to get user data but when i enter correct user information so i am getting exception that is invalid credentials. please help me

here is my model code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class email extends Model
{
    protected $table = 'users';
}

&
Here is my Controller Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\email;

class EmailController extends Controller
{
   public function databyemail(Request $request){
       $data = email::where('email', $request->email)->first();
       if($data->password === bcrypt($request->password))
       {
           return response()->json($data);
       }
       else
       {
           return response()->json(['error' => 'Incorrect credentials!']);
           }
           }

}

Body:
Can you try Hash::check method for matching password.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use App\email;

class EmailController extends Controller
{
   public function databyemail(Request $request){
        $data = email::where('email', $request->email)->first();

        if( Hash::check( $request->password, $data->password ) ) {
            return response()->json($data);
        }else{
            return response()->json(['error' => 'Incorrect credentials!']);
        }
    }
}


问:
how to fetch multiple result set from a mysql stored procedure in laravel
I want to fetch multiple result sets from a stored procedure in laravel. Is there a way I can do this?
Currently, I can get a single row's data using the below code:</p>

```<code>$result = DB::statement('CALL user_login(' . $userId . ',"'
                                                              . $password . '",'
                                                              . '@success'.','
                                                              . '@first_Name'
                                                              );

$res = DB::select('select @success AS success, @first_Name AS firstName);

Here is my stored procedure:

DELIMITER //

DROP PROCEDURE IF EXISTS user_login//

create procedure user_login (IN userid VARCHAR(50),
                                   IN password VARCHAR(50),
                                   out success int,
                                   OUT first_Name VARCHAR(255),
                                   )

begin

declare count int(1);
set count =0;

select firstName, count(*)
into first_Name, count
from `tmc`.user where user_id = userid and pwd=password;

if count >0 then

set success =0;

else
set success=1;

end if;

end//
</code>```

答:
If your stored procedure returns multiple outputs, In this case, you can handle this situation by two methods.

Goto vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php
and set PDO::ATTR_EMULATE_PREPARES as true.

It will create problems when you will developing APIs, because of all APIs return numbers as a string when response return in JSON Like: {"status": "1"} but it should be {"status": 1}

Add a new connection to a particular situation. You have to handle the above discussed problem for a particular API only not in all APIs. So I suggest choosing option 2nd.

Add connection in the config/database.php use below code into connections

```<code>'mysql_procedure' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => 'sv_',
'prefix_indexes' => true,
'strict' => false,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),PDO::ATTR_EMULATE_PREPARES => true
]) : [],
],
</code>```

update details as per your configuration.

```<code>$procRslts = DB::connection('mysql_procedure')
->select("CALL user_login(?,?,?,?)", array( $userId ,$password,$success,$firstName ));
</code>```

I think in this you don't need to pass the last two parameters, you can write logic int procedure to get from the database.

You can get multiple outputs returned by the stored procedure.

Body:
I want to fetch multiple result sets from a stored procedure in laravel. Is there a way I can do this?
Currently, I can get a single row's data using the below code:

$result = DB::statement('CALL user_login(' . $userId . ',"'
                                                              . $password . '",'
                                                              . '@success'.','
                                                              . '@first_Name'
                                                              );

$res = DB::select('select @success AS success, @first_Name AS firstName);

Here is my stored procedure:

DELIMITER //

DROP PROCEDURE IF EXISTS user_login//

create procedure user_login (IN userid VARCHAR(50),
                                   IN password VARCHAR(50),
                                   out success int,
                                   OUT first_Name VARCHAR(255),
                                   )

begin

declare count int(1);
set count =0;

select firstName, count(*)
into first_Name, count
from `tmc`.user where user_id = userid and pwd=password;

if count >0 then

set success =0;

else
set success=1;

end if;

end//

Body:
If your stored procedure returns multiple outputs, In this case, you can handle this situation by two methods.

Goto vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php
and set PDO::ATTR_EMULATE_PREPARES as true.

It will create problems when you will developing APIs, because of all APIs return numbers as a string when response return in JSON Like: {"status": "1"} but it should be {"status": 1}

Add a new connection to a particular situation. You have to handle the above discussed problem for a particular API only not in all APIs. So I suggest choosing option 2nd.

Add connection in the config/database.php use below code into connections

'mysql_procedure' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => 'sv_',
'prefix_indexes' => true,
'strict' => false,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),PDO::ATTR_EMULATE_PREPARES => true
]) : [],
],

update details as per your configuration.

$procRslts = DB::connection('mysql_procedure')
->select("CALL user_login(?,?,?,?)", array( $userId ,$password,$success,$firstName ));

I think in this you don't need to pass the last two parameters, you can write logic int procedure to get from the database.

You can get multiple outputs returned by the stored procedure.


问:
Content type blank is not supported
I want to handle the POST request when there is empty content-type.

When I add consumes = MediaType.APPLICATION_JSON_VALUE
and make a request in postman with Content-type blank I get the following error

```<code>{
    "timestamp": 1581594986909,
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type '' not supported",
    "path": "/test"
}
</code>```

Here is the code

  @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity create(@RequestBody TestRequest testRequest) throws TestException {
        LOG.debug("Starting...");
        //code
        return createtest(testRequest);
    }
```

<ol start="2">
<li>when i remove consumes = MediaType.APPLICATION_JSON_VALUE
and make a request with content-type = blank
i get the following error</li>
</ol>

```{
    "timestamp": 1581595348209,
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/octet-stream' not supported",
    "path": "/test"
}
```

<p>Here is the code</p>

<pre class="lang-java prettyprint-override"><code>@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity create(@RequestBody TestRequest testRequest) throws TestException {
        LOG.debug("Starting...");
        //code
        return createtest(testRequest);
    }
</code>```

Here is the POstMan request

I want to handle this scenario and assume as if content-Type= application/json is sent

答:
I finally configured it and it is working. Here is the correct configuration for MappingJackson2HttpMessageConverter

@Configuration(proxyBeanMethods = false)
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonMessageConverter());
        WebMvcConfigurer.super.configureMessageConverters(converters);
    }

    @Bean
    public MappingJackson2HttpMessageConverter jacksonMessageConverter() {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        List<MediaType> supportedMediaTypes=new ArrayList<>();
        supportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
        messageConverter.setSupportedMediaTypes(supportedMediaTypes);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        messageConverter.setSupportedMediaTypes(supportedMediaTypes);
        messageConverter.setPrettyPrint(true);
        return messageConverter;
    }
```

<p>Aso add the APPLICATION_OCTET_STREAM_VALUE } in the controller method you want to support the octet-stream.</p>

```consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE
 }
```

Title: Content type blank is not supported

Body:
I want to handle the POST request when there is empty content-type.

When I add consumes = MediaType.APPLICATION_JSON_VALUE
and make a request in postman with Content-type blank I get the following error

{
    "timestamp": 1581594986909,
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type '' not supported",
    "path": "/test"
}

Here is the code

  @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity create(@RequestBody TestRequest testRequest) throws TestException {
        LOG.debug("Starting...");
        //code
        return createtest(testRequest);
    }

when i remove consumes = MediaType.APPLICATION_JSON_VALUE
and make a request with content-type = blank
i get the following error

{
    "timestamp": 1581595348209,
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/octet-stream' not supported",
    "path": "/test"
}

Here is the code

@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity create(@RequestBody TestRequest testRequest) throws TestException {
        LOG.debug("Starting...");
        //code
        return createtest(testRequest);
    }

Here is the POstMan request

I want to handle this scenario and assume as if content-Type= application/json is sent

Body:
I finally configured it and it is working. Here is the correct configuration for MappingJackson2HttpMessageConverter

@Configuration(proxyBeanMethods = false)
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonMessageConverter());
        WebMvcConfigurer.super.configureMessageConverters(converters);
    }

    @Bean
    public MappingJackson2HttpMessageConverter jacksonMessageConverter() {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        List<MediaType> supportedMediaTypes=new ArrayList<>();
        supportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
        messageConverter.setSupportedMediaTypes(supportedMediaTypes);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        messageConverter.setSupportedMediaTypes(supportedMediaTypes);
        messageConverter.setPrettyPrint(true);
        return messageConverter;
    }

Aso add the APPLICATION_OCTET_STREAM_VALUE } in the controller method you want to support the octet-stream.

consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE
 }


问:
Why does the Rust compiler complain that I use a moved value when I've replaced it with a new value?
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}
```

<p>However, the compiler complains on the second while loop that</p>

```error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move
```

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

答:
Other than getting rid of the tuple (shown by others), you can capture a mutable reference to the nodes:

    while let (&mut Some(ref mut node1), &mut Some(ref mut node2)) = (&mut shorter, &mut longer) {
        shorter = node1.next.take();
        longer = node2.next.take();
    }
```

The use of take() enables this to work: shorter = node1.next would complain of moving a field out of a reference, which is not allowed (it would leave the node in an undefined state). But takeing it is ok because it leaves None in the next field.

Body:
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}

However, the compiler complains on the second while loop that

error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

Body:
Other than getting rid of the tuple (shown by others), you can capture a mutable reference to the nodes:

    while let (&mut Some(ref mut node1), &mut Some(ref mut node2)) = (&mut shorter, &mut longer) {
        shorter = node1.next.take();
        longer = node2.next.take();
    }

The use of take() enables this to work: shorter = node1.next would complain of moving a field out of a reference, which is not allowed (it would leave the node in an undefined state). But takeing it is ok because it leaves None in the next field.


问:
lcmm - knowing which IDs are in which class
I am using the LCMM package with the function hlme.

I want to know which IDs are classified in each class. Some of my cases are being dropped from the model. So when I use $pprob, the id variable is basically just starting at 1 and increasing. It is not the original study ID. So I am not able to merge it with the original dataset.

Does anyone know how to do that?

Here is the code:

q4r.fv <- hlme(i_rest~days+days2, subject = 'ninclu', ng=4, idiag=T, mixture=~days+days2,
               data=patch, maxiter = 100, returndata = TRUE,
               classmb=~tttantal+sexe+atchroniq+hads_anxiI+hads_depI+pcs_totI)
summary(q4r.fv)
fmq4r.fv <-q4r.fv$pprob
write.csv(fmq4r.fv,file="fmq4r.fv",row.names=F)
```

<p>With the csv file, I obtain the following. The ninclu should be my ID but it no longer matches my original minclu variables that is a string participant ID variable</p>

```> print.data.frame(fmq4r.fv)
    ninclu class        prob1        prob2        prob3        prob4
1        1     2 7.416779e-09 9.635142e-01 3.630078e-02 1.850563e-04
2        2     2 5.479232e-02 8.710804e-01 7.412726e-02 9.118352e-16
3        3     1 9.933911e-01 6.607882e-03 9.830514e-07 1.110920e-23
4        4     2 2.620132e-07 9.991825e-01 8.155809e-04 1.631318e-06
5        5     2 4.382259e-04 9.877001e-01 1.186168e-02 1.166050e-11
6        6     3 4.239271e-09 2.361263e-01 7.634902e-01 3.835313e-04
```

答:
You mention that your subject ID is a string participant ID variable.
If you look at the source code for lcmm, you can see that lcmm requires a numeric subject:

```<code>if(!is.numeric(data[,subject])) stop("The argument subject must be numeric")
</code>```

I suspect the character string participant ID is coerced to factor, and it is the default factor coding that is appearing as "subj" in the model output predictions.

Try using a numeric participant ID and see if your results make more sense.

Body:
I am using the LCMM package with the function hlme.

I want to know which IDs are classified in each class. Some of my cases are being dropped from the model. So when I use $pprob, the id variable is basically just starting at 1 and increasing. It is not the original study ID. So I am not able to merge it with the original dataset.

Does anyone know how to do that?

Here is the code:

q4r.fv <- hlme(i_rest~days+days2, subject = 'ninclu', ng=4, idiag=T, mixture=~days+days2,
               data=patch, maxiter = 100, returndata = TRUE,
               classmb=~tttantal+sexe+atchroniq+hads_anxiI+hads_depI+pcs_totI)
summary(q4r.fv)
fmq4r.fv <-q4r.fv$pprob
write.csv(fmq4r.fv,file="fmq4r.fv",row.names=F)

With the csv file, I obtain the following. The ninclu should be my ID but it no longer matches my original minclu variables that is a string participant ID variable

> print.data.frame(fmq4r.fv)
    ninclu class        prob1        prob2        prob3        prob4
1        1     2 7.416779e-09 9.635142e-01 3.630078e-02 1.850563e-04
2        2     2 5.479232e-02 8.710804e-01 7.412726e-02 9.118352e-16
3        3     1 9.933911e-01 6.607882e-03 9.830514e-07 1.110920e-23
4        4     2 2.620132e-07 9.991825e-01 8.155809e-04 1.631318e-06
5        5     2 4.382259e-04 9.877001e-01 1.186168e-02 1.166050e-11
6        6     3 4.239271e-09 2.361263e-01 7.634902e-01 3.835313e-04

Body:
You mention that your subject ID is a string participant ID variable.
If you look at the source code for lcmm, you can see that lcmm requires a numeric subject:

if(!is.numeric(data[,subject])) stop("The argument subject must be numeric")

I suspect the character string participant ID is coerced to factor, and it is the default factor coding that is appearing as "subj" in the model output predictions.

Try using a numeric participant ID and see if your results make more sense.


问:
App Transport Security - Error Domain=NSURLErrorDomain Code=-1200
I have come across this 1200 error whilst building a POC and I'm really stuck as to what the actual problem is. Before you read this, I'm not looking for work arounds as I have already implemented a work around, I want to properly fix this issue.

In my app I am making a @POST HTTP request, the code for the request is fine and I make my request, get some json, parse and do whatever with it.

When building the app I was using CharlesProxy as a middleman so I could see the request I was sending out (as my password field wasn't getting encoded properly). After I built the POC I closes Charles and then the app stopped working.

I got these error logs in my console:

```<code>error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made."
</code>```

I googled around for a fix and people seemed to suggest disabing transport security to prevent apple from interfering. The thing is the server I am interacting with is a HTTPS server and transport security is not picking up on this.

I've read that this is due to an error with the SSL handshake but nobody actually suggested any fixes.

For now I've changed the app transport security settings in my info.plist to allow arbitrary loads. Obviously I don't want to be doing this in my main app, I would like to know of a way to fix this once and for all! (and I can also run charles proxy alongside the app to get everything to work).

答:
I have encountered the same issue like you so I tried to add some code XML like this

```<code><key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
    <dict>
    <key>codedeman.github.io</key>

</code>```

codedeman.github.io it's subdomain of your url

It's work for me, i hope it useful for you

Body:
I have come across this 1200 error whilst building a POC and I'm really stuck as to what the actual problem is. Before you read this, I'm not looking for work arounds as I have already implemented a work around, I want to properly fix this issue.

In my app I am making a @POST HTTP request, the code for the request is fine and I make my request, get some json, parse and do whatever with it.

When building the app I was using CharlesProxy as a middleman so I could see the request I was sending out (as my password field wasn't getting encoded properly). After I built the POC I closes Charles and then the app stopped working.

I got these error logs in my console:

error : Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made."

I googled around for a fix and people seemed to suggest disabing transport security to prevent apple from interfering. The thing is the server I am interacting with is a HTTPS server and transport security is not picking up on this.

I've read that this is due to an error with the SSL handshake but nobody actually suggested any fixes.

For now I've changed the app transport security settings in my info.plist to allow arbitrary loads. Obviously I don't want to be doing this in my main app, I would like to know of a way to fix this once and for all! (and I can also run charles proxy alongside the app to get everything to work).

Body:
I have encountered the same issue like you so I tried to add some code XML like this

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
    <dict>
    <key>codedeman.github.io</key>

codedeman.github.io it's subdomain of your url

It's work for me, i hope it useful for you


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
Depends on what area you want to work in. But nothing worth doing correctly comes in at less than 1000 lines of code.

If you are going to be writing games then try writing a Tetris clone.

If you think you will be using sockets etc then writing a simple chat/irc client would help.

Do you have a specific itch that needs to be scratched? When was the last time you thought "this sucks, I could do better?". Can you do better?

OwnerDisplayName: climatewarrior

ContentLicense: CC BY-SA 2.5


问:
Why is the OData $batch request in my SAPUI5 application failing?
I have an OData v2 service running on Wildfly. This service is connected to a single table in SQL Server. Querying this service's metadata and table data in Postman works great. I believe the OData service itself is working like it should.

I have an SAPUI5 application that is pointing to the service (called SITEDATA) in the descriptor:

```<code>"sap.app": {
    ...,
    "dataSources": {
        "SAM": {
            "uri": "http://localhost:8080/odata/SITEDATA/",
            "type": "OData",
            "settings": {
                "odataVersion": "2.0"
            }
        }
    },...

"sap.ui5": {
    ...,
    "models": {
        ...,
        "perDiem": {
            "dataSource": "SAM"
        }...
</code>```

I have a very simple view that points to the single table (which is also called SITEDATA):

```<code>    <List
    items="{ path : 'perDiem>/SITEDATA' }">
    ...
    <items>
        <ObjectListItem title="{perDiem>SITE_ID}">
</code>```

When I run the application I can see that the application successfully queries the service for:

http: //localhost:8080/odata/SITEDATA/$metadata

http: //localhost:8080/odata/SITEDATA/SITEDATA?$skip=0&$top=100

...as well as a bunch of other things. But then I get this:

The WildFly log shows that SITEDATA/$batch just doesn't exist. However, localhost:8080/odata/SITEDATA/SITEDATA/$batch works just fine.

And after researching this problem for days it looks like yes, the $batch request should be performed on the table, not the service. So the error makes sense. But I can't find any way to fix this.

Has any one experienced this problem or see anything I need to do to correct it?

答: Are you able to successfully complete a $batch call that includes a call to /SITEDATA endpoint? sap.ui.model.odata.v2.ODataModel class initializes the model to use batch calls by default. You can disable it by adding "useBatch": false to your model definition in the descriptor. You can try that to see if the problem is with the batch call.

Body:
I have an OData v2 service running on Wildfly. This service is connected to a single table in SQL Server. Querying this service's metadata and table data in Postman works great. I believe the OData service itself is working like it should.

I have an SAPUI5 application that is pointing to the service (called SITEDATA) in the descriptor:

"sap.app": {
    ...,
    "dataSources": {
        "SAM": {
            "uri": "http://localhost:8080/odata/SITEDATA/",
            "type": "OData",
            "settings": {
                "odataVersion": "2.0"
            }
        }
    },...

"sap.ui5": {
    ...,
    "models": {
        ...,
        "perDiem": {
            "dataSource": "SAM"
        }...

I have a very simple view that points to the single table (which is also called SITEDATA):

    <List
    items="{ path : 'perDiem>/SITEDATA' }">
    ...
    <items>
        <ObjectListItem title="{perDiem>SITE_ID}">

When I run the application I can see that the application successfully queries the service for:

http: //localhost:8080/odata/SITEDATA/$metadata

http: //localhost:8080/odata/SITEDATA/SITEDATA?$skip=0&$top=100

...as well as a bunch of other things. But then I get this:

The WildFly log shows that SITEDATA/$batch just doesn't exist. However, localhost:8080/odata/SITEDATA/SITEDATA/$batch works just fine.

And after researching this problem for days it looks like yes, the $batch request should be performed on the table, not the service. So the error makes sense. But I can't find any way to fix this.

Has any one experienced this problem or see anything I need to do to correct it?


问:
Cloud sql proxy not working from docker container
My application is running on docker container and deployed with google compute groups and autoscalling enabled.
The problem iam facing is connecting mysql instance from auto-scaled compute instances but its not working expected.

Dockerfile

```<code>FROM ubuntu:16.04
RUN apt-get update && apt-get install -y software-properties-common && \
...installation other extenstion
RUN curl -sS https://getcomposer.org/installer | \
    php -- --install-dir=/usr/bin/ --filename=composer
COPY . /var/www/html
CMD cd /var/www/html
RUN composer install
ADD nginx.conf/default /etc/nginx/sites-available/default
RUN wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
RUN chmod +x cloud_sql_proxy
RUN mkdir /cloudsql
RUN chmod 777 /cloudsql
RUN chmod 777 -R storage bootstrap/cache
EXPOSE 80
**CMD service php7.1-fpm start && nginx -g "daemon off;" &&  ./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306 -credential_file=file.json &**
</code>```

The last line ./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306 -credential_file=file.json & is not getting executed when I run my container.

If I run this ./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306 -credential_file=file.json & inside container (by going to container via docker command) it's working and when i close the terminal again its stop working.

Even I tried to run in background, but no luck.

Anyone have a idea of it?

答:
Has been fixed by

Create start.sh file and move all command to start.sh

After start sql proxy I put sleep 10 and start the nginx and php

Now it's works as expected.

```<code>Dockerfile
FROM ubuntu:16.04
...other command
ADD start.sh /
RUN chmod +x /start.sh
EXPOSE 80
CMD ["/start.sh"]
</code>```

and this is start.sh file

```<code>//start.sh
#!/bin/sh
./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306     -credential_file=<file>.json &
sleep 10
service php7.1-fpm start
nginx -g "daemon off;"
</code>```

Body:
My application is running on docker container and deployed with google compute groups and autoscalling enabled.
The problem iam facing is connecting mysql instance from auto-scaled compute instances but its not working expected.

Dockerfile

FROM ubuntu:16.04
RUN apt-get update && apt-get install -y software-properties-common && \
...installation other extenstion
RUN curl -sS https://getcomposer.org/installer | \
    php -- --install-dir=/usr/bin/ --filename=composer
COPY . /var/www/html
CMD cd /var/www/html
RUN composer install
ADD nginx.conf/default /etc/nginx/sites-available/default
RUN wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
RUN chmod +x cloud_sql_proxy
RUN mkdir /cloudsql
RUN chmod 777 /cloudsql
RUN chmod 777 -R storage bootstrap/cache
EXPOSE 80
**CMD service php7.1-fpm start && nginx -g "daemon off;" &&  ./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306 -credential_file=file.json &**

The last line ./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306 -credential_file=file.json & is not getting executed when I run my container.

If I run this ./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306 -credential_file=file.json & inside container (by going to container via docker command) it's working and when i close the terminal again its stop working.

Even I tried to run in background, but no luck.

Anyone have a idea of it?

Body:
Has been fixed by

Create start.sh file and move all command to start.sh

After start sql proxy I put sleep 10 and start the nginx and php

Now it's works as expected.

Dockerfile
FROM ubuntu:16.04
...other command
ADD start.sh /
RUN chmod +x /start.sh
EXPOSE 80
CMD ["/start.sh"]

and this is start.sh file

//start.sh
#!/bin/sh
./cloud_sql_proxy -dir=/cloudsql -instances=<connectionname>=tcp:0.0.0.0:3306     -credential_file=<file>.json &
sleep 10
service php7.1-fpm start
nginx -g "daemon off;"