问:
Overriding the Console class in typescript/angular
I have a small utility that sends certain log events to a backend from an angular app. This is done by overriding the typescript console with an implementation that takes certain log messages and sends them to the applications backend where it is then logged.

This has been working just fine with angular 13, but I am now in the middle of upgrading to angular 14, where a problem has appeared.

export class RESTConsole implements globalThis.Console{
oldConsole: Console;
logService: BackendLoggingService;
consoleService: LoggingService;

```<code> constructor(oldConsole: Console, logService: BackendLoggingService, consoleService:
   LoggingService) {
   this.oldConsole = oldConsole;
   this.logService = logService;
   this.consoleService = consoleService;
 }

 getBackingConsole(): globalThis.Console{
   return this.oldConsole;
 }

 count(label?: string): void {
   this.oldConsole.count(label);
 }

 countReset(label?: string): void {
   this.oldConsole.countReset(label);
 }

 debug(...data: any[]): void {
   this.oldConsole.debug(...data);
   this.sendLogMessage(LogType.Debug, data);
 }

 trace(...data: any[]): void {
   this.oldConsole.trace(...data);
 }

 warn(...data: any[]): void {
   this.oldConsole.warn(...data);
   this.sendLogMessage(LogType.Warn, data);
 }

 ...All the rest of the functions are here too

 private sendLogMessage(type: LogType, data: any[]): void{
   ... Do stuff
 }
}
</code>```

When I upgrade to Angular 14 however, I get this error:

```<code>Error: node_modules/frontend-logging-travelcare/lib/services/logging-service/logging.service.d.ts:24:22 - error TS2420: Class 'RESTConsole' incorrectly implements interface 'Console'.
  Type 'RESTConsole' is missing the following properties from type 'Console': Console, profile, profileEnd
</code>```

I do not consider myself any sort of Angular expert, so I have no real idea what is going on but it SEEMS like the old version of the plugin used the Console in lib.dom.ts, which was the intended behavior, but the new Angular 14 version somehow ends up using the Console implementation in node_modules@types\node\ts4.8\console.d.ts and node_modules@types\node\ts4.8\console.d.ts.

This is a bit odd to me, as I was under the impression that Node was not something that ran in a browser, and I am building an Angular application.

The file I believe is causing the problem looks like this

```<code>    /**
 * The `console` module provides a simple debugging console that is similar to the
 * JavaScript console mechanism provided by web browsers.
 *
 * The module exports two specific components:
 *
 * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
 * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
 *
 * _**Warning**_: The global console object's methods are neither consistently
 * synchronous like the browser APIs they resemble, nor are they consistently
 * asynchronous like all other Node.js streams. See the `note on process I/O` for
 * more information.
 *
 * Example using the global `console`:
 *
 * ```js
 * console.log('hello world');
 * // Prints: hello world, to stdout
 * console.log('hello %s', 'world');
 * // Prints: hello world, to stdout
 * console.error(new Error('Whoops, something bad happened'));
 * // Prints error message and stack trace to stderr:
 * //   Error: Whoops, something bad happened
 * //     at [eval]:5:15
 * //     at Script.runInThisContext (node:vm:132:18)
 * //     at Object.runInThisContext (node:vm:309:38)
 * //     at node:internal/process/execution:77:19
 * //     at [eval]-wrapper:6:22
 * //     at evalScript (node:internal/process/execution:76:60)
 * //     at node:internal/main/eval_string:23:3
 *
 * const name = 'Will Robinson';
 * console.warn(`Danger ${name}! Danger!`);
 * // Prints: Danger Will Robinson! Danger!, to stderr
 * ```
 *
 * Example using the `Console` class:
 *
 * ```js
 * const out = getStreamSomehow();
 * const err = getStreamSomehow();
 * const myConsole = new console.Console(out, err);
 *
 * myConsole.log('hello world');
 * // Prints: hello world, to out
 * myConsole.log('hello %s', 'world');
 * // Prints: hello world, to out
 * myConsole.error(new Error('Whoops, something bad happened'));
 * // Prints: [Error: Whoops, something bad happened], to err
 *
 * const name = 'Will Robinson';
 * myConsole.warn(`Danger ${name}! Danger!`);
 * // Prints: Danger Will Robinson! Danger!, to err
 * ```
 * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/console.js)
 */
declare module 'console' {
    import console = require('node:console');
    export = console;
}
declare module 'node:console' {
    import { InspectOptions } from 'node:util';
    global {
        // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
        interface Console {
            Console: console.ConsoleConstructor;
            /**
             * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
             * writes a message and does not otherwise affect execution. The output always
             * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`.
             *
             * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
             *
             * ```js
             * console.assert(true, 'does nothing');
             *
             * console.assert(false, 'Whoops %s work', 'didn\'t');
             * // Assertion failed: Whoops didn't work
             *
             * console.assert();
             * // Assertion failed
             * ```
             * @since v0.1.101
             * @param value The value tested for being truthy.
             * @param message All arguments besides `value` are used as error message.
             */
            assert(value: any, message?: string, ...optionalParams: any[]): void;
            /**
             * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
             * TTY. When `stdout` is not a TTY, this method does nothing.
             *
             * The specific operation of `console.clear()` can vary across operating systems
             * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the
             * current terminal viewport for the Node.js
             * binary.
             * @since v8.3.0
             */
            clear(): void;
            /**
             * Maintains an internal counter specific to `label` and outputs to `stdout` the
             * number of times `console.count()` has been called with the given `label`.
             *
             * ```js
             * > console.count()
             * default: 1
             * undefined
             * > console.count('default')
             * default: 2
             * undefined
             * > console.count('abc')
             * abc: 1
             * undefined
             * > console.count('xyz')
             * xyz: 1
             * undefined
             * > console.count('abc')
             * abc: 2
             * undefined
             * > console.count()
             * default: 3
             * undefined
             * >
             * ```
             * @since v8.3.0
             * @param label The display label for the counter.
             */
            count(label?: string): void;
            /**
             * Resets the internal counter specific to `label`.
             *
             * ```js
             * > console.count('abc');
             * abc: 1
             * undefined
             * > console.countReset('abc');
             * undefined
             * > console.count('abc');
             * abc: 1
             * undefined
             * >
             * ```
             * @since v8.3.0
             * @param label The display label for the counter.
             */
            countReset(label?: string): void;
            /**
             * The `console.debug()` function is an alias for {@link log}.
             * @since v8.0.0
             */
            debug(message?: any, ...optionalParams: any[]): void;
            /**
             * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`.
             * This function bypasses any custom `inspect()` function defined on `obj`.
             * @since v0.1.101
             */
            dir(obj: any, options?: InspectOptions): void;
            /**
             * This method calls `console.log()` passing it the arguments received.
             * This method does not produce any XML formatting.
             * @since v8.0.0
             */
            dirxml(...data: any[]): void;
            /**
             * Prints to `stderr` with newline. Multiple arguments can be passed, with the
             * first used as the primary message and all additional used as substitution
             * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
             *
             * ```js
             * const code = 5;
             * console.error('error #%d', code);
             * // Prints: error #5, to stderr
             * console.error('error', code);
             * // Prints: error 5, to stderr
             * ```
             *
             * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string
             * values are concatenated. See `util.format()` for more information.
             * @since v0.1.100
             */
            error(message?: any, ...optionalParams: any[]): void;
            /**
             * Increases indentation of subsequent lines by spaces for `groupIndentation`length.
             *
             * If one or more `label`s are provided, those are printed first without the
             * additional indentation.
             * @since v8.5.0
             */
            group(...label: any[]): void;
            /**
             * An alias for {@link group}.
             * @since v8.5.0
             */
            groupCollapsed(...label: any[]): void;
            /**
             * Decreases indentation of subsequent lines by spaces for `groupIndentation`length.
             * @since v8.5.0
             */
            groupEnd(): void;
            /**
             * The `console.info()` function is an alias for {@link log}.
             * @since v0.1.100
             */
            info(message?: any, ...optionalParams: any[]): void;
            /**
             * Prints to `stdout` with newline. Multiple arguments can be passed, with the
             * first used as the primary message and all additional used as substitution
             * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
             *
             * ```js
             * const count = 5;
             * console.log('count: %d', count);
             * // Prints: count: 5, to stdout
             * console.log('count:', count);
             * // Prints: count: 5, to stdout
             * ```
             *
             * See `util.format()` for more information.
             * @since v0.1.100
             */
            log(message?: any, ...optionalParams: any[]): void;
            /**
             * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just
             * logging the argument if it can’t be parsed as tabular.
             *
             * ```js
             * // These can't be parsed as tabular data
             * console.table(Symbol());
             * // Symbol()
             *
             * console.table(undefined);
             * // undefined
             *
             * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
             * // ┌─────────┬─────┬─────┐
             * // │ (index) │  a  │  b  │
             * // ├─────────┼─────┼─────┤
             * // │    0    │  1  │ 'Y' │
             * // │    1    │ 'Z' │  2  │
             * // └─────────┴─────┴─────┘
             *
             * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
             * // ┌─────────┬─────┐
             * // │ (index) │  a  │
             * // ├─────────┼─────┤
             * // │    0    │  1  │
             * // │    1    │ 'Z' │
             * // └─────────┴─────┘
             * ```
             * @since v10.0.0
             * @param properties Alternate properties for constructing the table.
             */
            table(tabularData: any, properties?: ReadonlyArray<string>): void;
            /**
             * Starts a timer that can be used to compute the duration of an operation. Timers
             * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in
             * suitable time units to `stdout`. For example, if the elapsed
             * time is 3869ms, `console.timeEnd()` displays "3.869s".
             * @since v0.1.104
             */
            time(label?: string): void;
            /**
             * Stops a timer that was previously started by calling {@link time} and
             * prints the result to `stdout`:
             *
             * ```js
             * console.time('100-elements');
             * for (let i = 0; i < 100; i++) {}
             * console.timeEnd('100-elements');
             * // prints 100-elements: 225.438ms
             * ```
             * @since v0.1.104
             */
            timeEnd(label?: string): void;
            /**
             * For a timer that was previously started by calling {@link time}, prints
             * the elapsed time and other `data` arguments to `stdout`:
             *
             * ```js
             * console.time('process');
             * const value = expensiveProcess1(); // Returns 42
             * console.timeLog('process', value);
             * // Prints "process: 365.227ms 42".
             * doExpensiveProcess2(value);
             * console.timeEnd('process');
             * ```
             * @since v10.7.0
             */
            timeLog(label?: string, ...data: any[]): void;
            /**
             * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code.
             *
             * ```js
             * console.trace('Show me');
             * // Prints: (stack trace will vary based on where trace is called)
             * //  Trace: Show me
             * //    at repl:2:9
             * //    at REPLServer.defaultEval (repl.js:248:27)
             * //    at bound (domain.js:287:14)
             * //    at REPLServer.runBound [as eval] (domain.js:300:12)
             * //    at REPLServer.<anonymous> (repl.js:412:12)
             * //    at emitOne (events.js:82:20)
             * //    at REPLServer.emit (events.js:169:7)
             * //    at REPLServer.Interface._onLine (readline.js:210:10)
             * //    at REPLServer.Interface._line (readline.js:549:8)
             * //    at REPLServer.Interface._ttyWrite (readline.js:826:14)
             * ```
             * @since v0.1.104
             */
            trace(message?: any, ...optionalParams: any[]): void;
            /**
             * The `console.warn()` function is an alias for {@link error}.
             * @since v0.1.100
             */
            warn(message?: any, ...optionalParams: any[]): void;
            // --- Inspector mode only ---
            /**
             * This method does not display anything unless used in the inspector.
             *  Starts a JavaScript CPU profile with an optional label.
             */
            profile(label?: string): void;
            /**
             * This method does not display anything unless used in the inspector.
             *  Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector.
             */
            profileEnd(label?: string): void;
            /**
             * This method does not display anything unless used in the inspector.
             *  Adds an event with the label `label` to the Timeline panel of the inspector.
             */
            timeStamp(label?: string): void;
        }
        /**
         * The `console` module provides a simple debugging console that is similar to the
         * JavaScript console mechanism provided by web browsers.
         *
         * The module exports two specific components:
         *
         * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
         * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
         *
         * _**Warning**_: The global console object's methods are neither consistently
         * synchronous like the browser APIs they resemble, nor are they consistently
         * asynchronous like all other Node.js streams. See the `note on process I/O` for
         * more information.
         *
         * Example using the global `console`:
         *
         * ```js
         * console.log('hello world');
         * // Prints: hello world, to stdout
         * console.log('hello %s', 'world');
         * // Prints: hello world, to stdout
         * console.error(new Error('Whoops, something bad happened'));
         * // Prints error message and stack trace to stderr:
         * //   Error: Whoops, something bad happened
         * //     at [eval]:5:15
         * //     at Script.runInThisContext (node:vm:132:18)
         * //     at Object.runInThisContext (node:vm:309:38)
         * //     at node:internal/process/execution:77:19
         * //     at [eval]-wrapper:6:22
         * //     at evalScript (node:internal/process/execution:76:60)
         * //     at node:internal/main/eval_string:23:3
         *
         * const name = 'Will Robinson';
         * console.warn(`Danger ${name}! Danger!`);
         * // Prints: Danger Will Robinson! Danger!, to stderr
         * ```
         *
         * Example using the `Console` class:
         *
         * ```js
         * const out = getStreamSomehow();
         * const err = getStreamSomehow();
         * const myConsole = new console.Console(out, err);
         *
         * myConsole.log('hello world');
         * // Prints: hello world, to out
         * myConsole.log('hello %s', 'world');
         * // Prints: hello world, to out
         * myConsole.error(new Error('Whoops, something bad happened'));
         * // Prints: [Error: Whoops, something bad happened], to err
         *
         * const name = 'Will Robinson';
         * myConsole.warn(`Danger ${name}! Danger!`);
         * // Prints: Danger Will Robinson! Danger!, to err
         * ```
         * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js)
         */
        namespace console {
            interface ConsoleConstructorOptions {
                stdout: NodeJS.WritableStream;
                stderr?: NodeJS.WritableStream | undefined;
                ignoreErrors?: boolean | undefined;
                colorMode?: boolean | 'auto' | undefined;
                inspectOptions?: InspectOptions | undefined;
                /**
                 * Set group indentation
                 * @default 2
                 */
                groupIndentation?: number | undefined;
            }
            interface ConsoleConstructor {
                prototype: Console;
                new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console;
                new (options: ConsoleConstructorOptions): Console;
            }
        }
        var console: Console;
    }
    export = globalThis.console;
}
</code>```

Like I said, alot of what typescript does is black magic to me, but it very much looks like this file overwrites the global console interface which I then try to extend.
I am not sure if this file is even supposed to be in my codebase or it is some rouge dependency that has gobbled in some node code, or if I am supposed to use that interface now. In that case, I am unsure of how to extend it.

Thank you for your help.

Body:
I have a small utility that sends certain log events to a backend from an angular app. This is done by overriding the typescript console with an implementation that takes certain log messages and sends them to the applications backend where it is then logged.

This has been working just fine with angular 13, but I am now in the middle of upgrading to angular 14, where a problem has appeared.

export class RESTConsole implements globalThis.Console{
oldConsole: Console;
logService: BackendLoggingService;
consoleService: LoggingService;

 constructor(oldConsole: Console, logService: BackendLoggingService, consoleService:
   LoggingService) {
   this.oldConsole = oldConsole;
   this.logService = logService;
   this.consoleService = consoleService;
 }

 getBackingConsole(): globalThis.Console{
   return this.oldConsole;
 }

 count(label?: string): void {
   this.oldConsole.count(label);
 }

 countReset(label?: string): void {
   this.oldConsole.countReset(label);
 }

 debug(...data: any[]): void {
   this.oldConsole.debug(...data);
   this.sendLogMessage(LogType.Debug, data);
 }

 trace(...data: any[]): void {
   this.oldConsole.trace(...data);
 }

 warn(...data: any[]): void {
   this.oldConsole.warn(...data);
   this.sendLogMessage(LogType.Warn, data);
 }

 ...All the rest of the functions are here too

 private sendLogMessage(type: LogType, data: any[]): void{
   ... Do stuff
 }
}

When I upgrade to Angular 14 however, I get this error:

Error: node_modules/frontend-logging-travelcare/lib/services/logging-service/logging.service.d.ts:24:22 - error TS2420: Class 'RESTConsole' incorrectly implements interface 'Console'.
  Type 'RESTConsole' is missing the following properties from type 'Console': Console, profile, profileEnd

I do not consider myself any sort of Angular expert, so I have no real idea what is going on but it SEEMS like the old version of the plugin used the Console in lib.dom.ts, which was the intended behavior, but the new Angular 14 version somehow ends up using the Console implementation in node_modules@types\node\ts4.8\console.d.ts and node_modules@types\node\ts4.8\console.d.ts.

This is a bit odd to me, as I was under the impression that Node was not something that ran in a browser, and I am building an Angular application.

The file I believe is causing the problem looks like this

    /**
 * The `console` module provides a simple debugging console that is similar to the
 * JavaScript console mechanism provided by web browsers.
 *
 * The module exports two specific components:
 *
 * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
 * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
 *
 * _**Warning**_: The global console object's methods are neither consistently
 * synchronous like the browser APIs they resemble, nor are they consistently
 * asynchronous like all other Node.js streams. See the `note on process I/O` for
 * more information.
 *
 * Example using the global `console`:
 *
 * ```js
 * console.log('hello world');
 * // Prints: hello world, to stdout
 * console.log('hello %s', 'world');
 * // Prints: hello world, to stdout
 * console.error(new Error('Whoops, something bad happened'));
 * // Prints error message and stack trace to stderr:
 * //   Error: Whoops, something bad happened
 * //     at [eval]:5:15
 * //     at Script.runInThisContext (node:vm:132:18)
 * //     at Object.runInThisContext (node:vm:309:38)
 * //     at node:internal/process/execution:77:19
 * //     at [eval]-wrapper:6:22
 * //     at evalScript (node:internal/process/execution:76:60)
 * //     at node:internal/main/eval_string:23:3
 *
 * const name = 'Will Robinson';
 * console.warn(`Danger ${name}! Danger!`);
 * // Prints: Danger Will Robinson! Danger!, to stderr
 * ```
 *
 * Example using the `Console` class:
 *
 * ```js
 * const out = getStreamSomehow();
 * const err = getStreamSomehow();
 * const myConsole = new console.Console(out, err);
 *
 * myConsole.log('hello world');
 * // Prints: hello world, to out
 * myConsole.log('hello %s', 'world');
 * // Prints: hello world, to out
 * myConsole.error(new Error('Whoops, something bad happened'));
 * // Prints: [Error: Whoops, something bad happened], to err
 *
 * const name = 'Will Robinson';
 * myConsole.warn(`Danger ${name}! Danger!`);
 * // Prints: Danger Will Robinson! Danger!, to err
 * ```
 * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/console.js)
 */
declare module 'console' {
    import console = require('node:console');
    export = console;
}
declare module 'node:console' {
    import { InspectOptions } from 'node:util';
    global {
        // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
        interface Console {
            Console: console.ConsoleConstructor;
            /**
             * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
             * writes a message and does not otherwise affect execution. The output always
             * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`.
             *
             * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
             *
             * ```js
             * console.assert(true, 'does nothing');
             *
             * console.assert(false, 'Whoops %s work', 'didn\'t');
             * // Assertion failed: Whoops didn't work
             *
             * console.assert();
             * // Assertion failed
             * ```
             * @since v0.1.101
             * @param value The value tested for being truthy.
             * @param message All arguments besides `value` are used as error message.
             */
            assert(value: any, message?: string, ...optionalParams: any[]): void;
            /**
             * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
             * TTY. When `stdout` is not a TTY, this method does nothing.
             *
             * The specific operation of `console.clear()` can vary across operating systems
             * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the
             * current terminal viewport for the Node.js
             * binary.
             * @since v8.3.0
             */
            clear(): void;
            /**
             * Maintains an internal counter specific to `label` and outputs to `stdout` the
             * number of times `console.count()` has been called with the given `label`.
             *
             * ```js
             * > console.count()
             * default: 1
             * undefined
             * > console.count('default')
             * default: 2
             * undefined
             * > console.count('abc')
             * abc: 1
             * undefined
             * > console.count('xyz')
             * xyz: 1
             * undefined
             * > console.count('abc')
             * abc: 2
             * undefined
             * > console.count()
             * default: 3
             * undefined
             * >
             * ```
             * @since v8.3.0
             * @param label The display label for the counter.
             */
            count(label?: string): void;
            /**
             * Resets the internal counter specific to `label`.
             *
             * ```js
             * > console.count('abc');
             * abc: 1
             * undefined
             * > console.countReset('abc');
             * undefined
             * > console.count('abc');
             * abc: 1
             * undefined
             * >
             * ```
             * @since v8.3.0
             * @param label The display label for the counter.
             */
            countReset(label?: string): void;
            /**
             * The `console.debug()` function is an alias for {@link log}.
             * @since v8.0.0
             */
            debug(message?: any, ...optionalParams: any[]): void;
            /**
             * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`.
             * This function bypasses any custom `inspect()` function defined on `obj`.
             * @since v0.1.101
             */
            dir(obj: any, options?: InspectOptions): void;
            /**
             * This method calls `console.log()` passing it the arguments received.
             * This method does not produce any XML formatting.
             * @since v8.0.0
             */
            dirxml(...data: any[]): void;
            /**
             * Prints to `stderr` with newline. Multiple arguments can be passed, with the
             * first used as the primary message and all additional used as substitution
             * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
             *
             * ```js
             * const code = 5;
             * console.error('error #%d', code);
             * // Prints: error #5, to stderr
             * console.error('error', code);
             * // Prints: error 5, to stderr
             * ```
             *
             * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string
             * values are concatenated. See `util.format()` for more information.
             * @since v0.1.100
             */
            error(message?: any, ...optionalParams: any[]): void;
            /**
             * Increases indentation of subsequent lines by spaces for `groupIndentation`length.
             *
             * If one or more `label`s are provided, those are printed first without the
             * additional indentation.
             * @since v8.5.0
             */
            group(...label: any[]): void;
            /**
             * An alias for {@link group}.
             * @since v8.5.0
             */
            groupCollapsed(...label: any[]): void;
            /**
             * Decreases indentation of subsequent lines by spaces for `groupIndentation`length.
             * @since v8.5.0
             */
            groupEnd(): void;
            /**
             * The `console.info()` function is an alias for {@link log}.
             * @since v0.1.100
             */
            info(message?: any, ...optionalParams: any[]): void;
            /**
             * Prints to `stdout` with newline. Multiple arguments can be passed, with the
             * first used as the primary message and all additional used as substitution
             * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`).
             *
             * ```js
             * const count = 5;
             * console.log('count: %d', count);
             * // Prints: count: 5, to stdout
             * console.log('count:', count);
             * // Prints: count: 5, to stdout
             * ```
             *
             * See `util.format()` for more information.
             * @since v0.1.100
             */
            log(message?: any, ...optionalParams: any[]): void;
            /**
             * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just
             * logging the argument if it can’t be parsed as tabular.
             *
             * ```js
             * // These can't be parsed as tabular data
             * console.table(Symbol());
             * // Symbol()
             *
             * console.table(undefined);
             * // undefined
             *
             * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
             * // ┌─────────┬─────┬─────┐
             * // │ (index) │  a  │  b  │
             * // ├─────────┼─────┼─────┤
             * // │    0    │  1  │ 'Y' │
             * // │    1    │ 'Z' │  2  │
             * // └─────────┴─────┴─────┘
             *
             * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
             * // ┌─────────┬─────┐
             * // │ (index) │  a  │
             * // ├─────────┼─────┤
             * // │    0    │  1  │
             * // │    1    │ 'Z' │
             * // └─────────┴─────┘
             * ```
             * @since v10.0.0
             * @param properties Alternate properties for constructing the table.
             */
            table(tabularData: any, properties?: ReadonlyArray<string>): void;
            /**
             * Starts a timer that can be used to compute the duration of an operation. Timers
             * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in
             * suitable time units to `stdout`. For example, if the elapsed
             * time is 3869ms, `console.timeEnd()` displays "3.869s".
             * @since v0.1.104
             */
            time(label?: string): void;
            /**
             * Stops a timer that was previously started by calling {@link time} and
             * prints the result to `stdout`:
             *
             * ```js
             * console.time('100-elements');
             * for (let i = 0; i < 100; i++) {}
             * console.timeEnd('100-elements');
             * // prints 100-elements: 225.438ms
             * ```
             * @since v0.1.104
             */
            timeEnd(label?: string): void;
            /**
             * For a timer that was previously started by calling {@link time}, prints
             * the elapsed time and other `data` arguments to `stdout`:
             *
             * ```js
             * console.time('process');
             * const value = expensiveProcess1(); // Returns 42
             * console.timeLog('process', value);
             * // Prints "process: 365.227ms 42".
             * doExpensiveProcess2(value);
             * console.timeEnd('process');
             * ```
             * @since v10.7.0
             */
            timeLog(label?: string, ...data: any[]): void;
            /**
             * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code.
             *
             * ```js
             * console.trace('Show me');
             * // Prints: (stack trace will vary based on where trace is called)
             * //  Trace: Show me
             * //    at repl:2:9
             * //    at REPLServer.defaultEval (repl.js:248:27)
             * //    at bound (domain.js:287:14)
             * //    at REPLServer.runBound [as eval] (domain.js:300:12)
             * //    at REPLServer.<anonymous> (repl.js:412:12)
             * //    at emitOne (events.js:82:20)
             * //    at REPLServer.emit (events.js:169:7)
             * //    at REPLServer.Interface._onLine (readline.js:210:10)
             * //    at REPLServer.Interface._line (readline.js:549:8)
             * //    at REPLServer.Interface._ttyWrite (readline.js:826:14)
             * ```
             * @since v0.1.104
             */
            trace(message?: any, ...optionalParams: any[]): void;
            /**
             * The `console.warn()` function is an alias for {@link error}.
             * @since v0.1.100
             */
            warn(message?: any, ...optionalParams: any[]): void;
            // --- Inspector mode only ---
            /**
             * This method does not display anything unless used in the inspector.
             *  Starts a JavaScript CPU profile with an optional label.
             */
            profile(label?: string): void;
            /**
             * This method does not display anything unless used in the inspector.
             *  Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector.
             */
            profileEnd(label?: string): void;
            /**
             * This method does not display anything unless used in the inspector.
             *  Adds an event with the label `label` to the Timeline panel of the inspector.
             */
            timeStamp(label?: string): void;
        }
        /**
         * The `console` module provides a simple debugging console that is similar to the
         * JavaScript console mechanism provided by web browsers.
         *
         * The module exports two specific components:
         *
         * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream.
         * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`.
         *
         * _**Warning**_: The global console object's methods are neither consistently
         * synchronous like the browser APIs they resemble, nor are they consistently
         * asynchronous like all other Node.js streams. See the `note on process I/O` for
         * more information.
         *
         * Example using the global `console`:
         *
         * ```js
         * console.log('hello world');
         * // Prints: hello world, to stdout
         * console.log('hello %s', 'world');
         * // Prints: hello world, to stdout
         * console.error(new Error('Whoops, something bad happened'));
         * // Prints error message and stack trace to stderr:
         * //   Error: Whoops, something bad happened
         * //     at [eval]:5:15
         * //     at Script.runInThisContext (node:vm:132:18)
         * //     at Object.runInThisContext (node:vm:309:38)
         * //     at node:internal/process/execution:77:19
         * //     at [eval]-wrapper:6:22
         * //     at evalScript (node:internal/process/execution:76:60)
         * //     at node:internal/main/eval_string:23:3
         *
         * const name = 'Will Robinson';
         * console.warn(`Danger ${name}! Danger!`);
         * // Prints: Danger Will Robinson! Danger!, to stderr
         * ```
         *
         * Example using the `Console` class:
         *
         * ```js
         * const out = getStreamSomehow();
         * const err = getStreamSomehow();
         * const myConsole = new console.Console(out, err);
         *
         * myConsole.log('hello world');
         * // Prints: hello world, to out
         * myConsole.log('hello %s', 'world');
         * // Prints: hello world, to out
         * myConsole.error(new Error('Whoops, something bad happened'));
         * // Prints: [Error: Whoops, something bad happened], to err
         *
         * const name = 'Will Robinson';
         * myConsole.warn(`Danger ${name}! Danger!`);
         * // Prints: Danger Will Robinson! Danger!, to err
         * ```
         * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js)
         */
        namespace console {
            interface ConsoleConstructorOptions {
                stdout: NodeJS.WritableStream;
                stderr?: NodeJS.WritableStream | undefined;
                ignoreErrors?: boolean | undefined;
                colorMode?: boolean | 'auto' | undefined;
                inspectOptions?: InspectOptions | undefined;
                /**
                 * Set group indentation
                 * @default 2
                 */
                groupIndentation?: number | undefined;
            }
            interface ConsoleConstructor {
                prototype: Console;
                new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console;
                new (options: ConsoleConstructorOptions): Console;
            }
        }
        var console: Console;
    }
    export = globalThis.console;
}

Like I said, alot of what typescript does is black magic to me, but it very much looks like this file overwrites the global console interface which I then try to extend.
I am not sure if this file is even supposed to be in my codebase or it is some rouge dependency that has gobbled in some node code, or if I am supposed to use that interface now. In that case, I am unsure of how to extend it.

Thank you for your help.


来源: stackexchange

问:
how to specify an Rstan model when some combinations of variables are impossible?
I'm trying to create a single Bayesian model which allows me to measure the effect of gender and ethnicity on promotion and retention in promotion rates.  There is a very strong relationship between promotion retention - in that nobody who leaves can be promoted.  How should I specify this in an RStan model?

Here's my data generator for a simplified example:

```<code>logit2prob <- function(logit){
  odds <- exp(logit)
  prob <- odds / (1 + odds)
  return(prob)
}

# generate some data -----------------------------------------------------------

n <- 100000

data <- tibble(
  id = 1:n,
  gender = sample(c('m', 'f'), n, TRUE),
  eth = sample(c('wb', 'em'), n, TRUE)
) %>%

  mutate(leave_logit = -3
         + ifelse(eth == 'em', 0.5, 0)
         + rnorm(n, 0, 0.1),

         leave_prob = logit2prob(leave_logit),

         promote_logit = -3
          + ifelse(gender == 'm', 0.5, 0)
         + rnorm(n, 0, 0.1),

         promote_prob = logit2prob(promote_logit),

         leave_flag = rbernoulli(n, p = leave_prob),

         promote_flag = ifelse(leave_flag == 1,
                               0,
                               rbernoulli(n, p = promote_prob))
         )

</code>```

You can see in this example that ethnicity only directly effects likelihood of leaving, but as individuals who have left cannot be promoted, a naive regression on promotion would find an effect from ethnicity as well as gender.

Ideally, I'd like to create a single R stan model which has both a model which predicts retention and a model which predicts promotion, because I want to disentangle these two effects.  I want to tell Stan that there is no possibility of an individual being promoted if they have left, and can't figure out how.  Is this just a completely wrongheaded analytical approach?

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a single Bayesian model which allows me to measure the effect of gender and ethnicity on promotion and retention in promotion rates.  There is a very strong relationship between promotion retention - in that nobody who leaves can be promoted.  How should I specify this in an RStan model?

Here's my data generator for a simplified example:

logit2prob <- function(logit){
  odds <- exp(logit)
  prob <- odds / (1 + odds)
  return(prob)
}

# generate some data -----------------------------------------------------------

n <- 100000

data <- tibble(
  id = 1:n,
  gender = sample(c('m', 'f'), n, TRUE),
  eth = sample(c('wb', 'em'), n, TRUE)
) %>%

  mutate(leave_logit = -3
         + ifelse(eth == 'em', 0.5, 0)
         + rnorm(n, 0, 0.1),

         leave_prob = logit2prob(leave_logit),

         promote_logit = -3
          + ifelse(gender == 'm', 0.5, 0)
         + rnorm(n, 0, 0.1),

         promote_prob = logit2prob(promote_logit),

         leave_flag = rbernoulli(n, p = leave_prob),

         promote_flag = ifelse(leave_flag == 1,
                               0,
                               rbernoulli(n, p = promote_prob))
         )

You can see in this example that ethnicity only directly effects likelihood of leaving, but as individuals who have left cannot be promoted, a naive regression on promotion would find an effect from ethnicity as well as gender.

Ideally, I'd like to create a single R stan model which has both a model which predicts retention and a model which predicts promotion, because I want to disentangle these two effects.  I want to tell Stan that there is no possibility of an individual being promoted if they have left, and can't figure out how.  Is this just a completely wrongheaded analytical approach?


问:
How to insert a subList into solr with Spring Data Solr
I have following data:

```<code>"orders":{
      "placed_orders_count":2,
      "0":{
         "order_id":"000000001",
         "order_date":"2019-03-27 14:25:03"
      },
      "1":{
         "order_id":"000000002",
         "order_date":"2019-03-27 14:25:03"
      }
   }
</code>```

I want to insert all this data into Solr. I have tried:

```<code>String customerFeedJson = new Gson().toJson(customerFeedsolr.getOrders());
String solrUrl = solrServerUrl.concat(customerFeedPrefix).concat(Constants.HYPHEN).concat(String.valueOf(siteID))
                        .concat(Constants.SOLR_URL_QUERIES);
HttpEntity<String> requestEntity = new HttpEntity<String>(Arrays.asList(customerFeedJson).toString());
restTemplate.exchange(solrUrl, HttpMethod.POST, requestEntity, String.class);
</code>```

But on Solr, I am only able to index "placed_orders_count":2.
I have indexed orders field as:

```<code>public class CustomerFeedSolr {

    @Indexed("orders_*")
    @Field(child = true)
    private Map<String, ?> orders;
//Getters and Setters
}
</code>```

Expectations:

```<code>"placed_orders_count":[2.0],
 "0":[
      "order_id":"000000001",
      "order_date":"2019-03-27 14:25:03"
  ],
  "1":[
      "order_id":"000000002",
      "order_date":"2019-03-27 14:25:03"
  ]
</code>```

Actual

```<code>"placed_orders_count":[2.0]
</code>```

Body:
I have following data:

"orders":{
      "placed_orders_count":2,
      "0":{
         "order_id":"000000001",
         "order_date":"2019-03-27 14:25:03"
      },
      "1":{
         "order_id":"000000002",
         "order_date":"2019-03-27 14:25:03"
      }
   }

I want to insert all this data into Solr. I have tried:

String customerFeedJson = new Gson().toJson(customerFeedsolr.getOrders());
String solrUrl = solrServerUrl.concat(customerFeedPrefix).concat(Constants.HYPHEN).concat(String.valueOf(siteID))
                        .concat(Constants.SOLR_URL_QUERIES);
HttpEntity<String> requestEntity = new HttpEntity<String>(Arrays.asList(customerFeedJson).toString());
restTemplate.exchange(solrUrl, HttpMethod.POST, requestEntity, String.class);

But on Solr, I am only able to index "placed_orders_count":2.
I have indexed orders field as:

public class CustomerFeedSolr {

    @Indexed("orders_*")
    @Field(child = true)
    private Map<String, ?> orders;
//Getters and Setters
}

Expectations:

"placed_orders_count":[2.0],
 "0":[
      "order_id":"000000001",
      "order_date":"2019-03-27 14:25:03"
  ],
  "1":[
      "order_id":"000000002",
      "order_date":"2019-03-27 14:25:03"
  ]

Actual

"placed_orders_count":[2.0]


问:
Explanation of the detailed android intents required
I'm not an expert with android development, and I'm looking for an explanation on what these two intents do please from the system logs on my google pixel pro 7.

```<code>  * com.google.android.as: 3 items
    #0: PendingIntentRecord{648788e com.google.android.as startActivity}
      uid=10139 packageName=com.google.android.as featureId=null type=startActivity flags=0x4000000
      requestIntent=act=android.intent.action.DIAL dat=tel:919903517032 cmp=com.google.android.dialer/com.android.dialer.main.impl.MainActivity (has extras)
    #1: PendingIntentRecord{d6ac8af com.google.android.as startActivity}
      uid=10139 packageName=com.google.android.as featureId=null type=startActivity flags=0x4000000
      requestIntent=act=android.intent.action.SENDTO dat=smsto:919903517032 cmp=com.google.android.apps.messaging/.ui.conversation.LaunchConversationActivity (has extras)

</code>```

I have also discovered an app named project-919903517032 connected to my google account.

Kind Regards

Tom

Checking system logs I've noticed these intents, and would like an explanation of their function.

Body:
I'm not an expert with android development, and I'm looking for an explanation on what these two intents do please from the system logs on my google pixel pro 7.

  * com.google.android.as: 3 items
    #0: PendingIntentRecord{648788e com.google.android.as startActivity}
      uid=10139 packageName=com.google.android.as featureId=null type=startActivity flags=0x4000000
      requestIntent=act=android.intent.action.DIAL dat=tel:919903517032 cmp=com.google.android.dialer/com.android.dialer.main.impl.MainActivity (has extras)
    #1: PendingIntentRecord{d6ac8af com.google.android.as startActivity}
      uid=10139 packageName=com.google.android.as featureId=null type=startActivity flags=0x4000000
      requestIntent=act=android.intent.action.SENDTO dat=smsto:919903517032 cmp=com.google.android.apps.messaging/.ui.conversation.LaunchConversationActivity (has extras)

I have also discovered an app named project-919903517032 connected to my google account.

Kind Regards

Tom

Checking system logs I've noticed these intents, and would like an explanation of their function.


问:
VS Code trust workplace sends me to someone's website
when I click trust on some extensions, every time I open vs code it launches browser with someone's page or follow me thing. if I don't trust, I have problems anyway so is there any way to use extensions without annoying browser pop up thing?

I've tried to mistrust but then I cant use extension I need.


问:
How to handle any property type/value within an expression holder without boxing in C#
Lets assume I have an employee class as follow:

```<code>var employee = new Employee
{
    FirstName = "John",
    LastName = "Smith",
    DateOfBirth = DateTime.Now
};
</code>```

To define an expression for a given property, I wrote something like this:

```<code>Expression<Func<Employee, string>> expression = e => e.FirstName;
</code>```

This is fine for string type but if I want generalize this operation (extracting specified property value through an extension method). I have defined a general expression holder and then process it at given time. As a result, I have to define this expression as follow:

```<code>Expression<Func<Employee, object>> expressionHolder { get; set; }
</code>```

Because I may target non-reference type property (like DateTime). Is it possible to avoid this boxing for this holder?

Body:
Lets assume I have an employee class as follow:

var employee = new Employee
{
    FirstName = "John",
    LastName = "Smith",
    DateOfBirth = DateTime.Now
};

To define an expression for a given property, I wrote something like this:

Expression<Func<Employee, string>> expression = e => e.FirstName;

This is fine for string type but if I want generalize this operation (extracting specified property value through an extension method). I have defined a general expression holder and then process it at given time. As a result, I have to define this expression as follow:

Expression<Func<Employee, object>> expressionHolder { get; set; }

Because I may target non-reference type property (like DateTime). Is it possible to avoid this boxing for this holder?


问:
OpenCV C++ DescriptorMatcher::knnMatch - significant performance difference on Windows (MSVC) vs Linux (CLANG)
I am performing feature matching process using OpenCV - 4.5.3 (in C++).
I ran into an issue that performance of Matching on Windows is even 30 times slower than on Linux (Ubuntu 22.04 on WSL 2 to be precise) and depends on the number of images used for the process (more on that later).

The code which is the source of the problem looks more or less like this:

```<code>void matchDescriptorsPair(cv::Mat *queryDescriptors, cv::Ptr<cv::DescriptorMatcher> trainedMatcher)
{
    constexpr int N_NEAREST_NEIGHBORS = 2;

    vector<vector<cv::DMatch>> matches;
    matches.reserve(queryDescriptors->rows);

    trainedMatcher->knnMatch(*queryDescriptors, matches, N_NEAREST_NEIGHBORS);
    (...)
}

</code>```

To benchmark the problem, I used a dataset containing up to 200 images with 18 MP resolution. I batched them into groups of {5, 20, 50, 75, 100, 125, 150, 175, 200} images and executed the same code, on Windows 10 and Ubuntu 22.04 (WSL2).

The results can be seen on the chart below. You can see there that matching of single pairs on Linux always lasts around 2 seconds, when on Windows 10 execution time depends on the number of images in the dataset.

What can be a reason for such significant performance difference?

[Notes]

Feature Extraction is run before, and all the features are stored in RAM (a lot of data but there is lots of RAM available inside machine)

Matching is run in parallel (36 threads in this example - changing number of threads for Windows did not improve matching time)

Same behavior on both Windows 10 and 11

[EDIT 1]
For Windows code is compiled using MSVC. Linux uses CLANG. I will try to build on Windows using CLANG and give you update.

Body:
I am performing feature matching process using OpenCV - 4.5.3 (in C++).
I ran into an issue that performance of Matching on Windows is even 30 times slower than on Linux (Ubuntu 22.04 on WSL 2 to be precise) and depends on the number of images used for the process (more on that later).

The code which is the source of the problem looks more or less like this:

void matchDescriptorsPair(cv::Mat *queryDescriptors, cv::Ptr<cv::DescriptorMatcher> trainedMatcher)
{
    constexpr int N_NEAREST_NEIGHBORS = 2;

    vector<vector<cv::DMatch>> matches;
    matches.reserve(queryDescriptors->rows);

    trainedMatcher->knnMatch(*queryDescriptors, matches, N_NEAREST_NEIGHBORS);
    (...)
}

To benchmark the problem, I used a dataset containing up to 200 images with 18 MP resolution. I batched them into groups of {5, 20, 50, 75, 100, 125, 150, 175, 200} images and executed the same code, on Windows 10 and Ubuntu 22.04 (WSL2).

The results can be seen on the chart below. You can see there that matching of single pairs on Linux always lasts around 2 seconds, when on Windows 10 execution time depends on the number of images in the dataset.

What can be a reason for such significant performance difference?

[Notes]

Feature Extraction is run before, and all the features are stored in RAM (a lot of data but there is lots of RAM available inside machine)

Matching is run in parallel (36 threads in this example - changing number of threads for Windows did not improve matching time)

Same behavior on both Windows 10 and 11

[EDIT 1]
For Windows code is compiled using MSVC. Linux uses CLANG. I will try to build on Windows using CLANG and give you update.


问:
Custom prediction method for inference phase of a LSTM stacked layers model
I do some multivariate time series forecasting to design a one-step ahead predictor using Keras API and a stacked Long Short-Term Memory (LSTM) layers, so I'm tune and fit the following sequential model:

```<code>n_steps_in = 1
n_features = 3
model = Sequential()
model.add(LSTM(15, activation='tanh', return_sequences=True, input_shape=(n_steps_in,n_features)))
model.add(LSTM(20, activation='relu'))
model.add(Dense(n_features))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train_lstm, y_train_lstm, epochs=100, validation_data = (X_test_lstm, y_test_lstm),
            verbose=1)
</code>```

After that, In inference phase, I would like to use a my custom predict method instead of using the buit-in predict Keras method. To do so, fistly I have extract the weights and bias form the fitted model, and create a method that predict only one single time step i.e. I give to the fitted model an input sample with shape (1,1,3) and then it outputs a predicted vector with shape (1,3). This method is little similar than doing a feedforward pass.

```<code>def model_predict_LSTM(model, input_pred, c_tm1, h_tm1):

    # for layer in model.layers:
    #     if "LSTM" in str(layer):
    #         weightLSTM = layer.get_weights()
    # warr,uarr, barr = weightLSTM
    # warr.shape,uarr.shape,barr.shape

    #Layer_0
    units0 = int(int(model.layers[0].trainable_weights[0].shape[1])/4)
    print("Num units0: ", units0)

    W0 = model.layers[0].get_weights()[0]
    U0 = model.layers[0].get_weights()[1]
    b0 = model.layers[0].get_weights()[2]

    # Every LSTM cell contain 4 trainable weights (input gate, forget gate, new_candidate, output         gate)
    # Keras API divide them to W, U and b. W is the trainable weights for the input sequences
    # U is the trainable weights for the hidden states and b is the bias vector.

    W0_i = W0[:, :units0]
    W0_f = W0[:, units0: units0 * 2]
    W0_c = W0[:, units0 * 2: units0 * 3]
    W0_o = W0[:, units0 * 3:]

    U0_i = U0[:, :units0]
    U0_f = U0[:, units0: units0 * 2]
    U0_c = U0[:, units0 * 2: units0 * 3]
    U0_o = U0[:, units0 * 3:]

    b0_i = b0[:units0]
    b0_f = b0[units0: units0 * 2]
    b0_c = b0[units0 * 2: units0 * 3]
    b0_o = b0[units0 * 3:]

    i0_t = sigmoid(np.dot(input_pred, W0_i)+np.dot(h_tm1, U0_i)+b0_i)
    f0_t = sigmoid(np.dot(input_pred, W0_f)+np.dot(h_tm1, U0_f)+b0_f)
    o0_t = sigmoid(np.dot(input_pred, W0_o)+np.dot(h_tm1, U0_o)+b0_o)
    new_candidate0_t = tanh(np.dot(input_pred, W0_c)+np.dot(h_tm1, U0_c)+b0_c)
    c0_t = np.dot(f0_t, c_tm1)+np.dot(i0_t, new_candidate0_t)
    h0_t = np.dot(o0_t, tanh(c0_t))

    #Layer_1
    units1 = int(int(model.layers[1].trainable_weights[0].shape[1])/4)
    print("Num units1: ", units1)

    W1 = model.layers[1].get_weights()[0]
    U1 = model.layers[1].get_weights()[1]
    b1 = model.layers[1].get_weights()[2]

    W1_i = W1[:, :units1]
    W1_f = W1[:, units1: units1 * 2]
    W1_c = W1[:, units1 * 2: units1 * 3]
    W1_o = W1[:, units1 * 3:]

    U1_i = U1[:, :units1]
    U1_f = U1[:, units1: units1 * 2]
    U1_c = U1[:, units1 * 2: units1 * 3]
    U1_o = U1[:, units1 * 3:]

    b1_i = b1[:units1]
    b1_f = b1[units1: units1 * 2]
    b1_c = b1[units1 * 2: units1 * 3]
    b1_o = b1[units1 * 3:]

    i1_t = sigmoid(np.dot(input_pred, W1_i)+np.dot(h0_t, U1_i)+b1_i)
    f1_t = sigmoid(np.dot(input_pred, W1_f)+np.dot(h0_t, U1_f)+b1_f)
    o1_t = sigmoid(np.dot(input_pred, W1_o)+np.dot(h0_t, U1_o)+b1_o)
    new_candidate1_t = tanh(np.dot(input_pred, W1_c)+np.dot(h0_t, U1_c)+b1_c)
    c1_t = np.dot(f1_t, c0_t)+np.dot(i1_t, new_candidate1_t)
    h1_t = np.dot(o1_t, tanh(c1_t))

    #Layer_2
    dense_weights = model.layers[2].get_weights()[0]
    dense_bias = model.layers[2].get_weights()[1]
    dense_output=np.dot(h1_t, dense_weights)+dense_bias
    output_pred = layer3_output.reshape(1, 3)

    return output_pred

</code>```

My problem is I cannot get the prediction because I don't really understand how does the input vector propagates in the LSTM layers, the reccurent propagation (between LSTM cells) and the forward propagation (between LSTM layers) despite I read many blogs and papers talking about this topic. They usually use the built-in methods. Finally I would be grateful if someone helps me to create my custom predict method instead of using the Keras API built-in method to perform prediction. Thanks in advance

Body:
I do some multivariate time series forecasting to design a one-step ahead predictor using Keras API and a stacked Long Short-Term Memory (LSTM) layers, so I'm tune and fit the following sequential model:

n_steps_in = 1
n_features = 3
model = Sequential()
model.add(LSTM(15, activation='tanh', return_sequences=True, input_shape=(n_steps_in,n_features)))
model.add(LSTM(20, activation='relu'))
model.add(Dense(n_features))
model.compile(optimizer='adam', loss='mse')
model.fit(X_train_lstm, y_train_lstm, epochs=100, validation_data = (X_test_lstm, y_test_lstm),
            verbose=1)

After that, In inference phase, I would like to use a my custom predict method instead of using the buit-in predict Keras method. To do so, fistly I have extract the weights and bias form the fitted model, and create a method that predict only one single time step i.e. I give to the fitted model an input sample with shape (1,1,3) and then it outputs a predicted vector with shape (1,3). This method is little similar than doing a feedforward pass.

def model_predict_LSTM(model, input_pred, c_tm1, h_tm1):

    # for layer in model.layers:
    #     if "LSTM" in str(layer):
    #         weightLSTM = layer.get_weights()
    # warr,uarr, barr = weightLSTM
    # warr.shape,uarr.shape,barr.shape

    #Layer_0
    units0 = int(int(model.layers[0].trainable_weights[0].shape[1])/4)
    print("Num units0: ", units0)

    W0 = model.layers[0].get_weights()[0]
    U0 = model.layers[0].get_weights()[1]
    b0 = model.layers[0].get_weights()[2]

    # Every LSTM cell contain 4 trainable weights (input gate, forget gate, new_candidate, output         gate)
    # Keras API divide them to W, U and b. W is the trainable weights for the input sequences
    # U is the trainable weights for the hidden states and b is the bias vector.

    W0_i = W0[:, :units0]
    W0_f = W0[:, units0: units0 * 2]
    W0_c = W0[:, units0 * 2: units0 * 3]
    W0_o = W0[:, units0 * 3:]

    U0_i = U0[:, :units0]
    U0_f = U0[:, units0: units0 * 2]
    U0_c = U0[:, units0 * 2: units0 * 3]
    U0_o = U0[:, units0 * 3:]

    b0_i = b0[:units0]
    b0_f = b0[units0: units0 * 2]
    b0_c = b0[units0 * 2: units0 * 3]
    b0_o = b0[units0 * 3:]

    i0_t = sigmoid(np.dot(input_pred, W0_i)+np.dot(h_tm1, U0_i)+b0_i)
    f0_t = sigmoid(np.dot(input_pred, W0_f)+np.dot(h_tm1, U0_f)+b0_f)
    o0_t = sigmoid(np.dot(input_pred, W0_o)+np.dot(h_tm1, U0_o)+b0_o)
    new_candidate0_t = tanh(np.dot(input_pred, W0_c)+np.dot(h_tm1, U0_c)+b0_c)
    c0_t = np.dot(f0_t, c_tm1)+np.dot(i0_t, new_candidate0_t)
    h0_t = np.dot(o0_t, tanh(c0_t))

    #Layer_1
    units1 = int(int(model.layers[1].trainable_weights[0].shape[1])/4)
    print("Num units1: ", units1)

    W1 = model.layers[1].get_weights()[0]
    U1 = model.layers[1].get_weights()[1]
    b1 = model.layers[1].get_weights()[2]

    W1_i = W1[:, :units1]
    W1_f = W1[:, units1: units1 * 2]
    W1_c = W1[:, units1 * 2: units1 * 3]
    W1_o = W1[:, units1 * 3:]

    U1_i = U1[:, :units1]
    U1_f = U1[:, units1: units1 * 2]
    U1_c = U1[:, units1 * 2: units1 * 3]
    U1_o = U1[:, units1 * 3:]

    b1_i = b1[:units1]
    b1_f = b1[units1: units1 * 2]
    b1_c = b1[units1 * 2: units1 * 3]
    b1_o = b1[units1 * 3:]

    i1_t = sigmoid(np.dot(input_pred, W1_i)+np.dot(h0_t, U1_i)+b1_i)
    f1_t = sigmoid(np.dot(input_pred, W1_f)+np.dot(h0_t, U1_f)+b1_f)
    o1_t = sigmoid(np.dot(input_pred, W1_o)+np.dot(h0_t, U1_o)+b1_o)
    new_candidate1_t = tanh(np.dot(input_pred, W1_c)+np.dot(h0_t, U1_c)+b1_c)
    c1_t = np.dot(f1_t, c0_t)+np.dot(i1_t, new_candidate1_t)
    h1_t = np.dot(o1_t, tanh(c1_t))

    #Layer_2
    dense_weights = model.layers[2].get_weights()[0]
    dense_bias = model.layers[2].get_weights()[1]
    dense_output=np.dot(h1_t, dense_weights)+dense_bias
    output_pred = layer3_output.reshape(1, 3)

    return output_pred

My problem is I cannot get the prediction because I don't really understand how does the input vector propagates in the LSTM layers, the reccurent propagation (between LSTM cells) and the forward propagation (between LSTM layers) despite I read many blogs and papers talking about this topic. They usually use the built-in methods. Finally I would be grateful if someone helps me to create my custom predict method instead of using the Keras API built-in method to perform prediction. Thanks in advance


问:
Extract SQL & PWBI queries from pbix file with Python
When we undergo data migration where I work, we have field names in our DB that can change and sets up errors in our PWBI reports.

Being that we work with ~60 reports, I am looking for a way to extract the SQL and PowerBI queries we can find in the Transform Data pop up window using Python.

I know that converting the .pbix files to .pbit allows us to access the DataMashup file who contains the formulas/section1.m file that contains all the queries. Accessing the files of a .pibt file via python isn't an issue as they can be treated like zip files.

However, I don't know how to access the files contained in the DataMashup file. I can do it manually using 7zips "Extract Files...", but I haven't found a way to extract them within a Python script.

I've tried using the ZipFile class but it returns an empty folder when I use the .extractall function on the DataMashup file.

The py7zr module didn't seem to help either as it is only dedicated to .7z files


问:
How to read content of a file which is received using curl command in gitlab-ci.yml
Any idea on how to read a specific key/value from a file retrieved using curl command in gitlab-ci.yml.

Here is what I am doing:

```<code>run_tests:
  stage: test
  image: golang:latest
  before_script:
    - go mod tidy
  script:
    - go test ./...
    - echo "DOING CURL"
    - echo "ProjectID=" $ProjectID
    - echo "CIJobID=" $CIJobID
    - curl https://gitlab.com/api/v4/projects/$ProjectID/jobs/$CIJobID/artifacts/variables.txt
    - curl https://gitlab.com/api/v4/projects/$ProjectID/jobs/$CIJobID/artifacts/variables.txt
    - echo "CURL DONE"
#  when: manual
  only:
  - tags
</code>```

control file:

```<code>Package: release-management
Priority: optional
Section: custom
Maintainer: Thor
Architecture: all
Version: ${CI_COMMIT_TAG}
Description: "Custom release management"

</code>```

I have a variables.txt file which contains the CI_variables which I want to use in some other file(control file) outside of gitlab-ci.yml.

What I want is that curl command should have some parameter or something passing which give me the the value of the key, eg: CI_COMMIT_TAG:4.4.4
So it should give me 4.4.4 so that I can use it to change the version in control file to build the deb package.

Edit 1: And do you think that I would need to commit and push the file again in where we have used the CI variable.

Body:
Any idea on how to read a specific key/value from a file retrieved using curl command in gitlab-ci.yml.

Here is what I am doing:

run_tests:
  stage: test
  image: golang:latest
  before_script:
    - go mod tidy
  script:
    - go test ./...
    - echo "DOING CURL"
    - echo "ProjectID=" $ProjectID
    - echo "CIJobID=" $CIJobID
    - curl https://gitlab.com/api/v4/projects/$ProjectID/jobs/$CIJobID/artifacts/variables.txt
    - curl https://gitlab.com/api/v4/projects/$ProjectID/jobs/$CIJobID/artifacts/variables.txt
    - echo "CURL DONE"
#  when: manual
  only:
  - tags

control file:

Package: release-management
Priority: optional
Section: custom
Maintainer: Thor
Architecture: all
Version: ${CI_COMMIT_TAG}
Description: "Custom release management"

I have a variables.txt file which contains the CI_variables which I want to use in some other file(control file) outside of gitlab-ci.yml.

What I want is that curl command should have some parameter or something passing which give me the the value of the key, eg: CI_COMMIT_TAG:4.4.4
So it should give me 4.4.4 so that I can use it to change the version in control file to build the deb package.

Edit 1: And do you think that I would need to commit and push the file again in where we have used the CI variable.


问:
Joi condition based on value in object
I need to validate data with different conditions.

This is my config now.

```<code>body: Joi.object({
  id: Joi.string().min(1).required(),
  config: Joi.alternatives()
    .try(
      Joi.object({
        version: Joi.string().valid('V1').required(),
        account: Joi.string().required(),
        name: Joi.string().required(),
      }).required()
    )
    .required(),
}).required(),
</code>```

In string version: Joi.string().valid('V1').required(),
I want add another version. valid('V1’, 'V2’)
But now config check version 1 or 2 should have fields account and name, but version 2 will have other fields.

How to implement this?

Title: Joi condition based on value in object

Body:
I need to validate data with different conditions.

This is my config now.

body: Joi.object({
  id: Joi.string().min(1).required(),
  config: Joi.alternatives()
    .try(
      Joi.object({
        version: Joi.string().valid('V1').required(),
        account: Joi.string().required(),
        name: Joi.string().required(),
      }).required()
    )
    .required(),
}).required(),

In string version: Joi.string().valid('V1').required(),
I want add another version. valid('V1’, 'V2’)
But now config check version 1 or 2 should have fields account and name, but version 2 will have other fields.

How to implement this?


问:
JavaScript: How to know which content world an event came from?
If I have an event listener in the main world, then let's say a chrome extension dispatched an event onto the target of my listener, am I able to tell that this event was dispatched from another content world?</p>


问:
What's the difference between serving images statically vs non-statically?
I'm relatively new to web development and I don't quite understand where to store my image assets for my website project.

I'm using Next.js and Tailwind, and I've been storing all images for my website inside of my "public" folder so that I can access them easily like this:

<Image src="/my-image.png" .../>
```

I'm aware that this is referred to as "static file serving", but I'm not sure when it would be beneficial for me to use this method as opposed to "non-static file serving". I'm also not quite sure how I would go about serving my images non-statically.

If anyone could help me make sense of this I would really appreciate it.

Body:
I'm relatively new to web development and I don't quite understand where to store my image assets for my website project.

I'm using Next.js and Tailwind, and I've been storing all images for my website inside of my "public" folder so that I can access them easily like this:

<Image src="/my-image.png" .../>

I'm aware that this is referred to as "static file serving", but I'm not sure when it would be beneficial for me to use this method as opposed to "non-static file serving". I'm also not quite sure how I would go about serving my images non-statically.

If anyone could help me make sense of this I would really appreciate it.


问:
Javascript code showing on website instead of processing it
I have just installed react and made and opened the folder in Vscode then deleted everything in the src folder and made a javascript file.Next, I wrote the following code:

```<code>import React from "react";
import ReactDOM from "react-dom";
const element= <h1> Hello </h1>;
console.log(element);
</code>```

a
The problem is instead of processing the code,It was displayed in the web page and even when I linked an html file to it.The console displayed the error "SyntaxError: Cannot use import statement outside a module"

Body:
I have just installed react and made and opened the folder in Vscode then deleted everything in the src folder and made a javascript file.Next, I wrote the following code:

import React from "react";
import ReactDOM from "react-dom";
const element=
 Hello
;
console.log(element);

a
The problem is instead of processing the code,It was displayed in the web page and even when I linked an html file to it.The console displayed the error "SyntaxError: Cannot use import statement outside a module"


问:
Axios get request in react and typescript ,error retrieving data
I am trying to get the list of course from the api , the request is succesfull but when i get the data first it makes the request 20 times. And after assigning the retrieved data (setDataList(response.data);) to the dataList state array it says that Argument of type 'Response' is not assignable to parameter of type 'SetStateAction<DataObject[]>'.

Eventhough the error is there it shows correctly all the courses names in the list that I created.

........................................................................................

```<code>import * as React from "react";
import Box from "@mui/material/Box";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
import { FixedSizeList, ListChildComponentProps } from "react-window";
import Card from "@mui/material/Card";
import AddIcon from "@mui/icons-material/Add";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField";
import { styled } from "@mui/material/styles";
import DialogButton from "./Modal";
import { Button, CardActionArea, CardActions } from "@mui/material";
import Paper from "@mui/material/Paper";
import Grid from "@mui/material/Grid";
import axios from 'axios';
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

interface DataObject {
  id: number;
  courseName: string;
  language:string;
  description:string;
  version:string;
  credit:number;

}

interface Response {
  data: DataObject[];

const config = {
  headers: {
    'Content-type':'aplication/json',
    'Access-Control-Allow-Origin': '*'

  }
};

function renderRow() {
   // Define a state variable to store the array of data objects
   const [dataList, setDataList] = useState<DataObject[]>([]);

   useEffect(() => {
     // Make the GET request using axios
     axios.get<Response>('http://localhost:8001/api/course',config)

       .then(response => {
        // Update the state variable with the array of data objects from the response

        console.log(response.data)
        setDataList(response.data);

       })
       .catch(err => {
         // Handle the error if the request fails
         console.error(err);
       });
   }, []);

   // Use the data list in your component
   return (
     <div>
       {dataList?.map(item => (
         // render each item in the list
 <ListItem  key={item.id} component="div" disablePadding>
       <ListItemButton>
         <ListItemText
           primary={`${item.courseName}`}
           primaryTypographyProps={{
             color: "#000000",
           }}
         />
       </ListItemButton>
     </ListItem>

       ))}
     </div>
   );
}

export default function BasicGrid() {
  return (
    <Box sx={{ flexGrow: 1 }}>
      <Grid container spacing={1}>
        <Grid container item spacing={3}>
          <Box sx={{ flexGrow: 1 }}>
            <Grid container spacing={1}>
              <Grid
                container
                item
                spacing={3}
                alignItems="center"
                justifyContent="center"
              >
                <Box
                  display="flex"
                  justifyContent="center"
                  alignItems="center"
                  sx={{
                    width: "100%",
                    height: 150,
                    maxWidth: 300,
                  }}
                >
                  <Typography variant="h5" align="center" color="text.primary">
                    Software Engineering
                  </Typography>
                </Box>
              </Grid>
              <Grid
                container
                item
                spacing={3}
                px={22}
                alignItems="right"
                justifyContent="right"
              >
                  <Link to="/addCourse">
                  <DialogButton />
      </Link>

              </Grid>
            </Grid>
          </Box>
        </Grid>
        <Grid container item spacing={3}>
          <Box sx={{ flexGrow: 1, p: 8 }}>
            <Grid container spacing={1}>
              <Grid item xs={3}>
                <Box
                  sx={{
                    width: "100%",
                    height: 460,
                    maxWidth: 300,
                    bgcolor: "background.paper",
                  }}
                >
                  <TextField
                    id="outlined-basic"
                    label="Search"
                    variant="outlined"
                    sx={{
                      width: "100%",
                    }}
                  />
                  <FixedSizeList
                    height={400}
                    width={300}
                    itemSize={46}
                    itemCount={10}
                    overscanCount={5}
                  >
                 {renderRow}
                  </FixedSizeList>
                </Box>
              </Grid>
              <Grid item xs={8}>
                <Card sx={{ Width: 345, height: 400 }}>
                  <CardActionArea>
                    <CardContent>
                      <Typography gutterBottom variant="h5" component="div">
                        Item 1
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                        In laoreet lacinia nunc rutrum gravida. Nulla ante
                        neque, pharetra sed lacinia quis, ultricies quis nibh.
                        Sed nec egestas nibh, vel sagittis libero. Curabitur
                        vehicula finibus libero, ac euismod est pellentesque
                        accumsan. Pellentesque finibus tincidunt dolor,
                        consequat venenatis ex sollicitudin ut. Proin finibus
                        facilisis erat in ultricies. Suspendisse potenti. Fusce
                        eu scelerisque risus. Duis commodo enim non risus varius
                        eleifend.
                      </Typography>
                    </CardContent>
                  </CardActionArea>
                  <CardActions>
                    <Box
                      sx={{ pl: 95, pt: 20 }}

                      //margin
                    >
                      <Button
                        variant="contained"
                        color="primary"
                        sx={{ width: 40 }}
                      >
                        Edit
                      </Button>
                    </Box>
                  </CardActions>
                </Card>
              </Grid>
            </Grid>
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
}

</code>```

Body:
I am trying to get the list of course from the api , the request is succesfull but when i get the data first it makes the request 20 times. And after assigning the retrieved data (setDataList(response.data);) to the dataList state array it says that Argument of type 'Response' is not assignable to parameter of type 'SetStateAction<DataObject[]>'.

Eventhough the error is there it shows correctly all the courses names in the list that I created.

........................................................................................

import * as React from "react";
import Box from "@mui/material/Box";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
import { FixedSizeList, ListChildComponentProps } from "react-window";
import Card from "@mui/material/Card";
import AddIcon from "@mui/icons-material/Add";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField";
import { styled } from "@mui/material/styles";
import DialogButton from "./Modal";
import { Button, CardActionArea, CardActions } from "@mui/material";
import Paper from "@mui/material/Paper";
import Grid from "@mui/material/Grid";
import axios from 'axios';
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

interface DataObject {
  id: number;
  courseName: string;
  language:string;
  description:string;
  version:string;
  credit:number;

}

interface Response {
  data: DataObject[];

const config = {
  headers: {
    'Content-type':'aplication/json',
    'Access-Control-Allow-Origin': '*'

  }
};

function renderRow() {
   // Define a state variable to store the array of data objects
   const [dataList, setDataList] = useState<DataObject[]>([]);

   useEffect(() => {
     // Make the GET request using axios
     axios.get<Response>('http://localhost:8001/api/course',config)

       .then(response => {
        // Update the state variable with the array of data objects from the response

        console.log(response.data)
        setDataList(response.data);

       })
       .catch(err => {
         // Handle the error if the request fails
         console.error(err);
       });
   }, []);

   // Use the data list in your component
   return (

       {dataList?.map(item => (
         // render each item in the list
 <ListItem  key={item.id} component="div" disablePadding>
       <ListItemButton>
         <ListItemText
           primary={`${item.courseName}`}
           primaryTypographyProps={{
             color: "#000000",
           }}
         />
       </ListItemButton>
     </ListItem>

       ))}

   );
}

export default function BasicGrid() {
  return (
    <Box sx={{ flexGrow: 1 }}>
      <Grid container spacing={1}>
        <Grid container item spacing={3}>
          <Box sx={{ flexGrow: 1 }}>
            <Grid container spacing={1}>
              <Grid
                container
                item
                spacing={3}
                alignItems="center"
                justifyContent="center"
              >
                <Box
                  display="flex"
                  justifyContent="center"
                  alignItems="center"
                  sx={{
                    width: "100%",
                    height: 150,
                    maxWidth: 300,
                  }}
                >
                  <Typography variant="h5" align="center" color="text.primary">
                    Software Engineering
                  </Typography>
                </Box>
              </Grid>
              <Grid
                container
                item
                spacing={3}
                px={22}
                alignItems="right"
                justifyContent="right"
              >
                  <Link to="/addCourse">
                  <DialogButton />
      </Link>

              </Grid>
            </Grid>
          </Box>
        </Grid>
        <Grid container item spacing={3}>
          <Box sx={{ flexGrow: 1, p: 8 }}>
            <Grid container spacing={1}>
              <Grid item xs={3}>
                <Box
                  sx={{
                    width: "100%",
                    height: 460,
                    maxWidth: 300,
                    bgcolor: "background.paper",
                  }}
                >
                  <TextField
                    id="outlined-basic"
                    label="Search"
                    variant="outlined"
                    sx={{
                      width: "100%",
                    }}
                  />
                  <FixedSizeList
                    height={400}
                    width={300}
                    itemSize={46}
                    itemCount={10}
                    overscanCount={5}
                  >
                 {renderRow}
                  </FixedSizeList>
                </Box>
              </Grid>
              <Grid item xs={8}>
                <Card sx={{ Width: 345, height: 400 }}>
                  <CardActionArea>
                    <CardContent>
                      <Typography gutterBottom variant="h5" component="div">
                        Item 1
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                        In laoreet lacinia nunc rutrum gravida. Nulla ante
                        neque, pharetra sed lacinia quis, ultricies quis nibh.
                        Sed nec egestas nibh, vel sagittis libero. Curabitur
                        vehicula finibus libero, ac euismod est pellentesque
                        accumsan. Pellentesque finibus tincidunt dolor,
                        consequat venenatis ex sollicitudin ut. Proin finibus
                        facilisis erat in ultricies. Suspendisse potenti. Fusce
                        eu scelerisque risus. Duis commodo enim non risus varius
                        eleifend.
                      </Typography>
                    </CardContent>
                  </CardActionArea>
                  <CardActions>
                    <Box
                      sx={{ pl: 95, pt: 20 }}

                      //margin
                    >
                      <Button
                        variant="contained"
                        color="primary"
                        sx={{ width: 40 }}
                      >
                        Edit
                      </Button>
                    </Box>
                  </CardActions>
                </Card>
              </Grid>
            </Grid>
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
}


问:
Live query performance monitoring in Postgresql
We use the following to measure performance of query in ORACLE,

```<code>select dbms_sqltune.report_sql_monitor(
   sql_id => '&sql_id',
   type => 'TEXT',
   report_level => ALL) as report
from dual;
</code>```

Can someone suggest how should I achieve the above outcome in Postgresql

Body:
We use the following to measure performance of query in ORACLE,

select dbms_sqltune.report_sql_monitor(
   sql_id => '&sql_id',
   type => 'TEXT',
   report_level => ALL) as report
from dual;

Can someone suggest how should I achieve the above outcome in Postgresql


问:
Add a static library (.a file) to React Native iOS project
I have a React Native iOS project. There is a 3rd party SDK I would like to use. That SDK is published as a static library (.a file) and a header file (.h file).

My approach has been.

Create new folder in the /Libraries directory. Add the .a and .h files to that new directory.

Drag the .a file into Link Binary With Libraries

However, when I build the app it throws the error:

```<code>Library not found for -INameOfSDK
</code>```

What am I doing wrong?

Body:
I have a React Native iOS project. There is a 3rd party SDK I would like to use. That SDK is published as a static library (.a file) and a header file (.h file).

My approach has been.

Create new folder in the /Libraries directory. Add the .a and .h files to that new directory.

Drag the .a file into Link Binary With Libraries

However, when I build the app it throws the error:

Library not found for -INameOfSDK

What am I doing wrong?


问:
Copy specific data from multiple workbooks into one master sheet
I have to copy data from 10+ workbooks and paste it into a master workbook.
All the workbooks are located in a folder on my desktop: C:\Users\xbv.......

All the workbooks contain a sheet named 'appendix B', I have to open each workbook, go to sheet 'appendix B’, select columns range C to F starting from row 6 to row ‘x'(the last row can vary in each workbook), cntrl+v (copy), and paste the data range into master worksheet. In the master worksheet, I paste the data in Columns A to D and continue pasting/appending the data as I copy data from more workbooks. Eventually, the master workbook has the data in columns A to D from every workbook in one sheet.

The columns range C to F and starting from row 6 always remains constant in all the sheets (appendix B ) of every workbook. Each workbook contains 7 sheets, but I am only interested in sheet ‘appendix B’

I have to repeat the same steps for 10-30 workbooks and continue pasting/appending the data into master sheet. So, I was wondering if someone could please help me to create a VBA code for this? I'm really new to VBA and would really appreciate your help!

```<code>Sub CopyRange()
    Application.ScreenUpdating = False
    Dim wkbDest As Workbook
    Dim wkbSource As Workbook
    Set wkbDest = ThisWorkbook
    Const strPath As String = "C:\Users\xbv\Desktop\group1\"
    ChDir strPath
    strExtension = Dir("*.xls*")
    Do While strExtension <> ""
        Set wkbSource = Workbooks.Open(strPath & strExtension)
        With wkbSource
            .Sheets("Appendix B").Range("C6:F" & Range("C" & Rows.Count).End(xlUp).Row).Copy wkbDest.Sheets("Master1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Sheets("Appendix C").Range("D6:Y" & Range("D" & Rows.Count).End(xlUp).Row ).Copy wkbDest.Sheets("Master1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Sheets("Appendix D").Range("D5:I" & Range("D" & Rows.Count).End(xlUp).Row).Copy wkbDest.Sheets("Master1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Close savechanges:=False
        End With
        strExtension = Dir
    Loop
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I have to copy data from 10+ workbooks and paste it into a master workbook.
All the workbooks are located in a folder on my desktop: C:\Users\xbv.......

All the workbooks contain a sheet named 'appendix B', I have to open each workbook, go to sheet 'appendix B’, select columns range C to F starting from row 6 to row ‘x'(the last row can vary in each workbook), cntrl+v (copy), and paste the data range into master worksheet. In the master worksheet, I paste the data in Columns A to D and continue pasting/appending the data as I copy data from more workbooks. Eventually, the master workbook has the data in columns A to D from every workbook in one sheet.

The columns range C to F and starting from row 6 always remains constant in all the sheets (appendix B ) of every workbook. Each workbook contains 7 sheets, but I am only interested in sheet ‘appendix B’

I have to repeat the same steps for 10-30 workbooks and continue pasting/appending the data into master sheet. So, I was wondering if someone could please help me to create a VBA code for this? I'm really new to VBA and would really appreciate your help!

Sub CopyRange()
    Application.ScreenUpdating = False
    Dim wkbDest As Workbook
    Dim wkbSource As Workbook
    Set wkbDest = ThisWorkbook
    Const strPath As String = "C:\Users\xbv\Desktop\group1\"
    ChDir strPath
    strExtension = Dir("*.xls*")
    Do While strExtension <> ""
        Set wkbSource = Workbooks.Open(strPath & strExtension)
        With wkbSource
            .Sheets("Appendix B").Range("C6:F" & Range("C" & Rows.Count).End(xlUp).Row).Copy wkbDest.Sheets("Master1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Sheets("Appendix C").Range("D6:Y" & Range("D" & Rows.Count).End(xlUp).Row ).Copy wkbDest.Sheets("Master1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Sheets("Appendix D").Range("D5:I" & Range("D" & Rows.Count).End(xlUp).Row).Copy wkbDest.Sheets("Master1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
            .Close savechanges:=False
        End With
        strExtension = Dir
    Loop
    Application.ScreenUpdating = True
End Sub


问:
How to split a spark job into chunks automatically
Suppose you have a dataset with 900 million records.
You run a certain query that retrieves all of these 900M records, tries to process the data and spark crashes due to memory issues.

However, everything works fine if you run this job three times, each time with 300M records each. Meaning, if you split your dataframe by a certain parameter and get it as an input in the query so you don't have to load all the dataframe at once.
For example, in the image below, if you run the job with the complete table, spark crashes. However, if you split it in three runs, spark will do the job well.

How would you automate this split? Meaning, these three jobs can separately, but I don't want to do that manually.


问:
Can't find procedure entry point _p__argv
Can't find procedure entry point _p__argv this message appears while updating vsc
I have windows 8 for my laptop 32 bit
thanks for help

I tried to search in Google and downloaded vs c++ 2015 but the issue still


问:
Why does await works with "setState" in React JS?
I have been reading docs for almost a week now and searching to find an exact answer !
When I use inline setState() for a onClick event, It works perfectly fine but when I move the setState() to a function named updateCount() in my class, It does not work for the first time and I get the reason.

The problem is I added async/await to the function, strangely it works. ( I am aware of other methods )

The question is why it works with async/await?

(By the way when I use VS Code, I get this massage : 'await' has no effect on the type of this expression. but it actually has an effect so maybe that is a bug in react JS ?! )

Original code that works fine :

```<code>class LastTest extends Component {

    state = { count: 0 }
    componentDidMount() {
        document.title = `You clicked ${this.state.count} times`;
    }
    componentDidUpdate() {
        document.title = `You clicked ${this.state.count} times`;
    }
    render() {
        return (
            <div>
                <p>You clicked {this.state.count} times</p>
                <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                Click me
                </button>
            </div>
        );
    }
}
</code>```

Bad code that does not update count for first click:

```<code>class LastTest extends Component {

    state = { count: 0 }
    componentDidMount() {
        document.title = `You clicked ${this.state.count} times`;
    }
    updateCount(){
        this.setState({ count: this.state.count + 1 });
        document.title = `You clicked ${this.state.count} times`;
    }
    render() {
        return (
            <div>
                <p>You clicked {this.state.count} times</p>
                <button onClick={() => this.updateCount()}>
                Click me
                </button>
            </div>
        );
    }
}
</code>```

Updated code and added async/await to the function updateCount() :

```<code>class LastTest extends Component {

    state = { count: 0 }
    componentDidMount() {
        document.title = `You clicked ${this.state.count} times`;
    }
    async updateCount(){
        await this.setState({ count: this.state.count + 1 });
        document.title = `You clicked ${this.state.count} times`;
    }
    render() {
        return (
            <div>
                <p>You clicked {this.state.count} times</p>
                <button onClick={() => this.updateCount()}>
                Click me
                </button>
            </div>
        );
    }
}
</code>```

Body:
I have been reading docs for almost a week now and searching to find an exact answer !
When I use inline setState() for a onClick event, It works perfectly fine but when I move the setState() to a function named updateCount() in my class, It does not work for the first time and I get the reason.

The problem is I added async/await to the function, strangely it works. ( I am aware of other methods )

The question is why it works with async/await?

(By the way when I use VS Code, I get this massage : 'await' has no effect on the type of this expression. but it actually has an effect so maybe that is a bug in react JS ?! )

Original code that works fine :

class LastTest extends Component {

    state = { count: 0 }
    componentDidMount() {
        document.title = `You clicked ${this.state.count} times`;
    }
    componentDidUpdate() {
        document.title = `You clicked ${this.state.count} times`;
    }
    render() {
        return (

You clicked {this.state.count} times

                <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                Click me
                </button>

        );
    }
}

Bad code that does not update count for first click:

class LastTest extends Component {

    state = { count: 0 }
    componentDidMount() {
        document.title = `You clicked ${this.state.count} times`;
    }
    updateCount(){
        this.setState({ count: this.state.count + 1 });
        document.title = `You clicked ${this.state.count} times`;
    }
    render() {
        return (

You clicked {this.state.count} times

                <button onClick={() => this.updateCount()}>
                Click me
                </button>

        );
    }
}

Updated code and added async/await to the function updateCount() :

class LastTest extends Component {

    state = { count: 0 }
    componentDidMount() {
        document.title = `You clicked ${this.state.count} times`;
    }
    async updateCount(){
        await this.setState({ count: this.state.count + 1 });
        document.title = `You clicked ${this.state.count} times`;
    }
    render() {
        return (

You clicked {this.state.count} times

                <button onClick={() => this.updateCount()}>
                Click me
                </button>

        );
    }
}