问:
Include One Yaml File Inside Another
I want to have a base config file which is used by other config files to share common config.

E.g if I have one file base.yml with

```<code>foo: 1

bar:
  - 2
  - 3
</code>```

And then a second file some_file.yml with

```<code>foo: 2

baz: "baz"
</code>```

What I'd want to end up with a merged config file with

```<code>foo: 2

bar:
  - 2
  - 3

baz: "baz"
</code>```

It's easy enough to write a custom loader that handles an !include tag.

```<code>class ConfigLoader(yaml.SafeLoader):

    def __init__(self, stream):
        super().__init__(stream)
        self._base = Path(stream.name).parent

    def include(self, node):
        file_name = self.construct_scalar(node)
        file_path = self._base.joinpath(file_name)

        with file_path.open("rt") as fh:
            return yaml.load(fh, IncludeLoader)
</code>```

Then I can parse an !include tag. So if my file is

```<code>inherit:
   !include base.yml

foo: 2

baz: "baz"
</code>```

But now the base config is a mapping. I.e. if I load the the file I'll end up with

config = {'a': [42], 'c': [3.6, [1, 2, 3]], 'include': [{'a': 1, 'b': [1.43, 543.55]}]}
```
<p>But if I don't make the tag part of a mapping, e.g.</p>
```!include base.yml

foo: 2

baz: "baz"
```
<p>I get an error. <code>yaml.scanner.ScannerError: mapping values are not allowed here</code>.</p>
<p>But I know that the yaml parser can parse tags without needing a mapping. Because I can do things like</p>
```!!python/object:foo.Bar
x: 1.0
y: 3.14
```

So how do I write a loader and/or structure my YAML file so that I can include another file in my configuration?

答:
I recommend these 2 steps:

write or plug-in a custom load-constructor for including other files

structure the YAML for merging other keys (within the same file)
or including other files

Similar to what Anthon, author and maintainer of ruamel.yaml answered ... but with pyyaml.

How to merge in YAML keys (from within same file)

See the YAML merge syntax <<: is for merging in keys:

```<code>---
- &OTHER { foo: 1, bar: [2, 3] }

# merge it in from above
<< : OTHER

# the base
foo: 1

bar:
  - 2
  - 3
</code>```

How to include YAML files

YAML markup syntax has no include-directive or similar.
But each YAML-parser implementation can offer this feature.

For example, see another answer of Josh which has does so:

PyYAML allows you to attach custom constructors (such as !include) to the YAML loader.

This constructor can be plugged-in by pyyaml-include does:

```<code>import yaml
from yamlinclude import YamlIncludeConstructor

YamlIncludeConstructor.add_to_loader_class(loader_class=yaml.FullLoader, base_dir='/your/conf/dir')  # or specify another dir relatively or absolutely
# default is: include YAML files from current working directory

with open('base.yaml') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

print(data)
</code>```

To include (not merging in) a second file some_file.yaml (located in same directory) given as:

```<code>foo: 1

bar:
  - 2
  - 3
</code>```

within the base.yaml add:

```<code>!include some_file.yaml    # includes the file on top-level (relative path!)

foo: 1

bar:
  - 2
  - 3
</code>```

See also:

Are there specifiers to merge keys in yaml?

How can I include a YAML file inside another?

merge two yaml files in python

Recommended filename extension

From Wikipedia, YAML:

The official recommended filename extension for YAML files has been .yaml since 2006.12

(sourced from the official YAML-FAQ: "YAML Ain't Markup Language". September 24, 2006. Archived from the original on 2006-09-24.)

Title: Include One Yaml File Inside Another

Body:
I want to have a base config file which is used by other config files to share common config.

E.g if I have one file base.yml with

foo: 1

bar:
  - 2
  - 3

And then a second file some_file.yml with

foo: 2

baz: "baz"

What I'd want to end up with a merged config file with

foo: 2

bar:
  - 2
  - 3

baz: "baz"

It's easy enough to write a custom loader that handles an !include tag.

class ConfigLoader(yaml.SafeLoader):

    def __init__(self, stream):
        super().__init__(stream)
        self._base = Path(stream.name).parent

    def include(self, node):
        file_name = self.construct_scalar(node)
        file_path = self._base.joinpath(file_name)

        with file_path.open("rt") as fh:
            return yaml.load(fh, IncludeLoader)

Then I can parse an !include tag. So if my file is

inherit:
   !include base.yml

foo: 2

baz: "baz"

But now the base config is a mapping. I.e. if I load the the file I'll end up with

config = {'a': [42], 'c': [3.6, [1, 2, 3]], 'include': [{'a': 1, 'b': [1.43, 543.55]}]}

But if I don't make the tag part of a mapping, e.g.

!include base.yml

foo: 2

baz: "baz"

I get an error. yaml.scanner.ScannerError: mapping values are not allowed here.

But I know that the yaml parser can parse tags without needing a mapping. Because I can do things like

!!python/object:foo.Bar
x: 1.0
y: 3.14

So how do I write a loader and/or structure my YAML file so that I can include another file in my configuration?

Body:
I recommend these 2 steps:

write or plug-in a custom load-constructor for including other files

structure the YAML for merging other keys (within the same file)
or including other files

Similar to what Anthon, author and maintainer of ruamel.yaml answered ... but with pyyaml.

How to merge in YAML keys (from within same file)

See the YAML merge syntax <<: is for merging in keys:

---
- &OTHER { foo: 1, bar: [2, 3] }

# merge it in from above
<< : OTHER

# the base
foo: 1

bar:
  - 2
  - 3

How to include YAML files

YAML markup syntax has no include-directive or similar.
But each YAML-parser implementation can offer this feature.

For example, see another answer of Josh which has does so:

PyYAML allows you to attach custom constructors (such as !include) to the YAML loader.

This constructor can be plugged-in by pyyaml-include does:

import yaml
from yamlinclude import YamlIncludeConstructor

YamlIncludeConstructor.add_to_loader_class(loader_class=yaml.FullLoader, base_dir='/your/conf/dir')  # or specify another dir relatively or absolutely
# default is: include YAML files from current working directory

with open('base.yaml') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

print(data)

To include (not merging in) a second file some_file.yaml (located in same directory) given as:

foo: 1

bar:
  - 2
  - 3

within the base.yaml add:

!include some_file.yaml    # includes the file on top-level (relative path!)

foo: 1

bar:
  - 2
  - 3

See also:

Are there specifiers to merge keys in yaml?

How can I include a YAML file inside another?

merge two yaml files in python

Recommended filename extension

From Wikipedia, YAML:

The official recommended filename extension for YAML files has been .yaml since 2006.12

(sourced from the official YAML-FAQ: "YAML Ain't Markup Language". September 24, 2006. Archived from the original on 2006-09-24.)


来源: stackexchange

问:
Return array in stored function
I am trying to use the result of a stored function in a WHERE statement in MySQL (5.x), but it fails because in the function I am selecting values from a table into an INT variable and then returning them/it, which obviously doesn't work if the SELECT returns more than 1 row. I've tried returning a TABLE (as I understood TABLE means array in MySQL) but that didn't work either.

Is there any way that I could do something like:

```<code>SELECT ID FROM myTable WHERE ID IN my_function(params);
</code>```

Thank you.

答:
This cannot be done...

First, you cannot use a stored function to return multiple results - you would need to use a stored procedure.

The MySQL docs state:

Statements that return a result set can be used within a stored procedure but not within a stored function.

Second, you cannot use a stored procedure in a query - see this SO question.

Have you considered using 'HAVING ...' at the end of your query?

ContentLicense: CC BY-SA 3.0

Title: Return array in stored function

Body:
I am trying to use the result of a stored function in a WHERE statement in MySQL (5.x), but it fails because in the function I am selecting values from a table into an INT variable and then returning them/it, which obviously doesn't work if the SELECT returns more than 1 row. I've tried returning a TABLE (as I understood TABLE means array in MySQL) but that didn't work either.

Is there any way that I could do something like:

SELECT ID FROM myTable WHERE ID IN my_function(params);

Thank you.


问:
How to write a sql to generate same id column when any of three columns is the same?
We have a table T1 like below:

```<code>col1 col2 col3
 1    1    1
 1    2    1
 1    2    3
 4    4    4
</code>```

We want to generate one more column, and then new table T2 is like below:

```<code>col1 col2 col3  id
 1    1    1    1
 1    2    1    1
 1    2    3    1
 4    4    4    2
</code>```

The first three rows has at lease one same value in col1/col2/col3, so they have the same id 1. For example, row1 and row3 have same value 1 in col1, so they have the same id. The forth row don't have any same value with the first three row in col1/col2/col3, so it have a new id 2.

To be more percise, when T1 have one more column (4,2,4) like below, all rows have same id 1.

```<code>col1 col2 col3
 1    1    1
 1    2    1
 1    2    3
 4    4    4
 4    2    4
</code>```

My Idea:
1、We can join table T1 with itself to eliminate different rows

```<code>select * from T1 t11 join T1 t12 on t11.col1 = t12.col1 or t11.col2 = t12.col2 or t11.col3 = t12.col3.
</code>```
```<code>t11.col1 t11.col2 t11.col3 t12.col1 t12.col2 t12.col3
   1         1       1        1         1       1
   1         1       1        1         2       1
   1         1       1        1         2       3

   1         2       1        1         1       1
   1         2       1        1         2       1
   1         2       1        1         2       3

   1         2       3        1         1       1
   1         2       3        1         2       1
   1         2       3        1         2       3

   4         4       4        4         4       4
</code>```

2、Maybe we can distinct or group by the result above, but I don't kown how to do?

Can somebody help me out with this?

答:
First of all, your table is lacking a fourth column which provides the suggested ordering of the records.  For the purpose of this answer, I will assume that there exists an id column as follows:

```<code>id | col1 | col2 | col3
1  | 1    | 1    | 1
2  | 1    | 2    | 1
3  | 1    | 2    | 3
4  | 4    | 4    | 4
</code>```

We can use analytic functions here:

WITH cte AS (
    SELECT *, CASE WHEN col1 = col2 AND col2 = col3 AND col1 = col3
                   THEN 1 ELSE 0 END AS val
    FROM yourTable
)

SELECT col1, col2, col3, SUM(val) OVER (ORDER BY id) AS new_col
FROM cte
ORDER BY id;
```

Demo

ContentLicense: CC BY-SA 4.0

Body:
We have a table T1 like below:

col1 col2 col3
 1    1    1
 1    2    1
 1    2    3
 4    4    4

We want to generate one more column, and then new table T2 is like below:

col1 col2 col3  id
 1    1    1    1
 1    2    1    1
 1    2    3    1
 4    4    4    2

The first three rows has at lease one same value in col1/col2/col3, so they have the same id 1. For example, row1 and row3 have same value 1 in col1, so they have the same id. The forth row don't have any same value with the first three row in col1/col2/col3, so it have a new id 2.

To be more percise, when T1 have one more column (4,2,4) like below, all rows have same id 1.

col1 col2 col3
 1    1    1
 1    2    1
 1    2    3
 4    4    4
 4    2    4

My Idea:
1、We can join table T1 with itself to eliminate different rows

select * from T1 t11 join T1 t12 on t11.col1 = t12.col1 or t11.col2 = t12.col2 or t11.col3 = t12.col3.

t11.col1 t11.col2 t11.col3 t12.col1 t12.col2 t12.col3
   1         1       1        1         1       1
   1         1       1        1         2       1
   1         1       1        1         2       3

   1         2       1        1         1       1
   1         2       1        1         2       1
   1         2       1        1         2       3

   1         2       3        1         1       1
   1         2       3        1         2       1
   1         2       3        1         2       3

   4         4       4        4         4       4

2、Maybe we can distinct or group by the result above, but I don't kown how to do?

Can somebody help me out with this?

Body:
First of all, your table is lacking a fourth column which provides the suggested ordering of the records.  For the purpose of this answer, I will assume that there exists an id column as follows:

id | col1 | col2 | col3
1  | 1    | 1    | 1
2  | 1    | 2    | 1
3  | 1    | 2    | 3
4  | 4    | 4    | 4

We can use analytic functions here:

WITH cte AS (
    SELECT *, CASE WHEN col1 = col2 AND col2 = col3 AND col1 = col3
                   THEN 1 ELSE 0 END AS val
    FROM yourTable
)

SELECT col1, col2, col3, SUM(val) OVER (ORDER BY id) AS new_col
FROM cte
ORDER BY id;

Demo


问:
Rmd: Make the figure larger when clicked on it
I have a Rmarkdown file where I include figures with

knitr::include_graphics

The figures show up in the knitted document nicely. However, when I'm reading the knitted document, if I want to focus on one figure, I use the zoom option of the browser, which is not ideal.

Is it possible to add open the figure in a larger window when clicked on it?

PS: I use gitbook and/or bookdown::html for the output format of my Rmd files.

答:
You can try out the themes from rmdformats package which implement this feature. They call it lightbox. To enable,you just need to set lightbox to true in the RMD yaml.

Example:

```<code>---
title: "My document"
output:
  rmdformats::downcute:
    lightbox: true
---
</code>```

Body:
You can try out the themes from rmdformats package which implement this feature. They call it lightbox. To enable,you just need to set lightbox to true in the RMD yaml.

Example:

---
title: "My document"
output:
  rmdformats::downcute:
    lightbox: true
---


问:
How to make a Strapi entry with relation included through REST Api Post
I have two collection types that are connected with a relation :

Where Student has many Posts
and When I make a post trought the admin panel I don't have any problems.
I even figured out how to assign media with a POST request
which is done by giving the media id.
But I still can't figure out how to link the relation on post creation with the request
I tried giving the id of the user but it comes out empty also tried UID empty again

And the JSON request :

答: In request you have Student with a capital S, but in strapi admin it is student with lowercase s. You should use the same naming convention through all the properties to avoid such a problems.


问:
How to resolve eslint(vue/html-closing-bracket-newline) conflict
On save, VSCode is fixing eslint is fixing all the rules. How to fix the below conflict?

Expected Indentation

Unexpected Indentation

VScode Plugins in use:

```<code> [
    "formulahendry.auto-close-tag",
    "msjsdiag.debugger-for-chrome",
    "hookyqr.beautify",
    "mikestead.dotenv",
    "dbaeumer.vscode-eslint",
    "donjayamanne.githistory",
    "eamodio.gitlens",
    "sidthesloth.html5-boilerplate",
    "ecmel.vscode-html-css",
    "abusaidm.html-snippets",
    "wix.vscode-import-cost",
    "lonefy.vscode-js-css-html-formatter",
    "eg2.vscode-npm-script",
    "christian-kohler.npm-intellisense",
    "sibiraj-s.vscode-scss-formatter",
    "octref.vetur",
    "blanu.vscode-styled-jsx",
    "jcbuisson.vue",
    "hollowtree.vue-snippets",
    "wscats.vue",
    "sdras.vue-vscode-snippets",
    "dariofuzinato.vue-peek",
]
</code>```

Error

Here is the config in use:

```<code> 'vue/html-closing-bracket-newline': [
  'error',
  {
    singleline: 'never',
    multiline: 'never'
  }
],
'indent': ['error', 2],
'vue/html-indent': ['error', 2],
'vue/script-indent': ['error', 2],
'vue/multiline-html-element-content-newline': 0
</code>```

VSCode settings

```<code> {
    "editor.formatOnSave": true,
    "[javascript]": {
        "editor.formatOnSave": true
    },
    "eslint.alwaysShowStatus": true,
    "files.autoSave": "onFocusChange",
    "emmet.includeLanguages": {
        "javascript": "javascriptreact",
        "vue-html": "html",
        "plaintext": "jade",
        "edge": "html"
    },
    "emmet.syntaxProfiles": {
        "javascript": "jsx"
    },
    "emmet.triggerExpansionOnTab": true,
    "emmet.showSuggestionsAsSnippets": true,
    "files.associations": {
        "*.js": "javascriptreact"
    },
    "editor.fontSize": 14,
    "git.enableSmartCommit": true,
    "git.confirmSync": false,
    "search.exclude": {
        "**/.git": true,
        "**/node_modules": true,
        "**/bower_components": true,
        "**/tmp": true,
        "**/.bin": true,
        "**/.next": true,
        "**/__snapshots__/**": true,
        "**/coverage/**": true,
        "**/report/**": true
    },
    "javascript.updateImportsOnFileMove.enabled": "always",
    "explorer.confirmDragAndDrop": false,
    "explorer.confirmDelete": false,
    "diffEditor.ignoreTrimWhitespace": false,
    "workbench.editor.enablePreviewFromQuickOpen": false,
    "files.exclude": {
        ".next": true,
        "*.log": true,
        "**/__pycache__": true,
        "**/node_modules": true,
        "**/o": true,
        "dist": true,
        "geckodriver.log": true,
        "package-lock.json": true,
        "yarn.lock": true
    },
    "window.zoomLevel": 1,
    "editor.find.globalFindClipboard": true,
    "editor.fontLigatures": true,
    "editor.formatOnType": true,
    "team.showWelcomeMessage": false,
    "git.autofetch": true,
    "workbench.startupEditor": "newUntitledFile",
    "editor.codeActionsOnSave": {
        // For ESLint
        "source.fixAll.eslint": true,
        // For TSLint
        "source.fixAll.tslint": true,
        // For Stylelint
        "source.fixAll.stylelint": true
    },
    "launch": {},
    "workbench.colorCustomizations": {},
    "javascript.validate.enable": true,
    "javascript.suggestionActions.enabled": false,
    "editor.insertSpaces": false,
    "editor.detectIndentation": false,
    "prettier.disableLanguages": [],
    "vetur.format.defaultFormatter.js": "vscode-typescript",
    "vetur.format.defaultFormatter.html": "js-beautify-html",
    "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
    "eslint.validate": [
        "vue",
        "html",
        "javascript",
        "typescript",
        "javascriptreact",
        "typescriptreact"
    ]
}
</code>```

Multiline formatting should be retained, but the closing bracket should
be in the same line itself as expected from the image.

There should be no conflict between eslint and vscode settings

Require necessary vscode settings.
and eslint settings for vue setup Also, the sass files should not get affected with alignments every time on pre-commit checks.

It will be good if tab alignments are considered instead of 2 spaces for vue, js and sass files

答:
you can config .prettierrc.js</p>
```<code>bracketSameLine: true
</code>```

Body:
On save, VSCode is fixing eslint is fixing all the rules. How to fix the below conflict?

Expected Indentation

Unexpected Indentation

VScode Plugins in use:

 [
    "formulahendry.auto-close-tag",
    "msjsdiag.debugger-for-chrome",
    "hookyqr.beautify",
    "mikestead.dotenv",
    "dbaeumer.vscode-eslint",
    "donjayamanne.githistory",
    "eamodio.gitlens",
    "sidthesloth.html5-boilerplate",
    "ecmel.vscode-html-css",
    "abusaidm.html-snippets",
    "wix.vscode-import-cost",
    "lonefy.vscode-js-css-html-formatter",
    "eg2.vscode-npm-script",
    "christian-kohler.npm-intellisense",
    "sibiraj-s.vscode-scss-formatter",
    "octref.vetur",
    "blanu.vscode-styled-jsx",
    "jcbuisson.vue",
    "hollowtree.vue-snippets",
    "wscats.vue",
    "sdras.vue-vscode-snippets",
    "dariofuzinato.vue-peek",
]

Error

Here is the config in use:

 'vue/html-closing-bracket-newline': [
  'error',
  {
    singleline: 'never',
    multiline: 'never'
  }
],
'indent': ['error', 2],
'vue/html-indent': ['error', 2],
'vue/script-indent': ['error', 2],
'vue/multiline-html-element-content-newline': 0

VSCode settings

 {
    "editor.formatOnSave": true,
    "[javascript]": {
        "editor.formatOnSave": true
    },
    "eslint.alwaysShowStatus": true,
    "files.autoSave": "onFocusChange",
    "emmet.includeLanguages": {
        "javascript": "javascriptreact",
        "vue-html": "html",
        "plaintext": "jade",
        "edge": "html"
    },
    "emmet.syntaxProfiles": {
        "javascript": "jsx"
    },
    "emmet.triggerExpansionOnTab": true,
    "emmet.showSuggestionsAsSnippets": true,
    "files.associations": {
        "*.js": "javascriptreact"
    },
    "editor.fontSize": 14,
    "git.enableSmartCommit": true,
    "git.confirmSync": false,
    "search.exclude": {
        "**/.git": true,
        "**/node_modules": true,
        "**/bower_components": true,
        "**/tmp": true,
        "**/.bin": true,
        "**/.next": true,
        "**/__snapshots__/**": true,
        "**/coverage/**": true,
        "**/report/**": true
    },
    "javascript.updateImportsOnFileMove.enabled": "always",
    "explorer.confirmDragAndDrop": false,
    "explorer.confirmDelete": false,
    "diffEditor.ignoreTrimWhitespace": false,
    "workbench.editor.enablePreviewFromQuickOpen": false,
    "files.exclude": {
        ".next": true,
        "*.log": true,
        "**/__pycache__": true,
        "**/node_modules": true,
        "**/o": true,
        "dist": true,
        "geckodriver.log": true,
        "package-lock.json": true,
        "yarn.lock": true
    },
    "window.zoomLevel": 1,
    "editor.find.globalFindClipboard": true,
    "editor.fontLigatures": true,
    "editor.formatOnType": true,
    "team.showWelcomeMessage": false,
    "git.autofetch": true,
    "workbench.startupEditor": "newUntitledFile",
    "editor.codeActionsOnSave": {
        // For ESLint
        "source.fixAll.eslint": true,
        // For TSLint
        "source.fixAll.tslint": true,
        // For Stylelint
        "source.fixAll.stylelint": true
    },
    "launch": {},
    "workbench.colorCustomizations": {},
    "javascript.validate.enable": true,
    "javascript.suggestionActions.enabled": false,
    "editor.insertSpaces": false,
    "editor.detectIndentation": false,
    "prettier.disableLanguages": [],
    "vetur.format.defaultFormatter.js": "vscode-typescript",
    "vetur.format.defaultFormatter.html": "js-beautify-html",
    "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
    "eslint.validate": [
        "vue",
        "html",
        "javascript",
        "typescript",
        "javascriptreact",
        "typescriptreact"
    ]
}

Multiline formatting should be retained, but the closing bracket should
be in the same line itself as expected from the image.

There should be no conflict between eslint and vscode settings

Require necessary vscode settings.
and eslint settings for vue setup Also, the sass files should not get affected with alignments every time on pre-commit checks.

It will be good if tab alignments are considered instead of 2 spaces for vue, js and sass files

Body:
you can config .prettierrc.js

bracketSameLine: true


问:
Problem with "this" in JS
Consider the following code:

```<code>    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);
</code>```

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

答:
```<code>var table = function (tableId) {

        this.tableId = tableId;
        this.table = $("#" + tableId);

        this.removeStripes= function() {
            this.table.find(".alt").removeClass("alt");
        };

        this.addStripes= function () {
            this.table.find("tbody tr:even").addClass("alt");
        };

        this.resetStripes= function() {
            this.removeStripes();
            this.addStripes();
        };

        this.sort= function (options) {
            this.table.tablesorter(options);
            this.table.bind("sortEnd", this.resetStripes);
        };
}
</code>```

The "this" keyword usage in Javascript is rather different than in other languages. The version above should work (I tested it with jsc, rather than properly in a browser with jQuery).
Now the function is a proper constructor, making the interpreter to set "this" to the object to be created.

Title: Problem with "this" in JS

Body:
Consider the following code:

    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

Body:
var table = function (tableId) {

        this.tableId = tableId;
        this.table = $("#" + tableId);

        this.removeStripes= function() {
            this.table.find(".alt").removeClass("alt");
        };

        this.addStripes= function () {
            this.table.find("tbody tr:even").addClass("alt");
        };

        this.resetStripes= function() {
            this.removeStripes();
            this.addStripes();
        };

        this.sort= function (options) {
            this.table.tablesorter(options);
            this.table.bind("sortEnd", this.resetStripes);
        };
}

The "this" keyword usage in Javascript is rather different than in other languages. The version above should work (I tested it with jsc, rather than properly in a browser with jQuery).
Now the function is a proper constructor, making the interpreter to set "this" to the object to be created.


问:
Convert part of the values in rows in a data frame
I have a data frame which looks like this:

df

```<code>colA colB
0     0
1     1
0     1
0     1
0     1
1     0
0     0
1     1
0     1
</code>```

I would like to convert a certain proportion of the 0 in colA to NA and a certain proportion of 1 in colB to NA

if I do this:

```<code>df["colA"][df["colA"] == 0] <- NA
</code>```

all the 0 in columns A will be converted to NA, however I just want half of them to be converted

Similarly, for colB I want only 1/3 of the 1 to be converted:

```<code>df["colB"][df["colB"] == 1] <- NA
</code>```

Expected output:

```<code>   colA colB
    0     0
    1     1
    NA    1
    0     1
    NA    1
    1     0
    0     0
    1     NA
    NA    NA
</code>```

答:
You can use prodNA from the missForest package

set.seed(1)
library(missForest)
df[df$colA == 0, "colA"] <- prodNA(df[df$colA == 0, "colA", drop=F], noNA = 0.5)
df[df$colB == 1, "colB"] <- prodNA(df[df$colB == 1, "colB", drop=F], noNA = 1/3)
df

  colA colB
1   NA    0
2    1   NA
3    0   NA
4   NA    1
5   NA    1
6    1    0
7    0    0
8    1    1
9    0    1
```

Body:
I have a data frame which looks like this:

df

colA colB
0     0
1     1
0     1
0     1
0     1
1     0
0     0
1     1
0     1

I would like to convert a certain proportion of the 0 in colA to NA and a certain proportion of 1 in colB to NA

if I do this:

df["colA"][df["colA"] == 0] <- NA

all the 0 in columns A will be converted to NA, however I just want half of them to be converted

Similarly, for colB I want only 1/3 of the 1 to be converted:

df["colB"][df["colB"] == 1] <- NA

Expected output:

   colA colB
    0     0
    1     1
    NA    1
    0     1
    NA    1
    1     0
    0     0
    1     NA
    NA    NA


问:
Trying to move completed tasks from one list to another
Here we have a tab with incompled tasks and the list is supposed to be attached to the first tab(all-taks). After the task is finished it is supposed to get deleted from first list and move to second one with completed tasks. And after you switch to second tab, all the completed ones should be there. I can't figure out the way to do it.
I hope I could get some help or some detailed explanation, 'cause I have been stuck on this for some time.

Here is an image for more clarification:
[1]: https://i.stack.imgur.com/Dy0KL.png

HTML code:

```<code><body>
    <div class="container">
        <header>
            <h1>To-Do List</h1>
            <h4>Describe your list...</h4>
        </header>

        <form action="" class="todo-form">
            <div class="form-wrapper">
                <!-- action is where files will be sent after submitting -->
                <input class="todo-input" type="text" placeholder="Add a task...">
            </div>
            <div class="form-wrapper">
                <button class="todo-button" type="submit">Add</button>
            </div>
    </form>

    <div class="todo-tabs">
        <ul>
            <li class="all-tasks active">
                <span></span>All tasks (<span class="counter">0</span>)</span>
            </li>
            <li class="completed">
                <span>Completed (<span class="counter">0</span>)</span>
            </li>
        </ul>
    </div>

    <div class="todo-list">
        <div class="tabs-content" data-tab="1">
            <ol class="undone-tasks"></ol>
        </div>
        <div class="tabs-content" data-tab="2">
            <ol class="done-tasks"></ol>
        </div>
    </div>
</body>
</code>```

JS code:

```<code>//Selectors
const todoForm = document.querySelector('.todo-form');
const todoInput = document.querySelector('.todo-input');
const todoButton = document.querySelector('.todo-button');

const tabs = document.querySelectorAll('.todo-tabs ul li');
const tabWrap = document.querySelector('.todo-tabs ul');

const undone = document.querySelector('.undone-tasks');
const done = document.querySelectorAll('.done-tasks');

//Event Listeners
tabWrap.addEventListener('click', tabs)
todoButton.addEventListener('click', addToDo);

//Functions
tabs.forEach(function (tab, tab_index) {
    tab.addEventListener("click", function () {
        tabs.forEach(function (tab) {
            tab.classList.remove("active");
        })
        tabWrap.forEach(function (todoList, todoList_index) {
            if (todoList_index == tab_index) {
                todoList.style.display = "block";
            }
            else[
                todoList.style.display = "none"
            ]
        })
    })
})

function addToDo(event) {
    //Prevent form from submitting
    event.preventDefault();

    if (todoInput.value != "") {
        const todoDiv = document.createElement('div');
        todoDiv.classList.add('todo-div');

        const inputCheckbox = document.createElement('input');
        inputCheckbox.classList.add("checkbox-incompleted");
        inputCheckbox.setAttribute('type', 'checkbox');
        todoDiv.appendChild(inputCheckbox);

        //Create li
        const newToDo = document.createElement('li');
        newToDo.classList.add('todo-item');
        newToDo.insertAdjacentText("beforeend", todoInput.value);
        todoDiv.appendChild(newToDo);
        console.log(newToDo)

        //Append to list
        undone.appendChild(todoDiv);

        //Clear todo input value
        todoInput.value = "";

        //Focusing after 1st input
        todoInput.focus();
    }
}
</code>```

The commented area is what i tried to do for tabs and lists to switch, but it gives the following error:

```<code>Uncaught TypeError: tabWrap.forEach is not a function
    at HTMLLIElement.<anonymous> (script.js:32:17)
(anonymous) @ script.js:32
</code>```

The error starts at the beggining of the tabWrap.forEach function. But I guess there could be other way to solve this

答:
As @Anurag Srivastava pointed out on comment, in your code this is how you get tab elements:

```<code>const tabs = document.querySelectorAll('.todo-tabs ul li');
const tabWrap = document.querySelector('.todo-tabs ul');
</code>```

The method querySelector returns a single element, and querySelectorAll returns an iterable collection.

And this is why you're getting the error:

```<code>Uncaught TypeError: tabWrap.forEach is not a function
</code>```

If you don't have to support internet explorer you could take a look at Element.insertAdjacentElement() to move elements from one tab to another.

Body:
Here we have a tab with incompled tasks and the list is supposed to be attached to the first tab(all-taks). After the task is finished it is supposed to get deleted from first list and move to second one with completed tasks. And after you switch to second tab, all the completed ones should be there. I can't figure out the way to do it.
I hope I could get some help or some detailed explanation, 'cause I have been stuck on this for some time.

Here is an image for more clarification:
[1]: https://i.stack.imgur.com/Dy0KL.png

HTML code:

To-Do List

Describe your list...

        <form action="" class="todo-form">

                <input class="todo-input" type="text" placeholder="Add a task...">

                <button class="todo-button" type="submit">Add</button>

    </form>

                All tasks (0)

                Completed (0)

JS code:

//Selectors
const todoForm = document.querySelector('.todo-form');
const todoInput = document.querySelector('.todo-input');
const todoButton = document.querySelector('.todo-button');

const tabs = document.querySelectorAll('.todo-tabs ul li');
const tabWrap = document.querySelector('.todo-tabs ul');

const undone = document.querySelector('.undone-tasks');
const done = document.querySelectorAll('.done-tasks');

//Event Listeners
tabWrap.addEventListener('click', tabs)
todoButton.addEventListener('click', addToDo);

//Functions
tabs.forEach(function (tab, tab_index) {
    tab.addEventListener("click", function () {
        tabs.forEach(function (tab) {
            tab.classList.remove("active");
        })
        tabWrap.forEach(function (todoList, todoList_index) {
            if (todoList_index == tab_index) {
                todoList.style.display = "block";
            }
            else[
                todoList.style.display = "none"
            ]
        })
    })
})

function addToDo(event) {
    //Prevent form from submitting
    event.preventDefault();

    if (todoInput.value != "") {
        const todoDiv = document.createElement('div');
        todoDiv.classList.add('todo-div');

        const inputCheckbox = document.createElement('input');
        inputCheckbox.classList.add("checkbox-incompleted");
        inputCheckbox.setAttribute('type', 'checkbox');
        todoDiv.appendChild(inputCheckbox);

        //Create li
        const newToDo = document.createElement('li');
        newToDo.classList.add('todo-item');
        newToDo.insertAdjacentText("beforeend", todoInput.value);
        todoDiv.appendChild(newToDo);
        console.log(newToDo)

        //Append to list
        undone.appendChild(todoDiv);

        //Clear todo input value
        todoInput.value = "";

        //Focusing after 1st input
        todoInput.focus();
    }
}

The commented area is what i tried to do for tabs and lists to switch, but it gives the following error:

Uncaught TypeError: tabWrap.forEach is not a function
    at HTMLLIElement.<anonymous> (script.js:32:17)
(anonymous) @ script.js:32

The error starts at the beggining of the tabWrap.forEach function. But I guess there could be other way to solve this

Body:
As @Anurag Srivastava pointed out on comment, in your code this is how you get tab elements:

const tabs = document.querySelectorAll('.todo-tabs ul li');
const tabWrap = document.querySelector('.todo-tabs ul');

The method querySelector returns a single element, and querySelectorAll returns an iterable collection.

And this is why you're getting the error:

Uncaught TypeError: tabWrap.forEach is not a function

If you don't have to support internet explorer you could take a look at Element.insertAdjacentElement() to move elements from one tab to another.


问:
Varnish cache is missed after some time
Varnish cache is missed after some time even though the Page cache maximum age in "GENERAL SETTINGS" of Advanced Varnish configuration is set to "1 month"

While overriding the TTL value from individual content type still it doesn't work.

答:
There are many factors to affect the hit rate of your Varnish server.

Please share the following information:

The Cache-Control headers that your application sends

The VCL code

Your varnishd runtime parameters and specifically the value of the -s parameter

The output of varnishstat -f MAIN.n_lru_nuked -f MAIN.n_object -f SMA.*.g_bytes -f SMA.*.g_space

If there are specific transactions that result in a cache miss but that are supposed to be hits, please run send the output of the following command:

```<code>varnishlog -g request -q "ReqUrl eq '/'"
</code>```

FYI: This varnishlog command filters transactions for the / homepage. If the problem occurs on another page, please adjust the -q filter.

Based on all this information I can check where the problem is situated.

Title: Varnish cache is missed after some time

Body:
There are many factors to affect the hit rate of your Varnish server.

Please share the following information:

The Cache-Control headers that your application sends

The VCL code

Your varnishd runtime parameters and specifically the value of the -s parameter

The output of varnishstat -f MAIN.n_lru_nuked -f MAIN.n_object -f SMA.*.g_bytes -f SMA.*.g_space

If there are specific transactions that result in a cache miss but that are supposed to be hits, please run send the output of the following command:

varnishlog -g request -q "ReqUrl eq '/'"

FYI: This varnishlog command filters transactions for the / homepage. If the problem occurs on another page, please adjust the -q filter.

Based on all this information I can check where the problem is situated.


问:
Store output of shell command with multiple arguments into an array
I'm trying to store the states of my terraform workspaces in an array using shell.

I'm trying this way which usually works for me:

```<code>declare -a workspace_list=( $(terraform workspace list))

for a in $(seq 0 ${#workspace_list[*]})
do
    if [[ -z ${workspace_list[$a]} ]]
        then
              break
        fi
    echo $(($a+1))": "${workspace_list[$a]}
    a=$(($a+1))
done
</code>```

However, it gives me an output with all the files in the directory as well along with the workspaces.

I'm guessing it's to do with the multiple args with terraform command. Please help.

Output of terraform workspace list for reference

答:
When you initialize the array with the result of terraform command it looks like:

```<code>declare -a workspace_list=( * default dev-singapore)
</code>```

Here, * is glob-expanded to list of all files in current directory.

You can get rid of the asterisk just processing terraform's output.

```<code>declare -a workspace_list=($(terraform workspace list | sed 's/*//'))
</code>```

Unfortunately unlike terraform plan, there is no option for JSON output from terraform workspace, which would be more clean.

Body:
I'm trying to store the states of my terraform workspaces in an array using shell.

I'm trying this way which usually works for me:

declare -a workspace_list=( $(terraform workspace list))

for a in $(seq 0 ${#workspace_list[*]})
do
    if [[ -z ${workspace_list[$a]} ]]
        then
              break
        fi
    echo $(($a+1))": "${workspace_list[$a]}
    a=$(($a+1))
done

However, it gives me an output with all the files in the directory as well along with the workspaces.

I'm guessing it's to do with the multiple args with terraform command. Please help.

Output of terraform workspace list for reference

Body:
When you initialize the array with the result of terraform command it looks like:

declare -a workspace_list=( * default dev-singapore)

Here, * is glob-expanded to list of all files in current directory.

You can get rid of the asterisk just processing terraform's output.

declare -a workspace_list=($(terraform workspace list | sed 's/*//'))

Unfortunately unlike terraform plan, there is no option for JSON output from terraform workspace, which would be more clean.


问:
TypeORM NestJS ignore connection errors
Is there a way to ignore connection errors in the TypeORM NestJS module?

In my application I have 2 environments: in one of them I do use MySQL database (via the TypeORM), while in another I don't use any MySQL features, but still have to have it as a dependency because otherwise TypeORM will throw errors that it can't connect to the database.

I can differ the environments based on some variable, let's call it isSelfhosted.
Is there a way to ignore errors or don't connect to the TypeORM at all is this isSelfhosted variable is set to true, while still having some TypeORM related functions used in the code (which are called conditionally based on the specific environment)?

My current connection to the TypeORM looks like this:

@Module({
  imports: [
    ConfigModule.forRoot({ envFilePath: '.env' }),
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: process.env.MYSQL_HOST,
      port: 3306,
      username: process.env.MYSQL_USER,
      password: process.env.MYSQL_ROOT_PASSWORD,
      database: process.env.MYSQL_DATABASE,
      synchronize: false,
      entities: [User, ActionToken, Project],
    }),
    ScheduleModule.forRoot(),
    TaskManagerModule,
    AuthModule,
    UserModule,
    MailerModule,
    ActionTokensModule,
    ProjectModule,
    AnalyticsModule,
    WebhookModule,
    PingModule,
  ],
})
```

Thanks.

答:
I use a function like that to generate json file, and don't use you env variable directly in the connect function

    const generateOrmConfig = async (): Promise<void> => {
      const DATABASE_TYPE = 'postgres';
      const ORM_CONFIG_FILE = 'ormconfig.json';
      const ROOT_PATH: string = process.cwd();
      const pathToWriteOrmConfig = join(ROOT_PATH, ORM_CONFIG_FILE);
      const writeFileAsync = promisify(writeFile);
      const unlinkAsync = promisify(unlink);
      try {
        if (existsSync(join(ROOT_PATH, '.env'))) {
          config();
        }
        const env = process.env.APP_ENV || process.env.NODE_ENV;

        const configTemplate = `
        {
            "type": "<%= type %>",
            "host": "<%= host %>",
            "port": <%= port %>,
            "username": "<%= username %>",
            "password": "<%= password %>",
            "database": "<%= database %>",
            "entities": [<%= entities %>],
            "subscribers": ["<%= subscribers %>"],
            "migrationsTableName": "<%= migrationsTableName %>",
            "migrations": ["<%= migrations %>"],
            "cli": {
                "migrationsDir": "<%= migrationsFolder %>"
            }
        }`;

        logger.info(`Current env is: ${env}`);
        const buildExtension = env === 'production' ? 'js' : 'ts';

        const typeOrmConfigObject = {
          type: DATABASE_TYPE,
          host: process.env.DATABASE_HOST,
          port: process.env.DATABASE_PORT,
          username: process.env.DATABASE_USER,
          password: process.env.DATABASE_PASSWORD,
          database: process.env.DATABASE_NAME,
          entities: `"./src/**/**.entity{.ts,.js}"`,
          subscribers: `./src/**/**.subscriber.${buildExtension}`,
          migrationsTableName: 'migrations',
          migrations: `./migrations/*.${buildExtension}`,
          migrationsFolder: 'migrations',
        };

        const compiledTemplate = template(configTemplate)(typeOrmConfigObject);
        if (existsSync(pathToWriteOrmConfig)) {
          logger.warn('Orm config file already exists - lets recreate them');
          await unlinkAsync(pathToWriteOrmConfig);
        }
        await writeFileAsync(pathToWriteOrmConfig, compiledTemplate);
        logger.info(`Orm config has been created in: ${pathToWriteOrmConfig}`);
      } catch (e) {
        logger.error('Error occurs during ormconfig file creation');
        throw e;
      }
    };
    generateOrmConfig();
```

Title: TypeORM NestJS ignore connection errors

Body:
Is there a way to ignore connection errors in the TypeORM NestJS module?

In my application I have 2 environments: in one of them I do use MySQL database (via the TypeORM), while in another I don't use any MySQL features, but still have to have it as a dependency because otherwise TypeORM will throw errors that it can't connect to the database.

I can differ the environments based on some variable, let's call it isSelfhosted.
Is there a way to ignore errors or don't connect to the TypeORM at all is this isSelfhosted variable is set to true, while still having some TypeORM related functions used in the code (which are called conditionally based on the specific environment)?

My current connection to the TypeORM looks like this:

@Module({
  imports: [
    ConfigModule.forRoot({ envFilePath: '.env' }),
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: process.env.MYSQL_HOST,
      port: 3306,
      username: process.env.MYSQL_USER,
      password: process.env.MYSQL_ROOT_PASSWORD,
      database: process.env.MYSQL_DATABASE,
      synchronize: false,
      entities: [User, ActionToken, Project],
    }),
    ScheduleModule.forRoot(),
    TaskManagerModule,
    AuthModule,
    UserModule,
    MailerModule,
    ActionTokensModule,
    ProjectModule,
    AnalyticsModule,
    WebhookModule,
    PingModule,
  ],
})

Thanks.


问:
if radio box checked send different email fields
```<code><form method="post" action="" id="infoform">
<label for="first">
    First Name</label>
<input type="text" name="first" id="first" class="field validate[required]">
</br>
<label for="surname">
    Last Name</label>
<input type="text" name="surname" id="surname" class="field validate[required]"> </br>
    <label for="email">
        Email</label>
    <input type="text" name="email" id="email" class=" field email validate[required,custom[email]]">
        </br>
        <div class="radios">
            <input id="test2" checked="checked" type="radio" name="message" value="register" />
        Register for Updates</input>
    <input id="test1" type="radio" name="message" value="msgs" />
    Send a Message</input>
</div>
<div class="msg">
    <label for="message" id="messagelabel">
        Message</label>
    <textarea type="text" name="message" id="message"></textarea>
</div>
<input id="submit" type="submit" value=""><div class="test3">
    <a class="sbmt">Register</a></div>
    <div class="test4">
        <a class="sbmt">Send</a></div>
</input>
</form>
</code>```

If the radio box 'test1' is checked, then  the div msg appears. This is then sent via ajax to an email php script:

```<code><?php
    $EmailTo = "matt@explosivetitles.com";
    $adminSubject = "Civitas Message";

    $firstName = Trim(stripslashes($_POST['first']));
    $Surname = Trim(stripslashes($_POST['surname']));
    $Email = Trim(stripslashes($_POST['email']));
    $Message = Trim(stripslashes($_POST['message']));

    $adminheaders = 'From: "Civitas website" <info@civitas.com>';

    $adminBody .= "First Name: ";
    $adminBody .= $firstName;
    $adminBody .= "\n";
    $adminBody .= "Surname: ";
    $adminBody .= $Surname;
    $adminBody .= "\n";
    $adminBody .= "Email: ";
    $adminBody .= $Email;
    $adminBody .= "\n";
    $adminBody .= "Message: ";
    $adminBody .= $Message;
    $adminBody .= "\n";

    $adminMail = mail($EmailTo, $adminSubject, $adminBody, $adminheaders);

    if ($adminMail){
        echo "true";
    }
    else{
      echo "false";
    }
?>
</code>```

However I only want the "message" part of the email to be sent if the message box is showing. How can I do this?

答:
You can do this:

```<code>$adminBody .= "First Name: ";
$adminBody .= $firstName;
$adminBody .= "\n";
$adminBody .= "Surname: ";
$adminBody .= $Surname;
$adminBody .= "\n";
$adminBody .= "Email: ";
$adminBody .= $Email;
$adminBody .= "\n";
if (isset($_POST['message'])) {
  $adminBody .= "Message: ";
  $adminBody .= $Message;
}
$adminBody .= "\n";
</code>```

isset() will check if the variable exists, if yes it will return true.

Body:
<form method="post" action="" id="infoform">

    First Name
<input type="text" name="first" id="first" class="field validate[required]">

    Last Name
<input type="text" name="surname" id="surname" class="field validate[required]">

        Email
    <input type="text" name="email" id="email" class=" field email validate[required,custom[email]]">

            <input id="test2" checked="checked" type="radio" name="message" value="register" />
        Register for Updates</input>
    <input id="test1" type="radio" name="message" value="msgs" />
    Send a Message</input>

        Message
    <textarea type="text" name="message" id="message"></textarea>

<input id="submit" type="submit" value="">

    Register

        Send

</input>
</form>

If the radio box 'test1' is checked, then  the div msg appears. This is then sent via ajax to an email php script:

<?php
    $EmailTo = "matt@explosivetitles.com";
    $adminSubject = "Civitas Message";

    $firstName = Trim(stripslashes($_POST['first']));
    $Surname = Trim(stripslashes($_POST['surname']));
    $Email = Trim(stripslashes($_POST['email']));
    $Message = Trim(stripslashes($_POST['message']));

    $adminheaders = 'From: "Civitas website" <info@civitas.com>';

    $adminBody .= "First Name: ";
    $adminBody .= $firstName;
    $adminBody .= "\n";
    $adminBody .= "Surname: ";
    $adminBody .= $Surname;
    $adminBody .= "\n";
    $adminBody .= "Email: ";
    $adminBody .= $Email;
    $adminBody .= "\n";
    $adminBody .= "Message: ";
    $adminBody .= $Message;
    $adminBody .= "\n";

    $adminMail = mail($EmailTo, $adminSubject, $adminBody, $adminheaders);

    if ($adminMail){
        echo "true";
    }
    else{
      echo "false";
    }
?>

However I only want the "message" part of the email to be sent if the message box is showing. How can I do this?

Body:
You can do this:

$adminBody .= "First Name: ";
$adminBody .= $firstName;
$adminBody .= "\n";
$adminBody .= "Surname: ";
$adminBody .= $Surname;
$adminBody .= "\n";
$adminBody .= "Email: ";
$adminBody .= $Email;
$adminBody .= "\n";
if (isset($_POST['message'])) {
  $adminBody .= "Message: ";
  $adminBody .= $Message;
}
$adminBody .= "\n";

isset() will check if the variable exists, if yes it will return true.


问:
Ansible use if condition at hosts
I am trying to pass a variable called 'ci=hostname' from Ansible cmdline and what I am looking for is it should pick that variable 'if defined' but if not, then it should pick 'pod_Cluster_cl'. I tried it but it gives out an error that 'ci' is NOT defined variable.

I think I need to use some other conditional rather than using "!=" but don't know which. Something equivalent to

"ifdef"

maybe?

---
- hosts: >-
    {{ ci
      if ci != 0
          else 'pod_Cluster_cl'
    }}
```

答:
You can simply use the default filter.

---
 - hosts: "{{ ci | default('pod_Cluster_cl') }}"
```

Title: Ansible use if condition at hosts


问:
mod_rewrite a sub directoy to child subdirectory
I have a following sub domain and folder structure

https://subdomain.maindomain.com/companyName1/area/dashboard

I want to mod_rewrite to this

https://subdomain.maindomain.com/companyName1/area/

So that everything in "dashboard" loads, in "area"

I would like the .htaccess file to live in the area folder, as there are multiple companyNames

I've tried placing the following .htaccess in companyName1/area

```<code>RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-s
RewriteCond %{DOCUMENT_ROOT}/dashboard/%{REQUEST_URI} -s
RewriteRule ^(.*)$ /dashboard/$1 [L]
</code>```

However when visiting https://subdomain.maindomain.com/companyName1/area/ it just loads the index.html of that folder, and not of the /dashboard folder

答:
With your shown samples, attempts please try following htaccess rules. Please make sure to keep these rules at the top of your htaccess file.

Also make sure to clear your browser cache before testing your URLs.

```<code>RewriteEngine ON
RewriteBase /companyName1/area/
##For external redirect to area link.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s.*/dashboard/?\s [NC]
RewriteRule ^(.*)/dashboard/?$ /$1/? [R=301,L]
##For internal rewrite to dashboard folder here.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
</code>```

Body:
I have a following sub domain and folder structure

https://subdomain.maindomain.com/companyName1/area/dashboard

I want to mod_rewrite to this

https://subdomain.maindomain.com/companyName1/area/

So that everything in "dashboard" loads, in "area"

I would like the .htaccess file to live in the area folder, as there are multiple companyNames

I've tried placing the following .htaccess in companyName1/area

RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-s
RewriteCond %{DOCUMENT_ROOT}/dashboard/%{REQUEST_URI} -s
RewriteRule ^(.*)$ /dashboard/$1 [L]

However when visiting https://subdomain.maindomain.com/companyName1/area/ it just loads the index.html of that folder, and not of the /dashboard folder

Body:
With your shown samples, attempts please try following htaccess rules. Please make sure to keep these rules at the top of your htaccess file.

Also make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
RewriteBase /companyName1/area/
##For external redirect to area link.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s.*/dashboard/?\s [NC]
RewriteRule ^(.*)/dashboard/?$ /$1/? [R=301,L]
##For internal rewrite to dashboard folder here.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]


问:
How to play audio continuously in xamarin forms
I implemented audio implementation and added looping property also. But the audio Plays a two times only and after that audio doesn't play. Here I attached a code I implemented. Kindly help how to fix. Thanks for advance

```<code>namespace Com.Audio.Droid
{
    public class AudioService : IAudio
    {
        public AudioService()
        {
        }

        public void PlayAudioFile(string fileName)
        {
            var player = new MediaPlayer();
            var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
            player.Prepared += (s, e) =>
            {
                player.Start();
            };
            player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
            player.Looping = true;
            player.Prepare();
        }

        public void PauseAudioFile(string fileName)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var player = new MediaPlayer();
                var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
                player.Prepared += (s, e) =>
                {
                    player.Stop();
                    player.Release();
                    player.Dispose();
                };
                player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
                player.Prepare();
            });

        }
    }
}
</code>```

And in iOS the audio play a only one second. It's doesn't play the audio file entirely

```<code>namespace com.Audio.ios
{
    public class AudioService : IAudio
    {
        public AudioService()
        {
        }

        public void PlayAudioFile(string fileName)
        {
            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
            var url = NSUrl.FromString(sFilePath);
            var _player = AVAudioPlayer.FromUrl(url);
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                _player = null;
            };
            _player.NumberOfLoops = -1;
            _player.Play();
        }

        public void PauseAudioFile(string fileName)
        {
            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
            var url = NSUrl.FromString(sFilePath);
            var _player = AVAudioPlayer.FromUrl(url);
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                _player = null;
            };
            _player.Stop();
        }
    }
}
</code>```

答:
For Android

You need a hook way to implement a loopMediaPlayer, that is creating a new player when the audio is finished.

Refer to : https://stackoverflow.com/a/29883923/8187800 .

For iOS

Due to ARC , probably AVAudioPlayer is released after calling dependency service , to solved it you can try to make _player as global variable .

Refer to
https://stackoverflow.com/a/8415802/8187800 .

Body:
I implemented audio implementation and added looping property also. But the audio Plays a two times only and after that audio doesn't play. Here I attached a code I implemented. Kindly help how to fix. Thanks for advance

namespace Com.Audio.Droid
{
    public class AudioService : IAudio
    {
        public AudioService()
        {
        }

        public void PlayAudioFile(string fileName)
        {
            var player = new MediaPlayer();
            var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
            player.Prepared += (s, e) =>
            {
                player.Start();
            };
            player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
            player.Looping = true;
            player.Prepare();
        }

        public void PauseAudioFile(string fileName)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var player = new MediaPlayer();
                var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
                player.Prepared += (s, e) =>
                {
                    player.Stop();
                    player.Release();
                    player.Dispose();
                };
                player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
                player.Prepare();
            });

        }
    }
}

And in iOS the audio play a only one second. It's doesn't play the audio file entirely

namespace com.Audio.ios
{
    public class AudioService : IAudio
    {
        public AudioService()
        {
        }

        public void PlayAudioFile(string fileName)
        {
            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
            var url = NSUrl.FromString(sFilePath);
            var _player = AVAudioPlayer.FromUrl(url);
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                _player = null;
            };
            _player.NumberOfLoops = -1;
            _player.Play();
        }

        public void PauseAudioFile(string fileName)
        {
            string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
            var url = NSUrl.FromString(sFilePath);
            var _player = AVAudioPlayer.FromUrl(url);
            _player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
            {
                _player = null;
            };
            _player.Stop();
        }
    }
}


问:
Is save for multiple bash scripts to append to the same log file?
I would like to save multiple bash scripts to the same log file to be able to precisely monitor which event happened before another event.

Just to create some tests I have executed three bash scripts at nearly the same time.

File A.sh:

```<code>#!/bin/bash
watch -n 1 'echo AAA $(date '+%Y%m%d%H%M%S%N') >> mylog.log'
</code>```

File B.sh

```<code>#!/bin/bash
watch -n 1 'echo BBB $(date '+%Y%m%d%H%M%S%N') >> mylog.log'
</code>```

File C.sh

```<code>#!/bin/bash
watch -n 1 'echo CCC $(date '+%Y%m%d%H%M%S%N') >> mylog.log'
</code>```

And in log file I see:

```<code>AAA 20220211083057445268276
BBB 20220211083058398227435
CCC 20220211083058417044373
AAA 20220211083058453956479
BBB 20220211083059419856946
CCC 20220211083059436848192
</code>```

All this looks fine.

What will happen if two bash scripts write to log file at exactly the same time? Is there some file locking implemented, so B.sh has to wait until A.sh writes to log file, or will B.sh just overwrite the A.sh record?

答:
As "rici" stated, if you use the 'append' mode when opening then concurrent access, it shouldn't be an issue, however, the results may not be in the order you would expect.  Adding a time-stamp to your log entries would probably help to de-tangle them.

Concurrent access will also mean that a process will have to wait at some time.  I wouldn't expect long waits, but that also depends on how frequently a process will be appending. Waits might cause further issues for you down the line, especially if the number of concurrent access attempts grows (large number of processes or endless loop).

I'm not well versed, but you might want to look at the syslog system or similar; it could be a alternate option that possibly remove the some of the idiosyncrasies of concurrent file handling/writing (while bringing others ;-) ).

Body:
I would like to save multiple bash scripts to the same log file to be able to precisely monitor which event happened before another event.

Just to create some tests I have executed three bash scripts at nearly the same time.

File A.sh:

#!/bin/bash
watch -n 1 'echo AAA $(date '+%Y%m%d%H%M%S%N') >> mylog.log'

File B.sh

#!/bin/bash
watch -n 1 'echo BBB $(date '+%Y%m%d%H%M%S%N') >> mylog.log'

File C.sh

#!/bin/bash
watch -n 1 'echo CCC $(date '+%Y%m%d%H%M%S%N') >> mylog.log'

And in log file I see:

AAA 20220211083057445268276
BBB 20220211083058398227435
CCC 20220211083058417044373
AAA 20220211083058453956479
BBB 20220211083059419856946
CCC 20220211083059436848192

All this looks fine.

What will happen if two bash scripts write to log file at exactly the same time? Is there some file locking implemented, so B.sh has to wait until A.sh writes to log file, or will B.sh just overwrite the A.sh record?


问:
Read from a string until specific char in Android
How can I read numbers from a string until I find a specific char, in my case - a dot.

For example I have a

```<code>String date = "18.8.2011"
int mDay = 0;
int mMonth = 0;
int mYear = 0;
</code>```

And I want to make mDay = 18, mMonth = 8 and mYear = 2011 - I want to be able to copy the digits until I find a dot.

答:
```<code>String[] arr = date.split("[.]");

int mDay = Integer.parseInt(arr[0]);
int mMonth = Integer.parseInt(arr[1]);
int myear = Integer.parseInt(arr[2]);
</code>```

Body:
How can I read numbers from a string until I find a specific char, in my case - a dot.

For example I have a

String date = "18.8.2011"
int mDay = 0;
int mMonth = 0;
int mYear = 0;

And I want to make mDay = 18, mMonth = 8 and mYear = 2011 - I want to be able to copy the digits until I find a dot.


问:
Xcode 13: Build hangs with "iPhone is busy: making Apple Watch ready for development"
Issue: The build hangs with "iPhone is busy: making Apple Watch ready for development"

Further facts:

iOS 14.8

iPhone 8

watchOS 7.6.2

Xcode 13

Apple Watch Series 3 + Cellular (42mm)

Does anyone know a solution for that issue?

Many of the developers have the same issue:

https://developer.apple.com/forums/thread/691452

答:
I facing this issue too. This is because the latest xcode only support until iOS 15.2 sdk, but my phone's iOS version is 15.3. Thus, xcode is downloading the iOS 15.3 sdk from your phone that's why takes time (I knew the message is not saying that)

However, I do some testing and it works for me.

Get the iOS 15.3 sdk (is 10BG!!!) from my friend xcode's Devices Support iOS folder /Users/XXX/Library/Developer/Xcode/iOS DeviceSupport and paste it to yours one.

Downloading the iphone OS device support file from https://github.com/filsv/iPhoneOSDeviceSupport/blob/0e8ef7bc51b982304ed3258454f88ae2d5615ac7/15.3.zip unzip it and paste it in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Restart Xcode.

Build success without waiting.

Origin From: https://developer.apple.com/forums/thread/691452?answerId=704424022#704424022


问:
Implement follow/unfollow in Node.js
I am a beginner and i want to create follow/unfollow functionality in my app.

```<code>router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{

user.findById(req.params.id)
.then((otherUser)=>{
    if(otherUser.followers.includes(req.userInfo._id)){

        return res.json({message: "Already following user"});
    }
    req.userInfo.updateOne({$push: {followings: req.params.id}});
    otherUser.updateOne({ $push: {followers: req.userInfo._id}});
    res.json({message: "following user"});
    console.log(otherUser.followers);

})
.catch((e)=>{
    res.json(e);
})})
</code>```

when running the code it recieves the message "following user" but dosen't add to the database i.e. Mongodb (i'm using MERN stack)

It seems like this block of code is not executing.

```<code>req.userInfo.updateOne({$push: {followings: req.params.id}});
otherUser.updateOne({ $push: {followers: req.userInfo._id}});
</code>```

what am i doing wrong here?

答:
Well, this seems to work

```<code>router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{

user.findById(req.params.id)
.then((otherUser)=>{
    if(!otherUser.followers.includes(req.userInfo._id)){
        Promise.all([
            user.updateOne({_id:req.userInfo._id}, {$push: {followings: req.params.id}}),
            user.updateOne({_id: otherUser._id},{$push: {followers: req.userInfo._id}})
        ]).then(()=>{
            res.json({message: "following user"});
        })
        .catch((e)=>{
            res.json(e);
        });
    }else{
        return res.json({message: "Already following user"});
    }
})
});
</code>```

But it would be better if someone explained what went wrong previously, as I said i am beginner and would appreciate the feedback.

Title: Implement follow/unfollow in Node.js

Body:
I am a beginner and i want to create follow/unfollow functionality in my app.

router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{

user.findById(req.params.id)
.then((otherUser)=>{
    if(otherUser.followers.includes(req.userInfo._id)){

        return res.json({message: "Already following user"});
    }
    req.userInfo.updateOne({$push: {followings: req.params.id}});
    otherUser.updateOne({ $push: {followers: req.userInfo._id}});
    res.json({message: "following user"});
    console.log(otherUser.followers);

})
.catch((e)=>{
    res.json(e);
})})

when running the code it recieves the message "following user" but dosen't add to the database i.e. Mongodb (i'm using MERN stack)

It seems like this block of code is not executing.

req.userInfo.updateOne({$push: {followings: req.params.id}});
otherUser.updateOne({ $push: {followers: req.userInfo._id}});

what am i doing wrong here?

Body:
Well, this seems to work

router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{

user.findById(req.params.id)
.then((otherUser)=>{
    if(!otherUser.followers.includes(req.userInfo._id)){
        Promise.all([
            user.updateOne({_id:req.userInfo._id}, {$push: {followings: req.params.id}}),
            user.updateOne({_id: otherUser._id},{$push: {followers: req.userInfo._id}})
        ]).then(()=>{
            res.json({message: "following user"});
        })
        .catch((e)=>{
            res.json(e);
        });
    }else{
        return res.json({message: "Already following user"});
    }
})
});

But it would be better if someone explained what went wrong previously, as I said i am beginner and would appreciate the feedback.


问:
why when I add secure-ls to vuex-persistedstate the vuex information does not have the session data as it was before?
Previously when I had not configured secure-ls as it is here: https://codesandbox.io/s/7l9wb

in my localStorage in the 'vuex' key I had more or less the following

```<code>{authUser:{name:'My name', authenticated: true}}
</code>```

after having configured secure-sl in the vuex-persistedstate:

```<code> storage: {
        getItem: key => ls.get(key),
        setItem: (key, value) => ls.set(key, value),
        removeItem: key => ls.remove(key)
      }
</code>```

When I reload the page, the page appears blank, since the vuex values have been reset. If I then comment out the secure-sl setting:

```<code>/*storage: {
            getItem: key => ls.get(key),
            setItem: (key, value) => ls.set(key, value),
            removeItem: key => ls.remove(key)
          }*/
</code>```

and I refresh the page again, the localStorage values are:

```<code>{authUser:{name: null, authenticated: false}}
</code>```

please note that name is null and authenticated is false

Behavior that seems strange to me, this only happens when the user is logged in and before applying the secure-sl, since if I do it from incognito mode with a new session and the configuration of the secure-sl I do not have any problem.

答:
Seems like an issue with vuex-persistedstore.

It is is deprecated anyway, so stop using it. You can use Vuex.subscribe() instead:
https://www.mikestreety.co.uk/blog/vue-js-using-localstorage-with-the-vuex-store/

Body:
Previously when I had not configured secure-ls as it is here: https://codesandbox.io/s/7l9wb

in my localStorage in the 'vuex' key I had more or less the following

{authUser:{name:'My name', authenticated: true}}

after having configured secure-sl in the vuex-persistedstate:

 storage: {
        getItem: key => ls.get(key),
        setItem: (key, value) => ls.set(key, value),
        removeItem: key => ls.remove(key)
      }

When I reload the page, the page appears blank, since the vuex values have been reset. If I then comment out the secure-sl setting:

/*storage: {
            getItem: key => ls.get(key),
            setItem: (key, value) => ls.set(key, value),
            removeItem: key => ls.remove(key)
          }*/

and I refresh the page again, the localStorage values are:

{authUser:{name: null, authenticated: false}}

please note that name is null and authenticated is false

Behavior that seems strange to me, this only happens when the user is logged in and before applying the secure-sl, since if I do it from incognito mode with a new session and the configuration of the secure-sl I do not have any problem.


问:
Change to custom background when a cell is highlighted
How can I change the background of a custom cell when a it is selected ?

Thanks, Niels

答:
```<code>if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    UIView *v = [[[UIView alloc] init] autorelease];
    v.backgroundColor = [UIColor blueColor];
    cell.selectedBackgroundView = v;
</code>```

use this

Body:
if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    UIView *v = [[[UIView alloc] init] autorelease];
    v.backgroundColor = [UIColor blueColor];
    cell.selectedBackgroundView = v;

use this


问:
API returning 401 on Azure but not when run locally
The application in question is a web site which has an API tacked on the side that reuses the many of the data access methods developed for the website. So there maybe some interference between the web site authentication/authorization and the API's. But if that was the case I don't understand why it works locally.

When I run locally, I can test the API using Swagger or Postman to login, get the Bearer token and use it to call the API methods. On Azure, although the login succeeds the next call to the API returns a 401:

```<code>www-authenticate: Bearer error="invalid_token",error_description="The signature is invalid"
</code>```

The most obvious difference is the appsettings.json which I've copied to the Application Configuration blade on Azure:

The original appsettings looked like:

```<code>  "Rt5": {
    "BaseAddress": "https://localhost:44357"
  },
  "Azure": {
    "BuildNumber": ""
  },
  "AuthentificationJWT": {
    "Audience": "ddt-ssp",
    "Issuer": "ddt-rt5",
    "SecurityKey": "not so secret"
  },
</code>```

Usage - ConfigureServices():

```<code>        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.AccessDeniedPath = "/Home/Unauthorized";
                options.LoginPath = "/User/Login";
                options.LogoutPath = "/User/Logout";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AuthentificationJWT:SecurityKey"])),
                    ValidateIssuer = true,
                    ValidIssuer = Configuration["AuthentificationJWT:Issuer"],
                    ValidateAudience = true,
                    ValidAudience = Configuration["AuthentificationJWT:Audience"],
                    ValidateLifetime = true,
                    ValidAlgorithms = new HashSet<string> { SecurityAlgorithms.HmacSha256 },
                    ValidTypes = new HashSet<string> { "JWT" }
                };
            });

        services.AddAuthorization(o =>
        {
            o.AddPolicy(AllowViewExceptions.Policy, p
                => p.Requirements.Add(new AllowViewExceptions.Requirement()));
            o.AddPolicy(AllowSubmitException.Policy, p
                => p.Requirements.Add(new AllowSubmitException.Requirement()));
        });
</code>```

Usage - Configure():

```<code>        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();

        if (UseSwagger)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"); });
        }

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
</code>```

Confession: this isn't my code and I'm sure why we have the Cookie stuff mentioned though is does seem to be offer an alternative authorization mechanism. See here:

```<code>    public string GetAuthorization()
    {
        //TODO: use ExtractSecurityToken();
        var claimToken = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == AuthenticationConfig.AccessTokenCookieName);
        if (claimToken != null)
        {
            return $"Bearer {claimToken.Value}";
        }
        else if (_httpContextAccessor.HttpContext.Request.Headers.TryGetValue(AuthenticationConfig.AuthorizationHeader, out var headerToken))
        {
            return headerToken;
        }

        return null;
    }

    private JwtSecurityToken ExtractSecurityToken()
    {
        var accessToken = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == AuthenticationConfig.AccessTokenCookieName)?.Value;
        if (accessToken == null &&
            _httpContextAccessor.HttpContext.Request.Headers.TryGetValue(AuthenticationConfig.AuthorizationHeader, out var value))
        {
            accessToken = value.ToString().Replace("Bearer ", ""); // TODO: Find a better way then extracting Bearer e.g Get token without scheme
        }

        if (accessToken == null)
        {
            return null;
        }

        return (JwtSecurityToken)new JwtSecurityTokenHandler().ReadToken(accessToken);
    }
</code>```

答:
The problem appears to be with Azure Websites' "Authentication / Authorization" option, which when enabled prevents the Web Api from accepting requests with the Authentication header. Disabling the option and using the Owin library with Azure AD provides the desired solution.

Every app service that is associated with Azure-AD has a corresponding Azure-AD application declaration of type Web app/API. This resource id is the "App ID URI" in the app service's Azure-AD application declaration.

To debug Authentication issues, please refer this msdn link.

Body:
The application in question is a web site which has an API tacked on the side that reuses the many of the data access methods developed for the website. So there maybe some interference between the web site authentication/authorization and the API's. But if that was the case I don't understand why it works locally.

When I run locally, I can test the API using Swagger or Postman to login, get the Bearer token and use it to call the API methods. On Azure, although the login succeeds the next call to the API returns a 401:

www-authenticate: Bearer error="invalid_token",error_description="The signature is invalid"

The most obvious difference is the appsettings.json which I've copied to the Application Configuration blade on Azure:

The original appsettings looked like:

  "Rt5": {
    "BaseAddress": "https://localhost:44357"
  },
  "Azure": {
    "BuildNumber": ""
  },
  "AuthentificationJWT": {
    "Audience": "ddt-ssp",
    "Issuer": "ddt-rt5",
    "SecurityKey": "not so secret"
  },

Usage - ConfigureServices():

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.AccessDeniedPath = "/Home/Unauthorized";
                options.LoginPath = "/User/Login";
                options.LogoutPath = "/User/Logout";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AuthentificationJWT:SecurityKey"])),
                    ValidateIssuer = true,
                    ValidIssuer = Configuration["AuthentificationJWT:Issuer"],
                    ValidateAudience = true,
                    ValidAudience = Configuration["AuthentificationJWT:Audience"],
                    ValidateLifetime = true,
                    ValidAlgorithms = new HashSet<string> { SecurityAlgorithms.HmacSha256 },
                    ValidTypes = new HashSet<string> { "JWT" }
                };
            });

        services.AddAuthorization(o =>
        {
            o.AddPolicy(AllowViewExceptions.Policy, p
                => p.Requirements.Add(new AllowViewExceptions.Requirement()));
            o.AddPolicy(AllowSubmitException.Policy, p
                => p.Requirements.Add(new AllowSubmitException.Requirement()));
        });

Usage - Configure():

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();

        if (UseSwagger)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"); });
        }

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

Confession: this isn't my code and I'm sure why we have the Cookie stuff mentioned though is does seem to be offer an alternative authorization mechanism. See here:

    public string GetAuthorization()
    {
        //TODO: use ExtractSecurityToken();
        var claimToken = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == AuthenticationConfig.AccessTokenCookieName);
        if (claimToken != null)
        {
            return $"Bearer {claimToken.Value}";
        }
        else if (_httpContextAccessor.HttpContext.Request.Headers.TryGetValue(AuthenticationConfig.AuthorizationHeader, out var headerToken))
        {
            return headerToken;
        }

        return null;
    }

    private JwtSecurityToken ExtractSecurityToken()
    {
        var accessToken = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == AuthenticationConfig.AccessTokenCookieName)?.Value;
        if (accessToken == null &&
            _httpContextAccessor.HttpContext.Request.Headers.TryGetValue(AuthenticationConfig.AuthorizationHeader, out var value))
        {
            accessToken = value.ToString().Replace("Bearer ", ""); // TODO: Find a better way then extracting Bearer e.g Get token without scheme
        }

        if (accessToken == null)
        {
            return null;
        }

        return (JwtSecurityToken)new JwtSecurityTokenHandler().ReadToken(accessToken);
    }


问:
Why do we use "for" attribute inside label tag?
I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand

Code1

<input id="indoor" type="radio" name="indoor-outdoor">
Indoor```
</div>
</div>
</p>
<p>Code2</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label>
<br>
<label><input type="checkbox" name="personality"> Loving</label></code>```

I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?

答:
It is correct, that it works without it. But it is useful to connect the label with the input field. That is also important for the accessibility (e.g. for blind people, the text is read).

The browsers also allow you to click the labels and automatically focus the input fields.

For checkboxes this can be useful as well. But for these, you could also surround the checkbox-input like this:

```<code><label>
  <input type="checkbox"> I agree with the answer above.
</label>
</code>```

In this case, the checkbox is automatically checked when you click on the text.

The surrounding of the inputs with a label works with every input field. But the text, that describes the input field, should always be inside it. That what for is for: When your HTML disallows the label-surrounding, you can use the for-attribute.

The the both following examples:

Simple stuctured:

```<code><label>
  Your Name:<br>
  <input type="text"/>
</label>
</code>```

Complex structure around input fields:

```<code><div class="row">
  <div class="col">
    <label for="name">Your Name:</label>
  </div>
  <div class="col">
    <input type="text" id="name" />
  </div>
</div>
</code>```

Body:
I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand

Code1

<input id="indoor" type="radio" name="indoor-outdoor">
Indoor

Code2

<input id="loving" type="checkbox" name="personality"> Loving

<input type="checkbox" name="personality"> Loving

I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?

Body:
It is correct, that it works without it. But it is useful to connect the label with the input field. That is also important for the accessibility (e.g. for blind people, the text is read).

The browsers also allow you to click the labels and automatically focus the input fields.

For checkboxes this can be useful as well. But for these, you could also surround the checkbox-input like this:

<label>
  <input type="checkbox"> I agree with the answer above.
</label>

In this case, the checkbox is automatically checked when you click on the text.

The surrounding of the inputs with a label works with every input field. But the text, that describes the input field, should always be inside it. That what for is for: When your HTML disallows the label-surrounding, you can use the for-attribute.

The the both following examples:

Simple stuctured:

<label>
  Your Name:<br>
  <input type="text"/>
</label>

Complex structure around input fields:

<div class="row">
  <div class="col">
    <label for="name">Your Name:</label>
  </div>
  <div class="col">
    <input type="text" id="name" />
  </div>
</div>


问:
TypeError: Cannot read properties of undefined (reading 'childRecords') in syncfusion gantt when collapsing a group
I got an error when collapsing groups in the syncfusion gant. I could reproduce it here with my own set of data (stackblitz).

The error full message :

TypeError: Cannot read properties of undefined (reading 'childRecords')

```<code> at e.expandCollapseChartRows (constant.js:13:25)
 at e.expandCollapseChartRows (constant.js:13:25)
 at e.collapsedGanttRow (constant.js:13:25)
 at e.collapsed (constant.js:13:25)
 at e.notify (dom.js:466:34)
 at d.e.trigger (dom.js:466:34)
 at eval (constant.js:130:22)
 at e.notify (dom.js:466:34)
 at d.e.trigger (dom.js:466:34)
 at d.collapseRow (constant.js:130:22)
</code>```

A screenshot showing the collapse action :

The error occurs only when there are two nested grouping levels which i think is allowed in the syncfusion gantt (right?)

答: This issue occurs because the TaskID values in your data are not unique. The TaskID field acts as the primary key field in the Gantt. Hence, it should be unique for every record. Please ensure that the TaskID field is unique for every record in your data to avoid this issue.</p>

Body:
I got an error when collapsing groups in the syncfusion gant. I could reproduce it here with my own set of data (stackblitz).

The error full message :

TypeError: Cannot read properties of undefined (reading 'childRecords')

 at e.expandCollapseChartRows (constant.js:13:25)
 at e.expandCollapseChartRows (constant.js:13:25)
 at e.collapsedGanttRow (constant.js:13:25)
 at e.collapsed (constant.js:13:25)
 at e.notify (dom.js:466:34)
 at d.e.trigger (dom.js:466:34)
 at eval (constant.js:130:22)
 at e.notify (dom.js:466:34)
 at d.e.trigger (dom.js:466:34)
 at d.collapseRow (constant.js:130:22)

A screenshot showing the collapse action :

The error occurs only when there are two nested grouping levels which i think is allowed in the syncfusion gantt (right?)


问:
how do I troubleshoot fatal errors for simple commands: recursive gc invocation error after library()
I'm getting an error for "recursive gc invocation" just loading some packages. If I set my code to run further, this error continues to pop out throughout, and R studio experiences a fatal error and aborts. I do not know how to trouble shoot this to fix it.

I have already tried to restart the program, but get the same error in the same place. This happens even if I restart the program, close the project, and try again in a new / blank script. The error is shown below.

What are appropriate steps at this juncture? Should I uninstall /reinstall R? Is there a better way to try to pinpoint what is going wrong?

This is what I get in the console when I load these two libraries:

```<code>> library(descr)
> library(data.table)
*** recursive gc invocation
*** recursive gc invocation
*** recursive gc invocation
data.table 1.14.2 using 4 threads (see ?getDTthreads).  Latest news: r-datatable.com
</code>```

I included session info if that helps, but honestly I'm not really sure where to begin trouble shooting this.

```<code>> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] beepr_1.3         nngeo_0.4.4       stringr_1.4.0     bit64_4.0.5       bit_4.0.4         sf_1.0-5          data.table_1.14.2 descr_1.1.5

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.7         magrittr_2.0.1     units_0.7-2        xtable_1.8-4       R6_2.5.1           rlang_0.4.12       tools_4.1.2        grid_4.1.2
 [9] audio_0.1-10       KernSmooth_2.23-20 e1071_1.7-9        DBI_1.1.2          ellipsis_0.3.2     class_7.3-19       lifecycle_1.0.1    vctrs_0.3.8
[17] glue_1.6.0         stringi_1.7.6      proxy_0.4-26       compiler_4.1.2     generics_0.1.1     classInt_0.4-3
</code>```

答:
I've had the same problem.
Loading data.table and then having those recursive gc invocation.
I have found it to be very close in nature to this issue:
https://github.com/rstudio/rstudio/issues/10565

no fixes yet, but seems to be an Rstudio Ghost Orchid issue

Body:
I'm getting an error for "recursive gc invocation" just loading some packages. If I set my code to run further, this error continues to pop out throughout, and R studio experiences a fatal error and aborts. I do not know how to trouble shoot this to fix it.

I have already tried to restart the program, but get the same error in the same place. This happens even if I restart the program, close the project, and try again in a new / blank script. The error is shown below.

What are appropriate steps at this juncture? Should I uninstall /reinstall R? Is there a better way to try to pinpoint what is going wrong?

This is what I get in the console when I load these two libraries:

> library(descr)
> library(data.table)
*** recursive gc invocation
*** recursive gc invocation
*** recursive gc invocation
data.table 1.14.2 using 4 threads (see ?getDTthreads).  Latest news: r-datatable.com

I included session info if that helps, but honestly I'm not really sure where to begin trouble shooting this.

> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] beepr_1.3         nngeo_0.4.4       stringr_1.4.0     bit64_4.0.5       bit_4.0.4         sf_1.0-5          data.table_1.14.2 descr_1.1.5

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.7         magrittr_2.0.1     units_0.7-2        xtable_1.8-4       R6_2.5.1           rlang_0.4.12       tools_4.1.2        grid_4.1.2
 [9] audio_0.1-10       KernSmooth_2.23-20 e1071_1.7-9        DBI_1.1.2          ellipsis_0.3.2     class_7.3-19       lifecycle_1.0.1    vctrs_0.3.8
[17] glue_1.6.0         stringi_1.7.6      proxy_0.4-26       compiler_4.1.2     generics_0.1.1     classInt_0.4-3


问:
How to deploy dockerised react + django web app to google app engine?
I have created a web app which uses react as frontend and django as backend. I have also added nginx proxy to my both backend and frontend. I use docker compose to build and start all of my containers and everything works perfectly.

Now i want to deploy it to google app engine and I have no idea how to do that. I found this well written article, but it uses aws. I want to use app engine because its free (for now).

It would be really helpful if someone could guide me through this.

答: App engine supports specific runtimes, not dockerized applications. You would need to deploy a python app engine app for the Django backend and a nodejs app for the react app.</p>


问:
How to remove Model-Markers in MonacoEditor
Currently, I'm trying to remove model-markers from a Monaco-Model with the following approach.

```<code>    monac.editor.getModelMarkers({owner: "owner"}).forEach(marker => {
      console.log(marker)
      marker.dispose()
    })
</code>```

Markers currently are set through the setModelMarker() method

```<code>monaco.editor.setModelMarkers(editor.getModel(), "owner", markers)
</code>```

Setting an empty array to the Model override the model-markers, so this could be used as a workaround.

```<code>monaco.editor.setModelMarkers(editor.getModel(), "owner", [])
</code>```

Is there any way how I could reliably remove model-markers

答:
As pointed out in the comments, getModelMarkers() returns an array of IMarker, which do not have a dispose() method.

For any modification of the marker set, setModelMarkers() is the way.

The main explanation is that IMarkers are just interface object, which must thus have fields like severity, startLineNumber, etc.

The Monaco editor uses a single setModelMarkers() method to update the marker set, as any modification of these objects after calling the method will have no effect:

var markers = [{
    severity: monaco.MarkerSeverity.Warning,
    message: "Some warning",
    startLineNumber: 1,
    startColumn: 1,
    endLineNumber: 1,
    endColumn: editor.getModel().getLineLength(1) + 1
}];
monaco.editor.setModelMarkers(editor.getModel(), "owner", markers);
markers[0].severity = monaco.MarkerSeverity.Error; // No effect
```

With the same idea, you cannot delete a marker (with delete markers[0]; for example), as the delete operator deletes only a reference.

Body:
Currently, I'm trying to remove model-markers from a Monaco-Model with the following approach.

    monac.editor.getModelMarkers({owner: "owner"}).forEach(marker => {
      console.log(marker)
      marker.dispose()
    })

Markers currently are set through the setModelMarker() method

monaco.editor.setModelMarkers(editor.getModel(), "owner", markers)

Setting an empty array to the Model override the model-markers, so this could be used as a workaround.

monaco.editor.setModelMarkers(editor.getModel(), "owner", [])

Is there any way how I could reliably remove model-markers

Body:
As pointed out in the comments, getModelMarkers() returns an array of IMarker, which do not have a dispose() method.

For any modification of the marker set, setModelMarkers() is the way.

The main explanation is that IMarkers are just interface object, which must thus have fields like severity, startLineNumber, etc.

The Monaco editor uses a single setModelMarkers() method to update the marker set, as any modification of these objects after calling the method will have no effect:

var markers = [{
    severity: monaco.MarkerSeverity.Warning,
    message: "Some warning",
    startLineNumber: 1,
    startColumn: 1,
    endLineNumber: 1,
    endColumn: editor.getModel().getLineLength(1) + 1
}];
monaco.editor.setModelMarkers(editor.getModel(), "owner", markers);
markers[0].severity = monaco.MarkerSeverity.Error; // No effect

With the same idea, you cannot delete a marker (with delete markers[0]; for example), as the delete operator deletes only a reference.