问:
VSCode Launch.json configuration cannot start:desktop -- --app excel fails error 1 for Excel Office-Addin
Following the tutorial Tutorial Create an Excel Addin.

Have completed and tested the first section of the tutorial using the command line.

Trying to use the debugger in vscode to run and debug taskpane.js using Excel Desktop(Edge Legacy).

It fails with below debug error which in short is missing script: start:desktop -- --app excel
This was a closed issue for vscode 1.53.0 Issue 115876. Reading this however I am unsure how to update launch.json to resolve it.

I am using VSCODE 1.64.1

This is my config for Excel Desktop (Edge Legacy)

```<code> {
      "name": "Excel Desktop (Edge Legacy)",
      "type": "office-addin",
      "request": "attach",
      "url": "https://localhost:3000/taskpane.html?_host_Info=Excel$Win32$16.01$en-US$$$$0",
      "port": 9222,
      "timeout": 600000,
      "webRoot": "${workspaceRoot}",
      "preLaunchTask": "Debug: Excel Desktop",
      "postDebugTask": "Stop Debug"
    },
</code>```

Debug Output

```<code>0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'start:desktop -- --app excel'
1 verbose cli ]
2 info using npm@6.14.13
3 info using node@v14.17.3
4 verbose stack Error: missing script: start:desktop -- --app excel
4 verbose stack     at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:155:19)
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:63:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:116:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:436:5
4 verbose stack     at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:391:45)
4 verbose stack     at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:434:3)
4 verbose stack     at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:161:5)
4 verbose stack     at ReadFileContext.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:350:20)
4 verbose stack     at ReadFileContext.callback (C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:123:16)
4 verbose stack     at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:282:13)
5 verbose cwd C:\Users\PC_User\office_projects\My Office Add-in
6 verbose Windows_NT 10.0.19044
7 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "start:desktop -- --app excel"
8 verbose node v14.17.3
9 verbose npm  v6.14.13
10 error missing script: start:desktop -- --app excel
11 verbose exit [ 1, true ]
</code>```

Edit
Package.json

```<code>{
  "name": "office-addin-taskpane-js",
  "version": "0.0.1",
  "repository": {
    "type": "git",
    "url": "https://github.com/OfficeDev/Office-Addin-TaskPane-JS.git"
  },
  "license": "MIT",
  "config": {
    "app_to_debug": "excel",
    "app_type_to_debug": "desktop",
    "dev_server_port": 3000
  },
  "scripts": {
    "build": "webpack --mode production",
    "build:dev": "webpack --mode development",
    "dev-server": "webpack serve --mode development",
    "lint": "office-addin-lint check",
    "lint:fix": "office-addin-lint fix",
    "prettier": "office-addin-lint prettier",
    "start": "office-addin-debugging start manifest.xml",
    "start:desktop": "office-addin-debugging start manifest.xml desktop",
    "start:web": "office-addin-debugging start manifest.xml web",
    "stop": "office-addin-debugging stop manifest.xml",
    "validate": "office-addin-manifest validate manifest.xml",
    "watch": "webpack --mode development --watch"
  },
  "dependencies": {
    "core-js": "^3.9.1",
    "regenerator-runtime": "^0.13.7"
  },
  "devDependencies": {
    "@babel/core": "^7.13.10",
    "@babel/preset-env": "^7.12.11",
    "@babel/preset-typescript": "^7.13.0",
    "@types/office-js": "^1.0.180",
    "@types/office-runtime": "^1.0.17",
    "acorn": "^8.5.0",
    "babel-loader": "^8.2.2",
    "copy-webpack-plugin": "^9.0.1",
    "eslint-plugin-office-addins": "^2.0.0",
    "file-loader": "^6.2.0",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^5.3.2",
    "office-addin-cli": "^1.3.5",
    "office-addin-debugging": "^4.3.8",
    "office-addin-dev-certs": "^1.7.7",
    "office-addin-lint": "^2.0.0",
    "office-addin-manifest": "^1.7.7",
    "office-addin-prettier-config": "^1.1.4",
    "os-browserify": "^0.3.0",
    "process": "^0.11.10",
    "source-map-loader": "^3.0.0",
    "ts-loader": "^9.2.5",
    "typescript": "^4.3.5",
    "webpack": "^5.50.0",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "4.7.3"
  },
  "prettier": "office-addin-prettier-config",
  "browserslist": [
    "ie 11"
  ]
}
</code>```

答:
I've just tried to create a new Excel add-in according to your description and run it under the debugger. Everything went well without issues. But I've used the Edge (Chromium) option in the launch section.

It seems the package.json file doesn't contain a corresponding command in the scripts section, the following error message clearly states about that:

```<code>4 verbose stack Error: missing script: start:desktop -- --app excel
</code>```

I'd suggest generating a new add-in project using yeoman generator and checking the scripts section there. Don't forget to update the yeoman itself.

For example, in Outlook add-ins I see the following command in the scripts section:

```<code>"start:desktop": "office-addin-debugging start manifest.xml desktop",
</code>```

Body:
Following the tutorial Tutorial Create an Excel Addin.

Have completed and tested the first section of the tutorial using the command line.

Trying to use the debugger in vscode to run and debug taskpane.js using Excel Desktop(Edge Legacy).

It fails with below debug error which in short is missing script: start:desktop -- --app excel
This was a closed issue for vscode 1.53.0 Issue 115876. Reading this however I am unsure how to update launch.json to resolve it.

I am using VSCODE 1.64.1

This is my config for Excel Desktop (Edge Legacy)

 {
      "name": "Excel Desktop (Edge Legacy)",
      "type": "office-addin",
      "request": "attach",
      "url": "https://localhost:3000/taskpane.html?_host_Info=Excel$Win32$16.01$en-US$$$$0",
      "port": 9222,
      "timeout": 600000,
      "webRoot": "${workspaceRoot}",
      "preLaunchTask": "Debug: Excel Desktop",
      "postDebugTask": "Stop Debug"
    },

Debug Output

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'start:desktop -- --app excel'
1 verbose cli ]
2 info using npm@6.14.13
3 info using node@v14.17.3
4 verbose stack Error: missing script: start:desktop -- --app excel
4 verbose stack     at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:155:19)
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:63:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:116:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:436:5
4 verbose stack     at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:391:45)
4 verbose stack     at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:434:3)
4 verbose stack     at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:161:5)
4 verbose stack     at ReadFileContext.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:350:20)
4 verbose stack     at ReadFileContext.callback (C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:123:16)
4 verbose stack     at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:282:13)
5 verbose cwd C:\Users\PC_User\office_projects\My Office Add-in
6 verbose Windows_NT 10.0.19044
7 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "start:desktop -- --app excel"
8 verbose node v14.17.3
9 verbose npm  v6.14.13
10 error missing script: start:desktop -- --app excel
11 verbose exit [ 1, true ]

Edit
Package.json

{
  "name": "office-addin-taskpane-js",
  "version": "0.0.1",
  "repository": {
    "type": "git",
    "url": "https://github.com/OfficeDev/Office-Addin-TaskPane-JS.git"
  },
  "license": "MIT",
  "config": {
    "app_to_debug": "excel",
    "app_type_to_debug": "desktop",
    "dev_server_port": 3000
  },
  "scripts": {
    "build": "webpack --mode production",
    "build:dev": "webpack --mode development",
    "dev-server": "webpack serve --mode development",
    "lint": "office-addin-lint check",
    "lint:fix": "office-addin-lint fix",
    "prettier": "office-addin-lint prettier",
    "start": "office-addin-debugging start manifest.xml",
    "start:desktop": "office-addin-debugging start manifest.xml desktop",
    "start:web": "office-addin-debugging start manifest.xml web",
    "stop": "office-addin-debugging stop manifest.xml",
    "validate": "office-addin-manifest validate manifest.xml",
    "watch": "webpack --mode development --watch"
  },
  "dependencies": {
    "core-js": "^3.9.1",
    "regenerator-runtime": "^0.13.7"
  },
  "devDependencies": {
    "@babel/core": "^7.13.10",
    "@babel/preset-env": "^7.12.11",
    "@babel/preset-typescript": "^7.13.0",
    "@types/office-js": "^1.0.180",
    "@types/office-runtime": "^1.0.17",
    "acorn": "^8.5.0",
    "babel-loader": "^8.2.2",
    "copy-webpack-plugin": "^9.0.1",
    "eslint-plugin-office-addins": "^2.0.0",
    "file-loader": "^6.2.0",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^5.3.2",
    "office-addin-cli": "^1.3.5",
    "office-addin-debugging": "^4.3.8",
    "office-addin-dev-certs": "^1.7.7",
    "office-addin-lint": "^2.0.0",
    "office-addin-manifest": "^1.7.7",
    "office-addin-prettier-config": "^1.1.4",
    "os-browserify": "^0.3.0",
    "process": "^0.11.10",
    "source-map-loader": "^3.0.0",
    "ts-loader": "^9.2.5",
    "typescript": "^4.3.5",
    "webpack": "^5.50.0",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "4.7.3"
  },
  "prettier": "office-addin-prettier-config",
  "browserslist": [
    "ie 11"
  ]
}

Body:
I've just tried to create a new Excel add-in according to your description and run it under the debugger. Everything went well without issues. But I've used the Edge (Chromium) option in the launch section.

It seems the package.json file doesn't contain a corresponding command in the scripts section, the following error message clearly states about that:

4 verbose stack Error: missing script: start:desktop -- --app excel

I'd suggest generating a new add-in project using yeoman generator and checking the scripts section there. Don't forget to update the yeoman itself.

For example, in Outlook add-ins I see the following command in the scripts section:

"start:desktop": "office-addin-debugging start manifest.xml desktop",


来源: stackexchange

问:
*(*ptr)[4] and ++(*ptr)[2] functionality in this program
```<code>#include <iostream>
using namespace std;
int main()
{
    int i;
    const char *arr[] = {"C", "C++", "Java", "VBA"};
    const char *(*ptr)[4] = &arr;
    cout << ++(*ptr)[2];
    return 0;
}
</code>```

Output is "ava"

I am not able to understand why code is giving this output.
I tried to breakdown the code line by line to understand, but I am not that good in pointers so I am not able to understand what *(*ptr)[4] and ++(*ptr) is doing?
So I want to know their functionality in this code

答:
First line:

```<code>const char *(*ptr)[4] = &arr;
</code>```

This declares ptr to be a pointer to an array of 4 pointers to const char, and initialize it to point to arr

second one (I willingly omitted the cout):

```<code> ++(*ptr)[2];
</code>```

This increments the third element of the array pointed to by ptr, hence arr. After that, printing elements of the array would give C, C++, ava and VBA.

ContentLicense: CC BY-SA 4.0

Body:
#include <iostream>
using namespace std;
int main()
{
    int i;
    const char *arr[] = {"C", "C++", "Java", "VBA"};
    const char *(*ptr)[4] = &arr;
    cout << ++(*ptr)[2];
    return 0;
}

Output is "ava"

I am not able to understand why code is giving this output.
I tried to breakdown the code line by line to understand, but I am not that good in pointers so I am not able to understand what *(*ptr)[4] and ++(*ptr) is doing?
So I want to know their functionality in this code

Body:
First line:

const char *(*ptr)[4] = &arr;

This declares ptr to be a pointer to an array of 4 pointers to const char, and initialize it to point to arr

second one (I willingly omitted the cout):

 ++(*ptr)[2];

This increments the third element of the array pointed to by ptr, hence arr. After that, printing elements of the array would give C, C++, ava and VBA.


问:
Swagger and JSON Patch
I have the following object structure in my database

```<code>{
    partnerName: '24 Fitness',
    supportedProducts: [
        'FitBit',
        'Protein Powder'
    ]
},
</code>```

where the key value supportedProducts can be modified from the client side.

I am constructing a PATCH API method using swagger documentation to support the above functionality. But I am unsure of the patch object definition, as documentation doesn't provide an detailed example of constructing a PATCH.

The current definition that I have ends up in error upon execution and looks like as following

```<code> "patch":{
    "description":"Update supported products for a partner",
    "operationId":"Update supported products",
    "parameters":[
      {
        "name": "partnerName",
        "in": "path",
        "required": true,
        "type": "string"
      },
      {
        "name": "supportedProducts",
        "in": "body",
        "required": true,
        "schema":{
          "$ref":"#/definitions/PatchRequest"
        }
      }
    ],
    "responses":{
      "200":{
        "description": "product updated"
      },
      "404":{
        "description": "Not Found"
      }
    }

  "definitions": {
    "PatchRequest":{
      "type": "object",
      "required":[
        "partnerName",
        "supportedProducts"
      ],
      "properties":{
        "partnerName":{"type": "string"},
        "supportedProducts":{
          "type": "array",
          "items":{"type": "string"}
        }
      }

    }
  }
</code>```

答:
Since the JSON Patch format is well defined by RFC 6902 I think it would be sufficient (at least for OpenAPI 3) to specify the content type defined in the RFC, and since it seems to be necessary to define either a schema or example (at least in my swagger editor), to also specify type: string and format: JSON Patch or format: RFC 6902.

It doesn't make sense to redefine a format that is already well defined by the RFC.

Example:

```<code>paths:
  /users/{GUID}:
    patch:
      summary: Update a user
      parameters:
      - name: GUID
        in: path
        required: true
        type: string
        format: GUID
        description: The GUID of a specific user
      requestBody:
        content:
          application/json-patch+json:
            schema:
              type: string
              format: RFC 6902
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swagger and JSON Patch

Body:
I have the following object structure in my database

{
    partnerName: '24 Fitness',
    supportedProducts: [
        'FitBit',
        'Protein Powder'
    ]
},

where the key value supportedProducts can be modified from the client side.

I am constructing a PATCH API method using swagger documentation to support the above functionality. But I am unsure of the patch object definition, as documentation doesn't provide an detailed example of constructing a PATCH.

The current definition that I have ends up in error upon execution and looks like as following

 "patch":{
    "description":"Update supported products for a partner",
    "operationId":"Update supported products",
    "parameters":[
      {
        "name": "partnerName",
        "in": "path",
        "required": true,
        "type": "string"
      },
      {
        "name": "supportedProducts",
        "in": "body",
        "required": true,
        "schema":{
          "$ref":"#/definitions/PatchRequest"
        }
      }
    ],
    "responses":{
      "200":{
        "description": "product updated"
      },
      "404":{
        "description": "Not Found"
      }
    }

  "definitions": {
    "PatchRequest":{
      "type": "object",
      "required":[
        "partnerName",
        "supportedProducts"
      ],
      "properties":{
        "partnerName":{"type": "string"},
        "supportedProducts":{
          "type": "array",
          "items":{"type": "string"}
        }
      }

    }
  }

Body:
Since the JSON Patch format is well defined by RFC 6902 I think it would be sufficient (at least for OpenAPI 3) to specify the content type defined in the RFC, and since it seems to be necessary to define either a schema or example (at least in my swagger editor), to also specify type: string and format: JSON Patch or format: RFC 6902.

It doesn't make sense to redefine a format that is already well defined by the RFC.

Example:

paths:
  /users/{GUID}:
    patch:
      summary: Update a user
      parameters:
      - name: GUID
        in: path
        required: true
        type: string
        format: GUID
        description: The GUID of a specific user
      requestBody:
        content:
          application/json-patch+json:
            schema:
              type: string
              format: RFC 6902


问:
Swift: is there any functional difference between "private static let" (in a class definition) and "fileprivate let" (no owner)
The question says it all really, but is there a functional difference between:

One way to define it:

class SomeClass {

    private static let someValues: [String] = [
        "mrah!",
        "blah",
        "shmah!"
    ]

    var possibleValues: [String] {
        return Self.someValues
    }
}
```
<p>or defined as:</p>
<pre class="lang-swift prettyprint-override"><code>class SomeClass {

    var possibleValues: [String] {
        return someValues
    }
}

fileprivate let someValues: [String] = [
    "mrah!",
    "blah",
    "shmah!"
]
</code>```

Functionally identical, no?  The defined array is inaccessible outside of the instance variable someValues Is there a reason not to do the latter?

(I want to include a bunch of long arrays in my class definition and you can't declare stored properties in extensions, and for the sake of code readability / brevity, I want to put these at the bottom of the implementation file, underneath other extensions.)

答:
Your plan is fine, though you might as well mark the file-level value as private rather than fileprivate. They will behave the same. They are both even lazily initialized.

For full details on them, see "Global and Local Variables" and "Type Properties" in the Properties section of The Swift Programming Language.

Body:
The question says it all really, but is there a functional difference between:

One way to define it:

class SomeClass {

    private static let someValues: [String] = [
        "mrah!",
        "blah",
        "shmah!"
    ]

    var possibleValues: [String] {
        return Self.someValues
    }
}

or defined as:

class SomeClass {

    var possibleValues: [String] {
        return someValues
    }
}

fileprivate let someValues: [String] = [
    "mrah!",
    "blah",
    "shmah!"
]

Functionally identical, no?  The defined array is inaccessible outside of the instance variable someValues Is there a reason not to do the latter?

(I want to include a bunch of long arrays in my class definition and you can't declare stored properties in extensions, and for the sake of code readability / brevity, I want to put these at the bottom of the implementation file, underneath other extensions.)


问:
Customizing HttpStatus code to column cannot be null
What is the best HttpStatus code to return on a Rest Api when I have java.sql.SQLIntegrityConstraintViolationException: Column 'xpto' cannot be null?

I have an exception handler to other types, but not to null fields:

```<code>@ExceptionHandler({DataIntegrityViolationException.class})
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex, WebRequest request) {
        Throwable cause = ex.getRootCause();
        if (cause instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException consEx = (SQLIntegrityConstraintViolationException)cause;
            String message = "";
            String constraint = "";
            HttpStatus httpStatus = null;
            if (consEx.getMessage().contains("UNIQUE")) {
                message = "Cannot enter the same record twice";
                constraint = "DUPLICATED_RECORD";
                httpStatus = HttpStatus.CONFLICT;
            } else if (consEx.getMessage().contains("foreign key constraint")) {
                message = "Record still have reference from other table";
                constraint = "USED_RECORD";
                httpStatus = HttpStatus.UNPROCESSABLE_ENTITY;
            }

            return this.buildResponseEntity(new ApiError(httpStatus, message, consEx.getMessage(), constraint));
        } else {
            return ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException ? this.buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex)) : this.buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
        }
}
</code>```

答:
I've added a treatment to column cannot be null and used 400 - BAD_REQUEST as http status code:

```<code>    @ExceptionHandler(DataIntegrityViolationException.class)
    protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex,
                                                                  WebRequest request) {
        Throwable cause = ex.getRootCause();
        if (cause instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException consEx = (SQLIntegrityConstraintViolationException) cause;
            String message = "";
            String constraint = "";
            HttpStatus httpStatus = null;
            if (consEx.getMessage().contains("UNIQUE")) {
                message = "Cannot enter the same record twice";
                constraint = "DUPLICATED_RECORD";
                httpStatus = HttpStatus.CONFLICT;
            } else if (consEx.getMessage().contains("foreign key constraint")) {
                message = "Record still have reference from other table";
                constraint = "USED_RECORD";
                httpStatus = HttpStatus.UNPROCESSABLE_ENTITY;
            } else if (consEx.getMessage().contains("cannot be null")){
                message = "Record cannot be null";
                constraint = "NULL_RECORD";
                httpStatus = BAD_REQUEST;
            }
            return buildResponseEntity(new ApiError(httpStatus, message, consEx.getMessage(), constraint));
        } else if (ex.getCause() instanceof ConstraintViolationException) {
            return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex));
        }
        return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
}
</code>```

Body:
What is the best HttpStatus code to return on a Rest Api when I have java.sql.SQLIntegrityConstraintViolationException: Column 'xpto' cannot be null?

I have an exception handler to other types, but not to null fields:

@ExceptionHandler({DataIntegrityViolationException.class})
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex, WebRequest request) {
        Throwable cause = ex.getRootCause();
        if (cause instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException consEx = (SQLIntegrityConstraintViolationException)cause;
            String message = "";
            String constraint = "";
            HttpStatus httpStatus = null;
            if (consEx.getMessage().contains("UNIQUE")) {
                message = "Cannot enter the same record twice";
                constraint = "DUPLICATED_RECORD";
                httpStatus = HttpStatus.CONFLICT;
            } else if (consEx.getMessage().contains("foreign key constraint")) {
                message = "Record still have reference from other table";
                constraint = "USED_RECORD";
                httpStatus = HttpStatus.UNPROCESSABLE_ENTITY;
            }

            return this.buildResponseEntity(new ApiError(httpStatus, message, consEx.getMessage(), constraint));
        } else {
            return ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException ? this.buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex)) : this.buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
        }
}

Body:
I've added a treatment to column cannot be null and used 400 - BAD_REQUEST as http status code:

    @ExceptionHandler(DataIntegrityViolationException.class)
    protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex,
                                                                  WebRequest request) {
        Throwable cause = ex.getRootCause();
        if (cause instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException consEx = (SQLIntegrityConstraintViolationException) cause;
            String message = "";
            String constraint = "";
            HttpStatus httpStatus = null;
            if (consEx.getMessage().contains("UNIQUE")) {
                message = "Cannot enter the same record twice";
                constraint = "DUPLICATED_RECORD";
                httpStatus = HttpStatus.CONFLICT;
            } else if (consEx.getMessage().contains("foreign key constraint")) {
                message = "Record still have reference from other table";
                constraint = "USED_RECORD";
                httpStatus = HttpStatus.UNPROCESSABLE_ENTITY;
            } else if (consEx.getMessage().contains("cannot be null")){
                message = "Record cannot be null";
                constraint = "NULL_RECORD";
                httpStatus = BAD_REQUEST;
            }
            return buildResponseEntity(new ApiError(httpStatus, message, consEx.getMessage(), constraint));
        } else if (ex.getCause() instanceof ConstraintViolationException) {
            return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex));
        }
        return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
}


问:
Mongo .find() returning duplicate documents (with same _id) (!)
Mongo appears to be returning duplicate documents for the same query, i.e. it returns more documents than there are unique _ids in the returned documents:

```<code>lobby-brain> count_iterated = 0; ids = {}
{}
lobby-brain> db.the_collection.find({
    'a_boolean_key': true
}).forEach((el) => {
    count_iterated += 1;
    ids[el._id] = (ids[el._id]||0) + 1;
})
lobby-brain> count_iterated
278
lobby-brain> Object.keys(ids).length
251
</code>```

That is, the number of unique _id returned is 251 -- but there were 278 documents returned by the cursor.

Investigating further:

```<code>lobby-brain> ids
{
  '60cb8cb92c909a974a96a430': 1,
  '61114dea1a13c86146729f21': 1,
  '6111513a1a13c861467d3dcf': 1,
  ...
  '61114c491a13c861466d39cf': 2,
  '61114bcc1a13c861466b9f8e': 2,
  ...
}
lobby-brain> db.the_collection.find({
    _id: ObjectId("61114c491a13c861466d39cf")
}).forEach((el) => print("foo"));
foo

>
</code>```

That is, there aren't actually duplicate documents with the same _id -- it's just an issue with the .find().

I tried restarting the database, and rebuilding an index involving 'a_boolean_key', with the same results.

I've never seen this before and this seems impossible... what is causing this and how can I fix it?

Version info:

```<code>Using MongoDB:          5.0.5
Using Mongosh:          1.0.4
</code>```

It is a stand-alone database, no replica set or sharding or anything like that.

Further Info

One thing to note is, there is a compound index with a_boolean_key as the first index, and a datetime field as the second. The boolean key is rarely updated on the database (~once/day), but the datetime field is frequently updated.

Maybe these updates are causing the duplicate return values?

Update Feb 15, 2022: I added a Mongo JIRA task here.

答:
Try checking if you store indexes for a_boolean_key field.

When performing a count, MongoDB can return the count using only the
index

So, maybe you don't have indexes for all documents, so count method result is not equal to your manual count.

Body:
Mongo appears to be returning duplicate documents for the same query, i.e. it returns more documents than there are unique _ids in the returned documents:

lobby-brain> count_iterated = 0; ids = {}
{}
lobby-brain> db.the_collection.find({
    'a_boolean_key': true
}).forEach((el) => {
    count_iterated += 1;
    ids[el._id] = (ids[el._id]||0) + 1;
})
lobby-brain> count_iterated
278
lobby-brain> Object.keys(ids).length
251

That is, the number of unique _id returned is 251 -- but there were 278 documents returned by the cursor.

Investigating further:

lobby-brain> ids
{
  '60cb8cb92c909a974a96a430': 1,
  '61114dea1a13c86146729f21': 1,
  '6111513a1a13c861467d3dcf': 1,
  ...
  '61114c491a13c861466d39cf': 2,
  '61114bcc1a13c861466b9f8e': 2,
  ...
}
lobby-brain> db.the_collection.find({
    _id: ObjectId("61114c491a13c861466d39cf")
}).forEach((el) => print("foo"));
foo

>

That is, there aren't actually duplicate documents with the same _id -- it's just an issue with the .find().

I tried restarting the database, and rebuilding an index involving 'a_boolean_key', with the same results.

I've never seen this before and this seems impossible... what is causing this and how can I fix it?

Version info:

Using MongoDB:          5.0.5
Using Mongosh:          1.0.4

It is a stand-alone database, no replica set or sharding or anything like that.

Further Info

One thing to note is, there is a compound index with a_boolean_key as the first index, and a datetime field as the second. The boolean key is rarely updated on the database (~once/day), but the datetime field is frequently updated.

Maybe these updates are causing the duplicate return values?

Update Feb 15, 2022: I added a Mongo JIRA task here.


问:
'User' object has no attribute 'staffUser'
I customized the User Model Using Django One To One Field

My models.py

```<code>class StaffUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.ForeignKey(Dept, on_delete=models.RESTRICT)

    def __str__(self):
        return self.user.username
</code>```

When uploading a form, i want to get the department of the user

'My Views.py'

```<code>   def FileUploadForm(request, pk):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=False)
            u = User.objects.get(username=request.user)
            form.instance.username = u
            folder = Folder.objects.get(id=pk)
            department = u.staffUser.department
            form.save()
            messages.success(request, f'File Successfully uploaded to {folder} in {department}!')
            return redirect('home')
    else:
        form = UploadFileForm()

    context = {'pk':pk, 'form':form}
    return render(request, "pages/fileup_form.html", context)
</code>```

But it gives error
AttributeError at /file/new/1
'User' object has no attribute 'staffUser'

Please guys i need help

答:
You need to specify the reverse in lower case, so staffuser instead of staffUser.

Alternatively you can specify the related name to be used for calling the reverse accessor, as per below in place of some_name.

user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=some_name)

Body:
I customized the User Model Using Django One To One Field

My models.py

class StaffUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.ForeignKey(Dept, on_delete=models.RESTRICT)

    def __str__(self):
        return self.user.username

When uploading a form, i want to get the department of the user

'My Views.py'

   def FileUploadForm(request, pk):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=False)
            u = User.objects.get(username=request.user)
            form.instance.username = u
            folder = Folder.objects.get(id=pk)
            department = u.staffUser.department
            form.save()
            messages.success(request, f'File Successfully uploaded to {folder} in {department}!')
            return redirect('home')
    else:
        form = UploadFileForm()

    context = {'pk':pk, 'form':form}
    return render(request, "pages/fileup_form.html", context)

But it gives error
AttributeError at /file/new/1
'User' object has no attribute 'staffUser'

Please guys i need help


问:
How to setup apache superset local flask backed correctly?
I always get the following error while setting up the local backend for apache-superset following this article https://superset.apache.org/docs/Contributing/local-backend/

How to reproduce the bug

clone this repo https://github.com/apache/superset

cd superset

# Create a virtual environment and activate it (recommended)
python3 -m venv venv # setup a python3 virtualenv
source venv/bin/activate

# Install external dependencies
pip install -r requirements/testing.txt

# Install Superset in editable (development) mode
pip install -e .

# Initialize the database
superset db upgrade

# Create an admin user in your metadata database (use `admin` as username to be able to load the examples)
superset fab create-admin

# Create default roles and permissions
superset init

```
<h3>Expected results</h3>
<p>Apache superset must start successfully but upon running superset init the following error occurs frequently</p>
<h3>Actual results</h3>
<p>superset init command exits with exit code 1 and throwing following output.
clearly it can be seen the error is <code>sqlite3.OperationalError: no such column: dbs.allow_file_upload</code></p>
<pre class="lang-sh prettyprint-override"><code>(venv) (base) mohnish@MMMDVMOHNISHSINT superset % superset init
--------------------------------------------------------------------------------
                                    WARNING
--------------------------------------------------------------------------------
A Default SECRET_KEY was detected, please use superset_config.py to override it.
Use a strong complex alphanumeric string and use a tool to help you generate
a sufficiently random sequence, ex: openssl rand -base64 42
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
logging was configured successfully
2022-02-09 12:27:38,482:INFO:superset.utils.logging_configurator:logging was configured successfully
2022-02-09 12:27:38,492:INFO:root:Configured event logger of type <class 'superset.utils.log.DBEventLogger'>
/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask_caching/__init__.py:201: UserWarning: Flask-Caching: CACHE_TYPE is set to null, caching is effectively disabled.
  warnings.warn(
Syncing role definition
2022-02-09 12:27:40,476:INFO:superset.security.manager:Syncing role definition
Syncing Admin perms
2022-02-09 12:27:40,483:INFO:superset.security.manager:Syncing Admin perms
Syncing Alpha perms
2022-02-09 12:27:40,548:INFO:superset.security.manager:Syncing Alpha perms
Syncing Gamma perms
2022-02-09 12:27:40,613:INFO:superset.security.manager:Syncing Gamma perms
Syncing granter perms
2022-02-09 12:27:40,679:INFO:superset.security.manager:Syncing granter perms
Syncing sql_lab perms
2022-02-09 12:27:40,742:INFO:superset.security.manager:Syncing sql_lab perms
Fetching a set of all perms to lookup which ones are missing
2022-02-09 12:27:40,805:INFO:superset.security.manager:Fetching a set of all perms to lookup which ones are missing
Creating missing datasource permissions.
2022-02-09 12:27:40,864:INFO:superset.security.manager:Creating missing datasource permissions.
Traceback (most recent call last):
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 608, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such column: dbs.allow_file_upload

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/mohnish/Desktop/superset/venv/bin/superset", line 33, in <module>
    sys.exit(load_entry_point('apache-superset', 'console_scripts', 'superset')())
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask/cli.py", line 586, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask/cli.py", line 426, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask/cli.py", line 426, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/superset/cli/main.py", line 61, in init
    security_manager.sync_role_definitions()
  File "/Users/mohnish/Desktop/superset/superset/security/manager.py", line 726, in sync_role_definitions
    self.create_missing_perms()
  File "/Users/mohnish/Desktop/superset/superset/security/manager.py", line 668, in create_missing_perms
    merge_pv("datasource_access", datasource.get_perm())
  File "/Users/mohnish/Desktop/superset/superset/connectors/sqla/models.py", line 634, in get_perm
    return f"[{self.database}].[{self.table_name}](id:{self.id})"
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 294, in __get__
    return self.impl.get(instance_state(instance), dict_)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 730, in get
    value = self.callable_(state, passive)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py", line 759, in _load_for_state
    return self._emit_lazyload(
  File "<string>", line 1, in <lambda>
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py", line 847, in _emit_lazyload
    q(session)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/ext/baked.py", line 615, in _load_on_pk_identity
    result = list(bq.for_session(self.session).params(**params))
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/ext/baked.py", line 444, in __iter__
    return q._execute_and_instances(context)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 3560, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1011, in execute
    return meth(self, multiparams, params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 298, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1124, in _execute_clauseelement
    ret = self._execute_context(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1316, in _execute_context
    self._handle_dbapi_exception(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1510, in _handle_dbapi_exception
    util.raise_(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
    raise exception
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 608, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: dbs.allow_file_upload
[SQL: SELECT dbs.uuid AS dbs_uuid, dbs.created_on AS dbs_created_on, dbs.changed_on AS dbs_changed_on, dbs.id AS dbs_id, dbs.verbose_name AS dbs_verbose_name, dbs.database_name AS dbs_database_name, dbs.sqlalchemy_uri AS dbs_sqlalchemy_uri, dbs.password AS dbs_password, dbs.cache_timeout AS dbs_cache_timeout, dbs.select_as_create_table_as AS dbs_select_as_create_table_as, dbs.expose_in_sqllab AS dbs_expose_in_sqllab, dbs.configuration_method AS dbs_configuration_method, dbs.allow_run_async AS dbs_allow_run_async, dbs.allow_file_upload AS dbs_allow_file_upload, dbs.allow_ctas AS dbs_allow_ctas, dbs.allow_cvas AS dbs_allow_cvas, dbs.allow_dml AS dbs_allow_dml, dbs.force_ctas_schema AS dbs_force_ctas_schema, dbs.allow_multi_schema_metadata_fetch AS dbs_allow_multi_schema_metadata_fetch, dbs.extra AS dbs_extra, dbs.encrypted_extra AS dbs_encrypted_extra, dbs.impersonate_user AS dbs_impersonate_user, dbs.server_cert AS dbs_server_cert, dbs.is_managed_externally AS dbs_is_managed_externally, dbs.external_url AS dbs_external_url, dbs.created_by_fk AS dbs_created_by_fk, dbs.changed_by_fk AS dbs_changed_by_fk
FROM dbs
WHERE dbs.id = ?]
[parameters: (1,)]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
(venv) (base) mohnish@MMMDVMOHNISHSINT superset % FLASK_ENV=development superset run -p 8088 --with-threads --reload --debugger
</code>```

Environment

browser type and version: chrome latest macos

superset version: cloning directly from master branch of apache superset gihub repo

python version:  3.9

node.js version: 16.13.2

答: Just delete ~.superset/superset.db and run again it works fine!

Body:
I always get the following error while setting up the local backend for apache-superset following this article https://superset.apache.org/docs/Contributing/local-backend/

How to reproduce the bug

clone this repo https://github.com/apache/superset

cd superset

# Create a virtual environment and activate it (recommended)
python3 -m venv venv # setup a python3 virtualenv
source venv/bin/activate

# Install external dependencies
pip install -r requirements/testing.txt

# Install Superset in editable (development) mode
pip install -e .

# Initialize the database
superset db upgrade

# Create an admin user in your metadata database (use `admin` as username to be able to load the examples)
superset fab create-admin

# Create default roles and permissions
superset init

Expected results

Apache superset must start successfully but upon running superset init the following error occurs frequently

Actual results

superset init command exits with exit code 1 and throwing following output.
clearly it can be seen the error is sqlite3.OperationalError: no such column: dbs.allow_file_upload

(venv) (base) mohnish@MMMDVMOHNISHSINT superset % superset init
--------------------------------------------------------------------------------
                                    WARNING
--------------------------------------------------------------------------------
A Default SECRET_KEY was detected, please use superset_config.py to override it.
Use a strong complex alphanumeric string and use a tool to help you generate
a sufficiently random sequence, ex: openssl rand -base64 42
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
logging was configured successfully
2022-02-09 12:27:38,482:INFO:superset.utils.logging_configurator:logging was configured successfully
2022-02-09 12:27:38,492:INFO:root:Configured event logger of type <class 'superset.utils.log.DBEventLogger'>
/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask_caching/__init__.py:201: UserWarning: Flask-Caching: CACHE_TYPE is set to null, caching is effectively disabled.
  warnings.warn(
Syncing role definition
2022-02-09 12:27:40,476:INFO:superset.security.manager:Syncing role definition
Syncing Admin perms
2022-02-09 12:27:40,483:INFO:superset.security.manager:Syncing Admin perms
Syncing Alpha perms
2022-02-09 12:27:40,548:INFO:superset.security.manager:Syncing Alpha perms
Syncing Gamma perms
2022-02-09 12:27:40,613:INFO:superset.security.manager:Syncing Gamma perms
Syncing granter perms
2022-02-09 12:27:40,679:INFO:superset.security.manager:Syncing granter perms
Syncing sql_lab perms
2022-02-09 12:27:40,742:INFO:superset.security.manager:Syncing sql_lab perms
Fetching a set of all perms to lookup which ones are missing
2022-02-09 12:27:40,805:INFO:superset.security.manager:Fetching a set of all perms to lookup which ones are missing
Creating missing datasource permissions.
2022-02-09 12:27:40,864:INFO:superset.security.manager:Creating missing datasource permissions.
Traceback (most recent call last):
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 608, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such column: dbs.allow_file_upload

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/mohnish/Desktop/superset/venv/bin/superset", line 33, in <module>
    sys.exit(load_entry_point('apache-superset', 'console_scripts', 'superset')())
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask/cli.py", line 586, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask/cli.py", line 426, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/flask/cli.py", line 426, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/mohnish/Desktop/superset/superset/cli/main.py", line 61, in init
    security_manager.sync_role_definitions()
  File "/Users/mohnish/Desktop/superset/superset/security/manager.py", line 726, in sync_role_definitions
    self.create_missing_perms()
  File "/Users/mohnish/Desktop/superset/superset/security/manager.py", line 668, in create_missing_perms
    merge_pv("datasource_access", datasource.get_perm())
  File "/Users/mohnish/Desktop/superset/superset/connectors/sqla/models.py", line 634, in get_perm
    return f"[{self.database}].[{self.table_name}](id:{self.id})"
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 294, in __get__
    return self.impl.get(instance_state(instance), dict_)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 730, in get
    value = self.callable_(state, passive)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py", line 759, in _load_for_state
    return self._emit_lazyload(
  File "<string>", line 1, in <lambda>
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py", line 847, in _emit_lazyload
    q(session)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/ext/baked.py", line 615, in _load_on_pk_identity
    result = list(bq.for_session(self.session).params(**params))
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/ext/baked.py", line 444, in __iter__
    return q._execute_and_instances(context)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/orm/query.py", line 3560, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1011, in execute
    return meth(self, multiparams, params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 298, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1124, in _execute_clauseelement
    ret = self._execute_context(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1316, in _execute_context
    self._handle_dbapi_exception(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1510, in _handle_dbapi_exception
    util.raise_(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
    raise exception
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "/Users/mohnish/Desktop/superset/venv/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 608, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: dbs.allow_file_upload
[SQL: SELECT dbs.uuid AS dbs_uuid, dbs.created_on AS dbs_created_on, dbs.changed_on AS dbs_changed_on, dbs.id AS dbs_id, dbs.verbose_name AS dbs_verbose_name, dbs.database_name AS dbs_database_name, dbs.sqlalchemy_uri AS dbs_sqlalchemy_uri, dbs.password AS dbs_password, dbs.cache_timeout AS dbs_cache_timeout, dbs.select_as_create_table_as AS dbs_select_as_create_table_as, dbs.expose_in_sqllab AS dbs_expose_in_sqllab, dbs.configuration_method AS dbs_configuration_method, dbs.allow_run_async AS dbs_allow_run_async, dbs.allow_file_upload AS dbs_allow_file_upload, dbs.allow_ctas AS dbs_allow_ctas, dbs.allow_cvas AS dbs_allow_cvas, dbs.allow_dml AS dbs_allow_dml, dbs.force_ctas_schema AS dbs_force_ctas_schema, dbs.allow_multi_schema_metadata_fetch AS dbs_allow_multi_schema_metadata_fetch, dbs.extra AS dbs_extra, dbs.encrypted_extra AS dbs_encrypted_extra, dbs.impersonate_user AS dbs_impersonate_user, dbs.server_cert AS dbs_server_cert, dbs.is_managed_externally AS dbs_is_managed_externally, dbs.external_url AS dbs_external_url, dbs.created_by_fk AS dbs_created_by_fk, dbs.changed_by_fk AS dbs_changed_by_fk
FROM dbs
WHERE dbs.id = ?]
[parameters: (1,)]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
(venv) (base) mohnish@MMMDVMOHNISHSINT superset % FLASK_ENV=development superset run -p 8088 --with-threads --reload --debugger

Environment

browser type and version: chrome latest macos

superset version: cloning directly from master branch of apache superset gihub repo

python version:  3.9

node.js version: 16.13.2


问:
How to transform observations to column and reprensent the number of occurence of these observations
Here is a subset of my dataset. Patients had different types of adverse events (variables) with different types of severity (observations). I would like to create additional variables representing severity ("severe", "severe", "moderate") and have the number of severity types for each patient.

```<code>mydata<-structure(list(record_id = c("2", "4", "5", "9", "10", "11",
    "12", "15", "22", "23"), `Dégré Cytolyse hep ` = structure(c(NA,
    3L, NA, NA, 1L, NA, 2L, NA, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Trble digest` = structure(c(1L,
    NA, NA, NA, NA, 2L, 1L, 1L, NA, 3L), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Erupt cutanées` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Ins renale` = structure(c(NA,
    NA, NA, 1L, NA, NA, NA, NA, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Neuropath` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 1` = structure(c(NA,
    NA, 1L, NA, NA, 1L, NA, 1L, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 2` = structure(c(NA,
    NA, NA, NA, NA, 1L, NA, 1L, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 3` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 4` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 5` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor")), row.names = c(NA, 10L
    ), class = "data.frame")
</code>```

The expected dataset will be:

```<code>   record_id Dégré Cytolyse hep  Dégré Trble digest Dégré Erupt cutanées Dégré Ins renale Dégré Neuropath Dégré Autre 1 Dégré Autre 2 Dégré Autre 3 Dégré Autre 4 Dégré Autre 5 modéré sévère grave
1          2                <NA>             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
2          4              sévère               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0
3          5                <NA>               <NA>                 <NA>             <NA>            <NA>        modéré          <NA>          <NA>          <NA>          <NA>      1      0     0
4          9                <NA>               <NA>                 <NA>           modéré            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
5         10              modéré               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
6         11                <NA>              grave                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      2      0     1
7         12               grave             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     1
8         15                <NA>             modéré                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      3      0     0
9         22              sévère               <NA>                 <NA>             <NA>            <NA>        sévère          <NA>          <NA>          <NA>          <NA>      0      2     0
10        23                <NA>             sévère                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0
</code>```

答:
Here's a tidyverse approach. It assumes all columns that need to be counted starts with "Dégré", then do a rowwise() sum on these columns that matches the severity.

```<code>library(tidyverse)

mydata %>%
  rowwise() %>%
  mutate(sévère = sum(c_across(starts_with("Dégré")) == "sévère", na.rm = T),
         modéré = sum(c_across(starts_with("Dégré")) == "modéré", na.rm = T),
         grave = sum(c_across(starts_with("Dégré")) == "grave", na.rm = T)) %>%
  ungroup()
</code>```

Body:
Here is a subset of my dataset. Patients had different types of adverse events (variables) with different types of severity (observations). I would like to create additional variables representing severity ("severe", "severe", "moderate") and have the number of severity types for each patient.

mydata<-structure(list(record_id = c("2", "4", "5", "9", "10", "11",
    "12", "15", "22", "23"), `Dégré Cytolyse hep ` = structure(c(NA,
    3L, NA, NA, 1L, NA, 2L, NA, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Trble digest` = structure(c(1L,
    NA, NA, NA, NA, 2L, 1L, 1L, NA, 3L), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Erupt cutanées` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Ins renale` = structure(c(NA,
    NA, NA, 1L, NA, NA, NA, NA, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Neuropath` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 1` = structure(c(NA,
    NA, 1L, NA, NA, 1L, NA, 1L, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 2` = structure(c(NA,
    NA, NA, NA, NA, 1L, NA, 1L, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 3` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 4` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 5` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor")), row.names = c(NA, 10L
    ), class = "data.frame")

The expected dataset will be:

   record_id Dégré Cytolyse hep  Dégré Trble digest Dégré Erupt cutanées Dégré Ins renale Dégré Neuropath Dégré Autre 1 Dégré Autre 2 Dégré Autre 3 Dégré Autre 4 Dégré Autre 5 modéré sévère grave
1          2                <NA>             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
2          4              sévère               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0
3          5                <NA>               <NA>                 <NA>             <NA>            <NA>        modéré          <NA>          <NA>          <NA>          <NA>      1      0     0
4          9                <NA>               <NA>                 <NA>           modéré            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
5         10              modéré               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
6         11                <NA>              grave                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      2      0     1
7         12               grave             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     1
8         15                <NA>             modéré                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      3      0     0
9         22              sévère               <NA>                 <NA>             <NA>            <NA>        sévère          <NA>          <NA>          <NA>          <NA>      0      2     0
10        23                <NA>             sévère                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0

Body:
Here's a tidyverse approach. It assumes all columns that need to be counted starts with "Dégré", then do a rowwise() sum on these columns that matches the severity.

library(tidyverse)

mydata %>%
  rowwise() %>%
  mutate(sévère = sum(c_across(starts_with("Dégré")) == "sévère", na.rm = T),
         modéré = sum(c_across(starts_with("Dégré")) == "modéré", na.rm = T),
         grave = sum(c_across(starts_with("Dégré")) == "grave", na.rm = T)) %>%
  ungroup()


问:
Uncaught TypeError: $(...).size is not a function
I'm using a plugin to insert an image from the file manager, however I'm getting an error:

imagebrowser.php?func=addImage&w=160&h=120:77 Uncaught TypeError: $(...).size is not a function
  at addImage (/site/dashboard/load.php?id=i18n_gallery&create:564)
  at submitLink (imagebrowser.php?func=addImage&w=160&h=120:77)
  at HTMLAnchorElement.onclick (imagebrowser.php?func=addImage&w=160&h=120:53)
  addImage @ /site/dashboard/load.php?id=i18n_gallery&create:564
  submitLink @ imagebrowser.php?func=addImage&w=160&h=120:77
  onclick @ imagebrowser.php?func=addImage&w=160&h=120:53
```
<p>The JavaScript code I'm using:</p>
```
<?php echo count($filesSorted); ?> <?php i18n('TOTAL_FILES'); ?> (<?php echo fSize($totalsize); ?>)

<?php i18n('i18n_gallery/ADD_ALL_IMAGES'); ?>

  <?php // foreach ($metadata as &$m) if (!@$m['title']) $m['title'] = basename($m['url']); ?>

```
<p>EditExtra.php</p>
```<?php
  global $id, $url, $parent;
?>

```
<p>This is what I suspected as the main error reason after investigation:</p>
```if ($('#tick').size() > 0) {
```

But replacing it with length didn't resolve the issue.

jQuery version:  jquery-3.2.1.min.js?v=3.2.1

答:
size() function has been deprecated.
add below code:

```<code>$(function() {
    $.fn.size = function() {
        return this.length;
    }
});
</code>```

You don't need to change code.

Body:
I'm using a plugin to insert an image from the file manager, however I'm getting an error:

imagebrowser.php?func=addImage&w=160&h=120:77 Uncaught TypeError: $(...).size is not a function
  at addImage (/site/dashboard/load.php?id=i18n_gallery&create:564)
  at submitLink (imagebrowser.php?func=addImage&w=160&h=120:77)
  at HTMLAnchorElement.onclick (imagebrowser.php?func=addImage&w=160&h=120:53)
  addImage @ /site/dashboard/load.php?id=i18n_gallery&create:564
  submitLink @ imagebrowser.php?func=addImage&w=160&h=120:77
  onclick @ imagebrowser.php?func=addImage&w=160&h=120:53

The JavaScript code I'm using:

<?php echo count($filesSorted); ?> <?php i18n('TOTAL_FILES'); ?> (<?php echo fSize($totalsize); ?>)

<?php i18n('i18n_gallery/ADD_ALL_IMAGES'); ?>

  <?php // foreach ($metadata as &$m) if (!@$m['title']) $m['title'] = basename($m['url']); ?>

EditExtra.php

<?php
  global $id, $url, $parent;
?>

This is what I suspected as the main error reason after investigation:

if ($('#tick').size() > 0) {

But replacing it with length didn't resolve the issue.

jQuery version:  jquery-3.2.1.min.js?v=3.2.1

Body:
size() function has been deprecated.
add below code:

$(function() {
    $.fn.size = function() {
        return this.length;
    }
});

You don't need to change code.


问:
How to return values from C/++ functions correctly?
I have made some app and the method im using is this:

```<code>INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}
</code>```

and I call it like:

```<code>char returned[255];
name(first,second,returned);
printf/cout;
</code>```

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

答: In C++ you would probably return an std::string and throw an exception instead of returning an INT (?).</p>

Body:
I have made some app and the method im using is this:

INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}

and I call it like:

char returned[255];
name(first,second,returned);
printf/cout;

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.


问:
How to create a mongo unique index based on fields and a particular value of a field?
I have a bookings collection where I store data like this:

```<code>{
_id,
fieldId: (a reference to _id from another collection),
status: a string which can be `valid` or `cancelled` or `completed`,
date: eg. `2022-02-09T13:00:00.000+00:00`
}
</code>```

Now, I want to ensure that there can be only one booking for a fieldId at a given date that has status: valid. There can be more or none cancelled or completed ones, but the combination between fieldId, date and the value valid of status must be unique. I know how to create an unique index for fieldId and date:

```<code>BookingSchema.index({ fieldId: 1, date: 1 }, { unique: true });
</code>```

Is it possible to also add the value valid of status field? If not, should i just check on every booking if there already exists a valid booking for that date and field?

答:
Thank you prasad_ for offering the solution, which is Partial indexes.
Here is the solution in mongoose if anybody has the same type of problem:</p>
```<code>BookingSchema.index(
  { fieldId: 1, date: 1 },
  {
    unique: true,
    partialFilterExpression: {
      status: { $eq: `valid` },
    },
  }
);
</code>```

Body:
I have a bookings collection where I store data like this:

{
_id,
fieldId: (a reference to _id from another collection),
status: a string which can be `valid` or `cancelled` or `completed`,
date: eg. `2022-02-09T13:00:00.000+00:00`
}

Now, I want to ensure that there can be only one booking for a fieldId at a given date that has status: valid. There can be more or none cancelled or completed ones, but the combination between fieldId, date and the value valid of status must be unique. I know how to create an unique index for fieldId and date:

BookingSchema.index({ fieldId: 1, date: 1 }, { unique: true });

Is it possible to also add the value valid of status field? If not, should i just check on every booking if there already exists a valid booking for that date and field?

Body:
Thank you prasad_ for offering the solution, which is Partial indexes.
Here is the solution in mongoose if anybody has the same type of problem:

BookingSchema.index(
  { fieldId: 1, date: 1 },
  {
    unique: true,
    partialFilterExpression: {
      status: { $eq: `valid` },
    },
  }
);


问:
Python session SAMESITE=None not being set
I am having issues with chrome and SameSite. I am serving a webpage in a shopify iframe and when setting the session using flask-login, chrome tells me this:

A cookie associated with a cross-site resource at
URL was set without the
SameSite attribute. It been blocked, as Chrome now only delivers
cookies with cross-site requests if they are set with SameSite=None
and Secure.

Secure is set, but I tried to set SameSite in all the possible way, but without effect.

I tried setting

app.config['SESSION_COOKIE_SAMESITE'] = "None"

I tried, changing the behavior of the library, I tired setting the attribute in set_cookie() but nothing seemed to work. The response I see doesn't have the SameSite attribute.

(I have the last versions of flask, flask-login, flask-security and werkzeug)

Can you help me?

Thank you

答:
I had a similar issue where it kept setting SESSION_COOKIE_SAMESITE to Lax. In my case it was caused by flask-talisman, who was overwriting my config.
Specifying

```<code>session_cookie_samesite=app.config["SESSION_COOKIE_SAMESITE"]
</code>```

in the Talisman constructor worked.

Body:
I had a similar issue where it kept setting SESSION_COOKIE_SAMESITE to Lax. In my case it was caused by flask-talisman, who was overwriting my config.
Specifying

session_cookie_samesite=app.config["SESSION_COOKIE_SAMESITE"]

in the Talisman constructor worked.


问:
pull to refresh not working with small amount of cells
I have a feed view controller (implemented with a UICollectionViewController)
When i don't have enough cells to cover the hall screen height the pull to refresh isn't working.
How can i fix this?

Code:

```<code>var refreshControl: UIRefreshControl!

    override func viewDidLoad() {
    super.viewDidLoad()

    self.refreshControl = UIRefreshControl()
    self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
    self.postCollection.addSubview(refreshControl)
}

    func refresh(sender:AnyObject)
{
    getPost()
}
</code>```

EDIT:
by not working i mean that the uicollectionview cant be pulled down and the animation isn't starting.

答:
Programmatically:
self.collectionView.alwaysBounceVertical = true

or From Storyboard:
You should enable these two options

Body:
I have a feed view controller (implemented with a UICollectionViewController)
When i don't have enough cells to cover the hall screen height the pull to refresh isn't working.
How can i fix this?

Code:

var refreshControl: UIRefreshControl!

    override func viewDidLoad() {
    super.viewDidLoad()

    self.refreshControl = UIRefreshControl()
    self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
    self.postCollection.addSubview(refreshControl)
}

    func refresh(sender:AnyObject)
{
    getPost()
}

EDIT:
by not working i mean that the uicollectionview cant be pulled down and the animation isn't starting.


答:
The functional difference is minor: Your fileprivate (which could be private) global is accessible to all types defined within that file, whereas the former is limited to that one particular SomeClass.

The “private global” arguably requires non-local reasoning (i.e., you might have to scan through the whole file to see which types are there and might have access to it). On the other hand, the “private static property” makes the intent more clear at glance. As a result, many would favor this “private static property” approach.

For what it is worth, there is a hybrid approach:

class SomeClass {
    var possibleValues: [String] {
        return Self.someValues
    }
}

private extension SomeClass {
    private static let someValues: [String] = [
        "mrah!",
        "blah",
        "shmah!"
    ]
}
```

It keeps the core type definition very clean, but keeps the namespace for the static constant. Sometimes it is nice to put various subtypes, methods, and statics in extensions within the same file. It can make it easy to grok the code, facilitates code folding, etc.

Title: Swift: is there any functional difference between "private static let" (in a class definition) and "fileprivate let" (no owner)

Body:
The functional difference is minor: Your fileprivate (which could be private) global is accessible to all types defined within that file, whereas the former is limited to that one particular SomeClass.

The “private global” arguably requires non-local reasoning (i.e., you might have to scan through the whole file to see which types are there and might have access to it). On the other hand, the “private static property” makes the intent more clear at glance. As a result, many would favor this “private static property” approach.

For what it is worth, there is a hybrid approach:

class SomeClass {
    var possibleValues: [String] {
        return Self.someValues
    }
}

private extension SomeClass {
    private static let someValues: [String] = [
        "mrah!",
        "blah",
        "shmah!"
    ]
}

It keeps the core type definition very clean, but keeps the namespace for the static constant. Sometimes it is nice to put various subtypes, methods, and statics in extensions within the same file. It can make it easy to grok the code, facilitates code folding, etc.


问:
how to fill the remaining space inside a row?
i have a row that includes a column widget.now as its second child i want to have a container to fill the remaining space.here is my code:

```<code>Row(
        children: [
          _status(),
          Constants.smallHorizontalSpacer,
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _roundedAvatar(),
                _projectType(),
                _name(),
              ],
            ),
          ),
          _divider(),
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Column(
                      children: [
                        _usageTypes(),
                        Constants.smallVerticalSpacer,
                        _details(),
                      ],
                    ),
                    Expanded(
                      child: Container(

                        height: 60,
                        color: Colors.black,
                        child: const Text('fill the remaining space'),
                      ),
                    ),
                  ],
                ),
                Constants.smallVerticalSpacer,
                _description(),
              ],
            ),
          ),
          // _map(context),
        ],
      ),
</code>```

i have already tried expanded and flexble but all my widgets disappeared.any idea will be greate.

this is my result:
https://i.stack.imgur.com/gFTwX.png

答:
You can wrap your  Container with  Expanded widget.

 Row(
  children: [
    ///.....widgets
    Flexible(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                children: [Text("A")],
              ),
              Expanded(
                child: Container(
                  width: 60,
                  height: 60,
                  color: Colors.black,
                  child: const Text('fill the remaining space'),
                ),
```

Body:
i have a row that includes a column widget.now as its second child i want to have a container to fill the remaining space.here is my code:

Row(
        children: [
          _status(),
          Constants.smallHorizontalSpacer,
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _roundedAvatar(),
                _projectType(),
                _name(),
              ],
            ),
          ),
          _divider(),
          Padding(
            padding: const EdgeInsets.only(
              top: Constants.smallSize,
              bottom: Constants.smallSize,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Column(
                      children: [
                        _usageTypes(),
                        Constants.smallVerticalSpacer,
                        _details(),
                      ],
                    ),
                    Expanded(
                      child: Container(

                        height: 60,
                        color: Colors.black,
                        child: const Text('fill the remaining space'),
                      ),
                    ),
                  ],
                ),
                Constants.smallVerticalSpacer,
                _description(),
              ],
            ),
          ),
          // _map(context),
        ],
      ),

i have already tried expanded and flexble but all my widgets disappeared.any idea will be greate.

this is my result:
https://i.stack.imgur.com/gFTwX.png


问:
Making checkpoints in unity
I am trying to make a script where the player is repawned after hitting a checkpoint and dying subsequently. However, currently nothing happens when my player collides with an object marked as collision, so I could do with some help as to get the script working.

```<code>{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawn1;
    [SerializeField] private Transform respawn2;
    [SerializeField] private Transform respawn3;
    private int checkpointCount = 1;

    private void OnTriggerEnter(Collider other)
    {
        Rigidbody RB = player.GetComponent<Rigidbody>();
        if (other.gameObject.tag == "Respawn")
        {
            BoxCollider BC = other.gameObject.GetComponent<BoxCollider>();
            BC.enabled = false;
            checkpointCount++;

        }
        if (other.gameObject.tag == "Collision")
        {
            if (checkpointCount == 2)
            {

                player.transform.position = respawn2.transform.position;

            }
            else if (checkpointCount == 3)
            {
                player.transform.position = respawn3.transform.position;
            }
            else

                player.transform.position = respawn1.transform.position;
        }

</code>```

Thanks.

答: If player actually collides with that object tagged as "collision" (by that I mean that object is not just a trigger). You must handle the collision in OnCollisionEnter(Collision).

Title: Making checkpoints in unity

Body:
I am trying to make a script where the player is repawned after hitting a checkpoint and dying subsequently. However, currently nothing happens when my player collides with an object marked as collision, so I could do with some help as to get the script working.

{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawn1;
    [SerializeField] private Transform respawn2;
    [SerializeField] private Transform respawn3;
    private int checkpointCount = 1;

    private void OnTriggerEnter(Collider other)
    {
        Rigidbody RB = player.GetComponent<Rigidbody>();
        if (other.gameObject.tag == "Respawn")
        {
            BoxCollider BC = other.gameObject.GetComponent<BoxCollider>();
            BC.enabled = false;
            checkpointCount++;

        }
        if (other.gameObject.tag == "Collision")
        {
            if (checkpointCount == 2)
            {

                player.transform.position = respawn2.transform.position;

            }
            else if (checkpointCount == 3)
            {
                player.transform.position = respawn3.transform.position;
            }
            else

                player.transform.position = respawn1.transform.position;
        }

Thanks.


问:
How do i allow 'Access-Control-Allow-Origin' in Node.JS Http Server?
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem.
Here is my server:</p>
```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('@socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

app.post('/', (request, res) => {
  console.log("********************");
  console.log(" >POST RECEBIDO!!");
 console.log(res);

postData = request.body;
io.emit('message',postData);
 console.log(postData);

});

http.listen(3000, function(){

  console.log('listening on *:3000');

});
</code>```

答: Express has a middleware for CORS. Link here</p>

Body:
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem.
Here is my server:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('@socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

app.post('/', (request, res) => {
  console.log("********************");
  console.log(" >POST RECEBIDO!!");
 console.log(res);

postData = request.body;
io.emit('message',postData);
 console.log(postData);

});

http.listen(3000, function(){

  console.log('listening on *:3000');

});


问:
Android Studio Project says project is already on GitHub despite the fact I deleted repository.
I deleted the project from GitHub and want to re-share (create new repository) it via Android Studio but it still thinks I have it up on GitHub. Is there a way to reset this? </p>

答: On the Top Menu, Click Git->Manage Remotes and click the delete button.</p>


问:
Cannot import name 'Post' from 'instascrape'
I'm trying to set up instascraper from this article: https://github.com/chris-greening/instascrape/blob/master/tutorial/tutorial/Part%201%20-%20Intro%20to%20the%20API.ipynb

But already when running just this:

```<code>from instascrape import Post, Profile, Hashtag
</code>```

I get the following error:

ImportError: cannot import name 'Post' from 'instascrape' (unknown
location)

How can I fix this?

I've installed the library using

```<code>pip3 install insta-scrape
</code>```

答:
Make sure to install insta-scrape, and not a package with a similar name.

```<code>pip3 install insta-scrape
</code>```

Update

Additionally, make sure to uninstall any other packages that may use the same module name, i.e., "instascrape". Most importantly, please make sure you do not name your python file, or any other file in the directory your working from "instascrape.py". That might be another reason causing that error.

Body:
I'm trying to set up instascraper from this article: https://github.com/chris-greening/instascrape/blob/master/tutorial/tutorial/Part%201%20-%20Intro%20to%20the%20API.ipynb

But already when running just this:

from instascrape import Post, Profile, Hashtag

I get the following error:

ImportError: cannot import name 'Post' from 'instascrape' (unknown
location)

How can I fix this?

I've installed the library using

pip3 install insta-scrape

Body:
Make sure to install insta-scrape, and not a package with a similar name.

pip3 install insta-scrape

Update

Additionally, make sure to uninstall any other packages that may use the same module name, i.e., "instascrape". Most importantly, please make sure you do not name your python file, or any other file in the directory your working from "instascrape.py". That might be another reason causing that error.


问:
Re-authentication using Identity Server 4
We have 2 MVC applications as clients and an Identity Server 4.

We have setup cookie middleware and openIdconnect using owin.

Client 1 has a cookie lifetime of 40 minutes.

Client 2 has a cookie lifetime of 10 minutes (maybe it's more strict for security reasons)

We send max-age = session_length in the autzorization endpoint but in some cases we want to send the user immediately for re-authentication (for security reasons).

So, we decided to send max-age=0 in these cases.

So our problem is if we need to send the user for re-authentication before client cookie is expired, the user will be redirected to Identity Server with max-age=0 but what happening if a user hits again the client login page, the user will be redirected with max-age=session_length and the user will get tokens.

How can we protect the client?
The user is not authenticated so we don't know which user it is. How can we store information about the users previous activity? For example, where can we store the previous max-age value? So if the user tries to access the login page again we will know the correct max-age value.

答:
When the max-age parameter is sent during an OpenID Connect authorization redirect, it is issued in the ID token as an auth_time claim. There will be a separate one of these for each of your clients.

So given an incoming request, inspect cookies, get the ID token, and see if the auth_time is exceeded. If so (or if there is no valid application cookie) send these parameters as Anders says:

```<code>prompt=login, max_age=sessiontime
</code>```

Otherwise send just this:

```<code>max_age=sessiontime
</code>```

This mechanism is often used when you cannot get the desired logout usability or reliability. Just remove tokens from the app on logout and avoid a logout redirect to the Authorization Server.

Body:
When the max-age parameter is sent during an OpenID Connect authorization redirect, it is issued in the ID token as an auth_time claim. There will be a separate one of these for each of your clients.

So given an incoming request, inspect cookies, get the ID token, and see if the auth_time is exceeded. If so (or if there is no valid application cookie) send these parameters as Anders says:

prompt=login, max_age=sessiontime

Otherwise send just this:

max_age=sessiontime

This mechanism is often used when you cannot get the desired logout usability or reliability. Just remove tokens from the app on logout and avoid a logout redirect to the Authorization Server.


问:
Return columns that are binary in ndarray?
So for the same thing

```<code>data.loc[:,data.isin([0,1]).all()]
</code>```

does for a panda dataframe. I want to know how to do this when it is a ndarray?

1     40      0        0          0                  0        0          0

2     58      0        0          1                  0        0          0

3     41      0        1          1                  0        0          1

4     45      0        0          1                  1        0          1

5     60      0        1          0                  1        0          1

```<code>def checkBinary(data):
    getBinaryCol = data.loc[:,data.isin([0,1]).all()]
    if i in getBinaryCol:
        return True
    else:
        return False
</code>```

This is the function for pandas dataframe
how do i change getBinaryCol if passing data.values(ndarray) instead of only data?

答:
The code below checks if each cell contains either 0's or 1's, allows both by using np.logical_or and checks if the condition is met for the whole column by using np.all.

mat = np.array(
    [[ 3, 0, 1, 1, 0],
     [ 5, 1, 4, 0, 0],
     [ 8, 0, 0, 0, 0]]
)

def is_col_bin(mat, i):
    return np.all(np.logical_or(mat[...,i] == 0, mat[...,i] == 1))

print([is_col_bin(mat, i) for i in range(mat.shape[-1])])
# [False, True, False, True, True]
```

Body:
So for the same thing

data.loc[:,data.isin([0,1]).all()]

does for a panda dataframe. I want to know how to do this when it is a ndarray?

1     40      0        0          0                  0        0          0

2     58      0        0          1                  0        0          0

3     41      0        1          1                  0        0          1

4     45      0        0          1                  1        0          1

5     60      0        1          0                  1        0          1

def checkBinary(data):
    getBinaryCol = data.loc[:,data.isin([0,1]).all()]
    if i in getBinaryCol:
        return True
    else:
        return False

This is the function for pandas dataframe
how do i change getBinaryCol if passing data.values(ndarray) instead of only data?


问:
My message in assembly when compiled does not display
I'm on Windows 11 in 64 bits and I wrote this code in assembly a64 but after being compiled and linked (with nasm and then ld) it just wait 3sec average and just stop :

```<code>bits 64

section .data
    message db 'Hello World !', 10

section .text
    global _start
    _start:
        mov rax, 1
        mov rdi, 1
        mov rsi, message
        mov rdx, 13+1
        syscall

        mov rax, 60
        mov rdi, 0
        syscall
</code>```

nasm command typed in powershell : nasm -f win64 file.asm -o file.o

then ld command : ld file.o -o file.exe

When I start this file in powershell it just wait 3 sec and stop. Same for cmd.

It's a test program for my compiler to see if it works and I don't know if I didn't write correctly the code or if those compiler or linker don't work on Win 11.

Note : also my processsor is an Intel

答:
Windoze programs [generally] do not use syscall/sysenter;
you usually use the WinAPI.

Apart from adapting the “Hello World” referred to in David Wohlferd’s comment, you can meanwhile use the WSL, Windoh’s Subsystem for Linux, so you can still program with the familiar syscall interface.
Obviously this requires an ‑felf64 executable to begin with, but (without having tried that out) something like wsl ‑‑exec myProgram should do the trick then.

Some style comment:
Filling rdx with 13+1 is prone to error.
Use an equ constant instead.

Body:
I'm on Windows 11 in 64 bits and I wrote this code in assembly a64 but after being compiled and linked (with nasm and then ld) it just wait 3sec average and just stop :

bits 64

section .data
    message db 'Hello World !', 10

section .text
    global _start
    _start:
        mov rax, 1
        mov rdi, 1
        mov rsi, message
        mov rdx, 13+1
        syscall

        mov rax, 60
        mov rdi, 0
        syscall

nasm command typed in powershell : nasm -f win64 file.asm -o file.o

then ld command : ld file.o -o file.exe

When I start this file in powershell it just wait 3 sec and stop. Same for cmd.

It's a test program for my compiler to see if it works and I don't know if I didn't write correctly the code or if those compiler or linker don't work on Win 11.

Note : also my processsor is an Intel