问:
Create a line as a secondary axis with Plotly
I have the following dataframe:

```<code>         date type   value
1  2020-01-01    N    7956
2  2020-01-01    R   55709
3  2020-02-01    N    2513
4  2020-02-01    R   62325
5  2020-03-01    N    1419
6  2020-03-01    R   63745
7  2020-04-01    N     350
8  2020-04-01    R   65164
9  2020-05-01    N   11500
10 2020-05-01    R   65050
11 2020-06-01    N    7208
12 2020-06-01    R   74550
13 2020-07-01    N    2904
14 2020-07-01    R   81158
15 2020-08-01    N   11054
16 2020-08-01    R   80841
17 2020-09-01    N    7020
18 2020-09-01    R   91445
19 2020-10-01    N   25448
20 2020-10-01    R   97776
21 2020-11-01    N    8497
22 2020-11-01    R  122479
23 2020-12-01    N   11154
24 2020-12-01    R  129813
</code>```

I'm building the visualization below with this dataframe. My code so far is:

```<code>fig = px.bar(df_vintage, x='date', y='value', color='type',
             labels={'type': 'value'}, category_orders={"type": ["R", "N"]})

fig.update_layout(
    title_text='Vintage Analysis',
    template='seaborn',
    margin=dict(l=50, r=50, t=50, b=50),
    legend=dict(yanchor="top", y=0.98, xanchor="left", x=0.02),

)

fig.update_xaxes(
    dtick="M1",
    tickformat="%b\n%Y")

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

I'm trying to insert a line visualization, with the percentage change of the total value, from month-to-month (but without the using the make_subplots from Plotly). To create the vector from the percentage change:

```<code>pct_change = df_vintage.groupby('dates').sum().pct_change().reset_index()
</code>```

I'm referring to the blue line I draw in the visualization. Any ideas? Thanks in advance.

答:
If you have to avoid using make_subplots then you can draw the line using the shapes module and iterating through your pct_change DataFrame to draw lines between the i and i+1 element.

Unfortunately there isn't a second y-axis so the best I could was set the reference of the y-axis to "paper" which will draw the line as if the y-axis goes from 0 to 1 (e.g. a value of 0.5 in pct_change will appear halfway up the y-axis).

Since most of your percent changes are low, I added a constant value base_pct_value (which I set to 0.5) to the percent changes so they display above the bars while still showing the general trend in percent changes (I am assuming the trend of the line matters more to you than exactly where they are positioned on the y-axis)

```<code>import pandas as pd
import plotly.express as px
import io

df_vintage = pd.read_csv(
    io.StringIO(
        """date type   value
1  2020-01-01    N    7956
2  2020-01-01    R   55709
3  2020-02-01    N    2513
4  2020-02-01    R   62325
5  2020-03-01    N    1419
6  2020-03-01    R   63745
7  2020-04-01    N     350
8  2020-04-01    R   65164
9  2020-05-01    N   11500
10 2020-05-01    R   65050
11 2020-06-01    N    7208
12 2020-06-01    R   74550
13 2020-07-01    N    2904
14 2020-07-01    R   81158
15 2020-08-01    N   11054
16 2020-08-01    R   80841
17 2020-09-01    N    7020
18 2020-09-01    R   91445
19 2020-10-01    N   25448
20 2020-10-01    R   97776
21 2020-11-01    N    8497
22 2020-11-01    R  122479
23 2020-12-01    N   11154
24 2020-12-01    R  129813"""
    ),
    sep="\s+",
)

fig = px.bar(df_vintage, x='date', y='value', color='type',
             labels={'type': 'value'}, category_orders={"type": ["R", "N"]})

fig.update_layout(
    title_text='Vintage Analysis',
    template='seaborn',
    margin=dict(l=50, r=50, t=50, b=50),
    legend=dict(yanchor="top", y=0.98, xanchor="left", x=0.02),

)

fig.update_xaxes(
    dtick="M1",
    tickformat="%b\n%Y")

pct_change = df_vintage.groupby('date').sum().pct_change().reset_index()

## however far up on the y-axis you want the pct_change values to be drawn from, some value between 0 and 1
base_pct_value = 0.5

for i in range(1,len(pct_change)-1):
    fig.add_shape(type="line",
        x0=pct_change.iloc[i]['date'],
        y0=pct_change.iloc[i]['value'] + base_pct_value,
        x1=pct_change.iloc[i+1]['date'],
        y1=pct_change.iloc[i+1]['value'] + base_pct_value,
        yref="paper",
        line=dict(
            color="skyblue",
            width=10,
        )
    )
    fig.add_annotation(
        x=pct_change.iloc[i]['date'],
        y=pct_change.iloc[i]['value'] + base_pct_value,
        text=f"{pct_change.iloc[i]['value']:.2f}",
        showarrow=False,
        yref="paper",
        yshift=10
    )
    ## last iteration of loop
    if i+1 == len(pct_change)-1:
        fig.add_annotation(
        x=pct_change.iloc[i+1]['date'],
        y=pct_change.iloc[i+1]['value'] + base_pct_value,
        text=f"{pct_change.iloc[i+1]['value']:.2f}",
        showarrow=False,
        yref="paper",
        yshift=10
    )

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

Body:
I have the following dataframe:

         date type   value
1  2020-01-01    N    7956
2  2020-01-01    R   55709
3  2020-02-01    N    2513
4  2020-02-01    R   62325
5  2020-03-01    N    1419
6  2020-03-01    R   63745
7  2020-04-01    N     350
8  2020-04-01    R   65164
9  2020-05-01    N   11500
10 2020-05-01    R   65050
11 2020-06-01    N    7208
12 2020-06-01    R   74550
13 2020-07-01    N    2904
14 2020-07-01    R   81158
15 2020-08-01    N   11054
16 2020-08-01    R   80841
17 2020-09-01    N    7020
18 2020-09-01    R   91445
19 2020-10-01    N   25448
20 2020-10-01    R   97776
21 2020-11-01    N    8497
22 2020-11-01    R  122479
23 2020-12-01    N   11154
24 2020-12-01    R  129813

I'm building the visualization below with this dataframe. My code so far is:

fig = px.bar(df_vintage, x='date', y='value', color='type',
             labels={'type': 'value'}, category_orders={"type": ["R", "N"]})

fig.update_layout(
    title_text='Vintage Analysis',
    template='seaborn',
    margin=dict(l=50, r=50, t=50, b=50),
    legend=dict(yanchor="top", y=0.98, xanchor="left", x=0.02),

)

fig.update_xaxes(
    dtick="M1",
    tickformat="%b\n%Y")

fig.show()

I'm trying to insert a line visualization, with the percentage change of the total value, from month-to-month (but without the using the make_subplots from Plotly). To create the vector from the percentage change:

pct_change = df_vintage.groupby('dates').sum().pct_change().reset_index()

I'm referring to the blue line I draw in the visualization. Any ideas? Thanks in advance.

Body:
If you have to avoid using make_subplots then you can draw the line using the shapes module and iterating through your pct_change DataFrame to draw lines between the i and i+1 element.

Unfortunately there isn't a second y-axis so the best I could was set the reference of the y-axis to "paper" which will draw the line as if the y-axis goes from 0 to 1 (e.g. a value of 0.5 in pct_change will appear halfway up the y-axis).

Since most of your percent changes are low, I added a constant value base_pct_value (which I set to 0.5) to the percent changes so they display above the bars while still showing the general trend in percent changes (I am assuming the trend of the line matters more to you than exactly where they are positioned on the y-axis)

import pandas as pd
import plotly.express as px
import io

df_vintage = pd.read_csv(
    io.StringIO(
        """date type   value
1  2020-01-01    N    7956
2  2020-01-01    R   55709
3  2020-02-01    N    2513
4  2020-02-01    R   62325
5  2020-03-01    N    1419
6  2020-03-01    R   63745
7  2020-04-01    N     350
8  2020-04-01    R   65164
9  2020-05-01    N   11500
10 2020-05-01    R   65050
11 2020-06-01    N    7208
12 2020-06-01    R   74550
13 2020-07-01    N    2904
14 2020-07-01    R   81158
15 2020-08-01    N   11054
16 2020-08-01    R   80841
17 2020-09-01    N    7020
18 2020-09-01    R   91445
19 2020-10-01    N   25448
20 2020-10-01    R   97776
21 2020-11-01    N    8497
22 2020-11-01    R  122479
23 2020-12-01    N   11154
24 2020-12-01    R  129813"""
    ),
    sep="\s+",
)

fig = px.bar(df_vintage, x='date', y='value', color='type',
             labels={'type': 'value'}, category_orders={"type": ["R", "N"]})

fig.update_layout(
    title_text='Vintage Analysis',
    template='seaborn',
    margin=dict(l=50, r=50, t=50, b=50),
    legend=dict(yanchor="top", y=0.98, xanchor="left", x=0.02),

)

fig.update_xaxes(
    dtick="M1",
    tickformat="%b\n%Y")

pct_change = df_vintage.groupby('date').sum().pct_change().reset_index()

## however far up on the y-axis you want the pct_change values to be drawn from, some value between 0 and 1
base_pct_value = 0.5

for i in range(1,len(pct_change)-1):
    fig.add_shape(type="line",
        x0=pct_change.iloc[i]['date'],
        y0=pct_change.iloc[i]['value'] + base_pct_value,
        x1=pct_change.iloc[i+1]['date'],
        y1=pct_change.iloc[i+1]['value'] + base_pct_value,
        yref="paper",
        line=dict(
            color="skyblue",
            width=10,
        )
    )
    fig.add_annotation(
        x=pct_change.iloc[i]['date'],
        y=pct_change.iloc[i]['value'] + base_pct_value,
        text=f"{pct_change.iloc[i]['value']:.2f}",
        showarrow=False,
        yref="paper",
        yshift=10
    )
    ## last iteration of loop
    if i+1 == len(pct_change)-1:
        fig.add_annotation(
        x=pct_change.iloc[i+1]['date'],
        y=pct_change.iloc[i+1]['value'] + base_pct_value,
        text=f"{pct_change.iloc[i+1]['value']:.2f}",
        showarrow=False,
        yref="paper",
        yshift=10
    )

fig.show()


来源: stackexchange

问:
group an array into subarrays in a project stage
I want to split the following array according to the group-value. I know I can do this using $unwind and $group. Is there any way to this in a single $project-stage?

Input

```<code>{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "subgroup": "aa",
            "value": 1
        },
        {
            "group": "b",
            "subgroup": "bb",
            "value": 2
        },
        {
            "group": "a",
            "subgroup": "ab",
            "value": 2
        }
    ]
}
</code>```

desired output:

```<code>{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "values": [
                {
                    "subgroup": "aa",
                    "value": 1
                },
                {
                    "subgroup": "ab",
                    "value": 2
                }
            ]
        },
        {
            "group": "b",
            "values": [
                {
                    "subgroup": "bb",
                    "value": 2
                }
            ]
        }
    ]
}
</code>```

答:
Try this: https://mongoplayground.net/p/pFn3tLtAG4D</p>
```<code>$set: {
    _id: "$_id",
    some_field: "$some_field",
    array: {
      $map: {
        input: {
          $setUnion: [
            "$array.group"
          ]
        },
        in: {
          group: "$$this",
          values: {
            $map: {
              input: {
                $filter: {
                  input: "$array",
                  as: "elem",
                  cond: {
                    $eq: [
                      "$$elem.group",
                      "$$this"
                    ]
                  }
                }
              },
              as: "vals",
              in: {
                subgroup: "$$vals.subgroup",
                value: "$$vals.value"
              }
            }
          }
        }
      }
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to split the following array according to the group-value. I know I can do this using $unwind and $group. Is there any way to this in a single $project-stage?

Input

{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "subgroup": "aa",
            "value": 1
        },
        {
            "group": "b",
            "subgroup": "bb",
            "value": 2
        },
        {
            "group": "a",
            "subgroup": "ab",
            "value": 2
        }
    ]
}

desired output:

{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "values": [
                {
                    "subgroup": "aa",
                    "value": 1
                },
                {
                    "subgroup": "ab",
                    "value": 2
                }
            ]
        },
        {
            "group": "b",
            "values": [
                {
                    "subgroup": "bb",
                    "value": 2
                }
            ]
        }
    ]
}

Body:
Try this: https://mongoplayground.net/p/pFn3tLtAG4D

$set: {
    _id: "$_id",
    some_field: "$some_field",
    array: {
      $map: {
        input: {
          $setUnion: [
            "$array.group"
          ]
        },
        in: {
          group: "$$this",
          values: {
            $map: {
              input: {
                $filter: {
                  input: "$array",
                  as: "elem",
                  cond: {
                    $eq: [
                      "$$elem.group",
                      "$$this"
                    ]
                  }
                }
              },
              as: "vals",
              in: {
                subgroup: "$$vals.subgroup",
                value: "$$vals.value"
              }
            }
          }
        }
      }
    }
  }


问:
How do I generate this report by importing the hostname to a list or csv?
I had this script, but the format was in HTML and I cleaned up all the code and changed the commands that were "gwmi" to "Get-CimInstance" to have good practices. My goal is to transform this script that handles a hostname to a list of hostnames.

Can someone help me?

The idea I had would be to have a window that has a "browse" button to import the list, be it in txt or csv and for each hostname in that list it would do these commands and in the end it would export to an xlsx file (I tried with Export-Excel, but you need to download the module separately, and you need to trust the repository, authorize the import of the module for later use, so I would have to make this standalone, without any request, because I would convert this ps1 into an exe file) and the data, would need to be side by side with the headers, e.g. Hostname, Last User Logged, Type Of Chassis etc.

I would be very grateful if someone can help me, I've been building part 1 of this script for a few hours now, and now I need to go to part 2 (that is this process to create and export csv results) which is the part where I feel stuck.

```<code>Add-Type -AssemblyName Microsoft.VisualBasic
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox("Insert the hostname Name", "Hardware Report")
If ($ComputerName -eq "")
{
    break
}

#Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
$ProgressPreference = 'SilentlyContinue'
try {
    $ErrorActionPreference = "Stop";
    $TestComputerHost = Test-Connection $ComputerName -Count 1 -InformationAction Continue -WarningAction SilentlyContinue;
    } catch {
    #Hostname will be skipped
    } finally {
    $ProgressPreference = 'Continue'
    $ErrorActionPreference = "Continue"
    }

#Validade crucial service that is crucial for get remote data, and if is not possible to get this information, the hostname will be skipped
try {
$ErrorActionPreference = "Stop"
Get-CimInstance win32_operatingsystem -ComputerName $ComputerName | Out-Null }
catch [System.Runtime.InteropServices.COMException]
    {
    #Hostname will be skipped
    }

#Validate if the WS Management service is enabled on the remote device
$ProgressPreference = 'SilentlyContinue'
$TestComputerHost = Test-NetConnection $ComputerName -Port 5985 -InformationLevel Quiet -WarningAction SilentlyContinue
If ($TestComputerHost -ne "False"){

}
$ProgressPreference = 'Continue'

#Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine
Function Get-WUChassisType {

    [CmdletBinding()]
    param (
    )
    Set-StrictMode -Version 'Latest'
    [int[]]$chassisType = try {
    $ErrorActionPreference = "Stop";
    Get-CimInstance Win32_SystemEnclosure -ComputerName $ComputerName | Select-Object -ExpandProperty ChassisTypes;
    } catch {
    #Here need to be blank result or skip this result but keep the rest results
    } finally {
    $ErrorActionPreference = "Continue";
    }
    switch ($chassisType) {
        { $_ -in 3, 4, 5, 6, 7, 15, 16 } {
            return 'Desktop'
        }
        { $_ -in 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 } {
            return 'Notebook'
        }
        { $_ -in 30 } {
            return 'Tablet'
        }
        { $_ -in 17, 23 } {
            return 'Servidor'
        }
        Default {
        }
    }
}

#Function to get last logged user on remote computer
Function Get-LastUser {
try {
$ErrorActionPreference = "Stop"
Get-WmiObject Win32_LoggedOnUser -ComputerName $ComputerName |
    Select Antecedent -Unique |
    % {
        $domain = $_.Antecedent.Split('"')[1]
        if($domain -eq "DOMAIN") {
            "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3]
        }
    } | Select-Object -First 1
    } catch [System.Runtime.InteropServices.COMException]
    {

    }
    }

#Name of remote computer
$Name = 'Hostname' + $ComputerName

#Get last logged user (by function)
$LastLoggedUser = ((Get-LastUser).Split('\')[1])

#Last Boot Time
$LastBoot = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName |Select-Object CSName, LastBootUpTime | Select -ExpandProperty LastBootUpTime).tostring("dd/MM/yyyy hh:mm:ss")

#Chassis Type Of Computer
$ChassisType = Get-WUChassisType

#Operating System
$OS = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName).caption

#System Installed On
$SystemInstalledOn = ((Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).InstallDate).tostring("dd/MM/yyyy hh:mm:ss")

#Processor
$Processor = (Get-CimInstance win32_processor -ComputerName $ComputerName -filter "deviceid='CPU0'").Name

#Disk
$Disk = (Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size

#Ram Memory
$Ram = (Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity

#Serial Number
$SerialNumber = Get-CimInstance win32_bios -ComputerName $ComputerName | Select-Object -ExpandProperty SerialNumber

#Manufacturer
$Manufacturer = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Vendor

#Model
$Model = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Name

#Export to CSV
$Name + $LastLoggedUser + $ChassisType + $LastBoot + $OS + $SystemInstalledOn + $Processor + $Disk + $Ram + $SerialNumber + $Manufacturer + $Model | Export-Csv

#Dialog box to information finish script
[Microsoft.VisualBasic.Interaction]::MsgBox("Report is finished", "OKOnly,SystemModal,Information", "Success") | Out-Null```
```

答:
edit: rewrote it a little for you, try the below.
Note that the input csv expects a header called "ComputerName" and a list of computer names underneath that.

I copied the csv-to-excel part at the bottom from here

```<code>#Function to let user select a file then return the filepath.
Function Get-FileName($initialDirectory){
    [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = “CSV Exports (*.csv)| *.csv”
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.FileName
}

$filepath = Get-FileName -initialDirectory $PSScriptRoot
$csvdata = Import-Csv -Path $filepath

#Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine
Function Get-WUChassisType {
    [CmdletBinding()]
    param ($ComputerName=$null)
    Set-StrictMode -Version 'Latest'
    $chassisTypes = Get-CimInstance Win32_SystemEnclosure -ComputerName $ComputerName | Select -ExpandProperty ChassisTypes
    switch ($chassisTypes) {
        { $_ -in 3, 4, 5, 6, 7, 15, 16 } {
            return 'Desktop'
        }
        { $_ -in 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 } {
            return 'Notebook'
        }
        { $_ -in 30 } {
            return 'Tablet'
        }
        { $_ -in 17, 23 } {
            return 'Servidor'
        }
        Default {
            return ''
        }
    }
}

#Function to get last logged user on remote computer
Function Get-LastUser($ComputerName){
try {
Get-WmiObject Win32_LoggedOnUser -ComputerName $ComputerName |
    Select Antecedent -Unique |
    % {
        $domain = $_.Antecedent.Split('"')[1]
        if($domain -eq "VLINET") {
            "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3]
        }
    } | Select-Object -First 1
    } catch [System.Runtime.InteropServices.COMException]{

    }
}

#We'll append all our individual pc resuls into this array
$exportObj = @()
$offlineObj = @()

#Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
foreach ($row in $csvdata){
    if(Test-Connection $row.ComputerName -Count 1){
        $ciminfo = Get-CimInstance win32_operatingsystem -ComputerName $row.ComputerName -ErrorAction SilentlyContinue |Select-Object CSName, LastBootUpTime, Caption, InstallDate
        $sysinfo = Get-CimInstance win32_ComputerSystemProduct -ComputerName $row.ComputerName -ErrorAction SilentlyContinue | Select-Object Vendor, Name
        if ($ciminfo -and $sysinfo){
            $objPcResult = New-Object PSObject -Property @{
                Name              = 'Hostname: ' + $row.ComputerName;
                ChassisType       = Get-WUChassisType -ComputerName $row.ComputerName;
                LastLoggedUser    = ((Get-LastUser -ComputerName $row.ComputerName).Split('\')[1]);
                LastBoot          = $ciminfo.LastBootUpTime.tostring("dd/MM/yyyy hh:mm:ss");
                OS                = $ciminfo.Caption;
                SystemInstalledOn = $ciminfo.InstallDate.tostring("dd/MM/yyyy hh:mm:ss");
                Processor         = (Get-CimInstance win32_processor -ComputerName $row.ComputerName -filter "deviceid='CPU0'").Name;
                Disk              = (Get-CimInstance Win32_LogicalDisk -ComputerName $row.ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size;
                Ram               = (Get-CimInstance Win32_PhysicalMemory -ComputerName $row.ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity;
                SerialNumber      = Get-CimInstance win32_bios -ComputerName $row.ComputerName | Select-Object -ExpandProperty SerialNumber;
                Manufacturer      = $sysinfo.Vendor;
                Model             = $sysinfo.Name;
            }

            #Add each PC results as a new row in our array
            $exportObj += $objPcResult
        }
    }else{
        $objPcResult = New-Object PSObject -Property @{
                Name = 'Hostname: ' + $row.ComputerName;
                }
        $offlineObj += $objPcResult
    }
}

#Setup our temp variables to save our collected data as a temporary CSV, so we can import it into Excel to save as an XLSX.
$offlinecsv = "c:\temp\offline.csv" #Location of offline hosts
$tempcsv = "c:\temp\temp.csv" #Location of the source file
$xlsx = "c:\temp\output.xlsx" #Desired location of output
$delimiter = "," #Specify the delimiter used in the file

#Temp export our csv - to be converted to xlsx
$exportObj | Export-Csv -Path $tempcsv -NoTypeInformation
$offlineObj | Export-Csv -Path $offlinecsv -NoTypeInformation

### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$excel.Visible = $false
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $tempcsv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

# Execute & delete the import query
$query.Refresh()
$query.Delete()

# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()
</code>```

Body:
I had this script, but the format was in HTML and I cleaned up all the code and changed the commands that were "gwmi" to "Get-CimInstance" to have good practices. My goal is to transform this script that handles a hostname to a list of hostnames.

Can someone help me?

The idea I had would be to have a window that has a "browse" button to import the list, be it in txt or csv and for each hostname in that list it would do these commands and in the end it would export to an xlsx file (I tried with Export-Excel, but you need to download the module separately, and you need to trust the repository, authorize the import of the module for later use, so I would have to make this standalone, without any request, because I would convert this ps1 into an exe file) and the data, would need to be side by side with the headers, e.g. Hostname, Last User Logged, Type Of Chassis etc.

I would be very grateful if someone can help me, I've been building part 1 of this script for a few hours now, and now I need to go to part 2 (that is this process to create and export csv results) which is the part where I feel stuck.

Add-Type -AssemblyName Microsoft.VisualBasic
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox("Insert the hostname Name", "Hardware Report")
If ($ComputerName -eq "")
{
    break
}

#Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
$ProgressPreference = 'SilentlyContinue'
try {
    $ErrorActionPreference = "Stop";
    $TestComputerHost = Test-Connection $ComputerName -Count 1 -InformationAction Continue -WarningAction SilentlyContinue;
    } catch {
    #Hostname will be skipped
    } finally {
    $ProgressPreference = 'Continue'
    $ErrorActionPreference = "Continue"
    }

#Validade crucial service that is crucial for get remote data, and if is not possible to get this information, the hostname will be skipped
try {
$ErrorActionPreference = "Stop"
Get-CimInstance win32_operatingsystem -ComputerName $ComputerName | Out-Null }
catch [System.Runtime.InteropServices.COMException]
    {
    #Hostname will be skipped
    }

#Validate if the WS Management service is enabled on the remote device
$ProgressPreference = 'SilentlyContinue'
$TestComputerHost = Test-NetConnection $ComputerName -Port 5985 -InformationLevel Quiet -WarningAction SilentlyContinue
If ($TestComputerHost -ne "False"){

}
$ProgressPreference = 'Continue'

#Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine
Function Get-WUChassisType {

    [CmdletBinding()]
    param (
    )
    Set-StrictMode -Version 'Latest'
    [int[]]$chassisType = try {
    $ErrorActionPreference = "Stop";
    Get-CimInstance Win32_SystemEnclosure -ComputerName $ComputerName | Select-Object -ExpandProperty ChassisTypes;
    } catch {
    #Here need to be blank result or skip this result but keep the rest results
    } finally {
    $ErrorActionPreference = "Continue";
    }
    switch ($chassisType) {
        { $_ -in 3, 4, 5, 6, 7, 15, 16 } {
            return 'Desktop'
        }
        { $_ -in 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 } {
            return 'Notebook'
        }
        { $_ -in 30 } {
            return 'Tablet'
        }
        { $_ -in 17, 23 } {
            return 'Servidor'
        }
        Default {
        }
    }
}

#Function to get last logged user on remote computer
Function Get-LastUser {
try {
$ErrorActionPreference = "Stop"
Get-WmiObject Win32_LoggedOnUser -ComputerName $ComputerName |
    Select Antecedent -Unique |
    % {
        $domain = $_.Antecedent.Split('"')[1]
        if($domain -eq "DOMAIN") {
            "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3]
        }
    } | Select-Object -First 1
    } catch [System.Runtime.InteropServices.COMException]
    {

    }
    }

#Name of remote computer
$Name = 'Hostname' + $ComputerName

#Get last logged user (by function)
$LastLoggedUser = ((Get-LastUser).Split('\')[1])

#Last Boot Time
$LastBoot = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName |Select-Object CSName, LastBootUpTime | Select -ExpandProperty LastBootUpTime).tostring("dd/MM/yyyy hh:mm:ss")

#Chassis Type Of Computer
$ChassisType = Get-WUChassisType

#Operating System
$OS = (Get-CimInstance win32_operatingsystem -ComputerName $ComputerName).caption

#System Installed On
$SystemInstalledOn = ((Get-CimInstance Win32_OperatingSystem -ComputerName $ComputerName).InstallDate).tostring("dd/MM/yyyy hh:mm:ss")

#Processor
$Processor = (Get-CimInstance win32_processor -ComputerName $ComputerName -filter "deviceid='CPU0'").Name

#Disk
$Disk = (Get-CimInstance Win32_LogicalDisk -ComputerName $ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size

#Ram Memory
$Ram = (Get-CimInstance Win32_PhysicalMemory -ComputerName $ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity

#Serial Number
$SerialNumber = Get-CimInstance win32_bios -ComputerName $ComputerName | Select-Object -ExpandProperty SerialNumber

#Manufacturer
$Manufacturer = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Vendor

#Model
$Model = Get-CimInstance win32_ComputerSystemProduct -ComputerName $ComputerName | Select-Object -ExpandProperty Name

#Export to CSV
$Name + $LastLoggedUser + $ChassisType + $LastBoot + $OS + $SystemInstalledOn + $Processor + $Disk + $Ram + $SerialNumber + $Manufacturer + $Model | Export-Csv

#Dialog box to information finish script
[Microsoft.VisualBasic.Interaction]::MsgBox("Report is finished", "OKOnly,SystemModal,Information", "Success") | Out-Null```

Body:
edit: rewrote it a little for you, try the below.
Note that the input csv expects a header called "ComputerName" and a list of computer names underneath that.

I copied the csv-to-excel part at the bottom from here

#Function to let user select a file then return the filepath.
Function Get-FileName($initialDirectory){
    [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = “CSV Exports (*.csv)| *.csv”
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.FileName
}

$filepath = Get-FileName -initialDirectory $PSScriptRoot
$csvdata = Import-Csv -Path $filepath

#Function to create the Get-WUChassisType that is performed to find out if the Chassis of the equipment is Notebook or Desktop, and it is not configured to detect virtual machine
Function Get-WUChassisType {
    [CmdletBinding()]
    param ($ComputerName=$null)
    Set-StrictMode -Version 'Latest'
    $chassisTypes = Get-CimInstance Win32_SystemEnclosure -ComputerName $ComputerName | Select -ExpandProperty ChassisTypes
    switch ($chassisTypes) {
        { $_ -in 3, 4, 5, 6, 7, 15, 16 } {
            return 'Desktop'
        }
        { $_ -in 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 } {
            return 'Notebook'
        }
        { $_ -in 30 } {
            return 'Tablet'
        }
        { $_ -in 17, 23 } {
            return 'Servidor'
        }
        Default {
            return ''
        }
    }
}

#Function to get last logged user on remote computer
Function Get-LastUser($ComputerName){
try {
Get-WmiObject Win32_LoggedOnUser -ComputerName $ComputerName |
    Select Antecedent -Unique |
    % {
        $domain = $_.Antecedent.Split('"')[1]
        if($domain -eq "VLINET") {
            "{0}\{1}" -f $domain, $_.Antecedent.Split('"')[3]
        }
    } | Select-Object -First 1
    } catch [System.Runtime.InteropServices.COMException]{

    }
}

#We'll append all our individual pc resuls into this array
$exportObj = @()
$offlineObj = @()

#Check computer online in network, if is not online, the hostname will be skipped but necessary add in log entry which computers is offline
foreach ($row in $csvdata){
    if(Test-Connection $row.ComputerName -Count 1){
        $ciminfo = Get-CimInstance win32_operatingsystem -ComputerName $row.ComputerName -ErrorAction SilentlyContinue |Select-Object CSName, LastBootUpTime, Caption, InstallDate
        $sysinfo = Get-CimInstance win32_ComputerSystemProduct -ComputerName $row.ComputerName -ErrorAction SilentlyContinue | Select-Object Vendor, Name
        if ($ciminfo -and $sysinfo){
            $objPcResult = New-Object PSObject -Property @{
                Name              = 'Hostname: ' + $row.ComputerName;
                ChassisType       = Get-WUChassisType -ComputerName $row.ComputerName;
                LastLoggedUser    = ((Get-LastUser -ComputerName $row.ComputerName).Split('\')[1]);
                LastBoot          = $ciminfo.LastBootUpTime.tostring("dd/MM/yyyy hh:mm:ss");
                OS                = $ciminfo.Caption;
                SystemInstalledOn = $ciminfo.InstallDate.tostring("dd/MM/yyyy hh:mm:ss");
                Processor         = (Get-CimInstance win32_processor -ComputerName $row.ComputerName -filter "deviceid='CPU0'").Name;
                Disk              = (Get-CimInstance Win32_LogicalDisk -ComputerName $row.ComputerName | Select-Object @{Name="Size"; Expression={"$([math]::round($_.Size / 1GB,2))GB"}}).Size;
                Ram               = (Get-CimInstance Win32_PhysicalMemory -ComputerName $row.ComputerName | Select-Object @{Name="Capacity"; Expression={"$([math]::round($_.Capacity / 1GB,2))GB"}}).Capacity;
                SerialNumber      = Get-CimInstance win32_bios -ComputerName $row.ComputerName | Select-Object -ExpandProperty SerialNumber;
                Manufacturer      = $sysinfo.Vendor;
                Model             = $sysinfo.Name;
            }

            #Add each PC results as a new row in our array
            $exportObj += $objPcResult
        }
    }else{
        $objPcResult = New-Object PSObject -Property @{
                Name = 'Hostname: ' + $row.ComputerName;
                }
        $offlineObj += $objPcResult
    }
}

#Setup our temp variables to save our collected data as a temporary CSV, so we can import it into Excel to save as an XLSX.
$offlinecsv = "c:\temp\offline.csv" #Location of offline hosts
$tempcsv = "c:\temp\temp.csv" #Location of the source file
$xlsx = "c:\temp\output.xlsx" #Desired location of output
$delimiter = "," #Specify the delimiter used in the file

#Temp export our csv - to be converted to xlsx
$exportObj | Export-Csv -Path $tempcsv -NoTypeInformation
$offlineObj | Export-Csv -Path $offlinecsv -NoTypeInformation

### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$excel.Visible = $false
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $tempcsv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

# Execute & delete the import query
$query.Refresh()
$query.Delete()

# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()


问:
How to add MULTIPLE strings to a set?
I have a set "y"

I can add one string no problem, but here is the input/output when I add multiple strings:

```<code>y.update(['tam','sam'])
print(y)

{'sam', 'baz', 'a', 'tam', 's', 'bar', 'jas', 'foo', 't', 'm'}
</code>```

I created a list in the argument for update because I thought it is not iterable. Any thoughts/solutions?

答:
You can convert your set to list, add the new list and then convert it back to set.</p>
```<code>y = {'sam', 'baz', 'a', 'tam', 's', 'bar', 'jas', 'foo', 't', 'm'}

y = list(y)
y.extend(['ron', 'harry'])

y = set(y)
print(y)
</code>```
```<code>{'bar', 'sam', 'jas', 'm', 'ron', 'tam', 's', 'baz', 't', 'a', 'foo', 'harry'}
</code>```

Title: How to add MULTIPLE strings to a set?

Body:
I have a set "y"

I can add one string no problem, but here is the input/output when I add multiple strings:

y.update(['tam','sam'])
print(y)

{'sam', 'baz', 'a', 'tam', 's', 'bar', 'jas', 'foo', 't', 'm'}

I created a list in the argument for update because I thought it is not iterable. Any thoughts/solutions?

Body:
You can convert your set to list, add the new list and then convert it back to set.

y = {'sam', 'baz', 'a', 'tam', 's', 'bar', 'jas', 'foo', 't', 'm'}

y = list(y)
y.extend(['ron', 'harry'])

y = set(y)
print(y)

{'bar', 'sam', 'jas', 'm', 'ron', 'tam', 's', 'baz', 't', 'a', 'foo', 'harry'}


问:
Aggregate instantiating structs
Are there benefits to instantiating structs using aggregate initialization as opposed to having an init function to return an instance? This is what I'm talking about:</p>
```<code>sturct Data
{
    float x, y;
    std::string dataString;
};

Data init_data(float _x, float _y, std::string _dataString)
{
    Data data;
    data.x = _x;
    data.y = _y;
    data.dataString = _dataString;
    return data;
}

int main()
{
    Data d1 = init_data(1.0, 2.0, "testData"); // or
    Data d2 { 1.0, 2.0, "testData");
}
</code>```

答: In the sense of performance, probably yes. d2 directly generates the Data instance with specified data values, while d1 is generating the a Data{0,0,empty string} first inside the function, and then modifies the values that you wanted, then return that Data by value, making another copy of Data. although the optimization the compiler offers may reduce the overhead, but it is not guaranteed.</p>

Title: Aggregate instantiating structs

Body:
Are there benefits to instantiating structs using aggregate initialization as opposed to having an init function to return an instance? This is what I'm talking about:

sturct Data
{
    float x, y;
    std::string dataString;
};

Data init_data(float _x, float _y, std::string _dataString)
{
    Data data;
    data.x = _x;
    data.y = _y;
    data.dataString = _dataString;
    return data;
}

int main()
{
    Data d1 = init_data(1.0, 2.0, "testData"); // or
    Data d2 { 1.0, 2.0, "testData");
}


问:
Pulling and Resolving PR conflicts from AzDO
My company uses Azure DevOps for source control.  For the most part it works just like GitHub, but I can't figure out how to do this one scenario.  Another co-worker has raised a PR but there are conflicts in his PR.  How can I pull down the PR and resolve the conflicts locally.  Yes, he should do that, but he's going to be out for awhile.  I want to be able to see the conflict markers locally and resolve them in VSCode.

I've tried this command locally:  git fetch origin pull/27561/head:fixpr
but that just returns: fatal: couldn't find remote ref pull/27561/head

答:
As far as I know, there is no such method could pull down the PR to your local machine directly.

If you want to resolve the conflicts on your local machine, you need to clone the repo, then do a git pull locally to find out the conflicting files.

Finally you can change the file and push to Azure Repo.

Refer to this official doc to get the detailed steps: Resolve merge conflicts

On the other hand, you can also consider using this extension: Pull Request Merge Conflict Extension to resolve conflicts directly in Azure DevOps Pull Requests.

You can see the Conflicts tab in the Pull Request.

For example:


问:
R function for trimming beginning of a string
Here is a sample of the dataset I am working with.

```<code>df <- data.frame( precinct = c("01-001", "01-002", "Adv 1 01-001", "Adv 1 01-002"), total = c(100, 102, 4, 6))
</code>```

I need to remove the specific string "Adv 1 " while leaving everything else intact. I considered stringr functions like str_replace() and str_remove() but but I understand it only works on single letters. Is there a function or procedure for performing the trimming?

Body:
Here is a sample of the dataset I am working with.

df <- data.frame( precinct = c("01-001", "01-002", "Adv 1 01-001", "Adv 1 01-002"), total = c(100, 102, 4, 6))

I need to remove the specific string "Adv 1 " while leaving everything else intact. I considered stringr functions like str_replace() and str_remove() but but I understand it only works on single letters. Is there a function or procedure for performing the trimming?

Body:
Another base R solution :

df <- data.frame( precinct = c("01-001", "01-002", "Adv 1 01-001", "Adv 1 01-002"), total = c(100, 102, 4, 6))
df[,1] <- trimws(df[,1], whitespace =  "Adv 1")


问:
Parsing a pandas DataFrame by delimiter
I have the following problem:

I have a pandas DataFrame as follows:

```<code>      df

       A                    B

      GRA                 x - kuaiau;;a; y - kaj;jsuik;;;ou; yy -ll'jkusj;;l;
      GRB                 xx -iusiksu;;a; z - kuayatik;;;ou;
      GRC                 tt - hay;hayh;
      GRD                 NA
      GRE

</code>```

So what I want is whenever column B is not null, split the column B strings based on delimiter '-' and put the groups in 2 columns as shown.

Expected output:

```<code>  df_final

       A                    C                            D
      GRA                  x y yy              kuaiau;;a; kaj;jsuik;;;ou; ll'jkusj;;l;
      GRB                  xx z                iusiksu;;a; kuayatik;;;ou;
      GRC                  tt                  hay;hayh;
      GRD                  NA                  NA
      GRE

</code>```

I am able to split the column based on delimiter '-'. However since I have a varying number of '-' I am not able to concat them properly to get the output as desired and also not able to make it work at all, when the column is NULL, blank, or NA.

An help whatsoever will definitely help.

答:
We can use str.replace here with appropriate regex patterns:

df["C"] = df["B"].str.replace(r'\s*-\s*\S+;+\S+;+\s*', ' ').str.strip()
df["D"] = df["B"].str.replace(r'\w+\s*-\s*', '')
```

Title: Parsing a pandas DataFrame by delimiter

Body:
I have the following problem:

I have a pandas DataFrame as follows:

      df

       A                    B

      GRA                 x - kuaiau;;a; y - kaj;jsuik;;;ou; yy -ll'jkusj;;l;
      GRB                 xx -iusiksu;;a; z - kuayatik;;;ou;
      GRC                 tt - hay;hayh;
      GRD                 NA
      GRE

So what I want is whenever column B is not null, split the column B strings based on delimiter '-' and put the groups in 2 columns as shown.

Expected output:

  df_final

       A                    C                            D
      GRA                  x y yy              kuaiau;;a; kaj;jsuik;;;ou; ll'jkusj;;l;
      GRB                  xx z                iusiksu;;a; kuayatik;;;ou;
      GRC                  tt                  hay;hayh;
      GRD                  NA                  NA
      GRE

I am able to split the column based on delimiter '-'. However since I have a varying number of '-' I am not able to concat them properly to get the output as desired and also not able to make it work at all, when the column is NULL, blank, or NA.

An help whatsoever will definitely help.


问:
Can I build table with % and growhorizontally?
Trying to build a table with two columns and TextArea. Works great except for the first column is too narrow. Second column does growhorizontally as expected. Setting column width % removes the growhorizontally from second column. Any way around this?</p>

答:
Check out the JavaDoc for the Table class where it states:

The column width in percentages, -1 will use the preferred size. -2 for width will take up the rest of the available space

So you can use -2 but I find it simpler to just set values that add up to 100 to take up all available space.

Notice you just need to do this for the first row as all other rows will fit into the columns you defined.


问:
How do I declare the objects related to one class in other?
The error shows: no matching functions for call to birthday::birthday(). How else should I declare the objects of one class in another class?

```<code>#include <iostream>

using namespace std;

class birthday
{

public:

    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    int date;
    int month;
    int year;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on "<< day.printdate();
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}
</code>```

答:
While the answers given regarding adding a default c'tor for birthday are technically correct, I think that they miss the real issue. Given how you declare the variables b and p in main(), it looks as if your intent is for the birthday variable b to be added to the person variable, which implies that what you actually want is to modify the person() constructor as such:

```<code>    person(string x, birthday b): name(x), day(b)
    { }
</code>```

This will ensure that a birthday object is defined for a given person object when the person is constructed.

This isn't to say that adding a default c'tor for either birthday or person is wrong; indeed, it would probably be advisable. But on its own it might not have the desired effect.

Body:
The error shows: no matching functions for call to birthday::birthday(). How else should I declare the objects of one class in another class?

#include <iostream>

using namespace std;

class birthday
{

public:

    birthday(int d,int m,int y)
    {
        date=d;
        month=m;
        year=y;
    }
    void printdate()
    {
        cout<<date<<"/"<<month<<"/"<<year<<endl;
    }

private:

    int date;
    int month;
    int year;
};

class person
{

public:

    person(string x)
    {
        name=x;
    }
    void printname()
    {
        cout<< "the birthday person is "<< name << " whose birthday is on "<< day.printdate();
    }

private:

    birthday day;
    string name;
};

int main()
{
   birthday b(10,11,2007);
   person p("Jessica");
   p.printname();
   return 0;
}

Body:
While the answers given regarding adding a default c'tor for birthday are technically correct, I think that they miss the real issue. Given how you declare the variables b and p in main(), it looks as if your intent is for the birthday variable b to be added to the person variable, which implies that what you actually want is to modify the person() constructor as such:

    person(string x, birthday b): name(x), day(b)
    { }

This will ensure that a birthday object is defined for a given person object when the person is constructed.

This isn't to say that adding a default c'tor for either birthday or person is wrong; indeed, it would probably be advisable. But on its own it might not have the desired effect.


问:
Error with node-sass when running npm install
I'm getting the following errors whenever I run npm install on a vue.js project

```<code>5769 error code 1
5770 error path /*my path*/node_modules/node-sass
5771 error command failed
5772 error command sh -c node scripts/install.js
5773 error /*my path*/node_modules/request/index.js:30
5773 error   if (options !== null && typeof op
5773 error
5773 error
5773 error SyntaxError: Unexpected end of input
5773 error     at Object.compileFunction (node:vm:352:18)
5773 error     at wrapSafe (node:internal/modules/cjs/loader:1031:15)
5773 error     at Module._compile (node:internal/modules/cjs/loader:1065:27)
5773 error     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
5773 error     at Module.load (node:internal/modules/cjs/loader:981:32)
5773 error     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
5773 error     at Module.require (node:internal/modules/cjs/loader:1005:19)
5773 error     at require (node:internal/modules/cjs/helpers:102:18)
5773 error     at Object.<anonymous> (/*my path*/node_modules/node-sass/scripts/install.js:10:13)
5773 error     at Module._compile (node:internal/modules/cjs/loader:1101:14)
5774 verbose exit 1
</code>```

I've tried reinstalling node and npm, but it always seems to stop on node-sass.
npm install runs just fine on all my laravel projects. This only happens on the two projects that I've pulled recently that almost entirely Vue.js and typescript so I'm not sure if that may be the issue.

Edit: I tried delete my local version, pull from github and run npm install again and got this error. It was a bit of a mammoth error so I've had to delet a big chunk of it to fit it into the post.

```<code>2863 error code 1
2864 error path /*my path*/node_modules/node-sass
2865 error command failed
2866 error command sh -c node scripts/build.js
2867 error Building: /opt/homebrew/Cellar/node/16.10.0/bin/node /Users/scott/Dev/KPro/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
2867 error   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_GLIBCXX_USE_CXX11_ABI=1' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.5.5"' -I/Users/scott/.node-gyp/16.10.0/include/node -I/Users/scott/.node-gyp/16.10.0/src -I/Users/scott/.node-gyp/16.10.0/deps/openssl/config -I/Users/scott/.node-gyp/16.10.0/deps/openssl/openssl/include -I/Users/scott/.node-gyp/16.10.0/deps/uv/include -I/Users/scott/.node-gyp/16.10.0/deps/zlib -I/Users/scott/.node-gyp/16.10.0/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/ast.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/ast.o ../src/libsass/src/ast.cpp
2867 error   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_GLIBCXX_USE_CXX11_ABI=1' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.5.5"' -I/Users/scott/.node-gyp/16.10.0/include/node -I/Users/scott/.node-gyp/16.10.0/src -I/Users/scott/.node-gyp/16.10.0/deps/openssl/config -I/Users/scott/.node-gyp/16.10.0/deps/openssl/openssl/include -I/Users/scott/.node-gyp/16.10.0/deps/uv/include -I/Users/scott/.node-gyp/16.10.0/deps/zlib -I/Users/scott/.node-gyp/16.10.0/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/ast_fwd_decl.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/ast_fwd_decl.o ../src/libsass/src/ast_fwd_decl.cpp

2868 error gyp info it worked if it ends with ok
2868 error gyp verb cli [
2868 error gyp verb cli   '/opt/homebrew/Cellar/node/16.10.0/bin/node',
2868 error gyp verb cli   '/*my path*/node_modules/node-gyp/bin/node-gyp.js',
2868 error gyp verb cli   'rebuild',
2868 error gyp verb cli   '--verbose',
2868 error gyp verb cli   '--libsass_ext=',
2868 error gyp verb cli   '--libsass_cflags=',
2868 error gyp verb cli   '--libsass_ldflags=',
2868 error gyp verb cli   '--libsass_library='
2868 error gyp verb cli ]
2868 error gyp info using node-gyp@3.8.0
2868 error gyp info using node@16.10.0 | darwin | arm64
2868 error gyp verb command rebuild []
2868 error gyp verb command clean []
2868 error gyp verb clean removing "build" directory
2868 error gyp verb command configure []
2868 error gyp verb check python checking for Python executable "python2" in the PATH
2868 error gyp verb `which` succeeded python2 /usr/bin/python2
2868 error gyp verb check python version `/usr/bin/python2 -c "import sys; print "2.7.16
2868 error gyp verb check python version .%s.%s" % sys.version_info[:3];"` returned: %j
2868 error gyp verb get node dir no --target version specified, falling back to host node version: 16.10.0
2868 error gyp verb command install [ '16.10.0' ]
2868 error gyp verb install input version string "16.10.0"
2868 error gyp verb install installing version: 16.10.0
2868 error gyp verb install --ensure was passed, so won't reinstall if already installed
2868 error gyp verb install version is already installed, need to check "installVersion"
2868 error gyp verb got "installVersion" 9
2868 error gyp verb needs "installVersion" 9
2868 error gyp verb install version is good
2868 error gyp verb get node dir target node version installed: 16.10.0
2868 error gyp verb build dir attempting to create "build" dir: /Users/scott/Dev/KPro/node_modules/node-sass/build
2868 error gyp verb build dir "build" dir needed to be created? /Users/scott/Dev/KPro/node_modules/node-sass/build
2868 error gyp verb build/config.gypi creating config file
2868 error gyp verb build/config.gypi writing out config file: /*my path*/node_modules/node-sass/build/config.gypi
2868 error (node:57324) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
2868 error (Use `node --trace-deprecation ...` to show where the warning was created)
2868 error gyp verb config.gypi checking for gypi file: /*my path*/node_modules/node-sass/config.gypi
2868 error gyp verb common.gypi checking for gypi file: /*my path*/node_modules/node-sass/common.gypi
2868 error gyp verb gyp gyp format was not specified; forcing "make"
2868 error gyp info spawn /usr/bin/python2
2868 error gyp info spawn args [
2868 error gyp info spawn args   '/*my path*/node_modules/node-gyp/gyp/gyp_main.py',
2868 error gyp info spawn args   'binding.gyp',
2868 error gyp info spawn args   '-f',
2868 error gyp info spawn args   'make',
2868 error gyp info spawn args   '-I',
2868 error gyp info spawn args   '/*my path*/node_modules/node-sass/build/config.gypi',
2868 error gyp info spawn args   '-I',
2868 error gyp info spawn args   '/*my path*/node_modules/node-gyp/addon.gypi',
2868 error gyp info spawn args   '-I',
2868 error gyp info spawn args   '/Users/scott/.node-gyp/16.10.0/include/node/common.gypi',
2868 error gyp info spawn args   '-Dlibrary=shared_library',
2868 error gyp info spawn args   '-Dvisibility=default',
2868 error gyp info spawn args   '-Dnode_root_dir=/Users/scott/.node-gyp/16.10.0',
2868 error gyp info spawn args   '-Dnode_gyp_dir=/Users/scott/Dev/KPro/node_modules/node-gyp',
2868 error gyp info spawn args   '-Dnode_lib_file=/Users/scott/.node-gyp/16.10.0/<(target_arch)/node.lib',
2868 error gyp info spawn args   '-Dmodule_root_dir=/*my path*/node_modules/node-sass',
2868 error gyp info spawn args   '-Dnode_engine=v8',
2868 error gyp info spawn args   '--depth=.',
2868 error gyp info spawn args   '--no-parallel',
2868 error gyp info spawn args   '--generator-output',
2868 error gyp info spawn args   'build',
2868 error gyp info spawn args   '-Goutput_dir=.'
2868 error gyp info spawn args ]
2868 error gyp verb command build []
2868 error gyp verb build type Release
2868 error gyp verb architecture arm64
2868 error gyp verb node dev dir /Users/scott/.node-gyp/16.10.0
2868 error gyp verb `which` succeeded for `make` /usr/bin/make
2868 error gyp info spawn make
2868 error gyp info spawn args [ 'V=1', 'BUILDTYPE=Release', '-C', 'build' ]

2868 error 2 warnings generated.
2868 error In file included from ../src/libsass/src/ast_fwd_decl.cpp:1:
2868 error ../src/libsass/src/ast.hpp:1614:25: warning: loop variable 'numerator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
2868 error         for (const auto numerator : numerators)
2868 error                         ^
2868 error ../src/libsass/src/ast.hpp:1614:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
2868 error         for (const auto numerator : numerators)
2868 error              ^~~~~~~~~~~~~~~~~~~~~~
2868 error                         &
2868 error ../src/libsass/src/ast.hpp:1616:25: warning: loop variable 'denominator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
2868 error         for (const auto denominator : denominators)
2868 error                         ^
2868 error ../src/libsass/src/ast.hpp:1616:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
2868 error         for (const auto denominator : denominators)
2868 error              ^~~~~~~~~~~~~~~~~~~~~~~~

2868 error                                      remove_cv
2868 error /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:776:50: note: 'remove_cv' declared here
2868 error template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv
2868 error                                                  ^
2868 error 1 error generated.
2868 error make: *** [Release/obj.target/binding/src/binding.o] Error 1
2868 error gyp ERR! build error
2868 error gyp ERR! stack Error: `make` failed with exit code: 2
2868 error gyp ERR! stack     at ChildProcess.onExit (/*my path*/node_modules/node-gyp/lib/build.js:262:23)
2868 error gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
2868 error gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
2868 error gyp ERR! System Darwin 20.6.0
2868 error gyp ERR! command "/opt/homebrew/Cellar/node/16.10.0/bin/node" "/*my path*/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
2868 error gyp ERR! cwd /*my path*/node_modules/node-sass
2868 error gyp ERR! node -v v16.10.0
2868 error gyp ERR! node-gyp -v v3.8.0
2868 error gyp ERR! not ok
2868 error Build failed with error code: 1
2869 verbose exit 1
</code>```

答:
I fixed this by adding these to my devDependencies in package.json:

```<code>"node-pre-gyp": "0.17.0",
"fsevents": "2.2.1"
</code>```

Found in https://github.com/nodejs/node-gyp/issues/2296

Body:
I'm getting the following errors whenever I run npm install on a vue.js project

5769 error code 1
5770 error path /*my path*/node_modules/node-sass
5771 error command failed
5772 error command sh -c node scripts/install.js
5773 error /*my path*/node_modules/request/index.js:30
5773 error   if (options !== null && typeof op
5773 error
5773 error
5773 error SyntaxError: Unexpected end of input
5773 error     at Object.compileFunction (node:vm:352:18)
5773 error     at wrapSafe (node:internal/modules/cjs/loader:1031:15)
5773 error     at Module._compile (node:internal/modules/cjs/loader:1065:27)
5773 error     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
5773 error     at Module.load (node:internal/modules/cjs/loader:981:32)
5773 error     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
5773 error     at Module.require (node:internal/modules/cjs/loader:1005:19)
5773 error     at require (node:internal/modules/cjs/helpers:102:18)
5773 error     at Object.<anonymous> (/*my path*/node_modules/node-sass/scripts/install.js:10:13)
5773 error     at Module._compile (node:internal/modules/cjs/loader:1101:14)
5774 verbose exit 1

I've tried reinstalling node and npm, but it always seems to stop on node-sass.
npm install runs just fine on all my laravel projects. This only happens on the two projects that I've pulled recently that almost entirely Vue.js and typescript so I'm not sure if that may be the issue.

Edit: I tried delete my local version, pull from github and run npm install again and got this error. It was a bit of a mammoth error so I've had to delet a big chunk of it to fit it into the post.

2863 error code 1
2864 error path /*my path*/node_modules/node-sass
2865 error command failed
2866 error command sh -c node scripts/build.js
2867 error Building: /opt/homebrew/Cellar/node/16.10.0/bin/node /Users/scott/Dev/KPro/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
2867 error   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_GLIBCXX_USE_CXX11_ABI=1' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.5.5"' -I/Users/scott/.node-gyp/16.10.0/include/node -I/Users/scott/.node-gyp/16.10.0/src -I/Users/scott/.node-gyp/16.10.0/deps/openssl/config -I/Users/scott/.node-gyp/16.10.0/deps/openssl/openssl/include -I/Users/scott/.node-gyp/16.10.0/deps/uv/include -I/Users/scott/.node-gyp/16.10.0/deps/zlib -I/Users/scott/.node-gyp/16.10.0/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/ast.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/ast.o ../src/libsass/src/ast.cpp
2867 error   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_GLIBCXX_USE_CXX11_ABI=1' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.5.5"' -I/Users/scott/.node-gyp/16.10.0/include/node -I/Users/scott/.node-gyp/16.10.0/src -I/Users/scott/.node-gyp/16.10.0/deps/openssl/config -I/Users/scott/.node-gyp/16.10.0/deps/openssl/openssl/include -I/Users/scott/.node-gyp/16.10.0/deps/uv/include -I/Users/scott/.node-gyp/16.10.0/deps/zlib -I/Users/scott/.node-gyp/16.10.0/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/ast_fwd_decl.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/ast_fwd_decl.o ../src/libsass/src/ast_fwd_decl.cpp

2868 error gyp info it worked if it ends with ok
2868 error gyp verb cli [
2868 error gyp verb cli   '/opt/homebrew/Cellar/node/16.10.0/bin/node',
2868 error gyp verb cli   '/*my path*/node_modules/node-gyp/bin/node-gyp.js',
2868 error gyp verb cli   'rebuild',
2868 error gyp verb cli   '--verbose',
2868 error gyp verb cli   '--libsass_ext=',
2868 error gyp verb cli   '--libsass_cflags=',
2868 error gyp verb cli   '--libsass_ldflags=',
2868 error gyp verb cli   '--libsass_library='
2868 error gyp verb cli ]
2868 error gyp info using node-gyp@3.8.0
2868 error gyp info using node@16.10.0 | darwin | arm64
2868 error gyp verb command rebuild []
2868 error gyp verb command clean []
2868 error gyp verb clean removing "build" directory
2868 error gyp verb command configure []
2868 error gyp verb check python checking for Python executable "python2" in the PATH
2868 error gyp verb `which` succeeded python2 /usr/bin/python2
2868 error gyp verb check python version `/usr/bin/python2 -c "import sys; print "2.7.16
2868 error gyp verb check python version .%s.%s" % sys.version_info[:3];"` returned: %j
2868 error gyp verb get node dir no --target version specified, falling back to host node version: 16.10.0
2868 error gyp verb command install [ '16.10.0' ]
2868 error gyp verb install input version string "16.10.0"
2868 error gyp verb install installing version: 16.10.0
2868 error gyp verb install --ensure was passed, so won't reinstall if already installed
2868 error gyp verb install version is already installed, need to check "installVersion"
2868 error gyp verb got "installVersion" 9
2868 error gyp verb needs "installVersion" 9
2868 error gyp verb install version is good
2868 error gyp verb get node dir target node version installed: 16.10.0
2868 error gyp verb build dir attempting to create "build" dir: /Users/scott/Dev/KPro/node_modules/node-sass/build
2868 error gyp verb build dir "build" dir needed to be created? /Users/scott/Dev/KPro/node_modules/node-sass/build
2868 error gyp verb build/config.gypi creating config file
2868 error gyp verb build/config.gypi writing out config file: /*my path*/node_modules/node-sass/build/config.gypi
2868 error (node:57324) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
2868 error (Use `node --trace-deprecation ...` to show where the warning was created)
2868 error gyp verb config.gypi checking for gypi file: /*my path*/node_modules/node-sass/config.gypi
2868 error gyp verb common.gypi checking for gypi file: /*my path*/node_modules/node-sass/common.gypi
2868 error gyp verb gyp gyp format was not specified; forcing "make"
2868 error gyp info spawn /usr/bin/python2
2868 error gyp info spawn args [
2868 error gyp info spawn args   '/*my path*/node_modules/node-gyp/gyp/gyp_main.py',
2868 error gyp info spawn args   'binding.gyp',
2868 error gyp info spawn args   '-f',
2868 error gyp info spawn args   'make',
2868 error gyp info spawn args   '-I',
2868 error gyp info spawn args   '/*my path*/node_modules/node-sass/build/config.gypi',
2868 error gyp info spawn args   '-I',
2868 error gyp info spawn args   '/*my path*/node_modules/node-gyp/addon.gypi',
2868 error gyp info spawn args   '-I',
2868 error gyp info spawn args   '/Users/scott/.node-gyp/16.10.0/include/node/common.gypi',
2868 error gyp info spawn args   '-Dlibrary=shared_library',
2868 error gyp info spawn args   '-Dvisibility=default',
2868 error gyp info spawn args   '-Dnode_root_dir=/Users/scott/.node-gyp/16.10.0',
2868 error gyp info spawn args   '-Dnode_gyp_dir=/Users/scott/Dev/KPro/node_modules/node-gyp',
2868 error gyp info spawn args   '-Dnode_lib_file=/Users/scott/.node-gyp/16.10.0/<(target_arch)/node.lib',
2868 error gyp info spawn args   '-Dmodule_root_dir=/*my path*/node_modules/node-sass',
2868 error gyp info spawn args   '-Dnode_engine=v8',
2868 error gyp info spawn args   '--depth=.',
2868 error gyp info spawn args   '--no-parallel',
2868 error gyp info spawn args   '--generator-output',
2868 error gyp info spawn args   'build',
2868 error gyp info spawn args   '-Goutput_dir=.'
2868 error gyp info spawn args ]
2868 error gyp verb command build []
2868 error gyp verb build type Release
2868 error gyp verb architecture arm64
2868 error gyp verb node dev dir /Users/scott/.node-gyp/16.10.0
2868 error gyp verb `which` succeeded for `make` /usr/bin/make
2868 error gyp info spawn make
2868 error gyp info spawn args [ 'V=1', 'BUILDTYPE=Release', '-C', 'build' ]

2868 error 2 warnings generated.
2868 error In file included from ../src/libsass/src/ast_fwd_decl.cpp:1:
2868 error ../src/libsass/src/ast.hpp:1614:25: warning: loop variable 'numerator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
2868 error         for (const auto numerator : numerators)
2868 error                         ^
2868 error ../src/libsass/src/ast.hpp:1614:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
2868 error         for (const auto numerator : numerators)
2868 error              ^~~~~~~~~~~~~~~~~~~~~~
2868 error                         &
2868 error ../src/libsass/src/ast.hpp:1616:25: warning: loop variable 'denominator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
2868 error         for (const auto denominator : denominators)
2868 error                         ^
2868 error ../src/libsass/src/ast.hpp:1616:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
2868 error         for (const auto denominator : denominators)
2868 error              ^~~~~~~~~~~~~~~~~~~~~~~~

2868 error                                      remove_cv
2868 error /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:776:50: note: 'remove_cv' declared here
2868 error template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv
2868 error                                                  ^
2868 error 1 error generated.
2868 error make: *** [Release/obj.target/binding/src/binding.o] Error 1
2868 error gyp ERR! build error
2868 error gyp ERR! stack Error: `make` failed with exit code: 2
2868 error gyp ERR! stack     at ChildProcess.onExit (/*my path*/node_modules/node-gyp/lib/build.js:262:23)
2868 error gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
2868 error gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
2868 error gyp ERR! System Darwin 20.6.0
2868 error gyp ERR! command "/opt/homebrew/Cellar/node/16.10.0/bin/node" "/*my path*/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
2868 error gyp ERR! cwd /*my path*/node_modules/node-sass
2868 error gyp ERR! node -v v16.10.0
2868 error gyp ERR! node-gyp -v v3.8.0
2868 error gyp ERR! not ok
2868 error Build failed with error code: 1
2869 verbose exit 1

Body:
I fixed this by adding these to my devDependencies in package.json:

"node-pre-gyp": "0.17.0",
"fsevents": "2.2.1"

Found in https://github.com/nodejs/node-gyp/issues/2296


问:
How to represent as a matrix a 4-column dataframe, where column 0 specifies row, columns 1-2 specify column range, and column 3 specifies entry
I have a four-column data frame, given as follows: Column zero consists of text labels chosen from a list ['A','B','C','D'] with possible repetitions. Columns one-two are labelled, start and stop, where the former is less than the latter, and column three, intensity, is a float. For each label, none of the corresponding intervals formed using [start,stop] overlap.

A simple example is given by:

```<code>import numpy as np
import pandas as pd
labels=['A','B','C','D']
d = {'label': ['A','B','A','C','D','B','A'],'start': [1, 2,6,4,1,8,12], 'stop':
[4,4,9,6,7,11,16],'intensity':[8,2,4,6,7,1,5]}
df = pd.DataFrame(data=d)
print(df)

  label  start  stop  intensity
0     A      1     4          8
1     B      2     4          2
2     A      6     9          4
3     C      4     6          6
4     D      1     7          7
5     B      8    11          1
6     A     12    16          5
</code>```

I wish to create a matrix, M, having four (=len(labels)) rows and 16 columns. (The number of columns must be at least the maximum entry in df['stop']. Whether it's larger doesn't matter). For each integer k between 0 and 6, the index of df['label'][k] in labels specifies a row of my matrix M. The entries in columns d[start][k] to d[stop][k] of this row should all equal d['intensity'][k]. All other entries of M equal zero.

For example, label A corresponds to rows 0, 2, and 6. In row 0, entries in columns 1-4 equal 8, entries in columns 6-9 equal 4, and entries in columns 12-16 equal 5.

I'd like to do this in the most pythonic way using list operations and at most one loop.

答:
Here's a solution:

```<code>MAX = df['stop'].max()
new_df = pd.DataFrame(df.groupby('label').apply(lambda g: sum(g.apply(lambda x: np.isin(np.arange(MAX), np.arange(x['start']-1, x['stop'])).astype(int)*x['intensity'], axis=1))).tolist(), index=labels)
</code>```

Output:

```<code>>>> new_df
    0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
A   8   8   8   8   0   4   4   4   4   0   0   5   5   5   5   5
B   0   2   2   2   0   0   0   1   1   1   1   0   0   0   0   0
C   0   0   0   6   6   6   0   0   0   0   0   0   0   0   0   0
D   7   7   7   7   7   7   7   0   0   0   0   0   0   0   0   0
</code>```

Body:
I have a four-column data frame, given as follows: Column zero consists of text labels chosen from a list ['A','B','C','D'] with possible repetitions. Columns one-two are labelled, start and stop, where the former is less than the latter, and column three, intensity, is a float. For each label, none of the corresponding intervals formed using [start,stop] overlap.

A simple example is given by:

import numpy as np
import pandas as pd
labels=['A','B','C','D']
d = {'label': ['A','B','A','C','D','B','A'],'start': [1, 2,6,4,1,8,12], 'stop':
[4,4,9,6,7,11,16],'intensity':[8,2,4,6,7,1,5]}
df = pd.DataFrame(data=d)
print(df)

  label  start  stop  intensity
0     A      1     4          8
1     B      2     4          2
2     A      6     9          4
3     C      4     6          6
4     D      1     7          7
5     B      8    11          1
6     A     12    16          5

I wish to create a matrix, M, having four (=len(labels)) rows and 16 columns. (The number of columns must be at least the maximum entry in df['stop']. Whether it's larger doesn't matter). For each integer k between 0 and 6, the index of df['label'][k] in labels specifies a row of my matrix M. The entries in columns d[start][k] to d[stop][k] of this row should all equal d['intensity'][k]. All other entries of M equal zero.

For example, label A corresponds to rows 0, 2, and 6. In row 0, entries in columns 1-4 equal 8, entries in columns 6-9 equal 4, and entries in columns 12-16 equal 5.

I'd like to do this in the most pythonic way using list operations and at most one loop.

Body:
Here's a solution:

MAX = df['stop'].max()
new_df = pd.DataFrame(df.groupby('label').apply(lambda g: sum(g.apply(lambda x: np.isin(np.arange(MAX), np.arange(x['start']-1, x['stop'])).astype(int)*x['intensity'], axis=1))).tolist(), index=labels)

Output:

>>> new_df
    0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
A   8   8   8   8   0   4   4   4   4   0   0   5   5   5   5   5
B   0   2   2   2   0   0   0   1   1   1   1   0   0   0   0   0
C   0   0   0   6   6   6   0   0   0   0   0   0   0   0   0   0
D   7   7   7   7   7   7   7   0   0   0   0   0   0   0   0   0


问:
runZonedGuarded in flutter
```<code>// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'dart:async';
import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';

class AppBlocObserver extends BlocObserver {
  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    log('onChange(${bloc.runtimeType}, $change)');
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    log('onError(${bloc.runtimeType}, $error, $stackTrace)');
    super.onError(bloc, error, stackTrace);
  }
}

Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
  Bloc.observer = AppBlocObserver();
  FlutterError.onError = (details) {
    log(details.exceptionAsString(), stackTrace: details.stack);
  };

  await runZonedGuarded(
    () async => runApp(await builder()),
    (error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
  );
}
</code>```

Can someone explain this code snippet, I am just confused with runZonedGuarded() and bootstrap(FutureOr Function() builder). This code generated by very_good CLI, which will create a starter boilerplate for flutter app.

答:
Future<void> bootstrap(FutureOr<Widget> Function() builder) async { ...

is defining a function called bootstrap. This function takes a parameter called builder that is a

function taking no parameters

returning a Future or a Widget

and it will execute asynchronously (builder may or may not execute asynchronously).

The Bloc.observer = AppBlocObserver(); is a deprecated way of observing what the bloc(s) of the application are doing. The AppBlocObserver is defining a bunch of callbacks that will be executed when "events" are fired, like error, and change.

With version >= 8.0 of the BLoC- library you should likely do something like below instead of the run zone guarded postend in the question, since they moved the bloc observer property.

```<code>runZonedGuarded(
  () => BlocOverrides.runZoned(
    () async => runApp(await builder()),
    blocObserver: AppBlocObserver()
  ),
  (error, stackTrace) => log(error.toString(), stackTrace: stackTrace));
</code>```

This 'builder' method that's potentially an async method - or not - is then going to be executed and the returning widget is going to be the parameter to runApp - witch is going to

Inflate the given widget and attach it to the screen.

That app is then going to be run in an error zone, where the interesting part is

The onError function is used both to handle asynchronous errors by overriding ZoneSpecification.handleUncaughtError in zoneSpecification, if any, and to handle errors thrown synchronously by the call to body.

Title: runZonedGuarded in flutter

Body:
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'dart:async';
import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';

class AppBlocObserver extends BlocObserver {
  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    log('onChange(${bloc.runtimeType}, $change)');
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    log('onError(${bloc.runtimeType}, $error, $stackTrace)');
    super.onError(bloc, error, stackTrace);
  }
}

Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
  Bloc.observer = AppBlocObserver();
  FlutterError.onError = (details) {
    log(details.exceptionAsString(), stackTrace: details.stack);
  };

  await runZonedGuarded(
    () async => runApp(await builder()),
    (error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
  );
}

Can someone explain this code snippet, I am just confused with runZonedGuarded() and bootstrap(FutureOr Function() builder). This code generated by very_good CLI, which will create a starter boilerplate for flutter app.

Body:
Future<void> bootstrap(FutureOr<Widget> Function() builder) async { ...

is defining a function called bootstrap. This function takes a parameter called builder that is a

function taking no parameters

returning a Future or a Widget

and it will execute asynchronously (builder may or may not execute asynchronously).

The Bloc.observer = AppBlocObserver(); is a deprecated way of observing what the bloc(s) of the application are doing. The AppBlocObserver is defining a bunch of callbacks that will be executed when "events" are fired, like error, and change.

With version >= 8.0 of the BLoC- library you should likely do something like below instead of the run zone guarded postend in the question, since they moved the bloc observer property.

runZonedGuarded(
  () => BlocOverrides.runZoned(
    () async => runApp(await builder()),
    blocObserver: AppBlocObserver()
  ),
  (error, stackTrace) => log(error.toString(), stackTrace: stackTrace));

This 'builder' method that's potentially an async method - or not - is then going to be executed and the returning widget is going to be the parameter to runApp - witch is going to

Inflate the given widget and attach it to the screen.

That app is then going to be run in an error zone, where the interesting part is

The onError function is used both to handle asynchronous errors by overriding ZoneSpecification.handleUncaughtError in zoneSpecification, if any, and to handle errors thrown synchronously by the call to body.


问:
K8s cluster is healthy, but kubelet display unusual message repeatedly every minute
My k8s-env1 is on-premise and running well. I can create/get/describe/delete any k8s object.

However, I found kubelet display following message every minute, but it does not present in my another k8s-env2. Is this message ok on k8s-env1?

```<code>Feb 10 10:39:09 k8s-env1 kubelet[15461]: I0210 10:39:09.808611   15461 kubelet_getters.go:172] status for pod kube-controller-manager-k8s-env1 updated to {Running [{Initialized True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {Ready True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {ContainersReady True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {PodScheduled True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  }]    192.168.1.2 192.168.1.2 [{192.168.1.2}] 2022-02-10 09:32:58 +0800 CST [] [{kube-controller-manager {nil &ContainerStateRunning{StartedAt:2022-02-10 09:40:36 +0800 CST,} nil} {nil nil &ContainerStateTerminated{ExitCode:2,Signal:0,Reason:Error,Message:,StartedAt:2022-02-10 09:23:08 +0800 CST,FinishedAt:2022-02-10 09:38:13 +0800 CST,ContainerID:docker://1cc6e402be458374d365b6e379e7205267279c4da554c2207baca11cc1609be9,}} true 202 k8s.gcr.io/kube-controller-manager:v1.16.15 docker-pullable://k8s.gcr.io/kube-controller-manager@sha256:da7ac5487dc7b6eddfb4fbdf39af92bc065416a7dac147a937a39aff72716fe9 docker://7d0aa1e7ae3e3463347d68c644f45f97933ca819a4231b79a7fedcb5f8792dc6 0xc00189beb6}] Burstable []}
Feb 10 10:39:09 k8s-env1 kubelet[15461]: I0210 10:39:09.808770   15461 kubelet_getters.go:172] status for pod kube-scheduler-k8s-env1 updated to {Running [{Initialized True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {Ready True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {ContainersReady True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {PodScheduled True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  }]    192.168.1.2 192.168.1.2 [{192.168.1.2}] 2022-02-10 09:32:58 +0800 CST [] [{kube-scheduler {nil &ContainerStateRunning{StartedAt:2022-02-10 09:40:40 +0800 CST,} nil} {nil nil &ContainerStateTerminated{ExitCode:2,Signal:0,Reason:Error,Message:,StartedAt:2022-02-10 09:23:06 +0800 CST,FinishedAt:2022-02-10 09:38:14 +0800 CST,ContainerID:docker://94860e938310683e1a478d681256e649c00ba74570e70963b76804f60480b7a0,}} true 201 k8s.gcr.io/kube-scheduler:v1.16.15 docker-pullable://k8s.gcr.io/kube-scheduler@sha256:d9156baf649cd356bad6be119a62cf137b73956957604275ab8e3008bee96c8f docker://d626ea52253994ca2ee7d5b61ead84dacb0b99fd8f21b21268d92d53451e09af 0xc001c91189}] Burstable []}
Feb 10 10:39:09 k8s-env1 kubelet[15461]: I0210 10:39:09.808814   15461 kubelet_getters.go:172] status for pod kube-apiserver-k8s-env1 updated to {Running [{Initialized True 0001-01-01 00:00:00 +0000 UTC 2022-01-17 00:27:28 +0800 CST  } {Ready True 0001-01-01 00:00:00 +0000 UTC 2022-01-28 13:17:18 +0800 CST  } {ContainersReady True 0001-01-01 00:00:00 +0000 UTC 2022-01-17 00:38:58 +0800 CST  } {PodScheduled True 0001-01-01 00:00:00 +0000 UTC 2022-01-17 00:27:28 +0800 CST  }]    192.168.1.2 192.168.1.2 [{192.168.1.2}] 2022-01-17 00:27:28 +0800 CST [] [{kube-apiserver {nil &ContainerStateRunning{StartedAt:2022-02-10 09:40:33 +0800 CST,} nil} {nil nil &ContainerStateTerminated{ExitCode:137,Signal:0,Reason:Error,Message:,StartedAt:2022-02-10 09:23:05 +0800 CST,FinishedAt:2022-02-10 09:38:24 +0800 CST,ContainerID:docker://fcc0d48a9398656adc3e071b37f0f502ab45f0730e0d9ad51401db2b856fe1f3,}} true 16 k8s.gcr.io/kube-apiserver:v1.16.15 docker-pullable://k8s.gcr.io/kube-apiserver@sha256:58075c15f5978b4b73e58b004bb3a1856ad58a9061ac3075ef860207ba00ac75 docker://95a526b063d00b5eb497dc3280a0cf4610fec31a072685eb7279f5207dcc27b1 0xc00156e74c}] Burstable []}
Feb 10 10:39:10 k8s-env1 kubelet[15461]: I0210 10:39:10.064116   15461 kubelet_network_linux.go:141] Not using `--random-fully` in the MASQUERADE rule for iptables because the local version of iptables does not support it

</code>```

答:
In theory this shouldn't affect any functionality, but to.get rid  of this you can try installing a iptables version(1.6.2) which has support to the random fully. Something like this should do

Run the following inside the kubelet and reboot once done

```<code>        apt remove --purge iptables && \
        apt autoremove -y && \
        clean-install libip4tc0=1.6.2-1.1~bpo9+1 \
        libip6tc0=1.6.2-1.1~bpo9+1 \
        libiptc0=1.6.2-1.1~bpo9+1 \
        libxtables12=1.6.2-1.1~bpo9+1 \
        iptables=1.6.2-1.1~bpo9+1
</code>```

Body:
My k8s-env1 is on-premise and running well. I can create/get/describe/delete any k8s object.

However, I found kubelet display following message every minute, but it does not present in my another k8s-env2. Is this message ok on k8s-env1?

Feb 10 10:39:09 k8s-env1 kubelet[15461]: I0210 10:39:09.808611   15461 kubelet_getters.go:172] status for pod kube-controller-manager-k8s-env1 updated to {Running [{Initialized True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {Ready True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {ContainersReady True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {PodScheduled True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  }]    192.168.1.2 192.168.1.2 [{192.168.1.2}] 2022-02-10 09:32:58 +0800 CST [] [{kube-controller-manager {nil &ContainerStateRunning{StartedAt:2022-02-10 09:40:36 +0800 CST,} nil} {nil nil &ContainerStateTerminated{ExitCode:2,Signal:0,Reason:Error,Message:,StartedAt:2022-02-10 09:23:08 +0800 CST,FinishedAt:2022-02-10 09:38:13 +0800 CST,ContainerID:docker://1cc6e402be458374d365b6e379e7205267279c4da554c2207baca11cc1609be9,}} true 202 k8s.gcr.io/kube-controller-manager:v1.16.15 docker-pullable://k8s.gcr.io/kube-controller-manager@sha256:da7ac5487dc7b6eddfb4fbdf39af92bc065416a7dac147a937a39aff72716fe9 docker://7d0aa1e7ae3e3463347d68c644f45f97933ca819a4231b79a7fedcb5f8792dc6 0xc00189beb6}] Burstable []}
Feb 10 10:39:09 k8s-env1 kubelet[15461]: I0210 10:39:09.808770   15461 kubelet_getters.go:172] status for pod kube-scheduler-k8s-env1 updated to {Running [{Initialized True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {Ready True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {ContainersReady True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  } {PodScheduled True 0001-01-01 00:00:00 +0000 UTC 2022-02-10 09:32:58 +0800 CST  }]    192.168.1.2 192.168.1.2 [{192.168.1.2}] 2022-02-10 09:32:58 +0800 CST [] [{kube-scheduler {nil &ContainerStateRunning{StartedAt:2022-02-10 09:40:40 +0800 CST,} nil} {nil nil &ContainerStateTerminated{ExitCode:2,Signal:0,Reason:Error,Message:,StartedAt:2022-02-10 09:23:06 +0800 CST,FinishedAt:2022-02-10 09:38:14 +0800 CST,ContainerID:docker://94860e938310683e1a478d681256e649c00ba74570e70963b76804f60480b7a0,}} true 201 k8s.gcr.io/kube-scheduler:v1.16.15 docker-pullable://k8s.gcr.io/kube-scheduler@sha256:d9156baf649cd356bad6be119a62cf137b73956957604275ab8e3008bee96c8f docker://d626ea52253994ca2ee7d5b61ead84dacb0b99fd8f21b21268d92d53451e09af 0xc001c91189}] Burstable []}
Feb 10 10:39:09 k8s-env1 kubelet[15461]: I0210 10:39:09.808814   15461 kubelet_getters.go:172] status for pod kube-apiserver-k8s-env1 updated to {Running [{Initialized True 0001-01-01 00:00:00 +0000 UTC 2022-01-17 00:27:28 +0800 CST  } {Ready True 0001-01-01 00:00:00 +0000 UTC 2022-01-28 13:17:18 +0800 CST  } {ContainersReady True 0001-01-01 00:00:00 +0000 UTC 2022-01-17 00:38:58 +0800 CST  } {PodScheduled True 0001-01-01 00:00:00 +0000 UTC 2022-01-17 00:27:28 +0800 CST  }]    192.168.1.2 192.168.1.2 [{192.168.1.2}] 2022-01-17 00:27:28 +0800 CST [] [{kube-apiserver {nil &ContainerStateRunning{StartedAt:2022-02-10 09:40:33 +0800 CST,} nil} {nil nil &ContainerStateTerminated{ExitCode:137,Signal:0,Reason:Error,Message:,StartedAt:2022-02-10 09:23:05 +0800 CST,FinishedAt:2022-02-10 09:38:24 +0800 CST,ContainerID:docker://fcc0d48a9398656adc3e071b37f0f502ab45f0730e0d9ad51401db2b856fe1f3,}} true 16 k8s.gcr.io/kube-apiserver:v1.16.15 docker-pullable://k8s.gcr.io/kube-apiserver@sha256:58075c15f5978b4b73e58b004bb3a1856ad58a9061ac3075ef860207ba00ac75 docker://95a526b063d00b5eb497dc3280a0cf4610fec31a072685eb7279f5207dcc27b1 0xc00156e74c}] Burstable []}
Feb 10 10:39:10 k8s-env1 kubelet[15461]: I0210 10:39:10.064116   15461 kubelet_network_linux.go:141] Not using `--random-fully` in the MASQUERADE rule for iptables because the local version of iptables does not support it

Body:
In theory this shouldn't affect any functionality, but to.get rid  of this you can try installing a iptables version(1.6.2) which has support to the random fully. Something like this should do

Run the following inside the kubelet and reboot once done

        apt remove --purge iptables && \
        apt autoremove -y && \
        clean-install libip4tc0=1.6.2-1.1~bpo9+1 \
        libip6tc0=1.6.2-1.1~bpo9+1 \
        libiptc0=1.6.2-1.1~bpo9+1 \
        libxtables12=1.6.2-1.1~bpo9+1 \
        iptables=1.6.2-1.1~bpo9+1


问:
how could I use 2 foreach in Laravel using 1 view

الكورس الاول

    @foreach ($data as $item)

{{$item->name}}

            show lectures

    @endforeach

الكورس الثاني

    @foreach ($data2 as $item)

{{$item->name}}

            show lectures

    @endforeach

```

答:
If I'm understanding your question correctly.

You can nest @foreach statements like so

```<code>@foreach ($list1 as $item1)
     ...
     @foreach ($list2 as $item2)
          ...
     @endforeach
     ...
@endforeach
</code>```

You would obviously want to use better names for the variables than in my sample. You do not need to have additional statements between the loops. The "..." is there to show you can.

Body:
If I'm understanding your question correctly.

You can nest @foreach statements like so

@foreach ($list1 as $item1)
     ...
     @foreach ($list2 as $item2)
          ...
     @endforeach
     ...
@endforeach

You would obviously want to use better names for the variables than in my sample. You do not need to have additional statements between the loops. The "..." is there to show you can.


问:
Yarn - How do I update each dependency in package.json to the latest version?
I have a react app with deprecated dependencies. To make it work, I have to update the dependencies to their newer (but stable) versions.

As per this stakoverflow thread, to update dependencies in package.json to latest versions, npm-check-updates is the Best Option for npm. However, I'm using yarn for package management. Is there an equivalent of npm-check-updates in yarn. So that, I use a single package manager to manage my dependencies.

答:
In case you wanted to add the package to your package.json for development collaboration

```<code>yarn add yarn-upgrade-all -D
</code>```
```<code>yarn yarn-upgrade-all
</code>```

By the way, the package uses the command ( reinstall all packages again )

```<code>yarn install package1 package2 packageN
</code>```

Body:
In case you wanted to add the package to your package.json for development collaboration

yarn add yarn-upgrade-all -D

yarn yarn-upgrade-all

By the way, the package uses the command ( reinstall all packages again )

yarn install package1 package2 packageN


问:
How do you get the physical drive number of a removable device from the drive letter in Windows 7?
I'm trying to look up the physical drive number (as in, I need the N in \\.\PhysicalDriveN to open the block device for reading) from the drive letter of a CDROM drive on Windows 7. This page indicates that IOCTL_STORAGE_GET_DEVICE_NUMBER should work, but it returns 0 for the drive number for both C: and D: (where D: is the removable drive), so that can't be right. IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS is also suggested, but that fails with an ERROR_INVALID_FUNCTION on D:.

I can't help but feel that I've missed a crucial concept somewhere.

Here's my code:

```<code>#include "stdafx.h"
#include "Windows.h"

void printLastError(){
  DWORD lastError;
  DWORD bytesReturned;
  WCHAR outbuf[2048];

  lastError = GetLastError();

  bytesReturned = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
    NULL, lastError, LANG_USER_DEFAULT, outbuf, 2048, NULL);

  if (bytesReturned > 0){
    wprintf(outbuf);
  } else {
    printf("Error %d while formatting error %d\n", GetLastError(),     lastError);
  }
}

void readDeviceNumberByExtents(HANDLE hFile){
  BOOL ioctlSuccess;
  DWORD bytesReturned;

  VOLUME_DISK_EXTENTS vde;

  ioctlSuccess = DeviceIoControl(hFile,
    IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
    NULL, 0, &vde, sizeof(vde), &bytesReturned, NULL);

    if (ioctlSuccess != 0){
      printf("%d\n", vde.Extents->DiskNumber );
    } else {
      printLastError();
  }
}

void readDeviceNumberByStorage(HANDLE hFile){
  BOOL ioctlSuccess;
  DWORD bytesReturned;

  STORAGE_DEVICE_NUMBER sdn;

  ioctlSuccess = DeviceIoControl(hFile,
    IOCTL_STORAGE_GET_DEVICE_NUMBER,
    NULL, 0, &sdn, sizeof(sdn), &bytesReturned, NULL);

  if (ioctlSuccess != 0){
    printf("%d\n", sdn.DeviceNumber );
  } else {
    printLastError();
  }
}

void runTest(WCHAR* driveName){
  HANDLE driveHandle;
  DWORD diskNumber;

  driveHandle = CreateFile(driveName,
    0,
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

  if (driveHandle != INVALID_HANDLE_VALUE){
    wprintf(L"Opened %s\n", driveName);

    printf("Device number by extents: ");
    readDeviceNumberByExtents(driveHandle);
    printf("Device number by storage: ");
    readDeviceNumberByStorage(driveHandle);

    CloseHandle(driveHandle);
  } else {
    printf("Failure!\n");
  }
}

int _tmain(int argc, _TCHAR* argv[])
{
  runTest(L"\\\\.\\C:");
  printf("\n");
  runTest(L"\\\\.\\D:");

  getc(stdin);
  return 0;
}
</code>```

...and the output when I run it, either as Administrator or not:

```<code>Opened \\.\C:
Device number by extents: 0
Device number by storage: 0

Opened \\.\D:
Device number by extents: Incorrect function.
Device number by storage: 0
</code>```

答:
It's C#.Net code, but this is what i've written to do the job:</p>

```<code>using System.Management; //Add in a reference to this as well in the project settings
public static string GetPhysicalDevicePath(char DriveLetter)
{
    ManagementClass devs = new ManagementClass( @"Win32_Diskdrive");
    {
        ManagementObjectCollection moc = devs.GetInstances();
        foreach(ManagementObject mo in moc)
        {
            foreach (ManagementObject b in mo.GetRelated("Win32_DiskPartition"))
            {
                foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
                {
                    string DevName = string.Format("{0}", c["Name"]);
                    if (DevName[0] == DriveLetter)
                        return string.Format("{0}", mo["DeviceId"]);
                }
            }
        }
    }
    return "";
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to look up the physical drive number (as in, I need the N in \\.\PhysicalDriveN to open the block device for reading) from the drive letter of a CDROM drive on Windows 7. This page indicates that IOCTL_STORAGE_GET_DEVICE_NUMBER should work, but it returns 0 for the drive number for both C: and D: (where D: is the removable drive), so that can't be right. IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS is also suggested, but that fails with an ERROR_INVALID_FUNCTION on D:.

I can't help but feel that I've missed a crucial concept somewhere.

Here's my code:

#include "stdafx.h"
#include "Windows.h"

void printLastError(){
  DWORD lastError;
  DWORD bytesReturned;
  WCHAR outbuf[2048];

  lastError = GetLastError();

  bytesReturned = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
    NULL, lastError, LANG_USER_DEFAULT, outbuf, 2048, NULL);

  if (bytesReturned > 0){
    wprintf(outbuf);
  } else {
    printf("Error %d while formatting error %d\n", GetLastError(),     lastError);
  }
}

void readDeviceNumberByExtents(HANDLE hFile){
  BOOL ioctlSuccess;
  DWORD bytesReturned;

  VOLUME_DISK_EXTENTS vde;

  ioctlSuccess = DeviceIoControl(hFile,
    IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
    NULL, 0, &vde, sizeof(vde), &bytesReturned, NULL);

    if (ioctlSuccess != 0){
      printf("%d\n", vde.Extents->DiskNumber );
    } else {
      printLastError();
  }
}

void readDeviceNumberByStorage(HANDLE hFile){
  BOOL ioctlSuccess;
  DWORD bytesReturned;

  STORAGE_DEVICE_NUMBER sdn;

  ioctlSuccess = DeviceIoControl(hFile,
    IOCTL_STORAGE_GET_DEVICE_NUMBER,
    NULL, 0, &sdn, sizeof(sdn), &bytesReturned, NULL);

  if (ioctlSuccess != 0){
    printf("%d\n", sdn.DeviceNumber );
  } else {
    printLastError();
  }
}

void runTest(WCHAR* driveName){
  HANDLE driveHandle;
  DWORD diskNumber;

  driveHandle = CreateFile(driveName,
    0,
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

  if (driveHandle != INVALID_HANDLE_VALUE){
    wprintf(L"Opened %s\n", driveName);

    printf("Device number by extents: ");
    readDeviceNumberByExtents(driveHandle);
    printf("Device number by storage: ");
    readDeviceNumberByStorage(driveHandle);

    CloseHandle(driveHandle);
  } else {
    printf("Failure!\n");
  }
}

int _tmain(int argc, _TCHAR* argv[])
{
  runTest(L"\\\\.\\C:");
  printf("\n");
  runTest(L"\\\\.\\D:");

  getc(stdin);
  return 0;
}

...and the output when I run it, either as Administrator or not:

Opened \\.\C:
Device number by extents: 0
Device number by storage: 0

Opened \\.\D:
Device number by extents: Incorrect function.
Device number by storage: 0

Body:
It's C#.Net code, but this is what i've written to do the job:

using System.Management; //Add in a reference to this as well in the project settings
public static string GetPhysicalDevicePath(char DriveLetter)
{
    ManagementClass devs = new ManagementClass( @"Win32_Diskdrive");
    {
        ManagementObjectCollection moc = devs.GetInstances();
        foreach(ManagementObject mo in moc)
        {
            foreach (ManagementObject b in mo.GetRelated("Win32_DiskPartition"))
            {
                foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
                {
                    string DevName = string.Format("{0}", c["Name"]);
                    if (DevName[0] == DriveLetter)
                        return string.Format("{0}", mo["DeviceId"]);
                }
            }
        }
    }
    return "";
}

ContentLicense: CC BY-SA 3.0