问:
How do I escape quotes in an msdeploy post sync command that is executing a powershell script?
I am attempting to setup a Cake task that will use MsDeploy to sync a powershell script to a remote server and then execute that script as a post sync command.

The problem I'm facing is finding a combination of quotes and escapes within the cake file that allow the command to make it all the way to powershell with the file path quoted correctly to allow powershell to find the script; the path has spaces in it.

This appears to be so difficult because of the chain of execution that this command goes through at run time.
First because this is written in C# the string either needs to be verbatim (@"command here") or to have all internal double quotes escaped with \.

Next Cake performs several operations on the arguments, though none seemed to affect things like quoting and escaping until it actually got to the execution, at which point it uses the C# Process.Start() static method to run the MsDeploy executable. In my reading it was suggested that this method of running a command requires three double quotes to be properly escaped, though that didn't mesh with what I was seeing when I tried.

Then once on the remote machine MsDeploy uses CMD.exe to execute the command which notably has no support for single quotes so double quotes either needed to be escaped by using \" or "".

The closest I have gotten looks like this:

```<code>Task("InitializeIISApplication")
    .IsDependentOn("InjectVariables")
    .Does(() => {
        MsDeploy(new MsDeploySettings
        {
            Verb = Operation.Sync,
            RetryAttempts = 3,
            RetryInterval = 10000,
            Source = new FilePathProvider
            {
                Direction = Direction.source,
                Path = MakeAbsolute(File(@".\MyPowershell.ps1")).ToString()
            },
            Destination = new FilePathProvider
            {
                Direction = Direction.dest,
                Path = File(deployParameters.ApplicationDestinationPath + @"\MyPowershell.ps1").ToString(),
                Username = deployParameters.MsDeployUserName,
                Password = deployParameters.MsDeployUserPassword,
                WebManagementService = deployParameters.DeploymentTargetUrl
            },
            AllowUntrusted = true,
            EnableRules = new List<string> {
                "DoNotDeleteRule"
            },
            PostSyncCommand = new CommandProvider {
                AppendQuotesToPath = false,
                Direction = Direction.dest,
                Path = $"powershell -file '{deployParameters.ApplicationDestinationPath}\\MyPowershell.ps1' ",
            }
        });

        MsDeploy(new MsDeploySettings
        {
            Verb = Operation.Delete,
            Destination = new FilePathProvider
            {
                Direction = Direction.dest,
                Path = File(deployParameters.ApplicationDestinationPath + "\MyPowershell.ps1").ToString(),
                Username = deployParameters.MsDeployUserName,
                Password = deployParameters.MsDeployUserPassword,
                WebManagementService = deployParameters.DeploymentTargetUrl
            },
            AllowUntrusted = true
        });
    });
</code>```

The task dependency is just setting up the deployParameters object.

Which with Cake's Diagnostic verbosity enabled produces the following command into the logs (new lines added for clarity):

```<code>"C:/Program Files/IIS/Microsoft Web Deploy V3/msdeploy.exe"
-verb:sync
-source:filePath="Y:/PathToBuildArtifact/Deploy/MyPowershell.ps1"
-dest:filePath="C:/Application - With Spaces/MyPowershell.ps1",wmsvc="https://deploy-server/msdeploy.axd",userName=msdeployuser,password=********
-enableRule:DoNotDeleteRule
-retryAttempts:3
-retryInterval:10000
-allowUntrusted
-postSync:runCommand="powershell -file 'C:\Application - With Spaces\MyPowershell.ps1' "
</code>```

Then ends with the error:

Warning: Processing -File ''C:/Application' failed: The given path's format is not supported. Specify a valid path for the -File parameter.

Any variant I've tried using double quotes inside the postSync command instead results in this error:

Error: Unrecognized argument '-'.

If it matters this is being done on the Bamboo CI server.

答:
Using PowerShell's -File CLI parameter requires use of " as the - only supported - quote character.

(By contrast, using -Command instructs PowerShell to treat the rest of the command line as if it were PowerShell source code, in which case ' is recognized as a quote character, for strings with literal contents[1]).

Since your PowerShell command line becomes a double-quoted argument to another command that is ultimately passed to cmd.exe, you must additionally, \-escape the " chars.

Therefore, the following should work [update: but doesn't - see comments]:

Path = $@"powershell -file \""{deployParameters.ApplicationDestinationPath}\MyPowershell.ps1\""",
```

[1] -File requires a double-quoted script-file argument, and all remaining arguments are treated as literals.

By contrast, -Command (which is the implied option in Windows PowerShell, whereas in PowerShell Core it is now -File) space-concatenates all remaining arguments and treats the result as PowerShell code, which implies that single-quoted arguments are supported too, with individually double-quoted arguments having their quotes stripped before concatenation.

Body:
I am attempting to setup a Cake task that will use MsDeploy to sync a powershell script to a remote server and then execute that script as a post sync command.

The problem I'm facing is finding a combination of quotes and escapes within the cake file that allow the command to make it all the way to powershell with the file path quoted correctly to allow powershell to find the script; the path has spaces in it.

This appears to be so difficult because of the chain of execution that this command goes through at run time.
First because this is written in C# the string either needs to be verbatim (@"command here") or to have all internal double quotes escaped with \.

Next Cake performs several operations on the arguments, though none seemed to affect things like quoting and escaping until it actually got to the execution, at which point it uses the C# Process.Start() static method to run the MsDeploy executable. In my reading it was suggested that this method of running a command requires three double quotes to be properly escaped, though that didn't mesh with what I was seeing when I tried.

Then once on the remote machine MsDeploy uses CMD.exe to execute the command which notably has no support for single quotes so double quotes either needed to be escaped by using \" or "".

The closest I have gotten looks like this:

Task("InitializeIISApplication")
    .IsDependentOn("InjectVariables")
    .Does(() => {
        MsDeploy(new MsDeploySettings
        {
            Verb = Operation.Sync,
            RetryAttempts = 3,
            RetryInterval = 10000,
            Source = new FilePathProvider
            {
                Direction = Direction.source,
                Path = MakeAbsolute(File(@".\MyPowershell.ps1")).ToString()
            },
            Destination = new FilePathProvider
            {
                Direction = Direction.dest,
                Path = File(deployParameters.ApplicationDestinationPath + @"\MyPowershell.ps1").ToString(),
                Username = deployParameters.MsDeployUserName,
                Password = deployParameters.MsDeployUserPassword,
                WebManagementService = deployParameters.DeploymentTargetUrl
            },
            AllowUntrusted = true,
            EnableRules = new List<string> {
                "DoNotDeleteRule"
            },
            PostSyncCommand = new CommandProvider {
                AppendQuotesToPath = false,
                Direction = Direction.dest,
                Path = $"powershell -file '{deployParameters.ApplicationDestinationPath}\\MyPowershell.ps1' ",
            }
        });

        MsDeploy(new MsDeploySettings
        {
            Verb = Operation.Delete,
            Destination = new FilePathProvider
            {
                Direction = Direction.dest,
                Path = File(deployParameters.ApplicationDestinationPath + "\MyPowershell.ps1").ToString(),
                Username = deployParameters.MsDeployUserName,
                Password = deployParameters.MsDeployUserPassword,
                WebManagementService = deployParameters.DeploymentTargetUrl
            },
            AllowUntrusted = true
        });
    });

The task dependency is just setting up the deployParameters object.

Which with Cake's Diagnostic verbosity enabled produces the following command into the logs (new lines added for clarity):

"C:/Program Files/IIS/Microsoft Web Deploy V3/msdeploy.exe"
-verb:sync
-source:filePath="Y:/PathToBuildArtifact/Deploy/MyPowershell.ps1"
-dest:filePath="C:/Application - With Spaces/MyPowershell.ps1",wmsvc="https://deploy-server/msdeploy.axd",userName=msdeployuser,password=********
-enableRule:DoNotDeleteRule
-retryAttempts:3
-retryInterval:10000
-allowUntrusted
-postSync:runCommand="powershell -file 'C:\Application - With Spaces\MyPowershell.ps1' "

Then ends with the error:

Warning: Processing -File ''C:/Application' failed: The given path's format is not supported. Specify a valid path for the -File parameter.

Any variant I've tried using double quotes inside the postSync command instead results in this error:

Error: Unrecognized argument '-'.

If it matters this is being done on the Bamboo CI server.

Body:
Using PowerShell's -File CLI parameter requires use of " as the - only supported - quote character.

(By contrast, using -Command instructs PowerShell to treat the rest of the command line as if it were PowerShell source code, in which case ' is recognized as a quote character, for strings with literal contents[1]).

Since your PowerShell command line becomes a double-quoted argument to another command that is ultimately passed to cmd.exe, you must additionally, \-escape the " chars.

Therefore, the following should work [update: but doesn't - see comments]:

Path = $@"powershell -file \""{deployParameters.ApplicationDestinationPath}\MyPowershell.ps1\""",

[1] -File requires a double-quoted script-file argument, and all remaining arguments are treated as literals.

By contrast, -Command (which is the implied option in Windows PowerShell, whereas in PowerShell Core it is now -File) space-concatenates all remaining arguments and treats the result as PowerShell code, which implies that single-quoted arguments are supported too, with individually double-quoted arguments having their quotes stripped before concatenation.


来源: stackexchange

问:
RegEx for replacing part of a string in R
I am trying to do an exact pattern match using the gsub/sub and replace function. I am not getting the desired response. I am trying to remove the .x and .y from the names without affecting other names.

```<code>name = c("company", "deriv.x", "isConfirmed.y")
new.name = gsub(".x$|.y$", "", name)
new.name
[1] "compa"       "deriv"       "isConfirmed"
</code>```

company has become compa.

I have also tried

```<code>remove = c(".x", ".y")
replace(name, name %in% remove, "")
[1] "company"    "deriv.x"    "isConfirmed.y"
</code>```

I would like the outcome to be.
"company", "deriv", "isConfirmed"

How do I solve this problem?

答:
In a regex, . represents "any character". In order to recognize literal . characters, you need to escape the character, like so:

```<code>name <- c("company", "deriv.x", "isConfirmed.y")
new.name <- gsub("\\.x$|\\.y$", "", name)
new.name

[1] "company"     "deriv"       "isConfirmed"
</code>```

This explains why in your original example, "company" was being transformed to "compa" (deleting the "any character of 'n', followed by a 'y' and end of string").

Onyambu's comment would also work, since within the [ ] portion of a regex, . is interpreted literally.

```<code>gsub("[.](x|y)$", "", name)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do an exact pattern match using the gsub/sub and replace function. I am not getting the desired response. I am trying to remove the .x and .y from the names without affecting other names.

name = c("company", "deriv.x", "isConfirmed.y")
new.name = gsub(".x$|.y$", "", name)
new.name
[1] "compa"       "deriv"       "isConfirmed"

company has become compa.

I have also tried

remove = c(".x", ".y")
replace(name, name %in% remove, "")
[1] "company"    "deriv.x"    "isConfirmed.y"

I would like the outcome to be.
"company", "deriv", "isConfirmed"

How do I solve this problem?

Body:
In a regex, . represents "any character". In order to recognize literal . characters, you need to escape the character, like so:

name <- c("company", "deriv.x", "isConfirmed.y")
new.name <- gsub("\\.x$|\\.y$", "", name)
new.name

[1] "company"     "deriv"       "isConfirmed"

This explains why in your original example, "company" was being transformed to "compa" (deleting the "any character of 'n', followed by a 'y' and end of string").

Onyambu's comment would also work, since within the [ ] portion of a regex, . is interpreted literally.

gsub("[.](x|y)$", "", name)


问:
Stretching images when using as background image
I was trying to set an image as background image for my django application. But when i set it, it is getting displayed as tiled image. ie without actually stretching the image, same image is tiled and shown 4 times. Can somebody tell me how to stretch the image and set it as a background image. I will paste my code here. I am sure some attribute must be there setting this, which i couldnt find on googling.</p>

```<code><body bgcolor=" #408080" background="/static/paper.jpg" background-size: 100%; >
</code>```

答:
In short: no, you can't stretch the background image with html/css1/css2, you're only options is to either use css3 ( witch is not fully suported by all browsers ) or to use background-attachment and background-repeat css porperties to achieve an alternative result …

Another option would be to use an img tag as a background using z-index css proprety however you'll find it dificult to get it working proprely in all major browsers .

ContentLicense: CC BY-SA 3.0


问:
how does javascript async works with cycles?
I'm trying to understand how async working in javascript. and i cant handle 1 thing, that create async: async function with other promises generators and callbacks, or webAPI?

Here's a code. If i'am using settimeout function all works correctly but if i using a cycle something works unpredictable; then i using settimeout result showing 1 by 1 with timeout, but with a cycle result showing at the same time

```<code>function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep() {
  console.time("abc");
  await timeout(3000);
  console.timeEnd("abc");
}

sleep();

console.time();
var z = 1;
for (let i = 1; i < 10000; i++) {
  for (let j = 1; j < 10000; j++) {
    z *= j;
  }
  z *= i;
}
console.timeEnd();

//second var

function second(ms) {
  return new Promise(resolve => {
    var z = 1;
    for (let i = 1; i < 50000; i++) {
      for (let j = 1; j < 50000; j++) {
        z *= j;
      }
      z *= i;
    }
    resolve();
  });
}

// function timeout(ms) {
//   return new Promise(resolve => setTimeout(resolve, ms));
// }
async function sleep() {
  console.time("abc");
  await second();
  console.timeEnd("abc");
}

sleep();

console.time();
var z = 1;
for (let i = 1; i < 10000; i++) {
  for (let j = 1; j < 10000; j++) {
    z *= j;
  }
  z *= i;
}
console.timeEnd();

</code>```

//first result showing 1 by 1 with timeout

default: 932.822998046875ms

abc: 3000.555908203125ms

//second result showing at the same time

default: 913.716064453125ms

abc: 4396.77490234375ms

答: The normal for loops that you are using do not wait for Promise's to resolve before moving to the next iteration. You can either use a library like bluebird, which is optimized for promise handling, especially with collections, or use the for (i in arr){} loop.

Body:
I'm trying to understand how async working in javascript. and i cant handle 1 thing, that create async: async function with other promises generators and callbacks, or webAPI?

Here's a code. If i'am using settimeout function all works correctly but if i using a cycle something works unpredictable; then i using settimeout result showing 1 by 1 with timeout, but with a cycle result showing at the same time

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep() {
  console.time("abc");
  await timeout(3000);
  console.timeEnd("abc");
}

sleep();

console.time();
var z = 1;
for (let i = 1; i < 10000; i++) {
  for (let j = 1; j < 10000; j++) {
    z *= j;
  }
  z *= i;
}
console.timeEnd();

//second var

function second(ms) {
  return new Promise(resolve => {
    var z = 1;
    for (let i = 1; i < 50000; i++) {
      for (let j = 1; j < 50000; j++) {
        z *= j;
      }
      z *= i;
    }
    resolve();
  });
}

// function timeout(ms) {
//   return new Promise(resolve => setTimeout(resolve, ms));
// }
async function sleep() {
  console.time("abc");
  await second();
  console.timeEnd("abc");
}

sleep();

console.time();
var z = 1;
for (let i = 1; i < 10000; i++) {
  for (let j = 1; j < 10000; j++) {
    z *= j;
  }
  z *= i;
}
console.timeEnd();

//first result showing 1 by 1 with timeout

default: 932.822998046875ms

abc: 3000.555908203125ms

//second result showing at the same time

default: 913.716064453125ms

abc: 4396.77490234375ms


问:
Build Fails With Spread Operator on Travis CI Only
my build, npm run build, for my website works locally, but on Travis CI it fails with the following error:

```<code>> node scripts/build.js
/home/travis/build/PatrickDuncan/patrickduncan.github.io/node_modules/@hapi/hoek/lib/deep-equal.js:39
    options = { prototype: true, ...options };
                                 ^^^
SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/travis/build/PatrickDuncan/patrickduncan.github.io/node_modules/@hapi/hoek/lib/index.js:9:19)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
</code>```

I have babel-preset-stage-3 in my package.json, so I don't know what the issue is. I have no extraneous packages installed either.

package.json:

```<code>{
  "name": "personal_website",
  "homepage": "http://patrickduncan.co",
  "private": true,
  "dependencies": {
    "@babel/core": "7.4.3",
    "@babel/plugin-proposal-object-rest-spread": "^7.4.4",
    "@svgr/webpack": "4.1.0",
    "@typescript-eslint/eslint-plugin": "1.6.0",
    "@typescript-eslint/parser": "1.6.0",
    "babel-eslint": "10.0.1",
    "babel-jest": "^24.8.0",
    "babel-loader": "8.0.5",
    "babel-plugin-named-asset-import": "^0.3.2",
    "babel-preset-react-app": "^9.0.0",
    "babel-preset-stage-3": "^6.24.1",
    "camelcase": "^5.2.0",
    "case-sensitive-paths-webpack-plugin": "2.2.0",
    "chai": "^4.2.0",
    "css-loader": "2.1.1",
    "dotenv": "6.2.0",
    "dotenv-expand": "4.2.0",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.13.1",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-react-app": "^4.0.1",
    "eslint-loader": "2.1.2",
    "eslint-plugin-flowtype": "2.50.1",
    "eslint-plugin-import": "2.16.0",
    "eslint-plugin-jsx-a11y": "6.2.1",
    "eslint-plugin-react": "7.12.4",
    "eslint-plugin-react-hooks": "^1.5.0",
    "file-loader": "3.0.1",
    "fs-extra": "7.0.1",
    "html-webpack-plugin": "4.0.0-beta.5",
    "identity-obj-proxy": "3.0.0",
    "is-wsl": "^1.1.0",
    "jest": "24.7.1",
    "jest-environment-jsdom-fourteen": "0.1.0",
    "jest-resolve": "24.7.1",
    "jest-watch-typeahead": "0.3.0",
    "mini-css-extract-plugin": "0.5.0",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "pnp-webpack-plugin": "1.2.1",
    "postcss-flexbugs-fixes": "4.1.0",
    "postcss-loader": "3.0.0",
    "postcss-normalize": "7.0.1",
    "postcss-preset-env": "6.6.0",
    "postcss-safe-parser": "4.0.1",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-app-polyfill": "^1.0.1",
    "react-dev-utils": "^9.0.1",
    "react-dom": "^16.8.6",
    "react-icons": "^3.7.0",
    "react-motion": "^0.5.2",
    "react-scrollchor": "^6.0.0",
    "resolve": "1.10.0",
    "sass-loader": "7.1.0",
    "semver": "6.0.0",
    "style-loader": "0.23.1",
    "terser-webpack-plugin": "1.2.3",
    "ts-pnp": "1.1.2",
    "typescript": "^3.4.5",
    "underscore": "^1.9.1",
    "url-loader": "1.1.2",
    "victory": "^32.2.3",
    "webpack": "4.29.6",
    "webpack-dev-server": "3.2.1",
    "webpack-manifest-plugin": "2.0.4",
    "workbox-webpack-plugin": "4.2.0"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "beforeDeploy": "node scripts/beforeDeploy.js",
    "test": "node scripts/test.js --env=jsdom",
    "lint": "./node_modules/.bin/eslint src/*.js* src/*/*.js* src/*/*/*.js*"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "setupFilesAfterEnv": [
      "./scripts/setupTests.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jest-environment-jsdom-fourteen",
    "transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "modulePaths": [],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ],
    "watchPlugins": [
      "jest-watch-typeahead/filename",
      "jest-watch-typeahead/testname"
    ]
  },
  "babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      "@babel/plugin-proposal-object-rest-spread"
    ]
  }
}
</code>```

node v10.15.1

npm v6.4.1

答:
```<code>node_js:
 - "lts/*"
</code>```

Change your node version in your .travis.yml to use lts and that should resolve it.

Body:
my build, npm run build, for my website works locally, but on Travis CI it fails with the following error:

> node scripts/build.js
/home/travis/build/PatrickDuncan/patrickduncan.github.io/node_modules/@hapi/hoek/lib/deep-equal.js:39
    options = { prototype: true, ...options };
                                 ^^^
SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/travis/build/PatrickDuncan/patrickduncan.github.io/node_modules/@hapi/hoek/lib/index.js:9:19)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)

I have babel-preset-stage-3 in my package.json, so I don't know what the issue is. I have no extraneous packages installed either.

package.json:

{
  "name": "personal_website",
  "homepage": "http://patrickduncan.co",
  "private": true,
  "dependencies": {
    "@babel/core": "7.4.3",
    "@babel/plugin-proposal-object-rest-spread": "^7.4.4",
    "@svgr/webpack": "4.1.0",
    "@typescript-eslint/eslint-plugin": "1.6.0",
    "@typescript-eslint/parser": "1.6.0",
    "babel-eslint": "10.0.1",
    "babel-jest": "^24.8.0",
    "babel-loader": "8.0.5",
    "babel-plugin-named-asset-import": "^0.3.2",
    "babel-preset-react-app": "^9.0.0",
    "babel-preset-stage-3": "^6.24.1",
    "camelcase": "^5.2.0",
    "case-sensitive-paths-webpack-plugin": "2.2.0",
    "chai": "^4.2.0",
    "css-loader": "2.1.1",
    "dotenv": "6.2.0",
    "dotenv-expand": "4.2.0",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.13.1",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-react-app": "^4.0.1",
    "eslint-loader": "2.1.2",
    "eslint-plugin-flowtype": "2.50.1",
    "eslint-plugin-import": "2.16.0",
    "eslint-plugin-jsx-a11y": "6.2.1",
    "eslint-plugin-react": "7.12.4",
    "eslint-plugin-react-hooks": "^1.5.0",
    "file-loader": "3.0.1",
    "fs-extra": "7.0.1",
    "html-webpack-plugin": "4.0.0-beta.5",
    "identity-obj-proxy": "3.0.0",
    "is-wsl": "^1.1.0",
    "jest": "24.7.1",
    "jest-environment-jsdom-fourteen": "0.1.0",
    "jest-resolve": "24.7.1",
    "jest-watch-typeahead": "0.3.0",
    "mini-css-extract-plugin": "0.5.0",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "pnp-webpack-plugin": "1.2.1",
    "postcss-flexbugs-fixes": "4.1.0",
    "postcss-loader": "3.0.0",
    "postcss-normalize": "7.0.1",
    "postcss-preset-env": "6.6.0",
    "postcss-safe-parser": "4.0.1",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-app-polyfill": "^1.0.1",
    "react-dev-utils": "^9.0.1",
    "react-dom": "^16.8.6",
    "react-icons": "^3.7.0",
    "react-motion": "^0.5.2",
    "react-scrollchor": "^6.0.0",
    "resolve": "1.10.0",
    "sass-loader": "7.1.0",
    "semver": "6.0.0",
    "style-loader": "0.23.1",
    "terser-webpack-plugin": "1.2.3",
    "ts-pnp": "1.1.2",
    "typescript": "^3.4.5",
    "underscore": "^1.9.1",
    "url-loader": "1.1.2",
    "victory": "^32.2.3",
    "webpack": "4.29.6",
    "webpack-dev-server": "3.2.1",
    "webpack-manifest-plugin": "2.0.4",
    "workbox-webpack-plugin": "4.2.0"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "beforeDeploy": "node scripts/beforeDeploy.js",
    "test": "node scripts/test.js --env=jsdom",
    "lint": "./node_modules/.bin/eslint src/*.js* src/*/*.js* src/*/*/*.js*"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "setupFilesAfterEnv": [
      "./scripts/setupTests.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jest-environment-jsdom-fourteen",
    "transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "modulePaths": [],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ],
    "watchPlugins": [
      "jest-watch-typeahead/filename",
      "jest-watch-typeahead/testname"
    ]
  },
  "babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      "@babel/plugin-proposal-object-rest-spread"
    ]
  }
}

node v10.15.1

npm v6.4.1

Body:
node_js:
 - "lts/*"

Change your node version in your .travis.yml to use lts and that should resolve it.


问:
How do you cast integer in Rust to char* in C
I have the following use case. A struct in C looks like this:

```<code>typedef struct _zend_internal_arg_info {
    const char *name;
    zend_type type;
    zend_uchar pass_by_reference;
    zend_bool is_variadic;
} zend_internal_arg_info;
</code>```

Normally the name field contains a function name. But due to internal implementation this field can also carry an integer. On C end there is a macro doing the casting like this:

```<code>(const char*)(unsigned long int)(1)
</code>```

What I want to do is to do the same cast on Rust end. I ended up with the following code:

```<code>fn create_null_argument(required_args: u8, return_reference: bool) -> ZendFunctionArgument {
    let required_args_ref = Box::into_raw(Box::new(required_args as i8)) as *const i8;
    ZendFunctionArgument {
        arg: php_bindings::_zend_internal_arg_info {
            name: required_args_ref,
            type_: 0,
            pass_by_reference: if return_reference { 1 } else { 0 },
            is_variadic: 0,
        },
    }
}
</code>```

This seem to work with the following test:

```<code>let arguments_ptr = ZendFunctionArguments::new(5, true).into_raw();
unsafe {
    let arguments: Vec<php_bindings::_zend_internal_arg_info> = Vec::from_raw_parts(arguments_ptr as *mut _, 1, 1);
    let required_args = *arguments[0].name;
    assert_eq!(5, required_args);
}
</code>```

Unfortunatelly on PHP end (when the code is executed) the value is totally random on every execution.
What I want to ask here is whether the way I am casting the i8 is correct comparing to the casting on C end ((const char*)(unsigned long int)(1))?

---- EDIT -----

Some more details. Generated PHP binding:

```<code>#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _zend_internal_arg_info {
    pub name: *const ::std::os::raw::c_char,
    pub type_: zend_type,
    pub pass_by_reference: zend_uchar,
    pub is_variadic: zend_bool,
}
</code>```

Here an unused struct with some description of this twisted logic:

```<code>/* the following structure repeats the layout of zend_internal_arg_info,
 * but its fields have different meaning. It's used as the first element of
 * arg_info array to define properties of internal functions.
 * It's also used for the return type.
 */
typedef struct _zend_internal_function_info {
    zend_uintptr_t required_num_args;
    zend_type type;
    zend_bool return_reference;
    zend_bool _is_variadic;
} zend_internal_function_info;
</code>```

Here is the whole macro beig used mormally in c:

```<code>#define ZEND_BEGIN_ARG_INFO_EX(name, _unused, return_reference, required_num_args)  \
    static const zend_internal_arg_info name[] = { \
        { (const char*)(zend_uintptr_t)(required_num_args), 0, return_reference, 0 },
</code>```

And zend_uintptr_t is:

```<code>typedef uintptr_t zend_uintptr_t;
</code>```

and then:

```<code>typedef unsigned long int   uintptr_t;
</code>```

and the struct:

```<code>pub struct ZendFunctionArgument {
    arg: php_bindings::_zend_internal_arg_info,
}
</code>```

答:
Your code is not converting an integer to a pointer - as Stargateur says in the comments, the correct way to do that is more simply required_args as *const ::std::os::raw::c_char.

Instead, you are allocating required_args on the heap with Box::new, and then taking it out of the hands of the memory manager with into_raw - giving a pointer to the value of required_args, which, until you manually clean it up, will live forever.

This seem to work with the following test

Because you are dereferencing the pointer into the heap by doing *arguments[0].name, and the value at that pointer is indeed 5.

Unfortunatelly on PHP end (when the code is executed) the value is totally random on every execution.

This is unsurprising. Since the end result of your code is that the value of the field is just some pointer into the heap, it will change every time you run the code.

Body:
I have the following use case. A struct in C looks like this:

typedef struct _zend_internal_arg_info {
    const char *name;
    zend_type type;
    zend_uchar pass_by_reference;
    zend_bool is_variadic;
} zend_internal_arg_info;

Normally the name field contains a function name. But due to internal implementation this field can also carry an integer. On C end there is a macro doing the casting like this:

(const char*)(unsigned long int)(1)

What I want to do is to do the same cast on Rust end. I ended up with the following code:

fn create_null_argument(required_args: u8, return_reference: bool) -> ZendFunctionArgument {
    let required_args_ref = Box::into_raw(Box::new(required_args as i8)) as *const i8;
    ZendFunctionArgument {
        arg: php_bindings::_zend_internal_arg_info {
            name: required_args_ref,
            type_: 0,
            pass_by_reference: if return_reference { 1 } else { 0 },
            is_variadic: 0,
        },
    }
}

This seem to work with the following test:

let arguments_ptr = ZendFunctionArguments::new(5, true).into_raw();
unsafe {
    let arguments: Vec<php_bindings::_zend_internal_arg_info> = Vec::from_raw_parts(arguments_ptr as *mut _, 1, 1);
    let required_args = *arguments[0].name;
    assert_eq!(5, required_args);
}

Unfortunatelly on PHP end (when the code is executed) the value is totally random on every execution.
What I want to ask here is whether the way I am casting the i8 is correct comparing to the casting on C end ((const char*)(unsigned long int)(1))?

---- EDIT -----

Some more details. Generated PHP binding:

#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _zend_internal_arg_info {
    pub name: *const ::std::os::raw::c_char,
    pub type_: zend_type,
    pub pass_by_reference: zend_uchar,
    pub is_variadic: zend_bool,
}

Here an unused struct with some description of this twisted logic:

/* the following structure repeats the layout of zend_internal_arg_info,
 * but its fields have different meaning. It's used as the first element of
 * arg_info array to define properties of internal functions.
 * It's also used for the return type.
 */
typedef struct _zend_internal_function_info {
    zend_uintptr_t required_num_args;
    zend_type type;
    zend_bool return_reference;
    zend_bool _is_variadic;
} zend_internal_function_info;

Here is the whole macro beig used mormally in c:

#define ZEND_BEGIN_ARG_INFO_EX(name, _unused, return_reference, required_num_args)  \
    static const zend_internal_arg_info name[] = { \
        { (const char*)(zend_uintptr_t)(required_num_args), 0, return_reference, 0 },

And zend_uintptr_t is:

typedef uintptr_t zend_uintptr_t;

and then:

typedef unsigned long int   uintptr_t;

and the struct:

pub struct ZendFunctionArgument {
    arg: php_bindings::_zend_internal_arg_info,
}


问:
How do you read a file inside a zip file as text, not bytes?
A simple program for reading a CSV file inside a ZIP archive:

import csv, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')

for row in csv.DictReader(items_file):
    pass
```
<p>works in Python 2.7:</p>
<pre class="lang-none prettyprint-override"><code>$ python2.7 test_zip_file_py3k.py ~/data.zip
$
</code>```

but not in Python 3.2:

$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
    File "test_zip_file_py3k.py", line 8, in <module>
    for row in csv.DictReader(items_file):
    File "/somedir/python3.2/csv.py", line 109, in __next__
    self.fieldnames
    File "/somedir/python3.2/csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)
```

The csv module in Python 3 wants to see a text file, but zipfile.ZipFile.open returns a zipfile.ZipExtFile that is always treated as binary data.

How does one make this work in Python 3?

答:
You can wrap it in a io.TextIOWrapper.

```<code>items_file  = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')
</code>```

Should work.

Body:
A simple program for reading a CSV file inside a ZIP archive:

import csv, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')

for row in csv.DictReader(items_file):
    pass

works in Python 2.7:

$ python2.7 test_zip_file_py3k.py ~/data.zip
$

but not in Python 3.2:

$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
    File "test_zip_file_py3k.py", line 8, in <module>
    for row in csv.DictReader(items_file):
    File "/somedir/python3.2/csv.py", line 109, in __next__
    self.fieldnames
    File "/somedir/python3.2/csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)

The csv module in Python 3 wants to see a text file, but zipfile.ZipFile.open returns a zipfile.ZipExtFile that is always treated as binary data.

How does one make this work in Python 3?

Body:
You can wrap it in a io.TextIOWrapper.

items_file  = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')

Should work.


问:
Call flask function with javascript
Trying to get some data from a flask function with javascript.
Currently i have a html form and a oninput so I can live update a result when a change occur.

Everything works in the code except the return of  {{ sentVal(request.args.get('rev'), request.args.get('lang')) }}. The code works though outside of the  but not inside. Why does this happen and how can I fix it?

```<code><script>
function refreshFunction() {
    document.getElementById("tonality").innerHTML = "Tonality: " + {{ sentVal(request.args.get('rev'), request.args.get('lang')) }};
}
</script>
</code>```

答:
This can be done using a context processor, which will make your python sentVal function available to your Jinja code.

```<code>@app.context_processor
def utility_processor():
    def sentVal(rev, lang):
        ...
</code>```

As per comments, if you're wanting to rerun the sentVal function, this will need to be converted to an ajax function (there are plenty of easy to find examples of this). But an overview:

In your html:

```<code>function refreshFunction() {
    var sentVal = // ajax call to your new route

    document.getElementById("tonality").innerHTML = "Tonality: " + sentval;
}
</code>```

and Flask:

```<code>@app.route('/sentVal'):
   return sentVal(request.args.get('rev'), request.args.get('lang'))
</code>```

This is a pretty basic outline, but hopefully you get the idea!

Title: Call flask function with javascript

Body:
This can be done using a context processor, which will make your python sentVal function available to your Jinja code.

@app.context_processor
def utility_processor():
    def sentVal(rev, lang):
        ...

As per comments, if you're wanting to rerun the sentVal function, this will need to be converted to an ajax function (there are plenty of easy to find examples of this). But an overview:

In your html:

function refreshFunction() {
    var sentVal = // ajax call to your new route

    document.getElementById("tonality").innerHTML = "Tonality: " + sentval;
}

and Flask:

@app.route('/sentVal'):
   return sentVal(request.args.get('rev'), request.args.get('lang'))

This is a pretty basic outline, but hopefully you get the idea!


问:
Getting AWS State machine execution ARN inside the step function
I need to get the ARN of the current execution for my state machine inside the state machine itself. Is it possible?

So can I create a state machine(say from a lambda function) and then take its execution ARN and pass it as a parameter to that machine OR is there any utility available inside the state machine that allows getting the execution ARN for that machine?

答:
AWS Step Functions released recently a feature called context object.

Now you have access to the execution data through $$ inside the Parameters block.

https://docs.aws.amazon.com/step-functions/latest/dg/input-output-contextobject.html


问:
How to write an algorithm that finds out in which lines specific word appear (I am using std::map)
I am writing code which calculate how many times each word appears in text ( I DID THIS TASK), but I can't find a way to calculate in which lines these words appeared.

I don't know where to start.

#include "header.h"
int main()
{
     //read the input, keeping track of each word and how often we see it
     std::ifstream in("tekstas.txt"); // input file

    std::string input;
    std::map<std::string, int> counters; // store each word and an associated counter
    std::vector<char>CharVect; // vector that stores symbols i want to replace
    formuojuChar(CharVect); // pushbacking that vector with symbols
     for (unsigned int i = 0; !in.eof(); i++)
    {
        std::getline(in, input);
        std::transform(input.begin(), input.end(), input.begin(), ::tolower); // lowering letters so for example "Mom"= "mom"
        Replace(input,CharVect, ' '); // replace symbols with space
        std::stringstream read(input);
        std::string word;
        while (read >> word)
        {
            ++counters[word];
        }
     }
     std::ofstream out("isvestis.txt");
    std::cout<<"Words that appear more than once in the text: "<<std::endl;
    std::cout<<std::endl;
     for (std::map<std::string, int>::const_iterator it = counters.begin();it != counters.end(); ++it)
        {
            if((it->second)>1)
            {

                std::cout<<"'" <<it->first<<"' " <<"appears "<<it->second <<" times in lines: " ;
                /*
                 ANY IDEAS ?
                 */
                std::cout<<std::endl;

            }
        }
        return 0;

}

```

I expect output to show me in which .txt file lines that word appears. TY

答:
The major issue with your approach is that you're using a second loop to gather the information on the words, and in doing so, you've lost all the information about which line(s) the words are on.

Instead of trying to figure out what line you're on in the second loop, you have all the information necessary on the current line in the first loop.  All you need is a variable that keeps track of each line.  You are using (incorrectly I may add), std::getline -- each time you call that function, you are going to the next line, thus you know implicitly what line you're on in the first loop.

First, you need to fix your read loop so that it reads lines correctly from a file:

```<code>std::string line;
while (std::getline(in, line))
{
//...
}
</code>```

Second, inside the while loop, you can determine all the information you need for the word, word count, and line(s) where the word is found.  You don't need two loops to do this.

Instead of a std::map<std::string, int>, which only knows about the word count, you could create a map that holds all the information -- the word count and the line(s) the word is found on.  Here is a map type that can hold this information:

std::map<std::string, std::pair<int, std::set<int>>>

The "second" of the map holds the information on the count, and a std::set that will hold all of the line numbers where the word is found.  The reason for the std::set is to guarantee that duplicate line numbers will not be stored.

Putting this all together, here is a sample program using this type:

```<code>#include <map>
#include <set>
#include <string>
#include <sstream>
#include <iostream>

// pair and map type
using WordInfo = std::pair<int, std::set<int>>;
using WordMap = std::map<std::string, WordInfo>;

int main()
{
    // our map
    WordMap wm;
    std::string line;

    // the line count
    int line_number = 1;
    while (std::getline(std::cin, line))
    {
        // line parser
        std::istringstream strm(line);
        std::string word;
        while ( strm >> word)
        {
            // we call map::insert, not `[ ]` to insert into a map
            auto pr = wm.insert({word, {0,std::set<int>()}});

            // the return value of map::insert gives us a pair, where the first is
            // an iterator to the item in the map
            auto& mapIter = pr.first;

            // increment the word count
            ++(mapIter->second.first);

            // insert the line number into the set
            mapIter->second.second.insert(line_number);
        }

        // increment the line counter
        ++line_number;
    }

    // output results
    for (auto& m : wm )
    {
        std::cout << "The word  \"" << m.first << "\" appears " << m.second.first << " times on the following lines:\n";
        for ( auto& m2 : m.second.second)
            std::cout << m2 << " ";
        std::cout << "\n\n";
    }
}
</code>```

So what was done here?

1) The line where each word is on is known in the read loop.  All that is done is to increment the line count for each line that is read in.

2) We use std::map::insert to insert an entry into the map, and not std::map::operator[ ].  The reason is that map::insert will not insert an entry if the entry already exists, it will insert a brand new entry if the entry doesn't exist, and regardless of which is done, std::map::insert returns an iterator to the item in the map.

We need the iterator returned to us for later processing.  In the subsequent lines, we just increment the count and update the std::set.

Here is a live example.

Note:  I have no idea what all of the replacement you're doing in your original program, so I skipped over all of that and concentrated solely on the task of determining the words and the line(s) the words are situated.

Body:
I am writing code which calculate how many times each word appears in text ( I DID THIS TASK), but I can't find a way to calculate in which lines these words appeared.

I don't know where to start.

#include "header.h"
int main()
{
     //read the input, keeping track of each word and how often we see it
     std::ifstream in("tekstas.txt"); // input file

    std::string input;
    std::map<std::string, int> counters; // store each word and an associated counter
    std::vector<char>CharVect; // vector that stores symbols i want to replace
    formuojuChar(CharVect); // pushbacking that vector with symbols
     for (unsigned int i = 0; !in.eof(); i++)
    {
        std::getline(in, input);
        std::transform(input.begin(), input.end(), input.begin(), ::tolower); // lowering letters so for example "Mom"= "mom"
        Replace(input,CharVect, ' '); // replace symbols with space
        std::stringstream read(input);
        std::string word;
        while (read >> word)
        {
            ++counters[word];
        }
     }
     std::ofstream out("isvestis.txt");
    std::cout<<"Words that appear more than once in the text: "<<std::endl;
    std::cout<<std::endl;
     for (std::map<std::string, int>::const_iterator it = counters.begin();it != counters.end(); ++it)
        {
            if((it->second)>1)
            {

                std::cout<<"'" <<it->first<<"' " <<"appears "<<it->second <<" times in lines: " ;
                /*
                 ANY IDEAS ?
                 */
                std::cout<<std::endl;

            }
        }
        return 0;

}

I expect output to show me in which .txt file lines that word appears. TY

Body:
The major issue with your approach is that you're using a second loop to gather the information on the words, and in doing so, you've lost all the information about which line(s) the words are on.

Instead of trying to figure out what line you're on in the second loop, you have all the information necessary on the current line in the first loop.  All you need is a variable that keeps track of each line.  You are using (incorrectly I may add), std::getline -- each time you call that function, you are going to the next line, thus you know implicitly what line you're on in the first loop.

First, you need to fix your read loop so that it reads lines correctly from a file:

std::string line;
while (std::getline(in, line))
{
//...
}

Second, inside the while loop, you can determine all the information you need for the word, word count, and line(s) where the word is found.  You don't need two loops to do this.

Instead of a std::map<std::string, int>, which only knows about the word count, you could create a map that holds all the information -- the word count and the line(s) the word is found on.  Here is a map type that can hold this information:

std::map<std::string, std::pair<int, std::set<int>>>

The "second" of the map holds the information on the count, and a std::set that will hold all of the line numbers where the word is found.  The reason for the std::set is to guarantee that duplicate line numbers will not be stored.

Putting this all together, here is a sample program using this type:

#include <map>
#include <set>
#include <string>
#include <sstream>
#include <iostream>

// pair and map type
using WordInfo = std::pair<int, std::set<int>>;
using WordMap = std::map<std::string, WordInfo>;

int main()
{
    // our map
    WordMap wm;
    std::string line;

    // the line count
    int line_number = 1;
    while (std::getline(std::cin, line))
    {
        // line parser
        std::istringstream strm(line);
        std::string word;
        while ( strm >> word)
        {
            // we call map::insert, not `[ ]` to insert into a map
            auto pr = wm.insert({word, {0,std::set<int>()}});

            // the return value of map::insert gives us a pair, where the first is
            // an iterator to the item in the map
            auto& mapIter = pr.first;

            // increment the word count
            ++(mapIter->second.first);

            // insert the line number into the set
            mapIter->second.second.insert(line_number);
        }

        // increment the line counter
        ++line_number;
    }

    // output results
    for (auto& m : wm )
    {
        std::cout << "The word  \"" << m.first << "\" appears " << m.second.first << " times on the following lines:\n";
        for ( auto& m2 : m.second.second)
            std::cout << m2 << " ";
        std::cout << "\n\n";
    }
}

So what was done here?

1) The line where each word is on is known in the read loop.  All that is done is to increment the line count for each line that is read in.

2) We use std::map::insert to insert an entry into the map, and not std::map::operator[ ].  The reason is that map::insert will not insert an entry if the entry already exists, it will insert a brand new entry if the entry doesn't exist, and regardless of which is done, std::map::insert returns an iterator to the item in the map.

We need the iterator returned to us for later processing.  In the subsequent lines, we just increment the count and update the std::set.

Here is a live example.

Note:  I have no idea what all of the replacement you're doing in your original program, so I skipped over all of that and concentrated solely on the task of determining the words and the line(s) the words are situated.


问:
Fill CirleProgressView and save result to UserDefaults
I need help with my little project for university. I have two ViewControllers.
First - DietViewController
Second - WaterBalanceViewController (use SPStorkController)

I need to fill CircleProgressView in my DietVC.

When I click on Drink ->

```<code> @IBAction func drinkAction(_ sender: UIButton) {

        let controller = WaterBalanceViewController()
        let transitionDelegate = SPStorkTransitioningDelegate()
        controller.transitioningDelegate = transitionDelegate
        controller.modalPresentationStyle = .custom
        transitionDelegate.customHeight = 620
        transitionDelegate.showIndicator = false
        self.present(controller, animated: true, completion: nil)
    }
</code>```

And open SPStorkController - my secondVC

Next, when I click on button Drink in my secondVC I must save: how much i just drank. For example call this variable justDrunk. In my firstVC I have  var currentAmountOfWater = Float()This is the value that will be passed to CircleProgressView. I try to save:

```<code>@objc func pressButton(_ sender: UIButton){
        print("Hello")

        self.justDrunk = Float(textField.text!)!
        let vc = DietViewController()
        vc.currentAmountOfWater += justDrunk
        vc.currentAmountOfWater += justDrunk
       UserDefaults.standard.set(vc.currentAmountOfWater, forKey: "currentAmountOfWater")

        print(UserDefaults.standard.float(forKey: "currentAmountOfWater"))

        self.dismiss(animated: true, completion: nil)

    }
</code>```

When I try to print I can see that my value doest't save. Always printed the result of justDrunk.

Then I want to use my currentAmountOfWater in my firstVC.

In viewDidLoad  `var valueForWater = currentAmountOfWater/maxAmountOfWater

```<code>waterProgress.progressColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
       waterProgress.setProgressWithAnimation(duration: 1, value: valueForWater)
</code>```

Please, someone helps me. How to enter data in secondVC, pass data to firsVC and displayed all in CicrleProgressView. And maybe you can write a code that will reset currentAmountOfWater to zero every 24 hours.

Thank you!

答:
Since your are retrieving the value from storage immediately, you must execute UserDefaults.standard.synchronize() in order for your changes to get written on disk immediately

Here is your updated method

```<code>@objc func pressButton(_ sender: UIButton){
    guard let justDrunk = Float(textField.text!) else { return }

    self.justDrunk = justDrunk

    let vc = DietViewController()
    vc.currentAmountOfWater += justDrunk
    vc.currentAmountOfWater += justDrunk
    UserDefaults.standard.set(vc.currentAmountOfWater, forKey: "currentAmountOfWater")
    UserDefaults.standard.synchronize()

    print(UserDefaults.standard.float(forKey: "currentAmountOfWater"))

    self.dismiss(animated: true, completion: nil)
}
</code>```

Just a side note, do not force unwrap Float(String), user might input a non-numeric string and that could cause a crash in your app.

I would prefer to call delegate method to update the view controller, which I have explained briefly in another post, you can also have a look at sample project

Body:
I need help with my little project for university. I have two ViewControllers.
First - DietViewController
Second - WaterBalanceViewController (use SPStorkController)

I need to fill CircleProgressView in my DietVC.

When I click on Drink ->

 @IBAction func drinkAction(_ sender: UIButton) {

        let controller = WaterBalanceViewController()
        let transitionDelegate = SPStorkTransitioningDelegate()
        controller.transitioningDelegate = transitionDelegate
        controller.modalPresentationStyle = .custom
        transitionDelegate.customHeight = 620
        transitionDelegate.showIndicator = false
        self.present(controller, animated: true, completion: nil)
    }

And open SPStorkController - my secondVC

Next, when I click on button Drink in my secondVC I must save: how much i just drank. For example call this variable justDrunk. In my firstVC I have  var currentAmountOfWater = Float()This is the value that will be passed to CircleProgressView. I try to save:

@objc func pressButton(_ sender: UIButton){
        print("Hello")

        self.justDrunk = Float(textField.text!)!
        let vc = DietViewController()
        vc.currentAmountOfWater += justDrunk
        vc.currentAmountOfWater += justDrunk
       UserDefaults.standard.set(vc.currentAmountOfWater, forKey: "currentAmountOfWater")

        print(UserDefaults.standard.float(forKey: "currentAmountOfWater"))

        self.dismiss(animated: true, completion: nil)

    }

When I try to print I can see that my value doest't save. Always printed the result of justDrunk.

Then I want to use my currentAmountOfWater in my firstVC.

In viewDidLoad  `var valueForWater = currentAmountOfWater/maxAmountOfWater

waterProgress.progressColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
       waterProgress.setProgressWithAnimation(duration: 1, value: valueForWater)

Please, someone helps me. How to enter data in secondVC, pass data to firsVC and displayed all in CicrleProgressView. And maybe you can write a code that will reset currentAmountOfWater to zero every 24 hours.

Thank you!

Body:
Since your are retrieving the value from storage immediately, you must execute UserDefaults.standard.synchronize() in order for your changes to get written on disk immediately

Here is your updated method

@objc func pressButton(_ sender: UIButton){
    guard let justDrunk = Float(textField.text!) else { return }

    self.justDrunk = justDrunk

    let vc = DietViewController()
    vc.currentAmountOfWater += justDrunk
    vc.currentAmountOfWater += justDrunk
    UserDefaults.standard.set(vc.currentAmountOfWater, forKey: "currentAmountOfWater")
    UserDefaults.standard.synchronize()

    print(UserDefaults.standard.float(forKey: "currentAmountOfWater"))

    self.dismiss(animated: true, completion: nil)
}

Just a side note, do not force unwrap Float(String), user might input a non-numeric string and that could cause a crash in your app.

I would prefer to call delegate method to update the view controller, which I have explained briefly in another post, you can also have a look at sample project


问:
How to make nscd generate core dump files?
nscd service crashed without a core dump file.

ulimit -c is unlimited.

Someone says that that's because nscd use "setuid" when the "server-user" is set in /etc/nscd.conf.

Then I added a "#" to delete it at the beginning of  the "server-user" line in /etc/nscd.conf then restart the service.

Now it runs as root which could be checked by "ps -ef | grep nscd".

However, the following commands still could not make nscd to generate a core dump file:
   kill -ABRT nscd-pid
or kill -s SIGSEGV nscd-pid

Who can tell me why and how? Thanks in advance!

答: resolved it myself. That's because nscd is called with "daemon nscd ..." in /etc/init.d/nscd script, however the daemon function in /etc/init.d/functions modify the core dump file size to be 0, so even if issuing "ulimit -c unlimited" at the beginning of "/etc/init.d/nscd" could not make sence.</p>


问:
How to get only specific fields in Gitlab API response?
For example I want to receive only project names:
https://gitlab.com/api/v4/groups/:id/projects?fields=name

Is that possible?

答:
GitLab 1.11 (May 2019) has now introduced a "basic support for group GraphQL queries "

GraphQL APIs allows users to request exactly the data they need, making it possible to get all required data in a limited number of requests.

In this release, GitLab is now supporting basic group information support in the GraphQL API.

See Issue 60786 and documentation: "Available queries"

A first iteration of a GraphQL API includes the following queries

project : Within a project it is also possible to fetch a mergeRequest by IID.

group : Only basic group information is currently supported.


问:
How to use reinforcement learning models MDP Q-learning?
I am interested in studying reinforcement learning, in particular how to use RL for dynamic pricing. I tried to read some papers about it, and most of the time I see examples where authors try to simulate the environment in order to see the best options.

https://arxiv.org/pdf/1803.09967.pdf RL for fair dynamic pricing

https://ieeexplore.ieee.org/document/1210269 - Reinforcement learning applications in dynamic pricing of retail markets

I am trying to understand, in this case every time we have some sort of uncertainty it is possible to simulate the environment to get the answer. And every time we have new input (environment and state is different) we run the program go get the results? Is it possible to deploy the RL model?

I would really appreciate any information/links related to RL in dynamic pricing and how it is possible to use/reuse the RL models.

答:
RL assumes you have some way to simulate the environment. The idea is that the RL agent "plays the game" in the simulated environment many times, and in doing so it learns how to play well. I'm not sure what you mean "every time we have new input (environment and state is different)" -- if the state changes, you don't rerun (i.e., retrain the model). If the environment changes -- for ex., the pricing structure or demand distribution changes -- then you need to retrain. But if the environment changes meaning you move to a new state in the same environment, you don't retrain.

For dynamic pricing, RL could work something like this: You have a simulator of the real world. For any action you take (e.g., for any price you set), the simulator simulates the demands, your competitors' actions, etc., over a multi-time-period horizon. The RL agent plays the game repeatedly and learns how to choose good actions in each period based on the state of the environment in each of those periods.

Multiple-period environments are the typical setup for RL. If it's just a single period, then you don't need RL, there are much simpler models for revenue optimization in that sort of setting.


问:
How to fix undefined result in $scope select options array?
I'm using AngularJS and trying to set up a select dropbox field with options that are contained in an array, and added via an input box by the end user. I have the $scope successfully adding to the array, but the dropdown select box just shows "undefined" for all options.

I have looked for similar answers but none of them specifically address what my error is, or are using Angular 2+ which doesn't help.

<select class="form-control" id="maidOfHonor" ng-model="name"
        ng-options="names.value as names.value for name in names">
</select>
```

<pre class="lang-js prettyprint-override"><code>$scope.names = [
    {
        name: "Position Not Filled",
        value: "Position Not Filled"
    }
];
$scope.addName = function() {
    $scope.names.push({ name: this.party.addName, value: this.party.addName });
    console.log($scope.names);
}
</code>```

Ideally, I would like whatever "name" that is added via the $scope.addName() function to be added to the dropdown select box as the value or the name, instead of undefined of course.

答:
It seems to me that your issue is the ng-options syntax.

Instead of:

```<code>ng-options="names.value as names.value for name in names"
</code>```

Try

```<code>ng-options="name.value as name.name for name in names"
</code>```

name.value is the value to get from or set to the ng-model.

name.name is the value to show as the option's text.

Note that the variables referenced start with name, rather than names as in your original code.

Body:
I'm using AngularJS and trying to set up a select dropbox field with options that are contained in an array, and added via an input box by the end user. I have the $scope successfully adding to the array, but the dropdown select box just shows "undefined" for all options.

I have looked for similar answers but none of them specifically address what my error is, or are using Angular 2+ which doesn't help.

<select class="form-control" id="maidOfHonor" ng-model="name"
        ng-options="names.value as names.value for name in names">
</select>

$scope.names = [
    {
        name: "Position Not Filled",
        value: "Position Not Filled"
    }
];
$scope.addName = function() {
    $scope.names.push({ name: this.party.addName, value: this.party.addName });
    console.log($scope.names);
}

Ideally, I would like whatever "name" that is added via the $scope.addName() function to be added to the dropdown select box as the value or the name, instead of undefined of course.

Body:
It seems to me that your issue is the ng-options syntax.

Instead of:

ng-options="names.value as names.value for name in names"

Try

ng-options="name.value as name.name for name in names"

name.value is the value to get from or set to the ng-model.

name.name is the value to show as the option's text.

Note that the variables referenced start with name, rather than names as in your original code.


问:
AttributeError: module 'numpy' has no attribute 'array
I do not have a file named numpy.py.
My exact steps are: in Python, Open C:\Adrian\Python37\Lib\numpy-1.11.2\setup.py, I run this module:</p>

```<code>>>>
=========== RESTART: C:\Adrian\Python37\Lib\numpy-1.11.2\setup.py ===========
Running from numpy source directory.
>>> import numpy as np
>>> list_int = [8, 3, 34, 111]
>>> a_int = np.array(list_int)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a_int = np.array(list_int)
AttributeError: module 'numpy' has no attribute 'array'
</code>```

答:
Reported symptom is:

```<code>>>> import numpy as np
>>> a_int = np.array(list_int)
...
AttributeError: module 'numpy' has no attribute 'array'
</code>```

This can't possibly happen if numpy is correctly installed.

The OP explains that re-installing numpy properly on his machine solves the symptom.

Body:
I do not have a file named numpy.py.
My exact steps are: in Python, Open C:\Adrian\Python37\Lib\numpy-1.11.2\setup.py, I run this module:

>>>
=========== RESTART: C:\Adrian\Python37\Lib\numpy-1.11.2\setup.py ===========
Running from numpy source directory.
>>> import numpy as np
>>> list_int = [8, 3, 34, 111]
>>> a_int = np.array(list_int)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a_int = np.array(list_int)
AttributeError: module 'numpy' has no attribute 'array'

Body:
Reported symptom is:

>>> import numpy as np
>>> a_int = np.array(list_int)
...
AttributeError: module 'numpy' has no attribute 'array'

This can't possibly happen if numpy is correctly installed.

The OP explains that re-installing numpy properly on his machine solves the symptom.


问:
how to find a path to go home - algorithm

(source: blogcu.com)

Assume there is a rabbit and at position (1,1). Moreover, its home is at position (7,7). How can it reach that position ?

Home positon is not fix place.

Real question, I am trying to solve a problem on a book for exersizing c.What algorithm should I apply to find solution?
Should I use linked list to store data?

Data is (1,1), (1,2),..., (3,3) ..., (7,7)
Place marked with black shows wall.

答:
Breadth-first search is always a good one.

http://www.codeproject.com/KB/recipes/mazesolver.aspx

OwnerDisplayName: shelman


问:
Is it possible to deep link to a Facebook Event page?
I've tried fb://event/EventID#Here which attempts to open the event page in the Facebook app, but then says "Unable to load event. It may have been cancelled." Obviously I didn't cancel the event, and it isn't Private or Guest View only. Is this function simply not supported in iOS 10?

If not, what Facebook deep links are supported? I've only had success with Profiles and Pages, but this post has quite a large list that supposedly work: What are all the custom URL schemes supported by the Facebook iPhone app? (hasn't been updated for iOS 10 though)

答: deeplinks are supported now, your link should be https://facebook.com/events/:eventId/


问:
Ionic Android signed prod app does REST request fails / dead
Not sure what is going on.
When building my app for android
ionic cordova run android

and I manually deploy it to the phone it works well,
I can track https between the device and my backend server.

When I code sign the app

```<code>ionic cordova build android --prod --release
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore appStoreKey.jks ./platforms/android/app/build/outputs/apk/release/app-release-unsigned.apk MyApp
</code>```

There's no traffic between app and backend. I can not log into the app, it simply does not go beyond the login view and does not allow any traffic outside.

Here's my config.xml:

```<code><allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
</code>```

IMHO this should allow the app to see everything (it's not the default option, only trying to fix this).
Am I missing something? I even can not debug with Chrome since it has not been built in debug mode. I have no idea what could be going wrong and how to address this issue.

iOS works like a charm both, debug and prod mode.

答:
It turns out there's a feature (or it maybe a bug) in Android Cordova. Based on the top by @AbdulAzeem and blogpost it turns out one has to modify onReceivedSslError in CordovaWebViewClient.java to enable certificates that are still accepted by iOS. My reasoning is that since Apple puts more emphasis on service & app quality I can live with any certificate that Apple accepts and Cordova fails on. Anyway, the fix as shown in the link still works with Android 9.

Edit

```<code>platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java
</code>```

ll 237
add comment and code

```<code>// super.onReceivedSslError(view, handler, error);

// add code
handler.proceed();
return;
</code>```

Body:
Not sure what is going on.
When building my app for android
ionic cordova run android

and I manually deploy it to the phone it works well,
I can track https between the device and my backend server.

When I code sign the app

ionic cordova build android --prod --release
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore appStoreKey.jks ./platforms/android/app/build/outputs/apk/release/app-release-unsigned.apk MyApp

There's no traffic between app and backend. I can not log into the app, it simply does not go beyond the login view and does not allow any traffic outside.

Here's my config.xml:

<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />

IMHO this should allow the app to see everything (it's not the default option, only trying to fix this).
Am I missing something? I even can not debug with Chrome since it has not been built in debug mode. I have no idea what could be going wrong and how to address this issue.

iOS works like a charm both, debug and prod mode.

Body:
It turns out there's a feature (or it maybe a bug) in Android Cordova. Based on the top by @AbdulAzeem and blogpost it turns out one has to modify onReceivedSslError in CordovaWebViewClient.java to enable certificates that are still accepted by iOS. My reasoning is that since Apple puts more emphasis on service & app quality I can live with any certificate that Apple accepts and Cordova fails on. Anyway, the fix as shown in the link still works with Android 9.

Edit

platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java

ll 237
add comment and code

// super.onReceivedSslError(view, handler, error);

// add code
handler.proceed();
return;


问:
How to convert an unsigned char variable that holds two hexadecimal values into two chars with one hex number
I need to get the hash (sha1) value of a given unsigned char array. So, I have used openssl. The SHA1 function generate the hash value in an unsigned char array which has 20 values. Indeed each value represent two hexadecimal values.

But, I should convert the generated array (with length of 20) to an array of chars with 40 values.

For example now hashValue[0] is "a0" but, I want to have hashValue[0] = "a" and hashValue[1] = "0"

```<code>#include <iostream>
#include <openssl/sha.h> // For sha1

using namespace std;

int main() {

    unsigned char plainText[] = "compute sha1";
    unsigned char hashValue[20];

    SHA1(plainText,sizeof(plainText),hashValue);

    for (int i = 0; i < 20; i++) {
        printf("%02x", hashValue[i]);
    }
    printf("\n");

    return 0;

}
</code>```

答:
You could create another array and use sprintf or safer snprintf to print into it instead of the standard output.

Something like this:

```<code>#include <iostream>
#include <stdio.h>
#include <openssl/sha.h> // For sha1

using namespace std;

int main() {

    unsigned char plainText[] = "compute sha1";
    unsigned char hashValue[20];
    char output[41];

    SHA1(plainText,sizeof(plainText),hashValue);

    char *c_output = output;
    for (int i = 0; i < 20; i++, c_output += 2) {
        snprintf(c_output, 3, "%02x", hashValue[i]);
    }

    return 0;

}
</code>```

Now output[0] == 'a' and output[1] == '0'.

There might be other, even better solution, this is just the first that comes to mind.

EDIT: Added fix from comments.

Body:
I need to get the hash (sha1) value of a given unsigned char array. So, I have used openssl. The SHA1 function generate the hash value in an unsigned char array which has 20 values. Indeed each value represent two hexadecimal values.

But, I should convert the generated array (with length of 20) to an array of chars with 40 values.

For example now hashValue[0] is "a0" but, I want to have hashValue[0] = "a" and hashValue[1] = "0"

#include <iostream>
#include <openssl/sha.h> // For sha1

using namespace std;

int main() {

    unsigned char plainText[] = "compute sha1";
    unsigned char hashValue[20];

    SHA1(plainText,sizeof(plainText),hashValue);

    for (int i = 0; i < 20; i++) {
        printf("%02x", hashValue[i]);
    }
    printf("\n");

    return 0;

}

Body:
You could create another array and use sprintf or safer snprintf to print into it instead of the standard output.

Something like this:

#include <iostream>
#include <stdio.h>
#include <openssl/sha.h> // For sha1

using namespace std;

int main() {

    unsigned char plainText[] = "compute sha1";
    unsigned char hashValue[20];
    char output[41];

    SHA1(plainText,sizeof(plainText),hashValue);

    char *c_output = output;
    for (int i = 0; i < 20; i++, c_output += 2) {
        snprintf(c_output, 3, "%02x", hashValue[i]);
    }

    return 0;

}

Now output[0] == 'a' and output[1] == '0'.

There might be other, even better solution, this is just the first that comes to mind.

EDIT: Added fix from comments.


问:
Material table not sorting records
I can't find what is wrong with my script, the list loads OK but when clicking on the table headers the sorting does not work.

I have tried putting the sorting part inside a TimeOut on the response and also moving it to the ngAfterViewInit() function. Everything else on my app works fine except for this.

Heres is the ts code:

```<code>import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  listData: MatTableDataSource<any>;
  displayColumns: string[]=['id','nombre','acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData= new MatTableDataSource(response.object);
        this.listData.sort= this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}
</code>```

And here is the html:

```<code><div class="col-lg-12">
  <div class="row">
      <div class="col-lg-9 text-center">
          <h3 class="title-divider">
              <span>List</span>
          </h3>
      </div>
      <div class="col-lg-3 text-center">

      </div>
  </div>
  <div class="row">
      <div class="col-lg-12">
          <div class="mat-elevation-z8">
              <mat-table #table [dataSource]="listData" matSort>
                  <ng-container matColumnDef="id">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="nombre">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>Nombre</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="acciones">
                      <mat-header-cell *matHeaderCellDef>Acciones</mat-header-cell>
                      <mat-cell *matCellDef="let row">
                          <button mat-icon-button (click)="onDetail(row)"><mat-icon>details</mat-icon></button>
                          <button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
                          <button mat-icon-button color="warn" (click)="onDelete(row)"><mat-icon>delete_outline</mat-icon></button>
                      </mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="loading">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          Loading data
                      </mat-footer-cell>
                  </ng-container>
                  <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          No data
                      </mat-footer-cell>
                  </ng-container>
                  <mat-header-row *matHeaderRowDef="displayColumns; sticky:true "></mat-header-row>
                  <mat-row *matRowDef="let row; columns: displayColumns"></mat-row>
                  <mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':listData!=null}"></mat-footer-row>
                  <mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.data.length==0)}"></mat-footer-row>
              </mat-table>
              <mat-paginator [pageSizeOptions]="[5, 10, 15, 25]" [pageSize]="5" showFirstLastButtons></mat-paginator>
          </div>
      </div>
  </div>

</div>
</code>```

Here's also the console log displaying the MatSort object:

```<code>MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(2), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable
_isScalar: false
_subscribe: ƒ (subscriber)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: core.es5.js:474
[[Scopes]]: Scopes[4]
__proto__: Object
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (3) [Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(2)
size: (...)
__proto__: Map
[[Entries]]: Array(2)
0: {"id" => MatSortHeader}
1: {"nombre" => MatSortHeader}
length: 2
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1
</code>```

I've imported MatSortModule and MatTableModule on the AppModule and I have no errors displayed by the JS console.

答:
My understanding is that the sort headers you have defined have to match the exact property name to make sorting work. Right now you have id and ID. So just change it to:

```<code>displayColumns: string[]=['ID','nombre','acciones'];

<ng-container matColumnDef="ID">
</code>```

Title: Material table not sorting records

Body:
I can't find what is wrong with my script, the list loads OK but when clicking on the table headers the sorting does not work.

I have tried putting the sorting part inside a TimeOut on the response and also moving it to the ngAfterViewInit() function. Everything else on my app works fine except for this.

Heres is the ts code:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  listData: MatTableDataSource<any>;
  displayColumns: string[]=['id','nombre','acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData= new MatTableDataSource(response.object);
        this.listData.sort= this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}

And here is the html:

              List

              <mat-table #table [dataSource]="listData" matSort>
                  <ng-container matColumnDef="id">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="nombre">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>Nombre</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="acciones">
                      <mat-header-cell *matHeaderCellDef>Acciones</mat-header-cell>
                      <mat-cell *matCellDef="let row">
                          <button mat-icon-button (click)="onDetail(row)"><mat-icon>details</mat-icon></button>
                          <button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
                          <button mat-icon-button color="warn" (click)="onDelete(row)"><mat-icon>delete_outline</mat-icon></button>
                      </mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="loading">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          Loading data
                      </mat-footer-cell>
                  </ng-container>
                  <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          No data
                      </mat-footer-cell>
                  </ng-container>
                  <mat-header-row *matHeaderRowDef="displayColumns; sticky:true "></mat-header-row>
                  <mat-row *matRowDef="let row; columns: displayColumns"></mat-row>
                  <mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':listData!=null}"></mat-footer-row>
                  <mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.data.length==0)}"></mat-footer-row>
              </mat-table>
              <mat-paginator [pageSizeOptions]="[5, 10, 15, 25]" [pageSize]="5" showFirstLastButtons></mat-paginator>

Here's also the console log displaying the MatSort object:

MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(2), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable
_isScalar: false
_subscribe: ƒ (subscriber)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: core.es5.js:474
[[Scopes]]: Scopes[4]
__proto__: Object
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (3) [Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(2)
size: (...)
__proto__: Map
[[Entries]]: Array(2)
0: {"id" => MatSortHeader}
1: {"nombre" => MatSortHeader}
length: 2
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1

I've imported MatSortModule and MatTableModule on the AppModule and I have no errors displayed by the JS console.

Body:
My understanding is that the sort headers you have defined have to match the exact property name to make sorting work. Right now you have id and ID. So just change it to:

displayColumns: string[]=['ID','nombre','acciones'];

<ng-container matColumnDef="ID">


问:
How can I better handle config files?
In a package I'm writing, I have a config module that looks like this:

```<code>use v6.d;
use JSON::Fast;
use PSBot::Tools;

sub EXPORT(--> Hash) {
    my Str $path = do if %*ENV<TESTING> {
        $*REPO.Str.IO.child('META6.json').e
            ?? $*REPO.Str.IO.child('t/config.json').Str         # For when testing using zef
            !! $*REPO.Str.IO.parent.child('t/config.json').Str; # For when testing using prove
    } elsif $*DISTRO.is-win {
        "%*ENV<LOCALAPPDATA>\\PSBot\\config.json"
    } else {
        "$*HOME/.config/PSBot/config.json"
    };

    unless $path.IO.e {
        note "PSBot config at $path does not exist!";
        note "Copy psbot.json.example there and read the README for instructions on how to set up the config file.";
        exit 1;
    }

    with from-json slurp $path -> %config {
        %(
            USERNAME               => %config<username>,
            PASSWORD               => %config<password>,
            AVATAR                 => %config<avatar>,
            HOST                   => %config<host>,
            PORT                   => %config<port>,
            SERVERID               => %config<serverid>,
            COMMAND                => %config<command>,
            ROOMS                  => set(%config<rooms>.map: &to-roomid),
            ADMINS                 => set(%config<admins>.map: &to-id),
            MAX_RECONNECT_ATTEMPTS => %config<max_reconnect_attempts>,
            GIT                    => %config<git>,
            DICTIONARY_API_ID      => %config<dictionary_api_id>,
            DICTIONARY_API_KEY     => %config<dictionary_api_key>,
            YOUTUBE_API_KEY        => %config<youtube_api_key>,
            TRANSLATE_API_KEY      => %config<translate_api_key>
        )
    }
}
</code>```

Every time I make changes to the config file, I have to delete the precomp files for the changes to appear. Is there a way I can write this so the exports aren't defined at compile time so users don't have to do this?

答:
Assuming I understand your intentions correctly, one way to do it would be this:

get rid of the EXPORT sub

place the computation of $path and %config into the module's mainline

declare your 'constants' as terms such as

```<code>sub term:<USERNAME> is export { %config<username> }
</code>```

Title: How can I better handle config files?

Body:
In a package I'm writing, I have a config module that looks like this:

use v6.d;
use JSON::Fast;
use PSBot::Tools;

sub EXPORT(--> Hash) {
    my Str $path = do if %*ENV<TESTING> {
        $*REPO.Str.IO.child('META6.json').e
            ?? $*REPO.Str.IO.child('t/config.json').Str         # For when testing using zef
            !! $*REPO.Str.IO.parent.child('t/config.json').Str; # For when testing using prove
    } elsif $*DISTRO.is-win {
        "%*ENV<LOCALAPPDATA>\\PSBot\\config.json"
    } else {
        "$*HOME/.config/PSBot/config.json"
    };

    unless $path.IO.e {
        note "PSBot config at $path does not exist!";
        note "Copy psbot.json.example there and read the README for instructions on how to set up the config file.";
        exit 1;
    }

    with from-json slurp $path -> %config {
        %(
            USERNAME               => %config<username>,
            PASSWORD               => %config<password>,
            AVATAR                 => %config<avatar>,
            HOST                   => %config<host>,
            PORT                   => %config<port>,
            SERVERID               => %config<serverid>,
            COMMAND                => %config<command>,
            ROOMS                  => set(%config<rooms>.map: &to-roomid),
            ADMINS                 => set(%config<admins>.map: &to-id),
            MAX_RECONNECT_ATTEMPTS => %config<max_reconnect_attempts>,
            GIT                    => %config<git>,
            DICTIONARY_API_ID      => %config<dictionary_api_id>,
            DICTIONARY_API_KEY     => %config<dictionary_api_key>,
            YOUTUBE_API_KEY        => %config<youtube_api_key>,
            TRANSLATE_API_KEY      => %config<translate_api_key>
        )
    }
}

Every time I make changes to the config file, I have to delete the precomp files for the changes to appear. Is there a way I can write this so the exports aren't defined at compile time so users don't have to do this?

Body:
Assuming I understand your intentions correctly, one way to do it would be this:

get rid of the EXPORT sub

place the computation of $path and %config into the module's mainline

declare your 'constants' as terms such as

sub term:<USERNAME> is export { %config<username> }


问:
AWS Cloudwatch Log Insights - Filter Records by JSON filters on JSON log events
I have a log group which accumulates JSON logs to each of its streams. These JSON logs look like this.

I want to filter logs where "user" = "keet". AWS documentation explains on Using Metric Filters to Extract Values from JSON Log Events. I tried this using the AWS SDK, and it worked fine for the following code in NodeJS.

```<code>let params = {
    logGroupName: 'log-goupe-name', /* required */
    filterPattern: '{$.user=keet}',

};
cloudwatchlogs.filterLogEvents(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});
</code>```

Question:

Similarly, I want to know whether the same is possible on AWS Cloudwatch Insights Dashboard, on AWS Console? I know string pattern matching is possible. But I wanna know whether JSON field matching is possible on the Insights dashboard using @filter. The default query that comes is as follows.

```<code>fields @timestamp, @message
| sort @timestamp desc
| limit 20
</code>```

I tried following this answer on Stackoverflow, and it still did not help. This is only for parsing data. My requirement is to filter logs based on value in JSON logs.

Thanks in advance.

答:
You can parse out the user from json like this:

```<code>parse @message '"user":"*"' as user
</code>```

Depending on what you want to see on dashboard, you can filter out only particular users with this:

```<code>fields @message
| parse @message '"user":"*"' as user
| filter user == "keet"
</code>```

Result will be:

```<code>#    @message                            user
----------------------------------------------
1    info - {"user":"keet","age":30 }    keet
2    info - {"user":"keet","age":30 }    keet
3    info - {"user":"keet","age":30 }    keet
4    info - {"user":"keet","age":30 }    keet
</code>```

Also try just:

```<code>filter user == 'keet'
</code>```

maybe Insights will auto-discover the fields. You can see the list of auto-discovered fields on the right, in Discovered fields section.

Body:
I have a log group which accumulates JSON logs to each of its streams. These JSON logs look like this.

I want to filter logs where "user" = "keet". AWS documentation explains on Using Metric Filters to Extract Values from JSON Log Events. I tried this using the AWS SDK, and it worked fine for the following code in NodeJS.

let params = {
    logGroupName: 'log-goupe-name', /* required */
    filterPattern: '{$.user=keet}',

};
cloudwatchlogs.filterLogEvents(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});

Question:

Similarly, I want to know whether the same is possible on AWS Cloudwatch Insights Dashboard, on AWS Console? I know string pattern matching is possible. But I wanna know whether JSON field matching is possible on the Insights dashboard using @filter. The default query that comes is as follows.

fields @timestamp, @message
| sort @timestamp desc
| limit 20

I tried following this answer on Stackoverflow, and it still did not help. This is only for parsing data. My requirement is to filter logs based on value in JSON logs.

Thanks in advance.

Body:
You can parse out the user from json like this:

parse @message '"user":"*"' as user

Depending on what you want to see on dashboard, you can filter out only particular users with this:

fields @message
| parse @message '"user":"*"' as user
| filter user == "keet"

Result will be:

#    @message                            user
----------------------------------------------
1    info - {"user":"keet","age":30 }    keet
2    info - {"user":"keet","age":30 }    keet
3    info - {"user":"keet","age":30 }    keet
4    info - {"user":"keet","age":30 }    keet

Also try just:

filter user == 'keet'

maybe Insights will auto-discover the fields. You can see the list of auto-discovered fields on the right, in Discovered fields section.