问:
Store all data on specific host filesystem using Docker-Compose
Docker is storing data in volumes under /var/lib/docker/volumes/ on my host machine.
There is no more space on this disk.
I want docker to store all the data at a new location on the host.
I thought the following docker-compose file would work:

```<code>services:

  myservice:
    image: <image>
    container-name: myservice
    ports:
      - 5000:5000
    volumes:
      myservicevolume:/

volumes:
  myservicevoume:/mounts/bigdisk3/myservice
</code>```

But I get this error:

```<code>volumes must be a mapping, not a string.
</code>```

Using docker-compose file, how to have all data for a service stored on a specific disk?

Body:
Docker is storing data in volumes under /var/lib/docker/volumes/ on my host machine.
There is no more space on this disk.
I want docker to store all the data at a new location on the host.
I thought the following docker-compose file would work:

services:

  myservice:
    image: <image>
    container-name: myservice
    ports:
      - 5000:5000
    volumes:
      myservicevolume:/

volumes:
  myservicevoume:/mounts/bigdisk3/myservice

But I get this error:

volumes must be a mapping, not a string.

Using docker-compose file, how to have all data for a service stored on a specific disk?


来源: stackexchange

问:
What is the correct approach for load testing evm?
I am trying to create a load testing script for a simple evm with jsonrpc. I have a different type of methods in my mind.
First one is that i will send lets say 1000 requests(write transactions) to the server and wait for the responses and calculate total time then i can find a successful responses/seconds data. Second one is that i can send these request with a delay such as 100ms then during the process i can measure the successful responses/time lets say in every 250ms. In my opinion, real life request will not be sent so fast without a delay but in order to understand the edges of the server requests must be sent as soon as possible. So what is the correct approach to simulate and calculate a load testing result ?</p>

ContentLicense: CC BY-SA 4.0


问:
Traceback on rendering HTML to PDF through wkhtmltopdf
I using wkhtmltopdf tool to render html to pdf. On my linux computer it outputs everything right with css rules. But after installing the same tool on windows, the output does not look the same. I am receiving the following error.

```<code>Traceback (most recent call last):
  File "G:\Source\test.py", line 24, in <module>
    pdfkit.from_file('templates/test.html', 'test.pdf', options=options, configuration=config)
  File "C:\Users\akram.rahat\AppData\Local\Programs\Python\Python311\Lib\site-packages\pdfkit\api.py", line 51, in from_file
    return r.to_pdf(output_path)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\akram.rahat\AppData\Local\Programs\Python\Python311\Lib\site-packages\pdfkit\pdfkit.py", line 201, in to_pdf
    self.handle_error(exit_code, stderr)
  File "C:\Users\akram.rahat\AppData\Local\Programs\Python\Python311\Lib\site-packages\pdfkit\pdfkit.py", line 155, in handle_error
    raise IOError('wkhtmltopdf reported an error:\n' + stderr)
OSError: wkhtmltopdf reported an error:
Exit with code 1 due to network error: UnknownNetworkError
</code>```

What can be the problem here?

Here is the code snippet:

```<code>import pdfkit
from xhtml2pdf import pisa
from jinja2 import Environment, FileSystemLoader

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')
options = {
    'page-size': 'A4',
    'margin-top': '0',
    'margin-right': '0',
    'margin-bottom': '0',
    'margin-left': '0',
    'enable-local-file-access': '',
    'encoding': "UTF-8"
}

pdfkit.from_file('templates/test.html', 'test.pdf', options=options, configuration=config)
</code>```

Body:
I using wkhtmltopdf tool to render html to pdf. On my linux computer it outputs everything right with css rules. But after installing the same tool on windows, the output does not look the same. I am receiving the following error.

Traceback (most recent call last):
  File "G:\Source\test.py", line 24, in <module>
    pdfkit.from_file('templates/test.html', 'test.pdf', options=options, configuration=config)
  File "C:\Users\akram.rahat\AppData\Local\Programs\Python\Python311\Lib\site-packages\pdfkit\api.py", line 51, in from_file
    return r.to_pdf(output_path)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\akram.rahat\AppData\Local\Programs\Python\Python311\Lib\site-packages\pdfkit\pdfkit.py", line 201, in to_pdf
    self.handle_error(exit_code, stderr)
  File "C:\Users\akram.rahat\AppData\Local\Programs\Python\Python311\Lib\site-packages\pdfkit\pdfkit.py", line 155, in handle_error
    raise IOError('wkhtmltopdf reported an error:\n' + stderr)
OSError: wkhtmltopdf reported an error:
Exit with code 1 due to network error: UnknownNetworkError

What can be the problem here?

Here is the code snippet:

import pdfkit
from xhtml2pdf import pisa
from jinja2 import Environment, FileSystemLoader

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')
options = {
    'page-size': 'A4',
    'margin-top': '0',
    'margin-right': '0',
    'margin-bottom': '0',
    'margin-left': '0',
    'enable-local-file-access': '',
    'encoding': "UTF-8"
}

pdfkit.from_file('templates/test.html', 'test.pdf', options=options, configuration=config)


问:
Stuck at Building Android App using Bazel
I am following the guide to build android using Bazel (https://bazel.build/start/android-app) but unfortunately I am stuck at excuting build command.

I am running in windows 10, tried Bazel versions 6.0 & 7.0.0 .exe downloaded from Baze's GitHub page

Please assist.

Below please find the error log

C:\Bazel>bazel build //src/main:app

INFO: Analyzed target //src/main:app (0 packages loaded, 0 targets configured).

INFO: Found 1 target...

ERROR: C:/bazel/src/main/java/com/example/bazel/BUILD:5:16: Desugaring src/main/java/com/example/bazel/libgreeter_activity.jar for Android failed: Worker process did not return a WorkResponse:

---8<---8<--- Start of log, file at C:/users/eric/_bazel_eric/4yp365mj/bazel-workers/worker-15-Desugar.log ---8<---8<---

LAUNCHER ERROR: Cannot launch process: "bash.exe" -c "C:\\Users\\Eric\\_bazel_eric\\4yp365mj\\execroot\\main\\bazel-out\\x64_windows-opt-exec-2B5CBBC6\\bin\\external\\bazel_tools\\tools\\android\\desugar_java8 --persistent_worker"

Reason: (error: 2): The system cannot find the file specified.

---8<---8<--- End of log ---8<---8<---

Target //src/main:app failed to build

Use --verbose_failures to see the command lines of failed build steps.

INFO: Elapsed time: 1.123s, Critical Path: 0.27s

INFO: 3 processes: 3 internal.

FAILED: Build did NOT complete successfull


问:
Getting data from axios using eventListeners and having no response
I'm trying to make a get request from an api using axios + eventListeners because I only want the data to be loaded on my screen AFTER I click on an especific button. Everything was working out fine before I tried to add the eventListener logic, now I simply don't get aby results from the api (plus, no errors are shown in the console).
this is my code:

```<code>const[game,setGame]= React.useState([]);

    React.useEffect(()=>{
            axios.get("http://localhost:8080/games/1").then((response)=>{
            setGame(response.data);
            });
    }, []);
    if (!game) return null;

    window.onload=function(){
        let button = document.getElementById("button");
        button.addEventListener('click', ()=>{
            game.map((game, index) => {
                return(
                    <>
                        <p className="n1">{game}</p>
                    </>
                )
            });
        })
    }
</code>```

and, on the same page, this is the code for the button that I'm trying to make it work:

```<code><a href="#" className="button" id="button" >
     <p className="bttn-p" >GERAR NÚMEROS</p>
</a>
</code>```

This is my first time using eventListeners and I'm actually kind of new at react so if anyone knows anything that could help I'd be extremely grateful :D

Body:
I'm trying to make a get request from an api using axios + eventListeners because I only want the data to be loaded on my screen AFTER I click on an especific button. Everything was working out fine before I tried to add the eventListener logic, now I simply don't get aby results from the api (plus, no errors are shown in the console).
this is my code:

const[game,setGame]= React.useState([]);

    React.useEffect(()=>{
            axios.get("http://localhost:8080/games/1").then((response)=>{
            setGame(response.data);
            });
    }, []);
    if (!game) return null;

    window.onload=function(){
        let button = document.getElementById("button");
        button.addEventListener('click', ()=>{
            game.map((game, index) => {
                return(
                    <>

{game}

                    </>
                )
            });
        })
    }

and, on the same page, this is the code for the button that I'm trying to make it work:

GERAR NÚMEROS

This is my first time using eventListeners and I'm actually kind of new at react so if anyone knows anything that could help I'd be extremely grateful :D


问:
Editing CSS in PhpStorm is so slow
Lately I've been editing CSS files in PhpStorm a lot lately, and I've noticed that the CSS code completion is very slow. Suggested display time is about 2-5 seconds.

I think PhpStorm scanned too many files before giving me a suggestion.

How to make PhpStorm stop scanning other CSS files before showing me suggestions?

Title: Editing CSS in PhpStorm is so slow


问:
How can I store the columns index by converting the column name as a variable:
Ex:

```<code>A B C D
0 2 2 3
2 4 5 6
2 4 6 8
</code>```

Here, the index of column "C" is 2. I want to store this index in the variable by converting that column name into variable.

So, C=2

Note this should work in dynamic case.

Tried:

```<code>exec("%s = %s" % "a","b")
</code>```

But this is not working in a function.

The name of the column is unknown, need the index of the column stored in the same column name.

Body:
Ex:

A B C D
0 2 2 3
2 4 5 6
2 4 6 8

Here, the index of column "C" is 2. I want to store this index in the variable by converting that column name into variable.

So, C=2

Note this should work in dynamic case.

Tried:

exec("%s = %s" % "a","b")

But this is not working in a function.

The name of the column is unknown, need the index of the column stored in the same column name.


问:
How can I connect my Power BI Service Dataset to Elasticsearch through Logstash? I need config file for this problem.?
I tried this config file but it is throwing an error.
it is my config file which i try:</p>
```<code>input {
   http {
    http_method => "post"
    url => "https://api.powerbi.com/v1.0/myorg/datasets/your-dataset-id/"
    headers => {
      "Content-Type" => "application/json"
      "Authorization" => "Bearer access_tocken"
    }
  }
}

output {
  elasticsearch {
  hosts => ["http://localhost:9200"]
  index => "powerbi"
  }
}
</code>```

Body:
I tried this config file but it is throwing an error.
it is my config file which i try:

input {
   http {
    http_method => "post"
    url => "https://api.powerbi.com/v1.0/myorg/datasets/your-dataset-id/"
    headers => {
      "Content-Type" => "application/json"
      "Authorization" => "Bearer access_tocken"
    }
  }
}

output {
  elasticsearch {
  hosts => ["http://localhost:9200"]
  index => "powerbi"
  }
}


问:
.NET Pipe deadlock or pipe broken
I'm trying to do some logic according to this article, so many server pipes with many clients.

https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication?source=recommendations

But I'm achieving a deadlock when trying to do some stress test with a lot of clients. Server waits for write being completed and client also waits for its write being completed.

I don't close the pipe, because...

When I try to close the pipe after complete read, even with another instances created, I get Pipe broken exception on client - seems like the second client tries to connect to already closed pipe.

What approach is correct? Should pipe instance be closed after success operation? So how the second client should connect properly to not get Pipe broken error.

It's worth to say that I create a subpipes child pipes for scoped operations, but they work well and are properly disposed. The problem is with root pipe, so the one which many clients are simultaneously connected.

Also I use Protobuf for read/writes.

The client code:

  _pipeStream = new Lazy<Task<NamedPipeClientStream>>(CreateRootPipe);

  //...

  public async Task<NamedPipeClientStream> RequestPipeAsync(ClaimsIdentity forIdentity)
    {
        var message = new CreatePipeRequest()
        {
           //...
        };

        IMessageWriter writer = _writerFactory(await _pipeStream.Value);
        IMessageReader reader = _readerFactory(await _pipeStream.Value);

        await writer.WriteAsync(message);

        var response = await reader.ReadAsync<CreatePipeResponse>();

        return new NamedPipeClientStream(".", response.PipeName, PipeDirection.InOut);
    }

```
<pre class="lang-cs prettyprint-override"><code>await using NamedPipeClientStream pipe = await _pipeManager.RequestPipeAsync(...);

        await pipe.ConnectAsync();

        var request = new ParseExpressionRequest()
        {
           // ...
        };

        IMessageReader messageReader = _messageReaderFactory(pipe);
        IMessageWriter messageWriter = _messageWriterFactory(pipe);

        await messageWriter.WriteAsync(request);

        var response = await messageReader.ReadAsync<ParseExpressionResponse>();
</code>```

The server code:

    Task.WaitAll(
        Enumerable.Range(0, 10)
            .Select(_ => Task.Run(ListenHandler))
            .ToArray());

    async Task ListenHandler()
    {
        await using var rootPipe = new NamedPipeServerStream(
            options.Value.Name,
            PipeDirection.InOut,
            NamedPipeServerStream.MaxAllowedServerInstances,
            PipeTransmissionMode.Byte);

        var messageReader = new MessageReader(logger, rootPipe);
        var messageWriter = new MessageWriter(rootPipe, logger);

        await rootPipe.WaitForConnectionAsync();

        while (true)
        {

            var request = await messageReader.ReadAsync<CreatePipeRequest>();

            string pipeName = GetPipeName(request.Username);

            var scopedPipe = new NamedPipeServerStream(
                pipeName,
                PipeDirection.InOut);

            await messageWriter.WriteAsync(
                new CreatePipeResponse()
                {
                   // ...
                });

            Task.Factory.StartNew(ScopedPipeHandler, scopedPipe, TaskCreationOptions.LongRunning)
                .ContinueWith(ScopePipeFailHandler, TaskContinuationOptions.OnlyOnFaulted);

            rootPipe.Close(); // if not delete this line, the client gets pipe broken, if delete, then deadlock occurs in some stressful scenario
        }

```

Title: .NET Pipe deadlock or pipe broken

Body:
I'm trying to do some logic according to this article, so many server pipes with many clients.

https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication?source=recommendations

But I'm achieving a deadlock when trying to do some stress test with a lot of clients. Server waits for write being completed and client also waits for its write being completed.

I don't close the pipe, because...

When I try to close the pipe after complete read, even with another instances created, I get Pipe broken exception on client - seems like the second client tries to connect to already closed pipe.

What approach is correct? Should pipe instance be closed after success operation? So how the second client should connect properly to not get Pipe broken error.

It's worth to say that I create a subpipes child pipes for scoped operations, but they work well and are properly disposed. The problem is with root pipe, so the one which many clients are simultaneously connected.

Also I use Protobuf for read/writes.

The client code:

  _pipeStream = new Lazy<Task<NamedPipeClientStream>>(CreateRootPipe);

  //...

  public async Task<NamedPipeClientStream> RequestPipeAsync(ClaimsIdentity forIdentity)
    {
        var message = new CreatePipeRequest()
        {
           //...
        };

        IMessageWriter writer = _writerFactory(await _pipeStream.Value);
        IMessageReader reader = _readerFactory(await _pipeStream.Value);

        await writer.WriteAsync(message);

        var response = await reader.ReadAsync<CreatePipeResponse>();

        return new NamedPipeClientStream(".", response.PipeName, PipeDirection.InOut);
    }

await using NamedPipeClientStream pipe = await _pipeManager.RequestPipeAsync(...);

        await pipe.ConnectAsync();

        var request = new ParseExpressionRequest()
        {
           // ...
        };

        IMessageReader messageReader = _messageReaderFactory(pipe);
        IMessageWriter messageWriter = _messageWriterFactory(pipe);

        await messageWriter.WriteAsync(request);

        var response = await messageReader.ReadAsync<ParseExpressionResponse>();

The server code:

    Task.WaitAll(
        Enumerable.Range(0, 10)
            .Select(_ => Task.Run(ListenHandler))
            .ToArray());

    async Task ListenHandler()
    {
        await using var rootPipe = new NamedPipeServerStream(
            options.Value.Name,
            PipeDirection.InOut,
            NamedPipeServerStream.MaxAllowedServerInstances,
            PipeTransmissionMode.Byte);

        var messageReader = new MessageReader(logger, rootPipe);
        var messageWriter = new MessageWriter(rootPipe, logger);

        await rootPipe.WaitForConnectionAsync();

        while (true)
        {

            var request = await messageReader.ReadAsync<CreatePipeRequest>();

            string pipeName = GetPipeName(request.Username);

            var scopedPipe = new NamedPipeServerStream(
                pipeName,
                PipeDirection.InOut);

            await messageWriter.WriteAsync(
                new CreatePipeResponse()
                {
                   // ...
                });

            Task.Factory.StartNew(ScopedPipeHandler, scopedPipe, TaskCreationOptions.LongRunning)
                .ContinueWith(ScopePipeFailHandler, TaskContinuationOptions.OnlyOnFaulted);

            rootPipe.Close(); // if not delete this line, the client gets pipe broken, if delete, then deadlock occurs in some stressful scenario
        }


问:
Class extends value undefined is not a constructor or null when extending from a class/interface
I have a class that looks like this:

class TextElement extends ProjectElement {
    initialize() {
        this.name = "Text"
        this.elementID = "text"
        this.properties.addProperty(new ElementProperty("text", "Hi!"))
    }

    render(): any {
        return

            {this.properties.getProp("text")}

    }
}
```
<p>In my editor, it's all good (InteliSense doesn't throw any errors). But as soon as I enter the browser (in my case, my Electron app), I get this error:</p>
<pre class="lang-js prettyprint-override"><code>Uncaught TypeError: Class extends value undefined is not a constructor or null
    at eval (TextElement.tsx:9:37)
    at ./src/libs/elements/TextElement.tsx (main.js:993:1)
    at __webpack_require__ (main.js:1455:42)
    at eval (list.ts:6:39)
    at ./src/libs/elements/list.ts (main.js:1004:1)
    at __webpack_require__ (main.js:1455:42)
    at eval (project.tsx:10:32)
    at ./src/libs/project.tsx (main.js:1037:1)
    at __webpack_require__ (main.js:1455:42)
    at eval (Editor.tsx:45:35)
</code>```

What I think is happening is that TextElement is not extending the class ProjectElement, but rather the type/interface ProjectElement, so that when I use the new keyword, TypeScript finds no constructor() function.

I could define the constructor() manually but that defeats the purpose of inheriting entirely. If I want to add another one, I'd need to copy/paste code around which as we all know is not efficient.

tsconfig.js

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    "jsx": "react",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "CommonJS",                                /* Specify what module code is generated. */
    "rootDir": "./",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./ts-build",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}
```
<p><strong>UPDATE:</strong> After changing <code>module</code> to something other than <code>CommonJS</code>, I get a new error:</p>
<pre class="lang-js prettyprint-override"><code>Uncaught ReferenceError: Cannot access 'ProjectElement' before initialization
    at Module.ProjectElement (project.tsx:6:63)
    at eval (TextElement.tsx:11:65)
    at ./src/libs/elements/TextElement.tsx (main.js:993:1)
    at __webpack_require__ (main.js:1345:41)
    at eval (list.ts:5:70)
    at ./src/libs/elements/list.ts (main.js:1004:1)
    at __webpack_require__ (main.js:1345:41)
    at eval (project.tsx:12:72)
    at ./src/libs/project.tsx (main.js:1037:1)
    at __webpack_require__ (main.js:1345:41)
</code>```

This is due to a circular-import mess between 3 files.

project.tsx

import React from 'react';
import { v4 as uuidV4 } from 'uuid';

import ELEMENT_LIST from './elements/list';

interface Project {
    elements: {
        [key: string]: ProjectElement
    }
    name: string
    id: string
}

interface ProjectElement {
    uid: string
    properties: ElementProperties
    name: string
    render(): any,
    elementID: string
}

interface ElementProperty {
    value: any
    name: string
    uid: string
    editable: boolean
}

interface ElementProperties {
    properties: {
        [key: string]: ElementProperty
    }
}

class Project {
    constructor() {
        this.elements = {}
        this.name = ""
        this.id = ""
    }

    addElement(element: ProjectElement) {
        this.elements[element.uid] = element
    }

    serialize() {
        // Serialize elements
        let serializedElements: {
            [key: string]: {}
        } = {}
        Object.keys(this.elements).map((element_key) => {
            const element: ProjectElement = this.elements[element_key]
            const serializedElement = element.serialize()
            serializedElements[element.uid] = serializedElement
        })

        return {
            name: this.name,
            elements: serializedElements,
        }
    }

    load(json: any) {
        const elements: {
            [key: string]: any
        } = json.elements
        const name: string = json.name

        this.name = name
        this.id = json.id
        Object.keys(elements).map(key => {
            const element = elements[key]
            const elementID: string = element.elementID
            const ElementConstructor = ELEMENT_LIST[elementID]
            const newElement = new ElementConstructor()
            newElement.load(element)
            this.addElement(newElement)
        })
    }
}
class ProjectElement {
    constructor() {
        this.uid = uuidV4()
        this.name = "Element"
        this.elementID = "generic"
        this.properties = new ElementProperties()

        this.initialize()
        this.render = this.render.bind(this)
    }

    serialize() {
        return {
            uid: this.uid,
            properties: this.properties.getAllProps(),
            elementID: this.elementID
        }
    }

    render() {
        return

            Here you put your custom component logic!

    }

    initialize() {
        console.log(`Component "${this.uid}" initialized!`)
    }

    load(json: any) {
        this.uid = json.uid
        this.name = json.name
        this.elementID = json.elementID
        this.properties.loadProperties(json.properties)
    }
}

class ElementProperties {
    constructor() {
        this.properties = {};
    }

    addProperty(property: ElementProperty) {
        this.properties[property.name] = property
    }

    updateProperty(name: string, value: any) {
        this.properties[name].changeValue(value)
    }

    deleteProperty(name: string) {
        delete this.properties[name]
    }

    getProp(name: string) {
        let property = this.properties[name]
        return property.value
    }

    getAllProps() {
        let properties: {
            [key: string]: any
        } = {}
        Object.keys(this.properties).map((property_key: string) => {
            const property = this.properties[property_key]
            properties[property_key] = property.value
        })
        return properties
    }

    loadProperties(json: {
        [key: string]: any
    }) {
        Object.keys(json).map(key => {
            const property = json[key]
            const newProperty = new ElementProperty(property.name, property.value)
            this.addProperty(newProperty)
        })
    }
}

class ElementProperty {
    constructor(name: string, value: any) {
        this.value = value
        this.name = name
        this.uid = uuidV4()
        this.editable = true
    }

    changeValue(newValue: any) {
        this.value = newValue
    }

    serialize() {
        return {
            name: this.name,
            value: this.value,
            uid: this.uid,
            editable: this.editable
        }
    }
}

export default Project
export {
    ProjectElement,
    ElementProperty,
    ElementProperties,
    ELEMENT_LIST
}
```
<p><code>TextElement.tsx</code></p>
```Mentioned above
```
```import TextElement from "./TextElement";

const ELEMENT_LIST: {[key: string]: any} = {
    "text": TextElement
}

export default ELEMENT_LIST
```

Body:
I have a class that looks like this:

class TextElement extends ProjectElement {
    initialize() {
        this.name = "Text"
        this.elementID = "text"
        this.properties.addProperty(new ElementProperty("text", "Hi!"))
    }

    render(): any {
        return

            {this.properties.getProp("text")}

    }
}

In my editor, it's all good (InteliSense doesn't throw any errors). But as soon as I enter the browser (in my case, my Electron app), I get this error:

Uncaught TypeError: Class extends value undefined is not a constructor or null
    at eval (TextElement.tsx:9:37)
    at ./src/libs/elements/TextElement.tsx (main.js:993:1)
    at __webpack_require__ (main.js:1455:42)
    at eval (list.ts:6:39)
    at ./src/libs/elements/list.ts (main.js:1004:1)
    at __webpack_require__ (main.js:1455:42)
    at eval (project.tsx:10:32)
    at ./src/libs/project.tsx (main.js:1037:1)
    at __webpack_require__ (main.js:1455:42)
    at eval (Editor.tsx:45:35)

What I think is happening is that TextElement is not extending the class ProjectElement, but rather the type/interface ProjectElement, so that when I use the new keyword, TypeScript finds no constructor() function.

I could define the constructor() manually but that defeats the purpose of inheriting entirely. If I want to add another one, I'd need to copy/paste code around which as we all know is not efficient.

tsconfig.js

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    "jsx": "react",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "CommonJS",                                /* Specify what module code is generated. */
    "rootDir": "./",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./ts-build",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

UPDATE: After changing module to something other than CommonJS, I get a new error:

Uncaught ReferenceError: Cannot access 'ProjectElement' before initialization
    at Module.ProjectElement (project.tsx:6:63)
    at eval (TextElement.tsx:11:65)
    at ./src/libs/elements/TextElement.tsx (main.js:993:1)
    at __webpack_require__ (main.js:1345:41)
    at eval (list.ts:5:70)
    at ./src/libs/elements/list.ts (main.js:1004:1)
    at __webpack_require__ (main.js:1345:41)
    at eval (project.tsx:12:72)
    at ./src/libs/project.tsx (main.js:1037:1)
    at __webpack_require__ (main.js:1345:41)

This is due to a circular-import mess between 3 files.

project.tsx

import React from 'react';
import { v4 as uuidV4 } from 'uuid';

import ELEMENT_LIST from './elements/list';

interface Project {
    elements: {
        [key: string]: ProjectElement
    }
    name: string
    id: string
}

interface ProjectElement {
    uid: string
    properties: ElementProperties
    name: string
    render(): any,
    elementID: string
}

interface ElementProperty {
    value: any
    name: string
    uid: string
    editable: boolean
}

interface ElementProperties {
    properties: {
        [key: string]: ElementProperty
    }
}

class Project {
    constructor() {
        this.elements = {}
        this.name = ""
        this.id = ""
    }

    addElement(element: ProjectElement) {
        this.elements[element.uid] = element
    }

    serialize() {
        // Serialize elements
        let serializedElements: {
            [key: string]: {}
        } = {}
        Object.keys(this.elements).map((element_key) => {
            const element: ProjectElement = this.elements[element_key]
            const serializedElement = element.serialize()
            serializedElements[element.uid] = serializedElement
        })

        return {
            name: this.name,
            elements: serializedElements,
        }
    }

    load(json: any) {
        const elements: {
            [key: string]: any
        } = json.elements
        const name: string = json.name

        this.name = name
        this.id = json.id
        Object.keys(elements).map(key => {
            const element = elements[key]
            const elementID: string = element.elementID
            const ElementConstructor = ELEMENT_LIST[elementID]
            const newElement = new ElementConstructor()
            newElement.load(element)
            this.addElement(newElement)
        })
    }
}
class ProjectElement {
    constructor() {
        this.uid = uuidV4()
        this.name = "Element"
        this.elementID = "generic"
        this.properties = new ElementProperties()

        this.initialize()
        this.render = this.render.bind(this)
    }

    serialize() {
        return {
            uid: this.uid,
            properties: this.properties.getAllProps(),
            elementID: this.elementID
        }
    }

    render() {
        return

            Here you put your custom component logic!

    }

    initialize() {
        console.log(`Component "${this.uid}" initialized!`)
    }

    load(json: any) {
        this.uid = json.uid
        this.name = json.name
        this.elementID = json.elementID
        this.properties.loadProperties(json.properties)
    }
}

class ElementProperties {
    constructor() {
        this.properties = {};
    }

    addProperty(property: ElementProperty) {
        this.properties[property.name] = property
    }

    updateProperty(name: string, value: any) {
        this.properties[name].changeValue(value)
    }

    deleteProperty(name: string) {
        delete this.properties[name]
    }

    getProp(name: string) {
        let property = this.properties[name]
        return property.value
    }

    getAllProps() {
        let properties: {
            [key: string]: any
        } = {}
        Object.keys(this.properties).map((property_key: string) => {
            const property = this.properties[property_key]
            properties[property_key] = property.value
        })
        return properties
    }

    loadProperties(json: {
        [key: string]: any
    }) {
        Object.keys(json).map(key => {
            const property = json[key]
            const newProperty = new ElementProperty(property.name, property.value)
            this.addProperty(newProperty)
        })
    }
}

class ElementProperty {
    constructor(name: string, value: any) {
        this.value = value
        this.name = name
        this.uid = uuidV4()
        this.editable = true
    }

    changeValue(newValue: any) {
        this.value = newValue
    }

    serialize() {
        return {
            name: this.name,
            value: this.value,
            uid: this.uid,
            editable: this.editable
        }
    }
}

export default Project
export {
    ProjectElement,
    ElementProperty,
    ElementProperties,
    ELEMENT_LIST
}

TextElement.tsx

Mentioned above

import TextElement from "./TextElement";

const ELEMENT_LIST: {[key: string]: any} = {
    "text": TextElement
}

export default ELEMENT_LIST


问:
upload to remote subdomain ftp folder
This is driving me nuts:
My 'ftp.company.com' ftp account structure:

```<code>/root/
  public_html
  domains
   -mysubdomain.com
      -public_html
</code>```

i set up my git config:

```<code>[git-ftp]
    url = ftp.company.com/domains/mysubdomain.com/public_html
    user = company.com
    password = ******
</code>```

but 'git ftp init/push'  keeps uploading to:
//public_html/domains/mysubdomain.com/public_html

Why is git-ftp refering to my ftp ROOT/public_html as base url?
What am I doing wrong here?

thanks and regards
Tom

Title: upload to remote subdomain ftp folder

Body:
This is driving me nuts:
My 'ftp.company.com' ftp account structure:

/root/
  public_html
  domains
   -mysubdomain.com
      -public_html

i set up my git config:

[git-ftp]
    url = ftp.company.com/domains/mysubdomain.com/public_html
    user = company.com
    password = ******

but 'git ftp init/push'  keeps uploading to:
//public_html/domains/mysubdomain.com/public_html

Why is git-ftp refering to my ftp ROOT/public_html as base url?
What am I doing wrong here?

thanks and regards
Tom


问:
None of these files exist: * screens\loader.json
I have installed AnimatedLoader , but i am getting an error saying None of these files exist:
  * screens\loader.json.native|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json)

import AnimatedLoader from "react-native-animated-loader"

and within my code i used it .

```<code>    <AnimatedLoader
    visible={visible}
    overlayColor="rgba(255,255,255,0.75)"
    source={require("./loader.json")}
    animationStyle={styles.lottie}
    speed={1}
  />
</code>```

Any ideas how i can resolve this error?

I tried above and got an error message above

Body:
I have installed AnimatedLoader , but i am getting an error saying None of these files exist:
  * screens\loader.json.native|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.js|.native.js|.js|.ios.jsx|.native.jsx|.jsx|.ios.json|.native.json|.json)

import AnimatedLoader from "react-native-animated-loader"

and within my code i used it .

    <AnimatedLoader
    visible={visible}
    overlayColor="rgba(255,255,255,0.75)"
    source={require("./loader.json")}
    animationStyle={styles.lottie}
    speed={1}
  />

Any ideas how i can resolve this error?

I tried above and got an error message above


问:
Is it possible to add a space between the dropdown options? Squarespace
the dropdown box works well, but the options are too close. Can anyone fix it?

I tried searching it up and was expecting some coding to fix it, but nothing showed up that was an answer to my problem.


问:
How to filter out updated records from CTE in postgres?
I am trying to perform an update and insert operation on a partitioned table using the same CTE. The update query works perfectly fine. But during insert, I just want those records from CTE which were not updated so that I can make an optimal insert with least cost.

Below is my table and query :

```<code>create table scientist (id integer, firstname varchar(100), lastname varchar(100));
insert into scientist (id, firstname, lastname) values (1, 'albert', 'einstein');
insert into scientist (id, firstname, lastname) values (2, 'isaac', 'newton');
insert into scientist (id, firstname, lastname) values (3, 'marie', 'curie');
select * from scientist;

alter table scientist add constraint id_pk  PRIMARY KEY  ("id");
with temp(id, firstname, lastname) as (
  Select *
  from (values(1, 'albert','besra'),
              (5, 'abc', 'def')
       ) as a(id, firstname, lastname)
),
updated as(
  update scientist s
    set lastname = t.lastname
  from temp t
  where s.id = t.id returning t.*
)
Select *
from updated;
</code>```

At present, it is returning all the rows. I was able to filter out records which were updated but that increased the total cost of my operation.

```<code>where not exists (Select 1 from updated where updated.id = temp.id )
</code>```

Is there a way I can do that ?

Body:
I am trying to perform an update and insert operation on a partitioned table using the same CTE. The update query works perfectly fine. But during insert, I just want those records from CTE which were not updated so that I can make an optimal insert with least cost.

Below is my table and query :

create table scientist (id integer, firstname varchar(100), lastname varchar(100));
insert into scientist (id, firstname, lastname) values (1, 'albert', 'einstein');
insert into scientist (id, firstname, lastname) values (2, 'isaac', 'newton');
insert into scientist (id, firstname, lastname) values (3, 'marie', 'curie');
select * from scientist;

alter table scientist add constraint id_pk  PRIMARY KEY  ("id");
with temp(id, firstname, lastname) as (
  Select *
  from (values(1, 'albert','besra'),
              (5, 'abc', 'def')
       ) as a(id, firstname, lastname)
),
updated as(
  update scientist s
    set lastname = t.lastname
  from temp t
  where s.id = t.id returning t.*
)
Select *
from updated;

At present, it is returning all the rows. I was able to filter out records which were updated but that increased the total cost of my operation.

where not exists (Select 1 from updated where updated.id = temp.id )

Is there a way I can do that ?


问:
Add stored embedded JAVA Neo4j DB to Desktop Neo4j
is there a possibility to import a stored embedded Neo4j DB to the Neo4j desktop Version?
Because it is easier to see which nodes are a part of my db.  I created new db with the Neo4j desktop version
and i tried to import these embedded db like in this attached picture. It seems not to work.

enter image description here


问:
MongoDb aggregation for daily number of views and downloads
```<code>  const fetchSummary = expressAsyncHandler(async (req, res) => {
      //GET DAILY SUMMARY
      const dailySummary = await Post.aggregate([
        {
          $group: {
            _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
            downloads: { $sum: "$downloadCount" },
            totalViews: { $sum: "$numViews" },
          },
        },
        { $sort: { _id: -1 } },
      ]);
      res.send({  dailySummary });
    });
</code>```

Can someone please help me out here, I'm trying to fetch sum total for daily views and downloads for a post

And here is my result

```<code>"dailySummary": [
        {
            "_id": "2023-01-07",
            "downloads": 49,
            "totalViews": 227
        },
        {
            "_id": "2023-01-06",
            "downloads": 41,
            "totalViews": 605
        },
        {
            "_id": "2023-01-05",
            "downloads": 0,
            "totalViews": 0
        }
    ],
</code>```

And this result is a wrong

number of views for today is not even up 40,and downloads 10

```<code>//============
// Fetch single Post
//============

    const fetchPostCtrl = expressAsyncHandler(async (req, res) => {
      const { id } = req.params;
      validateMongodbId(id);
      try {
        const post = await Post.findById(id).populate("user comments");
        //Updating Number of views
        await Post.findByIdAndUpdate(
          id,
          {
            $inc: { numViews: 1 },
          },
          { new: true }
        );
        res.json(post);
      } catch (error) {
        res.json(error);
      }

});
</code>```

This is how I'm fetching post details

Body:
  const fetchSummary = expressAsyncHandler(async (req, res) => {
      //GET DAILY SUMMARY
      const dailySummary = await Post.aggregate([
        {
          $group: {
            _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
            downloads: { $sum: "$downloadCount" },
            totalViews: { $sum: "$numViews" },
          },
        },
        { $sort: { _id: -1 } },
      ]);
      res.send({  dailySummary });
    });

Can someone please help me out here, I'm trying to fetch sum total for daily views and downloads for a post

And here is my result

"dailySummary": [
        {
            "_id": "2023-01-07",
            "downloads": 49,
            "totalViews": 227
        },
        {
            "_id": "2023-01-06",
            "downloads": 41,
            "totalViews": 605
        },
        {
            "_id": "2023-01-05",
            "downloads": 0,
            "totalViews": 0
        }
    ],

And this result is a wrong

number of views for today is not even up 40,and downloads 10

//============
// Fetch single Post
//============

    const fetchPostCtrl = expressAsyncHandler(async (req, res) => {
      const { id } = req.params;
      validateMongodbId(id);
      try {
        const post = await Post.findById(id).populate("user comments");
        //Updating Number of views
        await Post.findByIdAndUpdate(
          id,
          {
            $inc: { numViews: 1 },
          },
          { new: true }
        );
        res.json(post);
      } catch (error) {
        res.json(error);
      }

});

This is how I'm fetching post details


问:
How can i remove one Object and rename all object sequence wise
array

i want to remove one object form module ex module_1 as i give in html data-modulename and rename all module name sequence wise. like moduel_2 module_3... and rename module_1 module_2...

```<code> array(1) {
    [0]=>
    object(App\Models\Course)#1268 (30) {
      ["connection":protected]=>
      string(5) "mysql"
      ["table":protected]=>
      string(7) "courses"
      ["primaryKey":protected]=>
      string(2) "id"
      ["keyType":protected]=>
      string(3) "int"
      ["incrementing"]=>
      bool(true)
      ["with":protected]=>
      array(0) {
      }
      ["withCount":protected]=>
      array(0) {
      }
      ["preventsLazyLoading"]=>
      bool(false)
      ["perPage":protected]=>
      int(15)
      ["exists"]=>
      bool(true)
      ["wasRecentlyCreated"]=>
      bool(false)
      ["escapeWhenCastingToString":protected]=>
      bool(false)
      ["attributes":protected]=>
      array(9) {
        ["id"]=>
        int(4)
        ["coursename"]=>
        string(11) "science new"
        ["awardingbody"]=>
        string(23) "Qualifi, United Kingdom"
        ["ofqualregistrationnumber"]=>
        string(8) "34443234"
        ["totalcredits"]=>
        string(5) "34242"
        ["numbersmodules"]=>
        string(1) "2"
        ["modules"]=>
        string(672) "{"module_1":{"modulename":"sdfsdf","moduletypes":"mandatory","moduleid":"32432","moduleaim":"sdfsdfsf","learningobjectives":"sdfsfsfd","assessmentcriteria":"sdfsfdsdf","scenario":"sdfsdf","tasknumber":2,"taskarea":["sdfsdfsf","adsdasdsd"],"librarylinks":["sdsfsf"],"studylinks":["sdfsdfsdf"],"videoslinks":["sdfsdsf"]},"module_2":{"modulename":"sdfsdfsdf","moduletypes":"optional","moduleid":"34234","moduleaim":"sdfsdfsdf","learningobjectives":"sdfsdfs","assessmentcriteria":"sdfsdsdfs","scenario":"sddssssd","tasknumber":2,"taskarea":["sdsdfsdf","sdsdfsdf"],"librarylinks":["sdsdfsdf","sdfsdffs"],"studylinks":["sdfsdf","sdfsdf"],"videoslinks":["sdfsdfs","sdfsfsdfsf"]}}"
        ["created_at"]=>
        string(10) "1673082184"
        ["updated_at"]=>
        string(10) "1673082214"
      }
</code>```

html

<button class="btn rounded-pill btn-primary remove_module remove_module_button" type="button" data-id="4" data-modulename="module_1">Remove Module </button>

js

`$(document).on('click', '.remove_module', function() {

```<code>$confirm = confirm("Are you Sure you want to delete this module");
if ($confirm == true) {
    $this = $(this);
    $id = $this.data('id');
    $modulename = $this.data('modulename');
    $.ajax({
        method: "GET",
        url: "deletemodule",
        data: {
            id: $id,
            modulename: $modulename
        },
        success: function(data) {
            if (data == 1) {
                alert("Service Start Successfully!");
                window.location.reload();
            }
        }
    });
}
</code>```

});`

php

`public function deleteModule(Request $request){
$id = $request->id;
$modulename = $request->modulename;

```<code>    $data =  Course::where('id', $id)->get();
    $module = $data[0]->modules;
    $json = json_decode($module);
    $result = [];

    foreach($json as $key => $value) {
            if($value->$modulename != $modulename) {
                    $result[] = $value;
            }
    }
    $update = [
        'module' => json_encode($result)
    ];
    Course::where('id', $id)->update($update);
    echo 1;
 }`
</code>```

Body:
array

i want to remove one object form module ex module_1 as i give in html data-modulename and rename all module name sequence wise. like moduel_2 module_3... and rename module_1 module_2...

 array(1) {
    [0]=>
    object(App\Models\Course)#1268 (30) {
      ["connection":protected]=>
      string(5) "mysql"
      ["table":protected]=>
      string(7) "courses"
      ["primaryKey":protected]=>
      string(2) "id"
      ["keyType":protected]=>
      string(3) "int"
      ["incrementing"]=>
      bool(true)
      ["with":protected]=>
      array(0) {
      }
      ["withCount":protected]=>
      array(0) {
      }
      ["preventsLazyLoading"]=>
      bool(false)
      ["perPage":protected]=>
      int(15)
      ["exists"]=>
      bool(true)
      ["wasRecentlyCreated"]=>
      bool(false)
      ["escapeWhenCastingToString":protected]=>
      bool(false)
      ["attributes":protected]=>
      array(9) {
        ["id"]=>
        int(4)
        ["coursename"]=>
        string(11) "science new"
        ["awardingbody"]=>
        string(23) "Qualifi, United Kingdom"
        ["ofqualregistrationnumber"]=>
        string(8) "34443234"
        ["totalcredits"]=>
        string(5) "34242"
        ["numbersmodules"]=>
        string(1) "2"
        ["modules"]=>
        string(672) "{"module_1":{"modulename":"sdfsdf","moduletypes":"mandatory","moduleid":"32432","moduleaim":"sdfsdfsf","learningobjectives":"sdfsfsfd","assessmentcriteria":"sdfsfdsdf","scenario":"sdfsdf","tasknumber":2,"taskarea":["sdfsdfsf","adsdasdsd"],"librarylinks":["sdsfsf"],"studylinks":["sdfsdfsdf"],"videoslinks":["sdfsdsf"]},"module_2":{"modulename":"sdfsdfsdf","moduletypes":"optional","moduleid":"34234","moduleaim":"sdfsdfsdf","learningobjectives":"sdfsdfs","assessmentcriteria":"sdfsdsdfs","scenario":"sddssssd","tasknumber":2,"taskarea":["sdsdfsdf","sdsdfsdf"],"librarylinks":["sdsdfsdf","sdfsdffs"],"studylinks":["sdfsdf","sdfsdf"],"videoslinks":["sdfsdfs","sdfsfsdfsf"]}}"
        ["created_at"]=>
        string(10) "1673082184"
        ["updated_at"]=>
        string(10) "1673082214"
      }

html

<button class="btn rounded-pill btn-primary remove_module remove_module_button" type="button" data-id="4" data-modulename="module_1">Remove Module </button>

js

`$(document).on('click', '.remove_module', function() {

$confirm = confirm("Are you Sure you want to delete this module");
if ($confirm == true) {
    $this = $(this);
    $id = $this.data('id');
    $modulename = $this.data('modulename');
    $.ajax({
        method: "GET",
        url: "deletemodule",
        data: {
            id: $id,
            modulename: $modulename
        },
        success: function(data) {
            if (data == 1) {
                alert("Service Start Successfully!");
                window.location.reload();
            }
        }
    });
}

});`

php

`public function deleteModule(Request $request){
$id = $request->id;
$modulename = $request->modulename;

    $data =  Course::where('id', $id)->get();
    $module = $data[0]->modules;
    $json = json_decode($module);
    $result = [];

    foreach($json as $key => $value) {
            if($value->$modulename != $modulename) {
                    $result[] = $value;
            }
    }
    $update = [
        'module' => json_encode($result)
    ];
    Course::where('id', $id)->update($update);
    echo 1;
 }`


问:
I want to send a connect-log message to discord through discord bot by following a file in tailer module
Here's my code:

```<code>import discord
from discord.ext import commands
from discord import app_commands
import tailer
import pyrcon
import geocoder
import time

Prefix = "-"
bot = commands.Bot(command_prefix=Prefix, case_insensitive = True, intents = discord.Intents.all())

@bot.event
async def on_ready():
    print(bot.user)
    await bot.change_presence(status=discord.Status.dnd)
    for line in tailer.follow(open("/data/dm/main/connectlog.log")):
        Name = line.split('%')[1]
        IP = line.split('%')[3]
        ip_address = geocoder.ip(IP)
        country = ip_address.country
        state = ip_address.state
        city = ip_address.city
        time.sleep(4)
        if "\"connect" in line:
            embed = discord.Embed(title = f"Player {Name} connected to SS-DM server", description=f"IP : {IP}\nCountry : {country}\nState/Province : {state}\n City : {city}", color=0x00FF00)
            channel = bot.get_channel(ID)
            await channel.send(embed = embed)

bot.run(TOKEN)

</code>```

So when I run my above code it shows the following error:

```<code>  File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 633, in run_until_complete
    self.run_forever()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 600, in run_forever
    self._run_once()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 1896, in _run_once
    handle._run()
  File "/usr/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/data/dm/main/codwatcher1.py", line 65, in on_ready
    for line in tailer.follow(open("/data/dm/main/connectlog.log")):
  File "/usr/local/lib/python3.10/dist-packages/tailer/__init__.py", line 182, in follow
    time.sleep(delay)

</code>```

Basically I am trying to follow a file through tailer module of python and send it to discord. I tried everything but in vain, so I hope you guys can help me figure this out.

Its my gameserver log. To see who connected to my server..

Body:
Here's my code:

import discord
from discord.ext import commands
from discord import app_commands
import tailer
import pyrcon
import geocoder
import time

Prefix = "-"
bot = commands.Bot(command_prefix=Prefix, case_insensitive = True, intents = discord.Intents.all())

@bot.event
async def on_ready():
    print(bot.user)
    await bot.change_presence(status=discord.Status.dnd)
    for line in tailer.follow(open("/data/dm/main/connectlog.log")):
        Name = line.split('%')[1]
        IP = line.split('%')[3]
        ip_address = geocoder.ip(IP)
        country = ip_address.country
        state = ip_address.state
        city = ip_address.city
        time.sleep(4)
        if "\"connect" in line:
            embed = discord.Embed(title = f"Player {Name} connected to SS-DM server", description=f"IP : {IP}\nCountry : {country}\nState/Province : {state}\n City : {city}", color=0x00FF00)
            channel = bot.get_channel(ID)
            await channel.send(embed = embed)

bot.run(TOKEN)

So when I run my above code it shows the following error:

  File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 633, in run_until_complete
    self.run_forever()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 600, in run_forever
    self._run_once()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 1896, in _run_once
    handle._run()
  File "/usr/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/data/dm/main/codwatcher1.py", line 65, in on_ready
    for line in tailer.follow(open("/data/dm/main/connectlog.log")):
  File "/usr/local/lib/python3.10/dist-packages/tailer/__init__.py", line 182, in follow
    time.sleep(delay)

Basically I am trying to follow a file through tailer module of python and send it to discord. I tried everything but in vain, so I hope you guys can help me figure this out.

Its my gameserver log. To see who connected to my server..


问:
Rust member functions as multithreaded mutable callbacks in real-time safe code
I am looking to use a member function of a struct as a mutable callback. The standard way I would do this is by wrapping my struct instance in a mutex and then in an Arc. In this use case however, my callback is a real-time audio callback which needs to be real-time safe and is triggered on a dedicated thread. This means no locking can happen that might delay the callback from occurring.

My actual member callback method must take a mutable reference to the struct (I think this is where things fall apart). The struct does contain members but these can all be atomic variables.

Here is an example of the kind of thing I'm looking for:

```<code>use std::sync::Arc;
use clap::error;
use cpal::{traits::{HostTrait, DeviceTrait}, StreamConfig, OutputCallbackInfo, StreamError};
use std::sync::atomic::AtomicI16;

pub struct AudioProcessor {
     var: AtomicI16,
}

impl AudioProcessor {
    fn audio_block_f32(&mut self, audio: &mut [f32], _info: &OutputCallbackInfo) {
    }

    fn audio_error(&mut self, error: StreamError) {
    }
}

fn initAudio()
{
     let out_dev = cpal::default_host().default_output_device().expect("No available output device found");

     let mut supported_configs_range = out_dev.supported_output_configs().expect("Could not obtain device configs");
     let config = supported_configs_range.next().expect("No available configs").with_max_sample_rate();

     let proc = Arc::new(AudioProcessor{var: AtomicI16::new(5)});
     let audio_callback_instance = proc.clone();
     let error_callback_instance = proc.clone();

     out_dev.build_output_stream(&StreamConfig::from(config), move |audio: &mut [f32], info: &OutputCallbackInfo| audio_callback_instance.audio_block_f32(audio, info), move |stream_error| error_callback_instance.clone().audio_error(stream_error));
 }
</code>```

Currently this code fails in the build_output_stream() function with this error message:

cannot borrow data in an Arc as mutable
trait DerefMut is required to modify through a dereference, but it is not implemented for Arc<AudioProcessor>

Are there any standard ways of dealing with problems like this?

Body:
I am looking to use a member function of a struct as a mutable callback. The standard way I would do this is by wrapping my struct instance in a mutex and then in an Arc. In this use case however, my callback is a real-time audio callback which needs to be real-time safe and is triggered on a dedicated thread. This means no locking can happen that might delay the callback from occurring.

My actual member callback method must take a mutable reference to the struct (I think this is where things fall apart). The struct does contain members but these can all be atomic variables.

Here is an example of the kind of thing I'm looking for:

use std::sync::Arc;
use clap::error;
use cpal::{traits::{HostTrait, DeviceTrait}, StreamConfig, OutputCallbackInfo, StreamError};
use std::sync::atomic::AtomicI16;

pub struct AudioProcessor {
     var: AtomicI16,
}

impl AudioProcessor {
    fn audio_block_f32(&mut self, audio: &mut [f32], _info: &OutputCallbackInfo) {
    }

    fn audio_error(&mut self, error: StreamError) {
    }
}

fn initAudio()
{
     let out_dev = cpal::default_host().default_output_device().expect("No available output device found");

     let mut supported_configs_range = out_dev.supported_output_configs().expect("Could not obtain device configs");
     let config = supported_configs_range.next().expect("No available configs").with_max_sample_rate();

     let proc = Arc::new(AudioProcessor{var: AtomicI16::new(5)});
     let audio_callback_instance = proc.clone();
     let error_callback_instance = proc.clone();

     out_dev.build_output_stream(&StreamConfig::from(config), move |audio: &mut [f32], info: &OutputCallbackInfo| audio_callback_instance.audio_block_f32(audio, info), move |stream_error| error_callback_instance.clone().audio_error(stream_error));
 }

Currently this code fails in the build_output_stream() function with this error message:

cannot borrow data in an Arc as mutable
trait DerefMut is required to modify through a dereference, but it is not implemented for Arc<AudioProcessor>

Are there any standard ways of dealing with problems like this?


问:
Install the npm module of openapi for testing an api
I am a QA engineer and I need to test an api using the openapi package: https://www.npmjs.com/package/openapi.

To install I understood it is clear

I already use this package : ng-openapi-gen. https://www.npmjs.com/package/ng-openapi-gen.

I would like to find the equivalent of this part with the openapi package : ng-openapi-gen --input my-api.yaml --output my-app/src/app/api

moreover I would like a detailed tuto of the use of this package 'openapi'if possible please

I just installed the openapi packge.


问:
threading function not executing in dockerfile
If I execute this python code in my IDE, it works perfectly fine and updates the plot gets updated every time the check_time function returns True.

```<code>import matplotlib.pyplot as plt
import time
from threading import Thread
from flask import Flask, send_file
from config import *
import mysql.connector
import pandas as pd
from support_analysis import *
import datetime

app = Flask(__name__)

def update_plot():
    while True:

    if check_time(consistent=True):
        #print("script is updating")
        result = download_data()
        right_pred_rise, longest_rise, right_pred_fall, longest_fall \
            = print_metrics_over_time(df=result)

        ml_1pred, ml2_pred = get_latest_pred(result)

        result = result[['return', 'return_static_invest']]
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Create the plot
        fig, ax = plt.subplots()
        result.plot(ax=ax)

        # Add the vertical lines
        plt.axvline(x=result.index[longest_rise[0]], color='green')
        plt.axvline(x=result.index[longest_rise[1]], color='green')
        plt.axvline(x=result.index[longest_fall[0]], color='red')
        plt.axvline(x=result.index[longest_fall[1]], color='red')

        # Add the red dot to the latest index
        latest_index = len(result) - 1
        ax.scatter(result.index[latest_index], ml_1pred, color='cornflowerblue')

        # Add the blue dot to the latest index
        ax.scatter(result.index[latest_index], ml2_pred, color='coral')

        plt.title(label='Bot vs buy and hold', fontweight='bold')
        plt.text(0.95, 0.01, timestamp, transform=plt.gcf().transFigure, ha='right', fontsize=8)

        plt.savefig('plot.png')

@app.route('/plot.png')
def plot():
    return send_file('plot.png', mimetype='image/png')

if __name__ == '__main__':
    # Start the update thread
    t = Thread(target=update_plot)
    t.start()

    # Run the web server
    app.run()
</code>```

When deploying it via docker, the plot.png gets created and displayed on the port/plot.png url, but never updated, meaning that the thread that updates the function stops executing

this is the corresponding dockerfile (where i assume that the issue is)

```<code>FROM python:3.10

COPY main.py main.py
COPY config.py config.py
COPY support_analysis.py support_analysis.py
COPY numbers.pkl numbers.pkl
COPY requirements.txt requirements.txt

RUN pip install -r requirements.txt

RUN pip install gunicorn

EXPOSE 8000

# Run the WSGI server
CMD ["gunicorn"  , "--bind", "0.0.0.0:8000", "main:app"]
</code>```

Body:
If I execute this python code in my IDE, it works perfectly fine and updates the plot gets updated every time the check_time function returns True.

import matplotlib.pyplot as plt
import time
from threading import Thread
from flask import Flask, send_file
from config import *
import mysql.connector
import pandas as pd
from support_analysis import *
import datetime

app = Flask(__name__)

def update_plot():
    while True:

    if check_time(consistent=True):
        #print("script is updating")
        result = download_data()
        right_pred_rise, longest_rise, right_pred_fall, longest_fall \
            = print_metrics_over_time(df=result)

        ml_1pred, ml2_pred = get_latest_pred(result)

        result = result[['return', 'return_static_invest']]
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Create the plot
        fig, ax = plt.subplots()
        result.plot(ax=ax)

        # Add the vertical lines
        plt.axvline(x=result.index[longest_rise[0]], color='green')
        plt.axvline(x=result.index[longest_rise[1]], color='green')
        plt.axvline(x=result.index[longest_fall[0]], color='red')
        plt.axvline(x=result.index[longest_fall[1]], color='red')

        # Add the red dot to the latest index
        latest_index = len(result) - 1
        ax.scatter(result.index[latest_index], ml_1pred, color='cornflowerblue')

        # Add the blue dot to the latest index
        ax.scatter(result.index[latest_index], ml2_pred, color='coral')

        plt.title(label='Bot vs buy and hold', fontweight='bold')
        plt.text(0.95, 0.01, timestamp, transform=plt.gcf().transFigure, ha='right', fontsize=8)

        plt.savefig('plot.png')

@app.route('/plot.png')
def plot():
    return send_file('plot.png', mimetype='image/png')

if __name__ == '__main__':
    # Start the update thread
    t = Thread(target=update_plot)
    t.start()

    # Run the web server
    app.run()

When deploying it via docker, the plot.png gets created and displayed on the port/plot.png url, but never updated, meaning that the thread that updates the function stops executing

this is the corresponding dockerfile (where i assume that the issue is)

FROM python:3.10

COPY main.py main.py
COPY config.py config.py
COPY support_analysis.py support_analysis.py
COPY numbers.pkl numbers.pkl
COPY requirements.txt requirements.txt

RUN pip install -r requirements.txt

RUN pip install gunicorn

EXPOSE 8000

# Run the WSGI server
CMD ["gunicorn"  , "--bind", "0.0.0.0:8000", "main:app"]


问:
Why if let with reference to some yields reference to inner value?
The following code doesn't compile because assigning a to b returns: expected struct std::string::String, found &std::string::String. I thought &s was &Option and not &Option<&T>. It seems that &s is behaving exactly like s.as_ref(). What's the reason behind this behavior?

```<code>fn main() {
    let s = Some("string".to_string());
    if let Some(a) = &s {
        let b: String = a;
        println!("{}", b);
    }
}
</code>```

Body:
The following code doesn't compile because assigning a to b returns: expected struct std::string::String, found &std::string::String. I thought &s was &Option and not &Option<&T>. It seems that &s is behaving exactly like s.as_ref(). What's the reason behind this behavior?

fn main() {
    let s = Some("string".to_string());
    if let Some(a) = &s {
        let b: String = a;
        println!("{}", b);
    }
}


问:
Is there any recommend way to get a ginkgo html report
I want to use ginkgo as the integration testing tool in project, but I have searched ginkgo doc and github issues below:

Feature request: HTML reporter #141

Specs aren't identified in go test . -json output #639

I find that ginkgo only support json reporter and junit reporter, no html reporter

But it's really need a html report for boss to see the test clearly, so I thought one solution it's to use the ginkgo junit report and use the tool below
https://github.com/inorton/junit2html
transfer it to html report.

It's a solution yet, but I want to know is there have any other solution to get a more beautiful html report. Thanks all.


问:
How to solve "arguments did not match any overloaded call" error? - Pyqt6 (QThreadPool)
Hey here is my worker class:

```<code>class Worker(QRunnable):
    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()

        self.fn = fn
        self.args = args
        self.kwargs = kwargs

    @Slot()
    def run(self):
        self.fn(*self.args, **self.kwargs)
</code>```

I use this worker like this:

```<code>def thread_profile_clear(self):

    for i in range(self.model.rowCount())[::-1]:
        if self.model.item(i).checkState() == Qt.CheckState.Checked:
            account = self.account_list[i]
            worker = Worker(self.profile_cleaner, account=account)
            self.threadpool.start(worker)
</code>```

However, when I trigger the button for this function, I get this error:

```<code>  TypeError: arguments did not match any overloaded call:
  start(self, QRunnable, priority: int = 0): argument 1 has unexpected type 'Worker'
  start(self, Callable[[], None], priority: int = 0): argument 1 has unexpected type 'Worker'
[1]    24372 abort      python3 reddit_bot.py
</code>```

How can I solve this problem?

Body:
Hey here is my worker class:

class Worker(QRunnable):
    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()

        self.fn = fn
        self.args = args
        self.kwargs = kwargs

    @Slot()
    def run(self):
        self.fn(*self.args, **self.kwargs)

I use this worker like this:

def thread_profile_clear(self):

    for i in range(self.model.rowCount())[::-1]:
        if self.model.item(i).checkState() == Qt.CheckState.Checked:
            account = self.account_list[i]
            worker = Worker(self.profile_cleaner, account=account)
            self.threadpool.start(worker)

However, when I trigger the button for this function, I get this error:

  TypeError: arguments did not match any overloaded call:
  start(self, QRunnable, priority: int = 0): argument 1 has unexpected type 'Worker'
  start(self, Callable[[], None], priority: int = 0): argument 1 has unexpected type 'Worker'
[1]    24372 abort      python3 reddit_bot.py

How can I solve this problem?


问:
If math marks > 50 then this record prints otherwise give the message to try again
students.forEach

```<code>(

  student =>
{

**if(student.sub.math>50)**{

**result.push
({

name: student.name,

Subject: student.sub,

marks: Object.values(student.sub).reduce((a, b) => a + b),

Average: Object. values(student. sub).reduce((a, b) => a + b/300)**

 }

}
else
{
    console.log('Try again');
});
</code>```

console.log(result)

Body:
students.forEach

(

  student =>
{

**if(student.sub.math>50)**{

**result.push
({

name: student.name,

Subject: student.sub,

marks: Object.values(student.sub).reduce((a, b) => a + b),

Average: Object. values(student. sub).reduce((a, b) => a + b/300)**

 }

}
else
{
    console.log('Try again');
});

console.log(result)


问:
Why is this code only gives last lrow of matrix, not complete matrix?
My code in MPI using C is:

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

int main (int argc, char **argv)
{
    int num_procs;
    int rank;
    int n;
    int lst[n];
    // int lst2[n];
    int matrix[n][n];

    MPI_Status status;

    MPI_Init(&argc, &argv);
    MPI_Comm_size (MPI_COMM_WORLD, &num_procs);
    MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    //printf("%d: hello (p=%d)\n", rank, num_procs);

    n=num_procs;

    if (rank==0){

        for (int i=0;i<n;i++) {
            lst[i]=(i+1)*(rank+1);
            // printf("%d ",lst[i]);
        }
        // printf("\n");

        for (int i=0;i<n;i++){
            matrix[0][i]=lst[i];
        }

        for (int k=1;k<num_procs;k++){
            MPI_Recv(&lst,n,MPI_INT,k,0,MPI_COMM_WORLD,&status);

            for (int j=0;j<n;j++){
                matrix[k][j]=lst[j];
            }

            // for (int i=0;i<n;i++) {
            //     printf("%d ",lst[i]);
            // }
            // printf("\n");
        }

        for (int i=0;i<n;i++){
            for (int j=0;j<n;j++){
                printf("%d ", matrix[i][j]);
                if (j==n-1){printf("\n");}
            }
        }
    }
    else{
        for (int i=0;i<n;i++) {
            lst[i]=(i+1)*(rank+1);
            // printf("%d ",lst[i]);
        }
        // printf("\n");

        MPI_Send(&lst[0],n,MPI_INT,0,0,MPI_COMM_WORLD);
    }

    MPI_Finalize();
}
</code>```

This gives:

```<code>4 8 12 16
4 8 12 16
4 8 12 16
4 8 12 16
</code>```

But expected answer is:

```<code>1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
</code>```

After cross checking, I know I used MPI function correctly and my print function is also correct, so my guess is, there is some error in this part:

```<code>            for (int j=0;j<n;j++){
                matrix[k][j]=lst2[j];
            }
</code>```

But I don't know what is getting know even after so many cross checking.

Can you explain me where am I wrong and what should I do to correct it?

Body:
My code in MPI using C is:

#include <stdio.h>
#include <mpi.h>

int main (int argc, char **argv)
{
    int num_procs;
    int rank;
    int n;
    int lst[n];
    // int lst2[n];
    int matrix[n][n];

    MPI_Status status;

    MPI_Init(&argc, &argv);
    MPI_Comm_size (MPI_COMM_WORLD, &num_procs);
    MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    //printf("%d: hello (p=%d)\n", rank, num_procs);

    n=num_procs;

    if (rank==0){

        for (int i=0;i<n;i++) {
            lst[i]=(i+1)*(rank+1);
            // printf("%d ",lst[i]);
        }
        // printf("\n");

        for (int i=0;i<n;i++){
            matrix[0][i]=lst[i];
        }

        for (int k=1;k<num_procs;k++){
            MPI_Recv(&lst,n,MPI_INT,k,0,MPI_COMM_WORLD,&status);

            for (int j=0;j<n;j++){
                matrix[k][j]=lst[j];
            }

            // for (int i=0;i<n;i++) {
            //     printf("%d ",lst[i]);
            // }
            // printf("\n");
        }

        for (int i=0;i<n;i++){
            for (int j=0;j<n;j++){
                printf("%d ", matrix[i][j]);
                if (j==n-1){printf("\n");}
            }
        }
    }
    else{
        for (int i=0;i<n;i++) {
            lst[i]=(i+1)*(rank+1);
            // printf("%d ",lst[i]);
        }
        // printf("\n");

        MPI_Send(&lst[0],n,MPI_INT,0,0,MPI_COMM_WORLD);
    }

    MPI_Finalize();
}

This gives:

4 8 12 16
4 8 12 16
4 8 12 16
4 8 12 16

But expected answer is:

1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

After cross checking, I know I used MPI function correctly and my print function is also correct, so my guess is, there is some error in this part:

            for (int j=0;j<n;j++){
                matrix[k][j]=lst2[j];
            }

But I don't know what is getting know even after so many cross checking.

Can you explain me where am I wrong and what should I do to correct it?


问:
Configure visiblity / Communications-options when tweeting through TweetInvi
I successfully tweet content using TweetInvi (latest 5 version):

```<code>return await userClient.Tweets.PublishTweetAsync(new PublishTweetParameters
{
  Text = content,
  InReplyToTweetId = replyTo,
});
</code>```

Now I need to be able to change the audience that can see or interact with my tweet. In twitter I got the following options.

Audience:

Who can reply:

Both properties do not seem to be available in the PublishTweetParameters class. (And I also did not find a clue in the documentation) Am I missing something? Can it done via the factory - portion from TweetInvi?

Body:
I successfully tweet content using TweetInvi (latest 5 version):

return await userClient.Tweets.PublishTweetAsync(new PublishTweetParameters
{
  Text = content,
  InReplyToTweetId = replyTo,
});

Now I need to be able to change the audience that can see or interact with my tweet. In twitter I got the following options.

Audience:

Who can reply:

Both properties do not seem to be available in the PublishTweetParameters class. (And I also did not find a clue in the documentation) Am I missing something? Can it done via the factory - portion from TweetInvi?


问:
How do I fetch this in Laravel Firebase
I have structure like this how do I fetch this and display in table:

Here is my code:

```<code>firebase.initializeApp(firebaseConfig);
   var firebaseRef = firebase.database().ref("Accounts");
   firebaseRef.on( "value" , function(snapshot){
       snapshot.forEach(function(element){
        console.log(element.val() );

       });
   })
</code>```

Title: How do I fetch this in Laravel Firebase

Body:
I have structure like this how do I fetch this and display in table:

Here is my code:

firebase.initializeApp(firebaseConfig);
   var firebaseRef = firebase.database().ref("Accounts");
   firebaseRef.on( "value" , function(snapshot){
       snapshot.forEach(function(element){
        console.log(element.val() );

       });
   })


问:
How to save individual quantities from a .sdf file as text or .csv( for opening in Excel)?
I have a .sdf file that I wish to extract two points of data from, namely a plasma density and a position. Both quantities are present as n-dimensional arrays, but when I try to save them using df.to_csv, or np.savetxt, errors are returned, usually due to the savetxt dispatcher expecting 1D or 2D arrays, but being unable to determine what the dimensionality of the arrays that I'm trying to save is, so it's interpreting them as 0D arrays. I need both arrays to save and be openable in Excel as columns of data, so that I can plot them against each other.
If anyone has any help or advice to offer, it would be much appreciated! Thank you.</p>