问:
Field 'browser' doesn't contain a valid alias configuration
I've started using webpack2 (to be precise, v2.3.2) and after re-creating my config I keep running into an issue I can't seem to solve I get (sorry in advance for ugly dump):

```<code>ERROR in ./src/main.js
Module not found: Error: Can't resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
  Parsed request is a module
  using description file: [absolute path to my repo]/package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    aliased with mapping 'components': '[absolute path to my repo]/src/components' to '[absolute path to my repo]/src/components/DoISuportIt'
      using description file: [absolute path to my repo]/package.json (relative path: ./src)
        Field 'browser' doesn't contain a valid alias configuration
      after using description file: [absolute path to my repo]/package.json (relative path: ./src)
        using description file: [absolute path to my repo]/package.json (relative path: ./src/components/DoISuportIt)
          as directory
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          no extension
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          .js
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.js doesn't exist
          .jsx
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.jsx doesn't exist
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt.js]
[[absolute path to my repo]/src/components/DoISuportIt.jsx]
</code>```

package.json

{
  "version": "1.0.0",
  "main": "./src/main.js",
  "scripts": {
    "build": "webpack --progress --display-error-details"
  },
  "devDependencies": {
    ...
  },
  "dependencies": {
    ...
  }
}
```

<p>In terms of the <code>browser</code> field it's complaining about, the documentation I've been able to find on this is: <code>package-browser-field-spec</code>. There is also webpack documentation for it, but it seems to have it turned on by default: <code>aliasFields: ["browser"]</code>. I tried adding a <code>browser</code> field to my <code>package.json</code> but that didn't seem to do any good.</p>

<p><strong>webpack.config.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import path from 'path';
const source = path.resolve(__dirname, 'src');

export default {
  context: __dirname,
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  resolve: {
    alias: {
      components: path.resolve(__dirname, 'src/components'),
    },
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: source,
        use: {
          loader: 'babel-loader',
          query: {
            cacheDirectory: true,
          },
        },
      },
      {
        test: /\.css$/,
        include: source,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            query: {
              importLoader: 1,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
              modules: true,
            },
          },
        ],
      },
    ],
  },
};
</code>```

src/main.js

import DoISuportIt from 'components/DoISuportIt';
```

<p><strong>src/components/DoISuportIt/index.jsx</strong></p>

<pre class="lang-js prettyprint-override"><code>export default function() { ... }
</code>```

For completeness, .babelrc

{
  "presets": [
    "latest",
    "react"
  ],
  "plugins": [
    "react-css-modules"
  ],
  "env": {
    "production": {
      "compact": true,
      "comments": false,
      "minified": true
    }
  },
  "sourceMaps": true
}
```

What am I doing wrong/missing?

答:
In my case, I had a mixture of enum and interface in the index.d.ts file.

I extracted enums into another file and the issue resolved.

Body:
I've started using webpack2 (to be precise, v2.3.2) and after re-creating my config I keep running into an issue I can't seem to solve I get (sorry in advance for ugly dump):

ERROR in ./src/main.js
Module not found: Error: Can't resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
  Parsed request is a module
  using description file: [absolute path to my repo]/package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    aliased with mapping 'components': '[absolute path to my repo]/src/components' to '[absolute path to my repo]/src/components/DoISuportIt'
      using description file: [absolute path to my repo]/package.json (relative path: ./src)
        Field 'browser' doesn't contain a valid alias configuration
      after using description file: [absolute path to my repo]/package.json (relative path: ./src)
        using description file: [absolute path to my repo]/package.json (relative path: ./src/components/DoISuportIt)
          as directory
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          no extension
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          .js
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.js doesn't exist
          .jsx
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.jsx doesn't exist
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt.js]
[[absolute path to my repo]/src/components/DoISuportIt.jsx]

package.json

{
  "version": "1.0.0",
  "main": "./src/main.js",
  "scripts": {
    "build": "webpack --progress --display-error-details"
  },
  "devDependencies": {
    ...
  },
  "dependencies": {
    ...
  }
}

In terms of the browser field it's complaining about, the documentation I've been able to find on this is: package-browser-field-spec. There is also webpack documentation for it, but it seems to have it turned on by default: aliasFields: ["browser"]. I tried adding a browser field to my package.json but that didn't seem to do any good.

webpack.config.js

import path from 'path';
const source = path.resolve(__dirname, 'src');

export default {
  context: __dirname,
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  resolve: {
    alias: {
      components: path.resolve(__dirname, 'src/components'),
    },
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: source,
        use: {
          loader: 'babel-loader',
          query: {
            cacheDirectory: true,
          },
        },
      },
      {
        test: /\.css$/,
        include: source,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            query: {
              importLoader: 1,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
              modules: true,
            },
          },
        ],
      },
    ],
  },
};

src/main.js

import DoISuportIt from 'components/DoISuportIt';

src/components/DoISuportIt/index.jsx

export default function() { ... }

For completeness, .babelrc

{
  "presets": [
    "latest",
    "react"
  ],
  "plugins": [
    "react-css-modules"
  ],
  "env": {
    "production": {
      "compact": true,
      "comments": false,
      "minified": true
    }
  },
  "sourceMaps": true
}

What am I doing wrong/missing?


来源: stackexchange

问:
How to install nvm in docker?
I am in the process of building a new Docker image and I'm looking to get NVM installed so I can manage nodejs.

Reading the docs on how to install NVM they mention that you need to source your .bashrc file in order to start using NVM.

I've tried to set this up in a Dockerfile, but so far building fails with the error:

"bash: nvm: command not found"

Here are the relevant lines from my Dockerfile:

```<code>ADD files/nvm_install.sh /root/
RUN chmod a+x  /root/nvm_install.sh
RUN bash -c "/root/nvm_install.sh"
RUN bash -l -c "source /root/.bashrc"
RUN cd /root
RUN bash -l -c "nvm install 0.10.31"
</code>```

Here is the output from trying to build:

docker build -t nginx_dock .

```<code>Step 0 : FROM ubuntu
---> 826544226fdc
Step 1 : MAINTAINER dficociello
---> Using cache
---> da3bc340fbb3
Step 2 : RUN apt-get update
---> Using cache
---> 6b6b611feb4f
Step 3 : RUN apt-get install nginx curl -y
---> Using cache
---> 159eb0b16d23
Step 4 : RUN touch /root/.bashrc
---> Using cache
---> 5e9e8216191b
Step 5 : ADD files/nginx.conf /etc/nginx/
---> Using cache
---> c4a4a11296a2
Step 6 : ADD files/nvm_install.sh /root/
---> Using cache
---> b37cba2a18ca
Step 7 : RUN chmod a+x  /root/nvm_install.sh
---> Using cache
---> bb13e2a2893d
Step 8 : RUN bash -c "/root/nvm_install.sh"
---> Using cache
---> 149b49a8fc71
Step 9 : RUN bash -l -c "source /root/.bashrc"
---> Running in 75f353ed0d53
---> 0eae8eae7874
Removing intermediate container 75f353ed0d53
Step 10 : RUN cd /root
---> Running in feacbd998dd0
---> 284293ef46b0
Removing intermediate container feacbd998dd0
Step 11 : RUN bash -l -c "nvm install 0.10.31"
---> Running in 388514d11067
bash: nvm: command not found
2014/09/17 13:15:11 The command [/bin/sh -c bash -l -c "nvm install 0.10.31"] returned a non-zero         code: 127
</code>```

I'm pretty new to Docker so I may be missing something fundamental to writing Dockerfiles, but so far all the reading I've done hasn't shown me a good solution.

答:
nvm not found can result from it being installed for a different user than the one who is executing the container. You may need to prefix the installation with the custom user who is executing the container. The last USER statement defines the container user.

```<code>USER $USERNAME

RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
</code>```

Reason

Diving into a nvm install script, e. g. v0.39.1, one can see that is installed into $HOME of the current user. If you have not changed it, the default user of a ubuntu image is root. When starting the container with a different user however, nvm won't be found; hence make sure user of installation and execution align.

nvm_default_install_dir() {
  [ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm"
}
```

ContentLicense: CC BY-SA 4.0

Title: How to install nvm in docker?

Body:
I am in the process of building a new Docker image and I'm looking to get NVM installed so I can manage nodejs.

Reading the docs on how to install NVM they mention that you need to source your .bashrc file in order to start using NVM.

I've tried to set this up in a Dockerfile, but so far building fails with the error:

"bash: nvm: command not found"

Here are the relevant lines from my Dockerfile:

ADD files/nvm_install.sh /root/
RUN chmod a+x  /root/nvm_install.sh
RUN bash -c "/root/nvm_install.sh"
RUN bash -l -c "source /root/.bashrc"
RUN cd /root
RUN bash -l -c "nvm install 0.10.31"

Here is the output from trying to build:

docker build -t nginx_dock .

Step 0 : FROM ubuntu
---> 826544226fdc
Step 1 : MAINTAINER dficociello
---> Using cache
---> da3bc340fbb3
Step 2 : RUN apt-get update
---> Using cache
---> 6b6b611feb4f
Step 3 : RUN apt-get install nginx curl -y
---> Using cache
---> 159eb0b16d23
Step 4 : RUN touch /root/.bashrc
---> Using cache
---> 5e9e8216191b
Step 5 : ADD files/nginx.conf /etc/nginx/
---> Using cache
---> c4a4a11296a2
Step 6 : ADD files/nvm_install.sh /root/
---> Using cache
---> b37cba2a18ca
Step 7 : RUN chmod a+x  /root/nvm_install.sh
---> Using cache
---> bb13e2a2893d
Step 8 : RUN bash -c "/root/nvm_install.sh"
---> Using cache
---> 149b49a8fc71
Step 9 : RUN bash -l -c "source /root/.bashrc"
---> Running in 75f353ed0d53
---> 0eae8eae7874
Removing intermediate container 75f353ed0d53
Step 10 : RUN cd /root
---> Running in feacbd998dd0
---> 284293ef46b0
Removing intermediate container feacbd998dd0
Step 11 : RUN bash -l -c "nvm install 0.10.31"
---> Running in 388514d11067
bash: nvm: command not found
2014/09/17 13:15:11 The command [/bin/sh -c bash -l -c "nvm install 0.10.31"] returned a non-zero         code: 127

I'm pretty new to Docker so I may be missing something fundamental to writing Dockerfiles, but so far all the reading I've done hasn't shown me a good solution.

Body:
nvm not found can result from it being installed for a different user than the one who is executing the container. You may need to prefix the installation with the custom user who is executing the container. The last USER statement defines the container user.

USER $USERNAME

RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

Reason

Diving into a nvm install script, e. g. v0.39.1, one can see that is installed into $HOME of the current user. If you have not changed it, the default user of a ubuntu image is root. When starting the container with a different user however, nvm won't be found; hence make sure user of installation and execution align.

nvm_default_install_dir() {
  [ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm"
}


问:
How fast is mprotect
My question is how fast is mprotect. What will be the difference between mprotecting say 1 MB of contiguous memory as compared to 1 GB of contiguous memory? Of course I can measure the time, but I want to know what goes under the hood.

答:
It is O(n) on page count in the region too, because it should change a access bits on all PTEs (Page translation Entries, which describes virtual->physical page mappings in PageTable). Calltree:

```<code>mprotect
->
mprotect_fixup
->
change_pte_range
</code>```

http://lxr.free-electrons.com/source/mm/mprotect.c#L32

```<code> 47     do {
 48                 oldpte = *pte;
 49                 if (pte_present(oldpte)) {
 50                         pte_t ptent;
 51
 52                         ptent = ptep_modify_prot_start(mm, addr, pte);
 53                         ptent = pte_modify(ptent, newprot);
 54
 55                         /*
 56                          * Avoid taking write faults for pages we know to be
 57                          * dirty.
 58                          */
 59                         if (dirty_accountable && pte_dirty(ptent))
 60                                 ptent = pte_mkwrite(ptent);
 61
 62                         ptep_modify_prot_commit(mm, addr, pte, ptent);
 63                 } else if (PAGE_MIGRATION && !pte_file(oldpte)) {
 64                         swp_entry_t entry = pte_to_swp_entry(oldpte);
 65
 66                         if (is_write_migration_entry(entry)) {
 67                                 /*
 68                                  * A protection check is difficult so
 69                                  * just be safe and disable write
 70                                  */
 71                                 make_migration_entry_read(&entry);
 72                                 set_pte_at(mm, addr, pte,
 73                                         swp_entry_to_pte(entry));
 74                         }
 75                 }
 76         } while (pte++, addr += PAGE_SIZE, addr != end);
</code>```

Note the increment: addr += PAGE_SIZE, addr != end);

ContentLicense: CC BY-SA 3.0

Title: How fast is mprotect

Body:
It is O(n) on page count in the region too, because it should change a access bits on all PTEs (Page translation Entries, which describes virtual->physical page mappings in PageTable). Calltree:

mprotect
->
mprotect_fixup
->
change_pte_range

http://lxr.free-electrons.com/source/mm/mprotect.c#L32

 47     do {
 48                 oldpte = *pte;
 49                 if (pte_present(oldpte)) {
 50                         pte_t ptent;
 51
 52                         ptent = ptep_modify_prot_start(mm, addr, pte);
 53                         ptent = pte_modify(ptent, newprot);
 54
 55                         /*
 56                          * Avoid taking write faults for pages we know to be
 57                          * dirty.
 58                          */
 59                         if (dirty_accountable && pte_dirty(ptent))
 60                                 ptent = pte_mkwrite(ptent);
 61
 62                         ptep_modify_prot_commit(mm, addr, pte, ptent);
 63                 } else if (PAGE_MIGRATION && !pte_file(oldpte)) {
 64                         swp_entry_t entry = pte_to_swp_entry(oldpte);
 65
 66                         if (is_write_migration_entry(entry)) {
 67                                 /*
 68                                  * A protection check is difficult so
 69                                  * just be safe and disable write
 70                                  */
 71                                 make_migration_entry_read(&entry);
 72                                 set_pte_at(mm, addr, pte,
 73                                         swp_entry_to_pte(entry));
 74                         }
 75                 }
 76         } while (pte++, addr += PAGE_SIZE, addr != end);

Note the increment: addr += PAGE_SIZE, addr != end);


问:
userId dosen't get into the mongoose schema
i'm trying to send a post request to create a new task for a user, the mongoose schema of each task is:

```<code>let todoSchema = new AppSchema ({
    userId: String,
    title: String,
    completed: Boolean
}, {versionKey: false})
</code>```

and when i send the request, the task is created without the userId.
this is the request:

```<code>add = () => {
        const task = {
            userId: this.props.id,
            title: this.state.title,
            completed: false,
        }

        if(task.title) {
            axiosUtils.create('http://localhost:8000/todos/', task)
            alert('task created!')
        }

    }
</code>```

*the typeof task.userId is string, it is the mongoDB _id of the specific user toString()

答:
You are doing axios.create() which is used to create an instance of axios.
To know more about axios.create() you can refer the official axios doc:
https://axios-http.com/docs/instance

In order to create a task you need to make a post request like:

```<code>axios.post("http://localhost:8080/todos/", { taskParam: task })
</code>```

Here the taskParam is the name of that variable you are using to accept the task at backend in req.body most probably.

Body:
i'm trying to send a post request to create a new task for a user, the mongoose schema of each task is:

let todoSchema = new AppSchema ({
    userId: String,
    title: String,
    completed: Boolean
}, {versionKey: false})

and when i send the request, the task is created without the userId.
this is the request:

add = () => {
        const task = {
            userId: this.props.id,
            title: this.state.title,
            completed: false,
        }

        if(task.title) {
            axiosUtils.create('http://localhost:8000/todos/', task)
            alert('task created!')
        }

    }

*the typeof task.userId is string, it is the mongoDB _id of the specific user toString()

Body:
You are doing axios.create() which is used to create an instance of axios.
To know more about axios.create() you can refer the official axios doc:
https://axios-http.com/docs/instance

In order to create a task you need to make a post request like:

axios.post("http://localhost:8080/todos/", { taskParam: task })

Here the taskParam is the name of that variable you are using to accept the task at backend in req.body most probably.


问:
Vertical Align text in a Label
I have been asked to vertically align the text in the labels for the fields in a form but I don't understand why they are not moving. I have tried putting in-line styles using vertical-align:top; and other attributes like bottom and middle but it doesn't work.

Any ideas?

```<code><dd>
   <label class="<?=$email_confirm_class;?>"
          style="text-align:right; padding-right:3px">Confirm Email</label>
   <input class="text" type="text"
          style="border:none;" name="email_confirm"
          id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>"
          tabindex="4" />
   *
</dd>
</code>```

答:
Lacking in elegance, pure html, no CSS solution:</p>
```<code><table>
   <tr>
      <td>
         <label></label>
      </td>
   </tr>
   <tr>
      <td>
         <input></input>
      </td>
   </tr>
</table>
</code>```

Title: Vertical Align text in a Label

Body:
I have been asked to vertically align the text in the labels for the fields in a form but I don't understand why they are not moving. I have tried putting in-line styles using vertical-align:top; and other attributes like bottom and middle but it doesn't work.

Any ideas?

   <label class="<?=$email_confirm_class;?>"
          style="text-align:right; padding-right:3px">Confirm Email
   <input class="text" type="text"
          style="border:none;" name="email_confirm"
          id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>"
          tabindex="4" />
   *

Body:
Lacking in elegance, pure html, no CSS solution:

<table>
   <tr>
      <td>
         <label></label>
      </td>
   </tr>
   <tr>
      <td>
         <input></input>
      </td>
   </tr>
</table>


问:
Get location of specific SCCM device collection in Powershell
I am writing a script to export the names of all computer in a device collection to a txt file. My script works as expected but I would like to preserve the folder structure in the exported file structure. For this I need to get the location of the Device Collection.

My Question:
Is there a way to get the location of a SCCM Device Collection in PowerShell?

I've stumbled across a few posts like this and this that use WMI and WQL for this, but I wasn't able to get those working in my script and I would like to do everything in PowerShell whenever possible.

```<code>$collections = (Get-CMDeviceCollection | Select -ExpandProperty "Name")

$totalCollections = $collections.length

"Number of Collections: $totalCollections"

$i = 0
foreach($name in $collections){
    ForEach-Object -Process {
        $i++
        "Writing File $i of $totalCollections"
        $SanitizedName = $name -replace '/','(slash)' -replace '\\','(backslash)' -replace ':','(colon)' -replace '\*','(asterisk)' -replace '\?','(questionmark)' -replace '"','(quote)' -replace '<','(less)' -replace '>','(more)' -replace '\|','(pipe)'
        $file = New-Item -Path "C:\Temp\exporte\$SanitizedName.txt"
        Add-Content -Path $file.FullName -Value (Get-CMCollectionMember -CollectionName $name | Select -ExpandProperty "Name")
    }
}
</code>```

I would like to expand this code so that the txt files are placed in the corresponding subfolder analog to the SCCM file structure. E.g rootFolder/rooms/

I was using this module until now but wasn't able to find anything that gives me back the specific location of a collection.

Thanks in advance

答:
I wasn't able to find a way to do this in plain PowerShell and the SCCM Module. In the end I did it like @FoxDeploy suggested. I made a SQL query select for each collection (performance isn't an issue in my case) on our SCCM database to get the folder path. I then used this to place the export file in the appropriate place.

This is my working example with some confidential lines removed

```<code>## Parameter ##
$exportLocation = [removed]
$sqlServer = [removed]
$db = [removed]

$query = "SELECT [ObjectPath] FROM [removed].[v_Collections] WHERE CollectionName ="

$SiteCode = [removed] # Site code
$ProviderMachineName = [removed] # SMS Provider machine name

# Customizations
$initParams = @{}

# Import the ConfigurationManager.psd1 module
if((Get-Module ConfigurationManager) -eq $null) {
    Import-Module [removed]\..\ConfigurationManager.psd1" @initParams
}

# Connect to the site's drive if it is not already present
if((Get-PSDrive -Name $SiteCode -PSProvider CMSite -ErrorAction SilentlyContinue) -eq $null) {
    New-PSDrive -Name $SiteCode -PSProvider CMSite -Root $ProviderMachineName @initParams
}

Set-Location "$($SiteCode):\" @initParams

# get all collections and save them to an array
$collections = (Get-CMDeviceCollection | Select -ExpandProperty "Name")

# total number of collections
$totalCollections = $collections.length

# output to console
"Number of Collections: $totalCollections"

# empty output directory
Set-Location [removed]
Remove-Item $exportLocation\* -Recurse -Force
Set-Location [removed]

# loop through all collections
$i = 0
foreach($name in $collections){
    ForEach-Object -Process {
        # print progress
        $i++
        "Writing File $i of $totalCollections"
        # remove all characters, that aren't compatible with the windows file naming scheme (/\:*?"<>|)
        $SanitizedName = $name -replace '/','(slash)' -replace '\\','(backslash)' -replace ':','(colon)' -replace '\*','(asterisk)' -replace '\?','(questionmark)' -replace '"','(quote)' -replace '<','(less)' -replace '>','(more)' -replace '\|','(pipe)'
        # get members of collection
        $collectionMembers = (Get-CMCollectionMember -CollectionName $name | Select -ExpandProperty "Name")
        # write to file
        Set-Location [removed]
        $path = (Invoke-Sqlcmd -ServerInstance $sqlServer -Database $db -Query "$query '$collection'").Item("ObjectPath")
        New-Item -ItemType Directory -Force -Path "$exportLocation$path"
        $file = New-Item -Path "$exportLocation$path\$SanitizedName.txt"
        Add-Content -Path $file.FullName -Value $collectionMembers
        Set-Location [removed]
    }
}
</code>```

hope this helps someone. Thanks @FoxDeploy

Body:
I am writing a script to export the names of all computer in a device collection to a txt file. My script works as expected but I would like to preserve the folder structure in the exported file structure. For this I need to get the location of the Device Collection.

My Question:
Is there a way to get the location of a SCCM Device Collection in PowerShell?

I've stumbled across a few posts like this and this that use WMI and WQL for this, but I wasn't able to get those working in my script and I would like to do everything in PowerShell whenever possible.

$collections = (Get-CMDeviceCollection | Select -ExpandProperty "Name")

$totalCollections = $collections.length

"Number of Collections: $totalCollections"

$i = 0
foreach($name in $collections){
    ForEach-Object -Process {
        $i++
        "Writing File $i of $totalCollections"
        $SanitizedName = $name -replace '/','(slash)' -replace '\\','(backslash)' -replace ':','(colon)' -replace '\*','(asterisk)' -replace '\?','(questionmark)' -replace '"','(quote)' -replace '<','(less)' -replace '>','(more)' -replace '\|','(pipe)'
        $file = New-Item -Path "C:\Temp\exporte\$SanitizedName.txt"
        Add-Content -Path $file.FullName -Value (Get-CMCollectionMember -CollectionName $name | Select -ExpandProperty "Name")
    }
}

I would like to expand this code so that the txt files are placed in the corresponding subfolder analog to the SCCM file structure. E.g rootFolder/rooms/

I was using this module until now but wasn't able to find anything that gives me back the specific location of a collection.

Thanks in advance

Body:
I wasn't able to find a way to do this in plain PowerShell and the SCCM Module. In the end I did it like @FoxDeploy suggested. I made a SQL query select for each collection (performance isn't an issue in my case) on our SCCM database to get the folder path. I then used this to place the export file in the appropriate place.

This is my working example with some confidential lines removed

## Parameter ##
$exportLocation = [removed]
$sqlServer = [removed]
$db = [removed]

$query = "SELECT [ObjectPath] FROM [removed].[v_Collections] WHERE CollectionName ="

$SiteCode = [removed] # Site code
$ProviderMachineName = [removed] # SMS Provider machine name

# Customizations
$initParams = @{}

# Import the ConfigurationManager.psd1 module
if((Get-Module ConfigurationManager) -eq $null) {
    Import-Module [removed]\..\ConfigurationManager.psd1" @initParams
}

# Connect to the site's drive if it is not already present
if((Get-PSDrive -Name $SiteCode -PSProvider CMSite -ErrorAction SilentlyContinue) -eq $null) {
    New-PSDrive -Name $SiteCode -PSProvider CMSite -Root $ProviderMachineName @initParams
}

Set-Location "$($SiteCode):\" @initParams

# get all collections and save them to an array
$collections = (Get-CMDeviceCollection | Select -ExpandProperty "Name")

# total number of collections
$totalCollections = $collections.length

# output to console
"Number of Collections: $totalCollections"

# empty output directory
Set-Location [removed]
Remove-Item $exportLocation\* -Recurse -Force
Set-Location [removed]

# loop through all collections
$i = 0
foreach($name in $collections){
    ForEach-Object -Process {
        # print progress
        $i++
        "Writing File $i of $totalCollections"
        # remove all characters, that aren't compatible with the windows file naming scheme (/\:*?"<>|)
        $SanitizedName = $name -replace '/','(slash)' -replace '\\','(backslash)' -replace ':','(colon)' -replace '\*','(asterisk)' -replace '\?','(questionmark)' -replace '"','(quote)' -replace '<','(less)' -replace '>','(more)' -replace '\|','(pipe)'
        # get members of collection
        $collectionMembers = (Get-CMCollectionMember -CollectionName $name | Select -ExpandProperty "Name")
        # write to file
        Set-Location [removed]
        $path = (Invoke-Sqlcmd -ServerInstance $sqlServer -Database $db -Query "$query '$collection'").Item("ObjectPath")
        New-Item -ItemType Directory -Force -Path "$exportLocation$path"
        $file = New-Item -Path "$exportLocation$path\$SanitizedName.txt"
        Add-Content -Path $file.FullName -Value $collectionMembers
        Set-Location [removed]
    }
}

hope this helps someone. Thanks @FoxDeploy


问:
Monaco Editor | How to properly use Hover's IMarkdownString with HTML

monaco.languages.register({ id: 'mySpecialLanguage' });

monaco.languages.registerHoverProvider('mySpecialLanguage', {
    provideHover: function (model, position) {
        return {
            range: new monaco.Range(
                1,
                1,
                model.getLineCount(),
                model.getLineMaxColumn(model.getLineCount())
            ),
            contents: [
                {
                    supportHtml: true,
                    value: '
yes
'
                }
            ]
        };
    }
});

monaco.editor.create(document.getElementById('container'), {
    value: '\n\nHover over this text',
    language: 'mySpecialLanguage'
});
```

I'm trying to provide a HoverProvider for my editor but I can't seem to render the element with a different foreground or classList, Am I doing something wrong here? It works okay but the style didn't load / inserted to the hover content. I'm using IMarkdownString

答:
The value does not contain a valid HTML. You're missing a colon after color and you're not closing the style attribute with a quote.
It should be: '
yes
'

Body:
monaco.languages.register({ id: 'mySpecialLanguage' });

monaco.languages.registerHoverProvider('mySpecialLanguage', {
    provideHover: function (model, position) {
        return {
            range: new monaco.Range(
                1,
                1,
                model.getLineCount(),
                model.getLineMaxColumn(model.getLineCount())
            ),
            contents: [
                {
                    supportHtml: true,
                    value: '
yes
'
                }
            ]
        };
    }
});

monaco.editor.create(document.getElementById('container'), {
    value: '\n\nHover over this text',
    language: 'mySpecialLanguage'
});

I'm trying to provide a HoverProvider for my editor but I can't seem to render the element with a different foreground or classList, Am I doing something wrong here? It works okay but the style didn't load / inserted to the hover content. I'm using IMarkdownString

Body:
The value does not contain a valid HTML. You're missing a colon after color and you're not closing the style attribute with a quote.
It should be: '<div style="color: red" class="test">yes</div>'


问:
How to call a function before the idle timeout session expiry in PHP
I have a large application which expires the session data after 30 minutes of idle time. Now I want to call a function before the session expiration.

My Reason for above question: I am storing a unique id in database for some purpose. When the user clicks logout, I will delete that ID. I want to delete that ID even when the user session expires after idle time.

答:
As far as i know , it will be bad practice to set a "counter" for users to check if their session is expired.

If you need this ID to see who is connected in your administration aria , one possible way to do it is by checking the session expiration on loading admin page , and then delete the expired sessions rows then showing only active sessions.

So my idea is that while you are not using your admin dashboard it is okay that some sessions ID's still in your database , once you try to see who is online , the check function is called and clean up your data for expired session.

THAT IF YOU ARE USING THAT ID FOR SOMTHING LIKE THAT SINCE YOU DIDN''T SHARE THE WHOLE REASON OF WHY YOU NEED TO DO SO.


问:
Total digits are inconsistent
I m using following code to get random hex values. But the output is inconsistent
Sometimes it returns 6 digits sometimes 5 digits</p>

```<code>function generateHexValue($length=6)
{
    $chars = "0123456789abcdef";

    $i = 0;
    $str = "";

    while ($i<$length) {
        $str .= $chars[mt_rand(0,strlen($chars))];
        $i++;
    }

    return $str;
}

$col=generateHexValue();
echo "<div style='background-color:#".$col."; width:100px; height:100px;'></div>";
echo $col."<br/>";
</code>```

答: That's because mt_rand(0,strlen($chars)) returns a number between 0 and 16 (inclusive), but your $chars string only has the offsets 0 - 15. A classic off-by-one mistake.

Title: Total digits are inconsistent

Body:
I m using following code to get random hex values. But the output is inconsistent
Sometimes it returns 6 digits sometimes 5 digits

function generateHexValue($length=6)
{
    $chars = "0123456789abcdef";

    $i = 0;
    $str = "";

    while ($i<$length) {
        $str .= $chars[mt_rand(0,strlen($chars))];
        $i++;
    }

    return $str;
}

$col=generateHexValue();
echo "

";
echo $col."
";


问:
Laravel-permission Undefined type PermissionRegistrar
I'm trying to install the package Laravel-permission v5 for a project in Laravel 8.

Following the instructions at the documentation, I runned

```<code>composer require spatie/laravel-permission
</code>```

and to be able to migrate the permission tables I executed:

```<code>php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
</code>```

Instantly, in the file database/migrations/create_permission_tables.php it gives me the error

Undefined type 'Spatie\Permission\PermissionRegistrar

What can I do? I'm new in Laravel

答:
Did you import it in config/app.php ??

Try this:

```<code> php artisan optimize:clear
 # or
 php artisan config:clear

 php artisan migrate
</code>```

Body:
I'm trying to install the package Laravel-permission v5 for a project in Laravel 8.

Following the instructions at the documentation, I runned

composer require spatie/laravel-permission

and to be able to migrate the permission tables I executed:

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

Instantly, in the file database/migrations/create_permission_tables.php it gives me the error

Undefined type 'Spatie\Permission\PermissionRegistrar

What can I do? I'm new in Laravel

Body:
Did you import it in config/app.php ??

Try this:

 php artisan optimize:clear
 # or
 php artisan config:clear

 php artisan migrate


问:
Spring DeferredResult setResult causing 404
I am using the new spring 3.2 async servlet requests.
All works well except in this one scenario...

```<code>@RequestMapping("/test")
@ResponseBody
public DeferredResult<byte[]> test(InputStream is, HttpServletResponse response, WebRequest request) {
    if (someTest()) {
        deferredResult.setResult(DATA);
        return deferredResult;
    }

    deferredResult.onTimeout(new Runnable() {

        @Override
        public void run() {
            deferredResult.setResult(DATA);
        }
    });

    // Use deferredResult in another thread when needed

    return deferredResult;
}
</code>```

When someTest() is true spring/tomcat returns a 404. I am not sure how I should go about this or why this happens? I assume it might be because the Servlet Async Context has already been created. Is this a bug or am I doing something wrong?

Any info will be appreciated!

答:
I was facing a weird 404 lately with a legacy project that uses DeferredResult and it was a matter of adding @ResponseBody. A simple runnable example:

```<code>@SpringBootApplication
public class TestApp {

    public static void main(String[] args) {
        SpringApplication.run(TestApp.class, args);
    }

    @Controller
    static class Rest {

        @Autowired
        private MyService myService;

        @GetMapping("/get")
        @ResponseStatus(HttpStatus.CREATED)
        @ResponseBody // <-- with and without
        public DeferredResult<String> get() {
            return myService.go();
        }
    }

    @Service
    static class MyService {
        public DeferredResult<String> go() {

            DeferredResult<String> result = new DeferredResult<>();

            Executors.newSingleThreadExecutor().submit(() -> {
                System.out.println("starting work");
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));
                System.out.println("done with work");
                result.setResult("done");
            });

            return result;
        }
    }

}
</code>```

Body:
I am using the new spring 3.2 async servlet requests.
All works well except in this one scenario...

@RequestMapping("/test")
@ResponseBody
public DeferredResult<byte[]> test(InputStream is, HttpServletResponse response, WebRequest request) {
    if (someTest()) {
        deferredResult.setResult(DATA);
        return deferredResult;
    }

    deferredResult.onTimeout(new Runnable() {

        @Override
        public void run() {
            deferredResult.setResult(DATA);
        }
    });

    // Use deferredResult in another thread when needed

    return deferredResult;
}

When someTest() is true spring/tomcat returns a 404. I am not sure how I should go about this or why this happens? I assume it might be because the Servlet Async Context has already been created. Is this a bug or am I doing something wrong?

Any info will be appreciated!

Body:
I was facing a weird 404 lately with a legacy project that uses DeferredResult and it was a matter of adding @ResponseBody. A simple runnable example:

@SpringBootApplication
public class TestApp {

    public static void main(String[] args) {
        SpringApplication.run(TestApp.class, args);
    }

    @Controller
    static class Rest {

        @Autowired
        private MyService myService;

        @GetMapping("/get")
        @ResponseStatus(HttpStatus.CREATED)
        @ResponseBody // <-- with and without
        public DeferredResult<String> get() {
            return myService.go();
        }
    }

    @Service
    static class MyService {
        public DeferredResult<String> go() {

            DeferredResult<String> result = new DeferredResult<>();

            Executors.newSingleThreadExecutor().submit(() -> {
                System.out.println("starting work");
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));
                System.out.println("done with work");
                result.setResult("done");
            });

            return result;
        }
    }

}


问:
MPI_Init_thread function was called before MPI_Init was invoked
I need an MPI_Init_Thread  call example in fortran.

I tried it without MPI_Init before it and got the message:"MPI_Init_thread function was called before MPI_Init was invoked".

I called after MPI_init and got the message "Calling MPI_Init or MPI_Init_Thread twpce is erreneous." altough I had each called once.

I am confused.

Also are there three or 4 arguments?  and what are they? I believe it is three and the second one I want is MPI_THREAD_MULTIPLE but program aborts.

It would be best if someone uses it with fortran could post an example call please.

For completeness I am posting a simple code I am tring to run in hybrid (MPI + OPENMP) mode.
My purpose is to run this job on two nodes , each with 32 threads by making use of openmp within each node.

```<code>program hello

Use mpi

integer ierr,np,pid,inull1,inul2,hug

    call MPI_Init(ierr)

   inull2=3

!    call MPI_Init_thread(inull1,inull2,ierr)

    call MPI_Comm_rank(MPI_COMM_WORLD, pid,ierr)

    call MPI_Comm_size(MPI_COMM_WORLD, np, ierr)

    write(6,*) 'inull2,MPI_THREAD_MULTIPLE',MPI_THREAD_MULTIPLE

 hug=huge(inull1)

!$OMP PARALLEL SHARED(inull1,inull2,hug,MPI_THREAD_MULTIPLE,np) &

!$OMP          PRIVATE(pid)

!$OMP DO SCEDULE (STATIC)

 do i=1,hug

    write(6,*) 'program hello_world i,np,pid,inull2,mtm',i,np,pid,inull2,MPI_THREAD_MULTIPLE

 enddo

!$OMP END DO

!$OMP END PARALLEL

    call MPI_Finalize(ierr)

end program hello
</code>```

I compile it with

```<code>      mpif90 -o hello_world_openmp.exe hello_world_openmp.f90
</code>```

and run it with the following command (for now)

```<code>
      mpirun -hostfile hostfile -pernode -bind-to none hello_world_openmp.exe
</code>```

Changing the code as

integer ierr,np,pid,inull1,inul2,hug

!    call MPI_Init(ierr)

```<code>call MPI_Init_thread(MPI_THREAD_FUNNELLED,inull2,ierr)
</code>```

also gives the following error:
*** The MPI_Init_thread() function was called before MPI_INIT was invoked.
*** This is disallowed by the MPI standard.
*** Your MPI job will now abort.

答:
The error message you quite is strange. But it has been reported before (https://www.mail-archive.com/devel@lists.open-mpi.org/msg19978.html https://github.com/TRIQS/cthyb/issues/122)

It points to some incompatibility somewhere. In your case it points to an incorrect call to MPI_Init_thread. The main point is:

Always use IMPLICIT NONE!

This cannot be over-stressed. Even in a very short code you must use it. You declared inul2 instead of inull2 and you used MPI_THREAD_FUNNELLED instead of MPI_THREAD_FUNNELED. After correcting that, your codes runs correctly for me.

One calls MPI_Init_thread instead of MPI_Init, not after.

You call it like

```<code>call MPI_Init_thread(required, provided, ie)
</code>```

where all arguments are integers, required is an input argument saying which threading level you need and provided is an output argument and says which threading level you got.

Be aware that for many MPI implementations MPI_THREAD_MULTIPLE is either not supported at all or is very slow. I suggest designing your programs without the need for MPI_THREAD_MULTIPLE.

The usage can be something like

```<code>    integer :: ie
    integer :: required, provided

    required = MPI_THREAD_SERIALIZED

    call MPI_Init_thread(required, provided, ie)

    if (ie/=0) ... error

    if (provided<required) then
       ... different error
</code>```

Body:
I need an MPI_Init_Thread  call example in fortran.

I tried it without MPI_Init before it and got the message:"MPI_Init_thread function was called before MPI_Init was invoked".

I called after MPI_init and got the message "Calling MPI_Init or MPI_Init_Thread twpce is erreneous." altough I had each called once.

I am confused.

Also are there three or 4 arguments?  and what are they? I believe it is three and the second one I want is MPI_THREAD_MULTIPLE but program aborts.

It would be best if someone uses it with fortran could post an example call please.

For completeness I am posting a simple code I am tring to run in hybrid (MPI + OPENMP) mode.
My purpose is to run this job on two nodes , each with 32 threads by making use of openmp within each node.

program hello

Use mpi

integer ierr,np,pid,inull1,inul2,hug

    call MPI_Init(ierr)

   inull2=3

!    call MPI_Init_thread(inull1,inull2,ierr)

    call MPI_Comm_rank(MPI_COMM_WORLD, pid,ierr)

    call MPI_Comm_size(MPI_COMM_WORLD, np, ierr)

    write(6,*) 'inull2,MPI_THREAD_MULTIPLE',MPI_THREAD_MULTIPLE

 hug=huge(inull1)

!$OMP PARALLEL SHARED(inull1,inull2,hug,MPI_THREAD_MULTIPLE,np) &

!$OMP          PRIVATE(pid)

!$OMP DO SCEDULE (STATIC)

 do i=1,hug

    write(6,*) 'program hello_world i,np,pid,inull2,mtm',i,np,pid,inull2,MPI_THREAD_MULTIPLE

 enddo

!$OMP END DO

!$OMP END PARALLEL

    call MPI_Finalize(ierr)

end program hello

I compile it with

      mpif90 -o hello_world_openmp.exe hello_world_openmp.f90

and run it with the following command (for now)

      mpirun -hostfile hostfile -pernode -bind-to none hello_world_openmp.exe

Changing the code as

integer ierr,np,pid,inull1,inul2,hug

!    call MPI_Init(ierr)

call MPI_Init_thread(MPI_THREAD_FUNNELLED,inull2,ierr)

also gives the following error:
*** The MPI_Init_thread() function was called before MPI_INIT was invoked.
*** This is disallowed by the MPI standard.
*** Your MPI job will now abort.

Body:
The error message you quite is strange. But it has been reported before (https://www.mail-archive.com/devel@lists.open-mpi.org/msg19978.html https://github.com/TRIQS/cthyb/issues/122)

It points to some incompatibility somewhere. In your case it points to an incorrect call to MPI_Init_thread. The main point is:

Always use IMPLICIT NONE!

This cannot be over-stressed. Even in a very short code you must use it. You declared inul2 instead of inull2 and you used MPI_THREAD_FUNNELLED instead of MPI_THREAD_FUNNELED. After correcting that, your codes runs correctly for me.

One calls MPI_Init_thread instead of MPI_Init, not after.

You call it like

call MPI_Init_thread(required, provided, ie)

where all arguments are integers, required is an input argument saying which threading level you need and provided is an output argument and says which threading level you got.

Be aware that for many MPI implementations MPI_THREAD_MULTIPLE is either not supported at all or is very slow. I suggest designing your programs without the need for MPI_THREAD_MULTIPLE.

The usage can be something like

    integer :: ie
    integer :: required, provided

    required = MPI_THREAD_SERIALIZED

    call MPI_Init_thread(required, provided, ie)

    if (ie/=0) ... error

    if (provided<required) then
       ... different error


问:
Can a constraint violation outside of a TRY block behave like an exception (and stop execution)?

Summary

I just discovered a surprising behavior of SQL Server: if a statement is executed outside of a TRY block, and it violates a constraint1, the execution will continue to the next statement.

I would have expected the execution to stop, like for an exception, but apparently constraint violations do not (always) behave like exceptions. However, if a statement is executed inside a TRY block, a constraint violation behaves like exception and stops the flow of execution before it reaches the next statement.

Test

Here is my test setup...

```<code>CREATE TABLE T (
    T_ID int,
    CONSTRAINT T_PK PRIMARY KEY (T_ID)
);

INSERT INTO T VALUES (1);
</code>```

Below, the INSERT has violated the primary key, but the next statement is executed nonetheless ('next reached' is printed):

```<code>INSERT INTO T VALUES(1);
PRINT 'next reached';

Msg 2627, Level 14, State 1, Line 10
Violation of PRIMARY KEY constraint 'T_PK'. Cannot insert duplicate key in object 'dbo.T'. The duplicate key value is (1).
The statement has been terminated.
next reached
</code>```

This is different from the "normal" exception ('next reached' is not printed):

```<code>THROW 50000, 'Some exception.', 0;
PRINT 'next reached';

Msg 50000, Level 16, State 0, Line 15
Some exception.
</code>```

Curiously, if I put the INSERT into a TRY block, the constraint violation starts behaving like an exception (note how neither 'next reached' nor 'end reached' are printed):

```<code>BEGIN TRY
    INSERT INTO T VALUES(1);
    PRINT 'next reached';
END TRY
BEGIN CATCH
    THROW;
END CATCH
PRINT 'end reached'

(0 rows affected)
Msg 2627, Level 14, State 1, Line 21
Violation of PRIMARY KEY constraint 'T_PK'. Cannot insert duplicate key in object 'dbo.T'. The duplicate key value is (1).
</code>```

Question

Is there a way to make the constraint violations behave like exceptions even when not enclosed within a TRY block?

Motivation: The above behavior is different from all programming languages supporting exceptions that I know of. When implementing complex business logic in stored procedures, using TRY everywhere would make the code less readable. More importantly, it would make it fragile: forgetting it somewhere, or relying on a caller to have it, and then somebody independently removing it from the caller, could easily make the stored procedure continue execution unexpectedly and potentially even corrupt the data.

1 I have tested PRIMARY KEY, UNIQUE, FOREIGN KEY and CHECK constraints, and they all seem to behave the same.

--- EDIT ---

For what it's worth, I have created a suggestion for Microsoft, but I'm not holding my breath that it will be implemented soon (or ever):

Consistent flow of execution with arithmetic errors and constraint violations

答:
Addressing your "Motivation" part, I strongly disagree. There are many versions of what is called try-transaction block, but sooner or later one realizes it should be included in almost every procedure. It's not more than 20 lines of code, so not really that pain to read. Here's what I use:

```<code>set xact_abort on -- rollsback when try-catch doesn't work, eg on table not found errors
begin try
    begin transaction    -- start the transaction
    ...........................
    commit
end try
begin catch
    if @@trancount > 0 rollback
    declare @rethrow nvarchar(4000)='Error >> num '+convert(nvarchar(max),error_number())+', line '+convert(nvarchar(max),error_line())+', message: '+error_message()
    raiserror(@rethrow, 16, 0)
end catch
</code>```

As always, I recommend the corresponding Erland Sommarskog's article, inside of which you will find a table detailing the exact behaviour for the various combinations of error types, xact_abort on/off, and using or not of try/catch.

You also mention you want to let your clients choose whether to "rollback or retry".  I am unfamiliar with this, but it has an ominous feeling. What is "retry"? If you plan to do some manual change and then retry, don't forget your procedure will still be probably holding locks if its transaction is still open, leading to bad situations. Best way would be to make a loop, where the transaction will be rolled back, and retry means to just fire it up from the beginning.

Body:
Summary

I just discovered a surprising behavior of SQL Server: if a statement is executed outside of a TRY block, and it violates a constraint1, the execution will continue to the next statement.

I would have expected the execution to stop, like for an exception, but apparently constraint violations do not (always) behave like exceptions. However, if a statement is executed inside a TRY block, a constraint violation behaves like exception and stops the flow of execution before it reaches the next statement.

Test

Here is my test setup...

CREATE TABLE T (
    T_ID int,
    CONSTRAINT T_PK PRIMARY KEY (T_ID)
);

INSERT INTO T VALUES (1);

Below, the INSERT has violated the primary key, but the next statement is executed nonetheless ('next reached' is printed):

INSERT INTO T VALUES(1);
PRINT 'next reached';

Msg 2627, Level 14, State 1, Line 10
Violation of PRIMARY KEY constraint 'T_PK'. Cannot insert duplicate key in object 'dbo.T'. The duplicate key value is (1).
The statement has been terminated.
next reached

This is different from the "normal" exception ('next reached' is not printed):

THROW 50000, 'Some exception.', 0;
PRINT 'next reached';

Msg 50000, Level 16, State 0, Line 15
Some exception.

Curiously, if I put the INSERT into a TRY block, the constraint violation starts behaving like an exception (note how neither 'next reached' nor 'end reached' are printed):

BEGIN TRY
    INSERT INTO T VALUES(1);
    PRINT 'next reached';
END TRY
BEGIN CATCH
    THROW;
END CATCH
PRINT 'end reached'

(0 rows affected)
Msg 2627, Level 14, State 1, Line 21
Violation of PRIMARY KEY constraint 'T_PK'. Cannot insert duplicate key in object 'dbo.T'. The duplicate key value is (1).

Question

Is there a way to make the constraint violations behave like exceptions even when not enclosed within a TRY block?

Motivation: The above behavior is different from all programming languages supporting exceptions that I know of. When implementing complex business logic in stored procedures, using TRY everywhere would make the code less readable. More importantly, it would make it fragile: forgetting it somewhere, or relying on a caller to have it, and then somebody independently removing it from the caller, could easily make the stored procedure continue execution unexpectedly and potentially even corrupt the data.

1 I have tested PRIMARY KEY, UNIQUE, FOREIGN KEY and CHECK constraints, and they all seem to behave the same.

--- EDIT ---

For what it's worth, I have created a suggestion for Microsoft, but I'm not holding my breath that it will be implemented soon (or ever):

Consistent flow of execution with arithmetic errors and constraint violations

Body:
Addressing your "Motivation" part, I strongly disagree. There are many versions of what is called try-transaction block, but sooner or later one realizes it should be included in almost every procedure. It's not more than 20 lines of code, so not really that pain to read. Here's what I use:

set xact_abort on -- rollsback when try-catch doesn't work, eg on table not found errors
begin try
    begin transaction    -- start the transaction
    ...........................
    commit
end try
begin catch
    if @@trancount > 0 rollback
    declare @rethrow nvarchar(4000)='Error >> num '+convert(nvarchar(max),error_number())+', line '+convert(nvarchar(max),error_line())+', message: '+error_message()
    raiserror(@rethrow, 16, 0)
end catch

As always, I recommend the corresponding Erland Sommarskog's article, inside of which you will find a table detailing the exact behaviour for the various combinations of error types, xact_abort on/off, and using or not of try/catch.

You also mention you want to let your clients choose whether to "rollback or retry".  I am unfamiliar with this, but it has an ominous feeling. What is "retry"? If you plan to do some manual change and then retry, don't forget your procedure will still be probably holding locks if its transaction is still open, leading to bad situations. Best way would be to make a loop, where the transaction will be rolled back, and retry means to just fire it up from the beginning.


问:
Why does my JAVA_HOME point to jre instead of jdk?
I want to compile a project on my manjaro system using mvn and every time I get this error:

```<code>The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK, not a JRE
</code>```

Can somebody help?

答:
Found the Solution myself:

```<code>sudo archlinux-java set <target java package name>
</code>```

For Example:

```<code>sudo archlinux-java set java-15-jdk
</code>```

Found this here: https://www.debugpoint.com/2021/02/install-java-arch/

Body:
I want to compile a project on my manjaro system using mvn and every time I get this error:

The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK, not a JRE

Can somebody help?

Body:
Found the Solution myself:

sudo archlinux-java set <target java package name>

For Example:

sudo archlinux-java set java-15-jdk

Found this here: https://www.debugpoint.com/2021/02/install-java-arch/


问:
How to add this type of node description by Mermaid?
This is a flowchart pattern that I really like to use and I currently use drawio to draw it:

Notice that there are two kinds of descriptions in the flow chart

description1:How does A get to B

description2:Some properties of B

I know Mermaid can implement the description1 by:

```<code>graph TB
    A --->|"description1:<br>How does A get to B"| B
</code>```

But description2 is also very important to me, is there any way to achieve it?

The current workaround:

I use the heading of subgraph instead of description2:

```<code>graph TB
    A --->|"description1:<br>How does A get to B"| B
    subgraph description2:<br>Some properties of B
    B
    end
</code>```

But I have to say it's a very ugly temporary solution. So I ask here..

答:
While some types of Mermaid diagrams explicitly support notes (e.g. sequence diagrams), flowcharts do not.

I believe the closest you're going to get is to connect B to itself with an invisible link (~~~):

```<code>graph TB
    A --->|"description1:<br>How does A get to B"| B
    B ~~~|"description2:<br>Some properties of B"| B
</code>```

Body:
This is a flowchart pattern that I really like to use and I currently use drawio to draw it:

Notice that there are two kinds of descriptions in the flow chart

description1:How does A get to B

description2:Some properties of B

I know Mermaid can implement the description1 by:

graph TB
    A --->|"description1:
How does A get to B"| B

But description2 is also very important to me, is there any way to achieve it?

The current workaround:

I use the heading of subgraph instead of description2:

graph TB
    A --->|"description1:
How does A get to B"| B
    subgraph description2:
Some properties of B
    B
    end

But I have to say it's a very ugly temporary solution. So I ask here..

Body:
While some types of Mermaid diagrams explicitly support notes (e.g. sequence diagrams), flowcharts do not.

I believe the closest you're going to get is to connect B to itself with an invisible link (~~~):

graph TB
    A --->|"description1:<br>How does A get to B"| B
    B ~~~|"description2:<br>Some properties of B"| B


问:
Handle state variable initialization
I'm trying to fill form data using state variable. Data of state variable is getting from redux store as shown below :

```<code>  const [location, setLocation] = useState(post && post.location);
  const [hastage, setHastage] = useState(post && post.hastage);
  const [caption, setCaption] = useState(post && post.caption);
  const [postImg, setPostImg] = useState(post && post.postImg);
</code>```

In above code 'post' is redux store instance.

Every thing is working Fine. However, Problem is that :

When I refresh page 'post' data is async call therefore before getting post data all variable is initialized with " "(Blank). and form is getting empty.

Hoe to initialize all state variable after 'post' data is ready ?

答:
You can make use of a conditional expression which only returns the form if the data has some value in it and when its fetching some value you could do something like a loading screen or a spinner hiding the form,etc. You could technically add an extra value in redux just for tracking this and when that value changes you display the form. Also you could try to disable the form fields just as a extra suggestion.

```<code>return (<div>{post.hasLoaded ? <MyForm /> : 'Loading...'}</div>);

</code>```

or

```<code>return (<div>{post && post.location ? <MyForm />:'Loading..'}</div>);
</code>```

Title: Handle state variable initialization

Body:
I'm trying to fill form data using state variable. Data of state variable is getting from redux store as shown below :

  const [location, setLocation] = useState(post && post.location);
  const [hastage, setHastage] = useState(post && post.hastage);
  const [caption, setCaption] = useState(post && post.caption);
  const [postImg, setPostImg] = useState(post && post.postImg);

In above code 'post' is redux store instance.

Every thing is working Fine. However, Problem is that :

When I refresh page 'post' data is async call therefore before getting post data all variable is initialized with " "(Blank). and form is getting empty.

Hoe to initialize all state variable after 'post' data is ready ?

Body:
You can make use of a conditional expression which only returns the form if the data has some value in it and when its fetching some value you could do something like a loading screen or a spinner hiding the form,etc. You could technically add an extra value in redux just for tracking this and when that value changes you display the form. Also you could try to disable the form fields just as a extra suggestion.

return (<div>{post.hasLoaded ? <MyForm /> : 'Loading...'}</div>);

or

return (<div>{post && post.location ? <MyForm />:'Loading..'}</div>);


问:
Find Last modified timestamp of a files/folders in Azure Datalake through python script in Azure databricks that uses Credential passthrough
I have an Azure DataLake Storage Gen2 which contains a few Parquet files. My Organization has enabled credential passthrough and so I am able to create a python script in Azure Databricks and access the files available in ADLS using dbutils.fs.ls. All these work fine.

Now, I need to access the last modified timestamp of these files too. I found a link that does this. However, it uses BlockBlobService and requires an account_key.

I do not have an account key and can't get one due to security policies of the organization. I am unsure of how to do the same using Credential passthrough. Any ideas here?

答:
You can do this using the Hadoop FileSystem object accessible via Spark:

```<code>import time

path = spark._jvm.org.apache.hadoop.fs.Path
fs = path('abfss://container@storageaccount.dfs.core.windows.net/').getFileSystem(sc._jsc.hadoopConfiguration())

res = fs.listFiles(path('abfss://container@storageaccount.dfs.core.windows.net/path'), True)

while res.hasNext():
  file = res.next()
  localTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(file.getModificationTime() / 1000))
  print(f"{file.getPath()}: {localTime}")
</code>```

Note that that the True parameter in the listFiles() method means recursive.

Body:
You can do this using the Hadoop FileSystem object accessible via Spark:

import time

path = spark._jvm.org.apache.hadoop.fs.Path
fs = path('abfss://container@storageaccount.dfs.core.windows.net/').getFileSystem(sc._jsc.hadoopConfiguration())

res = fs.listFiles(path('abfss://container@storageaccount.dfs.core.windows.net/path'), True)

while res.hasNext():
  file = res.next()
  localTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(file.getModificationTime() / 1000))
  print(f"{file.getPath()}: {localTime}")

Note that that the True parameter in the listFiles() method means recursive.


问:
grep: Search for multiple strings in files recursively, to find source code
I am fairly confident this can't be done with grep, unless there are some features that I don't know about. However I am hoping that if this is the case there might be some other Linux/Unix command line tool which will do the job I want.

This is a frequent problem when working with source code, so I am pretty sure there must be an adequete solution.

Problem:

I am working with some C++ source code, and I want to be able to grep for objects in my code to find the files containing the relevant information.

Here is a simple example:

Search for all files which contain matches for "MyClass" in the namespace "MYNAMESPACE".

Assume that although MyClass and MYNAMESPACE appear to be likely to be unique strings, in general they might not be.

In my case, the namespace "MYNAMESPACE" appears in hundreds of source files.

The actual name of the class I am searching for is "Parameter", which is such a generic word that it too appears in hundreds of files.

Here is what I want a grep-like tool to do:

Specify a list of words to search for

Return the list of files found where ALL words in the list of search words are found in the same file

Do this recursively to obtain all results in all files in a directory

Surely there is a way to do this? This is essentially a filtering problem: Take all the files found (recursively) inside a directory, and apply a filter to them for each of the words in the input list. Files pass the filter if they contain at least one instance of each word.

答:
Maybe grep piped to xargs grep?

]$ grep -rl "NAMESPACE" | xargs grep -l "Parameter"
```
<p>With these four files:</p>
<pre class="lang-none prettyprint-override"><code>]$ tail -n +1 *.txt
==> needle_1.txt <==
...NAMESPACE...
...
...Parameter...

==> needle_2.txt <==
...Parameter...
...
...NAMESPACE...

==> not_needle_1.txt <==
...
...NAMESPACE...
...

==> not_needle_2.txt <==
...
...Parameter...
...
</code>```

placed in each sub-directory (including .) of:

.
├── dir_1
│   ├── dir_1
│   └── dir_2
└── dir_2
    ├── dir_1
    └── dir_2
```
<p>the result is:</p>
<pre class="lang-bash prettyprint-override"><code>]$ grep -rl "NAMESPACE" | xargs grep -l "Parameter" | sort
dir_1/dir_1/needle_1.txt
dir_1/dir_1/needle_2.txt
dir_1/dir_2/needle_1.txt
dir_1/dir_2/needle_2.txt
dir_1/needle_1.txt
dir_1/needle_2.txt
dir_2/dir_1/needle_1.txt
dir_2/dir_1/needle_2.txt
dir_2/dir_2/needle_1.txt
dir_2/dir_2/needle_2.txt
dir_2/needle_1.txt
dir_2/needle_2.txt
needle_1.txt
needle_2.txt
</code>```

Body:
Maybe grep piped to xargs grep?

]$ grep -rl "NAMESPACE" | xargs grep -l "Parameter"

With these four files:

]$ tail -n +1 *.txt
==> needle_1.txt <==
...NAMESPACE...
...
...Parameter...

==> needle_2.txt <==
...Parameter...
...
...NAMESPACE...

==> not_needle_1.txt <==
...
...NAMESPACE...
...

==> not_needle_2.txt <==
...
...Parameter...
...

placed in each sub-directory (including .) of:

.
├── dir_1
│   ├── dir_1
│   └── dir_2
└── dir_2
    ├── dir_1
    └── dir_2

the result is:

]$ grep -rl "NAMESPACE" | xargs grep -l "Parameter" | sort
dir_1/dir_1/needle_1.txt
dir_1/dir_1/needle_2.txt
dir_1/dir_2/needle_1.txt
dir_1/dir_2/needle_2.txt
dir_1/needle_1.txt
dir_1/needle_2.txt
dir_2/dir_1/needle_1.txt
dir_2/dir_1/needle_2.txt
dir_2/dir_2/needle_1.txt
dir_2/dir_2/needle_2.txt
dir_2/needle_1.txt
dir_2/needle_2.txt
needle_1.txt
needle_2.txt


问:
Changing my nuxt project's localhost to be my local ip makes the site works only at the first load, then "Unable to fetch collections" happens
I want to run Nuxt at my local IP so that I can access the website from any device in my Network, So I run the following command:

'HOST=0 PORT=8000 npm run dev'

The Result:
The website is accessible from any device in my network, But it's working with many data missed. It's loaded the first time, but after executing some action, a message appears that says "unable to fetch collections".

I can use Ngrok, but I think it's an unsafe option that may be used in certain cases.

I'll appreciate your help all of you. Thanks in advance!

答:
Did you configure the server in nuxt.config file ?

Like this:

...
server: {
  host: '0' // default: localhost
}
...
```


问:
My first COM import
I have a .h file with the following declarations:

```<code>////////////////////////////////////////////////////////////////////////////////
// Syntek Plug-In Custom Control GUIDs.                                       //
////////////////////////////////////////////////////////////////////////////////
// {59DF6360-6F14-4472-82B6-6EAB971EEFAD}
DEFINE_GUID(CLSID_IStkCustomControl,
            0x59DF6360, 0x6F14, 0x4472, 0x82, 0xB6, 0x6E, 0xAB, 0x97, 0x1E, 0xEF, 0xAD);

// {59DF6361-6F14-4472-82B6-6EAB971EEFAD}
DEFINE_GUID(CLSID_IStkCustomControl_PropertyPage,
            0x59DF6361, 0x6F14, 0x4472, 0x82, 0xB6, 0x6E, 0xAB, 0x97, 0x1E, 0xEF, 0xAD);

// Custom Control Interfaces.
MIDL_INTERFACE("59DF6360-6F14-4472-82B6-6EAB971EEFAD")
IStkCustomControl : public IUnknown
{
public:
    virtual HRESULT STDMETHODCALLTYPE Get(PKSPROPERTY_STK_CUSTOM_CONTROL_S pStkCustomControl) = 0;
    virtual HRESULT STDMETHODCALLTYPE Set(PKSPROPERTY_STK_CUSTOM_CONTROL_S pStkCustomControl) = 0;
};
</code>```

I would like to port the interface IStkCustomControl to C#. So far, I have this C# code:

```<code>Guid guid = new Guid(0x59df6360, 0x6f14, 0x4472, 0x82, 0xb6, 0x6e, 0xab, 0x97, 0x1e, 0xef, 0xad);
Type type = Type.GetTypeFromCLSID(guid); // line 2
object obj = Activator.CreateInstance(type);
</code>```

When executing line 2, I get the exception

Creating an instance of the COM component with CLSID
  {59DF6360-6F14-4472-82B6-6EAB971EEFAD} from the IClassFactory failed
  due to the following error: 80040202.

What's going wrong here?

UPDATE: I found out that the IStkCustomControl interface is implemented in a file called StkProp.ax. I've tried to run AxImp.exe StkProp.ax, but that gave me

AxImp Error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))

答:
More often than not, the type info is embedded in the DLL that implements the object. Use OLEView to make sure. If so, then set up a COM reference to that DLL and use the auto wrapper.

Having the type info as standalone TLB file is so late nineties.

Title: My first COM import

Body:
I have a .h file with the following declarations:

////////////////////////////////////////////////////////////////////////////////
// Syntek Plug-In Custom Control GUIDs.                                       //
////////////////////////////////////////////////////////////////////////////////
// {59DF6360-6F14-4472-82B6-6EAB971EEFAD}
DEFINE_GUID(CLSID_IStkCustomControl,
            0x59DF6360, 0x6F14, 0x4472, 0x82, 0xB6, 0x6E, 0xAB, 0x97, 0x1E, 0xEF, 0xAD);

// {59DF6361-6F14-4472-82B6-6EAB971EEFAD}
DEFINE_GUID(CLSID_IStkCustomControl_PropertyPage,
            0x59DF6361, 0x6F14, 0x4472, 0x82, 0xB6, 0x6E, 0xAB, 0x97, 0x1E, 0xEF, 0xAD);

// Custom Control Interfaces.
MIDL_INTERFACE("59DF6360-6F14-4472-82B6-6EAB971EEFAD")
IStkCustomControl : public IUnknown
{
public:
    virtual HRESULT STDMETHODCALLTYPE Get(PKSPROPERTY_STK_CUSTOM_CONTROL_S pStkCustomControl) = 0;
    virtual HRESULT STDMETHODCALLTYPE Set(PKSPROPERTY_STK_CUSTOM_CONTROL_S pStkCustomControl) = 0;
};

I would like to port the interface IStkCustomControl to C#. So far, I have this C# code:

Guid guid = new Guid(0x59df6360, 0x6f14, 0x4472, 0x82, 0xb6, 0x6e, 0xab, 0x97, 0x1e, 0xef, 0xad);
Type type = Type.GetTypeFromCLSID(guid); // line 2
object obj = Activator.CreateInstance(type);

When executing line 2, I get the exception

Creating an instance of the COM component with CLSID
  {59DF6360-6F14-4472-82B6-6EAB971EEFAD} from the IClassFactory failed
  due to the following error: 80040202.

What's going wrong here?

UPDATE: I found out that the IStkCustomControl interface is implemented in a file called StkProp.ax. I've tried to run AxImp.exe StkProp.ax, but that gave me

AxImp Error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))


问:
iOS 14 UIMenu replacingChildren does not work
I want to add an UIMenu with conditional menu children to a UIButton's menu on iOS14, but the replacingChildren does not work.

```<code>self.button.menu = UIMenu( options: .displayInline, children:[
       UIAction(title:"Action 1"){_ in},
       UIAction(title:"Action 2"){_ in}
   ])
</code>```
```<code>//Try to update menu's children but it does not work

self.button.menu = self.button.menu?.replacingChildren([
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
 ])
</code>```

The menu does not change. I need to create a completely new instance of UIMenu with new children and assign it to self.button.menu. How to use replacingChildren or any mistake?

答:
I stumbled upon this as well. For some reason using replacingChildren resulted in the unaltered children array on iOS 14. For iOS 15 the behavior is as expected.

However, I was able to go around this by just setting a newly instantiated UIMenu instead.

In your case by calling:

```<code>self.button.menu = UIMenu(options: .displayInline, children:[
    UIAction(title:"Action 3"){_ in},
    UIAction(title:"Action 4"){_ in}
])
</code>```

Since this isn't the greatest solution and (for me) it was only needed for iOS 14 you might want to only use this when needed:

```<code>if #available(iOS 15.0, *) {
   self.button.menu = self.button.menu?.replacingChildren([
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
   ])
} else {
   self.button.menu = UIMenu(options: .displayInline, children:[
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
   ])
}
</code>```

I hope this might help whoever needs it.

Body:
I want to add an UIMenu with conditional menu children to a UIButton's menu on iOS14, but the replacingChildren does not work.

self.button.menu = UIMenu( options: .displayInline, children:[
       UIAction(title:"Action 1"){_ in},
       UIAction(title:"Action 2"){_ in}
   ])

//Try to update menu's children but it does not work

self.button.menu = self.button.menu?.replacingChildren([
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
 ])

The menu does not change. I need to create a completely new instance of UIMenu with new children and assign it to self.button.menu. How to use replacingChildren or any mistake?

Body:
I stumbled upon this as well. For some reason using replacingChildren resulted in the unaltered children array on iOS 14. For iOS 15 the behavior is as expected.

However, I was able to go around this by just setting a newly instantiated UIMenu instead.

In your case by calling:

self.button.menu = UIMenu(options: .displayInline, children:[
    UIAction(title:"Action 3"){_ in},
    UIAction(title:"Action 4"){_ in}
])

Since this isn't the greatest solution and (for me) it was only needed for iOS 14 you might want to only use this when needed:

if #available(iOS 15.0, *) {
   self.button.menu = self.button.menu?.replacingChildren([
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
   ])
} else {
   self.button.menu = UIMenu(options: .displayInline, children:[
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
   ])
}

I hope this might help whoever needs it.


问:
Extraxt substring until "?" with sub()
So, I want to extract the substring of a string like this
mystr <- "aa/bb/cc?rest"

I found the sub() function but executing sub("?.*", "", mystr) returns "" instead of "aa/bb/cc".

Why?

The reason is obviousyl because of ? being a special character but using backticks or "\?" doesn't solve this problem.

答:
You need double \ for escaping:</p>
```<code>> mystr <- "aa/bb/cc?rest"
> sub("\?.*", "", mystr)
Error: '\?' is an unrecognized escape in character string starting ""\?"
> sub("\\?.*", "", mystr)
[1] "aa/bb/cc"
</code>```

Title: Extraxt substring until "?" with sub()

Body:
You need double \ for escaping:

> mystr <- "aa/bb/cc?rest"
> sub("\?.*", "", mystr)
Error: '\?' is an unrecognized escape in character string starting ""\?"
> sub("\\?.*", "", mystr)
[1] "aa/bb/cc"


问:
Invoke-DbaQuery in a Loop With Just One Set of Headers
I'm running Invoke-DBAQuery with Format-Table in a loop to get system configs from various servers. Each run is writing out its own headers though. Using -HideTableHeaders means I get no headers at all. How can I get just the first set of headers and then not for the rest? All servers are running the same version of SQL so there won't be additional headers for different servers.

```<code>$Servers = 'ServerA','ServerB'
Clear-Variable -Name Data
$Data

ForEach ($Server in $Servers)
{
$Data += Invoke-DbaQuery -SqlInstance $Server -Query "Declare   @List Varchar(Max)

Select      @List = Coalesce(@List + ',', '') + Concat('[',Name,']')
From        sys.Configurations
Order By    Name

Declare @SQL Varchar(Max) =
'Select     @@ServerName as Server
            --,Row_Number() Over (Order By GetDate()) As RowNum
            ,*
From        (
            Select      Name
                        ,Value
            From        sys.configurations
            ) sq
    Pivot   (
            Max(Value)
            For Name In (' + @List + ')
            ) piv'

Exec (@SQL)" | Format-Table #-HideTableHeaders
}

$Data
</code>```

答:
I needed -as DataTable on the Invoke-DbaQuery and then move the Format-Table to the end, thanks @AlwaysLearning for pointing me at -As

```<code>$Servers = 'ServerA','ServerB'
Clear-Variable -Name Data
$Data

ForEach ($Server in $Servers)
{
$Data += Invoke-DbaQuery -SqlInstance $Server -Query "Declare   @List Varchar(Max)

Select      @List = Coalesce(@List + ',', '') + Concat('[',Name,']')
From        sys.Configurations
Order By    Name

Declare @SQL Varchar(Max) =
'Select     @@ServerName as Server
            --,Row_Number() Over (Order By GetDate()) As RowNum
            ,*
From        (
            Select      Name
                        ,Value
            From        sys.configurations
            ) sq
    Pivot   (
            Max(Value)
            For Name In (' + @List + ')
            ) piv'

Exec (@SQL)" -As DataTable
}

$Data | Format-Table
</code>```

Body:
I'm running Invoke-DBAQuery with Format-Table in a loop to get system configs from various servers. Each run is writing out its own headers though. Using -HideTableHeaders means I get no headers at all. How can I get just the first set of headers and then not for the rest? All servers are running the same version of SQL so there won't be additional headers for different servers.

$Servers = 'ServerA','ServerB'
Clear-Variable -Name Data
$Data

ForEach ($Server in $Servers)
{
$Data += Invoke-DbaQuery -SqlInstance $Server -Query "Declare   @List Varchar(Max)

Select      @List = Coalesce(@List + ',', '') + Concat('[',Name,']')
From        sys.Configurations
Order By    Name

Declare @SQL Varchar(Max) =
'Select     @@ServerName as Server
            --,Row_Number() Over (Order By GetDate()) As RowNum
            ,*
From        (
            Select      Name
                        ,Value
            From        sys.configurations
            ) sq
    Pivot   (
            Max(Value)
            For Name In (' + @List + ')
            ) piv'

Exec (@SQL)" | Format-Table #-HideTableHeaders
}

$Data

Body:
I needed -as DataTable on the Invoke-DbaQuery and then move the Format-Table to the end, thanks @AlwaysLearning for pointing me at -As

$Servers = 'ServerA','ServerB'
Clear-Variable -Name Data
$Data

ForEach ($Server in $Servers)
{
$Data += Invoke-DbaQuery -SqlInstance $Server -Query "Declare   @List Varchar(Max)

Select      @List = Coalesce(@List + ',', '') + Concat('[',Name,']')
From        sys.Configurations
Order By    Name

Declare @SQL Varchar(Max) =
'Select     @@ServerName as Server
            --,Row_Number() Over (Order By GetDate()) As RowNum
            ,*
From        (
            Select      Name
                        ,Value
            From        sys.configurations
            ) sq
    Pivot   (
            Max(Value)
            For Name In (' + @List + ')
            ) piv'

Exec (@SQL)" -As DataTable
}

$Data | Format-Table


问:
How to Create/Use SVN without internet to done work in Same Project without getting Crashed in iPhone Project development
I am using MACOS for Developing the iPhone Application.

I have made the repository in to some Public Site that gives Functionality to build the Repository in their server and after that we can use the project to work simultaneously. But it uses internet connection that's why it becomes to slow to update and modification.
I have multiple Computers and I want to Use One PC as a Server and want to Create the Repository there and after from another multiple Computer, I want to use the Same Project to be done simultaneously.

How can i done that settings or that kind repository ?
Please help me regarding this.

答:
I will suggest you to use mercurial rather than subversion. so any one can commit locally and once the server is up, just push the changes.

SVN is a centralised and
hg is a distributed control version system

The main difference b/w
Subversion uses one main directory to store the versionned version and can deploy (export) a specific revision at anytime.
whereas

Mercurial repository holds both the current public version and all the history. You do not have to deploy anything anywhere, just update your current repo with data from one of the revision.

and when you are using hg you do not really need to wait your server up, you can commit locally and push your changes once server up :)

To know more about look at HERE


问:
Need guidance in using LISTAGG with Regular Expression
```<code>SELECT
         ID_Col,
         lower(LISTAGG(distinct TEXT_COL,',')WITHIN GROUP(ORDER BY TEXT_COL))
         AS TEXT_COL_TXT
         FROM
         (SELECT
          CREATE_DT,
          ID_Col,
          TEXT_COL,
          TRY_CAST(Q_NO as INTEGER) as Q_NO
          FROM db_name.schema_name.tbl_name
          WHERE Flg = '0'
          AND date_of_cr = '2022-02-05'
          AND P_CODE NOT IN ('1','2','3','4')
          AND ID_Col IN('12345','23456')
          ORDER BY Q_NO)
          GROUP BY 1;
</code>```

When I run the above query, I'm getting results like this:

```<code>ID_COL                                        TEXT_COL

12345                                 ::abcd::0,aforapple
23456                                 ::abcd::0,n:sometext:::empty::
</code>```

I want this value to be removed in the result --> ::abcd::0,

The result should look like below:

```<code>ID_COL                                   TEXT_COL

12345                                 aforapple
23456                                 n:sometext:::empty::
</code>```

Can anyone guide me how to bring such a result?

When I use the below logic, I could see comma in the results now:

LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')

Result I could see is:

```<code>ID_COL                                   TEXT_COL

12345                                 ,aforapple
23456                                 ,n:sometext:::empty::
</code>```

I should not display comma in the results

答:
Try to apply IFF(), which is similar to CASE WHEN: https://docs.snowflake.com/en/sql-reference/functions/iff.html

```<code>LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')
</code>```

Logic described:
If TEXT_COL =  THEN use empty string ELSE use TEXT_COL for concatenation in LISTAGG

Body:
SELECT
         ID_Col,
         lower(LISTAGG(distinct TEXT_COL,',')WITHIN GROUP(ORDER BY TEXT_COL))
         AS TEXT_COL_TXT
         FROM
         (SELECT
          CREATE_DT,
          ID_Col,
          TEXT_COL,
          TRY_CAST(Q_NO as INTEGER) as Q_NO
          FROM db_name.schema_name.tbl_name
          WHERE Flg = '0'
          AND date_of_cr = '2022-02-05'
          AND P_CODE NOT IN ('1','2','3','4')
          AND ID_Col IN('12345','23456')
          ORDER BY Q_NO)
          GROUP BY 1;

When I run the above query, I'm getting results like this:

ID_COL                                        TEXT_COL

12345                                 ::abcd::0,aforapple
23456                                 ::abcd::0,n:sometext:::empty::

I want this value to be removed in the result --> ::abcd::0,

The result should look like below:

ID_COL                                   TEXT_COL

12345                                 aforapple
23456                                 n:sometext:::empty::

Can anyone guide me how to bring such a result?

When I use the below logic, I could see comma in the results now:

LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')

Result I could see is:

ID_COL                                   TEXT_COL

12345                                 ,aforapple
23456                                 ,n:sometext:::empty::

I should not display comma in the results

Body:
Try to apply IFF(), which is similar to CASE WHEN: https://docs.snowflake.com/en/sql-reference/functions/iff.html

LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')

Logic described:
If TEXT_COL =  THEN use empty string ELSE use TEXT_COL for concatenation in LISTAGG


问:
Serverless Framework - Unable to Deploy Step Function
I have the following serverless yaml that I'm using to try to deploy my first step function:

```<code>org: bizrob
app: flexipod-2-queue
service: flexipod-2-queue

frameworkVersion: "2 || 3"

package:
  exclude:
      # list of biggest modules that are in devdepenedecies and similar
      - node_modules/aws-sdk/**
      - node_modules/serverless-domain-manager/**
      - node_modules/@serverless
      - node_modules/serverless
      - node_modules/java-invoke-local
      - node_modules/tabtab
      - node_modules/snappy

custom:
  region: eu-west-1

provider:
  name: aws
  runtime: nodejs14.x

plugins:
  - serverless-step-functions
functions:
  GetConfigDbConnection:
    handler: flexipod-2-queue/dbConfig.getConfigDbConnection
    environment:
      REGION: ${self:custom.region}
  GetConfigRec:
    handler: flexipod-2-queue/dbConfig.getConfigRec
    environment:
      REGION: ${self:custom.region}
  GetSelectQueries:
    handler: flexipod-2-queue/dbConfig.getSelectQueries
    environment:
      REGION: ${self:custom.region}
  PullSqlSvr:
    handler: flexipod-2-queue/pullSqlSvrData.pullSqlSvr
    environment:
      REGION: ${self:custom.region}
      API_VERSION_S3: "2006-03-01"
      API_VERSION_SQS: "2012-11-05"
      SQS_QUEUE_URL: !Ref "MyQueue"
  SendToDataLake:
    handler: queue-2-datalake/sendToDataLake.sendBatchToQueue
    environment:
      REGION: ${self:custom.region}
      API_VERSION_S3: "2006-03-01"
      API_VERSION_SQS: "2012-11-05"

stepFunctions:
  stateMachines:
    flexipodFlow:
      name: flexipodFlow
      definition:
        StartAt: GetConfigDbConnection
        States:
          GetConfigDbConnection:
            Type: Task
            Resource:
              Fn::GetAtt: [GetConfigDbConnection, Arn]
            Next: GetConfigRec
          GetConfigRec:
            Type: Task
            Resource:
              Fn::GetAtt: [GetConfigRec, Arn]
            Next: GetSelectQueries
          GetSelectQueries:
            Type: Task
            Resource:
              Fn::GetAtt: [GetSelectQueries, Arn]
              ResultPath: $.queries
            Next: Map
          Map:
            Type: Map
            ItemsPath: $.queries
            MaxConcurrency: 2
            Next: Final State
            Iterator:
              StartAt: PullSql
              States:
                PullSql:
                  Type: Task
                  Resource:
                  Fn::GetAtt: [PullSqlSvr, Arn]
          Final State:
            Type: Pass
            End: true
resources:
  Resources:
    MyQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "flexipod"
</code>```

After running serverless deploy, I see get the following error in the vscode terminal:

```<code>Error:
TypeError: Cannot read property 'match' of null
    at C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:472:61
    at arrayMap (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\lodash\lodash.js:653:23)
    at map (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\lodash\lodash.js:9622:14)
    at Function.flatMap (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\lodash\lodash.js:9325:26)    at ServerlessStepFunctions.getIamPermissions (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:413:12)
    at C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:522:56
    at Array.forEach (<anonymous>)
    at ServerlessStepFunctions.compileIamRole (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:511:32)
    at ServerlessStepFunctions.tryCatcher (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\promise.js:547:31)
    at Promise._settlePromise (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\promise.js:604:18)
    at Promise._settlePromiseCtx (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\promise.js:641:10)
    at _drainQueueStep (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:97:12)
    at _drainQueue (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:86:9)
    at Async._drainQueues (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:102:5)
    at Immediate.Async.drainQueues [as _onImmediate] (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:15:14)
    at processImmediate (node:internal/timers:464:21)
</code>```

Anyone see what I've done wrong?

答:
Problem was due to yaml formatting. Line 192

Fn::GetAtt: [PullSqlSvr, Arn]

This needed an extra tab to indent below "Resource:"

Body:
I have the following serverless yaml that I'm using to try to deploy my first step function:

org: bizrob
app: flexipod-2-queue
service: flexipod-2-queue

frameworkVersion: "2 || 3"

package:
  exclude:
      # list of biggest modules that are in devdepenedecies and similar
      - node_modules/aws-sdk/**
      - node_modules/serverless-domain-manager/**
      - node_modules/@serverless
      - node_modules/serverless
      - node_modules/java-invoke-local
      - node_modules/tabtab
      - node_modules/snappy

custom:
  region: eu-west-1

provider:
  name: aws
  runtime: nodejs14.x

plugins:
  - serverless-step-functions
functions:
  GetConfigDbConnection:
    handler: flexipod-2-queue/dbConfig.getConfigDbConnection
    environment:
      REGION: ${self:custom.region}
  GetConfigRec:
    handler: flexipod-2-queue/dbConfig.getConfigRec
    environment:
      REGION: ${self:custom.region}
  GetSelectQueries:
    handler: flexipod-2-queue/dbConfig.getSelectQueries
    environment:
      REGION: ${self:custom.region}
  PullSqlSvr:
    handler: flexipod-2-queue/pullSqlSvrData.pullSqlSvr
    environment:
      REGION: ${self:custom.region}
      API_VERSION_S3: "2006-03-01"
      API_VERSION_SQS: "2012-11-05"
      SQS_QUEUE_URL: !Ref "MyQueue"
  SendToDataLake:
    handler: queue-2-datalake/sendToDataLake.sendBatchToQueue
    environment:
      REGION: ${self:custom.region}
      API_VERSION_S3: "2006-03-01"
      API_VERSION_SQS: "2012-11-05"

stepFunctions:
  stateMachines:
    flexipodFlow:
      name: flexipodFlow
      definition:
        StartAt: GetConfigDbConnection
        States:
          GetConfigDbConnection:
            Type: Task
            Resource:
              Fn::GetAtt: [GetConfigDbConnection, Arn]
            Next: GetConfigRec
          GetConfigRec:
            Type: Task
            Resource:
              Fn::GetAtt: [GetConfigRec, Arn]
            Next: GetSelectQueries
          GetSelectQueries:
            Type: Task
            Resource:
              Fn::GetAtt: [GetSelectQueries, Arn]
              ResultPath: $.queries
            Next: Map
          Map:
            Type: Map
            ItemsPath: $.queries
            MaxConcurrency: 2
            Next: Final State
            Iterator:
              StartAt: PullSql
              States:
                PullSql:
                  Type: Task
                  Resource:
                  Fn::GetAtt: [PullSqlSvr, Arn]
          Final State:
            Type: Pass
            End: true
resources:
  Resources:
    MyQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "flexipod"

After running serverless deploy, I see get the following error in the vscode terminal:

Error:
TypeError: Cannot read property 'match' of null
    at C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:472:61
    at arrayMap (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\lodash\lodash.js:653:23)
    at map (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\lodash\lodash.js:9622:14)
    at Function.flatMap (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\lodash\lodash.js:9325:26)    at ServerlessStepFunctions.getIamPermissions (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:413:12)
    at C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:522:56
    at Array.forEach (<anonymous>)
    at ServerlessStepFunctions.compileIamRole (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\serverless-step-functions\lib\deploy\stepFunctions\compileIamRole.js:511:32)
    at ServerlessStepFunctions.tryCatcher (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\promise.js:547:31)
    at Promise._settlePromise (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\promise.js:604:18)
    at Promise._settlePromiseCtx (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\promise.js:641:10)
    at _drainQueueStep (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:97:12)
    at _drainQueue (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:86:9)
    at Async._drainQueues (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:102:5)
    at Immediate.Async.drainQueues [as _onImmediate] (C:\GitBizTalkers\OLD_Wck_Flexipod\node_modules\bluebird\js\release\async.js:15:14)
    at processImmediate (node:internal/timers:464:21)

Anyone see what I've done wrong?


问:
Tkinter issue 'list' object has no attribute 'tk'
I am working on a tkinter project and am having issues creating a number of buttons using a for loop. When I try to create buttons within a loop, I get the error 'list' object has no attribute 'tk'. I am using two lists generated from a table in db browser which I have shown below. The second part is where the error is occuring. If I remove the RewardButton generator, then no error occurs so I believe it takes issue with this specific line</p>
```<code>    conn = sqlite3.connect("Scheduling.db")
    c = conn.cursor()
    c.execute("select reward from rewards where Cu_ID=?",(ID))
    rewards = c.fetchall()
    c.execute("select points from rewards where Cu_ID=?",(ID))
    points = c.fetchall()
    c.close()
    rewardlist=[]
    for l in rewards:
        rewardlist.append(l)
    pointlist=[]
    for p in points:
        pointlist.append(p)
</code>```
```<code>buttonnum=len(rewardlist)
    for x in range(buttonnum):
        rowpos = x+5
        reward = rewardlist[x]
        point = pointlist[x]
        RewardButton[x] = Button(rewards, text ="Button",command = lambda k=x: RedeemReward(k))
        RewardButton[x].grid(row=rowpos, column=3)
</code>```

答:
I believe your error is being generated because you are passing rewards, instead of reward, as an argument to your Button() class.

I’m assuming so because you defined reward during that for loop. However, I don’t see rewards defined in your code.

Body:
I am working on a tkinter project and am having issues creating a number of buttons using a for loop. When I try to create buttons within a loop, I get the error 'list' object has no attribute 'tk'. I am using two lists generated from a table in db browser which I have shown below. The second part is where the error is occuring. If I remove the RewardButton generator, then no error occurs so I believe it takes issue with this specific line

    conn = sqlite3.connect("Scheduling.db")
    c = conn.cursor()
    c.execute("select reward from rewards where Cu_ID=?",(ID))
    rewards = c.fetchall()
    c.execute("select points from rewards where Cu_ID=?",(ID))
    points = c.fetchall()
    c.close()
    rewardlist=[]
    for l in rewards:
        rewardlist.append(l)
    pointlist=[]
    for p in points:
        pointlist.append(p)

buttonnum=len(rewardlist)
    for x in range(buttonnum):
        rowpos = x+5
        reward = rewardlist[x]
        point = pointlist[x]
        RewardButton[x] = Button(rewards, text ="Button",command = lambda k=x: RedeemReward(k))
        RewardButton[x].grid(row=rowpos, column=3)


问:
Python dict of lists full join
I have a dict with list values, like this:

```<code>d = {'number': [1, 2], 'letter': ['a', 'b']}
</code>```

I need to full join those lists, so I do:

```<code>keys = list(d.keys())

r = [
    {keys[0]: v1, keys[1]: v2}
    for v1 in d[keys[0]]
    for v2 in d[keys[1]]
]
</code>```

This delivers the desired result:

```<code>[{'number': 1, 'letter': 'a'}, {'number': 1, 'letter': 'b'}, {'number': 2, 'letter': 'a'}, {'number': 2, 'letter': 'b'}]
</code>```

How do I scale this solution for a case of 3 or more lists?
For example if I need to process a dict of 3 lists:

```<code>d = {'number': [1, 2], 'letter': ['a', 'b'], 'sign': ['!', '.']}
</code>```

How to do this in case I don't know the number of lists inside the dict?

答:
IIUC, use itertools.product like this:

```<code>>>> from itertools import product
>>> d = {'number': [1, 2], 'letter': ['a', 'b']}
>>> [dict(zip(d, vs)) for vs in product(*d.values())]
[{'number': 1, 'letter': 'a'}, {'number': 1, 'letter': 'b'}, {'number': 2, 'letter': 'a'}, {'number': 2, 'letter': 'b'}]
</code>```

Title: Python dict of lists full join

Body:
I have a dict with list values, like this:

d = {'number': [1, 2], 'letter': ['a', 'b']}

I need to full join those lists, so I do:

keys = list(d.keys())

r = [
    {keys[0]: v1, keys[1]: v2}
    for v1 in d[keys[0]]
    for v2 in d[keys[1]]
]

This delivers the desired result:

[{'number': 1, 'letter': 'a'}, {'number': 1, 'letter': 'b'}, {'number': 2, 'letter': 'a'}, {'number': 2, 'letter': 'b'}]

How do I scale this solution for a case of 3 or more lists?
For example if I need to process a dict of 3 lists:

d = {'number': [1, 2], 'letter': ['a', 'b'], 'sign': ['!', '.']}

How to do this in case I don't know the number of lists inside the dict?

Body:
IIUC, use itertools.product like this:

>>> from itertools import product
>>> d = {'number': [1, 2], 'letter': ['a', 'b']}
>>> [dict(zip(d, vs)) for vs in product(*d.values())]
[{'number': 1, 'letter': 'a'}, {'number': 1, 'letter': 'b'}, {'number': 2, 'letter': 'a'}, {'number': 2, 'letter': 'b'}]