问:
Unable to run angular 13 project with webpack 5
My Angular 13 project is served through webpack. I've added css-loaders, style-loaders and html-loaders.

When I add the url-resolve-loader, I get the following errors. Does anyone have any idea why?

```<code>ERROR in ./node_modules/webpack/hot/dev-server.js
Module build failed (from ./node_modules/resolve-url-loader/index.js):
Error: resolve-url-loader: error processing CSS
  file://C:\Users\user\Desktop\clients\upgraded\node_modules\webpack\hot\dev-server.js:7:2: Unknown word
  at Input.error (C:\Users\user\Desktop\clients\upgraded\node_modules\postcss\lib\input.js:148:16)
    at encodeError (C:\Users\user\Desktop\clients\upgraded\node_modules\resolve-url-loader\index.js:274:12)
    at onFailure (C:\Users\user\Desktop\clients\upgraded\node_modules\resolve-url-loader\index.js:215:14)
</code>```

If I remove the url-resolve-loader, I get 193 errors and the app still doesn't run. It cannot resolve svg, eot and ttf files.
Basically, it can't resolve any of my asset resources that were to be used in my *.html and *.scss files.

My package.json reads as follows:

```<code>{
  "name": "app",
  "version": "0.0.0",
  "scripts": {
    "build": "webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:dev": "webpack-dev-server --mode development  --open",
    "start:dev:https": "webpack-dev-server --mode development --open --https",
    "server:docs:run": "./.server/bin/docs.server.js",
    "server:build:run": ".server/bin/run.env.server.js",
    "docs:gen": "npx compodoc src",
    "build:dev": "webpack --mode production",
    "build:qa": "webpack --mode production --config webpack.aot.js",
    "build:stage": "webpack --mode production --config webpack.aot.js",
    "build:prod": "webpack --mode production --config webpack.aot.js",
    "build:aot": "webpack --mode production --config webpack.aot.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.3.0",
    "@angular/common": "~13.3.0",
    "@angular/compiler": "~13.3.0",
    "@angular/core": "~13.3.0",
    "@angular/forms": "~13.3.0",
    "@angular/material": "^13.3.9",
    "@angular/platform-browser": "~13.3.0",
    "@angular/platform-browser-dynamic": "~13.3.0",
    "@angular/router": "~13.3.0",
    "hammerjs": "^2.0.8",
    "lodash": "^4.17.21",
    "modern-css-reset": "^1.4.0",
    "mq-scss": "^2.1.5",
    "ngx-cookie-service": "^13.2.1",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.3.10",
    "@angular/cli": "~13.3.10",
    "@angular/compiler-cli": "~13.3.0",
    "@softeq/types": "^1.0.0-beta.2",
    "@softeq/utils": "^0.1.0",
    "@types/jasmine": "~3.10.0",
    "@types/lodash": "^4.14.191",
    "@types/node": "^12.11.1",
    "angular2-template-loader": "^0.6.2",
    "css-loader": "^6.7.2",
    "express": "^4.18.2",
    "file-loader": "^6.2.0",
    "html-loader": "^4.2.0",
    "html-webpack-plugin": "^5.5.0",
    "jasmine-core": "~4.0.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.1.0",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "node-sass": "^7.0.3",
    "postcss-loader": "^7.0.2",
    "raw-loader": "^4.0.2",
    "resolve-url-loader": "^5.0.0",
    "sass": "^1.56.1",
    "sass-loader": "^13.2.0",
    "style-loader": "^3.3.1",
    "to-string-loader": "^1.2.0",
    "ts-loader": "^9.4.2",
    "tslint": "^6.1.3",
    "typescript": "~4.6.2",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.0",
    "webpack-dev-middleware": "^6.0.1",
    "webpack-dev-server": "^4.11.1",
    "webpack-merge": "^5.8.0"
  }
}

</code>```

And this is my webpack.config.js:

```<code>/*
 * Developed for General Electric by Softeq Development Corporation
 * http://www.softeq.com
 */

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const packageConfig = require('./package');

const commonSourcePaths = {
  root: ['src', 'app'],
  moduleTypes: {
    core: ['src', 'app', 'modules', 'core-modules'],
    page: ['src', 'app', 'modules', 'page-modules'],
    ui: ['src', 'app', 'modules', 'ui-modules'],
  },
  theme: ['src', 'app', 'theme'],
};

const path = require('path');
const root = path.join.bind(path, path.resolve(__dirname));

// @todo: Webpack alias builders
const modulesPaths = {
  core: {
    root: root(...commonSourcePaths.moduleTypes.core),
    children: {
      http: root(...commonSourcePaths.moduleTypes.core, 'http-core-module'),
      material: root(...commonSourcePaths.moduleTypes.core, 'material-core-module'),
      navigation: root(...commonSourcePaths.moduleTypes.core, 'navigation-core-module'),
      notification: root(...commonSourcePaths.moduleTypes.core, 'notification-core-module'),
      rest: root(...commonSourcePaths.moduleTypes.core, 'rest-core-module'),
      router: root(...commonSourcePaths.moduleTypes.core, 'router-core-module'),
    }
  },
  page: {
    root: root(...commonSourcePaths.moduleTypes.page),
    children: {
      dashboard: root(...commonSourcePaths.moduleTypes.page, 'dashboard-page-module'),
      settings: root(...commonSourcePaths.moduleTypes.page, 'settings-page-module'),
    },
  },
  ui: {
    root: root(...commonSourcePaths.moduleTypes.page),
    children: {
      common: root(...commonSourcePaths.moduleTypes.page, 'common-ui-module'),
    },
  },
};

const appPaths = {
  root: root(...commonSourcePaths.root),
  theme: root(...commonSourcePaths.theme),
  modules: {
    ...modulesPaths,
  },
};

const IMPORT_PREFIX = '@ge';
const modulesClusterImportPath = (type) => `${IMPORT_PREFIX}/${type}`;
const moduleImportPath = (type, name) => `${IMPORT_PREFIX}/${type}/${name}`;
function buildResolveAliases(modulesPaths) {
  const aliases = {};
  Object.keys(modulesPaths).forEach((type) => {
    aliases[modulesClusterImportPath(type)] = modulesPaths[type].root;
    Object.keys(modulesPaths[type].children).forEach((moduleName) => {
      aliases[moduleImportPath(type, moduleName)] = modulesPaths[type].children[moduleName];
    });
  });
}

// @todo: Environment config: devtool, etc.
module.exports = {
  entry: './src/main.ts',
  devtool: 'eval-source-map',
  output: {
    filename: '[name].bundle.js',
    path: root('.package', 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: ['ts-loader', 'angular2-template-loader'],
        exclude: /node_modules/,
      },
      {
        test: /\.html$/,
        loader: 'html-loader',
      },

      /**
       * To string and sass loader support for *.scss files (from Angular components).
       * Returns compiled css content as string.
       */
      {
        test: /\.s[ac]ss$/i,
        use: ['to-string-loader', 'css-loader', 'postcss-loader', {
          loader: 'sass-loader',
          options: {
            sassOptions: {
              includePaths: ['node_modules', appPaths.root],
              sourceMap: true,
            },
          },
        }],
        exclude: [appPaths.theme],
      },
      {
        loader: 'resolve-url-loader',
        options: { removeCR: true, sourceMap: true }
      },

      /**
       * Sass loader support for *.scss files (theme directory only).
       * Loads external sass styles into the DOM, supports HMR.
       */
      {
        test: /\.s[ac]ss$/i,
        use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
        include: [appPaths.theme],
      },
      {
        test: /\.(jpg|png|gif)$/,
        use: ['file-loader'],
      },
      {
        test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
        use: ['file-loader'],
      }
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [appPaths.root, 'node_modules'],
    alias: {
      '@ge/core/rest': path.resolve(__dirname, 'src/app/modules/core-modules/rest-core-module/index.ts'),
      '@ge/core/router': path.resolve(__dirname, 'src/app/modules/core-modules/router-core-module/index.ts'),
      '@ge/code/types': path.resolve(__dirname, 'src/app/modules/code-modules/module.d.ts'),
      '@ge/core/form': path.resolve(__dirname, 'src/app/modules/core-modules/form-core-module/index.ts'),
      '@ge/core/http': path.resolve(__dirname, 'src/app/modules/core-modules/http-core-module/index.ts'),
      '@ge/core/material': path.resolve(__dirname, 'src/app/modules/core-modules/material-core-module/index.ts'),
      '@ge/core/navigation': path.resolve(__dirname, 'src/app/modules/core-modules/navigation-core-module/index.ts'),
      '@ge/core/notification': path.resolve(__dirname, 'src/app/modules/core-modules/notification-core-module/index.ts'),

      '@ge/page/types': path.resolve(__dirname, 'src/app/modules/page-modules/module.d.ts'),
      '@ge/page/dashboard': path.resolve(__dirname, 'src/app/modules/page-modules/dashboard-page-module/index.ts'),
      '@ge/page/settings': path.resolve(__dirname, 'src/app/modules/page-modules/settings-page-module/index.ts'),

      '@ge/ui/types': path.resolve(__dirname, 'src/app/modules/ui-modules/module.d.ts'),
      '@ge/ui/common': path.resolve(__dirname, 'src/app/modules/ui-modules/common-ui-module/index.ts'),

      '@ge-types': path.resolve(__dirname, 'src/app/types/app.d.ts'),
    },
    symlinks: false,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
      inject: 'body',
    }),

    new webpack.DefinePlugin({
      // global app config object
      config: JSON.stringify({
        environment: {
          code: 'dev-1-data',
        },
        version: packageConfig.version,
      })
    }),

    /**
     * Copies individual files or entire directories to the build directory.
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin({
      patterns: [{
        from: 'src/assets',
        to: 'assets',
      }, {
        from: 'src/config',
        to: 'config',
      }]
    }),
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
    runtimeChunk: true,
  },
  devServer: {
    historyApiFallback: true,
    static: {
      directory: path.join(__dirname, "./")
    },
  },
};

</code>```

Body:
My Angular 13 project is served through webpack. I've added css-loaders, style-loaders and html-loaders.

When I add the url-resolve-loader, I get the following errors. Does anyone have any idea why?

ERROR in ./node_modules/webpack/hot/dev-server.js
Module build failed (from ./node_modules/resolve-url-loader/index.js):
Error: resolve-url-loader: error processing CSS
  file://C:\Users\user\Desktop\clients\upgraded\node_modules\webpack\hot\dev-server.js:7:2: Unknown word
  at Input.error (C:\Users\user\Desktop\clients\upgraded\node_modules\postcss\lib\input.js:148:16)
    at encodeError (C:\Users\user\Desktop\clients\upgraded\node_modules\resolve-url-loader\index.js:274:12)
    at onFailure (C:\Users\user\Desktop\clients\upgraded\node_modules\resolve-url-loader\index.js:215:14)

If I remove the url-resolve-loader, I get 193 errors and the app still doesn't run. It cannot resolve svg, eot and ttf files.
Basically, it can't resolve any of my asset resources that were to be used in my *.html and *.scss files.

My package.json reads as follows:

{
  "name": "app",
  "version": "0.0.0",
  "scripts": {
    "build": "webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:dev": "webpack-dev-server --mode development  --open",
    "start:dev:https": "webpack-dev-server --mode development --open --https",
    "server:docs:run": "./.server/bin/docs.server.js",
    "server:build:run": ".server/bin/run.env.server.js",
    "docs:gen": "npx compodoc src",
    "build:dev": "webpack --mode production",
    "build:qa": "webpack --mode production --config webpack.aot.js",
    "build:stage": "webpack --mode production --config webpack.aot.js",
    "build:prod": "webpack --mode production --config webpack.aot.js",
    "build:aot": "webpack --mode production --config webpack.aot.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.3.0",
    "@angular/common": "~13.3.0",
    "@angular/compiler": "~13.3.0",
    "@angular/core": "~13.3.0",
    "@angular/forms": "~13.3.0",
    "@angular/material": "^13.3.9",
    "@angular/platform-browser": "~13.3.0",
    "@angular/platform-browser-dynamic": "~13.3.0",
    "@angular/router": "~13.3.0",
    "hammerjs": "^2.0.8",
    "lodash": "^4.17.21",
    "modern-css-reset": "^1.4.0",
    "mq-scss": "^2.1.5",
    "ngx-cookie-service": "^13.2.1",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.3.10",
    "@angular/cli": "~13.3.10",
    "@angular/compiler-cli": "~13.3.0",
    "@softeq/types": "^1.0.0-beta.2",
    "@softeq/utils": "^0.1.0",
    "@types/jasmine": "~3.10.0",
    "@types/lodash": "^4.14.191",
    "@types/node": "^12.11.1",
    "angular2-template-loader": "^0.6.2",
    "css-loader": "^6.7.2",
    "express": "^4.18.2",
    "file-loader": "^6.2.0",
    "html-loader": "^4.2.0",
    "html-webpack-plugin": "^5.5.0",
    "jasmine-core": "~4.0.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.1.0",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "node-sass": "^7.0.3",
    "postcss-loader": "^7.0.2",
    "raw-loader": "^4.0.2",
    "resolve-url-loader": "^5.0.0",
    "sass": "^1.56.1",
    "sass-loader": "^13.2.0",
    "style-loader": "^3.3.1",
    "to-string-loader": "^1.2.0",
    "ts-loader": "^9.4.2",
    "tslint": "^6.1.3",
    "typescript": "~4.6.2",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.0",
    "webpack-dev-middleware": "^6.0.1",
    "webpack-dev-server": "^4.11.1",
    "webpack-merge": "^5.8.0"
  }
}

And this is my webpack.config.js:

/*
 * Developed for General Electric by Softeq Development Corporation
 * http://www.softeq.com
 */

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const packageConfig = require('./package');

const commonSourcePaths = {
  root: ['src', 'app'],
  moduleTypes: {
    core: ['src', 'app', 'modules', 'core-modules'],
    page: ['src', 'app', 'modules', 'page-modules'],
    ui: ['src', 'app', 'modules', 'ui-modules'],
  },
  theme: ['src', 'app', 'theme'],
};

const path = require('path');
const root = path.join.bind(path, path.resolve(__dirname));

// @todo: Webpack alias builders
const modulesPaths = {
  core: {
    root: root(...commonSourcePaths.moduleTypes.core),
    children: {
      http: root(...commonSourcePaths.moduleTypes.core, 'http-core-module'),
      material: root(...commonSourcePaths.moduleTypes.core, 'material-core-module'),
      navigation: root(...commonSourcePaths.moduleTypes.core, 'navigation-core-module'),
      notification: root(...commonSourcePaths.moduleTypes.core, 'notification-core-module'),
      rest: root(...commonSourcePaths.moduleTypes.core, 'rest-core-module'),
      router: root(...commonSourcePaths.moduleTypes.core, 'router-core-module'),
    }
  },
  page: {
    root: root(...commonSourcePaths.moduleTypes.page),
    children: {
      dashboard: root(...commonSourcePaths.moduleTypes.page, 'dashboard-page-module'),
      settings: root(...commonSourcePaths.moduleTypes.page, 'settings-page-module'),
    },
  },
  ui: {
    root: root(...commonSourcePaths.moduleTypes.page),
    children: {
      common: root(...commonSourcePaths.moduleTypes.page, 'common-ui-module'),
    },
  },
};

const appPaths = {
  root: root(...commonSourcePaths.root),
  theme: root(...commonSourcePaths.theme),
  modules: {
    ...modulesPaths,
  },
};

const IMPORT_PREFIX = '@ge';
const modulesClusterImportPath = (type) => `${IMPORT_PREFIX}/${type}`;
const moduleImportPath = (type, name) => `${IMPORT_PREFIX}/${type}/${name}`;
function buildResolveAliases(modulesPaths) {
  const aliases = {};
  Object.keys(modulesPaths).forEach((type) => {
    aliases[modulesClusterImportPath(type)] = modulesPaths[type].root;
    Object.keys(modulesPaths[type].children).forEach((moduleName) => {
      aliases[moduleImportPath(type, moduleName)] = modulesPaths[type].children[moduleName];
    });
  });
}

// @todo: Environment config: devtool, etc.
module.exports = {
  entry: './src/main.ts',
  devtool: 'eval-source-map',
  output: {
    filename: '[name].bundle.js',
    path: root('.package', 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: ['ts-loader', 'angular2-template-loader'],
        exclude: /node_modules/,
      },
      {
        test: /\.html$/,
        loader: 'html-loader',
      },

      /**
       * To string and sass loader support for *.scss files (from Angular components).
       * Returns compiled css content as string.
       */
      {
        test: /\.s[ac]ss$/i,
        use: ['to-string-loader', 'css-loader', 'postcss-loader', {
          loader: 'sass-loader',
          options: {
            sassOptions: {
              includePaths: ['node_modules', appPaths.root],
              sourceMap: true,
            },
          },
        }],
        exclude: [appPaths.theme],
      },
      {
        loader: 'resolve-url-loader',
        options: { removeCR: true, sourceMap: true }
      },

      /**
       * Sass loader support for *.scss files (theme directory only).
       * Loads external sass styles into the DOM, supports HMR.
       */
      {
        test: /\.s[ac]ss$/i,
        use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
        include: [appPaths.theme],
      },
      {
        test: /\.(jpg|png|gif)$/,
        use: ['file-loader'],
      },
      {
        test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
        use: ['file-loader'],
      }
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [appPaths.root, 'node_modules'],
    alias: {
      '@ge/core/rest': path.resolve(__dirname, 'src/app/modules/core-modules/rest-core-module/index.ts'),
      '@ge/core/router': path.resolve(__dirname, 'src/app/modules/core-modules/router-core-module/index.ts'),
      '@ge/code/types': path.resolve(__dirname, 'src/app/modules/code-modules/module.d.ts'),
      '@ge/core/form': path.resolve(__dirname, 'src/app/modules/core-modules/form-core-module/index.ts'),
      '@ge/core/http': path.resolve(__dirname, 'src/app/modules/core-modules/http-core-module/index.ts'),
      '@ge/core/material': path.resolve(__dirname, 'src/app/modules/core-modules/material-core-module/index.ts'),
      '@ge/core/navigation': path.resolve(__dirname, 'src/app/modules/core-modules/navigation-core-module/index.ts'),
      '@ge/core/notification': path.resolve(__dirname, 'src/app/modules/core-modules/notification-core-module/index.ts'),

      '@ge/page/types': path.resolve(__dirname, 'src/app/modules/page-modules/module.d.ts'),
      '@ge/page/dashboard': path.resolve(__dirname, 'src/app/modules/page-modules/dashboard-page-module/index.ts'),
      '@ge/page/settings': path.resolve(__dirname, 'src/app/modules/page-modules/settings-page-module/index.ts'),

      '@ge/ui/types': path.resolve(__dirname, 'src/app/modules/ui-modules/module.d.ts'),
      '@ge/ui/common': path.resolve(__dirname, 'src/app/modules/ui-modules/common-ui-module/index.ts'),

      '@ge-types': path.resolve(__dirname, 'src/app/types/app.d.ts'),
    },
    symlinks: false,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
      inject: 'body',
    }),

    new webpack.DefinePlugin({
      // global app config object
      config: JSON.stringify({
        environment: {
          code: 'dev-1-data',
        },
        version: packageConfig.version,
      })
    }),

    /**
     * Copies individual files or entire directories to the build directory.
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin({
      patterns: [{
        from: 'src/assets',
        to: 'assets',
      }, {
        from: 'src/config',
        to: 'config',
      }]
    }),
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
    runtimeChunk: true,
  },
  devServer: {
    historyApiFallback: true,
    static: {
      directory: path.join(__dirname, "./")
    },
  },
};


来源: stackexchange

问:
How to route Client to Client in Chat application using Java Spring Stomp over WebSocket
I try to implement multiclient chat that will have one general open room and the possibility for private messaging between active users. I wanted to use WebSocket for this purpose but I stumbled upon a problem that I cannot solve: How to notify other clients that a new one has appeared and give them information about his username (username will be important for the UI purpose except routing) and sessionId. I have one solution that is suboptimal at best:

```<code> @MessageMapping("/greeting")
    public void addUserAndNotifyOthers(@Header("simpSessionId") String sessionId, @Payload String username) {
        userToSessionMap.put(username, sessionId);
        simpMessagingTemplate.convertAndSend("topic/greeting", username);
    }
</code>```

After the handshake, the client will broadcast his username, in the controller I will keep a map that routes the username to the sessionId of the client. I can see drawbacks to this: an additional message must be broadcasted, and as it will be received by the very client that sent it, there must be additional logic that checks the sender. Is there better way to handle this kind of case? I have seen that interceptors are often used for keeping sessionIds of the clients but I struggle to find a solution to this with their use.

ContentLicense: CC BY-SA 4.0

Body:
I try to implement multiclient chat that will have one general open room and the possibility for private messaging between active users. I wanted to use WebSocket for this purpose but I stumbled upon a problem that I cannot solve: How to notify other clients that a new one has appeared and give them information about his username (username will be important for the UI purpose except routing) and sessionId. I have one solution that is suboptimal at best:

 @MessageMapping("/greeting")
    public void addUserAndNotifyOthers(@Header("simpSessionId") String sessionId, @Payload String username) {
        userToSessionMap.put(username, sessionId);
        simpMessagingTemplate.convertAndSend("topic/greeting", username);
    }

After the handshake, the client will broadcast his username, in the controller I will keep a map that routes the username to the sessionId of the client. I can see drawbacks to this: an additional message must be broadcasted, and as it will be received by the very client that sent it, there must be additional logic that checks the sender. Is there better way to handle this kind of case? I have seen that interceptors are often used for keeping sessionIds of the clients but I struggle to find a solution to this with their use.


问:
Remove URL encoded signs
I am currently building a Nodejs website but I'm having issues with the URL because signs like (=, ?) Are included in them, this url values comes from a string in my code

Please do anyone know how to remove those signs in the string and make it not URL encoded?

I tried looping changing it manually from the browser url buh it didn't work, cause I don't have a handler for that path.

Title: Remove URL encoded signs


问:
Is there any R function for finding the element in a vector which is perpendicular to the plain?
Is there any r function for finding the element in a vector?

I have a problem in finding r of the vector which is perpendicular to the plain
my concept is not clear.


问:
Can't resolve custom type definitions with a turborepo monorepo
I have a turborepo project with the following structure:

```<code>apps
  - my-app
    - src
      - some-test.spec.ts
    - tsconfig.json
    - types
      - index.d.ts
packages
  - tsconfig
    - base.json
</code>```

The pacakges/tsconfig/base.json looks like:

{
  "compilerOptions": {
    "types": ["node", "jest"],
    "typeRoots": ["../../node_modules/@types"]
  },
  "exclude": [
    "build"
  ]
}
```
<p>The <code>apps/my-app/tsconfig.json</code> looks like:</p>
```{
  "extends": "tsconfig/base.json",
  "include": [
    "src"
  ],
  "compilerOptions": {
    "typeRoots": [
      "./types"
    ]
  }
}
```

The apps/my-app/types/index.d.ts had definitions for a library that I'm using and I've overridden them.

The issue I have is that I can't get TypeScript to recognize the jest types.

If I leave just the types under the base.json's compilerOptions, jest works but the custom-defined type doesn't. If I leave only the typeRoots, the custom typings work but not jest's.

Any idea?

Body:
I have a turborepo project with the following structure:

apps
  - my-app
    - src
      - some-test.spec.ts
    - tsconfig.json
    - types
      - index.d.ts
packages
  - tsconfig
    - base.json

The pacakges/tsconfig/base.json looks like:

{
  "compilerOptions": {
    "types": ["node", "jest"],
    "typeRoots": ["../../node_modules/@types"]
  },
  "exclude": [
    "build"
  ]
}

The apps/my-app/tsconfig.json looks like:

{
  "extends": "tsconfig/base.json",
  "include": [
    "src"
  ],
  "compilerOptions": {
    "typeRoots": [
      "./types"
    ]
  }
}

The apps/my-app/types/index.d.ts had definitions for a library that I'm using and I've overridden them.

The issue I have is that I can't get TypeScript to recognize the jest types.

If I leave just the types under the base.json's compilerOptions, jest works but the custom-defined type doesn't. If I leave only the typeRoots, the custom typings work but not jest's.

Any idea?


问:
Bootstrap i18n Translation of column headings - TypeError: this.$i18n.t is not a function
Trying to add column headings to a bootstrap table in a Vue 3 project using i18n dependency:

"vue-i18n": "^9.3.0-beta.10",

```<code>computed: {
  fields() {
    return [
      { key: "formID", label: this.transColHeading("status.form_id"), sortable: true }
    ];
  }
},
methods: {
  transColHeading(colHeading) {
    return this.$i18n.t(colHeading);
  },
}
</code>```

But I am getting the error

TypeError: this.$i18n.t is not a function

Any idea how to make this work?

For info if I console log this.$i18n.locale I get the correct language.

Body:
Trying to add column headings to a bootstrap table in a Vue 3 project using i18n dependency:

"vue-i18n": "^9.3.0-beta.10",

computed: {
  fields() {
    return [
      { key: "formID", label: this.transColHeading("status.form_id"), sortable: true }
    ];
  }
},
methods: {
  transColHeading(colHeading) {
    return this.$i18n.t(colHeading);
  },
}

But I am getting the error

TypeError: this.$i18n.t is not a function

Any idea how to make this work?

For info if I console log this.$i18n.locale I get the correct language.


问:
React updating a state array that is nested within array of objects
So I'm feeling somewhat confident on updating the array of objects when it's just array of objects using map and the spread function. However, where I'm stuck on is updating an array that is within array of objects.

Here's the example.

I have a seperate state to choose which index

```<code>const [option, setOption] = useState(0);
</code>```

I initialize the state with array of objects

```<code>    const [parts, setParts] = useState([
        {bodyPart: "upperLip", price: 1000, active: [false, false, false]},
        {bodyPart: "chin", price: 1000, active: [false, false, false]},
    ])
</code>```

Basically, I want to update the array that is nested in array of objects when the description of bodyPart matches up.

```<code>    const handleOnClick = (bodyPart) => {

        parts.map((part) => {
            if (part.bodyPart === bodyPart){
                return {...part, active[option]=true}
            } else {
                //do nothing
            }
        })
    }
</code>```

I know that return {...part, active[option]=true} part is incorrect. What would be the proper way of updating this piece within the state?

I've tried to set it to true like I would for an array, but I'm not too sure anymore.

Body:
So I'm feeling somewhat confident on updating the array of objects when it's just array of objects using map and the spread function. However, where I'm stuck on is updating an array that is within array of objects.

Here's the example.

I have a seperate state to choose which index

const [option, setOption] = useState(0);

I initialize the state with array of objects

    const [parts, setParts] = useState([
        {bodyPart: "upperLip", price: 1000, active: [false, false, false]},
        {bodyPart: "chin", price: 1000, active: [false, false, false]},
    ])

Basically, I want to update the array that is nested in array of objects when the description of bodyPart matches up.

    const handleOnClick = (bodyPart) => {

        parts.map((part) => {
            if (part.bodyPart === bodyPart){
                return {...part, active[option]=true}
            } else {
                //do nothing
            }
        })
    }

I know that return {...part, active[option]=true} part is incorrect. What would be the proper way of updating this piece within the state?

I've tried to set it to true like I would for an array, but I'm not too sure anymore.


问:
Creating automatic pull request via a Github app
I am very new to the Github app concept. I already created a Github app and installed it in one of my repository. By using octokit library and installation token of the Github app I can create an issue on the repository. However, I can create a pull request via this Github app's installation access token. Github app only can create issues or just subscribe the events. Do you have any idea how can achieve it.

```<code># github app
@client = Octokit::Client.new(:access_token => "installation access token")

response = @client.create_pull_request(repo, base_branch, "test_branch", pr_title, pr_body)
</code>```

Getting this response:

403 - Resource not accessible by integration // See: https://docs.github.com/rest/reference/pulls#create-a-pull-request (Octokit::Forbidden)

I created a Github app and tried to create automatic pull requests without using a Github user.

Body:
I am very new to the Github app concept. I already created a Github app and installed it in one of my repository. By using octokit library and installation token of the Github app I can create an issue on the repository. However, I can create a pull request via this Github app's installation access token. Github app only can create issues or just subscribe the events. Do you have any idea how can achieve it.

# github app
@client = Octokit::Client.new(:access_token => "installation access token")

response = @client.create_pull_request(repo, base_branch, "test_branch", pr_title, pr_body)

Getting this response:

403 - Resource not accessible by integration // See: https://docs.github.com/rest/reference/pulls#create-a-pull-request (Octokit::Forbidden)

I created a Github app and tried to create automatic pull requests without using a Github user.


问:
What is the simplest way to programming, debugging and executing risc-v assembly code using Qemu?
I don't access to any RISC-V hardware, so, what is the simplest way to programming, debugging and executing risc-v assembly code using Qemu?

As I am reading the RISC-V edition of the Computer Organization and Design book, I prefer the 32 bit Architecture.


问:
Associate USB audio endpoint on windows with matching libusb device
Suppose there are two or more USB audio devices with identical VIDs and PIDs connected to a windows 10+ PC.  These USB audio devices are composite devices...they have a non audio control interface that an application could use libusb to control the device.  libusb can distinguish identical devices by the USB descriptor serial number if the device's firmware populates it.  (Lets assume it does)  Windows audio endpoints have a Endpoint ID string that appears to be a UUID.  The USB descriptor serial number does not appear in the Endpoint ID directly (maybe it is hashed?) or in the audio endpoint's friendly name.  MacOS and Linux both put the USB descriptor serial number in the audio device's friendly name.  Is there a way to associate a USB Audio composite device with its control interface on widows?  via USB descriptor serial number or other method?

I have tried printing out the audio endpoint's friendly name as well as all of the PKEY_Device_* listed here.


问:
Find used deprecated Nuget packages in Azure DevOps Git repositories
We are using Azure DevOps as source code management system.
I am searching for a tool which scans the git repositories and searches for used deprecated Nuget packages inside those repositories.

Does anybody know such a tool or is there any other way to find those packages easily without checking each repository by hand?


问:
css module preserve original class name nextJS
the output of next generates a classname_hash,
how can it be configured (via webpack) so that in "addition" to the classname_hash it also preserves the original class name?

I still want to use CSS modules to benefit of all its goodness, but for other reasons keep the original class name too.

```<code>import styles from '../styles.module.css'
...
    <div className={styles.hello}>Hello World</div>
...
</code>```

Without any change it omits:

```<code>    <div class="hello__Ux3Zx">Hello World</div>
</code>```

Is there a way to configure webpack to have them both like this?

```<code>    <div class="hello__Ux3Zx hello">Hello World</div>
</code>```

Body:
the output of next generates a classname_hash,
how can it be configured (via webpack) so that in "addition" to the classname_hash it also preserves the original class name?

I still want to use CSS modules to benefit of all its goodness, but for other reasons keep the original class name too.

import styles from '../styles.module.css'
...

Hello World

...

Without any change it omits:

Hello World

Is there a way to configure webpack to have them both like this?

Hello World


问:
td-agent configuration for postgresql Logs
I have installed the fluentd agent in my VM where postgresql is installed. Now I am looking for the td-agent.conf file which could help me to ship the pg logs and /var/log/messages to kibana. I am very new to ELF and hence looking for a sample file which I could use and add more logs to forwarding. Please help.

Thank you .


问:
Laravel "Trying to access array offset on value of type null" error when trying to render markdown
I'm trying to show some changelog content on my Laravel page with this markdown plugin, but it always throws this error: Trying to access array offset on value of type null

```<code>@markdown($changelog->content)
</code>```

The content is not null, all the content is there and it gets created and stored properly.

I found out about @isset but no matter how I use it, it still shows that error.

```<code>@isset($changelog->content)
  @markdown($changelog->content)
@endisset
</code>```

Note: I'm using Laravel 5.8, this is an older project.

Body:
I'm trying to show some changelog content on my Laravel page with this markdown plugin, but it always throws this error: Trying to access array offset on value of type null

@markdown($changelog->content)

The content is not null, all the content is there and it gets created and stored properly.

I found out about @isset but no matter how I use it, it still shows that error.

@isset($changelog->content)
  @markdown($changelog->content)
@endisset

Note: I'm using Laravel 5.8, this is an older project.


问:
python opencv - get box coordinates of central object by color
I would need a way to detect the size and position of the color blob representing the central object in a photo.

i have prepared a image that should explain what i am after. this is done in photoshop, so its just a handmade explanation. I need to simplify the object, in oder to remove reflections and small details. Then I need to find the outer box coordinates to be able to locate it in the image.

The object can have any color, and will always differentiate from the background. I am interested in the object that covers the central pixel of the image.

How can this be done in python using opencv?

thank you

Original image:

simplyfied color-blob image

needed box:


问:
Create subset of data using time intervals
Have gps collar data that I need to thin so I have one data point at a minimum of every 12 hours as had trouble with fixation success.

I've tried following various suggestions on different forums and got closest with the lubridate package and forming time steps, however whilst it does filter the data it is not filtered consistently and there are some datapoints that are less than 12 hours apart in the filtered version.

Example data:
|TimeStamp|
| 2022-06-23 6:54:46 UTC|
| 2022-06-23 7:55:32 UTC|
| 2022-06-23 9:55:45 UTC|

Failed attempt:
`

```<code>timefield <- as_datetime(BJdata$TimeStamp)
filtered <- BJdata %>%
  mutate(delta = timefield - first(timefield),
         steps = as.numeric(floor(delta / 43200)),
         change = ifelse(is.na(steps - lag(steps)), 1, steps - lag(steps))) %>%
  filter(change > 0)
</code>```

`

Looking for any method that can achieve a subset of data where the next time step is at least 12 hours on

Body:
Have gps collar data that I need to thin so I have one data point at a minimum of every 12 hours as had trouble with fixation success.

I've tried following various suggestions on different forums and got closest with the lubridate package and forming time steps, however whilst it does filter the data it is not filtered consistently and there are some datapoints that are less than 12 hours apart in the filtered version.

Example data:
|TimeStamp|
| 2022-06-23 6:54:46 UTC|
| 2022-06-23 7:55:32 UTC|
| 2022-06-23 9:55:45 UTC|

Failed attempt:
`

timefield <- as_datetime(BJdata$TimeStamp)
filtered <- BJdata %>%
  mutate(delta = timefield - first(timefield),
         steps = as.numeric(floor(delta / 43200)),
         change = ifelse(is.na(steps - lag(steps)), 1, steps - lag(steps))) %>%
  filter(change > 0)

`

Looking for any method that can achieve a subset of data where the next time step is at least 12 hours on


问:
why keyboard dismiss instantly when textinput pressed?
Here is my code.

```<code><Modal>
...
                            <TextInput
                                keyboardType="phone-pad"
                                placeholder={i18n.t('PhoneNumber')}
                                style={styles.modalTextPhoneNo}
                                onChangeText={(text) => setshareToPhone(text)}//useState
                            />
...
</Modal>
...
    modalTextPhoneNo: {
        width: '100%',
        marginBottom: 15,
        textAlign: 'center',
        fontSize: 20,
        color: colors.primary,
        borderBottomWidth: 2,
        borderBottomColor: colors.secondary,
    },
</code>```

When my app loaded, and press on the textinput for the first time, keyboard will dismiss instantly. After the first time, it works well, even when I navigated to other page and back to this page.

Also, textInput caret sometimes is centered sometimes not. Cannot find any pattern when will happened.

I have more TextInput on other page and they don't have the same problems. Only thing different is this textInput is wrapped with Modal.

Body:
Here is my code.

<Modal>
...
                            <TextInput
                                keyboardType="phone-pad"
                                placeholder={i18n.t('PhoneNumber')}
                                style={styles.modalTextPhoneNo}
                                onChangeText={(text) => setshareToPhone(text)}//useState
                            />
...
</Modal>
...
    modalTextPhoneNo: {
        width: '100%',
        marginBottom: 15,
        textAlign: 'center',
        fontSize: 20,
        color: colors.primary,
        borderBottomWidth: 2,
        borderBottomColor: colors.secondary,
    },

When my app loaded, and press on the textinput for the first time, keyboard will dismiss instantly. After the first time, it works well, even when I navigated to other page and back to this page.

Also, textInput caret sometimes is centered sometimes not. Cannot find any pattern when will happened.

I have more TextInput on other page and they don't have the same problems. Only thing different is this textInput is wrapped with Modal.


问:
How to: scrape URL, extract all CSV files from within the zip files on the page? [Python]
Looked all over SO for an approach to this problem and none that I have tried have worked. I've seen several posts about downloading zip files from URL or unzipping files from a local directory in Python, but I am a bit confused on how to put it all together.

My problem: I have a page of zipped data that is organized by month going back to 2010. I'd like to use some Python code to:

scrape the page and nab only the .zip files (there's other data on the page)

unzip each respective monthly dataset

extract and concatenate all the .csv files in each unzipped folder to one long Pandas dataframe

I've tried

```<code>from urllib.request import urlopen

url = "https://s3.amazonaws.com/capitalbikeshare-data/2010-capitalbikeshare-tripdata.zip"
save_as = "tripdata1.csv"

# Download from URL
with urlopen(url) as file:
    content = file.read()

# Save to file
with open(save_as, 'wb') as download:
    download.write(content)
</code>```

but this returns gibberish.

Then, I tried an approach I saw from a related SO post:

```<code>import glob
import pandas as pd
from zipfile import ZipFile

path = r'https://s3.amazonaws.com/capitalbikeshare-data/index.html' # my path to site

#load all zip files in folder
all_files = glob.glob(path + "/*.zip")

df_comb = pd.DataFrame()
flag = False

for filename in all_files:
    zip_file = ZipFile(filename)
    for text_file in zip_file.infolist():
        if text_file.filename.endswith('tripdata.csv'):
            df = pd.read_csv(zip_file.open(text_file.filename),
            delimiter=';',
            header=0,
            index_col=['ride_id']
            )
    if not flag:
        df_comb = df
        flag = True
    else:
        df_comb = pd.concat([df_comb, df])

print(df_comb.info())
</code>```

But this returned a df with zero data, or with additional tinkering, returned error that there were no filenames on the page... :/

Final data should essentially just be a row-wise merge of all the monthly trip data from the index.

Any advice or fixes will be highly appreciated!

Body:
Looked all over SO for an approach to this problem and none that I have tried have worked. I've seen several posts about downloading zip files from URL or unzipping files from a local directory in Python, but I am a bit confused on how to put it all together.

My problem: I have a page of zipped data that is organized by month going back to 2010. I'd like to use some Python code to:

scrape the page and nab only the .zip files (there's other data on the page)

unzip each respective monthly dataset

extract and concatenate all the .csv files in each unzipped folder to one long Pandas dataframe

I've tried

from urllib.request import urlopen

url = "https://s3.amazonaws.com/capitalbikeshare-data/2010-capitalbikeshare-tripdata.zip"
save_as = "tripdata1.csv"

# Download from URL
with urlopen(url) as file:
    content = file.read()

# Save to file
with open(save_as, 'wb') as download:
    download.write(content)

but this returns gibberish.

Then, I tried an approach I saw from a related SO post:

import glob
import pandas as pd
from zipfile import ZipFile

path = r'https://s3.amazonaws.com/capitalbikeshare-data/index.html' # my path to site

#load all zip files in folder
all_files = glob.glob(path + "/*.zip")

df_comb = pd.DataFrame()
flag = False

for filename in all_files:
    zip_file = ZipFile(filename)
    for text_file in zip_file.infolist():
        if text_file.filename.endswith('tripdata.csv'):
            df = pd.read_csv(zip_file.open(text_file.filename),
            delimiter=';',
            header=0,
            index_col=['ride_id']
            )
    if not flag:
        df_comb = df
        flag = True
    else:
        df_comb = pd.concat([df_comb, df])

print(df_comb.info())

But this returned a df with zero data, or with additional tinkering, returned error that there were no filenames on the page... :/

Final data should essentially just be a row-wise merge of all the monthly trip data from the index.

Any advice or fixes will be highly appreciated!


问:
Python: maldelbrot set multithreaded
I'm using the following algorithm to generate a Mandelbrot set fractal using threads in Python. Something is not working properly because I got minimum difference in time processing using 2, 4 , 8 or even 10 threads. Can someone kinldy help me and take a look to the code so it work correctly, please?!

import threading
from PIL import Image
import matplotlib.pyplot as plt
from timeit import default_timer as timer

# Fractals are infinitely repeating patterns on different scales

xSize = ySize = 2096 # defines a finite number of pixels on axes x and y.
image = Image.new("RGB", (xSize, ySize))
imageSize = xSize * ySize
maxIt = 256 # defines the maximun number of interactions allowed
# drawing region (xa < xb & ya < yb): defined the domain plan
xa = -2.0 # defines the begin of the real axis X: from xa
xb = 0.5 # defines the end of the real axis X: to xb
ya = -1.25 # defines the begin of the imaginary axis Y: from ya
yb = 1.25 # defines the end of the imaginary axis Y: to yb

xd = xb - xa # defines x dimension
yd = yb - ya # defines y dimension

numThr = 4 # number of threads to run

class MandelbrotThread(threading.Thread):

    print('Generating fractal image of size {0} x {1} with {2} interactions using {3} threads'.format(xSize, ySize, maxIt, numThr))

    def __init__ (self, k):
          self.k = k
          threading.Thread.__init__(self)
          print("Executing thread ", k)

    def run(self):
        # each thread only calculates its own share of pixels on the domain plan
        for i in range(t, imageSize, numThr):
            kx = i % xSize #calculates module to define pixels width
            ky = int(i / xSize) #calculates module to define pixels height
            xvalue = xa + xd * kx / (xSize - 1.0) # for every row: associates values to the axis x
            yvalue = ya + yd * ky / (ySize - 1.0) # for every col: associates values to the axis Y
            nReal = xvalue
            nImag = yvalue
            for n in range(maxIt):
                nReal2 = nReal * nReal
                nImag2 = nImag * nImag
                nImag = 2.0 * nReal * nImag + yvalue
                nReal = nReal2 - nImag2 + xvalue
                if nReal2 + nImag2 > 4:
                    # various color palettes can be created here
                    red = (n % 8) * 32
                    green = (20 - n % 20) * 20
                    blue = (n % 15) * 15
                    image.putpixel((kx, ky), (red, green, blue))

                    break

if __name__ == "__main__":
    tArr = []
    for t in range(numThr): # create all threads
        tArr.append(MandelbrotThread(t))

    start = timer()
    for t in range(numThr): # start all threads
        tArr[t].start()

    for t in range(numThr): # wait until all threads finished
        tArr[t].join()

    duration = timer() - start
    print(f'Total processing time: {duration:.2f} seconds')
    image.show()
```

Title: Python: maldelbrot set multithreaded


问:
GitHub Topics Query
I'm using GitHub API and PowerShell to try to do a query on my repos to filter the ones that contains topics with value equals "cloud".

The code I'm doing is like this:

```<code>$repoNames = gh api -X GET "/orgs/$org/repos?type=private" --paginate --jq '.[].name' | sort

foreach ($name in $repoNames) {

  gh api -X GET "/repos/$org/$name/topics"
}
</code>```

Is there a way to do the query to filter the repos by topic on the first gh cmd?
Or is there a way to filter topics by value in the second gh cmd?

I tried this code and nothing works to query topics so far.

Title: GitHub Topics Query

Body:
I'm using GitHub API and PowerShell to try to do a query on my repos to filter the ones that contains topics with value equals "cloud".

The code I'm doing is like this:

$repoNames = gh api -X GET "/orgs/$org/repos?type=private" --paginate --jq '.[].name' | sort

foreach ($name in $repoNames) {

  gh api -X GET "/repos/$org/$name/topics"
}

Is there a way to do the query to filter the repos by topic on the first gh cmd?
Or is there a way to filter topics by value in the second gh cmd?

I tried this code and nothing works to query topics so far.


问:
Use spacy for lemmatizations in a pyspark dataframe - Output not loading nor saving
Context: I'm trying to apply lemmatization process in a pyspark dataframe, however, when I want to do df.show() or see the output, or even save the table, it doesn't do anything (even with just 3 data points in a small dataframe). The function works as an example such as "purchased bought" returns "purchase buy", but when I apply in a pyspark dataframe it just doesn't do anything?

Minimal example:

```<code>import spacy
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

# Load the spaCy English language model
nlp = spacy.load("en_..._md")

# Define a UDF that uses the spaCy lemmatizer to lemmatize a given string
def lemmatize_string(input_string: str) -> str:
    # Use the spaCy nlp object to tokenize the input string
    doc = nlp(input_string)
    # Use the lemma_ attribute of each token to get its lemma, and join the lemmas together
    # with a space character in between to create the lemmatized string
    return " ".join([token.lemma_ for token in doc])

# Register the UDF as a PySpark SQL function
lemmatize_udf = udf(lemmatize_string, StringType())

# Use the UDF to apply lemmatization to the specified column in the DataFrame
df = df.withColumn("lemmatized_column", lemmatize_udf("col_to_lemmatize")
</code>```

What do I need to do to make sure that pyspark recognized nlp and uses it properly?

Note: This will be used for azure databricks and the models are downloaded and all pakcages correctly installed

Body:
Context: I'm trying to apply lemmatization process in a pyspark dataframe, however, when I want to do df.show() or see the output, or even save the table, it doesn't do anything (even with just 3 data points in a small dataframe). The function works as an example such as "purchased bought" returns "purchase buy", but when I apply in a pyspark dataframe it just doesn't do anything?

Minimal example:

import spacy
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

# Load the spaCy English language model
nlp = spacy.load("en_..._md")

# Define a UDF that uses the spaCy lemmatizer to lemmatize a given string
def lemmatize_string(input_string: str) -> str:
    # Use the spaCy nlp object to tokenize the input string
    doc = nlp(input_string)
    # Use the lemma_ attribute of each token to get its lemma, and join the lemmas together
    # with a space character in between to create the lemmatized string
    return " ".join([token.lemma_ for token in doc])

# Register the UDF as a PySpark SQL function
lemmatize_udf = udf(lemmatize_string, StringType())

# Use the UDF to apply lemmatization to the specified column in the DataFrame
df = df.withColumn("lemmatized_column", lemmatize_udf("col_to_lemmatize")

What do I need to do to make sure that pyspark recognized nlp and uses it properly?

Note: This will be used for azure databricks and the models are downloaded and all pakcages correctly installed


问:
i got an error in MIT App Inventor, how do i fix it?
error:

Runtime Error

Attempt to invoke virtual method 'int android.hardware.usb.UsbDeviceCo nnection.bulkTransfer(android.hardw are.usb.UsbEndpoint, byte[], int, int)' on a null object reference

End Application

i tried to make an app that talks to an arduino trough Serial


问:
'ORA-01002 fetch out of sequence' when fetching from cursor based on truncated temporary table
I have a PLSQL function which opens new cursor based on join of persistent table with temporary table. Every time the new cursor is created, the temporary table is truncated and filled with data (the content of temporary table is subset of ids in persistent table - it is actually result of computation of complex search query), each in own autonomous transaction.

Let's create two cursors. First cursor reads half of data, then second cursor reads all data and closes, then the first cursor tries to read remaining data. The attempt of reading remaining data fails with ORA-01002 fetch out of sequence error. The wrong behaviour is observed on Oracle 19.0.0.0.0 (our db) and 19.14.0.0.0 (LiveSQL) but not on Oracle 11 (our previous version).

Minimized example:

create global temporary table temp_table (
  id number(38,0)
) on commit preserve rows;

create table data_table (
  id number(38,0),
  val varchar2(10)
);

insert into data_table
select 1, 'a' from dual union all
select 2, 'b' from dual union all
select 3, 'c' from dual union all
select 4, 'd' from dual;

declare

type ref_cursor is ref cursor;

procedure storeToTempTable
is
  cmd varchar2(32767);
  pragma autonomous_transaction;
begin
  cmd := q'[
    insert into temp_table (id)
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual
  ]';
  execute immediate cmd;
  commit;
end;

procedure truncateTempTable
is
  pragma autonomous_transaction;
begin
  execute immediate 'truncate table temp_table';
end;

function getCursor return ref_cursor
is
  cur      ref_cursor;
  q  varchar2(32767);
begin
  truncateTempTable;
  storeToTempTable;
  q := 'select r.* from data_table r, temp_table t where r.id = t.id';
  open cur for q;
  return cur;
end;

--------------------------------------------------------------------------------

begin -- main

declare
  cursor1 ref_cursor;
  cursor2 ref_cursor;
  dto data_table%rowtype;
  i1 pls_integer := 0;
  i2 pls_integer := 0;
begin
  cursor1 := getCursor;
  loop
    exit when i1 = 2;
    i1 := i1 + 1;
    fetch cursor1 into dto;
    exit when cursor1%notfound;
    dbms_output.put_line('i1 = ' || i1 || ', dto.id = ' || dto.id);
  end loop;
  dbms_output.put_line('not closing 1');
  --dont close cursor1;

  cursor2 := getCursor;
  loop
    i2 := i2 + 1;
    fetch cursor2 into dto;
    exit when cursor2%notfound;
    dbms_output.put_line('i2 = ' || i2 || ', dto.id = ' || dto.id);
  end loop;
  dbms_output.put_line('closing 2');
  close cursor2;

  loop
    i1 := i1 + 1;
    fetch cursor1 into dto;
    exit when cursor1%notfound;
    dbms_output.put_line('i1 = ' || i1 || ', dto.id = ' || dto.id);
  end loop;
  dbms_output.put_line('closing 1');
  close cursor1;
end;

end;
/
```
<p>I guess the table truncation somehow invalidates <code>cursor1</code> during creation of <code>cursor2</code>. I don't have a clue why this worked in previous version (I actually wonder it worked.)</p>
<p>I also figured out a workaround - to replace body of <code>truncateTempTable</code> procedure for <code>execute immediate 'delete from temp_table'; commit;</code>. (Commit is necessary, otherwise ORA-06519 appears.) With the workaround, scripts provides correct result:</p>
```Table created.
Table created.
4 row(s) inserted.
Statement processed.
i1 = 1, dto.id = 1
i1 = 2, dto.id = 2
not closing 1
i2 = 1, dto.id = 1
i2 = 2, dto.id = 2
i2 = 3, dto.id = 3
i2 = 4, dto.id = 4
closing 2
i1 = 3, dto.id = 3
i1 = 4, dto.id = 4
closing 1
```

My question is if there is some support in documentation for such behavior and correctness of proposed workaround.

LiveSQL demo here. (no dbfiddle, sorry - attempts on 18c either fail or return even different results)

Body:
I have a PLSQL function which opens new cursor based on join of persistent table with temporary table. Every time the new cursor is created, the temporary table is truncated and filled with data (the content of temporary table is subset of ids in persistent table - it is actually result of computation of complex search query), each in own autonomous transaction.

Let's create two cursors. First cursor reads half of data, then second cursor reads all data and closes, then the first cursor tries to read remaining data. The attempt of reading remaining data fails with ORA-01002 fetch out of sequence error. The wrong behaviour is observed on Oracle 19.0.0.0.0 (our db) and 19.14.0.0.0 (LiveSQL) but not on Oracle 11 (our previous version).

Minimized example:

create global temporary table temp_table (
  id number(38,0)
) on commit preserve rows;

create table data_table (
  id number(38,0),
  val varchar2(10)
);

insert into data_table
select 1, 'a' from dual union all
select 2, 'b' from dual union all
select 3, 'c' from dual union all
select 4, 'd' from dual;

declare

type ref_cursor is ref cursor;

procedure storeToTempTable
is
  cmd varchar2(32767);
  pragma autonomous_transaction;
begin
  cmd := q'[
    insert into temp_table (id)
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual
  ]';
  execute immediate cmd;
  commit;
end;

procedure truncateTempTable
is
  pragma autonomous_transaction;
begin
  execute immediate 'truncate table temp_table';
end;

function getCursor return ref_cursor
is
  cur      ref_cursor;
  q  varchar2(32767);
begin
  truncateTempTable;
  storeToTempTable;
  q := 'select r.* from data_table r, temp_table t where r.id = t.id';
  open cur for q;
  return cur;
end;

--------------------------------------------------------------------------------

begin -- main

declare
  cursor1 ref_cursor;
  cursor2 ref_cursor;
  dto data_table%rowtype;
  i1 pls_integer := 0;
  i2 pls_integer := 0;
begin
  cursor1 := getCursor;
  loop
    exit when i1 = 2;
    i1 := i1 + 1;
    fetch cursor1 into dto;
    exit when cursor1%notfound;
    dbms_output.put_line('i1 = ' || i1 || ', dto.id = ' || dto.id);
  end loop;
  dbms_output.put_line('not closing 1');
  --dont close cursor1;

  cursor2 := getCursor;
  loop
    i2 := i2 + 1;
    fetch cursor2 into dto;
    exit when cursor2%notfound;
    dbms_output.put_line('i2 = ' || i2 || ', dto.id = ' || dto.id);
  end loop;
  dbms_output.put_line('closing 2');
  close cursor2;

  loop
    i1 := i1 + 1;
    fetch cursor1 into dto;
    exit when cursor1%notfound;
    dbms_output.put_line('i1 = ' || i1 || ', dto.id = ' || dto.id);
  end loop;
  dbms_output.put_line('closing 1');
  close cursor1;
end;

end;
/

I guess the table truncation somehow invalidates cursor1 during creation of cursor2. I don't have a clue why this worked in previous version (I actually wonder it worked.)

I also figured out a workaround - to replace body of truncateTempTable procedure for execute immediate 'delete from temp_table'; commit;. (Commit is necessary, otherwise ORA-06519 appears.) With the workaround, scripts provides correct result:

Table created.
Table created.
4 row(s) inserted.
Statement processed.
i1 = 1, dto.id = 1
i1 = 2, dto.id = 2
not closing 1
i2 = 1, dto.id = 1
i2 = 2, dto.id = 2
i2 = 3, dto.id = 3
i2 = 4, dto.id = 4
closing 2
i1 = 3, dto.id = 3
i1 = 4, dto.id = 4
closing 1

My question is if there is some support in documentation for such behavior and correctness of proposed workaround.

LiveSQL demo here. (no dbfiddle, sorry - attempts on 18c either fail or return even different results)


问:
Recommendations for developing Laravel User account pages as SPA?
Looking to rebuild account pages for users of a Laravel 8 based application using something like Inertia/Livewire, Vue/React to make just the account area an SPA. User accounts currently have many pages in which to manage their items and have a dashboard that summarises item data that link to item listing pages for managing.

Ideally the new dashboard will have component based widgets which would load the HTML with temporary place holders for the items whilst the data is being requested. Not sure what would make a better user experience, having the whole page show temporary place holders for dynamic data and then all populate at the same time or populate each component as and when the data is ready.

Would it be more efficient to have each component request its own data individually or should each component specify what data it needs to the parent component (dashboard) which then does one request for all widgets?

The widgets would link to item listing pages where users can manage items. The way the listing pages should work is very similar to that of Asana, when an item is selected it opens a panel to the right of the list which loads the data related to that item. Again, when the panel opens it has place holders until the data requested has been fetched.

With Inertia the data can be queried in the controller and then passed as props to the view that Inertia renders. Items would be passed in this way and then listed on a listing page component. The URL should update from /items to /item/123 when clicking an item so it would have its own dynamic route that passes the item id to the relevant action.

Would this have its own action separate from the one that gets the initial list of items?
The list still needs to be there and used to click between items so was thinking it could actually use the same action?

Items could be in the thousands and will have filtering options so pagination and throttling will be necessary.

Been looking at Inertia with Vue so far and it looks to meet requirements, can’t change from using Laravel 8,  just wondering what approach would be most suitable or if there is another approach that should be considered. Interested to hear how others might go about it.


问:
How can I fix this error? User' does not exist on type 'exports'
I want to write my code as below but the typescript compiler won't let me
what's the solution?

controller.ts

```<code>const autoBind = require('auto-bind')
const User = require('../model/user')

module.exports = class {
  constructor() {
    autoBind(this)
    this.User = User;
  }
}
</code>```

Body:
I want to write my code as below but the typescript compiler won't let me
what's the solution?

controller.ts

const autoBind = require('auto-bind')
const User = require('../model/user')

module.exports = class {
  constructor() {
    autoBind(this)
    this.User = User;
  }
}


问:
Perfectly fine method reference does not compile on most JDKs
While coding, I spotted that replacing a lambda with a perfectly fine (IMO) method reference results in a compilation error using openJDK 17.

Investigation of the case led me to creating a minimal example of the code, that does not work in compilers that I found on my PC:

```<code>import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

class ExampleTest {
    public static void main(String[] args) {
        SessionContext sessionContext = new SessionContext();
        Entity foo = new Entity(null, "foo");

        Optional<Long> id = sessionContext.get(session -> {
            return Stream.of(foo)
                    .map(entity -> insert(entity, session))
                    .map(Entity::getId)
                    .findAny();
        });

        System.out.println(id);
    }

    static Entity insert(Entity entity, Session session) {
        return session.persist(entity);
    }
}

class Session {
    Entity persist(Entity entity) {
        entity.setId(42L);
        return entity;
    }
}

class SessionContext {
    Session session = new Session();

    <T> T get(Function<Session, T> query) {
        return query.apply(session);
    }
}

class Entity {
    private Long id;
    private String data;

    Entity(Long id, String data) {
        this.id = id;
        this.data = data;
    }

    Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = id;
    }
}
</code>```

As far as I checked, the code compiles on openJDK 8. It does not compile on the following JVMs:

openJDK 17;

zulu16;

zulu17;

oracle 18.

Error displayed by the compilers:

```<code>ExampleTest.java:13: error: incompatible types: invalid method reference
                    .map(Entity::getId)
                         ^
    method getId in class Entity cannot be applied to given types
      required: no arguments
      found:    Object
      reason: actual and formal argument lists differ in length
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
</code>```

There are other quirks too. If you follow the hint in the message above and use -Xdiags:verbose... The compilation will automagically pass!

Please note that:

The code example itself might not make much sense, it is just to illustrate the point in the most clear way.

There can be a lot of refactorings done to the example code, but as far as I checked, they ultimately lead to not getting the compilation error.

Has anyone observed similar behavior? Does anyone recall if it is an official compilator error? Or maybe I am missing something in the code?

I expected this code to compile on all JVM as it looks OK.

Body:
While coding, I spotted that replacing a lambda with a perfectly fine (IMO) method reference results in a compilation error using openJDK 17.

Investigation of the case led me to creating a minimal example of the code, that does not work in compilers that I found on my PC:

import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

class ExampleTest {
    public static void main(String[] args) {
        SessionContext sessionContext = new SessionContext();
        Entity foo = new Entity(null, "foo");

        Optional<Long> id = sessionContext.get(session -> {
            return Stream.of(foo)
                    .map(entity -> insert(entity, session))
                    .map(Entity::getId)
                    .findAny();
        });

        System.out.println(id);
    }

    static Entity insert(Entity entity, Session session) {
        return session.persist(entity);
    }
}

class Session {
    Entity persist(Entity entity) {
        entity.setId(42L);
        return entity;
    }
}

class SessionContext {
    Session session = new Session();

    <T> T get(Function<Session, T> query) {
        return query.apply(session);
    }
}

class Entity {
    private Long id;
    private String data;

    Entity(Long id, String data) {
        this.id = id;
        this.data = data;
    }

    Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = id;
    }
}

As far as I checked, the code compiles on openJDK 8. It does not compile on the following JVMs:

openJDK 17;

zulu16;

zulu17;

oracle 18.

Error displayed by the compilers:

ExampleTest.java:13: error: incompatible types: invalid method reference
                    .map(Entity::getId)
                         ^
    method getId in class Entity cannot be applied to given types
      required: no arguments
      found:    Object
      reason: actual and formal argument lists differ in length
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

There are other quirks too. If you follow the hint in the message above and use -Xdiags:verbose... The compilation will automagically pass!

Please note that:

The code example itself might not make much sense, it is just to illustrate the point in the most clear way.

There can be a lot of refactorings done to the example code, but as far as I checked, they ultimately lead to not getting the compilation error.

Has anyone observed similar behavior? Does anyone recall if it is an official compilator error? Or maybe I am missing something in the code?

I expected this code to compile on all JVM as it looks OK.


问:
how to merge result from Python ThreadPoolExecutor?
I send some request with ThreadPoolExecutor but my merge after all do not work.

My code is:

```<code>from concurrent.futures import ThreadPoolExecutor

def get_foo_by_bars(authorisation_token: str, bar_ids: list):
    # Split the bar_ids list into chunks of size 10
    bar_id_chunks = [bar_ids[i:i + 10] for i in range(0, len(bar_ids), 10)]

    # Create a thread pool with as many threads as there are chunks
    with ThreadPoolExecutor(max_workers=len(bar_id_chunks)) as executor:
        # Use the map method to apply the send_request function to each chunk in parallel
        results = executor.map(send_request, bar_id_chunks, [authorisation_token] * len(bar_id_chunks))

    # Merge the results into a single list
    merged_results = [item for sublist in results for item in sublist]
    return merged_results

def send_request(bar_ids, authorisation_token):
    r = requests.get(BASE_URL + "/api/v1/foo/bar",
                     params={"bar_ids": bar_ids, "data_type": "Float"},
                     headers={"Authorization": authorisation_token})
    if r.status_code == 200:
        return r.json()["data"]["data"]
</code>```

My error is on merged_results = [item for sublist in results for item in sublist] line.

[ERROR] TypeError: 'NoneType' object is not iterable

Body:
I send some request with ThreadPoolExecutor but my merge after all do not work.

My code is:

from concurrent.futures import ThreadPoolExecutor

def get_foo_by_bars(authorisation_token: str, bar_ids: list):
    # Split the bar_ids list into chunks of size 10
    bar_id_chunks = [bar_ids[i:i + 10] for i in range(0, len(bar_ids), 10)]

    # Create a thread pool with as many threads as there are chunks
    with ThreadPoolExecutor(max_workers=len(bar_id_chunks)) as executor:
        # Use the map method to apply the send_request function to each chunk in parallel
        results = executor.map(send_request, bar_id_chunks, [authorisation_token] * len(bar_id_chunks))

    # Merge the results into a single list
    merged_results = [item for sublist in results for item in sublist]
    return merged_results

def send_request(bar_ids, authorisation_token):
    r = requests.get(BASE_URL + "/api/v1/foo/bar",
                     params={"bar_ids": bar_ids, "data_type": "Float"},
                     headers={"Authorization": authorisation_token})
    if r.status_code == 200:
        return r.json()["data"]["data"]

My error is on merged_results = [item for sublist in results for item in sublist] line.

[ERROR] TypeError: 'NoneType' object is not iterable


问:
How do I make my project modular with CMake?
First of all, I don't know what I should call it, module, component, or library are all fitting for me, but gave all mixed results trying to figure this out.

Problem

I am working on a project in C, where the amount of files grew quite large, so I wanted to split it up a bit, both for ordering and make it look less cluttered.

I want a file structure that looks something like this:

```<code>root
├modules
│├module_foo
││├include
│││├module_foo_a.h
││││...
│││└module_foo_z.h
││├private_include
│││├a.h
││││...
│││└z.h
││├source
│││├module_foo_a.c
││││...
│││└module_foo_z.c
││└module_foo.h
│└module_bar
│ ├include
│ │├module_bar_a.h
│ ││...
│ │└module_bar_z.h
│ ├private_include
│ │├a.h
│ ││...
│ │└z.h
│ ├source
│ │├module_bar_a.c
│ ││...
│ │└module_bar_z.c
│ └module_bar.h
├main.c
├main.h
└CMakeLists.txt
</code>```

Clarification

The goal of this would be that the private_include folders would be inaccessible by other modules and main, and the different modules would need to work (fairly) independent. Modules can include other modules, but this would need to be defined explicitly.

I also would like the CMake to be easy to modify, ideally only a single/couple line(s) to change for the modules used.

Pre research

As mentioned above, I have searched already, but the CMake documentation isn't meant for the people who just want to do some C coding.

When I searched for modules, almost all results were about the C++ modules and how to integrate them into CMake.

Components mostly gave results about the COMPONENTS keyword.

Library had the most results, however it still requires me to use #include "modules/module_foo/include/module_foo_a.h" from main, or #include "../../module_bar/include/module_bar_a.h" from module foo. The goal would be to have in both instances #include "module_foo_a.h".
Subdirectory isn't what I am looking for I believe, because that still makes it part of the root project. This is not what I want.

For the modules I currently have

```<code>project(foo)

add_library(${PROJECT_NAME} STATIC source/module_foo_a.c include/module_foo_a.h)

include_directories(private_include include)

link_libraries(bar)

target_include_directories(${PROJECT_NAME} INTERFACE include)

target_link_libraries(${PROJECT_NAME} PRIVATE bar)
</code>```

I have included the header files in the add_library because one source I found said it helped with IDE's.
I don't remember why I made the target_include_directories interface, or the target_link_libraries private.

For my main CMake I have

```<code>project(foobar)

include_directories(include)

add_executable(${PROJECT_NAME} source/main.c)

target_link_libraries(${PROJECT_NAME} foo bar)
</code>```

I believe I need to include bar again because of the private link in the module.

I don't even know if what I am searching for is actually possible, but I would really like to work with it this way, or close to this.

edit

Before I tried to add modules the folder structure looked something like this:

```<code>root
├include
│├foo_a.h
││...
│├foo_z.h
│├bar_a.h
││...
│├bar_z.h
│└main.h
└source
 ├foo_a.c
 │...
 ├foo_z.c
 ├bar_a.c
 │...
 ├bar_z.c
 └main.c
</code>```

This got very cluttered very quickly, hence why I want to change to modules.

As stated in my comment, the part that I have put above is what I have now. This does not make the modules easy to work with, as they don't provide short include names, both from outside the modules (main) and other modules (bar).

The little bits that I understand from CMake is that the functions have a 'normal' variant and a 'target' variant.

'Normal' is just for the current project, and 'target' is meant to also allow other CMakes to use those specified files/folders. This should however not work for the private_include folders, as they are only to be known to the module itself.

If I understand it correctly, including private_include in the 'target' variant would make it possible that you would do #include "a.h" or #include "private_include/a.h" in main, which is not what I want.

Body:
First of all, I don't know what I should call it, module, component, or library are all fitting for me, but gave all mixed results trying to figure this out.

Problem

I am working on a project in C, where the amount of files grew quite large, so I wanted to split it up a bit, both for ordering and make it look less cluttered.

I want a file structure that looks something like this:

root
├modules
│├module_foo
││├include
│││├module_foo_a.h
││││...
│││└module_foo_z.h
││├private_include
│││├a.h
││││...
│││└z.h
││├source
│││├module_foo_a.c
││││...
│││└module_foo_z.c
││└module_foo.h
│└module_bar
│ ├include
│ │├module_bar_a.h
│ ││...
│ │└module_bar_z.h
│ ├private_include
│ │├a.h
│ ││...
│ │└z.h
│ ├source
│ │├module_bar_a.c
│ ││...
│ │└module_bar_z.c
│ └module_bar.h
├main.c
├main.h
└CMakeLists.txt

Clarification

The goal of this would be that the private_include folders would be inaccessible by other modules and main, and the different modules would need to work (fairly) independent. Modules can include other modules, but this would need to be defined explicitly.

I also would like the CMake to be easy to modify, ideally only a single/couple line(s) to change for the modules used.

Pre research

As mentioned above, I have searched already, but the CMake documentation isn't meant for the people who just want to do some C coding.

When I searched for modules, almost all results were about the C++ modules and how to integrate them into CMake.

Components mostly gave results about the COMPONENTS keyword.

Library had the most results, however it still requires me to use #include "modules/module_foo/include/module_foo_a.h" from main, or #include "../../module_bar/include/module_bar_a.h" from module foo. The goal would be to have in both instances #include "module_foo_a.h".
Subdirectory isn't what I am looking for I believe, because that still makes it part of the root project. This is not what I want.

For the modules I currently have

project(foo)

add_library(${PROJECT_NAME} STATIC source/module_foo_a.c include/module_foo_a.h)

include_directories(private_include include)

link_libraries(bar)

target_include_directories(${PROJECT_NAME} INTERFACE include)

target_link_libraries(${PROJECT_NAME} PRIVATE bar)

I have included the header files in the add_library because one source I found said it helped with IDE's.
I don't remember why I made the target_include_directories interface, or the target_link_libraries private.

For my main CMake I have

project(foobar)

include_directories(include)

add_executable(${PROJECT_NAME} source/main.c)

target_link_libraries(${PROJECT_NAME} foo bar)

I believe I need to include bar again because of the private link in the module.

I don't even know if what I am searching for is actually possible, but I would really like to work with it this way, or close to this.

edit

Before I tried to add modules the folder structure looked something like this:

root
├include
│├foo_a.h
││...
│├foo_z.h
│├bar_a.h
││...
│├bar_z.h
│└main.h
└source
 ├foo_a.c
 │...
 ├foo_z.c
 ├bar_a.c
 │...
 ├bar_z.c
 └main.c

This got very cluttered very quickly, hence why I want to change to modules.

As stated in my comment, the part that I have put above is what I have now. This does not make the modules easy to work with, as they don't provide short include names, both from outside the modules (main) and other modules (bar).

The little bits that I understand from CMake is that the functions have a 'normal' variant and a 'target' variant.

'Normal' is just for the current project, and 'target' is meant to also allow other CMakes to use those specified files/folders. This should however not work for the private_include folders, as they are only to be known to the module itself.

If I understand it correctly, including private_include in the 'target' variant would make it possible that you would do #include "a.h" or #include "private_include/a.h" in main, which is not what I want.


问:
Input not fitting to CNN architecture
I implemented a CNN Model and the first part of it looks as follows:

```<code>    nn.ReLU(),
    nn.Conv1d(in_channels=16,out_channels=32,kernel_size=3,padding=2),
    nn.BatchNorm1d(32),
    nn.ReLU(),
    nn.MaxPool1d(kernel_size=2,stride=2,padding=1),
    nn.Conv1d(in_channels=32,out_channels=64,kernel_size=3,dilation=2,padding=2),
    nn.BatchNorm1d(64), nn.ReLU(),
    #...
</code>```

I am trying to run the Model, but I keep getting this error
Expected 2D (unbatched) or 3D (batched) input to conv1d, but got input of size: [4]

When I reshape the input, using tensor reshape, I get this new error
RuntimeError: running_mean should contain 6 elements not 32

What does that mean? How can I fix this? Would that be related to the nn.BatchNorm1d?

Title: Input not fitting to CNN architecture

Body:
I implemented a CNN Model and the first part of it looks as follows:

    nn.ReLU(),
    nn.Conv1d(in_channels=16,out_channels=32,kernel_size=3,padding=2),
    nn.BatchNorm1d(32),
    nn.ReLU(),
    nn.MaxPool1d(kernel_size=2,stride=2,padding=1),
    nn.Conv1d(in_channels=32,out_channels=64,kernel_size=3,dilation=2,padding=2),
    nn.BatchNorm1d(64), nn.ReLU(),
    #...

I am trying to run the Model, but I keep getting this error
Expected 2D (unbatched) or 3D (batched) input to conv1d, but got input of size: [4]

When I reshape the input, using tensor reshape, I get this new error
RuntimeError: running_mean should contain 6 elements not 32

What does that mean? How can I fix this? Would that be related to the nn.BatchNorm1d?


问:
How to configure TwinCAT EtherCAT PDOs?
I am having a problem to access to the rest of the memory of a etherCAT device, since it already comes with a default PDO configuration, but when i try to edit this configuration, it won't change and the device stops working correctly unless i use the default configuration again.

Is this the correct way of doing it, or is there any other mwthod to achieve this?. Or maybe, should I edit the ESI field to upload this properties to the device?

I already tried what beckhoff documentation says about adding new PDO directories, but i still get the same result. I also tried using the same directories and properties to the previous configuration adding the directories of the device that I also want to read and write.

Title: How to configure TwinCAT EtherCAT PDOs?


问:
jstree theme/icon size - how to change to the 40px one?
I am trying to increase the size of the icons in JSTree to anything above the tiny 32px. I've been trawling the internet for what seems like days to try and find anything. In the themes folder I can see an image for 40px and in the documentation it says if I set it to "responsive" it should use the 40px style but I just can't get it to work regardless of what I try. Any ideas?

```<code>$('#libraryTreeview').jstree({
    "core": {
        },
        'data': [
            { "id": "ajson1", "parent": "#", "text": "Simple root node", "type": "file" },
            { "id": "ajson2", "parent": "#", "text": "Root node 2" },
            { "id": "ajson3", "parent": "ajson2", "text": "Child 1" },
            { "id": "ajson4", "parent": "ajson2", "text": "Child 2", "type": "file" },
        ]
    },
    "themes": {
        variant: 'responsive',
        dots: false
    },
    "types": {
        "folder": {
            "icon": "WebsiteImages/LibraryIcons/Folder48.png"
        },
        "file": {
            "icon": "WebsiteImages/LibraryIcons/Image48.png"
        }
    },
    "plugins": ["types","themes","dnd","wholerow"]
})
</code>```

Bonus points if anyone has a stylesheet already done that uses 48px or 64px!!!!

Body:
I am trying to increase the size of the icons in JSTree to anything above the tiny 32px. I've been trawling the internet for what seems like days to try and find anything. In the themes folder I can see an image for 40px and in the documentation it says if I set it to "responsive" it should use the 40px style but I just can't get it to work regardless of what I try. Any ideas?

$('#libraryTreeview').jstree({
    "core": {
        },
        'data': [
            { "id": "ajson1", "parent": "#", "text": "Simple root node", "type": "file" },
            { "id": "ajson2", "parent": "#", "text": "Root node 2" },
            { "id": "ajson3", "parent": "ajson2", "text": "Child 1" },
            { "id": "ajson4", "parent": "ajson2", "text": "Child 2", "type": "file" },
        ]
    },
    "themes": {
        variant: 'responsive',
        dots: false
    },
    "types": {
        "folder": {
            "icon": "WebsiteImages/LibraryIcons/Folder48.png"
        },
        "file": {
            "icon": "WebsiteImages/LibraryIcons/Image48.png"
        }
    },
    "plugins": ["types","themes","dnd","wholerow"]
})

Bonus points if anyone has a stylesheet already done that uses 48px or 64px!!!!


问:
setting time zone attribute with `Sys.time()`
I use the checkmate package to check values progressing through a pipeline.

Currently I assert that all datetime values are in the past. I want to throw an error if any datetime is in the future, so I'm comparing the values to Sys.time().

But

checkmate::assert_posixct() strictly requires that the values have the same timezones, and

Sys.time() doesn't have a timezone by default.

My first three attempts fail and the 4th & 5th attempts seem unnecessary indirect.

I have a few related questions:

Is there a better approach & solution?

Why does upper_1 display "CST", but have a null time zone attribute?

Why does upper_3 display "CST", but have a null or "UTC" attribute, depending where you look?  (Here is lubridate's implmentation.)

Am I missing some important concept?

Input

timezone_local <- "America/Chicago"
dt <-
  c(
    "2021-01-01 12:34:56",
    "2022-01-01 22:34:56"
  ) |>
  as.POSIXct(tz = timezone_local)

attr(dt, "tzone")
# [1] "America/Chicago"
lubridate::tz(dt)
# [1] "America/Chicago"
```
<h3>Attempt 1: use the current time {fail}</h3>
<p>Despite the "CST" output, the timezone isn't recognized by lubridate or checkmate.</p>
<pre class="lang-r prettyprint-override"><code>upper_1 <- Sys.time()
upper_1
# [1] "2022-12-06 09:35:45 CST"
attr(upper_1, "tzone")
# NULL
lubridate::tz(upper_1)
# [1] ""
checkmate::assert_posixct(dt, upper = upper_1)
# Error in eval(ei, envir) :
#   Assertion on 'dt' failed: Timezones of 'x' and 'upper' must match.
</code>```

Attempt 2: passing a posxict value doesn't work {fail}

upper_2 <- as.POSIXct(Sys.time(), tz = timezone_local)
upper_2
# [1] "2022-12-06 09:35:46 CST"
attr(upper_2, "tzone")
# NULL
lubridate::tz(upper_2)
# [1] ""
checkmate::assert_posixct(dt, upper = upper_2)
# Error in eval(ei, envir) :
#   Assertion on 'dt' failed: Timezones of 'x' and 'upper' must match.
```
<h3>Attempt 3: using <code>format()</code> produces a conflict between UTC & CST? {fail}</h3>
<p>From https://stackoverflow.com/a/63951629/1082435</p>
<pre class="lang-r prettyprint-override"><code>upper_3 <- format(Sys.time(), tz = timezone_local, usetz = TRUE)
upper_3
# [1] "2022-12-06 09:35:47 CST"
attr(upper_3, "tzone")
# NULL
lubridate::tz(upper_3)
# [1] "UTC"
checkmate::assert_posixct(dt, upper = upper_3)
# Error in checkmate::assert_posixct(dt, upper = upper_3) :
#   Argument 'upper' must be provided as single POSIXct time
</code>```

Attempt 4: setting the attribute directly {success}

From https://stackoverflow.com/a/63951569/1082435

upper_4 <- `attr<-`(as.POSIXct(Sys.time()), "tzone", timezone_local)
upper_4
# [1] "2022-12-06 09:35:48 CST"
attr(upper_4, "tzone")
# "America/Chicago"
lubridate::tz(upper_4)
# [1] "America/Chicago"
checkmate::assert_posixct(dt, upper = upper_4)
# (The check passes)
```
<h3>Attempt 5: passing a string works {success}</h3>
<pre class="lang-r prettyprint-override"><code>upper_5 <- as.POSIXct(as.character(Sys.time()), tz = timezone_local)
upper_5
# [1] "2022-12-06 09:35:49 CST"
attr(upper_5, "tzone")
# "America/Chicago"
lubridate::tz(upper_5)
# [1] "America/Chicago"
checkmate::assert_posixct(dt, upper = upper_5)
# (The check passes)
</code>```

Body:
I use the checkmate package to check values progressing through a pipeline.

Currently I assert that all datetime values are in the past. I want to throw an error if any datetime is in the future, so I'm comparing the values to Sys.time().

But

checkmate::assert_posixct() strictly requires that the values have the same timezones, and

Sys.time() doesn't have a timezone by default.

My first three attempts fail and the 4th & 5th attempts seem unnecessary indirect.

I have a few related questions:

Is there a better approach & solution?

Why does upper_1 display "CST", but have a null time zone attribute?

Why does upper_3 display "CST", but have a null or "UTC" attribute, depending where you look?  (Here is lubridate's implmentation.)

Am I missing some important concept?

Input

timezone_local <- "America/Chicago"
dt <-
  c(
    "2021-01-01 12:34:56",
    "2022-01-01 22:34:56"
  ) |>
  as.POSIXct(tz = timezone_local)

attr(dt, "tzone")
# [1] "America/Chicago"
lubridate::tz(dt)
# [1] "America/Chicago"

Attempt 1: use the current time {fail}

Despite the "CST" output, the timezone isn't recognized by lubridate or checkmate.

upper_1 <- Sys.time()
upper_1
# [1] "2022-12-06 09:35:45 CST"
attr(upper_1, "tzone")
# NULL
lubridate::tz(upper_1)
# [1] ""
checkmate::assert_posixct(dt, upper = upper_1)
# Error in eval(ei, envir) :
#   Assertion on 'dt' failed: Timezones of 'x' and 'upper' must match.

Attempt 2: passing a posxict value doesn't work {fail}

upper_2 <- as.POSIXct(Sys.time(), tz = timezone_local)
upper_2
# [1] "2022-12-06 09:35:46 CST"
attr(upper_2, "tzone")
# NULL
lubridate::tz(upper_2)
# [1] ""
checkmate::assert_posixct(dt, upper = upper_2)
# Error in eval(ei, envir) :
#   Assertion on 'dt' failed: Timezones of 'x' and 'upper' must match.

Attempt 3: using format() produces a conflict between UTC & CST? {fail}

From https://stackoverflow.com/a/63951629/1082435

upper_3 <- format(Sys.time(), tz = timezone_local, usetz = TRUE)
upper_3
# [1] "2022-12-06 09:35:47 CST"
attr(upper_3, "tzone")
# NULL
lubridate::tz(upper_3)
# [1] "UTC"
checkmate::assert_posixct(dt, upper = upper_3)
# Error in checkmate::assert_posixct(dt, upper = upper_3) :
#   Argument 'upper' must be provided as single POSIXct time

Attempt 4: setting the attribute directly {success}

From https://stackoverflow.com/a/63951569/1082435

upper_4 <- `attr<-`(as.POSIXct(Sys.time()), "tzone", timezone_local)
upper_4
# [1] "2022-12-06 09:35:48 CST"
attr(upper_4, "tzone")
# "America/Chicago"
lubridate::tz(upper_4)
# [1] "America/Chicago"
checkmate::assert_posixct(dt, upper = upper_4)
# (The check passes)

Attempt 5: passing a string works {success}

upper_5 <- as.POSIXct(as.character(Sys.time()), tz = timezone_local)
upper_5
# [1] "2022-12-06 09:35:49 CST"
attr(upper_5, "tzone")
# "America/Chicago"
lubridate::tz(upper_5)
# [1] "America/Chicago"
checkmate::assert_posixct(dt, upper = upper_5)
# (The check passes)


问:
Create a relationship by ID using Neo4J and Spring Data
I have defined a simple node object like this:

```<code>@Node("product")
public class Product {

    @Id
    private String sku;

    ...

    @Relationship(type = "SOLD_BY")
    private Set<Shop> shops = new HashSet<>();

    ...
}
</code>```

However, my concerns are:

To create (and save) a new Product I must not only create the Product, but also the list of Shop objects. And maybe a Shop object holds an Address object or a list of Employees itself. This means I'm forced to construct a huge list of objects.

Also, maybe the Shop objects are already existing in the database and I don't want to overwrite them by saving the new Product.

By loading a Product, all related Shop objects will be loaded and so on. But I'm just interested in the Product, not in everything connected to it.

So instead I want to do this:

```<code>    @Relationship(type = "SOLD_BY")
    private Set<String> shops = new HashSet<>(); // Just the IDs of the Shops
</code>```

Is this possible?

Is this a valid approach to solve my problem?

Body:
I have defined a simple node object like this:

@Node("product")
public class Product {

    @Id
    private String sku;

    ...

    @Relationship(type = "SOLD_BY")
    private Set<Shop> shops = new HashSet<>();

    ...
}

However, my concerns are:

To create (and save) a new Product I must not only create the Product, but also the list of Shop objects. And maybe a Shop object holds an Address object or a list of Employees itself. This means I'm forced to construct a huge list of objects.

Also, maybe the Shop objects are already existing in the database and I don't want to overwrite them by saving the new Product.

By loading a Product, all related Shop objects will be loaded and so on. But I'm just interested in the Product, not in everything connected to it.

So instead I want to do this:

    @Relationship(type = "SOLD_BY")
    private Set<String> shops = new HashSet<>(); // Just the IDs of the Shops

Is this possible?

Is this a valid approach to solve my problem?


问:
Pandas - Distribute values for one day equally across the next week's days?
I have a data frame with a date column and a sales volume column.

There are days that I need to set sales volumes to zero and then distribute those volumes equally to the volumes of the next five non-weekend days.

So if I have a volume of 100 on a Monday, the next five non-business days are their volumes + (100/5).

I've tried some work arounds using date_range, but haven't had any success. I'm very lost on how to do this since I'm not so good with datetime methods.


问:
How to read or parse CRL with PHP
The code below works for "user certificates" or "certificate authority certificates"

The generated Pem file is like this

-----BEGIN CERTIFICATE-----

MIIEVDCCAzygAwIBAgIBBTANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJGUjEZ

...

3zk8lbSs5UE=

-----END CERTIFICATE-----

And I get the information about the certificate which I can use easily afterwards.

In particular the issuer and the timestamps (and others informations)

```<code>function derToPem($contentFonc,$typeFonc="")
{
    $response = "";

    if($contentFonc!="")
    {
        $response = chunk_split(base64_encode($contentFonc), 64, "\n");

        if($typeFonc!="crl")    $response = "-----BEGIN CERTIFICATE-----\n".$response."-----END CERTIFICATE-----\n";
        else $response = "-----BEGIN X509 CRL-----\n".$response."-----END X509 CRL-----\n";
  }

  return($response);
}

// Personnal Function That Return Certificat in DER (Binary) Format
$certificateContentDer = extractLdapQuery();

// Conversion DER to PEM
$certificateContentPem = derToPem($certificateContentDer);

// Extraction Information
$listeInfoCertificate   = openssl_x509_parse($certificateContentPem);
</code>```

But I would also like to do the same for a CRL.

My function "derToPem" works fine.

I compared to a transformed pem with the "openssl crl" command and the files are identical (encapsuled with the text "... X509 CRL...")

But I don't know how to extract information from this "crl.pem" file.

openssl_x509_parse function doesn't work.

I would like to be able to extract the issuer and the dates (last update and next update).

I know it's possible with "openssl crl" command like this "openssl crl -in my_file_crl.pem -noout -issuer"

But how to do this with PHP...?

I searched on Net before ask here but I don't find.

It's not possible in PHP...? Without running the openssl command and getting its output..?

Title: How to read or parse CRL with PHP

Body:
The code below works for "user certificates" or "certificate authority certificates"

The generated Pem file is like this

-----BEGIN CERTIFICATE-----

MIIEVDCCAzygAwIBAgIBBTANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJGUjEZ

...

3zk8lbSs5UE=

-----END CERTIFICATE-----

And I get the information about the certificate which I can use easily afterwards.

In particular the issuer and the timestamps (and others informations)

function derToPem($contentFonc,$typeFonc="")
{
    $response = "";

    if($contentFonc!="")
    {
        $response = chunk_split(base64_encode($contentFonc), 64, "\n");

        if($typeFonc!="crl")    $response = "-----BEGIN CERTIFICATE-----\n".$response."-----END CERTIFICATE-----\n";
        else $response = "-----BEGIN X509 CRL-----\n".$response."-----END X509 CRL-----\n";
  }

  return($response);
}

// Personnal Function That Return Certificat in DER (Binary) Format
$certificateContentDer = extractLdapQuery();

// Conversion DER to PEM
$certificateContentPem = derToPem($certificateContentDer);

// Extraction Information
$listeInfoCertificate   = openssl_x509_parse($certificateContentPem);

But I would also like to do the same for a CRL.

My function "derToPem" works fine.

I compared to a transformed pem with the "openssl crl" command and the files are identical (encapsuled with the text "... X509 CRL...")

But I don't know how to extract information from this "crl.pem" file.

openssl_x509_parse function doesn't work.

I would like to be able to extract the issuer and the dates (last update and next update).

I know it's possible with "openssl crl" command like this "openssl crl -in my_file_crl.pem -noout -issuer"

But how to do this with PHP...?

I searched on Net before ask here but I don't find.

It's not possible in PHP...? Without running the openssl command and getting its output..?


问:
The font size of chart on android device is different from on iOS device and on Simulator
This issue happens on the pie charts, time series charts, and line charts. I have an example on the pie chart.
I have a medium font declared as follows:
public static Font medFont = Font.createTrueTypeFont("Noto Sans CJK TC Light", "Noto Sans CJK TC Light.ttf").derive(36f, Style.UNIT_TYPE_DIPS);

And set the label of the pie chart as follows:
renderer.setLabelsTextSize(medFont.getHeight()/2);

the pie chart on the simulator with Samsung Galaxy s7 Skin

the pie chart on an iOS device - iPhone 7 plus

the pie char on an Android device -Samsung A31


问:
Issues with vue router installed on my vue2 project
When I installed vue router on my vue2 project, all the code on my App.vue file got overriden and the router-link thingy was set-up there instead now I can't find the code anywhere and that code is very important cos its the homepage of the website.

I tried uninstalling vue router cos I thought this would help but the steps for the uninstallation was very confusing. Please anyone with any ideas? I'd appreciate it a lot.


问:
Kotlin: Only the original thread that created a view hierarchy can touch its views
I have problem with this solution. I have multi language app. In original lang its all ok, but when  I change lang to EN, app return error on line with this code:

```<code>android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at com.example.quiz.LogicalActivity.setQuestion(LogicalActivity.kt:114)
at com.example.quiz.LogicalActivity.setAnswer(LogicalActivity.kt:210)
at com.example.quiz.LogicalActivity.access$setAnswer(LogicalActivity.kt:31)
</code>```
```<code>idTvQuestion.setText(getString(R.string.abstract_question_2_question))
</code>```
```<code><string name="abstract_question_3_question">The more days, months or years have passed from your injury, the more likely it is it stops hurting.</string>
</code>```

I try too many solutions..

Body:
I have problem with this solution. I have multi language app. In original lang its all ok, but when  I change lang to EN, app return error on line with this code:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at com.example.quiz.LogicalActivity.setQuestion(LogicalActivity.kt:114)
at com.example.quiz.LogicalActivity.setAnswer(LogicalActivity.kt:210)
at com.example.quiz.LogicalActivity.access$setAnswer(LogicalActivity.kt:31)

idTvQuestion.setText(getString(R.string.abstract_question_2_question))

<string name="abstract_question_3_question">The more days, months or years have passed from your injury, the more likely it is it stops hurting.</string>

I try too many solutions..