问:
How do I turn on logging for ActionCable for Ruby on Rails? Cannot seem to get a websockets server running at all
So I'm new to Ruby on Rails. I've managed to get a basic website running, and I'm hosting it with Puma.
I'm trying to integrate websockets stuff, and was following this guide here:
https://guides.rubyonrails.org/action_cable_overview.html

My problem is that after implementing that, when I load my site, I still get an error in Chrome console:
"WebSocket connection to 'ws://:3000/cable' failed:"
There is no console output from ActionCable/Websockets whatsoever server-side. Nothing when I load the page, and nothing when I start the server.

At this point I feel like ActionCable wasn't installed correctly / is not running?

Just to reiterate, there is no console output at all from ActionCable server-side, even though the client is clearly trying to connect.

In routes.rb I have:

```<code>mount ActionCable.server => '/cable'
</code>```

In development.rb I have:

```<code>config.action_cable.url = "ws://<website>:3000/cable"
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
config.action_cable.worker_pool_size = 5
config.action_cable.disable_request_forgery_protection = true
config.action_cable.mount_path = '/cable'
</code>```

In app/channels/application_cable/connection.rb I have:

```<code>module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :identity

    def connect
        puts "We got a connection!"
        self.identity = find_verified_user
        #self.identity = User.find_by(id: cookies.encrypted['_session']['user_id'])
    end

    private

    def find_verified_user
        puts "Finding verified user!"
        session["didWebSocket"] = true #Needed to initialize session array?
        session[:user_id]
    end

  end
end
</code>```

I also just have my adapter set to async and have nothing else for my development environment in my cable.yml file.

Body:
So I'm new to Ruby on Rails. I've managed to get a basic website running, and I'm hosting it with Puma.
I'm trying to integrate websockets stuff, and was following this guide here:
https://guides.rubyonrails.org/action_cable_overview.html

My problem is that after implementing that, when I load my site, I still get an error in Chrome console:
"WebSocket connection to 'ws://:3000/cable' failed:"
There is no console output from ActionCable/Websockets whatsoever server-side. Nothing when I load the page, and nothing when I start the server.

At this point I feel like ActionCable wasn't installed correctly / is not running?

Just to reiterate, there is no console output at all from ActionCable server-side, even though the client is clearly trying to connect.

In routes.rb I have:

mount ActionCable.server => '/cable'

In development.rb I have:

config.action_cable.url = "ws://<website>:3000/cable"
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
config.action_cable.worker_pool_size = 5
config.action_cable.disable_request_forgery_protection = true
config.action_cable.mount_path = '/cable'

In app/channels/application_cable/connection.rb I have:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :identity

    def connect
        puts "We got a connection!"
        self.identity = find_verified_user
        #self.identity = User.find_by(id: cookies.encrypted['_session']['user_id'])
    end

    private

    def find_verified_user
        puts "Finding verified user!"
        session["didWebSocket"] = true #Needed to initialize session array?
        session[:user_id]
    end

  end
end

I also just have my adapter set to async and have nothing else for my development environment in my cable.yml file.


来源: stackexchange

问:
angular.json search and copy files into one directory
I want to search files (*.md) in several subdirectories (projects/rufma-styleguide/src= and copy the found files to a new directory (markdown) without specifying the path.

"assets": [
  {
    "glob": "**/*.md",
    "input": "project/src",
    "output": "markdown"
  },

```

input - project structure

project

project/src/page/colors.md

project/src/page/typography.md

project/src/component/button.md

output

markdown/colors.md

markdown/typography.md

markdown/button.md

No matter how I try, the full path is always stored in the output directory for all files.

What's wrong?

ContentLicense: CC BY-SA 4.0

Body:
I want to search files (*.md) in several subdirectories (projects/rufma-styleguide/src= and copy the found files to a new directory (markdown) without specifying the path.

"assets": [
  {
    "glob": "**/*.md",
    "input": "project/src",
    "output": "markdown"
  },

input - project structure

project

project/src/page/colors.md

project/src/page/typography.md

project/src/component/button.md

output

markdown/colors.md

markdown/typography.md

markdown/button.md

No matter how I try, the full path is always stored in the output directory for all files.

What's wrong?


问:
Keep bottom edge of table at the bottom of page
I'm writing an XSL-FO to generate PDF report.
I need to make a table that keep the bottom border even if the content of the last cell continues on the next page.

We use this code in the pdf.xsl file:

```<code>    <xsl:attribute-set name="table.table.properties">
        <xsl:attribute name="border-after-width.conditionality">retain</xsl:attribute>
        <xsl:attribute name="border-before-width.conditionality">retain</xsl:attribute>
    </xsl:attribute-set>
</code>```

Processing in fo seems to be correct according to this code:

```<code></fo:inline></fo:block><fo:table border-before-width.conditionality="retain" border-collapse="collapse" border-after-width.conditionality="retain" border-start-style="solid" border-end-style="solid" border-top-style="solid" border-bottom-style="solid" border-start-width="0.5pt" border-end-width="0.5pt" border-top-width="0.5pt" border-bottom-width="0.5pt" border-start-color="gray" border-end-color="gray" border-top-color="gray" border-bottom-color="gray" table-layout="fixed" width="100%">
</code>```

Body:
I'm writing an XSL-FO to generate PDF report.
I need to make a table that keep the bottom border even if the content of the last cell continues on the next page.

We use this code in the pdf.xsl file:

    <xsl:attribute-set name="table.table.properties">
        <xsl:attribute name="border-after-width.conditionality">retain</xsl:attribute>
        <xsl:attribute name="border-before-width.conditionality">retain</xsl:attribute>
    </xsl:attribute-set>

Processing in fo seems to be correct according to this code:

</fo:inline></fo:block><fo:table border-before-width.conditionality="retain" border-collapse="collapse" border-after-width.conditionality="retain" border-start-style="solid" border-end-style="solid" border-top-style="solid" border-bottom-style="solid" border-start-width="0.5pt" border-end-width="0.5pt" border-top-width="0.5pt" border-bottom-width="0.5pt" border-start-color="gray" border-end-color="gray" border-top-color="gray" border-bottom-color="gray" table-layout="fixed" width="100%">


问:
I am not able to set browser capabilities in UFT Developer
I need to download a file from Browser and i need to store it in particular place for that i am trying to use the below code but that was not working

```<code>browser = BrowserFactory.launch(BrowserType.CHROME);
browser = BrowserFactory.attach(new BrowserDescription.Builder().set(
                                     "download.default_directory",
                                      Constants.DOWNLOADS
                                   ).build()
                               );
</code>```

Need a code to set browser capabilities to download a file from website and stored in my desired path by using UFT Developer

Body:
I need to download a file from Browser and i need to store it in particular place for that i am trying to use the below code but that was not working

browser = BrowserFactory.launch(BrowserType.CHROME);
browser = BrowserFactory.attach(new BrowserDescription.Builder().set(
                                     "download.default_directory",
                                      Constants.DOWNLOADS
                                   ).build()
                               );

Need a code to set browser capabilities to download a file from website and stored in my desired path by using UFT Developer


问:
How to disable ANSI escape code output during a Rollup build?
When doing a runtime build with vite it uses rollupjs to do the code transformation, which prints some interesting information in the terminal. While this is fine on a local dev box, it becomes a nuisance in a CI build (here Jenkins):

```<code>[36mvite v4.0.3 [32mbuilding for production...[36m[39m
transforming...

Missing export "createServer" has been shimmed in module "__vite-browser-external".

Missing export "Socket" has been shimmed in module "__vite-browser-external".
[32m✓[39m 3098 modules transformed.
rendering chunks...
computing gzip size...
[2mbuild/[22m[2massets/[22m[32meditor-side-line-straight-3b1dfbb4.svg            [39m[1m[2m    0.41 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32msquiggle-cb9fe55e.svg                             [39m[1m[2m    0.47 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32mmarkdown-8b37fca1.svg                             [39m[1m[2m    0.58 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32mshell-40c17629.svg                                [39m[1m[2m    0.60 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32mremove-899a6ae3.svg                               [39m[1m[2m    0.65 kB[22m[1m[22m
</code>```

Is it possible to disable the ANSI escape code in the output to get just the text? Ideally, this should be configurable (say, using an env variable, to know when doing a CI build).

Body:
When doing a runtime build with vite it uses rollupjs to do the code transformation, which prints some interesting information in the terminal. While this is fine on a local dev box, it becomes a nuisance in a CI build (here Jenkins):

[36mvite v4.0.3 [32mbuilding for production...[36m[39m
transforming...

Missing export "createServer" has been shimmed in module "__vite-browser-external".

Missing export "Socket" has been shimmed in module "__vite-browser-external".
[32m✓[39m 3098 modules transformed.
rendering chunks...
computing gzip size...
[2mbuild/[22m[2massets/[22m[32meditor-side-line-straight-3b1dfbb4.svg            [39m[1m[2m    0.41 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32msquiggle-cb9fe55e.svg                             [39m[1m[2m    0.47 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32mmarkdown-8b37fca1.svg                             [39m[1m[2m    0.58 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32mshell-40c17629.svg                                [39m[1m[2m    0.60 kB[22m[1m[22m
[2mbuild/[22m[2massets/[22m[32mremove-899a6ae3.svg                               [39m[1m[2m    0.65 kB[22m[1m[22m

Is it possible to disable the ANSI escape code in the output to get just the text? Ideally, this should be configurable (say, using an env variable, to know when doing a CI build).


问:
Flutter white screen on app after adding widget
I have run into an issue that has my head itching a bit. When adding a new element to my page (using ReactiveDateTimePicker) and running the code I am met with a page that displays nothing but white (The appbar and hamburger menu at the top still show though).

Without the added code the page looks like the screenshot below.

However once I add in the code, the screen looks like the screenshot below

The code for the page is quite lengthy, so I am adding it on codepen for easier visibility. Here is the link to the full code. The section I added which caused the error is below

```<code>ReactiveForm(
                      formGroup: _form,
                      child: ListView(children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(top: 0, left: 0, right: 0),
                          child: ReactiveDateTimePicker(
                            formControlName: 'child_details.dateOfBirth',
                            type: ReactiveDatePickerFieldType.date,
                            firstDate: DateTime(DateTime.now().year - 18, 1, 1),
                            lastDate: DateTime.now()
                                .subtract(Duration(days: 2 * 365)),
                            datePickerEntryMode: DatePickerEntryMode.calendar,
                            showClearIcon: false,
                            validationMessages: {
                              '_requiredYounger120': (error) =>
                                  'Really? More than 120 years old?'
                            },
                            decoration: InputDecoration(
                              labelText: 'Date of birth',
                              border: UnderlineInputBorder(),
                              helperText: '',
                            ),
                            //locale: Localizations.localeOf(context),
                            builder: (BuildContext context, Widget child) {
                              return Theme(
                                data: ThemeData.light().copyWith(
                                  primaryColor: Theme.of(context).primaryColor,
                                  accentColor: Theme.of(context).accentColor,
                                  colorScheme: ColorScheme.light(
                                      primary: Theme.of(context).primaryColor),
                                  buttonTheme: ButtonThemeData(
                                      textTheme: ButtonTextTheme.primary),
                                ),
                                child: child,
                              );
                            },
                          ),
                        ),
                      ])),
</code>```

I am getting the error after I add the code from line 1297 - 1335. This happens on both Android and iOS

Body:
I have run into an issue that has my head itching a bit. When adding a new element to my page (using ReactiveDateTimePicker) and running the code I am met with a page that displays nothing but white (The appbar and hamburger menu at the top still show though).

Without the added code the page looks like the screenshot below.

However once I add in the code, the screen looks like the screenshot below

The code for the page is quite lengthy, so I am adding it on codepen for easier visibility. Here is the link to the full code. The section I added which caused the error is below

ReactiveForm(
                      formGroup: _form,
                      child: ListView(children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(top: 0, left: 0, right: 0),
                          child: ReactiveDateTimePicker(
                            formControlName: 'child_details.dateOfBirth',
                            type: ReactiveDatePickerFieldType.date,
                            firstDate: DateTime(DateTime.now().year - 18, 1, 1),
                            lastDate: DateTime.now()
                                .subtract(Duration(days: 2 * 365)),
                            datePickerEntryMode: DatePickerEntryMode.calendar,
                            showClearIcon: false,
                            validationMessages: {
                              '_requiredYounger120': (error) =>
                                  'Really? More than 120 years old?'
                            },
                            decoration: InputDecoration(
                              labelText: 'Date of birth',
                              border: UnderlineInputBorder(),
                              helperText: '',
                            ),
                            //locale: Localizations.localeOf(context),
                            builder: (BuildContext context, Widget child) {
                              return Theme(
                                data: ThemeData.light().copyWith(
                                  primaryColor: Theme.of(context).primaryColor,
                                  accentColor: Theme.of(context).accentColor,
                                  colorScheme: ColorScheme.light(
                                      primary: Theme.of(context).primaryColor),
                                  buttonTheme: ButtonThemeData(
                                      textTheme: ButtonTextTheme.primary),
                                ),
                                child: child,
                              );
                            },
                          ),
                        ),
                      ])),

I am getting the error after I add the code from line 1297 - 1335. This happens on both Android and iOS


问:
Android Studio - unable to read USB serial data as USB Host
I am trying to read serial data from a USB device using my Samsung phone as the host. I have followed the USB Host Overview tutorial closely but I cannot get any data from the device. I am performing async read using UsbRequest as the device is continually streaming data I would like to read.

My Java code:

```<code>class TransferThread extends Thread {
    private static final String TAG = "MainActivity";
    private static int TIMEOUT = 5000;
    private static int BUFFER_LENGTH = 32768;
    private byte[] buffer = new byte[BUFFER_LENGTH];

    UsbDeviceConnection connection;
    UsbEndpoint endpoint;

    TransferThread(UsbDeviceConnection connection, UsbEndpoint endpoint) {
        this.connection = connection;
        this.endpoint = endpoint;
    }

    public void run() {
        Log.v(TAG, "New thread started");

        UsbRequest usbRequest = new UsbRequest();
        if(usbRequest.initialize(connection, endpoint)) {
            Log.v(TAG, "USB request successfully initialised");
        }
        final ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_LENGTH);
        if(usbRequest.queue(byteBuffer)) {
            Log.v(TAG, "USB request successfully queued");
        }
        if(connection.requestWait() == usbRequest) {
            Log.v(TAG, "Successfully returned USB request result");
            Log.v(TAG, "Has array: " + byteBuffer.hasArray());
            Log.v(TAG, "Data: " + Arrays.toString(byteBuffer.array()));
            Log.v(TAG, "Data: " + byteBuffer.toString());
        }
        else {
            Log.v(TAG, "Failed to return USB request");
        }

        Log.v(TAG, "byteBuffer.ToString(): " + byteBuffer.toString());

/*        int numBytesTransferred = connection.bulkTransfer(endpoint, buffer, buffer.length, TIMEOUT);
        if(numBytesTransferred >= 0) {
            Log.v(TAG, "Bulk transfer successful");
        }
        else {
            Log.v(TAG, "Bulk transfer failed");
        }*/
    }
}

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if(device != null){
                            Log.v(TAG,"Permission granted for device");
                        }
                    }
                    else {
                        Log.d(TAG, "permission denied for device " + device);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.v(TAG, "Running Main activity onCreate");

        // Enumerate USB devices
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Log.v(TAG, String.format("%d device(s) found by UsbManager", deviceList.size()));
        for (HashMap.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
            String key = entry.getKey();
            Log.v(TAG, "Device name: " + key);
        }
        UsbDevice device = deviceList.get("/dev/bus/usb/002/002");
        Log.v(TAG, "Device info: " + device.toString());
        Log.v(TAG, String.format("Device has %d configuration(s)", device.getConfigurationCount()));
        Log.v(TAG, String.format("Device has %d interface(s)", device.getInterfaceCount()));

        // Obtain permission to communicate with a device
        PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_MUTABLE);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(usbReceiver, filter);
        manager.requestPermission(device, permissionIntent);

        int interfaceNumber = 0;
        int endpointNumber = 0;
        UsbInterface usbInterface = device.getInterface(interfaceNumber);
        Log.v(TAG, String.format("Got interface %d", interfaceNumber));
        Log.v(TAG, "Interface name: " + usbInterface.getName());
        Log.v(TAG, "Interface class: Vendor specific " + usbInterface.getInterfaceClass());
        UsbEndpoint endpoint = usbInterface.getEndpoint(endpointNumber);
        Log.v(TAG, String.format("Got endpoint %d", endpointNumber));
        int endpointType = endpoint.getType();
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_CONTROL) {
            Log.v(TAG, "Endpoint type: endpoint zero");
        }
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_ISOC) {
            Log.v(TAG, "Endpoint type: isochronous endpoint");
        }
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_BULK) {
            Log.v(TAG, "Endpoint type: bulk endpoint");
        }
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_INT) {
            Log.v(TAG, "Endpoint type: interrupt endpoint");
        }
        int endpointDir = endpoint.getDirection();
        if(endpointDir == UsbConstants.USB_DIR_IN) {
            Log.v(TAG, "Endpoint direction: IN (device to host)");
        }
        if(endpointDir == UsbConstants.USB_DIR_OUT) {
            Log.v(TAG, "Endpoint direction: OUT (host to device)");
        }

        UsbDeviceConnection connection = manager.openDevice(device);
        connection.claimInterface(usbInterface, true);

        TransferThread thread = new TransferThread(connection, endpoint);
        thread.start();
    }
}
</code>```

Using endpoint 0 (interrupt type) I get the following data when I run the code:

Results in Logcat

I'm not sure if I'm using requestWait incorrectly or if I'm using the wrong endpoint or some other USB setting. Any help would be appreciated, thanks!

Body:
I am trying to read serial data from a USB device using my Samsung phone as the host. I have followed the USB Host Overview tutorial closely but I cannot get any data from the device. I am performing async read using UsbRequest as the device is continually streaming data I would like to read.

My Java code:

class TransferThread extends Thread {
    private static final String TAG = "MainActivity";
    private static int TIMEOUT = 5000;
    private static int BUFFER_LENGTH = 32768;
    private byte[] buffer = new byte[BUFFER_LENGTH];

    UsbDeviceConnection connection;
    UsbEndpoint endpoint;

    TransferThread(UsbDeviceConnection connection, UsbEndpoint endpoint) {
        this.connection = connection;
        this.endpoint = endpoint;
    }

    public void run() {
        Log.v(TAG, "New thread started");

        UsbRequest usbRequest = new UsbRequest();
        if(usbRequest.initialize(connection, endpoint)) {
            Log.v(TAG, "USB request successfully initialised");
        }
        final ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_LENGTH);
        if(usbRequest.queue(byteBuffer)) {
            Log.v(TAG, "USB request successfully queued");
        }
        if(connection.requestWait() == usbRequest) {
            Log.v(TAG, "Successfully returned USB request result");
            Log.v(TAG, "Has array: " + byteBuffer.hasArray());
            Log.v(TAG, "Data: " + Arrays.toString(byteBuffer.array()));
            Log.v(TAG, "Data: " + byteBuffer.toString());
        }
        else {
            Log.v(TAG, "Failed to return USB request");
        }

        Log.v(TAG, "byteBuffer.ToString(): " + byteBuffer.toString());

/*        int numBytesTransferred = connection.bulkTransfer(endpoint, buffer, buffer.length, TIMEOUT);
        if(numBytesTransferred >= 0) {
            Log.v(TAG, "Bulk transfer successful");
        }
        else {
            Log.v(TAG, "Bulk transfer failed");
        }*/
    }
}

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if(device != null){
                            Log.v(TAG,"Permission granted for device");
                        }
                    }
                    else {
                        Log.d(TAG, "permission denied for device " + device);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.v(TAG, "Running Main activity onCreate");

        // Enumerate USB devices
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Log.v(TAG, String.format("%d device(s) found by UsbManager", deviceList.size()));
        for (HashMap.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
            String key = entry.getKey();
            Log.v(TAG, "Device name: " + key);
        }
        UsbDevice device = deviceList.get("/dev/bus/usb/002/002");
        Log.v(TAG, "Device info: " + device.toString());
        Log.v(TAG, String.format("Device has %d configuration(s)", device.getConfigurationCount()));
        Log.v(TAG, String.format("Device has %d interface(s)", device.getInterfaceCount()));

        // Obtain permission to communicate with a device
        PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_MUTABLE);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(usbReceiver, filter);
        manager.requestPermission(device, permissionIntent);

        int interfaceNumber = 0;
        int endpointNumber = 0;
        UsbInterface usbInterface = device.getInterface(interfaceNumber);
        Log.v(TAG, String.format("Got interface %d", interfaceNumber));
        Log.v(TAG, "Interface name: " + usbInterface.getName());
        Log.v(TAG, "Interface class: Vendor specific " + usbInterface.getInterfaceClass());
        UsbEndpoint endpoint = usbInterface.getEndpoint(endpointNumber);
        Log.v(TAG, String.format("Got endpoint %d", endpointNumber));
        int endpointType = endpoint.getType();
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_CONTROL) {
            Log.v(TAG, "Endpoint type: endpoint zero");
        }
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_ISOC) {
            Log.v(TAG, "Endpoint type: isochronous endpoint");
        }
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_BULK) {
            Log.v(TAG, "Endpoint type: bulk endpoint");
        }
        if(endpointType == UsbConstants.USB_ENDPOINT_XFER_INT) {
            Log.v(TAG, "Endpoint type: interrupt endpoint");
        }
        int endpointDir = endpoint.getDirection();
        if(endpointDir == UsbConstants.USB_DIR_IN) {
            Log.v(TAG, "Endpoint direction: IN (device to host)");
        }
        if(endpointDir == UsbConstants.USB_DIR_OUT) {
            Log.v(TAG, "Endpoint direction: OUT (host to device)");
        }

        UsbDeviceConnection connection = manager.openDevice(device);
        connection.claimInterface(usbInterface, true);

        TransferThread thread = new TransferThread(connection, endpoint);
        thread.start();
    }
}

Using endpoint 0 (interrupt type) I get the following data when I run the code:

Results in Logcat

I'm not sure if I'm using requestWait incorrectly or if I'm using the wrong endpoint or some other USB setting. Any help would be appreciated, thanks!


问:
CSS Tabs remove bottom border on active tab, while having a background image and having rounded borders on content
I want to implement a tab menu that is similar to the following image but with a background-image instead of a fixed background-color:

In order to achieve the rounded border of the content I had to add the border of tabs in the content ( border-top ) and in order to hide the border on the active tab I had a border on bottom of the active tab with the same color as the background. Now that I need to add a background-image this solution does not work.

I already tried similar solutions like using the :before, :after pseudo-class  to add a fake border before and after the active tab but I lose the functionality of border-radius.

Current implementation: https://codesandbox.io/s/compassionate-wright-13kwl7?file=/index.html


问:
Interesting task with service layer in Controller Spring Boot
So, i have controller, that should return List of Courses (2 course in MYSQL), where i can find Course by name.
When i run application, i don't see anything course, but i can find necessary course in the search column. Example: write "java" and application print me.

```<code>@GetMapping ("/index")
public String findCourse (Model model, @RequestParam (name="keyword", defaultValue = "") String keyword ) {
    List <Course> course = courseService.findCourseBycourseName(keyword);
    model.addAttribute("listCourses", course);
    model.addAttribute("keyword", keyword);
    return "views/courses";

}
</code>```

When i change main method in Controller, i see List Course, but i can not search this course. Button search don't work.

```<code> List <Course> course = courseService.findCourseBycourseName(keyword);
 to --> List <Course> course = courseService.fatchAll();
</code>```

Who know where my problem, and how and where i can see what findCourseBycourseName returned me?

Service layer.

```<code> public interface CourseService {

    List <Course> findCourseBycourseName(String keyword);

    List <Course> fetchAll();

</code>```

ServiceImpl

```<code>@Override
    public List <Course> findCourseBycourseName(String keyword) {
        return courseDao.findCourseBycourseName(keyword);
    }

    @Override
    public List<Course> fetchAll() {
        return courseDao.findAll();
    }
</code>```

And Dao

```<code>public interface CourseDao extends JpaRepository <Course, Long> {

    List <Course> findCourseBycourseName (String keyword);
</code>```

Body:
So, i have controller, that should return List of Courses (2 course in MYSQL), where i can find Course by name.
When i run application, i don't see anything course, but i can find necessary course in the search column. Example: write "java" and application print me.

@GetMapping ("/index")
public String findCourse (Model model, @RequestParam (name="keyword", defaultValue = "") String keyword ) {
    List <Course> course = courseService.findCourseBycourseName(keyword);
    model.addAttribute("listCourses", course);
    model.addAttribute("keyword", keyword);
    return "views/courses";

}

When i change main method in Controller, i see List Course, but i can not search this course. Button search don't work.

 List <Course> course = courseService.findCourseBycourseName(keyword);
 to --> List <Course> course = courseService.fatchAll();

Who know where my problem, and how and where i can see what findCourseBycourseName returned me?

Service layer.

 public interface CourseService {

    List <Course> findCourseBycourseName(String keyword);

    List <Course> fetchAll();

ServiceImpl

@Override
    public List <Course> findCourseBycourseName(String keyword) {
        return courseDao.findCourseBycourseName(keyword);
    }

    @Override
    public List<Course> fetchAll() {
        return courseDao.findAll();
    }

And Dao

public interface CourseDao extends JpaRepository <Course, Long> {

    List <Course> findCourseBycourseName (String keyword);


问:
Scipy for Heart Rate data processing, Scipy.signal find_peaks returning empty array
Had an array with HR data in the form of BPMs (beats per minute).

Need to split the data into segments where the HR was increasing, decreasing, and stayed the same to find the up/down amplitude and the associated times as well as the times when the heart rate did not change.

To do so, tried using find_peaks to find the peaks and troughs of the HR data.
To find troughs, I did a transformation of the original HR by multiplying it by -1 to find its peaks which in turn is the real troughs of the original HR data.

find_peaks while specifying plateau and height, gives outputs that contains the peak location as well as the plateau locations and the peak values, example from below:

```<code>find_peaks(arr, height=0.5, prominence=0.1, plateau_size=0.5)

(array([ 9, 18, 33, 64, 70, 80, 87]),
{'plateau_sizes': array([5, 2, 2, 3, 1, 3, 2]),
'left_edges': array([ 7, 18, 33, 63, 70, 79, 87]),
'right_edges': array([11, 19, 34, 65, 70, 81, 88]),
'peak_heights': array([ 80.,  87.,  81., 107., 106., 105., 105.]),
'prominences': array([ 2., 11.,  2., 18.,  3.,  8.,  8.]),
'left_bases': array([ 3,  3, 29, 43, 68, 74, 74]),
'right_bases': array([13, 40, 40, 98, 98, 98, 98])})
</code>```

however, upon specifying height for the negative version of the original Heart rate Data to find the troughs and the heights, it returned empty array. If I remove the height=0.5, it outputs valid values except the peak_heights.

```<code>find_peaks(trougharr,plateau_size=0.5,height=0.5)
(array([], dtype=int64),
{'plateau_sizes': array([], dtype=int64),
'left_edges': array([], dtype=int64),
'right_edges': array([], dtype=int64),
'peak_heights': array([], dtype=float64)})
</code>```

Is there something wrong calling height with negative numbered arrays?
If there's a easier method or simpler method for splitting up the data into up and down and constant portions, that would be much appreciated.

the original sample HR data is as such:

```<code>HR
    array([ 77,  77,  77,  76,  77,  78,  79,  80,  80,  80,  80,  80,  79,
            78,  78,  79,  83,  85,  87,  87,  86,  86,  86,  85,  83,  81,
            80,  79,  79,  79,  80,  80,  80,  81,  81,  80,  79,  79,  79,
            74,  69,  69,  69,  69,  70,  70,  70,  70,  70,  71,  72,  80,
            82,  89,  92,  95,  97,  99, 100, 102, 103, 105, 106, 107, 107,
           107, 105, 104, 103, 105, 106, 102, 100,  97,  97,  98, 101, 102,
           104, 105, 105, 105, 104, 104, 104, 104, 104, 105, 105, 104, 104,
           104, 104,  98,  96,  93,  92,  90,  89])
</code>```

-1*HR. (the problematic one)

```<code>    array([ -77,  -77,  -77,  -76,  -77,  -78,  -79,  -80,  -80,  -80,  -80,
            -80,  -79,  -78,  -78,  -79,  -83,  -85,  -87,  -87,  -86,  -86,
            -86,  -85,  -83,  -81,  -80,  -79,  -79,  -79,  -80,  -80,  -80,
            -81,  -81,  -80,  -79,  -79,  -79,  -74,  -69,  -69,  -69,  -69,
            -70,  -70,  -70,  -70,  -70,  -71,  -72,  -80,  -82,  -89,  -92,
            -95,  -97,  -99, -100, -102, -103, -105, -106, -107, -107, -107,
           -105, -104, -103, -105, -106, -102, -100,  -97,  -97,  -98, -101,
           -102, -104, -105, -105, -105, -104, -104, -104, -104, -104, -105,
           -105, -104, -104, -104, -104,  -98,  -96,  -93,  -92,  -90,  -89])
</code>```

Tried to split Heart Rate data into sections where it was increasing/decreasing/staying constant to find the up_amplitude,up_time, down_amplitude, down_time, time_constant.
Found find_peaks to do it but it may not be the simplest, if there's a simpler method, please point me to it.

Tried to use peak_prominences, but it did not detect all prominences for some reason, the codes tried were:

```<code>peaks, _ = find_peaks(x)
prominences = peak_prominences(x, peaks)[0]

contour_heights = x[peaks] - prominences
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks])
plt.show()
</code>```

The prominences missed several locations.

Body:
Had an array with HR data in the form of BPMs (beats per minute).

Need to split the data into segments where the HR was increasing, decreasing, and stayed the same to find the up/down amplitude and the associated times as well as the times when the heart rate did not change.

To do so, tried using find_peaks to find the peaks and troughs of the HR data.
To find troughs, I did a transformation of the original HR by multiplying it by -1 to find its peaks which in turn is the real troughs of the original HR data.

find_peaks while specifying plateau and height, gives outputs that contains the peak location as well as the plateau locations and the peak values, example from below:

find_peaks(arr, height=0.5, prominence=0.1, plateau_size=0.5)

(array([ 9, 18, 33, 64, 70, 80, 87]),
{'plateau_sizes': array([5, 2, 2, 3, 1, 3, 2]),
'left_edges': array([ 7, 18, 33, 63, 70, 79, 87]),
'right_edges': array([11, 19, 34, 65, 70, 81, 88]),
'peak_heights': array([ 80.,  87.,  81., 107., 106., 105., 105.]),
'prominences': array([ 2., 11.,  2., 18.,  3.,  8.,  8.]),
'left_bases': array([ 3,  3, 29, 43, 68, 74, 74]),
'right_bases': array([13, 40, 40, 98, 98, 98, 98])})

however, upon specifying height for the negative version of the original Heart rate Data to find the troughs and the heights, it returned empty array. If I remove the height=0.5, it outputs valid values except the peak_heights.

find_peaks(trougharr,plateau_size=0.5,height=0.5)
(array([], dtype=int64),
{'plateau_sizes': array([], dtype=int64),
'left_edges': array([], dtype=int64),
'right_edges': array([], dtype=int64),
'peak_heights': array([], dtype=float64)})

Is there something wrong calling height with negative numbered arrays?
If there's a easier method or simpler method for splitting up the data into up and down and constant portions, that would be much appreciated.

the original sample HR data is as such:

HR
    array([ 77,  77,  77,  76,  77,  78,  79,  80,  80,  80,  80,  80,  79,
            78,  78,  79,  83,  85,  87,  87,  86,  86,  86,  85,  83,  81,
            80,  79,  79,  79,  80,  80,  80,  81,  81,  80,  79,  79,  79,
            74,  69,  69,  69,  69,  70,  70,  70,  70,  70,  71,  72,  80,
            82,  89,  92,  95,  97,  99, 100, 102, 103, 105, 106, 107, 107,
           107, 105, 104, 103, 105, 106, 102, 100,  97,  97,  98, 101, 102,
           104, 105, 105, 105, 104, 104, 104, 104, 104, 105, 105, 104, 104,
           104, 104,  98,  96,  93,  92,  90,  89])

-1*HR. (the problematic one)

    array([ -77,  -77,  -77,  -76,  -77,  -78,  -79,  -80,  -80,  -80,  -80,
            -80,  -79,  -78,  -78,  -79,  -83,  -85,  -87,  -87,  -86,  -86,
            -86,  -85,  -83,  -81,  -80,  -79,  -79,  -79,  -80,  -80,  -80,
            -81,  -81,  -80,  -79,  -79,  -79,  -74,  -69,  -69,  -69,  -69,
            -70,  -70,  -70,  -70,  -70,  -71,  -72,  -80,  -82,  -89,  -92,
            -95,  -97,  -99, -100, -102, -103, -105, -106, -107, -107, -107,
           -105, -104, -103, -105, -106, -102, -100,  -97,  -97,  -98, -101,
           -102, -104, -105, -105, -105, -104, -104, -104, -104, -104, -105,
           -105, -104, -104, -104, -104,  -98,  -96,  -93,  -92,  -90,  -89])

Tried to split Heart Rate data into sections where it was increasing/decreasing/staying constant to find the up_amplitude,up_time, down_amplitude, down_time, time_constant.
Found find_peaks to do it but it may not be the simplest, if there's a simpler method, please point me to it.

Tried to use peak_prominences, but it did not detect all prominences for some reason, the codes tried were:

peaks, _ = find_peaks(x)
prominences = peak_prominences(x, peaks)[0]

contour_heights = x[peaks] - prominences
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks])
plt.show()

The prominences missed several locations.


问:
How to set graphql-codegen documents file?
I have graphql-codegen.yml file and src folder under project root path.

graphql-codegen.yml

```<code>schema: "https://swapi-graphql.netlify.app/.netlify/functions/index"
overwrite: true
documents: "src/**/*.graphql"
generates:
 src/generated/graphql-types.tsx:
 plugins:
 — "typescript"
 — "typescript-operations"
 — "typescript-react-apollo"
</code>```

src/graphql/getAllPeople.graphql

```<code>query GetAllPeople($pageSize: Int) {
    allPeople(first: $pageSize) {
        people {
            name
            birthYear
            gender
            height
        }
    }
}
</code>```

package.json

```<code>"scripts": {
        "graphql:codegen": "graphql-codegen — config graphql-codegen.yml"
    },
        "dependencies": {
        "@apollo/client": "^3.7.0",
        "@emotion/core": "^10.0.21",
        "@graphql-codegen/cli": "^2.16.2",
        "@graphql-codegen/fragment-matcher": "^3.3.3",
        "@graphql-codegen/typescript": "^2.8.6",
        "@graphql-codegen/typescript-operations": "^2.5.11",
        "@graphql-codegen/typescript-react-apollo": "^3.3.7"
    },
</code>```

When I type command  yarn graphql:codegen on terminal, it shows error:

```<code>yarn run v1.22.17
$ graphql-codegen — config graphql-codegen.yml
Unable to find Codegen config file!

        Please make sure that you have a configuration file under the current directory!

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

What's wrong with the setting ?

Body:
I have graphql-codegen.yml file and src folder under project root path.

graphql-codegen.yml

schema: "https://swapi-graphql.netlify.app/.netlify/functions/index"
overwrite: true
documents: "src/**/*.graphql"
generates:
 src/generated/graphql-types.tsx:
 plugins:
 — "typescript"
 — "typescript-operations"
 — "typescript-react-apollo"

src/graphql/getAllPeople.graphql

query GetAllPeople($pageSize: Int) {
    allPeople(first: $pageSize) {
        people {
            name
            birthYear
            gender
            height
        }
    }
}

package.json

"scripts": {
        "graphql:codegen": "graphql-codegen — config graphql-codegen.yml"
    },
        "dependencies": {
        "@apollo/client": "^3.7.0",
        "@emotion/core": "^10.0.21",
        "@graphql-codegen/cli": "^2.16.2",
        "@graphql-codegen/fragment-matcher": "^3.3.3",
        "@graphql-codegen/typescript": "^2.8.6",
        "@graphql-codegen/typescript-operations": "^2.5.11",
        "@graphql-codegen/typescript-react-apollo": "^3.3.7"
    },

When I type command  yarn graphql:codegen on terminal, it shows error:

yarn run v1.22.17
$ graphql-codegen — config graphql-codegen.yml
Unable to find Codegen config file!

        Please make sure that you have a configuration file under the current directory!

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

What's wrong with the setting ?


问:
how to check a mutex exists for a scheduled job using laravel tinker?
I have a job scheduled to run every hour. 'withoutOverlapping' is set for this job and mutex expiry time is 24 hour.

But when I checked cron.log. I found that it is not running every hour. But it runs once in a day and at the end of job, there is a redis write error. I think this error is getting when clearing mutex (lock) of this job from redis after completion of job execution.  Then after 24 hour, mutex expires automatically, then this job runs next hour.

To check mutex clears from redis or not, I need to see mutex of this job exists. So I tried below cod in tinker but it is showing zero events. Actually there are 7 jobs scheduked

```<code>>>> $s = new Illuminate\Console\Scheduling\Schedule();
=> Illuminate\Console\Scheduling\Schedule {#3543}
>>> count($s->events())
=> 0
>>>
</code>```

So using tinker how can I achieve this ?

Body:
I have a job scheduled to run every hour. 'withoutOverlapping' is set for this job and mutex expiry time is 24 hour.

But when I checked cron.log. I found that it is not running every hour. But it runs once in a day and at the end of job, there is a redis write error. I think this error is getting when clearing mutex (lock) of this job from redis after completion of job execution.  Then after 24 hour, mutex expires automatically, then this job runs next hour.

To check mutex clears from redis or not, I need to see mutex of this job exists. So I tried below cod in tinker but it is showing zero events. Actually there are 7 jobs scheduked

>>> $s = new Illuminate\Console\Scheduling\Schedule();
=> Illuminate\Console\Scheduling\Schedule {#3543}
>>> count($s->events())
=> 0
>>>

So using tinker how can I achieve this ?


问:
How can I supply user with download details after payment?
I would like to use Stripe to sell digital goods. User needs a licence code after completing payment. The Strip API allows adding a description to the PaymentIntent that is apparently shown to the user on the Receipt.
Are there better ways for managing supply of download details/ license keys through the Stripe API?


问:
Is there any way how to get data before utf8 encoded in pgsql
Using PGSQL, I had query error like

```<code>invalid byte sequence for encoding "UTF8": 0xea 0x3c 0x68
</code>```

when I was just using SELECT statements.

```<code>SELECT id, data, test FROM t_example WHERE id = 'hello';
-- Error!
</code>```

And I have found that the query goes well without the 'data' column.

```<code>SELECT id, test FROM t_example WHERE id = 'hello';
-- Works well...
</code>```

So it seems the cause of the error probably is on the data column. I want to check or view what kind of text is inside the data column, but it seems I cant take it because the SELECT query itself is not working here because of the encoding problem...

Is there anyway I can check the data inside without encoding or whatever please.
But the thing is that I don't want to do dumping or migration because the database is too huge to do that. Please let me know if there is something easy and fast way to solve this problem.

Thank you

Body:
Using PGSQL, I had query error like

invalid byte sequence for encoding "UTF8": 0xea 0x3c 0x68

when I was just using SELECT statements.

SELECT id, data, test FROM t_example WHERE id = 'hello';
-- Error!

And I have found that the query goes well without the 'data' column.

SELECT id, test FROM t_example WHERE id = 'hello';
-- Works well...

So it seems the cause of the error probably is on the data column. I want to check or view what kind of text is inside the data column, but it seems I cant take it because the SELECT query itself is not working here because of the encoding problem...

Is there anyway I can check the data inside without encoding or whatever please.
But the thing is that I don't want to do dumping or migration because the database is too huge to do that. Please let me know if there is something easy and fast way to solve this problem.

Thank you


问:
Unity Engine: [Cam Post Process] + [outline Post Process] Color and depth buffers have mismatched Surfaces Resolved Buffer flag Error Log?
When i closing camera post process error gone (using std built in pp and custom outline pp) !

(closing camera post process and is gone)


问:
when making a binding lib for xamarin android you need to adapt the functions with out parameters
I have a .jar library that I have added as EmbebedJar. Among them there is a function that returns an integer and asks for two parameters, a context and a list in which the readers are going to be listed. When I use that function, it returns ok, but it doesn't fill the list with readers.

```<code>public virtual long SCardListReaders(Android.Content.Context p0, System.Collections.IList p1)
</code>```

I can not debug the code because I have the USB port busy, but I add a log output file.

```<code>private bool ReloadReader()
{
    bool ret = false;
    try
    {
        _SmartCard = new SCard();

        long succes = _SmartCard.SCardEstablishContext(Application.Context);
        if (succes == 0)
        {
            succes = _SmartCard.USBRequestPermission(Application.Context);
            if (succes == 0)
            {
                System.Collections.IList tempReadersList = new List<string>();
                succes = _SmartCard.SCardListReaders(Application.Context, tempReadersList);
                List<string> readersList = (List<string>)tempReadersList;

                if (succes == 0 && readersList != null && readersList.Count() > 0)
                {
                    ret = true;
                }
            }
        }
    catch (Exception ex)
    {
        ret = false;
        new LogRepository(DbPath).SaveLog(_context, LogType.Error, "Error in ReloadReader", ex);
    }

    return ret;
}
</code>```

ListReaders returns ok, but no readers in the list.

Body:
I have a .jar library that I have added as EmbebedJar. Among them there is a function that returns an integer and asks for two parameters, a context and a list in which the readers are going to be listed. When I use that function, it returns ok, but it doesn't fill the list with readers.

public virtual long SCardListReaders(Android.Content.Context p0, System.Collections.IList p1)

I can not debug the code because I have the USB port busy, but I add a log output file.

private bool ReloadReader()
{
    bool ret = false;
    try
    {
        _SmartCard = new SCard();

        long succes = _SmartCard.SCardEstablishContext(Application.Context);
        if (succes == 0)
        {
            succes = _SmartCard.USBRequestPermission(Application.Context);
            if (succes == 0)
            {
                System.Collections.IList tempReadersList = new List<string>();
                succes = _SmartCard.SCardListReaders(Application.Context, tempReadersList);
                List<string> readersList = (List<string>)tempReadersList;

                if (succes == 0 && readersList != null && readersList.Count() > 0)
                {
                    ret = true;
                }
            }
        }
    catch (Exception ex)
    {
        ret = false;
        new LogRepository(DbPath).SaveLog(_context, LogType.Error, "Error in ReloadReader", ex);
    }

    return ret;
}

ListReaders returns ok, but no readers in the list.


问:
JS: navigator.mediaDevices.getUserMedia set which device to use
So, when the site requires access to the users mic and cam, i want to select which microphone i want to access

```<code>        await navigator.mediaDevices.getUserMedia({
          audio: this.micOn,
          video: this.camOn,
        });
</code>```

Like:

Available mics:

[] mic 1

[x] mic 2 (use this microphone)

Is there any way to do this? Thanks!

Body:
So, when the site requires access to the users mic and cam, i want to select which microphone i want to access

        await navigator.mediaDevices.getUserMedia({
          audio: this.micOn,
          video: this.camOn,
        });

Like:

Available mics:

[] mic 1

[x] mic 2 (use this microphone)

Is there any way to do this? Thanks!


问:
VueJs - Unexpected token '?'
I added a new package.
After that when i run my project the compiler gives me unexpected token error because doesn't undertand question mark character.
eg "defaultedOptions.onSuccess?.(data);"

I tried to add transpileDependencies setting in app.config.js but continues to give me the same problem.

Title: VueJs - Unexpected token '?'


问:
Convert table with array vectors to applicable data forms of MultithreadedTableWriter using DolphinDB Java API
I have a BasicTable object “data” with columns of double array vector. I execute the following code via DolphinDB Java API to write data with MultiThreadedTableWriter::insert,

```<code>BasicTable data;
MultithreadedTableWriter mtwWriter = new MultithreadedTableWriter(/*...... params*/);
for (int rowIdx = 0; rowIdx < data.rows(); rowIdx++) {
List<Object> row = new ArrayList<>();
for (int k = 0; k < data.columns(); k++) {
Vector col = data.getColumn(k);
row.add(col.get(rowIdx));
  }
mtwWriter.insert(row.toArray());
}
</code>```

The error message is reported:

```<code>java.lang.RuntimeException: Failed to insert data. Cannot convert Entity to DT_DOUBLE_ARRAY.
at com.xxdb.data.BasicEntityFactory.createScalar
</code>```

Body:
I have a BasicTable object “data” with columns of double array vector. I execute the following code via DolphinDB Java API to write data with MultiThreadedTableWriter::insert,

BasicTable data;
MultithreadedTableWriter mtwWriter = new MultithreadedTableWriter(/*...... params*/);
for (int rowIdx = 0; rowIdx < data.rows(); rowIdx++) {
List<Object> row = new ArrayList<>();
for (int k = 0; k < data.columns(); k++) {
Vector col = data.getColumn(k);
row.add(col.get(rowIdx));
  }
mtwWriter.insert(row.toArray());
}

The error message is reported:

java.lang.RuntimeException: Failed to insert data. Cannot convert Entity to DT_DOUBLE_ARRAY.
at com.xxdb.data.BasicEntityFactory.createScalar


问:
Instagram allows only one sessions
I made a bot using istagrapi. And I could have my bot running, have a desktop Instagram open and have my phone Instagram open.
I belive I had 3 sessions, one for each an everything worked.
But now, when I log with bot, I am kicked out off my phone Instagram. It says "you need to log in". And if I do that, error accours on my bot; LoginRequired. I have to login with a bot again. Witch kickes me out off my phone again.

I tried to loggin with cookie, with session id, witch I got with a tool on my browser. But it still allows me to have only one sesion running.

Even without the bot; If I log in with desktop, I am kicked out off my phone.

Is this related to me, becouse I use a bot? Is this a silent warning from Insgram to stop using it?
If so, how can I avoid this?

Title: Instagram allows only one sessions


问:
The development server returned response error code: 500
I encounter this error only happend on my PC. I tried on my other PC and it worked normally. This app is to make Geofencing app that have notif.
This error always happend when I run the project using npm run android.

This is the metro looks like

This is the Android Simulator looks like

I tried searching how to fix it but I cant find the one who works


问:
Right way to permute
I'm trying to find if there is a standard way that we can permute that ensures the randomness of the permutation.

In my case, to shuffle a sequence of size n, im doing this way.

Read bytes from /dev/urandom as they appear and mod the byte with n(considering n value is 52).

Then on the random sequence I'm applying Fisher-Yates shuffle, but for random picks I'm again relying upon dev/urandom.

Since I'm reading the random bits in KB's only from /dev/urandom I believe it should be fine. So basically security of my shuffle is depend on the randomness of the data that is extracted from /dev/urandom. I would like is this good enough or are there any well thought approaches exists on how we permute the numbers and are there any algos that exists that can validate the entropy of my permutation?

Title: Right way to permute


问:
Can morelogin provide dynamic IP?
Can morelogin provide dynamic IP?
How to change WEBGL and GEOLocation in morelogin?

I hope someone who has used morelogin can help me to solve some questions.

Title: Can morelogin provide dynamic IP?


问:
When i build my vue project get an error, please tell me how to resolve it?
my project is from vuecli3 upgrade to vuecli5, When build project i don't want to transform asset smaller than 8KiB, So i added these code in vue.config.js:

```<code>const imagesRule = config.module.rule('images');
imagesRule.set('parser', {
  dataUrlCondition: {
   maxSize: 0.1 * 1024
}
})
</code>```

But i get an error:

Conflict: Multiple chunks emit assets to the same filename static/img/xxx.png (chunks 685 and 4880)

My vue.config.js file contents:

```<code>'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const shell = require('shelljs')
const fs = require('fs')
const address = require('address')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Admin Template' // page title

const port = process.env.port || process.env.npm_config_port || 8888 // dev port

if (/build/g.test(process.env.npm_config_argv) && fs.existsSync(path.resolve(__dirname, './dist'))) shell.rm('-rf', 'dist')
module.exports = {
  publicPath: 'xxx',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: false,
  productionSourceMap:false,
  filenameHashing: false,
  devServer: {
    port: port,
    hot: true,
    open: false,
    allowedHosts: 'all',
    client: {
      overlay: {
        warnings: false,
        errors: false
      },
    },
    server: 'https'
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    cache: {
      type: 'filesystem',
      buildDependencies: {
        // 当配置修改时，缓存失效
        config: [__filename],
      },
    },
  },
  chainWebpack(config) {
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test
    const imagesRule = config.module.rule('images');
    imagesRule.set('parser', {
      dataUrlCondition: {
        maxSize: 0.1 * 1024
      }
    })
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
    // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-module-source-map')
      )

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  }
}

</code>```

Body:
my project is from vuecli3 upgrade to vuecli5, When build project i don't want to transform asset smaller than 8KiB, So i added these code in vue.config.js:

const imagesRule = config.module.rule('images');
imagesRule.set('parser', {
  dataUrlCondition: {
   maxSize: 0.1 * 1024
}
})

But i get an error:

Conflict: Multiple chunks emit assets to the same filename static/img/xxx.png (chunks 685 and 4880)

My vue.config.js file contents:

'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const shell = require('shelljs')
const fs = require('fs')
const address = require('address')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Admin Template' // page title

const port = process.env.port || process.env.npm_config_port || 8888 // dev port

if (/build/g.test(process.env.npm_config_argv) && fs.existsSync(path.resolve(__dirname, './dist'))) shell.rm('-rf', 'dist')
module.exports = {
  publicPath: 'xxx',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: false,
  productionSourceMap:false,
  filenameHashing: false,
  devServer: {
    port: port,
    hot: true,
    open: false,
    allowedHosts: 'all',
    client: {
      overlay: {
        warnings: false,
        errors: false
      },
    },
    server: 'https'
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    cache: {
      type: 'filesystem',
      buildDependencies: {
        // 当配置修改时，缓存失效
        config: [__filename],
      },
    },
  },
  chainWebpack(config) {
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test
    const imagesRule = config.module.rule('images');
    imagesRule.set('parser', {
      dataUrlCondition: {
        maxSize: 0.1 * 1024
      }
    })
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
    // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-module-source-map')
      )

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  }
}


问:
E:\j2eeproject\Job_Find\nbproject\build-impl.xml:1033: The module has not been deployed. See the server log for details
when ever I try to run my project this type of error confuse me please help me.
I'm work in Jsp project but this deployment error I can not solve this I try many
things but is can't work.

E:\j2eeproject\Job_Find\nbproject\build-impl.xml:1033: The module has not been deployed. See the server log for details


问:
Position Text in Center
I have bootstrap 5 and trying to display text when hover on image. I have my HTML code like below

```<code><div class="slider-img">
    <img src="https://via.placeholder.com/500x500/" data-src="https://via.placeholder.com/500x500/" class="img-fluid h-100 lzy_img" width="100%" height="100%" alt="Latest English Status Shayari">
                    <div class="overlay">
                        <a class="link-bold" href="en/">English Status</a>
                    </div>
                </div>
</code>```

and CSS like

```<code>.slider-img {
  position: relative;
  border-radius: 10px;
}
.overlay {
    position: absolute;
    border-radius: 10px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    text-align: center;
    background: rgb(0,0,0,.8);
    color: #fff;
    width: 100%;
    transition: .5s ease;
    opacity: 0;
    color: #fff;
    font-size: 20px;
    padding: 20px;
    min-height: 100%;
}
</code>```

I want my text to stay in center of box but its always showing on top like this

I am new in CSS and not getting idea whats I am missing in it. Let me know if someone here can help me for same.

Thanks!

Title: Position Text in Center

Body:
I have bootstrap 5 and trying to display text when hover on image. I have my HTML code like below

                        English Status

and CSS like

.slider-img {
  position: relative;
  border-radius: 10px;
}
.overlay {
    position: absolute;
    border-radius: 10px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    text-align: center;
    background: rgb(0,0,0,.8);
    color: #fff;
    width: 100%;
    transition: .5s ease;
    opacity: 0;
    color: #fff;
    font-size: 20px;
    padding: 20px;
    min-height: 100%;
}

I want my text to stay in center of box but its always showing on top like this

I am new in CSS and not getting idea whats I am missing in it. Let me know if someone here can help me for same.

Thanks!


问:
Implement the parse_cookie function python
Implemented the test function from parsing, the tests passed. Now it is necessary to make a second function that uses cookies, receives as input a string with values, and at the output we have a key\value dictionary.
I have attached an example of the first function.

```<code>import urllib.parse

def parse(url: str) -> dict:
fragment = urllib.parse.urlparse(url).query
params = dict(urllib.parse.parse_qsl(fragment))
return params

if __name__ == '__main__':
assert parse('https://example.com/path/to/page?name=ferret&color=purple') == {'name': 'ferret', 'color': '   purple'}
assert parse('https://example.com/path/to/page?name=ferret&color=purple&') == {'name': 'ferret', '      color': 'purple'}
assert parse('https://example.com/') == {}
</code>```

The function that needs to be implemented, more precisely, to rework the first one.

```<code>def parse_cookie(query: str) -> dict:
return {}

if __name__ == '__main__':
assert parse_cookie('name=Dima;') == {'name': 'Dima'}
assert parse_cookie('') == {}`
</code>```

Body:
Implemented the test function from parsing, the tests passed. Now it is necessary to make a second function that uses cookies, receives as input a string with values, and at the output we have a key\value dictionary.
I have attached an example of the first function.

import urllib.parse

def parse(url: str) -> dict:
fragment = urllib.parse.urlparse(url).query
params = dict(urllib.parse.parse_qsl(fragment))
return params

if __name__ == '__main__':
assert parse('https://example.com/path/to/page?name=ferret&color=purple') == {'name': 'ferret', 'color': '   purple'}
assert parse('https://example.com/path/to/page?name=ferret&color=purple&') == {'name': 'ferret', '      color': 'purple'}
assert parse('https://example.com/') == {}

The function that needs to be implemented, more precisely, to rework the first one.

def parse_cookie(query: str) -> dict:
return {}

if __name__ == '__main__':
assert parse_cookie('name=Dima;') == {'name': 'Dima'}
assert parse_cookie('') == {}`


问:
Express RESTful API, what and how to test with jest and supertest
I started learning node.js and I have some doubts about tests.

I build RESTful API with ExpressJs, Typescript, Typeorm and Postgresql. While developing I was trying to follow "feature by package" architecture. Every package/module have own Controller, Service and Repository.

My question is what is best way to test API.

Should I use jest mocking or go without mocking and just use supertest?

My guess is to use mocking for a reasons like:

to isolate and focus on the code being tested and not on the behavior or state of external dependencies

creating faster tests.

If I should use mocking, should I mock controller or service or both of them?

I think to just mock controller.

Should I go just with supertest call and check response with .toBe(), toEqual(), etc...

I think this is simple and strait forward but for example if my API is down tests will fail but actually it shouldn't because code behavior is still correct.

```<code>// src/user/UserController.ts

@Response('401', 'Unauthorized')
@SuccessResponse('201', 'Created user')
@Post()
public async create(@Header('X-Access-Token') _token: string, @Body() body: CreateUserDto) {
    try {
        const user = await this.service.create(body);

        if (user === null) {
            return this.notFound(`Couldn't create user with email ${body.email}`);
        }

        return this.created(user);
    } catch (e) {
        console.log(e);

        return this.serverError('Error while trying to save user');
    }
}
</code>```
```<code>// src/user/UserService.ts

public async create(payload: RegisterDto): Promise<UserDto> {
    const password = await bcrypt.hash(payload.password, 10);
    const user = await this.repository.save({ ...payload, ...{ password } });

    return UserMapper.toDto(user);
}
</code>```
```<code>// Example one of POST - /api/users test
// src/user/test/user.test.ts

it('should return 201 and created user', async () => {
    const createUserControllerMock = jest
        .spyOn(UserController.prototype, 'create')
        .mockReturnValueOnce(
            Promise.resolve({
                status: 201,
                message: 'Created',
                data: userPayload
            })
        );

    const { statusCode, body } = await supertest(app)
        .post('/api/users')
        .set('X-Access-Token', token)
        .send(userInput);

    expect(statusCode).toBe(201);
    expect(body.data).toEqual(userPayload);
    expect(createUserControllerMock).toHaveBeenCalledWith(token, userInput);
});
</code>```
```<code>// Example two of POST - /api/users test
// src/user/test/user.test.ts

it('should return 201 and created user', async () => {
        const { statusCode, body } = await supertest('http://localhost:8000/api')
        .post('/users')
        .set('X-Access-Token', token)
        .send(CreateUserPayload);

    expect(statusCode).toBe(201);
    expect(body.message).toBe('Created');
});
</code>```

Body:
I started learning node.js and I have some doubts about tests.

I build RESTful API with ExpressJs, Typescript, Typeorm and Postgresql. While developing I was trying to follow "feature by package" architecture. Every package/module have own Controller, Service and Repository.

My question is what is best way to test API.

Should I use jest mocking or go without mocking and just use supertest?

My guess is to use mocking for a reasons like:

to isolate and focus on the code being tested and not on the behavior or state of external dependencies

creating faster tests.

If I should use mocking, should I mock controller or service or both of them?

I think to just mock controller.

Should I go just with supertest call and check response with .toBe(), toEqual(), etc...

I think this is simple and strait forward but for example if my API is down tests will fail but actually it shouldn't because code behavior is still correct.

// src/user/UserController.ts

@Response('401', 'Unauthorized')
@SuccessResponse('201', 'Created user')
@Post()
public async create(@Header('X-Access-Token') _token: string, @Body() body: CreateUserDto) {
    try {
        const user = await this.service.create(body);

        if (user === null) {
            return this.notFound(`Couldn't create user with email ${body.email}`);
        }

        return this.created(user);
    } catch (e) {
        console.log(e);

        return this.serverError('Error while trying to save user');
    }
}

// src/user/UserService.ts

public async create(payload: RegisterDto): Promise<UserDto> {
    const password = await bcrypt.hash(payload.password, 10);
    const user = await this.repository.save({ ...payload, ...{ password } });

    return UserMapper.toDto(user);
}

// Example one of POST - /api/users test
// src/user/test/user.test.ts

it('should return 201 and created user', async () => {
    const createUserControllerMock = jest
        .spyOn(UserController.prototype, 'create')
        .mockReturnValueOnce(
            Promise.resolve({
                status: 201,
                message: 'Created',
                data: userPayload
            })
        );

    const { statusCode, body } = await supertest(app)
        .post('/api/users')
        .set('X-Access-Token', token)
        .send(userInput);

    expect(statusCode).toBe(201);
    expect(body.data).toEqual(userPayload);
    expect(createUserControllerMock).toHaveBeenCalledWith(token, userInput);
});

// Example two of POST - /api/users test
// src/user/test/user.test.ts

it('should return 201 and created user', async () => {
        const { statusCode, body } = await supertest('http://localhost:8000/api')
        .post('/users')
        .set('X-Access-Token', token)
        .send(CreateUserPayload);

    expect(statusCode).toBe(201);
    expect(body.message).toBe('Created');
});


问:
Representing data in Excel in JSON object
How can I write the following representation as json?
enter image description here</p>


问:
Sequelize does not fetch all associated elements when using aggreate function
_ My project is using sequelize to working with mysql database, if i'm using the aggregate function, it's not display all associatied element.

_ Product model:

```<code>const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Product extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
    static async findAllProducts() {
      return await Product.findAll()
    }
  }
  Product.init({
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
      },
      name: {
        type: DataTypes.CHAR,
        allowNull: false
      },
      description: {
        type: DataTypes.TEXT
      },
      price: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false
      },
  }, {
    sequelize,
    modelName: 'Product',
  });
  Product.associate = (models) => {
    Product.belongsTo(models.Category)
    Product.hasMany(models.ProductSize)
    Product.hasMany(models.Image)
    Product.hasMany(models.Cart)
  }
  return Product;
};
</code>```

_ ProductSize Model:

```<code>const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class ProductSize extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
    static async createProductSizes() {

    }
  }
  ProductSize.init({
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    size: {
      type: DataTypes.STRING,
      allowNull: false
    },
    quantity:{
      type: DataTypes.INTEGER,
      allowNull: false
    },
    ProductId: {
      type: DataTypes.INTEGER,
      allowNull: true
    }
  }, {
    sequelize,
    modelName: 'ProductSize',
  });
  ProductSize.associate = (models) => {
    ProductSize.belongsTo(models.Product)
  }
  return ProductSize;
};
</code>```

_ Sequelize code that display all ProductSizes associated with Product

```<code>        return await Product.findAll({
            include: [
                {
                    model: Category,
                    required: true
                },
                {
                    model: ProductSize,
                    required: true
                },
                {
                    model: Image,
                    required: true
                },
            ],

        })
</code>```

_ Result of above code.

```<code>[
  {
    "id": 5,
    "name": "Sex",
    "description": "Im in",
    "price": 150000,
    "createdAt": "2023-01-04T06:39:21.000Z",
    "updatedAt": "2023-01-04T06:39:21.000Z",
    "CategoryId": 1,
    "Category": {
      "id": 1,
      "name": "Ao khoac",
      "createdAt": "2023-01-04T06:33:57.000Z",
      "updatedAt": "2023-01-04T06:33:57.000Z",
      "GenderId": 1
    },
    "ProductSizes": [
      {
        "id": 1,
        "size": "M",
        "quantity": 2,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      },
      {
        "id": 2,
        "size": "S",
        "quantity": 3,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      }
    ],
    "Images": [
      {
        "id": 1,
        "path": "kindpng_1595848_1648263463719_22039.png",
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z",
        "ProductId": 5
      }
    ]
  }
]
</code>```

_ Now it still renders as it should, but when I add aggregate function to calculate the total quantity of a product the statement gives only 1 size associated with the product

```<code>        return await Product.findAll({
            include: [
                {
                    model: Category,
                    required: true
                },
                {
                    model: ProductSize,
                    required: true
                },
                {
                    model: Image,
                    required: true
                },
            ],
            attributes:[[Sequelize.fn('sum',Sequelize.col('ProductSizes.quantity')), 'TotalQuantity' ]],
</code>```
```<code>  {
    "TotalQuantity": "5",
    "Category": {
      "id": 1,
      "name": "Ao khoac",
      "createdAt": "2023-01-04T06:33:57.000Z",
      "updatedAt": "2023-01-04T06:33:57.000Z",
      "GenderId": 1
    },
    "ProductSizes": [
      {
        "id": 1,
        "size": "M",
        "quantity": 2,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      }
    ],
    "Images": [
      {
        "id": 1,
        "path": "kindpng_1595848_1648263463719_22039.png",
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z",
        "ProductId": 5
      }
    ]
  }
]
</code>```

_ Expected result

```<code>  {
    "TotalQuantity": "5",
    "Category": {
      "id": 1,
      "name": "Ao khoac",
      "createdAt": "2023-01-04T06:33:57.000Z",
      "updatedAt": "2023-01-04T06:33:57.000Z",
      "GenderId": 1
    },
    "ProductSizes": [
      {
        "id": 1,
        "size": "M",
        "quantity": 2,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      },
      {
        "id": 2,
        "size": "S",
        "quantity": 3,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      }
    ],
    "Images": [
      {
        "id": 1,
        "path": "kindpng_1595848_1648263463719_22039.png",
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z",
        "ProductId": 5
      }
    ]
  }
]
</code>```

----Solution-----

_ Because the deadline is approaching, I have hardcoded a function that calculates the total quantity of ProductSizes

    let sum = 0
    for(let i = 0; i<=products.length-1;i++){
        for(let j = 0; j<=products[i].ProductSizes.length-1;j++){

            sum+=products[i].ProductSizes[j]["quantity"]
        }
        products[i]["SizeQuant"]={ sum }
        sum=0
    }
```
<p>_ The result of product object after calling the above function</p>
```Product {
  dataValues: {
    id: 5,
    name: 'Sex',
    description: 'Im in',
    price: 150000,
    createdAt: 2023-01-04T06:39:21.000Z,
    updatedAt: 2023-01-04T06:39:21.000Z,
    CategoryId: 1,
    Category: Category {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    },
    ProductSizes: [ [ProductSize], [ProductSize] ],
    Images: [ [Image] ]
  },
  _previousDataValues: {
    id: 5,
    name: 'Sex',
    description: 'Im in',
    price: 150000,
    createdAt: 2023-01-04T06:39:21.000Z,
    updatedAt: 2023-01-04T06:39:21.000Z,
    CategoryId: 1,
    Category: Category {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    },
    ProductSizes: [ [ProductSize], [ProductSize] ],
    Images: [ [Image] ]
  },
  uniqno: 1,
  _changed: Set(0) {},
  _options: {
    isNewRecord: false,
    _schema: null,
    _schemaDelimiter: '',
    include: [ [Object], [Object], [Object] ],
    includeNames: [ 'Category', 'ProductSizes', 'Images' ],
    includeMap: { Category: [Object], ProductSizes: [Object], Images: [Object] },
    includeValidated: true,
    attributes: [
      'id',
      'name',
      'description',
      'price',
      'createdAt',
      'updatedAt',
      'CategoryId'
    ],
    raw: true
  },
  isNewRecord: false,
  Category: Category {
    dataValues: {
      id: 1,
      name: 'Ao khoac',
      createdAt: 2023-01-04T06:33:57.000Z,
      updatedAt: 2023-01-04T06:33:57.000Z,
      GenderId: 1
    },
    _previousDataValues: {
      id: 1,
      name: 'Ao khoac',
      createdAt: 2023-01-04T06:33:57.000Z,
      updatedAt: 2023-01-04T06:33:57.000Z,
      GenderId: 1
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      include: undefined,
      includeNames: undefined,
      includeMap: undefined,
      includeValidated: true,
      raw: true,
      attributes: undefined
    },
    isNewRecord: false
  },
  ProductSizes: [
    ProductSize {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    },
    ProductSize {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    }
  ],
  Images: [
    Image {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    }
  ],
  SizeQuant: { sum: 5 }
}
```
<p>_ And then fetch to the user:</p>
```                    <% products.forEach(function(prod){ %>

                            <%=prod.name%>
                            <%=prod.Category.name%>
                            <%=prod.price%>
                            <%=prod.description%>
                            <%=prod.SizeQuant.sum%>
                            <%=prod.createdAt%>
                            <%=prod.updatedAt%>

                        <%});%>
```

Body:
_ My project is using sequelize to working with mysql database, if i'm using the aggregate function, it's not display all associatied element.

_ Product model:

const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Product extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
    static async findAllProducts() {
      return await Product.findAll()
    }
  }
  Product.init({
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
      },
      name: {
        type: DataTypes.CHAR,
        allowNull: false
      },
      description: {
        type: DataTypes.TEXT
      },
      price: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false
      },
  }, {
    sequelize,
    modelName: 'Product',
  });
  Product.associate = (models) => {
    Product.belongsTo(models.Category)
    Product.hasMany(models.ProductSize)
    Product.hasMany(models.Image)
    Product.hasMany(models.Cart)
  }
  return Product;
};

_ ProductSize Model:

const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class ProductSize extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
    static async createProductSizes() {

    }
  }
  ProductSize.init({
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    size: {
      type: DataTypes.STRING,
      allowNull: false
    },
    quantity:{
      type: DataTypes.INTEGER,
      allowNull: false
    },
    ProductId: {
      type: DataTypes.INTEGER,
      allowNull: true
    }
  }, {
    sequelize,
    modelName: 'ProductSize',
  });
  ProductSize.associate = (models) => {
    ProductSize.belongsTo(models.Product)
  }
  return ProductSize;
};

_ Sequelize code that display all ProductSizes associated with Product

        return await Product.findAll({
            include: [
                {
                    model: Category,
                    required: true
                },
                {
                    model: ProductSize,
                    required: true
                },
                {
                    model: Image,
                    required: true
                },
            ],

        })

_ Result of above code.

[
  {
    "id": 5,
    "name": "Sex",
    "description": "Im in",
    "price": 150000,
    "createdAt": "2023-01-04T06:39:21.000Z",
    "updatedAt": "2023-01-04T06:39:21.000Z",
    "CategoryId": 1,
    "Category": {
      "id": 1,
      "name": "Ao khoac",
      "createdAt": "2023-01-04T06:33:57.000Z",
      "updatedAt": "2023-01-04T06:33:57.000Z",
      "GenderId": 1
    },
    "ProductSizes": [
      {
        "id": 1,
        "size": "M",
        "quantity": 2,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      },
      {
        "id": 2,
        "size": "S",
        "quantity": 3,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      }
    ],
    "Images": [
      {
        "id": 1,
        "path": "kindpng_1595848_1648263463719_22039.png",
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z",
        "ProductId": 5
      }
    ]
  }
]

_ Now it still renders as it should, but when I add aggregate function to calculate the total quantity of a product the statement gives only 1 size associated with the product

        return await Product.findAll({
            include: [
                {
                    model: Category,
                    required: true
                },
                {
                    model: ProductSize,
                    required: true
                },
                {
                    model: Image,
                    required: true
                },
            ],
            attributes:[[Sequelize.fn('sum',Sequelize.col('ProductSizes.quantity')), 'TotalQuantity' ]],

  {
    "TotalQuantity": "5",
    "Category": {
      "id": 1,
      "name": "Ao khoac",
      "createdAt": "2023-01-04T06:33:57.000Z",
      "updatedAt": "2023-01-04T06:33:57.000Z",
      "GenderId": 1
    },
    "ProductSizes": [
      {
        "id": 1,
        "size": "M",
        "quantity": 2,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      }
    ],
    "Images": [
      {
        "id": 1,
        "path": "kindpng_1595848_1648263463719_22039.png",
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z",
        "ProductId": 5
      }
    ]
  }
]

_ Expected result

  {
    "TotalQuantity": "5",
    "Category": {
      "id": 1,
      "name": "Ao khoac",
      "createdAt": "2023-01-04T06:33:57.000Z",
      "updatedAt": "2023-01-04T06:33:57.000Z",
      "GenderId": 1
    },
    "ProductSizes": [
      {
        "id": 1,
        "size": "M",
        "quantity": 2,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      },
      {
        "id": 2,
        "size": "S",
        "quantity": 3,
        "ProductId": 5,
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z"
      }
    ],
    "Images": [
      {
        "id": 1,
        "path": "kindpng_1595848_1648263463719_22039.png",
        "createdAt": "2023-01-04T06:39:21.000Z",
        "updatedAt": "2023-01-04T06:39:21.000Z",
        "ProductId": 5
      }
    ]
  }
]

----Solution-----

_ Because the deadline is approaching, I have hardcoded a function that calculates the total quantity of ProductSizes

    let sum = 0
    for(let i = 0; i<=products.length-1;i++){
        for(let j = 0; j<=products[i].ProductSizes.length-1;j++){

            sum+=products[i].ProductSizes[j]["quantity"]
        }
        products[i]["SizeQuant"]={ sum }
        sum=0
    }

_ The result of product object after calling the above function

Product {
  dataValues: {
    id: 5,
    name: 'Sex',
    description: 'Im in',
    price: 150000,
    createdAt: 2023-01-04T06:39:21.000Z,
    updatedAt: 2023-01-04T06:39:21.000Z,
    CategoryId: 1,
    Category: Category {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    },
    ProductSizes: [ [ProductSize], [ProductSize] ],
    Images: [ [Image] ]
  },
  _previousDataValues: {
    id: 5,
    name: 'Sex',
    description: 'Im in',
    price: 150000,
    createdAt: 2023-01-04T06:39:21.000Z,
    updatedAt: 2023-01-04T06:39:21.000Z,
    CategoryId: 1,
    Category: Category {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    },
    ProductSizes: [ [ProductSize], [ProductSize] ],
    Images: [ [Image] ]
  },
  uniqno: 1,
  _changed: Set(0) {},
  _options: {
    isNewRecord: false,
    _schema: null,
    _schemaDelimiter: '',
    include: [ [Object], [Object], [Object] ],
    includeNames: [ 'Category', 'ProductSizes', 'Images' ],
    includeMap: { Category: [Object], ProductSizes: [Object], Images: [Object] },
    includeValidated: true,
    attributes: [
      'id',
      'name',
      'description',
      'price',
      'createdAt',
      'updatedAt',
      'CategoryId'
    ],
    raw: true
  },
  isNewRecord: false,
  Category: Category {
    dataValues: {
      id: 1,
      name: 'Ao khoac',
      createdAt: 2023-01-04T06:33:57.000Z,
      updatedAt: 2023-01-04T06:33:57.000Z,
      GenderId: 1
    },
    _previousDataValues: {
      id: 1,
      name: 'Ao khoac',
      createdAt: 2023-01-04T06:33:57.000Z,
      updatedAt: 2023-01-04T06:33:57.000Z,
      GenderId: 1
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      include: undefined,
      includeNames: undefined,
      includeMap: undefined,
      includeValidated: true,
      raw: true,
      attributes: undefined
    },
    isNewRecord: false
  },
  ProductSizes: [
    ProductSize {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    },
    ProductSize {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    }
  ],
  Images: [
    Image {
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    }
  ],
  SizeQuant: { sum: 5 }
}

_ And then fetch to the user:

                    <% products.forEach(function(prod){ %>

                            <%=prod.name%>
                            <%=prod.Category.name%>
                            <%=prod.price%>
                            <%=prod.description%>
                            <%=prod.SizeQuant.sum%>
                            <%=prod.createdAt%>
                            <%=prod.updatedAt%>

                        <%});%>


问:
Aspose.PDF Change page from horizontal to vertical without rotating content of page
I have PDF generated from third party. When I add that PDF to document like this:

```<code>var labelBytes = client.DownloadData(url);
var stream =  new MemoryStream(labelBytes);
Document labelDocument = new Document(labelStream);
</code>```

I get PDF page horizontal, but content vertical:
page horizontal instead of vertical

I tried to set page size but after that all content has shifted to bottom left corner of page :

```<code> Document labelDocument = new Document(labelStream);
 PageCollection pageCollection = labelDocument.Pages;
 Page pdfPage = pageCollection[1];
 pdfPage.SetPageSize(597.6, 842.4);
</code>```

Looks like this:
content shifted to bottom left.

Has anyone ran to something similar or have more experience with Aspose libraries?

Body:
I have PDF generated from third party. When I add that PDF to document like this:

var labelBytes = client.DownloadData(url);
var stream =  new MemoryStream(labelBytes);
Document labelDocument = new Document(labelStream);

I get PDF page horizontal, but content vertical:
page horizontal instead of vertical

I tried to set page size but after that all content has shifted to bottom left corner of page :

 Document labelDocument = new Document(labelStream);
 PageCollection pageCollection = labelDocument.Pages;
 Page pdfPage = pageCollection[1];
 pdfPage.SetPageSize(597.6, 842.4);

Looks like this:
content shifted to bottom left.

Has anyone ran to something similar or have more experience with Aspose libraries?


问:
Mongoose new version doesn't read models properly
I was using mongoose with next, but I was getting a .split error or something similar, and I saw that they are some updates to the package and decided to upgrade it.

However now after the upgrade I', getting another error:
TypeError: Cannot read properties of undefined (reading 'Landing')

Here is an screenshot of the error:

Here is my code, I use it with nextJS:

```<code>import { Schema, model, models } from "mongoose";

const LandingSchema = new Schema({ Test: { type: String }});

const Landing = models.Landing || model("Landing", LandingSchema);
export default Landing;
</code>```

Body:
I was using mongoose with next, but I was getting a .split error or something similar, and I saw that they are some updates to the package and decided to upgrade it.

However now after the upgrade I', getting another error:
TypeError: Cannot read properties of undefined (reading 'Landing')

Here is an screenshot of the error:

Here is my code, I use it with nextJS:

import { Schema, model, models } from "mongoose";

const LandingSchema = new Schema({ Test: { type: String }});

const Landing = models.Landing || model("Landing", LandingSchema);
export default Landing;


问:
Do not show ChatPopup with Cypress
I am practice test about ChatPopUp with 3rd Party JavaScript Cypress
This is the website: https://glebbahmutov.com/cypress-3rd-party-script-example/

This is my code

```<code>it.only('Slow Down And Wait For 3rd Party JavaScript To Load',function(){
    cy.intercept('https://code.tidio.co/*.js').as('tidio')
    cy.visit('https://glebbahmutov.com/cypress-3rd-party-script-example/')
    cy.wait('@tidio')
    cy.get('#open-chat').click()
});
</code>```

It should show like

Please help to me, I really know to understand, thank a lot

Title: Do not show ChatPopup with Cypress

Body:
I am practice test about ChatPopUp with 3rd Party JavaScript Cypress
This is the website: https://glebbahmutov.com/cypress-3rd-party-script-example/

This is my code

it.only('Slow Down And Wait For 3rd Party JavaScript To Load',function(){
    cy.intercept('https://code.tidio.co/*.js').as('tidio')
    cy.visit('https://glebbahmutov.com/cypress-3rd-party-script-example/')
    cy.wait('@tidio')
    cy.get('#open-chat').click()
});

It should show like

Please help to me, I really know to understand, thank a lot