问:
Is there a way to identify which USB port a mass storage drive uses?
I am trying to identify which port a USB mass storage is connected to.
Here is my scenario. I have a vbscript program that monitors the USB mass storage drive plug-ins and do some routines on them and its process flow needs to know which port the drive was connected to.

So far I am not able to find a link between the USB events, the identified usb mass storage drive and the port on the computer (for eg., Location - Port_#0001.Hub_#0006 as shown in Windows device manager->usb controllers->USB mass storage). My search was mainly using 'VbsEdit' tool by connecting a storage device and stepping through the available snippets.

```<code>Sub Monitor_usb_storage_events()
    Dim WsShell,strComputer,wmi, wmiEvent,usb,objDisk,fileSys,colDisks,Drive
    Set WsShell = CreateObject("WScript.Shell")
    strComputer = "."
    Set wmi = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set wmiEvent = wmi.ExecNotificationQuery("select * from __InstanceOperationEvent within 1 where TargetInstance ISA 'Win32_PnPEntity' and TargetInstance.Description='USB Mass Storage Device'")
    While True
    Set usb = wmiEvent.NextEvent()
    Select Case usb.Path_.Class
        Case "__InstanceCreationEvent"
            'WScript.Echo("USB device found")
            Set colDisks = wmi.ExecQuery _
            ("SELECT * FROM Win32_LogicalDisk")
            For Each objDisk in colDisks
              If objDisk.DriveType = 2 Then
                 Set fileSys = CreateObject("Scripting.FileSystemObject")
                 For Each Drive In fileSys.Drives
                    If Drive.IsReady Then
                       '*Need port number where this drive is connected*
                    End If
                 Next
              End If
           Next
        Case "__InstanceDeletionEvent"
            'WScript.Echo("USB device removed")
        Case "__InstanceModificationEvent"
            'WScript.Echo("USB device modified")
    End Select
    Wend
End Sub
</code>```

答:
Here is a script I've had a for while that queries the Win32_USBControllerDevice and then returns the dependent devices.

```<code>Option Explicit
Dim strComputer: strComputer = "."

Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Dim colDevices: Set colDevices = objWMIService.ExecQuery _
   ("Select * From Win32_USBControllerDevice")
Dim objDevice

For Each objDevice in colDevices
   Dim strDeviceName: strDeviceName = objDevice.Dependent
   strDeviceName = Replace(strDeviceName, """", "")
   Dim arrDeviceNames: arrDeviceNames = Split(strDeviceName, "=")
   strDeviceName = arrDeviceNames(1)
   Dim colUSBDevices: Set colUSBDevices = objWMIService.ExecQuery _
       ("Select * From Win32_PnPEntity Where DeviceID = '" & strDeviceName & "'")
   Dim objUSBDevice

   For Each objUSBDevice in colUSBDevices
       Wscript.Echo objUSBDevice.Description
       WScript.Echo objUSBDevice.PnPDeviceID
   Next
Next
</code>```

If you combined this with your __InstanceOperationEvent WMI query you should be able to modify the above script to query the DeviceID returned in the matched Win32_PnPEntity instance.

You can get the DeviceID in your above script using:

```<code>strDeviceName = usb.TargetInstance.DeviceID
</code>```

Body:
I am trying to identify which port a USB mass storage is connected to.
Here is my scenario. I have a vbscript program that monitors the USB mass storage drive plug-ins and do some routines on them and its process flow needs to know which port the drive was connected to.

So far I am not able to find a link between the USB events, the identified usb mass storage drive and the port on the computer (for eg., Location - Port_#0001.Hub_#0006 as shown in Windows device manager->usb controllers->USB mass storage). My search was mainly using 'VbsEdit' tool by connecting a storage device and stepping through the available snippets.

Sub Monitor_usb_storage_events()
    Dim WsShell,strComputer,wmi, wmiEvent,usb,objDisk,fileSys,colDisks,Drive
    Set WsShell = CreateObject("WScript.Shell")
    strComputer = "."
    Set wmi = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set wmiEvent = wmi.ExecNotificationQuery("select * from __InstanceOperationEvent within 1 where TargetInstance ISA 'Win32_PnPEntity' and TargetInstance.Description='USB Mass Storage Device'")
    While True
    Set usb = wmiEvent.NextEvent()
    Select Case usb.Path_.Class
        Case "__InstanceCreationEvent"
            'WScript.Echo("USB device found")
            Set colDisks = wmi.ExecQuery _
            ("SELECT * FROM Win32_LogicalDisk")
            For Each objDisk in colDisks
              If objDisk.DriveType = 2 Then
                 Set fileSys = CreateObject("Scripting.FileSystemObject")
                 For Each Drive In fileSys.Drives
                    If Drive.IsReady Then
                       '*Need port number where this drive is connected*
                    End If
                 Next
              End If
           Next
        Case "__InstanceDeletionEvent"
            'WScript.Echo("USB device removed")
        Case "__InstanceModificationEvent"
            'WScript.Echo("USB device modified")
    End Select
    Wend
End Sub

Body:
Here is a script I've had a for while that queries the Win32_USBControllerDevice and then returns the dependent devices.

Option Explicit
Dim strComputer: strComputer = "."

Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Dim colDevices: Set colDevices = objWMIService.ExecQuery _
   ("Select * From Win32_USBControllerDevice")
Dim objDevice

For Each objDevice in colDevices
   Dim strDeviceName: strDeviceName = objDevice.Dependent
   strDeviceName = Replace(strDeviceName, """", "")
   Dim arrDeviceNames: arrDeviceNames = Split(strDeviceName, "=")
   strDeviceName = arrDeviceNames(1)
   Dim colUSBDevices: Set colUSBDevices = objWMIService.ExecQuery _
       ("Select * From Win32_PnPEntity Where DeviceID = '" & strDeviceName & "'")
   Dim objUSBDevice

   For Each objUSBDevice in colUSBDevices
       Wscript.Echo objUSBDevice.Description
       WScript.Echo objUSBDevice.PnPDeviceID
   Next
Next

If you combined this with your __InstanceOperationEvent WMI query you should be able to modify the above script to query the DeviceID returned in the matched Win32_PnPEntity instance.

You can get the DeviceID in your above script using:

strDeviceName = usb.TargetInstance.DeviceID


来源: stackexchange

问:
The drawable "ic_settings" in drawable has no declaration in the base drawable folder
I added a vector asset to a wear os project using and cannot access it using:

```<code>ContextCompat.getDrawable(mContext,R.drawable.ic_settings);
</code>```

It does not seem to be finding the asset. I have the Drawable directory and see the assets in it. I opened up the xml file and there is an error:

"The drawable 'ic_settings' in drawable has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier"

I have no idea what this means. I just added it using the New -> Vector Asset menu. Does anybody know how to solve this issue?

Here is the line in the code:

Here is where it is in android studio:

When I look at the file:

Furthermore I have a roundbutton.xml in the drawable directory which is referred by R.drawable in another pice of code, and which there are no errors.

UPDATE

After doing all the checks (is the asset in the drawable directory), I closed and restarted Android Studio and it recognized them. Ye ol' reboot. Thanks to all for the responses. I am going to select the one which helped the most as the answer.

答:
Which helped me in a similar case with another file.
I redid a bunch of work to fix this error. Deleted the entire contents of the file in the IDE editor. Retyped and rechecked the contents of the entire project probably 10 times. Nothing helped. It seemed mystical.
The problem was solved like this:
I removed the ic_launcher_background.xml file. Not safe.
And created a new one. Then I typed the whole text again.
And everything became good.

Perhaps some hidden control character in the file interfered. I can't repeat the situation again.

ContentLicense: CC BY-SA 4.0

Body:
I added a vector asset to a wear os project using and cannot access it using:

ContextCompat.getDrawable(mContext,R.drawable.ic_settings);

It does not seem to be finding the asset. I have the Drawable directory and see the assets in it. I opened up the xml file and there is an error:

"The drawable 'ic_settings' in drawable has no declaration in the base drawable folder or in a drawable-densitydpi folder; this can lead to crashes when the drawable is queried in a configuration that does not match this qualifier"

I have no idea what this means. I just added it using the New -> Vector Asset menu. Does anybody know how to solve this issue?

Here is the line in the code:

Here is where it is in android studio:

When I look at the file:

Furthermore I have a roundbutton.xml in the drawable directory which is referred by R.drawable in another pice of code, and which there are no errors.

UPDATE

After doing all the checks (is the asset in the drawable directory), I closed and restarted Android Studio and it recognized them. Ye ol' reboot. Thanks to all for the responses. I am going to select the one which helped the most as the answer.


问:
Java program runtime error
```<code>public class Hobbits {
 String name;

 public static void main(String[] args){

  Hobbits [] h = new Hobbits[3];
  int z = 0;

  while (z<4) {
   z = z + 1;
   h[z] = new Hobbits();
   h[z].name = "Bilbo";
   if (z == 1) {
    h[z].name = "Frodo";
   }
   if (z == 2){
    h[z].name = "Sam";
   }
   System.out.print(h[z].name+ " is a ");
   System.out.println("good Hobbit name");

  }
 }
}
</code>```

At runtime this program is giving the exception:

```<code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
</code>```

答:
Try this and it should work.</p>

```<code>int  z  =  -1
while   (z  < 2)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java program runtime error

Body:
public class Hobbits {
 String name;

 public static void main(String[] args){

  Hobbits [] h = new Hobbits[3];
  int z = 0;

  while (z<4) {
   z = z + 1;
   h[z] = new Hobbits();
   h[z].name = "Bilbo";
   if (z == 1) {
    h[z].name = "Frodo";
   }
   if (z == 2){
    h[z].name = "Sam";
   }
   System.out.print(h[z].name+ " is a ");
   System.out.println("good Hobbit name");

  }
 }
}

At runtime this program is giving the exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

Body:
Try this and it should work.

int  z  =  -1
while   (z  < 2)

ContentLicense: CC BY-SA 3.0


问:
getting cypress to work with a plugin via docker, also showing different version
I'll got a reproducible repo here: https://github.com/opyate/cypress-weirdness

We're using Cypress 9.1.1 and I'm trying to run the tests with:

```<code>docker-compose up --exit-code-from cypress
</code>```

But it has an error, and the weirdest bit is this:

```<code>Error: EACCES: permission denied, mkdir '/root/.cache/Cypress/9.4.1'
</code>```

But I'm not even using 9.4.1 anywhere.

I would greatly appreciate some pointers to make this work, and even clean it up, or use latest Cypress (which I've tried, with its own EACCESS errors...).

(I've also asked this in the Discord.)

答:
This commit fixes it.

I install cypress-file-upload inside the container in /opt, then mount my tests in /opt/e2e.

NPM then looks recursively for the dependency in these places until it finds it:

```<code>/opt/e2e/cypress/support/package.json
/opt/e2e/cypress/support/node_modules
/opt/e2e/cypress/node_modules
/opt/e2e/node_modules
/opt/node_modules        # <---- finds the dep here
/node_modules
</code>```

This setup has the added benefit of not polluting your host with node_nodules, package.json and package-lock.json.

No idea why 9.4.1 shows up in a 9.1.1 build, but I also upgraded Cypress to 9.4.1 and all seems to be working fine.

Body:
I'll got a reproducible repo here: https://github.com/opyate/cypress-weirdness

We're using Cypress 9.1.1 and I'm trying to run the tests with:

docker-compose up --exit-code-from cypress

But it has an error, and the weirdest bit is this:

Error: EACCES: permission denied, mkdir '/root/.cache/Cypress/9.4.1'

But I'm not even using 9.4.1 anywhere.

I would greatly appreciate some pointers to make this work, and even clean it up, or use latest Cypress (which I've tried, with its own EACCESS errors...).

(I've also asked this in the Discord.)

Body:
This commit fixes it.

I install cypress-file-upload inside the container in /opt, then mount my tests in /opt/e2e.

NPM then looks recursively for the dependency in these places until it finds it:

/opt/e2e/cypress/support/package.json
/opt/e2e/cypress/support/node_modules
/opt/e2e/cypress/node_modules
/opt/e2e/node_modules
/opt/node_modules        # <---- finds the dep here
/node_modules

This setup has the added benefit of not polluting your host with node_nodules, package.json and package-lock.json.

No idea why 9.4.1 shows up in a 9.1.1 build, but I also upgraded Cypress to 9.4.1 and all seems to be working fine.


问:
What is wrong with the 'when' clause?
```<code>CREATE TRIGGER UPDATE_CAR_DETALS
AFTER UPDATE ON BOOKING_DETALS
FOR EACH ROW
 WHEN (IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> 'NULL' OR
  NEW.BOOKING_STATUS ='C')
</code>```

答:
Multi statements in triggers need a BEGIN and END

Also when you use query tabs you need also DELIMITER

CASE WHEN you would use if you have multiple choices, but you use better IF THEN

```<code>DELIMITER $$
CREATE TRIGGER UPDATE_CAR_DETALS
AFTER UPDATE ON BOOKING_DETALS
FOR EACH ROW
BEGIN
    IF (IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> 'NULL' OR NEW.BOOKING_STATUS ='C') then
        BEGIN
            IF NEW.BOOKING_STATUS ='C' THEN
                UPDATE CAR SET AVAILABILITY_FLAG = 'A' , LOC_ID = NEW.PICKUP_LOC
                WHERE REGISTRATION_NUMBER = NEW.REG_NUM;
            ELSE
                IF IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> NULL THEN

                    UPDATE CAR SET AVAILABILITY_FLAG = 'A' , LOC_ID = NEW.DROP_LOC, MILEAGE = MILEAGE+GET_MILEAGE
                    WHERE REGISTRATION_NUMBER = NEW.REG_NUM;
                END IF;
            END IF;
        END;
    END IF;
END;
DELIMITER ;
</code>```

Title: What is wrong with the 'when' clause?

Body:
Multi statements in triggers need a BEGIN and END

Also when you use query tabs you need also DELIMITER

CASE WHEN you would use if you have multiple choices, but you use better IF THEN

DELIMITER $$
CREATE TRIGGER UPDATE_CAR_DETALS
AFTER UPDATE ON BOOKING_DETALS
FOR EACH ROW
BEGIN
    IF (IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> 'NULL' OR NEW.BOOKING_STATUS ='C') then
        BEGIN
            IF NEW.BOOKING_STATUS ='C' THEN
                UPDATE CAR SET AVAILABILITY_FLAG = 'A' , LOC_ID = NEW.PICKUP_LOC
                WHERE REGISTRATION_NUMBER = NEW.REG_NUM;
            ELSE
                IF IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME),NULL) <> NULL THEN

                    UPDATE CAR SET AVAILABILITY_FLAG = 'A' , LOC_ID = NEW.DROP_LOC, MILEAGE = MILEAGE+GET_MILEAGE
                    WHERE REGISTRATION_NUMBER = NEW.REG_NUM;
                END IF;
            END IF;
        END;
    END IF;
END;
DELIMITER ;


问:
Test train data split - Machine learning
I am trying to do some test train split (90% and 10%) and used below query

X_train, X_test, y_train, y_test = train_test_split(pdf.drop(columns = list(set(cols_not_used).union(set(['RANK'])))) , pdf['RANK'], random_state = 13, train_size = 0.9)

But in my dataframe I have "date" column and would like to split train and test based on date.
i.e., test data as latest 3 months information and the rest as train dataset.

Please let me know how that can be done.

答:
Not sure if this is the best way to proceed, but you can sort the data by time.

```<code>df = df.sort_values(by="date")
</code>```

After sorting it by time you can create your train test set:

```<code>import numpy as np
train_set, test_set = np.split(data, [int(0.9 *len(df))])
</code>```

The next step is to simply split between your predictory and explanatory variables:

```<code>xtrain = train_set.drop('Survived', axis=1)
ytrain = train_set['Survived']
xtest = test_set.drop('Survived', axis=1)
ytest = test_set['Survived']
</code>```

Body:
Not sure if this is the best way to proceed, but you can sort the data by time.

df = df.sort_values(by="date")

After sorting it by time you can create your train test set:

import numpy as np
train_set, test_set = np.split(data, [int(0.9 *len(df))])

The next step is to simply split between your predictory and explanatory variables:

xtrain = train_set.drop('Survived', axis=1)
ytrain = train_set['Survived']
xtest = test_set.drop('Survived', axis=1)
ytest = test_set['Survived']


问:
AWK: Help on transforming data table
I have the following file called in.txt:

```<code>2020-01-01  fruit   banana  3.4
2020-03-02  alcohol smirnov 26.99
2020-03-10  fruit   orange  4.20
2020-04-03  fruit   orange  4.20
2021-09-01  alcohol beer    6.00
2021-08-03  fruit   mango   6.99
2022-01-01  fruit   orange  4.30
2022-03-04  alcohol beer    6.00
2022-03-03  alcohol beer    6.00
2022-04-01  fruit   mango   7.20
</code>```

I want to transform the file so it reads something like this:

```<code>                2020-01-01      2021-01-01      2022-01-01
                -2020-12-31     -2021-12-31     -2022-12-31
fruit   banana  3.40             0.00            0.00
        orange  8.40            0.00            4.30
        mango   0.00            6.99            7.20

Subt            11.80           6.99            11.50

alcohol beer    0.00            6.00            12.00
        smirnov 26.99           0.00            0.00

Subt            26.99           6.00            12.00

Total           38.59           12.99           23.50
</code>```

I have started writing the following script but am stuck on how to approach this. How can I display totals columns side by side. The other problem is that this is just dummy data. I have many different categories other than fruit and alcohol and it seems wrong to write if statements and for-loops for each one. Also how can I print fruit and alcohol out just once rather than for every iteration of column 3 and bring the date range to the top. Help is much appreciated.

```<code>#!/usr/bin/env bash

awk '

        BEGIN{
        FS=OFS="\t";
        }

        {
        if ($2 ~ fruit && $1 >= "2020-01-01" && $1 <= "2020-12-31") {
                        a[$3]+=$4;
                        sa+=$4;
                }
        }

        END {
        PROCINFO["sorted_in"]="@ind_str_asc";
        for (i in a) {
                        print "fruit", i, a[i]
                }
        }

' "${@:--}"
</code>```

答:
I believe the following piece of awk code is a good start. The remaining part to do is just some cleanup and some extra code for the sums.

```<code>BEGIN{
   # how many divisions per year
   n=1
   # initialisation of some variables
   tmax=0;tmin=999999; ymax=qmax=0;ymin=9999;qmin=99
}
# convert date to quarter,trim,half
{ y=$1+0; q=(substr($1,6,7)+0)%n}
# compute min max time
(y*100+q < tmin) { ymin=y;qmin=q;tmin=y*100+q }
(y*100+q > tmax) { ymax=y;qmax=q;tmax=y*100+q }
# Create arrays that keep track of everything
# a : prices by year,q,category and element
# b : just a list of categories, eg fruit
# c : just a list of elements and the category it belongs to.
{ a[y,q,$2,$3]=$4; b[$2]; c[$3]=$2 }
END{
   # loop over categories (eg fruit)
   for(i in b) {
     # loop over elemnts
     for(j in c) {
        # exclude elements that do not belong to category
        if (i!=c[j]) continue
        s=i OFS j;
        # loop over the time
        for (y=ymin;y<=ymax;y++) {
          for (q=0;q<n;++q) {
             if (y*100+q < tmin) continue
             if (y*100+q > tmax) continue
             s=s OFS a[y,q,i,j]+0
          }
        }
        print s
     }
   }
}
</code>```

This currently outputs:

```<code>alcohol beer 0 6 6
alcohol smirnov 26.99 0 0
fruit orange 4.2 0 4.3
fruit mango 0 6.99 7.2
fruit banana 3.4 0 0
</code>```

Title: AWK: Help on transforming data table

Body:
I have the following file called in.txt:

2020-01-01  fruit   banana  3.4
2020-03-02  alcohol smirnov 26.99
2020-03-10  fruit   orange  4.20
2020-04-03  fruit   orange  4.20
2021-09-01  alcohol beer    6.00
2021-08-03  fruit   mango   6.99
2022-01-01  fruit   orange  4.30
2022-03-04  alcohol beer    6.00
2022-03-03  alcohol beer    6.00
2022-04-01  fruit   mango   7.20

I want to transform the file so it reads something like this:

                2020-01-01      2021-01-01      2022-01-01
                -2020-12-31     -2021-12-31     -2022-12-31
fruit   banana  3.40             0.00            0.00
        orange  8.40            0.00            4.30
        mango   0.00            6.99            7.20

Subt            11.80           6.99            11.50

alcohol beer    0.00            6.00            12.00
        smirnov 26.99           0.00            0.00

Subt            26.99           6.00            12.00

Total           38.59           12.99           23.50

I have started writing the following script but am stuck on how to approach this. How can I display totals columns side by side. The other problem is that this is just dummy data. I have many different categories other than fruit and alcohol and it seems wrong to write if statements and for-loops for each one. Also how can I print fruit and alcohol out just once rather than for every iteration of column 3 and bring the date range to the top. Help is much appreciated.

#!/usr/bin/env bash

awk '

        BEGIN{
        FS=OFS="\t";
        }

        {
        if ($2 ~ fruit && $1 >= "2020-01-01" && $1 <= "2020-12-31") {
                        a[$3]+=$4;
                        sa+=$4;
                }
        }

        END {
        PROCINFO["sorted_in"]="@ind_str_asc";
        for (i in a) {
                        print "fruit", i, a[i]
                }
        }

' "${@:--}"

Body:
I believe the following piece of awk code is a good start. The remaining part to do is just some cleanup and some extra code for the sums.

BEGIN{
   # how many divisions per year
   n=1
   # initialisation of some variables
   tmax=0;tmin=999999; ymax=qmax=0;ymin=9999;qmin=99
}
# convert date to quarter,trim,half
{ y=$1+0; q=(substr($1,6,7)+0)%n}
# compute min max time
(y*100+q < tmin) { ymin=y;qmin=q;tmin=y*100+q }
(y*100+q > tmax) { ymax=y;qmax=q;tmax=y*100+q }
# Create arrays that keep track of everything
# a : prices by year,q,category and element
# b : just a list of categories, eg fruit
# c : just a list of elements and the category it belongs to.
{ a[y,q,$2,$3]=$4; b[$2]; c[$3]=$2 }
END{
   # loop over categories (eg fruit)
   for(i in b) {
     # loop over elemnts
     for(j in c) {
        # exclude elements that do not belong to category
        if (i!=c[j]) continue
        s=i OFS j;
        # loop over the time
        for (y=ymin;y<=ymax;y++) {
          for (q=0;q<n;++q) {
             if (y*100+q < tmin) continue
             if (y*100+q > tmax) continue
             s=s OFS a[y,q,i,j]+0
          }
        }
        print s
     }
   }
}

This currently outputs:

alcohol beer 0 6 6
alcohol smirnov 26.99 0 0
fruit orange 4.2 0 4.3
fruit mango 0 6.99 7.2
fruit banana 3.4 0 0


问:
Auto Formatting adding text on VS Code
Working on a shared project and my coworker created a new branch with an updated npm package (@mui/material from @material-ui/core). When I pull his branch and run npm install everything installs and works correctly. But now if I make a change to a file and then save (format on save is turned on), all my imports get formatted with value before them ex: import React from 'react' becomes import value React from 'react'. Not sure what to make of this because updating MUI shouldn't have changed anything related to formatting. He does not experience this problem.

We utilize ESLint v2.2.2 and Prettier - Code formatter v9.1.0  extensions in VS Code.

.eslintrc.json

```<code>  "env": {
    "browser": true,
    "es2020": true,
    "jest": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended", "react-app"],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 11,
    "sourceType": "module"
  },
  "plugins": ["react", "prettier"],
  "rules": {
    "react/prop-types": "off"
  }
}
</code>```

.prettierrc

```<code>{
  "singleQuote": true
}
</code>```

local settings

```<code>{
  "editor.formatOnSave": true,
  "eslint.format.enable": true,
  "javascript.updateImportsOnFileMove.enabled": "always",
  "terminal.integrated.tabs.enabled": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "workbench.startupEditor": "none",
  "git.confirmSync": false,
  "git.suggestSmartCommit": false,
  "typescript.updateImportsOnFileMove.enabled": "always"
}
</code>```

答:
I had this same issue after updating some yarn package versions.

For me, simply quitting VS Code and launching it again solved the problem.

Title: Auto Formatting adding text on VS Code

Body:
Working on a shared project and my coworker created a new branch with an updated npm package (@mui/material from @material-ui/core). When I pull his branch and run npm install everything installs and works correctly. But now if I make a change to a file and then save (format on save is turned on), all my imports get formatted with value before them ex: import React from 'react' becomes import value React from 'react'. Not sure what to make of this because updating MUI shouldn't have changed anything related to formatting. He does not experience this problem.

We utilize ESLint v2.2.2 and Prettier - Code formatter v9.1.0  extensions in VS Code.

.eslintrc.json

  "env": {
    "browser": true,
    "es2020": true,
    "jest": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended", "react-app"],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 11,
    "sourceType": "module"
  },
  "plugins": ["react", "prettier"],
  "rules": {
    "react/prop-types": "off"
  }
}

.prettierrc

{
  "singleQuote": true
}

local settings

{
  "editor.formatOnSave": true,
  "eslint.format.enable": true,
  "javascript.updateImportsOnFileMove.enabled": "always",
  "terminal.integrated.tabs.enabled": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "workbench.startupEditor": "none",
  "git.confirmSync": false,
  "git.suggestSmartCommit": false,
  "typescript.updateImportsOnFileMove.enabled": "always"
}


问:
Difference between Object.assign and just assign
I would like to know the difference between this:

```<code>Object.assign(otherObject, {
  someNewProperty: ''
});
</code>```

and

```<code>otherObject.someNewProperty = '';
</code>```

And.. which one is faster?

Thanks.

答:
There is another important thing to show here about the differences between assign directly and using Object.assign(actually, not exactly a difference, but a important thing to be aware).

If you have a Object that's assigned to another variable in JS, like this:

```<code>const a = { a: 1 }
const b = a
</code>```

then, you decided to use Object.assign to change the value in a and assign to another variable(d), you will change the value in b as well(even you not assigning the Object.assign return to a, in this example let's assign to a new variable d).

```<code>const d = Object.assign(a, { a: 2 })
console.log(a) // { a: 2 }
console.log(b) // { a: 2 }
console.log(d) // { a: 2 }
</code>```

Basically, it's important to know that Object.assign will mutate the target object as well all variables pointing to it.

Now, if you use directly the assignment to d, it'll not change the value in a(and in b as well will not change).

```<code>const d = { ...a, ...{ a: 2 }}
console.log(a) // { a: 1 }
console.log(b) // { a: 1 }
console.log(d) // { a: 2 }
</code>```

Body:
I would like to know the difference between this:

Object.assign(otherObject, {
  someNewProperty: ''
});

and

otherObject.someNewProperty = '';

And.. which one is faster?

Thanks.

Body:
There is another important thing to show here about the differences between assign directly and using Object.assign(actually, not exactly a difference, but a important thing to be aware).

If you have a Object that's assigned to another variable in JS, like this:

const a = { a: 1 }
const b = a

then, you decided to use Object.assign to change the value in a and assign to another variable(d), you will change the value in b as well(even you not assigning the Object.assign return to a, in this example let's assign to a new variable d).

const d = Object.assign(a, { a: 2 })
console.log(a) // { a: 2 }
console.log(b) // { a: 2 }
console.log(d) // { a: 2 }

Basically, it's important to know that Object.assign will mutate the target object as well all variables pointing to it.

Now, if you use directly the assignment to d, it'll not change the value in a(and in b as well will not change).

const d = { ...a, ...{ a: 2 }}
console.log(a) // { a: 1 }
console.log(b) // { a: 1 }
console.log(d) // { a: 2 }


问:
Excel 365 Getting a Drop down with right Parent for Child
I have a family tree with 4 generations. I have put them into named groups of Parent and Child, for a child in 1st generation becomes a Parent in 2nd generation and so forth.

I can easily, pending some rules, decide what Parent resides in 1st generation and a list of  Children from Parent.

When you work with this for a while you start to recognise a system of Children in the 4th generation, and you then just select that Child and from that choise I can then select (XLOOKUP, VLOOKUP) who is the Parent of selected Child.

My problem comes when my children Peter, Joe, Beatrice, Jim, Joe suddenly gets an overlap. The 2 Joes which normally have 2 different parents now only have 1, due to LOOKUP only finding the first solution.

I can easily make a FILTER of which Parents are linked to a Child, and list them seperately but I need that FILTER inside a Data Validation (Drop Down). I have tried the INDIRECT solution and it didn't work as intended. FILTER(Parent;Child=D5)

The function I'm using right now is XLOOKUP(D1;Child;Parent;"not found";0;1) , that works brilliantly when the family tree is straight up and clear. I select the Child, it finds the Parent, which in turn find the (Grand)Parent, etc. When I do find a Joe it returns the Parent of the 1st Joe in the system, messing up the family trees.

Optimally I would have a Drop Down of the possible Parents of this Joe and then the family tree would continue.

(There's a client and level of IP involved. The specific word is 'Other' and several trees are using the word to describe a group of products. Due to IP I can't change any names or make it Joe 1, Joe 2, etc)

I have 1000s of rows of this, when I've selected a family/product-line for a row that row is done. I can't feasible allocate that Drop Down out. The filter needs to be incl in the Drop Down/Data validation menu. Each time the client returns with a new Workbook, I'd prefer I just copy-paste the logic and easily covering the 1000s of rows.

4 generations and 5 families. If for each generation there'd be a drop down of Parents for a Child, that would solve for those families with a Joe.

答:
```<code>TRANSPOSE(FILTER(Parent;Child=D1))
</code>```

Actually the solution was a support outsider, but not column, but rather row wise.

But what about the indetermined length of possible parents?

That is where the spill functionality comes in. Data validation with just the first cell, and reference finished with a #. The # makes it a spill. =C1#

But a Data validation is normally vertical, how do you turn it?

Excel does that by auto.

Body:
TRANSPOSE(FILTER(Parent;Child=D1))

Actually the solution was a support outsider, but not column, but rather row wise.

But what about the indetermined length of possible parents?

That is where the spill functionality comes in. Data validation with just the first cell, and reference finished with a #. The # makes it a spill. =C1#

But a Data validation is normally vertical, how do you turn it?

Excel does that by auto.


问:
CardBackgroundColor cannot work while give cardElevation="0dp"
When I'm giving CardView to app:CardBackgroudColor="@color/black" it's work

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.cardview.widget.CardView
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:layout_gravity="center"
        android:layout_margin="2dp"
        app:cardCornerRadius="20dp"/>
    <androidx.cardview.widget.CardView
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_gravity="center"
        app:cardBackgroundColor="@color/black"
        app:cardCornerRadius="19dp"/>
</FrameLayout>
</code>```

CardView img 1

But, When I'm giving CardView to app:CardBackgroudColor="@color/black" and app:cardElevation="0dp" card background color remove from the card.

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.cardview.widget.CardView
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:layout_gravity="center"
        android:layout_margin="2dp"
        app:cardCornerRadius="20dp"/>
    <androidx.cardview.widget.CardView
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_gravity="center"
        app:cardElevation="0dp"
        app:cardBackgroundColor="@color/black"
        app:cardCornerRadius="19dp"/>
</FrameLayout>
</code>```

CardView img 2

答:
It's Because of Elevation and z-index, by default card view has 4dp elevation and that's the reason the card view place on top of the other views, if you have a view that has 4dp elevation and another view that has 6dp the view with 6dp elevation always be on top of other views, when you set the elevation 0 to card view, the other view that has elevation place on top of this card view. to solve this problem, you have 2 options:

1- make your both card view elevation to 0dp

2- wrap your second card view that has black background in first card view
for example:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.cardview.widget.CardView
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:layout_gravity="center"
        android:layout_margin="2dp"
        app:cardCornerRadius="20dp">

        <androidx.cardview.widget.CardView
            android:layout_width="38dp"
            android:layout_height="38dp"
            android:layout_gravity="center"
            app:cardElevation="0dp"
            app:cardBackgroundColor="@color/black"
            app:cardCornerRadius="19dp"/>

      <androidx.cardview.widget.CardView/>
</FrameLayout>
</code>```

Body:
When I'm giving CardView to app:CardBackgroudColor="@color/black" it's work

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.cardview.widget.CardView
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:layout_gravity="center"
        android:layout_margin="2dp"
        app:cardCornerRadius="20dp"/>
    <androidx.cardview.widget.CardView
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_gravity="center"
        app:cardBackgroundColor="@color/black"
        app:cardCornerRadius="19dp"/>
</FrameLayout>

CardView img 1

But, When I'm giving CardView to app:CardBackgroudColor="@color/black" and app:cardElevation="0dp" card background color remove from the card.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.cardview.widget.CardView
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:layout_gravity="center"
        android:layout_margin="2dp"
        app:cardCornerRadius="20dp"/>
    <androidx.cardview.widget.CardView
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_gravity="center"
        app:cardElevation="0dp"
        app:cardBackgroundColor="@color/black"
        app:cardCornerRadius="19dp"/>
</FrameLayout>

CardView img 2

Body:
It's Because of Elevation and z-index, by default card view has 4dp elevation and that's the reason the card view place on top of the other views, if you have a view that has 4dp elevation and another view that has 6dp the view with 6dp elevation always be on top of other views, when you set the elevation 0 to card view, the other view that has elevation place on top of this card view. to solve this problem, you have 2 options:

1- make your both card view elevation to 0dp

2- wrap your second card view that has black background in first card view
for example:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.cardview.widget.CardView
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:layout_gravity="center"
        android:layout_margin="2dp"
        app:cardCornerRadius="20dp">

        <androidx.cardview.widget.CardView
            android:layout_width="38dp"
            android:layout_height="38dp"
            android:layout_gravity="center"
            app:cardElevation="0dp"
            app:cardBackgroundColor="@color/black"
            app:cardCornerRadius="19dp"/>

      <androidx.cardview.widget.CardView/>
</FrameLayout>


问:
Why the size of the const char *arr is greater then const char arr[]?
I am using the xc32 compiler for the microchip pic32 microcontroller.

The program memory size (for the startup, vectors and etc..) is 1656 bytes.

```<code>#include <plib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>

//if I use const char array[] for string literal then the size of the program memory increased
//equal to the string length(only 12 bytes)

//const char array[] = "Hello World"; //program mem size(1668 0x684) bytes

//but in this case size increased 28 bytes
//const char *array = "Hello World";  //program mem size(1684 0x694) bytes

int main {

    while(1);
}
</code>```

for optimization purposes:

which one is good(for both speed and size)?

#define STRLIT "HELLO WORLD"

const char *strlit = "HELLO WORLD";

const char arr[] = "HELLO WORLD"

答:
There are differences between your 3 options:

#define STRLIT "HELLO WORLD" defines a preprocessor token: no code or data is generated in the executable, yet every instance of STRLIT in the code will be replaced with the string literal at compile time, which may generate more data or not.

const char arr[] = "HELLO WORLD" defines a named array of char of size 12 bytes, initialized and null terminated. It takes 12 bytes in the executable read-only data segment, which may increase the size of the executable by 12 bytes or more depending on alignment constraints in the executable format.

const char *strlit = "HELLO WORLD"; defined both a string literal (a constant array of size 12 bytes) and a modifiable pointer strlit initialized to point to the string literal. This should at least use 4 bytes more in the executable (the size of a pointer on your 32-bit target system), but may increase the size of the executable by more than 4 bytes again depending on alignment constraints in the executable format.

Note also that depending on compiler options, there might be debugging data present in the executable file.

Body:
I am using the xc32 compiler for the microchip pic32 microcontroller.

The program memory size (for the startup, vectors and etc..) is 1656 bytes.

#include <plib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>

//if I use const char array[] for string literal then the size of the program memory increased
//equal to the string length(only 12 bytes)

//const char array[] = "Hello World"; //program mem size(1668 0x684) bytes

//but in this case size increased 28 bytes
//const char *array = "Hello World";  //program mem size(1684 0x694) bytes

int main {

    while(1);
}

for optimization purposes:

which one is good(for both speed and size)?

#define STRLIT "HELLO WORLD"

const char *strlit = "HELLO WORLD";

const char arr[] = "HELLO WORLD"


问:
What if I only want one class to access my form's controls?
I implemented an Undo/Redo system in my application but because it is a separate class from my main form it cannot access any of its controls. Currently I'm passing every control that needs undoing or redoing in to the class's constructor but it is quickly becoming one of the largest constructors in my project.

It'd be nice if only this class were allowed to access to my form's controls. If I pass in the form to the constructor I still cannot access the control's because they are all private. I suppose the simple solution would be to make all the controls I need to use public but what is the ideal or elegant solution?

P.S. I have already read about the technique of having a public property for everything required and passing in the form to the constructor but that will end up being quite a bit of properties and the solution does not seem very applicable in this situation.

Thanks!

答:
Very, very, very rarely is it good practice to pass UI controls or forms to a class. This is just a maintenance/dependency nightmare in the making.

You don't want your class to know diddly about your form's controls, all it should care about is its data.

Your form knows itself, knows the data it needs to save and how to restore it to the proper controls.

If all you are looking for is undo/redo capability, you want to look into the Memento design pattern.  You don't need to make a fully propertied class unless you have some other business need for it.

For the memento pattern.

A simple object holds the state you want to preserve....

```<code> internal class Memento: IMemento
    {
        private object _state;

        public void SetState(object state)
        {
            _state = state;
        }

        public object GetState()
        {
            return _state;
        }
    }
</code>```

A caretaker object manages the mementos for the form.

```<code> public class Caretaker
    {
        private Dictionary<int,IMemento> _mementos = new Dictionary<int,IMemento>();
        public void AddMemento(int tag, IMemento memento)
        {
            _mementos.Add(tag, memento);
        }

        public IMemento GetMemento(int tag)
        {

            if (_mementos.ContainsKey(tag))
            {
                return _mementos[tag];
            }

            return null;
        }
    }
</code>```

The form saves a new memento to the Caretaker after changing state. We take advantage of the extreme flexibility of the object class...

```<code>private void SaveMemento()
{
            Memento memento = new Memento();
            string[] state = {TextBox1.Text, TextBox2.Text};//expand as needed
            memento.SetState(state);
            _caretaker.AddMemento(_currentStateIndex, memento);
            _currentStateIndex++;
}
</code>```

The form reverts as needed.

```<code>private void RevertToPreviousState()
        {
            Memento memento = (Memento)_caretaker.GetMemento(--_currentStateIndex);
            string[] state = (string[]) memento.GetState();
            TextBox1.Text = state[0];
            TextBox2.Text = state[1];//expand as needed

        }
</code>```

Forgot IMemento --just a tagging interface, in case you want to put the caretaker in another assembly for full Memento pattern implementation.

```<code>public interface IMemento
    {
    }
</code>```

Body:
Very, very, very rarely is it good practice to pass UI controls or forms to a class. This is just a maintenance/dependency nightmare in the making.

You don't want your class to know diddly about your form's controls, all it should care about is its data.

Your form knows itself, knows the data it needs to save and how to restore it to the proper controls.

If all you are looking for is undo/redo capability, you want to look into the Memento design pattern.  You don't need to make a fully propertied class unless you have some other business need for it.

For the memento pattern.

A simple object holds the state you want to preserve....

 internal class Memento: IMemento
    {
        private object _state;

        public void SetState(object state)
        {
            _state = state;
        }

        public object GetState()
        {
            return _state;
        }
    }

A caretaker object manages the mementos for the form.

 public class Caretaker
    {
        private Dictionary<int,IMemento> _mementos = new Dictionary<int,IMemento>();
        public void AddMemento(int tag, IMemento memento)
        {
            _mementos.Add(tag, memento);
        }

        public IMemento GetMemento(int tag)
        {

            if (_mementos.ContainsKey(tag))
            {
                return _mementos[tag];
            }

            return null;
        }
    }

The form saves a new memento to the Caretaker after changing state. We take advantage of the extreme flexibility of the object class...

private void SaveMemento()
{
            Memento memento = new Memento();
            string[] state = {TextBox1.Text, TextBox2.Text};//expand as needed
            memento.SetState(state);
            _caretaker.AddMemento(_currentStateIndex, memento);
            _currentStateIndex++;
}

The form reverts as needed.

private void RevertToPreviousState()
        {
            Memento memento = (Memento)_caretaker.GetMemento(--_currentStateIndex);
            string[] state = (string[]) memento.GetState();
            TextBox1.Text = state[0];
            TextBox2.Text = state[1];//expand as needed

        }

Forgot IMemento --just a tagging interface, in case you want to put the caretaker in another assembly for full Memento pattern implementation.

public interface IMemento
    {
    }


问:
How to merge jacoco reports of two different version - 0.7.9 and 0.8.7
I have execs report of two different jacoco plugins from two different projects -  0.7.9 and 0.8.7 version of jacoco. I want to merge and show a single report. Is it possible?</p>

答:
java -jar jacococli.jar report project1/jacoco.exec project2/jacoco.exec --classfiles project1/classes --classfiles project2/classes --sourcefiles project1/src --sourcefiles project2/src --html report

Using this command we can do that and it will support from version 0.7.5 to the latest. 0.7.4 and lower are incompatible.


问:
Resulting array is zero when jax.numpy is used
I wrote the code below using numpy and got the correct output as shown in program 1. However when I switch to jax.numpy as jnp (in Program 2) the resulting output is an array of zeros. My MWE is shown below. I would like to know where I got the computation wrong?
PS: the codes were run in different python files.</p>
```<code>#Program 1 (using numpy as np):
import numpy as np

num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = np.where(np.isinf(smf), 1, num_cols)
kvals = np.insert(kvals, 0, 0)
kvals = np.cumsum(kvals)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))

for i in range(num_rows):
    par0_col[kvals[i]:kvals[i+1]] = par[i, :kvals[i+1]-kvals[i]]
    lb_col[kvals[i]:kvals[i+1]] = lb[i]
    ub_col[kvals[i]:kvals[i+1]] = ub[i]

arr_1 = np.zeros(shape = (num_rows, num_cols))
arr_2 = np.zeros(shape = (num_rows, num_cols))

par_log = np.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

k = 0
for i in range(num_rows):

    arr_1[i, :] = (par_log[kvals[i]:kvals[i+1]])
    arr_2[i, :] = 10**par_log[kvals[i]:kvals[i+1]]

print(arr_1)

# [[0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.        ]
#  [0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361]
#  [0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996]
#  [0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336]
#  [0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608]]

# Program 2 (using jax.numpy as jnp):

import jax
import jax.numpy as jnp
jax.config.update("jax_enable_x64", True)

smf = jnp.array([jnp.inf, 0.1, 0.1, 0.1, 0.1])
par_init = jnp.array([1.0,2.0,3.0,4.0,5.0])
lb = jnp.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = jnp.array([10.0, 10.0, 10.0, 10.0, 10.0])
par = jnp.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = jnp.where(jnp.isinf(smf), 1, num_cols)
kvals = jnp.insert(kvals, 0, 0)
kvals = jnp.cumsum(kvals)

par0_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
lb_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
ub_col = jnp.zeros(num_rows*num_cols- (num_cols-1) * jnp.sum(jnp.isinf(smf)))

for i in range(num_rows):
    par0_col.at[kvals[i]:kvals[i+1]].set(par[i, :kvals[i+1]-kvals[i]])
    lb_col.at[kvals[i]:kvals[i+1]].set(lb[i])
    ub_col.at[kvals[i]:kvals[i+1]].set(ub[i])

arr_1 = jnp.zeros(shape = (num_rows, num_cols))
arr_2 = jnp.zeros(shape = (num_rows, num_cols))

par_log = jnp.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

for i in range(num_rows):

    arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
    arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])

print(arr_1)

# #[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

</code>```

答: Oh I already figured it out. I needed to make an explicit assignment.</p>

Body:
I wrote the code below using numpy and got the correct output as shown in program 1. However when I switch to jax.numpy as jnp (in Program 2) the resulting output is an array of zeros. My MWE is shown below. I would like to know where I got the computation wrong?
PS: the codes were run in different python files.

#Program 1 (using numpy as np):
import numpy as np

num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = np.where(np.isinf(smf), 1, num_cols)
kvals = np.insert(kvals, 0, 0)
kvals = np.cumsum(kvals)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))

for i in range(num_rows):
    par0_col[kvals[i]:kvals[i+1]] = par[i, :kvals[i+1]-kvals[i]]
    lb_col[kvals[i]:kvals[i+1]] = lb[i]
    ub_col[kvals[i]:kvals[i+1]] = ub[i]

arr_1 = np.zeros(shape = (num_rows, num_cols))
arr_2 = np.zeros(shape = (num_rows, num_cols))

par_log = np.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

k = 0
for i in range(num_rows):

    arr_1[i, :] = (par_log[kvals[i]:kvals[i+1]])
    arr_2[i, :] = 10**par_log[kvals[i]:kvals[i+1]]

print(arr_1)

# [[0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.        ]
#  [0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361]
#  [0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996]
#  [0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336]
#  [0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608]]

# Program 2 (using jax.numpy as jnp):

import jax
import jax.numpy as jnp
jax.config.update("jax_enable_x64", True)

smf = jnp.array([jnp.inf, 0.1, 0.1, 0.1, 0.1])
par_init = jnp.array([1.0,2.0,3.0,4.0,5.0])
lb = jnp.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = jnp.array([10.0, 10.0, 10.0, 10.0, 10.0])
par = jnp.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = jnp.where(jnp.isinf(smf), 1, num_cols)
kvals = jnp.insert(kvals, 0, 0)
kvals = jnp.cumsum(kvals)

par0_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
lb_col = jnp.zeros(num_rows*num_cols - (num_cols-1) * jnp.sum(jnp.isinf(smf)))
ub_col = jnp.zeros(num_rows*num_cols- (num_cols-1) * jnp.sum(jnp.isinf(smf)))

for i in range(num_rows):
    par0_col.at[kvals[i]:kvals[i+1]].set(par[i, :kvals[i+1]-kvals[i]])
    lb_col.at[kvals[i]:kvals[i+1]].set(lb[i])
    ub_col.at[kvals[i]:kvals[i+1]].set(ub[i])

arr_1 = jnp.zeros(shape = (num_rows, num_cols))
arr_2 = jnp.zeros(shape = (num_rows, num_cols))

par_log = jnp.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

for i in range(num_rows):

    arr_1.at[i, :].set((par_log[kvals[i]:kvals[i+1]]))
    arr_2.at[i, :].set(10**par_log[kvals[i]:kvals[i+1]])

print(arr_1)

# #[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]


问:
Getting No Activity found to handle Intent while using firebase auth SDK in android
I'm using firebase auth for the phone number, google, Facebook, and Apple in our android app. it's working perfectly in the live version, but sometimes getting crashes in firebase crashlytics as below, and also got few feedback from our customer like they can't be logged in due to this issue.

```<code>Fatal Exception: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://app-id.firebaseapp.com/... flg=0x50000000 (has extras) }
       at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2067)
       at android.app.Instrumentation.execStartActivity(Instrumentation.java:1727)
       at android.app.Activity.startActivityForResult(Activity.java:5409)
       at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:597)
       at android.app.Activity.startActivityForResult(Activity.java:5367)
       at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:583)
       at android.app.Activity.startActivity(Activity.java:5753)
       at android.app.Activity.startActivity(Activity.java:5706)
       at com.google.firebase.auth.internal.GenericIdpActivity.zza(com.google.firebase:firebase-auth@@20.0.4:12)
       at com.google.android.gms.internal.firebase-auth-api.zztw.zzb(com.google.firebase:firebase-auth@@20.0.4:7)
       at com.google.android.gms.internal.firebase-auth-api.zztw.onPostExecute(com.google.firebase:firebase-auth@@20.0.4:2)
       at android.os.AsyncTask.finish(AsyncTask.java:771)
       at android.os.AsyncTask.access$900(AsyncTask.java:199)
       at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loop(Looper.java:223)
       at android.app.ActivityThread.main(ActivityThread.java:7943)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:603)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
</code>```

答:
This problem was caused for firebase auth captcha.
To solve this problem please use the real devices don't use the emulators.

Body:
I'm using firebase auth for the phone number, google, Facebook, and Apple in our android app. it's working perfectly in the live version, but sometimes getting crashes in firebase crashlytics as below, and also got few feedback from our customer like they can't be logged in due to this issue.

Fatal Exception: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://app-id.firebaseapp.com/... flg=0x50000000 (has extras) }
       at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2067)
       at android.app.Instrumentation.execStartActivity(Instrumentation.java:1727)
       at android.app.Activity.startActivityForResult(Activity.java:5409)
       at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:597)
       at android.app.Activity.startActivityForResult(Activity.java:5367)
       at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:583)
       at android.app.Activity.startActivity(Activity.java:5753)
       at android.app.Activity.startActivity(Activity.java:5706)
       at com.google.firebase.auth.internal.GenericIdpActivity.zza(com.google.firebase:firebase-auth@@20.0.4:12)
       at com.google.android.gms.internal.firebase-auth-api.zztw.zzb(com.google.firebase:firebase-auth@@20.0.4:7)
       at com.google.android.gms.internal.firebase-auth-api.zztw.onPostExecute(com.google.firebase:firebase-auth@@20.0.4:2)
       at android.os.AsyncTask.finish(AsyncTask.java:771)
       at android.os.AsyncTask.access$900(AsyncTask.java:199)
       at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loop(Looper.java:223)
       at android.app.ActivityThread.main(ActivityThread.java:7943)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:603)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)


问:
What methods of ‘clearfix’ can I use?
I have the age-old problem of a div wrapping a two-column layout. My sidebar is floated, so my container div fails to wrap the content and sidebar.

```

There seem to be numerous methods of fixing the clear bug in Firefox:

overflow:auto

overflow:hidden

In my situation, the only one that seems to work correctly is the
 solution, which is a little bit scruffy. overflow:auto gives me nasty scrollbars, and overflow:hidden must surely have side effects.
Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox.

Which method currently available to us is the most robust?

答: I always float the main sections of my grid and apply clear: both; to the footer. That doesn't require an extra div or class.

OwnerDisplayName: Pickledegg

Title: What methods of ‘clearfix’ can I use?

Body:
I have the age-old problem of a div wrapping a two-column layout. My sidebar is floated, so my container div fails to wrap the content and sidebar.

There seem to be numerous methods of fixing the clear bug in Firefox:

overflow:auto

overflow:hidden

In my situation, the only one that seems to work correctly is the
 solution, which is a little bit scruffy. overflow:auto gives me nasty scrollbars, and overflow:hidden must surely have side effects.
Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox.

Which method currently available to us is the most robust?


问:
How to get all titles with child from one table
i have a table like this:

id
title
parent_id

1
title1
null

2
title2
1

3
title3
1

4
title4
2

5
title5
2

6
title6
3

i want to display all rows which have id in column parent_id so that the result is:

id
title

1
title1

2
title2

3
title3

答:
You can try to use EXISTS subquery

```<code>SELECT id,title
FROM T t1
WHERE EXISTS (
    SELECT 1
    FROM T tt
    WHERE tt.parent_id = t1.id
)
</code>```

sqlfiddle

Body:
You can try to use EXISTS subquery

SELECT id,title
FROM T t1
WHERE EXISTS (
    SELECT 1
    FROM T tt
    WHERE tt.parent_id = t1.id
)

sqlfiddle


问:
Detect user is outside the GoogleMap route (perpendicular distance to path)
I am creating a simple navigation application using GoogleMap.
When the user set the start location and destination location I am drawing the path using polylines.

If the user deviate from the path, I want to redraw the path based on current user location.

Problem I have is how to detect user is not in the current route?

I am using
https://maps.googleapis.com/maps/api/directions/json?
to get the directions.
Is there a function in that to detect whether user is outside the route?

I also have the list of coordinates used to draw the poly lines.
Can they be used to detect user moved outside the current route ?

Based on an example I found in web, I created this method. The example is not designed to for the map coordinates.
Function for finding the distance between a point and an edge in java

Is there a better way of doing this?

```<code>static double perpendicularDistance(LatLng point, LatLng start, LatLng end) {
double x = point.longitude;
double y = point.latitude;

double x1 = start.longitude;
double y1 = start.latitude;
double x2 = end.longitude;
double y2 = end.latitude;

double A = x - x1;
double B = y - y1;
double C = x2 - x1;
double D = y2 - y1;

double dot = A * C + B * D;
double len_sq = C * C + D * D;
double param = -1;
if (len_sq != 0) //in case of 0 length line
  param = dot / len_sq;

double xx, yy;

if (param < 0) {
  xx = x1;
  yy = y1;
} else if (param > 1) {
  xx = x2;
  yy = y2;
} else {
  xx = x1 + param * C;
  yy = y1 + param * D;
}

var dx = x - xx;
var dy = y - yy;
// one degree is equivalent to 111km approximately
return (sqrt(dx * dx + dy * dy)).abs() * 111000;
</code>```

}

答:
May be you need to get coordinates of user everytime he/she walks, and check if that coordinates lies in the list of coordinates which you have.
You can get location using https://pub.dev/packages/location.
These is just a thought, I can be wrong.</p>

Body:
I am creating a simple navigation application using GoogleMap.
When the user set the start location and destination location I am drawing the path using polylines.

If the user deviate from the path, I want to redraw the path based on current user location.

Problem I have is how to detect user is not in the current route?

I am using
https://maps.googleapis.com/maps/api/directions/json?
to get the directions.
Is there a function in that to detect whether user is outside the route?

I also have the list of coordinates used to draw the poly lines.
Can they be used to detect user moved outside the current route ?

Based on an example I found in web, I created this method. The example is not designed to for the map coordinates.
Function for finding the distance between a point and an edge in java

Is there a better way of doing this?

static double perpendicularDistance(LatLng point, LatLng start, LatLng end) {
double x = point.longitude;
double y = point.latitude;

double x1 = start.longitude;
double y1 = start.latitude;
double x2 = end.longitude;
double y2 = end.latitude;

double A = x - x1;
double B = y - y1;
double C = x2 - x1;
double D = y2 - y1;

double dot = A * C + B * D;
double len_sq = C * C + D * D;
double param = -1;
if (len_sq != 0) //in case of 0 length line
  param = dot / len_sq;

double xx, yy;

if (param < 0) {
  xx = x1;
  yy = y1;
} else if (param > 1) {
  xx = x2;
  yy = y2;
} else {
  xx = x1 + param * C;
  yy = y1 + param * D;
}

var dx = x - xx;
var dy = y - yy;
// one degree is equivalent to 111km approximately
return (sqrt(dx * dx + dy * dy)).abs() * 111000;

}


问:
Eclipse error when trying to open Eclipse Marketplace: Cannot open Eclipse Marketplace Cannot install remote marketplace locations
I am trying to install some dependencies on my Eclipse Oxygen when I suddenly hit this error. The full error message is:

```<code>Cannot open Eclipse Marketplace
Cannot install remote marketplace locations: Cannot complete request to http://marketplace.eclipse.org/catalogs/api/p: Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
Cannot complete request to http://marketplace.eclipse.org/catalogs/api/p: Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
The element type "link" must be terminated by the matching end-tag "</link>".
Received response begins with:

1: <!DOCTYPE html>
2:
3: <html lang="en">

Cannot complete request to http://marketplace.eclipse.org/catalogs/api/p: Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
The element type "link" must be terminated by the matching end-tag "</link>".
Received response begins with:

1: <!DOCTYPE html>
2:
3: <html lang="en">
</code>```

It was fine before. I started to see this error after I installed IBM WebSphere Application Server V8.5x Developer Tools for Oxygen. I am very new to Eclipse so I'm not sure how to debug this.

Yes I have internet and I have no antivirus installed (it's running in a CentOS VM). I also have tried resetting the network connection settings to default but its not working.

答:
Tried everything possible on the internet! Failed.
The issue is with our network only. Please check if you have any content filtering enabled on your network, URL blocker/filter, security-enabled that blocks certain keywords in URLs.
For me, It was Content Filtering enabled on my WiFi Router, which was blocking certain URLs.</p>

Body:
I am trying to install some dependencies on my Eclipse Oxygen when I suddenly hit this error. The full error message is:

Cannot open Eclipse Marketplace
Cannot install remote marketplace locations: Cannot complete request to http://marketplace.eclipse.org/catalogs/api/p: Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
Cannot complete request to http://marketplace.eclipse.org/catalogs/api/p: Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
The element type "link" must be terminated by the matching end-tag "</link>".
Received response begins with:

1: <!DOCTYPE html>
2:
3:

Cannot complete request to http://marketplace.eclipse.org/catalogs/api/p: Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
Invalid response content: The element type "link" must be terminated by the matching end-tag "</link>".
The element type "link" must be terminated by the matching end-tag "</link>".
Received response begins with:

1: <!DOCTYPE html>
2:
3:

It was fine before. I started to see this error after I installed IBM WebSphere Application Server V8.5x Developer Tools for Oxygen. I am very new to Eclipse so I'm not sure how to debug this.

Yes I have internet and I have no antivirus installed (it's running in a CentOS VM). I also have tried resetting the network connection settings to default but its not working.


问:
How to use @Viewbuilder and return view in swiftUi?
I have overlay with below code

```<code>.overlay(abcViewModel.isError ? AnyView(DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
    action()
    abcViewModel.isError = false
}, isDialogboxFirstButtonClicked: .constant(true))) :  AnyView(EmptyView()))
</code>```

I am trying to avoid use of Anyview and did below code but getting error as "Unknown attribute 'Viewbuilder'" and not sure how to return view in if case

```<code>private func getOverlayView() -> some View {
     if abcViewModel.isError {
          DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
              action()
              abcViewModel.isError = false
          }, isDialogboxFirstButtonClicked: .constant(true))
    } else {
       return EmptyView()
    }
}
</code>```

Kindly help me the best way for this

答:
You need to add @ViewBuilder to the computed property/function creating the overlay view.

```<code>@ViewBuilder
private var overlay: some View {
    if abcViewModel.isError {
        DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
             action()
             abcViewModel.isError = false
         }, isDialogboxFirstButtonClicked: .constant(true))
    } else {
       EmptyView()
    }
}
</code>```

and then pass this property to overlay

```<code>.overlay(overlay)
</code>```

Body:
I have overlay with below code

.overlay(abcViewModel.isError ? AnyView(DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
    action()
    abcViewModel.isError = false
}, isDialogboxFirstButtonClicked: .constant(true))) :  AnyView(EmptyView()))

I am trying to avoid use of Anyview and did below code but getting error as "Unknown attribute 'Viewbuilder'" and not sure how to return view in if case

private func getOverlayView() -> some View {
     if abcViewModel.isError {
          DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
              action()
              abcViewModel.isError = false
          }, isDialogboxFirstButtonClicked: .constant(true))
    } else {
       return EmptyView()
    }
}

Kindly help me the best way for this

Body:
You need to add @ViewBuilder to the computed property/function creating the overlay view.

@ViewBuilder
private var overlay: some View {
    if abcViewModel.isError {
        DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
             action()
             abcViewModel.isError = false
         }, isDialogboxFirstButtonClicked: .constant(true))
    } else {
       EmptyView()
    }
}

and then pass this property to overlay

.overlay(overlay)


问:
cv2 import error in virtual environment
I tried everything in the virtual environment, but again and again "no module named opencv". I checked the site packages folder and found that there is no cv2 folder, like I found numpy, pip folders; but there was 1 folder named:

```<code>cv2-1.0-py2.7.egg-info
</code>```

Now what should I do? Open CV 3.0 is not compatible with python 3.5.1 while there is this problem hindering me again and again for python 2.7. Please help!!

P.S. None of the solutions mentioned in the previous answers worked :/

Screenshot of Site-Packages

答: I found that once I activated the virtual environment, I had to select the virtual environment's Python Interpreter from the Command Palette and then it was able to locate OpenCV. Apparently, I hadn't selected any of the Python interpreters prior to this.</p>

Title: cv2 import error in virtual environment

Body:
I tried everything in the virtual environment, but again and again "no module named opencv". I checked the site packages folder and found that there is no cv2 folder, like I found numpy, pip folders; but there was 1 folder named:

cv2-1.0-py2.7.egg-info

Now what should I do? Open CV 3.0 is not compatible with python 3.5.1 while there is this problem hindering me again and again for python 2.7. Please help!!

P.S. None of the solutions mentioned in the previous answers worked :/

Screenshot of Site-Packages


问:
How do I create folders in ASP.NET in code behind?
I want to create dynamic folders at run time.  Folder names with be input via a TextBox and output will be displayed in a TreeView.

The form will submit if I enter the first folder name into textbox1 and click the "Add Folder" button.  When I submit multiple folders with the same name the output should be an indexed increment of the name. Eg. FooFolder, FooFolder(2), FooFolder(3), etc.

If I delete FooFolder(2) and then recreate a folder with the name FooFolder, the folder should be FooFolder(2), and if I create one more folder then it should be FooFolder(4).

For deletion one can select the particular folder from the TreeView which will be displayed in TextBox2 and click the "Remove Folder" button.

Here is my presentation code:

```<code><asp:Button ID="btnAddFolder" runat="server" Height="24px" Text="Add Folder"
        Width="148px" onclick="btnAddFolder_Click" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    <asp:Button ID="btnRemoveFolder" runat="server" Text="Remove Folder" />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer"
        NodeIndent="15">
        <ParentNodeStyle Font-Bold="False" />
        <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
        <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False"
            HorizontalPadding="0px" VerticalPadding="0px" />
        <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black"
            HorizontalPadding="2px" NodeSpacing="0px" VerticalPadding="2px" />
    </asp:TreeView>
</code>```

Now how do I write the code to do the work?

答:
You can read the directory for the sub directories, compare the directory names with the given name(entered in textbox). If it is found you can append the counter value. You need to increment this counter if the folder name is like "()".
After getting the proper name i.e., after appending the counter value you can call win32 API to create the directory

```<code>int SHCreateDirectory(HWND hwnd, LPCWSTR pszPath);
</code>```

EDIT: You can call the specific apis depending on the OS, technology to create the directory. Above is for Win32.

Body:
I want to create dynamic folders at run time.  Folder names with be input via a TextBox and output will be displayed in a TreeView.

The form will submit if I enter the first folder name into textbox1 and click the "Add Folder" button.  When I submit multiple folders with the same name the output should be an indexed increment of the name. Eg. FooFolder, FooFolder(2), FooFolder(3), etc.

If I delete FooFolder(2) and then recreate a folder with the name FooFolder, the folder should be FooFolder(2), and if I create one more folder then it should be FooFolder(4).

For deletion one can select the particular folder from the TreeView which will be displayed in TextBox2 and click the "Remove Folder" button.

Here is my presentation code:

<asp:Button ID="btnAddFolder" runat="server" Height="24px" Text="Add Folder"
        Width="148px" onclick="btnAddFolder_Click" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <asp:Button ID="btnRemoveFolder" runat="server" Text="Remove Folder" />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

    <asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer"
        NodeIndent="15">
        <ParentNodeStyle Font-Bold="False" />
        <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
        <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False"
            HorizontalPadding="0px" VerticalPadding="0px" />
        <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black"
            HorizontalPadding="2px" NodeSpacing="0px" VerticalPadding="2px" />
    </asp:TreeView>

Now how do I write the code to do the work?

LastEditorDisplayName: LFSR Consulting

Body:
You can read the directory for the sub directories, compare the directory names with the given name(entered in textbox). If it is found you can append the counter value. You need to increment this counter if the folder name is like "()".
After getting the proper name i.e., after appending the counter value you can call win32 API to create the directory

int SHCreateDirectory(HWND hwnd, LPCWSTR pszPath);

EDIT: You can call the specific apis depending on the OS, technology to create the directory. Above is for Win32.

OwnerDisplayName: Vinay


问:
How to get load event in Pictures same as images?
Is it possible to add onload event to picture.

Eg code for images in vue.js

```<code><img src="../../assets/hero-mobile.png" alt="Banner" @load="loaded"/>
</code>```

the methods is triggered when image loaded.

I have tried to add load event for picture but its not working. Is there any way checking the image is loaded or not ?

```<code><picture class="banner-images" @load="loaded">
      <source media="(min-width:992px)" srcset="../../assets/hero-web.png" />
      <source media="(min-width:768px)" srcset="../../assets/hero-tablet.png" />
      <source media="(min-width:576px)" srcset="../../assets/hero-mobile.png" />
      <img src="../../assets/hero-mobile.png" alt="Banner" @load="loaded"/>
</picture>
</code>```

答:
Only set @load on img tag:

new Vue({
  el: "#demo",
  data() {
    return {
      isImageLoaded: false,
    }
  },
  methods: {
    loaded() {
      this.isImageLoaded = true
      console.log('>>loaded', this.isImageLoaded)
    },
  },
  watch: {
    isImageLoaded(newValue, oldValue) {
      console.log("New value is: " + newValue)
      console.log("Old value is: " + oldValue)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div>
    <picture class="banner-images">
      <source media="(min-width:992px)" srcset="https://picsum.photos/992" />
      <source media="(min-width:768px)" srcset="https://picsum.photos/768" />
      <source media="(min-width:576px)" srcset="https://picsum.photos/576" />
      <img src="https://picsum.photos/200" alt="Banner" @load="loaded" />
    </picture>
  </div>
</div></code>```

Body:
Is it possible to add onload event to picture.

Eg code for images in vue.js

the methods is triggered when image loaded.

I have tried to add load event for picture but its not working. Is there any way checking the image is loaded or not ?

<picture class="banner-images" @load="loaded">
      <source media="(min-width:992px)" srcset="../../assets/hero-web.png" />
      <source media="(min-width:768px)" srcset="../../assets/hero-tablet.png" />
      <source media="(min-width:576px)" srcset="../../assets/hero-mobile.png" />

</picture>

Body:
Only set @load on img tag:

new Vue({
  el: "#demo",
  data() {
    return {
      isImageLoaded: false,
    }
  },
  methods: {
    loaded() {
      this.isImageLoaded = true
      console.log('>>loaded', this.isImageLoaded)
    },
  },
  watch: {
    isImageLoaded(newValue, oldValue) {
      console.log("New value is: " + newValue)
      console.log("Old value is: " + oldValue)
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div>
    <picture class="banner-images">
      <source media="(min-width:992px)" srcset="https://picsum.photos/992" />
      <source media="(min-width:768px)" srcset="https://picsum.photos/768" />
      <source media="(min-width:576px)" srcset="https://picsum.photos/576" />
      <img src="https://picsum.photos/200" alt="Banner" @load="loaded" />
    </picture>
  </div>
</div>


问:
Is it possible to use only lookaround to match characters that are not repeated immediately before and after?
For example, to match the first slash after the domain name in the URL.

Intent: Only match '/' in '.com/...' but not any '/' in 'https://'.

url = 'https://example.com/...';
[
url.match(       /(?<!\/)(?<slash>\/)(?!\k<slash>).../), // [A]
url.match(/(?<!\k<slash>)(?<slash>\/)(?!\k<slash>).../)  // [B]
]
```

The above [A] returns the correct match, but [B] is the kind of expression I want (although it did not match any characters), that is, to use the / character only 1 time in the body of regex literals.

Is there a generalized form of expression similar to [B] (using capturing groups or the like) and using only regular expression literals (instead of using the constructor (RegExp))?

答:
You can put a positive lookbehind after an optional character inside a negative lookahead. The lookbehind asserts 2 consecutive slashes (using a reference). This way the lookbehind tests the captured slash position and also the position before. Obviously, when it succeeds, the negative lookahead fails.

```<code>/(\/)(?!.?(?<=\1{2}))/
</code>```

(feel free to use named captures)

or without captures:

```<code>/\/(?!.?(?<=\/\/))/
</code>```

Body:
For example, to match the first slash after the domain name in the URL.

Intent: Only match '/' in '.com/...' but not any '/' in 'https://'.

url = 'https://example.com/...';
[
url.match(       /(?<!\/)(?<slash>\/)(?!\k<slash>).../), // [A]
url.match(/(?<!\k<slash>)(?<slash>\/)(?!\k<slash>).../)  // [B]
]

The above [A] returns the correct match, but [B] is the kind of expression I want (although it did not match any characters), that is, to use the / character only 1 time in the body of regex literals.

Is there a generalized form of expression similar to [B] (using capturing groups or the like) and using only regular expression literals (instead of using the constructor (RegExp))?

Body:
You can put a positive lookbehind after an optional character inside a negative lookahead. The lookbehind asserts 2 consecutive slashes (using a reference). This way the lookbehind tests the captured slash position and also the position before. Obviously, when it succeeds, the negative lookahead fails.

/(\/)(?!.?(?<=\1{2}))/

(feel free to use named captures)

or without captures:

/\/(?!.?(?<=\/\/))/


问:
Cast a base class issues
```<code>class YourInterface {
public:
    YourInterface(){
    }

    virtual ~YourInterface(){
    }

    virtual void saveData(Data data) = 0; //Pure virtual = Childs are forced to implement those functions to become non abstract
    virtual Data loadData() = 0;
};

//One implementation to load and save data to/from a xml file
class XmlImplementation : public YourInterface {
public:
    XmlImplementation(){
    }

    virtual ~XmlImplementation(){
    }

    //Overriding functions:
    void saveData(Data data){
        //Save data to a xml file here
    }

    Data loadData(){
        //Load data from a xml file here
    }
};

void main(){
    YourInterface* p;
    p = (YourInterface*) new XmlImplementation();

    p->loadData(); //We just want to get our Data here, we dont care whether its from a xml or binary file etc.
}
</code>```

Please take that as an example, I know it is not good but I can't write any better than that.

I'd like to know better why the cast in main refuses to work properly ? and it has been suggested as an errorful cast.

答: Nothing wrong with the code, except that the cast is actually unnecessary. The code would compile and work fine without it.</p>

Title: Cast a base class issues

Body:
class YourInterface {
public:
    YourInterface(){
    }

    virtual ~YourInterface(){
    }

    virtual void saveData(Data data) = 0; //Pure virtual = Childs are forced to implement those functions to become non abstract
    virtual Data loadData() = 0;
};

//One implementation to load and save data to/from a xml file
class XmlImplementation : public YourInterface {
public:
    XmlImplementation(){
    }

    virtual ~XmlImplementation(){
    }

    //Overriding functions:
    void saveData(Data data){
        //Save data to a xml file here
    }

    Data loadData(){
        //Load data from a xml file here
    }
};

void main(){
    YourInterface* p;
    p = (YourInterface*) new XmlImplementation();

    p->loadData(); //We just want to get our Data here, we dont care whether its from a xml or binary file etc.
}

Please take that as an example, I know it is not good but I can't write any better than that.

I'd like to know better why the cast in main refuses to work properly ? and it has been suggested as an errorful cast.