问:
React- Webpack: Cannot read property 'tap' of undefined
I have a React application configured with Django Application. I have different webpack config files for development and production, When I run "npm run start", it gives me error that:

Cannot read property 'tap' of undefined

package.json file:

```<code>{
    "name": "project",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
    "@babel/core": "7.1.0",
    "@svgr/webpack": "2.4.1",
    "ajv": "^6.5.4",
    "ajv-keywords": "^3.2.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "9.0.0",
    "babel-jest": "23.6.0",
    "babel-loader": "8.0.4",
    "babel-plugin-named-asset-import": "^0.2.2",
    "babel-preset-react-app": "^5.0.4",
    "bfj": "6.1.1",
    "case-sensitive-paths-webpack-plugin": "2.1.2",
    "chalk": "2.4.1",
    "css-loader": "1.0.0",
    "dotenv": "6.0.0",
    "dotenv-expand": "4.2.0",
    "eslint": "5.6.0",
    "eslint-config-react-app": "^3.0.4",
    "eslint-loader": "2.1.1",
    "eslint-plugin-flowtype": "2.50.1",
    "eslint-plugin-import": "2.14.0",
    "eslint-plugin-jsx-a11y": "6.1.2",
    "eslint-plugin-react": "7.11.1",
    "file-loader": "2.0.0",
    "fs-extra": "7.0.0",
    "identity-obj-proxy": "3.0.0",
    "jest": "23.6.0",
    "jest-pnp-resolver": "1.0.1",
    "jest-resolve": "23.6.0",
    "mini-css-extract-plugin": "0.4.3",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "pnp-webpack-plugin": "1.1.0",
    "postcss-flexbugs-fixes": "4.1.0",
    "postcss-loader": "3.0.0",
    "postcss-preset-env": "6.0.6",
    "postcss-safe-parser": "4.0.1",
    "react": "^16.6.0",
    "react-app-polyfill": "^0.1.3",
    "react-dev-utils": "^6.0.5",
    "react-dom": "^16.6.0",
    "resolve": "1.8.1",
    "sass-loader": "7.1.0",
    "style-loader": "0.23.0",
    "terser-webpack-plugin": "1.1.0",
    "url-loader": "1.1.1",
    "webpack": "4.19.1",
    "webpack-dev-server": "3.1.9",
    "webpack-manifest-plugin": "2.0.4",
    "workbox-webpack-plugin": "3.6.2"
},
"scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
},
"eslintConfig": {
    "extends": "react-app"
},
"browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
],
"jest": {
    "collectCoverageFrom": [
        "src/**/*.{js,jsx}"
    ],
    "resolver": "jest-pnp-resolver",
    "setupFiles": [
        "react-app-polyfill/jsdom"
    ],
    "testMatch": [
        "<rootDir>/src/**/__tests__/**/*.{js,jsx}",
        "<rootDir>/src/**/?(*.)(spec|test).{js,jsx}"
    ],
    "testEnvironment": "jsdom",
    "testURL": "http://localhost",
    "transform": {
        "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
        "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
        "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
        "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$",
        "^.+\\.module\\.(css|sass|scss)$"
    ],
    "moduleNameMapper": {
        "^react-native$": "react-native-web",
        "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
        "web.js",
        "js",
        "json",
        "web.jsx",
        "jsx",
        "node"
    ]
},
"babel": {
    "presets": [
        "react-app"
    ]
},
"devDependencies": {
       "html-webpack-plugin": "^4.0.0-beta.2",
       "react-hot-loader": "^4.0.0",
       "tap": "^11.0.0-rc.3",
       "webpack-bundle-tracker": "^0.4.2-beta",
       "webpack-cli": "^3.1.2"
    }
}
</code>```

webpack.config.dev.js file:
    "use strict";

```<code>const path = require("path");
const webpack = require("webpack");
const PnpWebpackPlugin = require("pnp-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-
webpack-plugin");
const InterpolateHtmlPlugin = require("react-dev-
 utils/InterpolateHtmlPlugin");
 const WatchMissingNodeModulesPlugin = require("react-dev-
  utils/WatchMissingNodeModulesPlugin");
  const ModuleScopePlugin = require("react-dev-
  utils/ModuleScopePlugin");
  const getCSSModuleLocalIdent = require("react-dev-
     utils/getCSSModuleLocalIdent");
 const getClientEnvironment = require("./env");
 const paths = require("./paths");
 const ManifestPlugin = require("webpack-manifest-plugin");
 const ModuleNotFoundPlugin = require("react-dev-
utils/ModuleNotFoundPlugin");

 // Webpack uses `publicPath` to determine where the app is being
served from.
 // In development, we always serve from the root. This makes config
 easier.
 //const publicPath = '/';
 // `publicUrl` is just like `publicPath`, but we will provide it to our app
 // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in
 JavaScript.
 // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than
       %PUBLIC_PATH%xyz.

    const publicPath = "http://localhost:3000/";
   const publicUrl = "http://localhost:3000/";
     // Get environment variables to inject into our app.
    const env = getClientEnvironment(publicUrl);
   const BundleTracker = require("webpack-bundle-tracker");
    // style files regexes
     const cssRegex = /\.css$/;
     const cssModuleRegex = /\.module\.css$/;
    const sassRegex = /\.(scss|sass)$/;
 const sassModuleRegex = /\.module\.(scss|sass)$/;

 // common function to get style loaders
 const getStyleLoaders = (cssOptions, preProcessor) => {
  const loaders = [
    require.resolve("style-loader"),
     {
           loader: require.resolve("css-loader"),
           options: cssOptions
      },
     {
  // Options for PostCSS as we reference these options twice
  // Adds vendor prefixing based on your specified browser support in
  // package.json
  loader: require.resolve("postcss-loader"),
  options: {
    // Necessary for external CSS imports to work
    // https://github.com/facebook/create-react-app/issues/2677
    ident: "postcss",
    plugins: () => [
      require("postcss-flexbugs-fixes"),
      require("postcss-preset-env")({
        autoprefixer: {
          flexbox: "no-2009"
        },
        stage: 3
      })
    ]
  }
   }
 ];
 if (preProcessor) {
   loaders.push(require.resolve(preProcessor));
 }
 return loaders;
};

 // This is the development configuration.
 // It is focused on developer experience and fast rebuilds.
 // The production configuration is different and lives in a separate
    file.
   module.exports = {
      mode: "development",
       // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
       // See the discussion in https://github.com/facebook/create-react-app/issues/343
     devtool: "cheap-module-source-map",
   // These are the "entry points" to our application.
    // This means they will be the "root" imports that are included in JS bundle.
    entry: [
        // Include an alternative client for WebpackDevServer. A client's job is to
      // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
     // of CSS changes), or refresh the page (in case of JS changes). When you
           // make a syntax error, this client will display a syntax error overlay.
   // Note: instead of the default WebpackDevServer client, we use a custom one
     // to bring better experience for Create React App users. You can replace
      // the line below with these two lines if you prefer the stock client:
       // require.resolve('webpack-dev-server/client') + '?/',
       // require.resolve('webpack/hot/dev-server'),
     require.resolve("react-dev-utils/webpackHotDevClient"),
     require.resolve("webpack-dev-server/client") + "?
     http://localhost:3000",
     require.resolve("webpack/hot/dev-server"),
      // Finally, this is your app's code:
      paths.appIndexJs
        // We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
    // changing JS code would still trigger a refresh.
  ],
   output: {
     // Add /* filename */ comments to generated require()s in the output.
      pathinfo: true,
          // This does not produce a real file. It's just the virtual path that is
       // served by WebpackDevServer in development. This is the JS bundle
    // containing code from all our entry points, and the Webpack runtime.
       filename: "static/js/bundle.js",
// There are also additional JS chunk files if you use code splitting.
chunkFilename: "static/js/[name].chunk.js",
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
  path.resolve(info.absoluteResourcePath).replace(/\\/g, "/")
  },
   optimization: {
     // Automatically split vendor and commons
    // https://twitter.com/wSokra/status/969633336732905474
    // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
  chunks: "all",
  name: false
},
minimize: false,
// Keep the runtime chunk seperated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
    runtimeChunk: true
  },
   resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ["node_modules"].concat(
  // It is guaranteed to exist because we tweak it in `env.js`
  process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: [".mjs", ".web.js", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
  // Support React Native Web
  // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  "react-native": "react-native-web"
},
plugins: [
  // Adds support for installing with Plug'n'Play, leading to faster installs and adding
  // guards against forgotten dependencies and such.
  PnpWebpackPlugin,
  // Prevents users from importing files from outside of src/ (or node_modules/).
  // This often causes confusion because we only process files within src/ with babel.
  // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  // please link the files into your node_modules/ and let module-resolution kick in.
  // Make sure your source files are compiled, as they will not be processed in any way.
  new BundleTracker({
    path: paths.statsRoot,
    filename: "webpack-stats.dev.json"
  }),
  new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
]
 },
   resolveLoader: {
plugins: [
  // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
  // from the current package.
  PnpWebpackPlugin.moduleLoader(module)
]
  },
  module: {
strictExportPresence: true,
rules: [
  // Disable require.ensure as it's not a standard language feature.
  { parser: { requireEnsure: false } },

  // First, run the linter.
  // It's important to do this before Babel processes the JS.
  {
    test: /\.(js|mjs|jsx)$/,
    enforce: "pre",
    use: [
      {
        options: {
          formatter: require.resolve("react-dev-utils/eslintFormatter"),
          eslintPath: require.resolve("eslint")
        },
        loader: require.resolve("eslint-loader")
      }
    ],
    include: paths.appSrc
  },
  {
    // "oneOf" will traverse all following loaders until one will
    // match the requirements. When no loader matches it will fall
    // back to the "file" loader at the end of the loader list.
    oneOf: [
      // "url" loader works like "file" loader except that it embeds assets
      // smaller than specified limit in bytes as data URLs to avoid requests.
      // A missing `test` is equivalent to a match.
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve("url-loader"),
        options: {
          limit: 10000,
          name: "static/media/[name].[hash:8].[ext]"
        }
      },
      // Process application JS with Babel.
      // The preset includes JSX, Flow, and some ESnext features.
      {
        test: /\.(js|mjs|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve("babel-loader"),
        options: {
          customize: require.resolve(
            "babel-preset-react-app/webpack-overrides"
          ),

             plugins: [
            [
              require.resolve("babel-plugin-named-asset-import"),
              {
                loaderMap: {
                  svg: {
                    ReactComponent: "@svgr/webpack?-prettier,-svgo![path]"
                  }
                }
              }
            ]
          ],
          // This is a feature of `babel-loader` for webpack (not Babel itself).
          // It enables caching results in ./node_modules/.cache/babel-loader/
          // directory for faster rebuilds.
          cacheDirectory: true,
          // Don't waste time on Gzipping the cache
          cacheCompression: false
        }
      },
      // Process any JS outside of the app with Babel.
      // Unlike the application JS, we only compile the standard ES features.
      {
        test: /\.(js|mjs)$/,
        exclude: /@babel(?:\/|\\{1,2})runtime/,
        loader: require.resolve("babel-loader"),
        options: {
          babelrc: false,
          configFile: false,
          compact: false,
          presets: [
            [
              require.resolve("babel-preset-react-app/dependencies"),
              { helpers: true }
            ]
          ],
          cacheDirectory: true,
          // Don't waste time on Gzipping the cache
          cacheCompression: false,

          // If an error happens in a package, it's possible to be
          // because it was compiled. Thus, we don't want the browser
          // debugger to show the original code. Instead, the code
          // being evaluated would be much more helpful.
          sourceMaps: false
        }
      },
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader turns CSS into JS modules that inject <style> tags.
      // In production, we use a plugin to extract that CSS to a file, but
      // in development "style" loader enables hot editing of CSS.
      // By default we support CSS Modules with the extension .module.css
      {
        test: cssRegex,
        exclude: cssModuleRegex,
        use: getStyleLoaders({
          importLoaders: 1
        })
      },
      // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
      // using the extension .module.css
      {
        test: cssModuleRegex,
        use: getStyleLoaders({
          importLoaders: 1,
          modules: true,
          getLocalIdent: getCSSModuleLocalIdent
        })
      },
      // Opt-in support for SASS (using .scss or .sass extensions).
      // Chains the sass-loader with the css-loader and the style-loader
      // to immediately apply all styles to the DOM.
      // By default we support SASS Modules with the
      // extensions .module.scss or .module.sass
      {
        test: sassRegex,
        exclude: sassModuleRegex,
        use: getStyleLoaders({ importLoaders: 2 }, "sass-loader")
      },
      // Adds support for CSS Modules, but using SASS
      // using the extension .module.scss or .module.sass
      {
        test: sassModuleRegex,
        use: getStyleLoaders(
          {
            importLoaders: 2,
            modules: true,
            getLocalIdent: getCSSModuleLocalIdent
          },
          "sass-loader"
        )
      },
      // "file" loader makes sure those assets get served by WebpackDevServer.
      // When you `import` an asset, you get its (virtual) filename.
      // In production, they would get copied to the `build` folder.
      // This loader doesn't use a "test" so it will catch all modules
      // that fall through the other loaders.
      {
        // Exclude `js` files to keep "css" loader working as it injects
        // its runtime that would otherwise be processed through "file" loader.
        // Also exclude `html` and `json` extensions so they get processed
        // by webpacks internal loaders.
        exclude: [/\.(js|mjs|jsx)$/, /\.html$/, /\.json$/],
        loader: require.resolve("file-loader"),
        options: {
          name: "static/media/[name].[hash:8].[ext]"
        }
      }
    ]
  }
  // ** STOP ** Are you adding a new loader?
  // Make sure to add the new loader(s) before the "file" loader.
]
 },
   plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
  inject: true,
  template: paths.appHtml
}),

// new InterpolateHtmlPlugin({
//   name: "xu"
// }),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
  fileName: "asset-manifest.json",
  publicPath: publicPath
})
 ],

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty"
 },
     // Turn off performance processing because we utilize
   // our own hints via the FileSizeReporter
 performance: false
};
</code>```

start.js file:
       "use strict";

```<code>      // Do this as the first thing so that any code reading it knows the right env.
   process.env.BABEL_ENV = "development";
   process.env.NODE_ENV = "development";

  // Makes the script crash on unhandled rejections instead of silently
   // ignoring them. In the future, promise rejections that are not handled will
  // terminate the Node.js process with a non-zero exit code.
   process.on("unhandledRejection", err => {
      throw err;
   });

   // Ensure environment variables are read.
  require("../config/env");

   const fs = require("fs");
  const chalk = require("chalk");
  const webpack = require("webpack");
const WebpackDevServer = require("webpack-dev-server");
const clearConsole = require("react-dev-utils/clearConsole");
const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles");
const {
  choosePort,
  createCompiler,
 prepareProxy,
 prepareUrls
} = require("react-dev-utils/WebpackDevServerUtils");
 const openBrowser = require("react-dev-utils/openBrowser");
 const paths = require("../config/paths");
 const config = require("../config/webpack.config.dev");
 const createDevServerConfig =
 require("../config/webpackDevServer.config");

 const useYarn = fs.existsSync(paths.yarnLockFile);
 const isInteractive = process.stdout.isTTY;

 // Warn and crash if required files are missing
 if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
        process.exit(1);
  }

 // Tools like Cloud9 rely on this.
      const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
  const HOST = process.env.HOST || "0.0.0.0";

 if (process.env.HOST) {
    console.log(
     chalk.cyan(
  `   Attempting to bind to HOST environment variable: ${chalk.yellow(
    chalk.bold(process.env.HOST)
  )}`
  )
 );
   console.log(
   `If this was unintentional, check that you haven't mistakenly set it in your shell.`
  );
      console.log(
     `Learn more here:`
   );
 console.log();
}

         // We require that you explictly set browsers and do not fall
    back to
  // browserslist defaults.
    const { checkBrowsers } = require("react-dev-utils/browsersHelper");
      checkBrowsers(paths.appPath, isInteractive)
     .then(() => {
           // We attempt to use the default port but if it is busy, we offer the user to
         // run on a different port. `choosePort()` Promise resolves to the next free port.
        return choosePort(HOST, DEFAULT_PORT);
      })
       .then(port => {
       if (port == null) {
          // We have not found a port.
         return;
         }
    const protocol = process.env.HTTPS === "true" ? "https" : "http";
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = createDevServerConfig(
  proxyConfig,
  urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
  if (err) {
    return console.log(err);
  }
  if (isInteractive) {
    clearConsole();
  }
  console.log(chalk.cyan("Starting the development server...\n"));
  openBrowser(urls.localUrlForBrowser);
});

["SIGINT", "SIGTERM"].forEach(function(sig) {
  process.on(sig, function() {
    devServer.close();
    process.exit();
  });
});
 })
 .catch(err => {
   if (err && err.message) {
     console.log(err.message);
   }
   process.exit(1);
 });
</code>```

Error Stacktrace:

```<code>> project@0.1.0 start /usr/react_projects/project
> node scripts/start.js

 Cannot read property 'tap' of undefined
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! project@0.1.0 start: `node scripts/start.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the project@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

I don't understand why it is giving Cannot find property "tap" undefined.

答:
I had the same exact problem. You have to add @babel/preset-react library to your package.json file.

Run yarn yarn add @babel/preset-react or npm install @babel/preset-react

Body:
I have a React application configured with Django Application. I have different webpack config files for development and production, When I run "npm run start", it gives me error that:

Cannot read property 'tap' of undefined

package.json file:

{
    "name": "project",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
    "@babel/core": "7.1.0",
    "@svgr/webpack": "2.4.1",
    "ajv": "^6.5.4",
    "ajv-keywords": "^3.2.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "9.0.0",
    "babel-jest": "23.6.0",
    "babel-loader": "8.0.4",
    "babel-plugin-named-asset-import": "^0.2.2",
    "babel-preset-react-app": "^5.0.4",
    "bfj": "6.1.1",
    "case-sensitive-paths-webpack-plugin": "2.1.2",
    "chalk": "2.4.1",
    "css-loader": "1.0.0",
    "dotenv": "6.0.0",
    "dotenv-expand": "4.2.0",
    "eslint": "5.6.0",
    "eslint-config-react-app": "^3.0.4",
    "eslint-loader": "2.1.1",
    "eslint-plugin-flowtype": "2.50.1",
    "eslint-plugin-import": "2.14.0",
    "eslint-plugin-jsx-a11y": "6.1.2",
    "eslint-plugin-react": "7.11.1",
    "file-loader": "2.0.0",
    "fs-extra": "7.0.0",
    "identity-obj-proxy": "3.0.0",
    "jest": "23.6.0",
    "jest-pnp-resolver": "1.0.1",
    "jest-resolve": "23.6.0",
    "mini-css-extract-plugin": "0.4.3",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "pnp-webpack-plugin": "1.1.0",
    "postcss-flexbugs-fixes": "4.1.0",
    "postcss-loader": "3.0.0",
    "postcss-preset-env": "6.0.6",
    "postcss-safe-parser": "4.0.1",
    "react": "^16.6.0",
    "react-app-polyfill": "^0.1.3",
    "react-dev-utils": "^6.0.5",
    "react-dom": "^16.6.0",
    "resolve": "1.8.1",
    "sass-loader": "7.1.0",
    "style-loader": "0.23.0",
    "terser-webpack-plugin": "1.1.0",
    "url-loader": "1.1.1",
    "webpack": "4.19.1",
    "webpack-dev-server": "3.1.9",
    "webpack-manifest-plugin": "2.0.4",
    "workbox-webpack-plugin": "3.6.2"
},
"scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
},
"eslintConfig": {
    "extends": "react-app"
},
"browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
],
"jest": {
    "collectCoverageFrom": [
        "src/**/*.{js,jsx}"
    ],
    "resolver": "jest-pnp-resolver",
    "setupFiles": [
        "react-app-polyfill/jsdom"
    ],
    "testMatch": [
        "<rootDir>/src/**/__tests__/**/*.{js,jsx}",
        "<rootDir>/src/**/?(*.)(spec|test).{js,jsx}"
    ],
    "testEnvironment": "jsdom",
    "testURL": "http://localhost",
    "transform": {
        "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
        "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
        "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
        "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$",
        "^.+\\.module\\.(css|sass|scss)$"
    ],
    "moduleNameMapper": {
        "^react-native$": "react-native-web",
        "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
        "web.js",
        "js",
        "json",
        "web.jsx",
        "jsx",
        "node"
    ]
},
"babel": {
    "presets": [
        "react-app"
    ]
},
"devDependencies": {
       "html-webpack-plugin": "^4.0.0-beta.2",
       "react-hot-loader": "^4.0.0",
       "tap": "^11.0.0-rc.3",
       "webpack-bundle-tracker": "^0.4.2-beta",
       "webpack-cli": "^3.1.2"
    }
}

webpack.config.dev.js file:
    "use strict";

const path = require("path");
const webpack = require("webpack");
const PnpWebpackPlugin = require("pnp-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CaseSensitivePathsPlugin = require("case-sensitive-paths-
webpack-plugin");
const InterpolateHtmlPlugin = require("react-dev-
 utils/InterpolateHtmlPlugin");
 const WatchMissingNodeModulesPlugin = require("react-dev-
  utils/WatchMissingNodeModulesPlugin");
  const ModuleScopePlugin = require("react-dev-
  utils/ModuleScopePlugin");
  const getCSSModuleLocalIdent = require("react-dev-
     utils/getCSSModuleLocalIdent");
 const getClientEnvironment = require("./env");
 const paths = require("./paths");
 const ManifestPlugin = require("webpack-manifest-plugin");
 const ModuleNotFoundPlugin = require("react-dev-
utils/ModuleNotFoundPlugin");

 // Webpack uses `publicPath` to determine where the app is being
served from.
 // In development, we always serve from the root. This makes config
 easier.
 //const publicPath = '/';
 // `publicUrl` is just like `publicPath`, but we will provide it to our app
 // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in
 JavaScript.
 // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than
       %PUBLIC_PATH%xyz.

    const publicPath = "http://localhost:3000/";
   const publicUrl = "http://localhost:3000/";
     // Get environment variables to inject into our app.
    const env = getClientEnvironment(publicUrl);
   const BundleTracker = require("webpack-bundle-tracker");
    // style files regexes
     const cssRegex = /\.css$/;
     const cssModuleRegex = /\.module\.css$/;
    const sassRegex = /\.(scss|sass)$/;
 const sassModuleRegex = /\.module\.(scss|sass)$/;

 // common function to get style loaders
 const getStyleLoaders = (cssOptions, preProcessor) => {
  const loaders = [
    require.resolve("style-loader"),
     {
           loader: require.resolve("css-loader"),
           options: cssOptions
      },
     {
  // Options for PostCSS as we reference these options twice
  // Adds vendor prefixing based on your specified browser support in
  // package.json
  loader: require.resolve("postcss-loader"),
  options: {
    // Necessary for external CSS imports to work
    // https://github.com/facebook/create-react-app/issues/2677
    ident: "postcss",
    plugins: () => [
      require("postcss-flexbugs-fixes"),
      require("postcss-preset-env")({
        autoprefixer: {
          flexbox: "no-2009"
        },
        stage: 3
      })
    ]
  }
   }
 ];
 if (preProcessor) {
   loaders.push(require.resolve(preProcessor));
 }
 return loaders;
};

 // This is the development configuration.
 // It is focused on developer experience and fast rebuilds.
 // The production configuration is different and lives in a separate
    file.
   module.exports = {
      mode: "development",
       // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
       // See the discussion in https://github.com/facebook/create-react-app/issues/343
     devtool: "cheap-module-source-map",
   // These are the "entry points" to our application.
    // This means they will be the "root" imports that are included in JS bundle.
    entry: [
        // Include an alternative client for WebpackDevServer. A client's job is to
      // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
     // of CSS changes), or refresh the page (in case of JS changes). When you
           // make a syntax error, this client will display a syntax error overlay.
   // Note: instead of the default WebpackDevServer client, we use a custom one
     // to bring better experience for Create React App users. You can replace
      // the line below with these two lines if you prefer the stock client:
       // require.resolve('webpack-dev-server/client') + '?/',
       // require.resolve('webpack/hot/dev-server'),
     require.resolve("react-dev-utils/webpackHotDevClient"),
     require.resolve("webpack-dev-server/client") + "?
     http://localhost:3000",
     require.resolve("webpack/hot/dev-server"),
      // Finally, this is your app's code:
      paths.appIndexJs
        // We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
    // changing JS code would still trigger a refresh.
  ],
   output: {
     // Add /* filename */ comments to generated require()s in the output.
      pathinfo: true,
          // This does not produce a real file. It's just the virtual path that is
       // served by WebpackDevServer in development. This is the JS bundle
    // containing code from all our entry points, and the Webpack runtime.
       filename: "static/js/bundle.js",
// There are also additional JS chunk files if you use code splitting.
chunkFilename: "static/js/[name].chunk.js",
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
  path.resolve(info.absoluteResourcePath).replace(/\\/g, "/")
  },
   optimization: {
     // Automatically split vendor and commons
    // https://twitter.com/wSokra/status/969633336732905474
    // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
  chunks: "all",
  name: false
},
minimize: false,
// Keep the runtime chunk seperated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
    runtimeChunk: true
  },
   resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ["node_modules"].concat(
  // It is guaranteed to exist because we tweak it in `env.js`
  process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: [".mjs", ".web.js", ".js", ".json", ".web.jsx", ".jsx"],
alias: {
  // Support React Native Web
  // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  "react-native": "react-native-web"
},
plugins: [
  // Adds support for installing with Plug'n'Play, leading to faster installs and adding
  // guards against forgotten dependencies and such.
  PnpWebpackPlugin,
  // Prevents users from importing files from outside of src/ (or node_modules/).
  // This often causes confusion because we only process files within src/ with babel.
  // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  // please link the files into your node_modules/ and let module-resolution kick in.
  // Make sure your source files are compiled, as they will not be processed in any way.
  new BundleTracker({
    path: paths.statsRoot,
    filename: "webpack-stats.dev.json"
  }),
  new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson])
]
 },
   resolveLoader: {
plugins: [
  // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
  // from the current package.
  PnpWebpackPlugin.moduleLoader(module)
]
  },
  module: {
strictExportPresence: true,
rules: [
  // Disable require.ensure as it's not a standard language feature.
  { parser: { requireEnsure: false } },

  // First, run the linter.
  // It's important to do this before Babel processes the JS.
  {
    test: /\.(js|mjs|jsx)$/,
    enforce: "pre",
    use: [
      {
        options: {
          formatter: require.resolve("react-dev-utils/eslintFormatter"),
          eslintPath: require.resolve("eslint")
        },
        loader: require.resolve("eslint-loader")
      }
    ],
    include: paths.appSrc
  },
  {
    // "oneOf" will traverse all following loaders until one will
    // match the requirements. When no loader matches it will fall
    // back to the "file" loader at the end of the loader list.
    oneOf: [
      // "url" loader works like "file" loader except that it embeds assets
      // smaller than specified limit in bytes as data URLs to avoid requests.
      // A missing `test` is equivalent to a match.
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve("url-loader"),
        options: {
          limit: 10000,
          name: "static/media/[name].[hash:8].[ext]"
        }
      },
      // Process application JS with Babel.
      // The preset includes JSX, Flow, and some ESnext features.
      {
        test: /\.(js|mjs|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve("babel-loader"),
        options: {
          customize: require.resolve(
            "babel-preset-react-app/webpack-overrides"
          ),

             plugins: [
            [
              require.resolve("babel-plugin-named-asset-import"),
              {
                loaderMap: {
                  svg: {
                    ReactComponent: "@svgr/webpack?-prettier,-svgo![path]"
                  }
                }
              }
            ]
          ],
          // This is a feature of `babel-loader` for webpack (not Babel itself).
          // It enables caching results in ./node_modules/.cache/babel-loader/
          // directory for faster rebuilds.
          cacheDirectory: true,
          // Don't waste time on Gzipping the cache
          cacheCompression: false
        }
      },
      // Process any JS outside of the app with Babel.
      // Unlike the application JS, we only compile the standard ES features.
      {
        test: /\.(js|mjs)$/,
        exclude: /@babel(?:\/|\\{1,2})runtime/,
        loader: require.resolve("babel-loader"),
        options: {
          babelrc: false,
          configFile: false,
          compact: false,
          presets: [
            [
              require.resolve("babel-preset-react-app/dependencies"),
              { helpers: true }
            ]
          ],
          cacheDirectory: true,
          // Don't waste time on Gzipping the cache
          cacheCompression: false,

          // If an error happens in a package, it's possible to be
          // because it was compiled. Thus, we don't want the browser
          // debugger to show the original code. Instead, the code
          // being evaluated would be much more helpful.
          sourceMaps: false
        }
      },
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader turns CSS into JS modules that inject


来源: stackexchange

问:
Single Row Table in Entity Framework 6
I couldn't find a solution for this problem but the title makes clear what I want.

Is it possible to create a single row table (I only need to store a boolean value in a table)? And how can I configure this constraint with Fluent API?

答:
In EF Core you can set the check constraint for the primary key. It enforces that column Id must have value that is equal to 1.

```<code>modelBuilder.Entity<YourTable>(e =>
{
   e.HasCheckConstraint("CK_Table_Column", "[Id] = 1");

   e.HasData(...) //optionally add some initial date for Id = 1
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Single Row Table in Entity Framework 6

Body:
In EF Core you can set the check constraint for the primary key. It enforces that column Id must have value that is equal to 1.

modelBuilder.Entity<YourTable>(e =>
{
   e.HasCheckConstraint("CK_Table_Column", "[Id] = 1");

   e.HasData(...) //optionally add some initial date for Id = 1
});

ContentLicense: CC BY-SA 4.0


问:
Csh echo foreach loop index
Hi I'm new to shell scripting in csh and I need help with an annoying problem. Take the code below:

```<code>   set s = ("one" "two" "three" "four")
   foreach i (${s})
      echo $i"-" [what do I put here to get the index?]
   end
</code>```

This yields the output

```<code>  one-
  two-
  three-
  four-
</code>```

However, I would also like to print out the loop counter index too, so:

```<code>  one-1
  two-2
  three-3
  four-4
</code>```

Sorry if this question is really basic but I don't have much experience in shell scripting (let alone csh) and forums and other stack-overflow posts didn't help much.

答:
For var in One-1 Two-2 Three-3 Four-4

do

echo $var

done

Title: Csh echo foreach loop index

Body:
Hi I'm new to shell scripting in csh and I need help with an annoying problem. Take the code below:

   set s = ("one" "two" "three" "four")
   foreach i (${s})
      echo $i"-" [what do I put here to get the index?]
   end

This yields the output

  one-
  two-
  three-
  four-

However, I would also like to print out the loop counter index too, so:

  one-1
  two-2
  three-3
  four-4

Sorry if this question is really basic but I don't have much experience in shell scripting (let alone csh) and forums and other stack-overflow posts didn't help much.


问:
Error in genereting_fuction(100) : could not find function "genereting_fuction
I created this function to generate the data with the characteristics I need:

```<code>genereting_fuction<-function(n){

  X1=rnorm(n)+mean_shifts[1]
  X4=rnorm(n)+mean_shifts[4]
  X2=X1*p12+std_e2*rnorm(n)+mean_shifts[2]
  X3=X1*p13+X4*p43+std_e3*rnorm(n)+mean_shifts[3]
  X5=X2*p25+X3*p35+std_e5*rnorm(n)+mean_shifts[5]
  sample=cbind(X1,X2,X3,X4,X5)
  return(sample)
}
</code>```

if I call it for a single item it works but when I call it in the applay function as follows:

```<code>dati<-lapply(1:100, genereting_fuction(100))
</code>```

I get this error:
Error in genereting_fuction(100) :
could not find function "genereting_fuction"

答:
Note that I prefer the replicate solution by @Jakub.Novotny for your purpose, but to understand what went wrong using lapply, this is why and how to solve it.

Using apply and a function, it assumes x the value of your apply to be provided always in the function.

To make it work you can do two things.

lapply(1:100, function(x) genereting_fuction(100))

include x in your function like genereting_fuction <- function(x, n) { # code here } and then you can use lapply(1:100, genereting_fuction, n = 100)

Body:
I created this function to generate the data with the characteristics I need:

genereting_fuction<-function(n){

  X1=rnorm(n)+mean_shifts[1]
  X4=rnorm(n)+mean_shifts[4]
  X2=X1*p12+std_e2*rnorm(n)+mean_shifts[2]
  X3=X1*p13+X4*p43+std_e3*rnorm(n)+mean_shifts[3]
  X5=X2*p25+X3*p35+std_e5*rnorm(n)+mean_shifts[5]
  sample=cbind(X1,X2,X3,X4,X5)
  return(sample)
}

if I call it for a single item it works but when I call it in the applay function as follows:

dati<-lapply(1:100, genereting_fuction(100))

I get this error:
Error in genereting_fuction(100) :
could not find function "genereting_fuction"


问:
The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, in Flutter How can I change the minimum IOS Deploying Target
I changed everything to 9.0 in the project but I'm having the same error in a lot of pods.

I tried doing a lot of different things but nothing worked. Does anyone know how can I fix this?

```<code>warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'gRPC-C++-gRPCCertificates-Cpp' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'GoogleAppMeasurement' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'FirebaseAuth' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'GoogleUtilities' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'vibration' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'nanopb' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'BoringSSL-GRPC' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'gRPC-Core' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'gRPC-C++' from project 'Pods')
</code>```

Encountered error while building for device.

答:
Change MinimumOSVersion to 9.0 in /ios/Flutter/AppFrameworkInfo.plist.

Then in ios/Runner.xcodeproj/project.bpxproj replace
IPHONEOS_DEPLOYMENT_TARGET = 8.0 to IPHONEOS_DEPLOYMENT_TARGET = 9.0 in three lines.

It also works if you are building your .ipa whit codemagic

Body:
I changed everything to 9.0 in the project but I'm having the same error in a lot of pods.

I tried doing a lot of different things but nothing worked. Does anyone know how can I fix this?

warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'gRPC-C++-gRPCCertificates-Cpp' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'GoogleAppMeasurement' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'FirebaseAuth' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'GoogleUtilities' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'vibration' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'nanopb' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'BoringSSL-GRPC' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'gRPC-Core' from project 'Pods')
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is
9.0 to 14.0.99. (in target 'gRPC-C++' from project 'Pods')

Encountered error while building for device.


问:
Interactive Browser Credential "You can't sign in here with a personal account. Use your work or school account instead."
I am attempting to implement Interactive Browser Credential with Azure Identity (JS) in my app so that users can authenticate to their own Azure accounts for my dev tool. I got advice that app registration in Azure AD would be required on a Reddit thread (https://www.reddit.com/r/AZURE/comments/smcl15/azure_identity_sdk_js_how_to_authenticate_to/). I have now done so.

I have registered localhost:8083 and localhost:8085 as redirect URIs and selected the option to allow Account in any organizational directory. However, I am still getting the error "You can't sign in here with a personal account. Use your work or school account instead." Every answer(Access with personal account to multi-tenant application AAD) I have read on the topic says that I need to set    "signInAudience": "AzureADandPersonalMicrosoftAccount" in the manifest. However, that is how my manifest already is and has been since the beginning. How do I fix the error?

答:
This error may occur in one of the below two scenarios.

1. Resource being different from client application

Please ensure the request resource is added to the applications required API permissions and the resource API has been consented to .Resource for which you want an access token, you can pass either the Resource URI of a Web APP, or the client Id of the target Web API.  It's important to note that the token  contains the resource as requested (audience).

If you have a permission something like user_impersonation, try by giving scope as https://management.azure.com/user_impersonation

Please check if you need to add api version as query string as per  Azure REST API reference documentation | Microsoft Docs.

Make sure you see the app in the app registrations >all applications blade while Searching for the appId present in the error provided.

2: Resource and client  is the same app registration

In app registrations ,after exposing the api and adding permissions and scope, Ensure the app has been consented to permission.

For example:


问:
Macro questions
On a software project (some old C compiler) we have a lot of variables which have to be saved normal and inverted.

Has somebody a idea how i can make a macro like that?

```<code>SET(SomeVariable, 137);
</code>```

which will execute

```<code>SomeVariable = 137;
SomeVariable_inverse = ~137;
</code>```

Edit:

The best Solution seems to be:

```<code>#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)
</code>```

Thanks for the answers

答:
One hazard I haven't seen mentioned is that the 'value' macro argument is evaluated twice in most of the solutions.  That can cause problems if someone tries something like this:

```<code>int x = 10;
SET(myVariable, x++);
</code>```

After this call, myVariable would be 10 and myVariable_inverse would be ~11.  Oops.  A minor change to JaredPar's solution solves this:

```<code>#define SET(var,value) do { var = (value); var##_inverse = ~(var); } while(0)
</code>```

OwnerDisplayName: nuriaion

ContentLicense: CC BY-SA 2.5

Title: Macro questions

Body:
On a software project (some old C compiler) we have a lot of variables which have to be saved normal and inverted.

Has somebody a idea how i can make a macro like that?

SET(SomeVariable, 137);

which will execute

SomeVariable = 137;
SomeVariable_inverse = ~137;

Edit:

The best Solution seems to be:

#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)

Thanks for the answers

LastEditorDisplayName: Evan Teran

Body:
One hazard I haven't seen mentioned is that the 'value' macro argument is evaluated twice in most of the solutions.  That can cause problems if someone tries something like this:

int x = 10;
SET(myVariable, x++);

After this call, myVariable would be 10 and myVariable_inverse would be ~11.  Oops.  A minor change to JaredPar's solution solves this:

#define SET(var,value) do { var = (value); var##_inverse = ~(var); } while(0)

OwnerDisplayName: Fred Larson


问:
Coldfuson CFScript "setSQL" method was not found
I've got a Coldfusion component, with a method in it called getColumnNames

This just queries a MySQL table, and returns the columnlist:

```<code>remote string function getColumnNames() {
    qProcessCars = new Query();
    qProcessCars.setDataSource('#APPLICATION.dsn#');
    qProcessCars.setSQL('SELECT * FROM sand_cars WHERE 1 LIMIT 1');
    qProcessCars = qProcessCars.Execute().getResult();

    return qProcessCars.columnlist;
}
</code>```

If I access this remotely in the browser, with page.cfc?method=getColumnNames, then I get the expected list of columns back.

However, if I try to access this from inside another method within the component, I get an error

```<code>remote string function otherFunction() {
   ...
   sColumns = getColumnNames();
   ...
}
</code>```

The error dump for the above code returns the message "The setSQL method was not found".

So can anyone help me find out why it works as a remote call, but not when called from another method inside the same component.

答:
Ah I've answered my own question again. Sorry.

I've used the same name qProcessCars else where in the component, I hadn't put var in front of them.

I don't know WHY that was causing the problem, but it was. Maybe setSQL can only be called once per query object?

Body:
I've got a Coldfusion component, with a method in it called getColumnNames

This just queries a MySQL table, and returns the columnlist:

remote string function getColumnNames() {
    qProcessCars = new Query();
    qProcessCars.setDataSource('#APPLICATION.dsn#');
    qProcessCars.setSQL('SELECT * FROM sand_cars WHERE 1 LIMIT 1');
    qProcessCars = qProcessCars.Execute().getResult();

    return qProcessCars.columnlist;
}

If I access this remotely in the browser, with page.cfc?method=getColumnNames, then I get the expected list of columns back.

However, if I try to access this from inside another method within the component, I get an error

remote string function otherFunction() {
   ...
   sColumns = getColumnNames();
   ...
}

The error dump for the above code returns the message "The setSQL method was not found".

So can anyone help me find out why it works as a remote call, but not when called from another method inside the same component.


问:
Does the Event Listeners in javascript deal only with the user interaction or with scripts too?
I have three inputs namely, field1, field2, and resultField. I have attached event listeners to the first of two respectively and am getting their values and subtracting the first one from the second one. I am assigning their result to the result field which serves as an "input" for the result Field. I have then attached an event Listener to the result Field but the problem is the event listener won't fire as soon as it receives the evaluated input from field1 and field2. Please find my code below.

let field1 = document.getElementById("field1");
let field2 = document.getElementById("field2");
let resultField = document.getElementById("fieldResult");
let value1 = field1.value;
let value2 = field2.value;

field1.addEventListener("input", result);
field2.addEventListener("input", result);
resultField.addEventListener("input", alertFunc);

function result() {
  value1 = field1.value;
  value2 = field2.value;
  let resultValue = value1 - value2;
  resultField.value = resultValue;
}

function alertFunc() {
  alert("We have an input in result Field.");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <label for="field1">Filed 1</label>
  <input type "number" id="field1"></input>
  <label for="field2">Filed 2</label>
  <input type "number" id="field2"></input>
  <label for="fieldResult">Result Filed</label>
  <input type "number" id="fieldResult" readonly></input>
</body>

</html></code>```

答:
Event are not fired if you update an input value with js (you have to explicitly fired it)

Event are send by browser when there is browser action (load, online...) or user action (click, keyup...) but not when you do myfield.value=

you have to explicitly fire the event after you update the field value with

```<code> resultField.dispatchEvent(new Event('input'));
</code>```

let field1 = document.getElementById("field1");
let field2 = document.getElementById("field2");
let resultField = document.getElementById("fieldResult");
let value1 = field1.value;
let value2 = field2.value;

field1.addEventListener("input", result);
field2.addEventListener("input", result);
resultField.addEventListener("input", alertFunc);

function result() {
  value1 = field1.value;
  value2 = field2.value;
  let resultValue = value1 - value2;
  resultField.value = resultValue;
  resultField.dispatchEvent(new Event('input'));
}

function alertFunc() {
  alert("We have an input in result Field.");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <label for="field1">Filed 1</label>
  <input type "number" id="field1"></input>
  <label for="field2">Filed 2</label>
  <input type "number" id="field2"></input>
  <label for="fieldResult">Result Filed</label>
  <input type "number" id="fieldResult" readonly></input>
</body>

</html></code>```

Body:
I have three inputs namely, field1, field2, and resultField. I have attached event listeners to the first of two respectively and am getting their values and subtracting the first one from the second one. I am assigning their result to the result field which serves as an "input" for the result Field. I have then attached an event Listener to the result Field but the problem is the event listener won't fire as soon as it receives the evaluated input from field1 and field2. Please find my code below.

let field1 = document.getElementById("field1");
let field2 = document.getElementById("field2");
let resultField = document.getElementById("fieldResult");
let value1 = field1.value;
let value2 = field2.value;

field1.addEventListener("input", result);
field2.addEventListener("input", result);
resultField.addEventListener("input", alertFunc);

function result() {
  value1 = field1.value;
  value2 = field2.value;
  let resultValue = value1 - value2;
  resultField.value = resultValue;
}

function alertFunc() {
  alert("We have an input in result Field.");
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

  Filed 1
  <input type "number" id="field1"></input>
  Filed 2
  <input type "number" id="field2"></input>
  Result Filed
  <input type "number" id="fieldResult" readonly></input>

Body:
Event are not fired if you update an input value with js (you have to explicitly fired it)

Event are send by browser when there is browser action (load, online...) or user action (click, keyup...) but not when you do myfield.value=

you have to explicitly fire the event after you update the field value with

 resultField.dispatchEvent(new Event('input'));

let field1 = document.getElementById("field1");
let field2 = document.getElementById("field2");
let resultField = document.getElementById("fieldResult");
let value1 = field1.value;
let value2 = field2.value;

field1.addEventListener("input", result);
field2.addEventListener("input", result);
resultField.addEventListener("input", alertFunc);

function result() {
  value1 = field1.value;
  value2 = field2.value;
  let resultValue = value1 - value2;
  resultField.value = resultValue;
  resultField.dispatchEvent(new Event('input'));
}

function alertFunc() {
  alert("We have an input in result Field.");
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <label for="field1">Filed 1</label>
  <input type "number" id="field1"></input>
  <label for="field2">Filed 2</label>
  <input type "number" id="field2"></input>
  <label for="fieldResult">Result Filed</label>
  <input type "number" id="fieldResult" readonly></input>
</body>

</html>


问:
Issue with onChange event in ant design upload component in react
I am trying to receive the files uploaded in the ant design upload component using the onCHange event but I keep encountering an error

"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'files')".

The code:

```<code><Form.Item>
    <Form.Item name="dragger" valuePropName="fileList" noStyle>
        <Upload.Dragger // onChange={(e)=> handleInputChange("file", e.target.files[0])}
            beforeUpload={() => false}
            name="files"
            accept=".apng,.avif,.gif,.jpg,.jpeg,.jfif,.pjpeg,.pjp,.png,.svg,.webp"
            action=""
            >
            <p className="ant-upload-drag-icon">
                <InboxOutlined />
            </p>
            <p className="text-dark">Click or drag file to this area to upload</p>
            <p className="text-muted">Support for PNG, JPG, GIF up to 10MB.</p>
        </Upload.Dragger>
    </Form.Item>
</Form.Item>
</code>```

I intend to manipulate the file in a function. I don't want to use the ant design upload component's upload functionality. I only wanted the drag and drop UI.

答:
The solution:

ant-design doesn't return the usual event object but it's own object. The object has another object called file which would have suited my code.

Therefore, I should have used: e.file instead of e.target.files[0]
That solves the error!

Body:
I am trying to receive the files uploaded in the ant design upload component using the onCHange event but I keep encountering an error

"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'files')".

The code:

<Form.Item>
    <Form.Item name="dragger" valuePropName="fileList" noStyle>
        <Upload.Dragger // onChange={(e)=> handleInputChange("file", e.target.files[0])}
            beforeUpload={() => false}
            name="files"
            accept=".apng,.avif,.gif,.jpg,.jpeg,.jfif,.pjpeg,.pjp,.png,.svg,.webp"
            action=""
            >

                <InboxOutlined />

Click or drag file to this area to upload

Support for PNG, JPG, GIF up to 10MB.

        </Upload.Dragger>
    </Form.Item>
</Form.Item>

I intend to manipulate the file in a function. I don't want to use the ant design upload component's upload functionality. I only wanted the drag and drop UI.


问:
Delete key and value form a dictionary, if it is longer than 5 symbols
How to create a new dictionary where all keys and values are converted to string type? If string length is more than 5 symbols it must be excluded from the answer (both the key and value)

My code now looks like this:

file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

key_values = file1data.items()
new_dictionary = {str(key):str(value) for key, value in key_values}

print((str(new_dictionary)))

```

It can covert all values and keys to a string type, but not detect if length is more than 5.

For example if is given this dictionary: {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

The result should be: {"1":"2","2":"5","1231":"14","-2":"7"}

答:
A simple way to do it is to iterate through the keys of the dictionary and check if you should delete it or not if yes add it to a list and delete it later

```<code>file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}
delete = list()
for key in file1data:
    if len(str(key)) > 5:
        delete.append(key)
for i in delete:
    del file1data[i]
</code>```

I know that it is not the most compact way to do it but it works

Body:
How to create a new dictionary where all keys and values are converted to string type? If string length is more than 5 symbols it must be excluded from the answer (both the key and value)

My code now looks like this:

file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

key_values = file1data.items()
new_dictionary = {str(key):str(value) for key, value in key_values}

print((str(new_dictionary)))

It can covert all values and keys to a string type, but not detect if length is more than 5.

For example if is given this dictionary: {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}

The result should be: {"1":"2","2":"5","1231":"14","-2":"7"}

Body:
A simple way to do it is to iterate through the keys of the dictionary and check if you should delete it or not if yes add it to a list and delete it later

file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}
delete = list()
for key in file1data:
    if len(str(key)) > 5:
        delete.append(key)
for i in delete:
    del file1data[i]

I know that it is not the most compact way to do it but it works


问:
JSON array transform with JOLT
I receive following JSON from some REST API:

{
  "operation_id" : [ 1405494, 1409934, 1420753 ],
  "operation_status" : "success"
}
```
<p>I want to split <code>operation_id</code> from array to get 1 by 1 value and create new JSON which should look like:</p>
<pre class="lang-json prettyprint-override"><code>{
  "operationsStatus": [
    {
      "operation_id": 1405494,
      "operation_status": "success"
    },
    {
      "operation_id": 1409934,
      "operation_status": "success"
    },
    {
      "operation_id": 1420753,
      "operation_status": "success"
    }
  ]
}
</code>```

Can I do it with JOLT spec?

答:
You can walk through the operation_id array by using a shift transformation such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "operation_id": {
          "*": {
            "@": "operationsStatus[&1].&2",
            "@(2,operation_status)": "operationsStatus[&1].operation_status"
          }
        }
      }
    }
  }
]
```

the Result of the demo on https://jolt-demo.appspot.com/

Title: JSON array transform with JOLT

Body:
I receive following JSON from some REST API:

{
  "operation_id" : [ 1405494, 1409934, 1420753 ],
  "operation_status" : "success"
}

I want to split operation_id from array to get 1 by 1 value and create new JSON which should look like:

{
  "operationsStatus": [
    {
      "operation_id": 1405494,
      "operation_status": "success"
    },
    {
      "operation_id": 1409934,
      "operation_status": "success"
    },
    {
      "operation_id": 1420753,
      "operation_status": "success"
    }
  ]
}

Can I do it with JOLT spec?

Body:
You can walk through the operation_id array by using a shift transformation such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "operation_id": {
          "*": {
            "@": "operationsStatus[&1].&2",
            "@(2,operation_status)": "operationsStatus[&1].operation_status"
          }
        }
      }
    }
  }
]

the Result of the demo on https://jolt-demo.appspot.com/


问:
How do I modify the background color of a List in SwiftUI?
I'm trying to recreate an UI I built with UIKit in SwiftUI but I'm running into some minor issues.

I want the change the color of the List here, but no property seems to work as I expects. Sample code below:

```<code>struct ListView: View {
    @EnvironmentObject var listData: ListData

       var body: some View {
        NavigationView {
            List(listData.items) { item in
                ListItemCell(item: item)
            }
            .content.background(Color.yellow) // not sure what content is defined as here
            .background(Image("paper-3")) // this is the entire screen
        }
    }
}

struct ListItemCell: View {
    let item: ListItem

    var body: some View {

        NavigationButton(destination: Text(item.name)) {
            Text("\(item.name) ........................................................................................................................................................................................................")
                .background(Color.red) // not the area I'm looking for
        }.background(Color.blue) // also not the area I'm looking for
    }
}
</code>```

答:
Using UITableView.appearance().backgroundColor is not a good idea as it changes the backgroundColor of all tables. I found a working solution for color changing at the exact table you selected in iOS 14, 15.

We will change the color using a modifier that needs to be applied inside the List

```<code>extension View {

    func backgroundTableModifier(_ color: UIColor? = nil) -> some View {
        self.modifier(BackgroundTableModifier(color: color))
    }

}
</code>```

Our task is to find the UITableView and after that change the color.

```<code>private struct BackgroundTableModifier: ViewModifier {

    private let color: UIColor?
    @State private var tableView: UITableView?

    init(color: UIColor?) {
        self.color = color
    }

    public func body(content: Content) -> some View {
        if tableView?.backgroundColor != color {
            content
                .overlay(BackgroundTableViewRepresentable(tableBlock: { tableView in
                    tableView.backgroundColor = color
                    self.tableView = tableView
                }))
        } else {
            content
        }
    }
}

private struct BackgroundTableViewRepresentable: UIViewRepresentable {

    var tableBlock: (UITableView) -> ()

    func makeUIView(context: Context) -> BackgroundTableView  {
        let view = BackgroundTableView(tableBlock: tableBlock)
        return view
    }

    func updateUIView(_ uiView: BackgroundTableView, context: Context) {}
}

class BackgroundTableView: UIView {

    var tableBlock: (UITableView) -> ()

    init(tableBlock: @escaping (UITableView) -> ()) {
        self.tableBlock = tableBlock
        super.init(frame: .zero)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        if let tableView = findTableView(in: self) {
            tableBlock(tableView)
        }
    }

    private func findTableView(in view: UIView) -> UITableView? {
        if let tableView = view as? UITableView {
            return tableView
        }

        if let superView = view.superview {
            return findTableView(in: superView)
        }

        return nil
    }

}
</code>```

In order to find UITableView, the modifier must be inside the List. Naturally, you need to ensure that the modifier is called only once, you do not need to apply it to each row. Here is an example of usage

```<code>List {
   rows()
     .backgroundTableModifier(.clear)
}

func rows() -> some View {
    ForEach(0..<10, id: \.self) { index in
        Row()
    }
}
</code>```

Body:
I'm trying to recreate an UI I built with UIKit in SwiftUI but I'm running into some minor issues.

I want the change the color of the List here, but no property seems to work as I expects. Sample code below:

struct ListView: View {
    @EnvironmentObject var listData: ListData

       var body: some View {
        NavigationView {
            List(listData.items) { item in
                ListItemCell(item: item)
            }
            .content.background(Color.yellow) // not sure what content is defined as here
            .background(Image("paper-3")) // this is the entire screen
        }
    }
}

struct ListItemCell: View {
    let item: ListItem

    var body: some View {

        NavigationButton(destination: Text(item.name)) {
            Text("\(item.name) ........................................................................................................................................................................................................")
                .background(Color.red) // not the area I'm looking for
        }.background(Color.blue) // also not the area I'm looking for
    }
}

Body:
Using UITableView.appearance().backgroundColor is not a good idea as it changes the backgroundColor of all tables. I found a working solution for color changing at the exact table you selected in iOS 14, 15.

We will change the color using a modifier that needs to be applied inside the List

extension View {

    func backgroundTableModifier(_ color: UIColor? = nil) -> some View {
        self.modifier(BackgroundTableModifier(color: color))
    }

}

Our task is to find the UITableView and after that change the color.

private struct BackgroundTableModifier: ViewModifier {

    private let color: UIColor?
    @State private var tableView: UITableView?

    init(color: UIColor?) {
        self.color = color
    }

    public func body(content: Content) -> some View {
        if tableView?.backgroundColor != color {
            content
                .overlay(BackgroundTableViewRepresentable(tableBlock: { tableView in
                    tableView.backgroundColor = color
                    self.tableView = tableView
                }))
        } else {
            content
        }
    }
}

private struct BackgroundTableViewRepresentable: UIViewRepresentable {

    var tableBlock: (UITableView) -> ()

    func makeUIView(context: Context) -> BackgroundTableView  {
        let view = BackgroundTableView(tableBlock: tableBlock)
        return view
    }

    func updateUIView(_ uiView: BackgroundTableView, context: Context) {}
}

class BackgroundTableView: UIView {

    var tableBlock: (UITableView) -> ()

    init(tableBlock: @escaping (UITableView) -> ()) {
        self.tableBlock = tableBlock
        super.init(frame: .zero)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        if let tableView = findTableView(in: self) {
            tableBlock(tableView)
        }
    }

    private func findTableView(in view: UIView) -> UITableView? {
        if let tableView = view as? UITableView {
            return tableView
        }

        if let superView = view.superview {
            return findTableView(in: superView)
        }

        return nil
    }

}

In order to find UITableView, the modifier must be inside the List. Naturally, you need to ensure that the modifier is called only once, you do not need to apply it to each row. Here is an example of usage

List {
   rows()
     .backgroundTableModifier(.clear)
}

func rows() -> some View {
    ForEach(0..<10, id: \.self) { index in
        Row()
    }
}


问:
Why when casting an int to a char pointer, printing the char does not give the unicode?
I had for class to do a code which shows if machine is big or little endian. I made this:

```<code>#include <stdio.h>

typedef unsigned char *byte_pointer;

int show_bytes(int x) {
    byte_pointer a = (byte_pointer)&x;
    int i;
    printf("%c", a[0]); // why here when printing a[0] does not give the ascii representation?
    if (a[0] == 0x01)
       return 1;
   return 0;
}

int isEndian() {
    int i = 1;
    return show_bytes(i);
}

int main(int argc, char **argv){
    int a = isEndian();
    printf("%d", a);
}
</code>```

And I do not understand why when printing back the char[0] on a little endian machine, does not print the unicode representation of 1?

答:
The bytes making up an integer in memory have nothing to do with the bytes representing the ASCII (or Unicode) characters that would serve as a human-readable decimal representation of that integer.

If I say

```<code>int i = 1234;
</code>```

the bytes representing it in memory are either

```<code>d2 04
</code>```

or

```<code>d2 04 00 00
</code>```

(using little-endian order, and depending on whether type int has 16 or 32 bits).

But the bytes representing a decimal string representation (such as I'd get with sprintf(buf, "%d", i)) are

```<code>31  32  33  34
'1' '2' '3' '4'
</code>```

Body:
I had for class to do a code which shows if machine is big or little endian. I made this:

#include <stdio.h>

typedef unsigned char *byte_pointer;

int show_bytes(int x) {
    byte_pointer a = (byte_pointer)&x;
    int i;
    printf("%c", a[0]); // why here when printing a[0] does not give the ascii representation?
    if (a[0] == 0x01)
       return 1;
   return 0;
}

int isEndian() {
    int i = 1;
    return show_bytes(i);
}

int main(int argc, char **argv){
    int a = isEndian();
    printf("%d", a);
}

And I do not understand why when printing back the char[0] on a little endian machine, does not print the unicode representation of 1?

Body:
The bytes making up an integer in memory have nothing to do with the bytes representing the ASCII (or Unicode) characters that would serve as a human-readable decimal representation of that integer.

If I say

int i = 1234;

the bytes representing it in memory are either

d2 04

or

d2 04 00 00

(using little-endian order, and depending on whether type int has 16 or 32 bits).

But the bytes representing a decimal string representation (such as I'd get with sprintf(buf, "%d", i)) are

31  32  33  34
'1' '2' '3' '4'


问:
proc transpose with duplicate ID values
I need help with proc transpose procedure in SAS. My code initially was:

```<code>proc transpose data=temp out=temp1;
by patid;
var text;
Id datanumber;
run;
</code>```

This gave me error "The ID value " " occurs twice in the same BY group". I modified the code to this:

```<code>proc sort data = temp;
by patid text datanumber;
run;

data temp;
set temp by patid text datanumber;
if first.datanunmber then n = 0;
n+1;
run;

proc sort data = temp;
by patid text datanumber n;
run;

proc transpose out=temp1 (drop=n) let;
by patid;
var text;
id datanumber;
run;
</code>```

This is giving me error: variable n is not recognized. Adding a let option is giving a lot of error "occurs twice in the same BY group". I want to keep all id values.

Please help me in this.

Data Example:
Patid          Text

答: Try to sort your dataset by patid n datanumber, (n before datanumber). and  proc transpose "by patib n ";</p>

Title: proc transpose with duplicate ID values

Body:
I need help with proc transpose procedure in SAS. My code initially was:

proc transpose data=temp out=temp1;
by patid;
var text;
Id datanumber;
run;

This gave me error "The ID value " " occurs twice in the same BY group". I modified the code to this:

proc sort data = temp;
by patid text datanumber;
run;

data temp;
set temp by patid text datanumber;
if first.datanunmber then n = 0;
n+1;
run;

proc sort data = temp;
by patid text datanumber n;
run;

proc transpose out=temp1 (drop=n) let;
by patid;
var text;
id datanumber;
run;

This is giving me error: variable n is not recognized. Adding a let option is giving a lot of error "occurs twice in the same BY group". I want to keep all id values.

Please help me in this.

Data Example:
Patid          Text


问:
MPMoviePlayerController Manual loading screen
In MPMoviewPlayerController i have to play movie from a particular url.Its work fine.I want to show a loadingview (like a spinning wheel rotate in the center of the screen with text loading please wait) before it starts playing movie. (I am using ios4.2)

Can anyone help me ?

Thanks a lot.

答:
try this.
          when u alloc MPMoviePlayerController after that use this method.

```<code>   [[NSNotificationCenter defaultCenter] addObserver:self      selector:@selector(myMovieFinishedCallback:)   name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification object:moviePlayer];
  [activity startanimating];
</code>```

and  after that use the delegate method..

```<code>  -(void)myMovieFinishedCallback:(NSNotification*)aNotification
 {
   moviePlayer=[aNotification object];
CFShow([aNotification userInfo]);
[activity hide];

   [[NSNotificationCenter defaultCenter] removeObserver:self         name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification object:moviePlayer];

  }
</code>```

Body:
try this.
          when u alloc MPMoviePlayerController after that use this method.

   [[NSNotificationCenter defaultCenter] addObserver:self      selector:@selector(myMovieFinishedCallback:)   name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification object:moviePlayer];
  [activity startanimating];

and  after that use the delegate method..

  -(void)myMovieFinishedCallback:(NSNotification*)aNotification
 {
   moviePlayer=[aNotification object];
CFShow([aNotification userInfo]);
[activity hide];

   [[NSNotificationCenter defaultCenter] removeObserver:self         name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification object:moviePlayer];

  }


问:
Moving a MDToolbar in kivymd
i don't know how to move the toolbar to the top of the screen, before when i was creating a toolbar it was placed at the top of the screen by default. How can i fix this problem?
output image

KV = ('''
Screen:

    MDToolbar:
        title: "WeatherApp"

    MDLabel:
        text: "Hello World"
''')

class WeatherApp(MDApp):

    Window.size = (350, 630)

    def build(self):

        self.title = "WeatherApp"
        self.theme_cls.theme_style = 'Dark'
        return Builder.load_string(KV)

WeatherApp().run()
```

答:
To have full control over widgets on the screen you could use RelativeLayout but computing the exact position might be a lil complicated but easy when you get it

```<code>Screen:
    RelativeLayout:
        MDToolbar:
            y: self.parent.height - self.height
            title: "WeatherApp"
</code>```

in RelativeLayout y defaults to 0 and x defaults to 0 which places the widget at the bottom left of the screen

The y property applies on the bottom of the widget so if you set

```<code>y: dp(30)
</code>```

means the bottom of the widget is dp(30) from the bottom of the screen

same with the x property.

x applies on the left end of the widget. so if you set x: dp(10) it means the left end of the widget is dp(10) from the left end of the screen

Title: Moving a MDToolbar in kivymd

Body:
To have full control over widgets on the screen you could use RelativeLayout but computing the exact position might be a lil complicated but easy when you get it

Screen:
    RelativeLayout:
        MDToolbar:
            y: self.parent.height - self.height
            title: "WeatherApp"

in RelativeLayout y defaults to 0 and x defaults to 0 which places the widget at the bottom left of the screen

The y property applies on the bottom of the widget so if you set

y: dp(30)

means the bottom of the widget is dp(30) from the bottom of the screen

same with the x property.

x applies on the left end of the widget. so if you set x: dp(10) it means the left end of the widget is dp(10) from the left end of the screen


问:
Error: Cannot read properties of undefined (reading 'headerCell') - Creating reactive form inside a angular material table
I'm trying to create an angular material table with reactive form.
I need to add some properties, so I'm using formArray.
But my table is not showing  any result, and angular keeps me returning the same error:

ERROR TypeError: Cannot read properties of undefined (reading
'headerCell')

This is what I got until now:

HTML

```<code><button mat-button mat-raised-button (click)="addParameterWhatsApp()" color="primary">Add</button>

    <form [formGroup]="form" autocomplete="off">

      <table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8" formGroupName="whatsapp">
        <ng-container formArrayName="parameters">
          <ng-container *ngFor="let dados of parameters.controls; let i = index ">

            <div [formGroupName]="i">

              <ng-container matColumnDef="posicao">
                <th mat-header-cell *matHeaderCellDef> Posicao </th>
                <td mat-cell *matCellDef="let element">
                  <mat-form-field appearance="outline">
                    <mat-label>Posicao</mat-label>
                    <input matInput formControlName="posicao">
                  </mat-form-field>
                </td>
              </ng-container>

              <ng-container matColumnDef="valor">
                <th mat-header-cell *matHeaderCellDef>Valor</th>
                <td mat-cell *matCellDef="let element">
                  <mat-form-field appearance="outline">
                    <mat-label>Valor</mat-label>
                    <input matInput formControlName="valor">
                  </mat-form-field>
                </td>
              </ng-container>
          </ng-container>
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
    </form>
</code>```

TS

```<code>form!: FormGroup;
  dataSource;
  displayedColumns = ['posicao', 'valor'];
  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.createForm();
  }

  createForm() {
    this.form = this._formBuilder.group({
      whatsapp: this._formBuilder.group({
        name: [],
        parameters: this.buildArrayParametersWhatsApp(),
      }),
    });
  }

  get parameters() {
    return this.form.get('whatsapp')?.get('parameters') as FormArray;
  }

  buildArrayParametersWhatsApp() {
    return this._formBuilder.array([]);
  }

  addParameterWhatsApp() {
    const parametersArray = this._formBuilder?.group({
      posicao: [],
      valor: [],
    });

    if (parametersArray) {
      this.parameters.push(parametersArray);
    }
  }
</code>```

Image:

What I am missing?

答:
I don't know why angular shows you not related error ERROR TypeError: Cannot read properties of undefined (reading 'headerCell').
But the reason your app did not work is because you missed to close
. you you can see here after this div is closed

Body:
I'm trying to create an angular material table with reactive form.
I need to add some properties, so I'm using formArray.
But my table is not showing  any result, and angular keeps me returning the same error:

ERROR TypeError: Cannot read properties of undefined (reading
'headerCell')

This is what I got until now:

HTML

<button mat-button mat-raised-button (click)="addParameterWhatsApp()" color="primary">Add</button>

    <form [formGroup]="form" autocomplete="off">

        <ng-container formArrayName="parameters">
          <ng-container *ngFor="let dados of parameters.controls; let i = index ">

              <ng-container matColumnDef="posicao">
                 Posicao

                  <mat-form-field appearance="outline">
                    <mat-label>Posicao</mat-label>
                    <input matInput formControlName="posicao">
                  </mat-form-field>

              </ng-container>

              <ng-container matColumnDef="valor">
                Valor

                  <mat-form-field appearance="outline">
                    <mat-label>Valor</mat-label>
                    <input matInput formControlName="valor">
                  </mat-form-field>

              </ng-container>
          </ng-container>
        </ng-container>

    </form>

TS

form!: FormGroup;
  dataSource;
  displayedColumns = ['posicao', 'valor'];
  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.createForm();
  }

  createForm() {
    this.form = this._formBuilder.group({
      whatsapp: this._formBuilder.group({
        name: [],
        parameters: this.buildArrayParametersWhatsApp(),
      }),
    });
  }

  get parameters() {
    return this.form.get('whatsapp')?.get('parameters') as FormArray;
  }

  buildArrayParametersWhatsApp() {
    return this._formBuilder.array([]);
  }

  addParameterWhatsApp() {
    const parametersArray = this._formBuilder?.group({
      posicao: [],
      valor: [],
    });

    if (parametersArray) {
      this.parameters.push(parametersArray);
    }
  }

Image:

What I am missing?

Body:
I don't know why angular shows you not related error ERROR TypeError: Cannot read properties of undefined (reading 'headerCell').
But the reason your app did not work is because you missed to close <div [formGroupName]="i">. you you can see here after this div is closed


问:
Rendering clipped SVG image using GeoTools (version 26.2)
Trying to generate SVG from an external graphic link but the output SVG image not rendering properly. To generate SVG using the below code,

```<code>package org.geotools.tutorial.quickstart;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGGraphics2D;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.*;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.expression.Expression;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.awt.*;
import java.awt.Dimension;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;

public class SvgRendering {

static StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory();
static FilterFactory2 filterFactory = CommonFactoryFinder.getFilterFactory2();

public static void main(String[] args) throws Exception {

    Coordinate[] listOfPoints = new Coordinate[5];
    listOfPoints[0] = new Coordinate(-73.82, 41.24);

    setupSVG(listOfPoints);
}

public static DefaultFeatureCollection createBoundingBox(Coordinate[] listofP){
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("MyFeatureType");
    b.add("location", Polygon.class);
    final SimpleFeatureType TYPE = b.buildFeatureType();
    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
    Polygon polygon = geometryFactory.createPolygon(listofP);
    featureBuilder.add(polygon);
    SimpleFeature feature = featureBuilder.buildFeature("polygon");
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal", TYPE);
    featureCollection.add(feature); //Add feature 1
    return featureCollection;
}

private static void setupSVG(Coordinate[] listofP)
        throws IOException, ParserConfigurationException, URISyntaxException, TransformerException {

    //URL url = new URL("http://localhost:8080/");
    URL url = new URL("file:///C:/poc/mapreport/Map_marker.svg");
    //File file = new File(baseFilePath + "mapreport\\Map_marker.svg");
    //URL url = file.toURI().toURL();

    PointSymbolizer symb = styleFactory.createPointSymbolizer();
    ExternalGraphic eg = styleFactory.createExternalGraphic(url, "image/svg+xml");
    symb.getGraphic().graphicalSymbols().add(eg);
    Expression size = filterFactory.literal(54);
    symb.getGraphic().setSize(size);

    Rule rule = styleFactory.createRule();
    rule.symbolizers().add(symb);
    FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(rule);
    Style style = styleFactory.createStyle();
    style.featureTypeStyles().add(fts);

    MapContent mc = new MapContent();

    DefaultFeatureCollection boundingbox = createBoundingBox(listofP);
    Layer layer = new FeatureLayer(boundingbox, style);
    mc.addLayer(layer);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    // Create an instance of org.w3c.dom.Document
    Document document = db.getDOMImplementation().createDocument(null, "svg", null);

    // Set up the map
    SVGGeneratorContext ctx1 = SVGGeneratorContext.createDefault(document);
    SVGGeneratorContext ctx = ctx1;
    ctx.setComment("Generated by GeoTools2 with Batik SVG Generator");

    SVGGraphics2D g2d = new SVGGraphics2D(ctx, true);

    Dimension canvasSize = new Dimension(1024, 1024);
    g2d.setSVGCanvasSize(canvasSize);
    StreamingRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(mc);
    Rectangle outputArea = new Rectangle(g2d.getSVGCanvasSize());
    ReferencedEnvelope dataArea = mc.getMaxBounds();
    dataArea.expandBy(5); // some of these have 0 size

    renderer.paint(g2d, outputArea, dataArea);
    File fileToSave = new File("C:\\poc\\markers.svg");

    OutputStreamWriter osw = null;
    try {
        OutputStream out = new FileOutputStream(fileToSave);
        osw = null;

        osw = new OutputStreamWriter(out, "UTF-8");
        g2d.stream(osw);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }  finally {
        if (osw != null)
            try {
                osw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

    mc.dispose();
}
</code>```

}

Expected Output:-

Final Output:-

So, in the final output SVG marker is getting cut from the right-hand side.

Help would be appreciated.

Thanks in advance

This is different from the previous question.

答: This happens near the bounds of the layer. You can enlarge the layer's bounds manually in the layer config page.</p>

Body:
Trying to generate SVG from an external graphic link but the output SVG image not rendering properly. To generate SVG using the below code,

package org.geotools.tutorial.quickstart;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGGraphics2D;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.*;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.expression.Expression;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.awt.*;
import java.awt.Dimension;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;

public class SvgRendering {

static StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory();
static FilterFactory2 filterFactory = CommonFactoryFinder.getFilterFactory2();

public static void main(String[] args) throws Exception {

    Coordinate[] listOfPoints = new Coordinate[5];
    listOfPoints[0] = new Coordinate(-73.82, 41.24);

    setupSVG(listOfPoints);
}

public static DefaultFeatureCollection createBoundingBox(Coordinate[] listofP){
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("MyFeatureType");
    b.add("location", Polygon.class);
    final SimpleFeatureType TYPE = b.buildFeatureType();
    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
    Polygon polygon = geometryFactory.createPolygon(listofP);
    featureBuilder.add(polygon);
    SimpleFeature feature = featureBuilder.buildFeature("polygon");
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal", TYPE);
    featureCollection.add(feature); //Add feature 1
    return featureCollection;
}

private static void setupSVG(Coordinate[] listofP)
        throws IOException, ParserConfigurationException, URISyntaxException, TransformerException {

    //URL url = new URL("http://localhost:8080/");
    URL url = new URL("file:///C:/poc/mapreport/Map_marker.svg");
    //File file = new File(baseFilePath + "mapreport\\Map_marker.svg");
    //URL url = file.toURI().toURL();

    PointSymbolizer symb = styleFactory.createPointSymbolizer();
    ExternalGraphic eg = styleFactory.createExternalGraphic(url, "image/svg+xml");
    symb.getGraphic().graphicalSymbols().add(eg);
    Expression size = filterFactory.literal(54);
    symb.getGraphic().setSize(size);

    Rule rule = styleFactory.createRule();
    rule.symbolizers().add(symb);
    FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(rule);
    Style style = styleFactory.createStyle();
    style.featureTypeStyles().add(fts);

    MapContent mc = new MapContent();

    DefaultFeatureCollection boundingbox = createBoundingBox(listofP);
    Layer layer = new FeatureLayer(boundingbox, style);
    mc.addLayer(layer);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    // Create an instance of org.w3c.dom.Document
    Document document = db.getDOMImplementation().createDocument(null, "svg", null);

    // Set up the map
    SVGGeneratorContext ctx1 = SVGGeneratorContext.createDefault(document);
    SVGGeneratorContext ctx = ctx1;
    ctx.setComment("Generated by GeoTools2 with Batik SVG Generator");

    SVGGraphics2D g2d = new SVGGraphics2D(ctx, true);

    Dimension canvasSize = new Dimension(1024, 1024);
    g2d.setSVGCanvasSize(canvasSize);
    StreamingRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(mc);
    Rectangle outputArea = new Rectangle(g2d.getSVGCanvasSize());
    ReferencedEnvelope dataArea = mc.getMaxBounds();
    dataArea.expandBy(5); // some of these have 0 size

    renderer.paint(g2d, outputArea, dataArea);
    File fileToSave = new File("C:\\poc\\markers.svg");

    OutputStreamWriter osw = null;
    try {
        OutputStream out = new FileOutputStream(fileToSave);
        osw = null;

        osw = new OutputStreamWriter(out, "UTF-8");
        g2d.stream(osw);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }  finally {
        if (osw != null)
            try {
                osw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

    mc.dispose();
}

}

Expected Output:-

Final Output:-

So, in the final output SVG marker is getting cut from the right-hand side.

Help would be appreciated.

Thanks in advance

This is different from the previous question.