问:
MassTransit is not able to produce messages to a Kafka topic in Confluent Cloud due to message size that is too large
Before I continue with my question, let me summarize which technologies I'm using first.

Current situation

Using:

MassTransit (InMemory)

Confluent Cloud (Apache Kafka Cluster is running here)

Visual Studio 2022 (IDE)

ASP.NET Core Web API (backend)

C# (backend)

JavaScript (frontend)

My question/problem I'm facing:

At the moment I try to send an image file to a Apache Kafka topic within Confluent Cloud, but I get an error that is saying that the message size is too big. I've checked the MassTransit configuration as well as the configuration of the Kafka topic in Confluent Cloud. Message sizes of at least 2.5 MB are allowed (based on my given input) to be able to go through the Kafka topic. I also did this in the MassTransit configuration. However, I'm not able to send images bigger than 1 MB to an Apache Kafka topic.

Configuration

MassTransit - Producer

```<code>services.AddMassTransit(x =>
{
    x.UsingInMemory((context, cfg) =>
    {
        cfg.ConfigureEndpoints(context);
    });

    x.AddRider(rider =>
    {
        rider.AddProducer<[...Event...]>(topicName: "<TOPIC NAME...>");

        rider.UsingKafka((riderContext, kafkaFactory) =>
        {
            kafkaFactory.SecurityProtocol = SecurityProtocol.SaslSsl;
            kafkaFactory.MessageMaxBytes = 2500000; //DOES NOT WORK...
            kafkaFactory.Host(builder.Configuration["ConfluentCloud:BootstrapServerHost"], configureHost =>
            {
                configureHost.UseSasl(saslConfig =>
                {
                    saslConfig.Mechanism = SaslMechanism.Plain;
                    saslConfig.Username = builder.Configuration["ConfluentCloud:API_KEY"];
                    saslConfig.Password = builder.Configuration["ConfluentCloud:API_SECRET"];
                });
            });
        });
    });
});
</code>```

MassTransit - Consumer

```<code>services.AddMassTransit(x =>
{
    x.UsingInMemory((context, cfg) =>
    {
        cfg.ConfigureEndpoints(context);
    });

    x.AddRider(rider =>
    {
        rider.AddConsumer<[...TOPIC_CONSUMER...]>();

        rider.UsingKafka((riderContext, kafkaFactory) =>
        {
            kafkaFactory.SecurityProtocol = SecurityProtocol.SaslSsl;
            kafkaFactory.MessageMaxBytes = 2500000; //DOES NOT WORK...
            kafkaFactory.Host(builder.Configuration["ConfluentCloud:BootstrapServerHost"], configureHost =>
            {
                configureHost.UseSasl(saslConfig =>
                {
                    saslConfig.Mechanism = SaslMechanism.Plain;
                    saslConfig.Username = builder.Configuration["ConfluentCloud:API_KEY"];
                    saslConfig.Password = builder.Configuration["ConfluentCloud:API_SECRET"];
                });
            });

            var consumerConfig = new ConsumerConfig()
            {
                GroupId = "<GROUPID>",
                AutoOffsetReset = AutoOffsetReset.Latest,
                EnableAutoCommit = false
            };

            kafkaFactory.TopicEndpoint<[...Event...]>(
                topicName: "<TOPIC NAME>", consumerConfig, kafkaTopicReceiveEndpointConfig =>
                {
                    kafkaTopicReceiveEndpointConfig.ConfigureConsumer<[...TOPIC_CONSUMER...]>(riderContext);
                });
        });
    });
});
</code>```

Confluent Cloud

Limitations confluent has is that a message can be up to 8 MB, but still even though I confiured the topic to allow at least 2.5MB it will still not produce messages to this topic when they are larger than 1 MB...

2500000 bytes = 2.5 MB (Rounded Megabytes)

Image size calculation code in JavaScript (very simple):

```<code>const fileInBytes = file.size;
const IsSmallFile = (fileInBytes / 1024 /*=kb*/ / 1024 /*=mb */) < 2; //In my frontend I use 2 MB as limitation but allow 2.5 MB through the Kafka topic which is fine.
</code>```

Actual image size calculated in frontend:

Error I'm receiving:

Can someone please tell me what is going on, because I do not get it fully and could not find any solutions online to solve it..

Body:
Before I continue with my question, let me summarize which technologies I'm using first.

Current situation

Using:

MassTransit (InMemory)

Confluent Cloud (Apache Kafka Cluster is running here)

Visual Studio 2022 (IDE)

ASP.NET Core Web API (backend)

C# (backend)

JavaScript (frontend)

My question/problem I'm facing:

At the moment I try to send an image file to a Apache Kafka topic within Confluent Cloud, but I get an error that is saying that the message size is too big. I've checked the MassTransit configuration as well as the configuration of the Kafka topic in Confluent Cloud. Message sizes of at least 2.5 MB are allowed (based on my given input) to be able to go through the Kafka topic. I also did this in the MassTransit configuration. However, I'm not able to send images bigger than 1 MB to an Apache Kafka topic.

Configuration

MassTransit - Producer

services.AddMassTransit(x =>
{
    x.UsingInMemory((context, cfg) =>
    {
        cfg.ConfigureEndpoints(context);
    });

    x.AddRider(rider =>
    {
        rider.AddProducer<[...Event...]>(topicName: "<TOPIC NAME...>");

        rider.UsingKafka((riderContext, kafkaFactory) =>
        {
            kafkaFactory.SecurityProtocol = SecurityProtocol.SaslSsl;
            kafkaFactory.MessageMaxBytes = 2500000; //DOES NOT WORK...
            kafkaFactory.Host(builder.Configuration["ConfluentCloud:BootstrapServerHost"], configureHost =>
            {
                configureHost.UseSasl(saslConfig =>
                {
                    saslConfig.Mechanism = SaslMechanism.Plain;
                    saslConfig.Username = builder.Configuration["ConfluentCloud:API_KEY"];
                    saslConfig.Password = builder.Configuration["ConfluentCloud:API_SECRET"];
                });
            });
        });
    });
});

MassTransit - Consumer

services.AddMassTransit(x =>
{
    x.UsingInMemory((context, cfg) =>
    {
        cfg.ConfigureEndpoints(context);
    });

    x.AddRider(rider =>
    {
        rider.AddConsumer<[...TOPIC_CONSUMER...]>();

        rider.UsingKafka((riderContext, kafkaFactory) =>
        {
            kafkaFactory.SecurityProtocol = SecurityProtocol.SaslSsl;
            kafkaFactory.MessageMaxBytes = 2500000; //DOES NOT WORK...
            kafkaFactory.Host(builder.Configuration["ConfluentCloud:BootstrapServerHost"], configureHost =>
            {
                configureHost.UseSasl(saslConfig =>
                {
                    saslConfig.Mechanism = SaslMechanism.Plain;
                    saslConfig.Username = builder.Configuration["ConfluentCloud:API_KEY"];
                    saslConfig.Password = builder.Configuration["ConfluentCloud:API_SECRET"];
                });
            });

            var consumerConfig = new ConsumerConfig()
            {
                GroupId = "<GROUPID>",
                AutoOffsetReset = AutoOffsetReset.Latest,
                EnableAutoCommit = false
            };

            kafkaFactory.TopicEndpoint<[...Event...]>(
                topicName: "<TOPIC NAME>", consumerConfig, kafkaTopicReceiveEndpointConfig =>
                {
                    kafkaTopicReceiveEndpointConfig.ConfigureConsumer<[...TOPIC_CONSUMER...]>(riderContext);
                });
        });
    });
});

Confluent Cloud

Limitations confluent has is that a message can be up to 8 MB, but still even though I confiured the topic to allow at least 2.5MB it will still not produce messages to this topic when they are larger than 1 MB...

2500000 bytes = 2.5 MB (Rounded Megabytes)

Image size calculation code in JavaScript (very simple):

const fileInBytes = file.size;
const IsSmallFile = (fileInBytes / 1024 /*=kb*/ / 1024 /*=mb */) < 2; //In my frontend I use 2 MB as limitation but allow 2.5 MB through the Kafka topic which is fine.

Actual image size calculated in frontend:

Error I'm receiving:

Can someone please tell me what is going on, because I do not get it fully and could not find any solutions online to solve it..


来源: stackexchange

问:
JVM crashes with EXCEPTION_ACCESS_VIOLATION (0xc0000005), points to jvm.dll
The JVM running my simulation client (for SUMO, using TraCI as libtraci) keeps crashing.
This is the command line message:

```<code>A fatal error has been detected by the Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffd7e94b97c, pid=33996, tid=26012

JRE version: OpenJDK Runtime Environment Temurin-17.0.5+8 (17.0.5+8) (build 17.0.5+8)
Java VM: OpenJDK 64-Bit Server VM Temurin-17.0.5+8 (17.0.5+8, mixed mode, sharing, tiered, compressed class ptrs, g1 gc, windows-amd64)
Problematic frame:
V  \[jvm.dll+0x80b97c\]

No core dump will be written. Minidumps are not enabled by default on client versions of Windows

An error report file with more information is saved as:
C:\\Projekte\\Bachelorarbeit\\Simulationstudie\\Simulacrum\\hs_err_pid33996.log
Compiled method (c1)  921857 2548       3       org.eclipse.sumo.libtraci.TraCINextStopData::getLane (9 bytes)
total in heap  \[0x0000016a8841b810,0x0000016a8841bb58\] = 840
relocation     \[0x0000016a8841b968,0x0000016a8841b9a0\] = 56
main code      \[0x0000016a8841b9a0,0x0000016a8841baa0\] = 256
stub code      \[0x0000016a8841baa0,0x0000016a8841bae8\] = 72
oops           \[0x0000016a8841bae8,0x0000016a8841baf0\] = 8
metadata       \[0x0000016a8841baf0,0x0000016a8841baf8\] = 8
scopes data    \[0x0000016a8841baf8,0x0000016a8841bb10\] = 24
scopes pcs     \[0x0000016a8841bb10,0x0000016a8841bb50\] = 64
dependencies   \[0x0000016a8841bb50,0x0000016a8841bb58\] = 8

Process finished with exit code 1
</code>```

The same exception access violation keeps occuring at different times during runs of my simulation. The problematic frame has so far always stated 'jvm.dll' and the compiled method is also consistently libtraci.TraCINextStopData::getLane.

I have so far tried a different JVM version and a different libtraci version with the same results and am now a little dumbstruck on what to try next.

[EDIT: I'm happy to provide the relevant log file 'hs_err_pid33996.log', but am a bit unsure of how to best include it here. Should I post the content of the entire (very long) file?]

ContentLicense: CC BY-SA 4.0

Body:
The JVM running my simulation client (for SUMO, using TraCI as libtraci) keeps crashing.
This is the command line message:

A fatal error has been detected by the Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffd7e94b97c, pid=33996, tid=26012

JRE version: OpenJDK Runtime Environment Temurin-17.0.5+8 (17.0.5+8) (build 17.0.5+8)
Java VM: OpenJDK 64-Bit Server VM Temurin-17.0.5+8 (17.0.5+8, mixed mode, sharing, tiered, compressed class ptrs, g1 gc, windows-amd64)
Problematic frame:
V  \[jvm.dll+0x80b97c\]

No core dump will be written. Minidumps are not enabled by default on client versions of Windows

An error report file with more information is saved as:
C:\\Projekte\\Bachelorarbeit\\Simulationstudie\\Simulacrum\\hs_err_pid33996.log
Compiled method (c1)  921857 2548       3       org.eclipse.sumo.libtraci.TraCINextStopData::getLane (9 bytes)
total in heap  \[0x0000016a8841b810,0x0000016a8841bb58\] = 840
relocation     \[0x0000016a8841b968,0x0000016a8841b9a0\] = 56
main code      \[0x0000016a8841b9a0,0x0000016a8841baa0\] = 256
stub code      \[0x0000016a8841baa0,0x0000016a8841bae8\] = 72
oops           \[0x0000016a8841bae8,0x0000016a8841baf0\] = 8
metadata       \[0x0000016a8841baf0,0x0000016a8841baf8\] = 8
scopes data    \[0x0000016a8841baf8,0x0000016a8841bb10\] = 24
scopes pcs     \[0x0000016a8841bb10,0x0000016a8841bb50\] = 64
dependencies   \[0x0000016a8841bb50,0x0000016a8841bb58\] = 8

Process finished with exit code 1

The same exception access violation keeps occuring at different times during runs of my simulation. The problematic frame has so far always stated 'jvm.dll' and the compiled method is also consistently libtraci.TraCINextStopData::getLane.

I have so far tried a different JVM version and a different libtraci version with the same results and am now a little dumbstruck on what to try next.

[EDIT: I'm happy to provide the relevant log file 'hs_err_pid33996.log', but am a bit unsure of how to best include it here. Should I post the content of the entire (very long) file?]


问:
return response of createProxyMiddleware
I can't return the response of my middleware proxy request in node.js.

```<code>const express = require("express");
const morgan = require("morgan");
const { createProxyMiddleware } = require("http-proxy-middleware");
</code>```
```<code>app.use(
  "/translate",
  function (req, res){
    createProxyMiddleware({
        target: API_SERVICE_URL + "&text=" + req.query.text + "&target_lang=" +
                req.query.target_lang,
        changeOrigin: true,
        })
  }
);
</code>```

I want to return the response of createProxymiddleware on /translate

I tried the target in my browser and it worked. (It gave me a response)

Body:
I can't return the response of my middleware proxy request in node.js.

const express = require("express");
const morgan = require("morgan");
const { createProxyMiddleware } = require("http-proxy-middleware");

app.use(
  "/translate",
  function (req, res){
    createProxyMiddleware({
        target: API_SERVICE_URL + "&text=" + req.query.text + "&target_lang=" +
                req.query.target_lang,
        changeOrigin: true,
        })
  }
);

I want to return the response of createProxymiddleware on /translate

I tried the target in my browser and it worked. (It gave me a response)


问:
How to set options using JavaScript with bootstrap-select?
I am trying to set options for the select element using JavaScript and not data attributes with bootstrap-select: https://developer.snapappointments.com/bootstrap-select/options/

But the docs don't show the syntax to set the options with JavaScript, only with data-attributes.


问:
Extract recurring CSV files from S3 bucket and transform the data using Glue job
I am working on a POC where the requirement is to transform multiple CSV files stored in s3 bucket using AWS Glue. I need some help regarding reading the data from s3 bucket because the data format is CSV and data is loaded multiple times in a day. 1 Load will consist of 50 CSV files with different schema and in 1 day 5 to 6 similar 50 CSV files is loaded into s3 bucket. Each file may have similar transformation or transformation may differ.

Questions :
1)How can I read only latest files /objects from particular folder.
2)If data is cumulative (Todays data will include all previous days data), how to extract only current data..?(no date column inside csv file).


问:
Serializing list of Files with gson not working in Android 12+ (API 32, 33)
I do have an object with a list of Files (java.io.File):

```<code>class NewRequestBody {
    val files: MutableList<File> = ArrayList()
}
</code>```

I need that object in my WorkManager class, so I use Gson to convert it to Json and add it to the WorkRequest.Builder as InputData:

```<code>val inputData = Data.Builder().putString(BODY_KEY, Gson().toJson(body)).build()

val myWorker = OneTimeWorkRequest.Builder(MyWorker::class.java)
      .setInputData(inputData)
      .build()
</code>```

Then in my WorkManager class I'm converting it back:

```<code>val body = gson.fromJson(inputData.getString(BODY_KEY), NewRequestBody::class.java)
</code>```

So far, with compileSdkVersion 30, that worked perfectly fine. The json hold this information for the files:

```<code>"files": [
    {
        "path": "path_to_the_file"
    }
]
</code>```

However, after updating the targetSdkVersion and compileSdkVersion to 33, that doesn't work anymore. The json now holds just an empty array:

```<code>"files": [
    {}
]
</code>```

Any idea what this is the case and how to fix it?

Body:
I do have an object with a list of Files (java.io.File):

class NewRequestBody {
    val files: MutableList<File> = ArrayList()
}

I need that object in my WorkManager class, so I use Gson to convert it to Json and add it to the WorkRequest.Builder as InputData:

val inputData = Data.Builder().putString(BODY_KEY, Gson().toJson(body)).build()

val myWorker = OneTimeWorkRequest.Builder(MyWorker::class.java)
      .setInputData(inputData)
      .build()

Then in my WorkManager class I'm converting it back:

val body = gson.fromJson(inputData.getString(BODY_KEY), NewRequestBody::class.java)

So far, with compileSdkVersion 30, that worked perfectly fine. The json hold this information for the files:

"files": [
    {
        "path": "path_to_the_file"
    }
]

However, after updating the targetSdkVersion and compileSdkVersion to 33, that doesn't work anymore. The json now holds just an empty array:

"files": [
    {}
]

Any idea what this is the case and how to fix it?


问:
Flutter Process.run() with runInShell: true runs the command in shell but when compiled to exe opens a new window
I have a function that uses the Windows ping command:

```<code>ProcessResult process = await Process.run(
  'ping',
  ['-n', '1', '-l', '1', '-w', '100', host.name],
  runInShell: true,
);
</code>```

When I run it in Visual Studio Code it works normally. But When I compile it to Windows executable and it runs my function, it opens a new window of my app instead of opening cmd in the background and executing the ping command in it.

Is there a reason and possibly a solution why it does that?

Body:
I have a function that uses the Windows ping command:

ProcessResult process = await Process.run(
  'ping',
  ['-n', '1', '-l', '1', '-w', '100', host.name],
  runInShell: true,
);

When I run it in Visual Studio Code it works normally. But When I compile it to Windows executable and it runs my function, it opens a new window of my app instead of opening cmd in the background and executing the ping command in it.

Is there a reason and possibly a solution why it does that?


问:
Java hibernate foreign key long id convert to entity
I am getting transactionId as longs, it is possible somehow to convert this id to entity without using repository.findById() ?

'''

```<code>class Report {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, updatable = false)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "transaction_id")
private Transaction tr;

public Long getId() {
    return id;
}

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

public void setTr(Long transactionId) {
// magically id converts id to entity tr
}
</code>```

'''

Body:
I am getting transactionId as longs, it is possible somehow to convert this id to entity without using repository.findById() ?

'''

class Report {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, updatable = false)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "transaction_id")
private Transaction tr;

public Long getId() {
    return id;
}

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

public void setTr(Long transactionId) {
// magically id converts id to entity tr
}

'''


问:
VSIX group id context for json files C#
I'm building a Visual studio extension specific for JSON files. I want the extension logic to be usable when you right click in the editor view and get the menu with copy, past etc.
For non json files it works if I assign my menugroup to the parent guidSHLMainMenu and id IDM_VS_CTXT_CODEWIN but the json files will not show my menu item in the menu list.

```<code> <Groups>
      <Group guid="guidVSIXProject1PackageCmdSet" id="MyMenuGroup" priority="0x0400">
          <Parent guid="guidSHLMainMenu" id="IDM_VS_CTXT_CODEWIN"/>
      </Group>
    </Groups>
</code>```

I'm using visual studio 2022 (17.4) who knows the correct ID for the JSON menu?

Title: VSIX group id context for json files C#

Body:
I'm building a Visual studio extension specific for JSON files. I want the extension logic to be usable when you right click in the editor view and get the menu with copy, past etc.
For non json files it works if I assign my menugroup to the parent guidSHLMainMenu and id IDM_VS_CTXT_CODEWIN but the json files will not show my menu item in the menu list.

 <Groups>
      <Group guid="guidVSIXProject1PackageCmdSet" id="MyMenuGroup" priority="0x0400">
          <Parent guid="guidSHLMainMenu" id="IDM_VS_CTXT_CODEWIN"/>
      </Group>
    </Groups>

I'm using visual studio 2022 (17.4) who knows the correct ID for the JSON menu?


问:
How do I read a Roberta tokenizer from Google Cloud Storage?
I have saved a Robert tokenizer (autotokenizer) which I have used for a Roberta model to a GCS bucket. I get the error:

```<code>HFValidationError: Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are forbidden, '-' and '.' cannot start or end the name, max length is 96: '[<_io.BytesIO object at 0x7f3cbf1db770>, <_io.BytesIO object at 0x7f3cb5c61a70>, <_io.BytesIO object at 0x7f3cb5c611d0>]'.
</code>```

I have saved the tokenizer to a Google Cloud Storage bucket where it appears as three json files ("special_tokens_map.json", "tokenizer.json", and "tokenizer_config.json"). How can I load them so I can use them for retraining/inference (for example within a Vertex AI notebook). I am trying to load them in the same way as the model, by downloading each blob (json file) as a string and then converted those strings using BytesIO. I put a list containing those converted strings into AutoTokenizer.from_pretrained().

```<code>tokeniser_parts_names=["special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"]

tokeniser_parts=[BytesIO(__bucket.get_blob(tokeniser_folder+part).download_as_string()) for part in tokeniser_parts_names]

tokeniser = AutoTokenizer.from_pretrained(tokeniser_parts)
</code>```

The model loads correctly but the tokeniser doesn't load. I realise you're supposed to put a directory in the .from_pretrained method, but how do I do this using a GCS bucket?

Body:
I have saved a Robert tokenizer (autotokenizer) which I have used for a Roberta model to a GCS bucket. I get the error:

HFValidationError: Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are forbidden, '-' and '.' cannot start or end the name, max length is 96: '[<_io.BytesIO object at 0x7f3cbf1db770>, <_io.BytesIO object at 0x7f3cb5c61a70>, <_io.BytesIO object at 0x7f3cb5c611d0>]'.

I have saved the tokenizer to a Google Cloud Storage bucket where it appears as three json files ("special_tokens_map.json", "tokenizer.json", and "tokenizer_config.json"). How can I load them so I can use them for retraining/inference (for example within a Vertex AI notebook). I am trying to load them in the same way as the model, by downloading each blob (json file) as a string and then converted those strings using BytesIO. I put a list containing those converted strings into AutoTokenizer.from_pretrained().

tokeniser_parts_names=["special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"]

tokeniser_parts=[BytesIO(__bucket.get_blob(tokeniser_folder+part).download_as_string()) for part in tokeniser_parts_names]

tokeniser = AutoTokenizer.from_pretrained(tokeniser_parts)

The model loads correctly but the tokeniser doesn't load. I realise you're supposed to put a directory in the .from_pretrained method, but how do I do this using a GCS bucket?


问:
Order Fill alerts are triggering multiple times
Hello fellow traders,

I dont know why but my Order Fill alerts are triggering quite inconsistently. For some Assets they are working as expected and for another assets, they are triggering multiple times or with great delay (few minutes).
The strategy itself shows the correct entries and stop losses ...

Anyone having similar issues ?

I am Automation QA specialist with experience in C# and I have no idea why is this happening...

There is not much room for trying as the Alerts doesn't have many settings.


问:
How to override two methods of 2 parents that inherits same classes with virtual methods in C++
Consider the next Example:

```<code>#include <iostream>

class Base{
    public:
    virtual void f() {
        std::cout << "Base::f()" << std::endl;
    }
};

class Derived1 : public Base
{
    public:
    virtual void f() override
    {
        Base::f();
        std::cout << "Derived1::f()" << std::endl;
    }
};

class Derived2 : public Base
{
    public:
    virtual void f() override
    {
        Base::f();
        std::cout << "Derived2::f()" << std::endl;
    }
};

class DerivedUnion : public Derived1, public Derived2
{
    public:
    void Derived1::f() override { // Errors

    }

    void Derived2::f() override { // Errors

    }

};
</code>```

is there some how that allow me to override the
Derived2::f()
in the
DerivedUnion{}
class?

I have tried to target specific one with namespace like style, but it didnt worked:

```<code>class DerivedUnion : public Derived1, public Derived2
   // Notice DerivedUnion is not a Union, name is for
   // Demostration Purposes, not intended to create
   // A union Behavior
{
    public:
    virtual void Derived1::f() override; // Compile error
    virtual void Derived2::f() override; // Compile error
    virtual void f() override; // Not a compile error, but both Derived1 and Derived2 call same
};

void UseBase(Base* b){
       b->f(); // expected Ambiguos call compile time
       b->DerivedUnion::f() // Expected overriden DerivedUnion::f() to be called
       b->Derived1::f(); // Expected overriden Derived1::f() to be called
       b->Derived2::f(); // Expected overriden Derived2::f() to be called
}
</code>```

An Example of it could be this one, code is self explanatory:

```<code>#include <iostream>

/* Interface Drawable */
class IDrawable {
    public:

    virtual void Draw() {};
};

/* Asume this is a button from one kind of bar */
class ButtonA : public IDrawable{
    public:
    virtual void Draw() override {
        std::cout << "ButtonA::Draw()" << std::endl;
    }
};

/* Asume this is a button from another kind of bar */
class ButtonB : public IDrawable{
    public:
    virtual void Draw() override {
        std::cout << "ButtonB::Draw()" << std::endl;
    }
};

/**
Where Component X is a representation that will represent 2 buttons types
*/
class ComponentX : public ButtonA, public ButtonB {
    public:
    void ButtonA::Draw() override { // cannot define member function ‘ButtonA::Draw’ within ‘ComponentX’
        ButtonA::Draw();
        std::cout << "Custom ComponentX::Draw()" << std::endl;
    }

    void ButtonB::Draw() override { // error: cannot define member function ‘ButtonB::Draw’ within ‘ComponentX’
        ButtonB::Draw();
        std::cout << "Custom ComponentX::Draw()" << std::endl;
    }
};

class ComponentY : public ButtonA, public ButtonB {
    public:
    void ButtonA::Draw() override { // cannot define member function ‘ButtonA::Draw’ within ‘ComponentY’
        ButtonA::Draw();
        std::cout << "Custom ComponentY::Draw()" << std::endl;
    }

    void ButtonB::Draw() override { // error: cannot define member function ‘ButtonB::Draw’ within ‘ComponentY’
        ButtonB::Draw();
        std::cout << "Custom ComponentY::Draw()" << std::endl;
    }
};

using namespace std;

void DummyAddButtonA(ButtonA* pBtnA)
{
    //Add it somewhere ...
}

void DummyAddButtonB(ButtonB* pBtnB)
{
    //Add it somewhere ...
}

int main()
{
    ComponentX compx;
    ComponentY compy;

    DummyAddButtonA(&compx);
    DummyAddButtonB(&compx);

    DummyAddButtonA(&compy);
    DummyAddButtonB(&compy);

    return 0;
}
</code>```

Body:
Consider the next Example:

#include <iostream>

class Base{
    public:
    virtual void f() {
        std::cout << "Base::f()" << std::endl;
    }
};

class Derived1 : public Base
{
    public:
    virtual void f() override
    {
        Base::f();
        std::cout << "Derived1::f()" << std::endl;
    }
};

class Derived2 : public Base
{
    public:
    virtual void f() override
    {
        Base::f();
        std::cout << "Derived2::f()" << std::endl;
    }
};

class DerivedUnion : public Derived1, public Derived2
{
    public:
    void Derived1::f() override { // Errors

    }

    void Derived2::f() override { // Errors

    }

};

is there some how that allow me to override the
Derived2::f()
in the
DerivedUnion{}
class?

I have tried to target specific one with namespace like style, but it didnt worked:

class DerivedUnion : public Derived1, public Derived2
   // Notice DerivedUnion is not a Union, name is for
   // Demostration Purposes, not intended to create
   // A union Behavior
{
    public:
    virtual void Derived1::f() override; // Compile error
    virtual void Derived2::f() override; // Compile error
    virtual void f() override; // Not a compile error, but both Derived1 and Derived2 call same
};

void UseBase(Base* b){
       b->f(); // expected Ambiguos call compile time
       b->DerivedUnion::f() // Expected overriden DerivedUnion::f() to be called
       b->Derived1::f(); // Expected overriden Derived1::f() to be called
       b->Derived2::f(); // Expected overriden Derived2::f() to be called
}

An Example of it could be this one, code is self explanatory:

#include <iostream>

/* Interface Drawable */
class IDrawable {
    public:

    virtual void Draw() {};
};

/* Asume this is a button from one kind of bar */
class ButtonA : public IDrawable{
    public:
    virtual void Draw() override {
        std::cout << "ButtonA::Draw()" << std::endl;
    }
};

/* Asume this is a button from another kind of bar */
class ButtonB : public IDrawable{
    public:
    virtual void Draw() override {
        std::cout << "ButtonB::Draw()" << std::endl;
    }
};

/**
Where Component X is a representation that will represent 2 buttons types
*/
class ComponentX : public ButtonA, public ButtonB {
    public:
    void ButtonA::Draw() override { // cannot define member function ‘ButtonA::Draw’ within ‘ComponentX’
        ButtonA::Draw();
        std::cout << "Custom ComponentX::Draw()" << std::endl;
    }

    void ButtonB::Draw() override { // error: cannot define member function ‘ButtonB::Draw’ within ‘ComponentX’
        ButtonB::Draw();
        std::cout << "Custom ComponentX::Draw()" << std::endl;
    }
};

class ComponentY : public ButtonA, public ButtonB {
    public:
    void ButtonA::Draw() override { // cannot define member function ‘ButtonA::Draw’ within ‘ComponentY’
        ButtonA::Draw();
        std::cout << "Custom ComponentY::Draw()" << std::endl;
    }

    void ButtonB::Draw() override { // error: cannot define member function ‘ButtonB::Draw’ within ‘ComponentY’
        ButtonB::Draw();
        std::cout << "Custom ComponentY::Draw()" << std::endl;
    }
};

using namespace std;

void DummyAddButtonA(ButtonA* pBtnA)
{
    //Add it somewhere ...
}

void DummyAddButtonB(ButtonB* pBtnB)
{
    //Add it somewhere ...
}

int main()
{
    ComponentX compx;
    ComponentY compy;

    DummyAddButtonA(&compx);
    DummyAddButtonB(&compx);

    DummyAddButtonA(&compy);
    DummyAddButtonB(&compy);

    return 0;
}


问:
Is there any way to modify the rows that a forest plot ref_line is displayed in? for R forestplotter
I have been creating a very busy Forest plot using R's forestplotter package and I am happy with everything except for 1 very small section. I have added an extra row to my data set for subheadings but the CI column reference line seems to go into the blank subheading row.

I have tried all manner of things including removing the reference line and just trying to specify a vertline, but again, I can not control the number of rows it appears in.

Could someone help me please? My code, input and output is below:

My input is:

My code for the forest plot is as follows:

```<code>    # Set-up theme
tm <- forest_theme(base_size = 10,
                   # Confidence interval point shape, line type/color/width
                   ci_pch = 15,
                   ci_col = "#762a83",
                   ci_fill = "black",
                   ci_alpha = 0.8,
                   ci_lty = 1,
                   ci_lwd = 1.5,
                   ci_Theight = 0.2, # Set an T end at the end of CI
                   # Reference line width/type/color
                   refline_lwd = 1,
                   refline_lty = "dashed",
                   refline_col = "grey20",
                   # Vertical line width/type/color
                   vertline_lwd = 1,
                   vertline_lty = "dashed",
                   vertline_col = "grey20",
                   # Change summary color for filling and borders
                   summary_fill = "#4575b4",
                   summary_col = "#4575b4",
                   # Footnote font size/face/color
                   footnote_cex = 0.6,
                   footnote_fontface = "italic",
                   footnote_col = "blue")

p1 <- forest(usoccrp[,c(1,39,40,33,38,41,32,37,42,31,36,44,30,35,43,29,34,45,28)],
            est = list(usoccrp$est6,
                       usoccrp$est5,
                       usoccrp$est4,
                       usoccrp$est3,
                       usoccrp$est2,
                       usoccrp$est1),
            lower = list(usoccrp$ci.lo6,
                         usoccrp$ci.lo5,
                         usoccrp$ci.lo4,
                         usoccrp$ci.lo3,
                         usoccrp$ci.lo2,
                         usoccrp$ci.lo1),
            upper = list(usoccrp$ci.hi6,
                         usoccrp$ci.hi5,
                         usoccrp$ci.hi4,
                         usoccrp$ci.hi3,
                         usoccrp$ci.hi2,
                         usoccrp$ci.hi1),
            ci_column = c(3,6,9,12,15,18),
            xlim = list(c(-0.08,0.08),
                        c(-0.015, 0.015),
                        c(-0.015, 0.015),
                        c(-0.015, 0.015),
                        c(-0.015, 0.015),
                        c(-0.08,0.08)),
            ticks_at = list(c(-0.08,0,0.08),
                            c(-0.01, 0, 0.01),
                            c(-0.01, 0, 0.01),
                            c(-0.01, 0, 0.01),
                            c(-0.01, 0, 0.01),
                            c(-0.08,0,0.08)),
            ref_line =  0,
            nudge_y = 0.1,
            title = "CRP",
            theme = tm)
p1 <- add_border(p1, row = 0:8, col = c(4,7,10,13,16), where = "right",
                 gp = gpar(lwd=1, lty = "solid"))
# ADD DASHED BORDER TO SEPERATE FACTORS
p1 <- add_border(p1, row = 1:8, col = 1, where = "right",
                 gp = gpar(lwd=1, lty = "dashed"))
p1 <- edit_plot(p1,
                row = 1,
                gp = gpar(fontface = "bold"))
plot(p1)
</code>```

And my output is this (I have highlighted with blue circles the bits that I want to remove)

Could someone please help me work out how to specify the length of the ref_lines? e.g., row = 2:8

Body:
I have been creating a very busy Forest plot using R's forestplotter package and I am happy with everything except for 1 very small section. I have added an extra row to my data set for subheadings but the CI column reference line seems to go into the blank subheading row.

I have tried all manner of things including removing the reference line and just trying to specify a vertline, but again, I can not control the number of rows it appears in.

Could someone help me please? My code, input and output is below:

My input is:

My code for the forest plot is as follows:

    # Set-up theme
tm <- forest_theme(base_size = 10,
                   # Confidence interval point shape, line type/color/width
                   ci_pch = 15,
                   ci_col = "#762a83",
                   ci_fill = "black",
                   ci_alpha = 0.8,
                   ci_lty = 1,
                   ci_lwd = 1.5,
                   ci_Theight = 0.2, # Set an T end at the end of CI
                   # Reference line width/type/color
                   refline_lwd = 1,
                   refline_lty = "dashed",
                   refline_col = "grey20",
                   # Vertical line width/type/color
                   vertline_lwd = 1,
                   vertline_lty = "dashed",
                   vertline_col = "grey20",
                   # Change summary color for filling and borders
                   summary_fill = "#4575b4",
                   summary_col = "#4575b4",
                   # Footnote font size/face/color
                   footnote_cex = 0.6,
                   footnote_fontface = "italic",
                   footnote_col = "blue")

p1 <- forest(usoccrp[,c(1,39,40,33,38,41,32,37,42,31,36,44,30,35,43,29,34,45,28)],
            est = list(usoccrp$est6,
                       usoccrp$est5,
                       usoccrp$est4,
                       usoccrp$est3,
                       usoccrp$est2,
                       usoccrp$est1),
            lower = list(usoccrp$ci.lo6,
                         usoccrp$ci.lo5,
                         usoccrp$ci.lo4,
                         usoccrp$ci.lo3,
                         usoccrp$ci.lo2,
                         usoccrp$ci.lo1),
            upper = list(usoccrp$ci.hi6,
                         usoccrp$ci.hi5,
                         usoccrp$ci.hi4,
                         usoccrp$ci.hi3,
                         usoccrp$ci.hi2,
                         usoccrp$ci.hi1),
            ci_column = c(3,6,9,12,15,18),
            xlim = list(c(-0.08,0.08),
                        c(-0.015, 0.015),
                        c(-0.015, 0.015),
                        c(-0.015, 0.015),
                        c(-0.015, 0.015),
                        c(-0.08,0.08)),
            ticks_at = list(c(-0.08,0,0.08),
                            c(-0.01, 0, 0.01),
                            c(-0.01, 0, 0.01),
                            c(-0.01, 0, 0.01),
                            c(-0.01, 0, 0.01),
                            c(-0.08,0,0.08)),
            ref_line =  0,
            nudge_y = 0.1,
            title = "CRP",
            theme = tm)
p1 <- add_border(p1, row = 0:8, col = c(4,7,10,13,16), where = "right",
                 gp = gpar(lwd=1, lty = "solid"))
# ADD DASHED BORDER TO SEPERATE FACTORS
p1 <- add_border(p1, row = 1:8, col = 1, where = "right",
                 gp = gpar(lwd=1, lty = "dashed"))
p1 <- edit_plot(p1,
                row = 1,
                gp = gpar(fontface = "bold"))
plot(p1)

And my output is this (I have highlighted with blue circles the bits that I want to remove)

Could someone please help me work out how to specify the length of the ref_lines? e.g., row = 2:8


问:
How to add Document with Custom ID to firestore jetpack compose kotlin
Is there any chance to add a document to firestore collection with custom generated id, not the id generated by firestore engine?

in Kotlin jetpack compose android development how you would do it?


问:
VBA Copy sheet and include macros associated with the sheet
I have a template sheet that I copy with the following code where strNameOfSheetToCreate is a string captured from a cell :

```<code>Dim Wb As Workbook: Set Wb = ThisWorkbook
Wb.Sheets.Add.Name = strNameOfSheetToCreate

Dim SheetSource As Worksheet
Dim SheetTarget As Worksheet

Set SheetSource = Wb.Worksheets("Project Template")
Set SheetTarget = Wb.Worksheets(strNameOfSheetToCreate)

'copy all formulas and conditional formatting from template
SheetSource.Cells.Copy
SheetTarget.Cells.PasteSpecial Paste:=xlPasteAllMergingConditionalFormats
</code>```

This copies the sheet correctly but doesn't copy over any of the macro code from the template sheet, such as the activate macro as below:

```<code>Private Sub Worksheet_Activate()
        Dim ThisSheet As Worksheet
        Set ThisSheet = ActiveSheet
        ThisSheet.Range("H40").Formula2 = "=FILTER(FILTER(AllStaffProjectAllocationTbl,AllStaffProjectAllocationTbl[Project Code Name]=B2), {1,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0,0})"
End Sub
</code>```

Is there a way to also copy over the macro code to the new sheet?

Body:
I have a template sheet that I copy with the following code where strNameOfSheetToCreate is a string captured from a cell :

Dim Wb As Workbook: Set Wb = ThisWorkbook
Wb.Sheets.Add.Name = strNameOfSheetToCreate

Dim SheetSource As Worksheet
Dim SheetTarget As Worksheet

Set SheetSource = Wb.Worksheets("Project Template")
Set SheetTarget = Wb.Worksheets(strNameOfSheetToCreate)

'copy all formulas and conditional formatting from template
SheetSource.Cells.Copy
SheetTarget.Cells.PasteSpecial Paste:=xlPasteAllMergingConditionalFormats

This copies the sheet correctly but doesn't copy over any of the macro code from the template sheet, such as the activate macro as below:

Private Sub Worksheet_Activate()
        Dim ThisSheet As Worksheet
        Set ThisSheet = ActiveSheet
        ThisSheet.Range("H40").Formula2 = "=FILTER(FILTER(AllStaffProjectAllocationTbl,AllStaffProjectAllocationTbl[Project Code Name]=B2), {1,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0,0})"
End Sub

Is there a way to also copy over the macro code to the new sheet?


问:
What is the type of selectionchange listener event parameter?
What is the type of selectionchange listener event parameter?

// Trying to avoid using any
const handleSelectionChange = (event: any) => {
  console.log(event)
}

document.addEventListener("selectionchange", handleSelectionChange)
```

UPDATE: apparently, Event is the right type.

Body:
What is the type of selectionchange listener event parameter?

// Trying to avoid using any
const handleSelectionChange = (event: any) => {
  console.log(event)
}

document.addEventListener("selectionchange", handleSelectionChange)

UPDATE: apparently, Event is the right type.


问:
add var with alphanumeric code in order of value
I have data from counties and for a peudonymized plot I want to add an alphanumeric code in the order of a sort variable. It is not so important what the code will look like, but I want to have a letter at the beginning so that it will not be confused with the numeric information in the chart.
In the original data, I have more than 26 observations. Therefore the code needs to have two digits.

```<code># example data

county <- c("all", "Berkshire", "Blackpool", "Bournemouth", "Bristol",
             "Cambridgeshire", "Cheshire", "Devon", "Dorset", "Essex",
             "Gloucestershire", "Hampshire", "Kent", "Lincolnshire",
             "Norfolk", "Oxfordshire", "Suffolk", "Wiltshire", "Worcestershire",
             "Yorkshire")
sort <- c(-2, 16.5, 400, 331, 375.2, 13.1, 400, 376.4,
          128.3, 400, 48.6, 6.7, 113.5, 43.7, 295.9,400,
          261.5, 100, 183.3, 400)

df <- data.frame(county, sort)
</code>```

This is how I would like the result to look like:

Body:
I have data from counties and for a peudonymized plot I want to add an alphanumeric code in the order of a sort variable. It is not so important what the code will look like, but I want to have a letter at the beginning so that it will not be confused with the numeric information in the chart.
In the original data, I have more than 26 observations. Therefore the code needs to have two digits.

# example data

county <- c("all", "Berkshire", "Blackpool", "Bournemouth", "Bristol",
             "Cambridgeshire", "Cheshire", "Devon", "Dorset", "Essex",
             "Gloucestershire", "Hampshire", "Kent", "Lincolnshire",
             "Norfolk", "Oxfordshire", "Suffolk", "Wiltshire", "Worcestershire",
             "Yorkshire")
sort <- c(-2, 16.5, 400, 331, 375.2, 13.1, 400, 376.4,
          128.3, 400, 48.6, 6.7, 113.5, 43.7, 295.9,400,
          261.5, 100, 183.3, 400)

df <- data.frame(county, sort)

This is how I would like the result to look like:


问:
How run trained tflite model for urbansound 8k dataset using python
I have trained a audio classification model URBANSOUND8k and converted it into tflite file how can we run the model for diffrent audio other than dataset

code to run tflite model file . Audio Classification


问:
Unable to process Paytm in django rest framework
Im trying to integrate paytm with django rest framework. But don't know why I get checksum mismatch. That is while initiating payment app a checksum is generated but when verifying the checksum it is different.
#Views - initiating payment

```<code>            context = {
                "MID": settings.PAYTM_MERCHANT_ID,
                "INDUSTRY_TYPE_ID": settings.PAYTM_INDUSTRY_TYPE_ID,
                "WEBSITE": settings.PAYTM_WEBSITE,
                "CHANNEL_ID": settings.PAYTM_CHANNEL_ID,
                "CALLBACK_URL": settings.PAYTM_CALLBACK_URL,
                "ORDER_ID": str(order.order_number),
                "TXN_AMOUNT": str(amount),
                "CUST_ID": str(user.id),
            }
            context["CHECKSUMHASH"] = Checksum.generate_checksum(
                context, settings.PAYTM_MERCHANT_KEY
            )
            return Response({"context": context})
</code>```

After initiating it  Iam sending the CHECKSUMHASH in post request along with MID, ORDERID through postman and check for the checksum validation

```<code>def VerifyPaytmResponse(response):
    response_dict = dict()
    print('in VerifyPaytmResponse 0')
    if response.method == "POST":
        data_dict = dict()
        form = response.POST
        for key in form.keys():
            data_dict[key] = form[key]
            print('ENTERING HERER')
            if key == 'CHECKSUMHASH':
                check_sum = data_dict[key]
        MID = data_dict['MID']
        ORDERID = data_dict['ORDERID']
        verify = Checksum.verify_checksum(
            data_dict, settings.PAYTM_MERCHANT_KEY, check_sum)
        if verify:
            STATUS_URL = settings.PAYTM_TRANSACTION_STATUS_URL
            headers = {
                'Content-Type': 'application/json',
            }
            data = '{"MID":"%s","ORDERID":"%s"}' % (MID, ORDERID)
            check_resp = requests.post(
                STATUS_URL, data=data, headers=headers).json()
            if check_resp['STATUS'] == 'TXN_SUCCESS':
                response_dict['verified'] = True
                response_dict['paytm'] = check_resp
                return (response_dict)
            else:
                response_dict['verified'] = False
                response_dict['paytm'] = check_resp
                return (response_dict)
        else:
            response_dict['verified'] = False
            return (response_dict)
    response_dict['verified'] = False
    return response_dict

</code>```

This is getting failed because the function to verify checksum is not getting matched. Below is the verifying function

```<code>def generate_checksum(param_dict, merchant_key, salt=None):
    params_string = __get_param_string__(param_dict)
    salt = salt if salt else __id_generator__(4)
    final_string = '%s|%s' % (params_string, salt)

    hasher = hashlib.sha256(final_string.encode())
    hash_string = hasher.hexdigest()

    hash_string += salt

    return __encode__(hash_string, IV, merchant_key)

def verify_checksum(param_dict, merchant_key, checksum):
    # Remove checksum
    if 'CHECKSUMHASH' in param_dict:
        param_dict.pop('CHECKSUMHASH')

    # Get salt
    paytm_hash = __decode__(checksum, IV, merchant_key)

    salt = paytm_hash[-4:]
    return calculated_checksum == checksum
</code>```

In above function verify_checksum the calculated_checksum  is not equal to the checksum. This is why verification getting failed.

Body:
Im trying to integrate paytm with django rest framework. But don't know why I get checksum mismatch. That is while initiating payment app a checksum is generated but when verifying the checksum it is different.
#Views - initiating payment

            context = {
                "MID": settings.PAYTM_MERCHANT_ID,
                "INDUSTRY_TYPE_ID": settings.PAYTM_INDUSTRY_TYPE_ID,
                "WEBSITE": settings.PAYTM_WEBSITE,
                "CHANNEL_ID": settings.PAYTM_CHANNEL_ID,
                "CALLBACK_URL": settings.PAYTM_CALLBACK_URL,
                "ORDER_ID": str(order.order_number),
                "TXN_AMOUNT": str(amount),
                "CUST_ID": str(user.id),
            }
            context["CHECKSUMHASH"] = Checksum.generate_checksum(
                context, settings.PAYTM_MERCHANT_KEY
            )
            return Response({"context": context})

After initiating it  Iam sending the CHECKSUMHASH in post request along with MID, ORDERID through postman and check for the checksum validation

def VerifyPaytmResponse(response):
    response_dict = dict()
    print('in VerifyPaytmResponse 0')
    if response.method == "POST":
        data_dict = dict()
        form = response.POST
        for key in form.keys():
            data_dict[key] = form[key]
            print('ENTERING HERER')
            if key == 'CHECKSUMHASH':
                check_sum = data_dict[key]
        MID = data_dict['MID']
        ORDERID = data_dict['ORDERID']
        verify = Checksum.verify_checksum(
            data_dict, settings.PAYTM_MERCHANT_KEY, check_sum)
        if verify:
            STATUS_URL = settings.PAYTM_TRANSACTION_STATUS_URL
            headers = {
                'Content-Type': 'application/json',
            }
            data = '{"MID":"%s","ORDERID":"%s"}' % (MID, ORDERID)
            check_resp = requests.post(
                STATUS_URL, data=data, headers=headers).json()
            if check_resp['STATUS'] == 'TXN_SUCCESS':
                response_dict['verified'] = True
                response_dict['paytm'] = check_resp
                return (response_dict)
            else:
                response_dict['verified'] = False
                response_dict['paytm'] = check_resp
                return (response_dict)
        else:
            response_dict['verified'] = False
            return (response_dict)
    response_dict['verified'] = False
    return response_dict

This is getting failed because the function to verify checksum is not getting matched. Below is the verifying function

def generate_checksum(param_dict, merchant_key, salt=None):
    params_string = __get_param_string__(param_dict)
    salt = salt if salt else __id_generator__(4)
    final_string = '%s|%s' % (params_string, salt)

    hasher = hashlib.sha256(final_string.encode())
    hash_string = hasher.hexdigest()

    hash_string += salt

    return __encode__(hash_string, IV, merchant_key)

def verify_checksum(param_dict, merchant_key, checksum):
    # Remove checksum
    if 'CHECKSUMHASH' in param_dict:
        param_dict.pop('CHECKSUMHASH')

    # Get salt
    paytm_hash = __decode__(checksum, IV, merchant_key)

    salt = paytm_hash[-4:]
    return calculated_checksum == checksum

In above function verify_checksum the calculated_checksum  is not equal to the checksum. This is why verification getting failed.


问:
Why react-pdf freeze app while rendering?
I'm trying to render basic example from react-pdf official website (https://react-pdf.org/)
but app is freezing while i'm trying to use one of rendering options (i tried PDFViever, usePDF hook, PDFDownloadLink).

When im trying the same example on codesandbox.io everything works fine.

Can someone explain why that could happen and whats possible solutions?

Example code:

import {
  usePDF,
  Page,
  Text,
  View,
  Document,
  StyleSheet,
} from "@react-pdf/renderer";

const styles = StyleSheet.create({
  page: {
    flexDirection: "row",
    backgroundColor: "#E4E4E4"
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

const MyDocument = () => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text>Section #1</Text>
      </View>
      <View style={styles.section}>
        <Text>Section #2</Text>
      </View>
    </Page>
  </Document>
);

const ContractorCardView = () => {

  // if i comment this line and button in JSX - app not freezes
  const [instance] = usePDF({document: <MyDocument/>})

  return

    <button onClick={() => window.open(instance.url)}/>

};
```

Button is rendered, but whole page is not responding, so i can't even click it. When i delete\comment button and usePDF hook then app is loading fine, but obviously i cant render PDF that way))

Same code in codesandbox.io works fine:
https://codesandbox.io/s/loving-blackwell-l2dks5?file=/src/App.js

Body:
I'm trying to render basic example from react-pdf official website (https://react-pdf.org/)
but app is freezing while i'm trying to use one of rendering options (i tried PDFViever, usePDF hook, PDFDownloadLink).

When im trying the same example on codesandbox.io everything works fine.

Can someone explain why that could happen and whats possible solutions?

Example code:

import {
  usePDF,
  Page,
  Text,
  View,
  Document,
  StyleSheet,
} from "@react-pdf/renderer";

const styles = StyleSheet.create({
  page: {
    flexDirection: "row",
    backgroundColor: "#E4E4E4"
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

const MyDocument = () => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text>Section #1</Text>
      </View>
      <View style={styles.section}>
        <Text>Section #2</Text>
      </View>
    </Page>
  </Document>
);

const ContractorCardView = () => {

  // if i comment this line and button in JSX - app not freezes
  const [instance] = usePDF({document: <MyDocument/>})

  return

    <button onClick={() => window.open(instance.url)}/>

};

Button is rendered, but whole page is not responding, so i can't even click it. When i delete\comment button and usePDF hook then app is loading fine, but obviously i cant render PDF that way))

Same code in codesandbox.io works fine:
https://codesandbox.io/s/loving-blackwell-l2dks5?file=/src/App.js


问:
render html, gin GOLANG
I want to render an html page with the items it has
in my database

```<code>func (h Handler) ListUser(c *gin.Context) {

    var listUsers []Users

    //listUsers = make([]Users, 0)
    listUsers = append(listUsers, Users{})
    c.HTML(http.StatusOK, "listar.html", gin.H{
        "listUsers": listUsers,
    })
    h.DB.Find(&listUsers)

}

func main() {
    db := Init()
    h := OpenDB(db)

    r := gin.Default()
    r.Static("/static", "./public")

    list := r.Group("/list")
    r.LoadHTMLFiles("listar.html")
    {
        list.GET("/list", h.ListUser)
    }

    r.POST("/upload", h.Postform)

    r.Run(":7878")
}
</code>```

I want my database items (Name and Email) to be rendered in my html page, but when I run my code, the html page comes up blank

Title: render html, gin GOLANG

Body:
I want to render an html page with the items it has
in my database

func (h Handler) ListUser(c *gin.Context) {

    var listUsers []Users

    //listUsers = make([]Users, 0)
    listUsers = append(listUsers, Users{})
    c.HTML(http.StatusOK, "listar.html", gin.H{
        "listUsers": listUsers,
    })
    h.DB.Find(&listUsers)

}

func main() {
    db := Init()
    h := OpenDB(db)

    r := gin.Default()
    r.Static("/static", "./public")

    list := r.Group("/list")
    r.LoadHTMLFiles("listar.html")
    {
        list.GET("/list", h.ListUser)
    }

    r.POST("/upload", h.Postform)

    r.Run(":7878")
}

I want my database items (Name and Email) to be rendered in my html page, but when I run my code, the html page comes up blank


问:
Error: Error: Failed to download metadata for repo 'advanced-virtualization': Cannot prepare internal mirrorlist: No URLs in mirrorlist
I am using RHEL 9.1 machine where I am trying to install a package 'python3-distro' but I am getting error:

Error: Failed to download metadata for repo 'advanced-virtualization': Cannot prepare internal mirrorlist: No URLs in mirrorlist

can anyone please help me resolve this issue?

I was expecting 'sudo dnf install python3-distro' to work successfully.

I tried running below cmds:

```<code>sudo sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/*
sudo sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/*
</code>```

and as result after reboot I am getting below error:

Error: Failed to download metadata for repo 'advanced-virtualization': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

Output- ls 'yum.repos.d'

```<code>$ls /etc/yum.repos.d/
advanced-virtualization.repo  nfv-openvswitch.repo  redhat.repo
ceph-pacific.repo             rdo-release.repo
messaging.repo                rdo-testing.repo
</code>```

Any help would be appreciated.

Body:
I am using RHEL 9.1 machine where I am trying to install a package 'python3-distro' but I am getting error:

Error: Failed to download metadata for repo 'advanced-virtualization': Cannot prepare internal mirrorlist: No URLs in mirrorlist

can anyone please help me resolve this issue?

I was expecting 'sudo dnf install python3-distro' to work successfully.

I tried running below cmds:

sudo sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/*
sudo sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/*

and as result after reboot I am getting below error:

Error: Failed to download metadata for repo 'advanced-virtualization': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

Output- ls 'yum.repos.d'

$ls /etc/yum.repos.d/
advanced-virtualization.repo  nfv-openvswitch.repo  redhat.repo
ceph-pacific.repo             rdo-release.repo
messaging.repo                rdo-testing.repo

Any help would be appreciated.


问:
Reading through multiple txt files in a directory and counting words,sentences and exporting it to a csv format?
Everything works except for the part where i loop throught the directory to open and read the txt files, What can i change to make it work ?

```<code>import os
import csv

if __name__ == "__main__":
    path_to_txt = os.path.abspath(os.path.join("./", "E:\cleanable\.mp3\Dire Dawa- txt\txt"))

    text = ""
    with open(path_to_txt, "r", encoding="utf8") as stream:
        text = stream.read()

    words = text.split()
    # print("Words     : ", words)
    wrd= len(words)
    print("-" * 80)

    # Count Unique Words in a file
    uniqwords = sorted(set(words))
    # print("Unique Words     : ", words, "\n")
    uniq=len(uniqwords)
    print("-" * 80)
    #sentence count
    sentences=text.split("፡፡")
    sen=len(sentences)
    print("-" * 80)

    # df= pd. read_csv ("count.csv", header=None)
    # df.to_csv ("count.csv", header=["Name", "word","unique word","sentence"], index=False)
    f = open("count.csv", "a", newline='')
    row = (path_to_txt,wrd,uniq,sen)

    writer=csv.writer (f)
    writer.writerow (row)
    f.close()
</code>```

Im expecting it to loop through a folder with only txt files and count words and output a csv data file.

Body:
Everything works except for the part where i loop throught the directory to open and read the txt files, What can i change to make it work ?

import os
import csv

if __name__ == "__main__":
    path_to_txt = os.path.abspath(os.path.join("./", "E:\cleanable\.mp3\Dire Dawa- txt\txt"))

    text = ""
    with open(path_to_txt, "r", encoding="utf8") as stream:
        text = stream.read()

    words = text.split()
    # print("Words     : ", words)
    wrd= len(words)
    print("-" * 80)

    # Count Unique Words in a file
    uniqwords = sorted(set(words))
    # print("Unique Words     : ", words, "\n")
    uniq=len(uniqwords)
    print("-" * 80)
    #sentence count
    sentences=text.split("፡፡")
    sen=len(sentences)
    print("-" * 80)

    # df= pd. read_csv ("count.csv", header=None)
    # df.to_csv ("count.csv", header=["Name", "word","unique word","sentence"], index=False)
    f = open("count.csv", "a", newline='')
    row = (path_to_txt,wrd,uniq,sen)

    writer=csv.writer (f)
    writer.writerow (row)
    f.close()

Im expecting it to loop through a folder with only txt files and count words and output a csv data file.


问:
FloatingPointError: The system is too ill-conditioned for this solver. The system is too ill-conditioned for this solver
I am trying to reproduce a  GitHub repo. I have normalized data using minmaxscaler(). However, when I use graph lasso to get the skeleton of my data using:

```<code>skeleton = glasso.predict(df)
</code>```

I face the following error:

FloatingPointError: The system is too ill-conditioned for this solver. The system is too ill-conditioned for this solver. What does this mean? How to resolve this issue?

Body:
I am trying to reproduce a  GitHub repo. I have normalized data using minmaxscaler(). However, when I use graph lasso to get the skeleton of my data using:

skeleton = glasso.predict(df)

I face the following error:

FloatingPointError: The system is too ill-conditioned for this solver. The system is too ill-conditioned for this solver. What does this mean? How to resolve this issue?


问:
In DialogFlow-ES, how can I measure the accuracy of my agent apart from calculating the confidence score?
I have created a chatbot using DialogFlow-ES, but I cannot find a way to generate a confusion matrix from which we can measure the accuracy, precision, recall of our chatbot.
Even if we cannot generate a confusion matrix, are there any other performance metric apart from the Confidence score for a query, that DialogFlow-ES provides?

I tried searching for other metrics in google and everywhere only confidence score was mentioned. Also, I read some articles that dialogflow chatbots are different from the conventional chatbots. That is why I might have been unable to find any python libraries for this task too


问:
I am trying to read a file using fs readFile but im getting no return
When i use fs.readFile() on a characters.json file that i created through fs.writeFile() i dont get any errors or return.

Characters.json:

```<code>["Monkey D. Luffy","Roronoa Zoro","Nami","Usopp","Sanji","Tony Tony Chopper","Nico Robin","Franky","Brook","Jinbe","Shanks","Koby","Gaimon","Kaya","Johnny","Yosaku","Zeff","Nojiko","Bell-mère","Higuma","Alvida","Morgan","Helmeppo","Buggy","Kuro","Krieg","Gin","Arlong","Nefertari Vivi","Laboon","Karoo","Dorry","Brogy","Dalton","Kureha","Portgas D. Ace","Igaram","Kohza","Nefertari Cobra","Smoker","Wapol","Mikita","Gem","Marianne","Galdino","Bentham","Zala","Daz Bonez","Crocodile","Mont Blanc Cricket","Conis","Pagaya","Wyper","Gan Fall","Aisa","Montblanc Noland","Kalgara","Bellamy","Enel","Satori","Shura","Gedatsu","Ohm","Iceburg","Paulie","Kokoro","Galley-La Company","Franky Family","Rob Lucci","Kaku","Jabra","Blueno","Kalifa","Fukurou","Kumadori","Spandam","Kuzan","Foxy","Charlotte Lola","Gekko Moriah","Hogback","Absalom","Perona","Oars","Ryuma","Bartholomew Kuma","Keimi","Pappug","Hatchan","Silvers Rayleigh","Worst Generation","Boa Hancock","Emporio Ivankov","Edward Newgate","Marco","Duval","Charlos","Marshall D. Teach","Magellan","Hannyabal","Sakazuki","Kuzan","Borsalino","Sentomaru","Dracule Mihawk","Donquixote Doflamingo","Momonga","Shirahoshi","Neptune","Surume","Shyarly","Trafalgar D. Water Law","Kin'emon","Kozuki Momonosuke","Kurozumi Kanjuro","Chadros Higelyges","Bartolomeo","Cavendish","Rebecca","Kyros","Riku Doldo III","Sabo","Caribou","Hody Jones","Vander Decken IX","Hyouzou","Caesar Clown","Monet","Vergo","Trebol","Diamante","Pica","Senor Pink","Buffalo","Baby 5","Issho","Raizo","Carrot","Pedro","Wanda","Inuarashi","Nekomamushi","Pekoms","Zunesha","Capone Bege","Kaidou","Jack","Charlotte Linlin","Vinsmoke Judge","Charlotte Katakuri","Charlotte Pudding","Charlotte Cracker","Charlotte Smoothie","Charlotte Perospero","Kozuki Oden","Kozuki Hiyori","Kikunojo","Denjiro","Ashura Doji","Kawamatsu","Shinobu","Hyogoro","Shimotsuki Yasuie","Yamato","King","Queen","Who's-Who","Black Maria","Sasaki","Page One","Ulti","Scratchmen Apoo","Numbers"]
</code>```

code

```<code>const fs = require('fs/promises');
fs.readFile('characters.json', 'utf-8', (err, data) =>{
    if(err){
        console.log(err)
    }
    console.log(data)
});
</code>```

Body:
When i use fs.readFile() on a characters.json file that i created through fs.writeFile() i dont get any errors or return.

Characters.json:

["Monkey D. Luffy","Roronoa Zoro","Nami","Usopp","Sanji","Tony Tony Chopper","Nico Robin","Franky","Brook","Jinbe","Shanks","Koby","Gaimon","Kaya","Johnny","Yosaku","Zeff","Nojiko","Bell-mère","Higuma","Alvida","Morgan","Helmeppo","Buggy","Kuro","Krieg","Gin","Arlong","Nefertari Vivi","Laboon","Karoo","Dorry","Brogy","Dalton","Kureha","Portgas D. Ace","Igaram","Kohza","Nefertari Cobra","Smoker","Wapol","Mikita","Gem","Marianne","Galdino","Bentham","Zala","Daz Bonez","Crocodile","Mont Blanc Cricket","Conis","Pagaya","Wyper","Gan Fall","Aisa","Montblanc Noland","Kalgara","Bellamy","Enel","Satori","Shura","Gedatsu","Ohm","Iceburg","Paulie","Kokoro","Galley-La Company","Franky Family","Rob Lucci","Kaku","Jabra","Blueno","Kalifa","Fukurou","Kumadori","Spandam","Kuzan","Foxy","Charlotte Lola","Gekko Moriah","Hogback","Absalom","Perona","Oars","Ryuma","Bartholomew Kuma","Keimi","Pappug","Hatchan","Silvers Rayleigh","Worst Generation","Boa Hancock","Emporio Ivankov","Edward Newgate","Marco","Duval","Charlos","Marshall D. Teach","Magellan","Hannyabal","Sakazuki","Kuzan","Borsalino","Sentomaru","Dracule Mihawk","Donquixote Doflamingo","Momonga","Shirahoshi","Neptune","Surume","Shyarly","Trafalgar D. Water Law","Kin'emon","Kozuki Momonosuke","Kurozumi Kanjuro","Chadros Higelyges","Bartolomeo","Cavendish","Rebecca","Kyros","Riku Doldo III","Sabo","Caribou","Hody Jones","Vander Decken IX","Hyouzou","Caesar Clown","Monet","Vergo","Trebol","Diamante","Pica","Senor Pink","Buffalo","Baby 5","Issho","Raizo","Carrot","Pedro","Wanda","Inuarashi","Nekomamushi","Pekoms","Zunesha","Capone Bege","Kaidou","Jack","Charlotte Linlin","Vinsmoke Judge","Charlotte Katakuri","Charlotte Pudding","Charlotte Cracker","Charlotte Smoothie","Charlotte Perospero","Kozuki Oden","Kozuki Hiyori","Kikunojo","Denjiro","Ashura Doji","Kawamatsu","Shinobu","Hyogoro","Shimotsuki Yasuie","Yamato","King","Queen","Who's-Who","Black Maria","Sasaki","Page One","Ulti","Scratchmen Apoo","Numbers"]

code

const fs = require('fs/promises');
fs.readFile('characters.json', 'utf-8', (err, data) =>{
    if(err){
        console.log(err)
    }
    console.log(data)
});


问:
Provisioning Confluent Cloud using CloudFormation
I am looking for a way to manage Confluent Cloud (Kafka) infrastructure (cluster/topics etc.) using CloudFormation. So far I have only found a way to do this in Terraform, but not with CloudFormation.

Is there anyway to achieve this using CloudFormation?


问:
How can I rotate over a 3D surface plot(using quiver) so that I can see clearly where the arrows flow?
I have the following code of the 3D plot and would like to rotate it so that I can clearly see the arrows inside the cube.

```<code>import matplotlib.pyplot as plt
import numpy as np

ax = plt.figure().add_subplot(projection='3d')

# Make the grid
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
                     np.arange(-0.8, 1, 0.2),
                     np.arange(-0.8, 1, 0.8))

# Make the direction data for the arrows
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
    np.sin(np.pi * z))

ax.quiver(x, y, z, u, v, w, length=0.1, normalize=True)

plt.show()

</code>```

Is there any way to rotate the cube to see inside the cube clearly? I mean by hovering the mouse on the plot.

Body:
I have the following code of the 3D plot and would like to rotate it so that I can clearly see the arrows inside the cube.

import matplotlib.pyplot as plt
import numpy as np

ax = plt.figure().add_subplot(projection='3d')

# Make the grid
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
                     np.arange(-0.8, 1, 0.2),
                     np.arange(-0.8, 1, 0.8))

# Make the direction data for the arrows
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
    np.sin(np.pi * z))

ax.quiver(x, y, z, u, v, w, length=0.1, normalize=True)

plt.show()

Is there any way to rotate the cube to see inside the cube clearly? I mean by hovering the mouse on the plot.


问:
Using Sparse Tensors as Input for Autoencoders
I have an One-hot-encoded sparse matrix which can't be transformed into a normal matrix due to its size.

I would like to reduce the dimensions using an autoencoder. Currently I am trying to use Tensorflow and its Keras library for that.
The Tensorflow docs state that sparse tensors exist and that they can be used in Keras (see https://www.tensorflow.org/guide/sparse_tensor).

The Problem is that all autoencoders I've found in the internet do not seem to work with sparse tensors.

I have prepared a small code example which stops after the first training epoch with the error message: "Failed to convert elements of SparseTensor to Tensor. Consider casting elements to a supported type.".

My Questions would be:

Do you have an idea to improve the Code or ideally do you have an example which I can look up?

If not: Do you have other ideas on how to do what I would like to do (e.g. another library, other method, etc.)?

Code Example:

```<code>#necessary imports
import tensorflow as tf
from keras.models import Model, Sequential
from keras.layers import Input, Dense, ActivityRegularization
from tensorflow.keras import backend as K
from tensorflow.keras import regularizers

#example one-hot-encoded matrix with 10 records with each one out of 4 distinct categories
sparse_tensor = tf.sparse.SparseTensor(indices=[[0,3], [1,3], [2,0], [3,1], [4,0], [5,2], [6,2], [7,1], [8,3], [9,1]],
                      values=[1 for i in range(10)],
                      dense_shape=[10, 4])

encoder = Sequential([
    Input(shape=(4,), sparse=True),
    Dense(1, activation = 'relu'),
    ActivityRegularization(l1=1e-3)
])

decoder = Sequential([
    Dense(4, activation = 'sigmoid', input_shape = (1, )),
])

autoencoder = Sequential([encoder, decoder])
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
autoencoder.fit(x=sparse_tensor, y=sparse_tensor, epochs=5, batch_size=5, shuffle=True)
</code>```

Body:
I have an One-hot-encoded sparse matrix which can't be transformed into a normal matrix due to its size.

I would like to reduce the dimensions using an autoencoder. Currently I am trying to use Tensorflow and its Keras library for that.
The Tensorflow docs state that sparse tensors exist and that they can be used in Keras (see https://www.tensorflow.org/guide/sparse_tensor).

The Problem is that all autoencoders I've found in the internet do not seem to work with sparse tensors.

I have prepared a small code example which stops after the first training epoch with the error message: "Failed to convert elements of SparseTensor to Tensor. Consider casting elements to a supported type.".

My Questions would be:

Do you have an idea to improve the Code or ideally do you have an example which I can look up?

If not: Do you have other ideas on how to do what I would like to do (e.g. another library, other method, etc.)?

Code Example:

#necessary imports
import tensorflow as tf
from keras.models import Model, Sequential
from keras.layers import Input, Dense, ActivityRegularization
from tensorflow.keras import backend as K
from tensorflow.keras import regularizers

#example one-hot-encoded matrix with 10 records with each one out of 4 distinct categories
sparse_tensor = tf.sparse.SparseTensor(indices=[[0,3], [1,3], [2,0], [3,1], [4,0], [5,2], [6,2], [7,1], [8,3], [9,1]],
                      values=[1 for i in range(10)],
                      dense_shape=[10, 4])

encoder = Sequential([
    Input(shape=(4,), sparse=True),
    Dense(1, activation = 'relu'),
    ActivityRegularization(l1=1e-3)
])

decoder = Sequential([
    Dense(4, activation = 'sigmoid', input_shape = (1, )),
])

autoencoder = Sequential([encoder, decoder])
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
autoencoder.fit(x=sparse_tensor, y=sparse_tensor, epochs=5, batch_size=5, shuffle=True)


问:
Macro VBA Button to save screenshot of Dashboard in Sheet in JPG on Excel (using version 16.67 on Mac)
I am trying to make a button with VBA which automatically creates a screenshot of my dashboard presented in my worksheet and saves it as a separate JPG file.
I am using a Mac with Excel version 16.67.

The idea is that the button is able to do the following:

The button should select the range D4:AG175.

The file must be in JPG.

The location of the file could be in the same map as where the
Dashboard document is located (or on the Desktop, also fine).

The name of the file should be "='Filter Employee Week'!B2" + "='Filter
Employee Week'!B1" + ".jpg"

The "'Filter Employee Week'!B1 and B2" is a name selected from a slicer, which is connected to a pivot table.

So in summary:
The button takes a screenshot of the dashboard in the range D4 to AG175, it must be saved as a JPG in the same folder as the dashboard and the name should idyllically be the name of the employee selected in B2 and B1 (which are imported from a pivot table on a different sheet but presented by a connected slicer).

Can anyone help me with this code? I tried different codes from other users with problems that are comparable to this one, however, I can not get it fixed myself.

I am not able to solve this problem with the solutions presented at this question myself:
Using Excel VBA Macro To Capture + Save Screenshot of Specific Area In Same File

Save captured screenshot as JPG with vba


问:
Build with gradlew and make it available in ./m2
I'm building Ranger 2.4, as I need for Kafka 3.2.1.

The issue I'm getting is that Kafka is asked to be built with gradlew, which I do as follows:

./gradlew clean build releaseTarGz

I understand the release file can be found in ./core/build/distributions/, but when I build Ranger it doesn't seem to find it:

Failure to find org.apache.kafka:kafka-clients:jar:3.2.1-MYPROJECT-SNAPSHOT in https://repository.apache.org/content/repositories/snapshots

And effectively, I can't find it on .m2/org/apache/kafka. How would I register the release?


问:
maven-eclipse-plugin with maven 3.8
After migration to jdk11 and maven 3.8.6 , is the plugin maven-eclipse-plugin still useful, knowing that it is noted that it is retired https://maven.apache.org/plugins/maven-eclipse-plugin/
Should i delete this plugin from my pom.xml?

              org.apache.maven.plugins
              maven-eclipse-plugin

how can i replace it?

Title: maven-eclipse-plugin with maven 3.8


问:
Visual Studio Setup Project remember/set TARGETDIR on installation
In a Visual Studio setup project I want to set and remember the TARGETDIR respectively "Application Folder" on runtime (while the installation process is running) if the user is changing the default TARGETDIR.
Because next time the user is running the installer (on upgrade/update) to set the chosen TARGETDIR automatically from the previous installation.

The chosen TARGETDIR can be stored in the registry, but how can I read the registry and set the TARGETDIR before the installation dialog for selecting the Application Folder appears?

Is there a way to integrate this in a Visual Studio setup project or do I have to use a separate commercial product?


问:
Type and constant generation from a pattern in TypeScript
I have some extremely repetative code in TypeScript where I need to do essentially this dozens and dozens of times:

const IdPIdChangedDecoder = D.struct({
  newIdpId: UuidDecoder,
})
export type IdPIdChangedPayload = D.TypeOf<typeof IdPIdChangedDecoder>;
export const IdPIdChanged: EventMeta<Customer, IdPIdChangedPayload> = {
  name: EventNames.IdPIdChanged,
  decoder: IdPIdChangedDecoder,
  fn: (customer, p) => {
    return { ...customer, idpId: p.payload.newIdpId, lastUpdated: p.timestamp }
  },
}
export type IdPIdChanged = KnownEvent<EventNames.IdPIdChanged, EmailAddressChangedPayload>
```

As is evident the IdpIdChanged is repeated no less than 9 times in a single block.

Coming from Rust, I'd probably reach for a Macro in this scenario, because given a name, and a decoder, I could simply metaprogram that out.

In all my research however it seems like TypeScript compilers don't support anything like this in general?

Is there any general option to reduce the boilerplate? Bonus points if I can also eliminate the EventNames.IdpIdChanged enum (enum Eg { IdpIdChanged = "idp_id_changed" , }), and also add all the KnownEvent variants to a union type.

This is all boilerplate for an event driven system I am working on, and the various flavors of events, decoders, types, constants and such are all used in either the read, or write- side of the system, someplace or other.

I would have some limited flexibility in changing these types for a different paradigm, but not a great deal.

Body:
I have some extremely repetative code in TypeScript where I need to do essentially this dozens and dozens of times:

const IdPIdChangedDecoder = D.struct({
  newIdpId: UuidDecoder,
})
export type IdPIdChangedPayload = D.TypeOf<typeof IdPIdChangedDecoder>;
export const IdPIdChanged: EventMeta<Customer, IdPIdChangedPayload> = {
  name: EventNames.IdPIdChanged,
  decoder: IdPIdChangedDecoder,
  fn: (customer, p) => {
    return { ...customer, idpId: p.payload.newIdpId, lastUpdated: p.timestamp }
  },
}
export type IdPIdChanged = KnownEvent<EventNames.IdPIdChanged, EmailAddressChangedPayload>

As is evident the IdpIdChanged is repeated no less than 9 times in a single block.

Coming from Rust, I'd probably reach for a Macro in this scenario, because given a name, and a decoder, I could simply metaprogram that out.

In all my research however it seems like TypeScript compilers don't support anything like this in general?

Is there any general option to reduce the boilerplate? Bonus points if I can also eliminate the EventNames.IdpIdChanged enum (enum Eg { IdpIdChanged = "idp_id_changed" , }), and also add all the KnownEvent variants to a union type.

This is all boilerplate for an event driven system I am working on, and the various flavors of events, decoders, types, constants and such are all used in either the read, or write- side of the system, someplace or other.

I would have some limited flexibility in changing these types for a different paradigm, but not a great deal.


问:
Insert into a table selecting from an external list of tables
Good morning everybody !
I have a list of tables in SQL from which i have to select a number of fields and then copying them into another table.

This list is not "fixed" since it's updated every week, so some tables are deleted and others are added.
I've already created a really easy table where i store the ID and the name of these tables.

My import procedure is very easy :

```<code>INSERT INTO [LIST_UNION] ([1],[2],[3]
SELECT [1],[2],[3] FROM [First_List_in_Table]
</code>```

But what i need is to repeat this for every table of the initial list :

```<code>INSERT INTO [LIST_UNION] ([1],[2],[3]
SELECT [1],[2],[3] FROM [Second_List_in_Table]

INSERT INTO [LIST_UNION] ([1],[2],[3]
SELECT [1],[2],[3] FROM [Third_List_in_Table]
</code>```

And so on.
How can i create a procedure to dinamically read these tables ID and import the fields i need one by one ?

Body:
Good morning everybody !
I have a list of tables in SQL from which i have to select a number of fields and then copying them into another table.

This list is not "fixed" since it's updated every week, so some tables are deleted and others are added.
I've already created a really easy table where i store the ID and the name of these tables.

My import procedure is very easy :

INSERT INTO [LIST_UNION] ([1],[2],[3]
SELECT [1],[2],[3] FROM [First_List_in_Table]

But what i need is to repeat this for every table of the initial list :

INSERT INTO [LIST_UNION] ([1],[2],[3]
SELECT [1],[2],[3] FROM [Second_List_in_Table]

INSERT INTO [LIST_UNION] ([1],[2],[3]
SELECT [1],[2],[3] FROM [Third_List_in_Table]

And so on.
How can i create a procedure to dinamically read these tables ID and import the fields i need one by one ?


问:
What is a native pipe if it does not exist?
In my package, I would like magrittr's pipe %>% to have the same behaviour as the native pipe |>, because I work on expressions and calls, and replacing . in an expression is quite challenging.

I tried to create the following function

```<code>`%>%` <- function(...){
    `|>`(...)
}
</code>```

Unfortunately that does not work (function "|>" not found). I wanted to investigate a little further to understand what native pipe |> is and print the code.

```<code>> magrittr::`%>%`
function (lhs, rhs)
{
    lhs <- substitute(lhs)
    rhs <- substitute(rhs)
    kind <- 1L
    env <- parent.frame()
    lazy <- TRUE
    .External2(magrittr_pipe)
}
<bytecode: 0x55a4bb334560>
<environment: namespace:magrittr>

> `|>`
Error: object '|>' not found

> exists("|>")
[1] FALSE
</code>```

I'm confused: even special functions such as if do exist. If native pipe does not exist, what is it?

Body:
In my package, I would like magrittr's pipe %>% to have the same behaviour as the native pipe |>, because I work on expressions and calls, and replacing . in an expression is quite challenging.

I tried to create the following function

`%>%` <- function(...){
    `|>`(...)
}

Unfortunately that does not work (function "|>" not found). I wanted to investigate a little further to understand what native pipe |> is and print the code.

> magrittr::`%>%`
function (lhs, rhs)
{
    lhs <- substitute(lhs)
    rhs <- substitute(rhs)
    kind <- 1L
    env <- parent.frame()
    lazy <- TRUE
    .External2(magrittr_pipe)
}
<bytecode: 0x55a4bb334560>
<environment: namespace:magrittr>

> `|>`
Error: object '|>' not found

> exists("|>")
[1] FALSE

I'm confused: even special functions such as if do exist. If native pipe does not exist, what is it?


问:
PostgreSQL foreign table network load when using where with nested select
I have a PostgreSQL database (local) that fetches a lot of data from another PostgreSQL database (remote).

The remote table is a foreign table in the local database.

My problem is that when I SELECT with a WHERE condition, that has a nested SELECT, from the foreign table the whole table is moved over the network before the WHERE is applied.

But if I actually list the IDs in the WHERE condition, exactly the same values as in the nested SELECT, only the result of the WHERE are moved over the network.

```<code>SELECT * FROM bi.booking WHERE book_id IN (1,2,3, ... ,9999999)
</code>```

Takes around 2-3sec

```<code>SELECT * FROM bi.booking WHERE book_id IN (SELECT DISTINCT(book_id) FROM bi.temp_new_booking_history)
</code>```

Takes over 20 minutes because of the whole bi.booking table is moved over the network first.

The goal here is to only move the data matching the a subset of id in a local table.

I have tried few things unsuccessfully so far.

string_agg to build a list, that gives an error on the IN part of the query, "operator does not exist: bigint = text"

array_agg to bild a array, that also gives an error on the IN part of the query, "operator does not exist: bigint = bigint[]"

UPDATE - 14.12.2022 14:12

After few good pointers in the comments I wanted to add the result of EXPLAIN for few versions of this query

Original
Query

```<code>SELECT * FROM bi.booking WHERE book_id IN (SELECT DISTINCT(book_id) FROM bi.temp_new_booking_history)
</code>```

EXPLAIN

```<code>"Nested Loop  (cost=177.00..39787.58 rows=625697 width=373)"
"  ->  HashAggregate  (cost=76.58..80.23 rows=366 width=8)"
"        Group Key: temp_new_booking_history.book_id"
"        ->  Seq Scan on temp_new_booking_history  (cost=0.00..75.66 rows=366 width=8)"
"  ->  Foreign Scan on booking  (cost=100.43..108.47 rows=1 width=1538)"
</code>```

Original with hardcoded list of IDs
Query

```<code>EXPLAIN SELECT * FROM keahotelsl26.booking WHERE book_id IN (1,2,3,4,...,366);
</code>```

EXPLAIN

```<code>"Foreign Scan on booking  (cost=100.42..3047.70 rows=366 width=1538)"
</code>```

Suggestiond from Laurenz Albe
Query

```<code>EXPLAIN SELECT b.* FROM bi.booking AS b WHERE EXISTS (SELECT FROM bi.temp_new_booking_history AS h WHERE b.book_id = h.book_id)
</code>```

EXPLAIN

```<code>"Nested Loop  (cost=177.00..39783.92 rows=312848 width=373)"
"  ->  HashAggregate  (cost=76.58..80.23 rows=366 width=8)"
"        Group Key: h.book_id"
"        ->  Seq Scan on temp_new_booking_history h  (cost=0.00..75.66 rows=366 width=8)"
"  ->  Foreign Scan on booking b  (cost=100.43..108.47 rows=1 width=1538)"
</code>```

Body:
I have a PostgreSQL database (local) that fetches a lot of data from another PostgreSQL database (remote).

The remote table is a foreign table in the local database.

My problem is that when I SELECT with a WHERE condition, that has a nested SELECT, from the foreign table the whole table is moved over the network before the WHERE is applied.

But if I actually list the IDs in the WHERE condition, exactly the same values as in the nested SELECT, only the result of the WHERE are moved over the network.

SELECT * FROM bi.booking WHERE book_id IN (1,2,3, ... ,9999999)

Takes around 2-3sec

SELECT * FROM bi.booking WHERE book_id IN (SELECT DISTINCT(book_id) FROM bi.temp_new_booking_history)

Takes over 20 minutes because of the whole bi.booking table is moved over the network first.

The goal here is to only move the data matching the a subset of id in a local table.

I have tried few things unsuccessfully so far.

string_agg to build a list, that gives an error on the IN part of the query, "operator does not exist: bigint = text"

array_agg to bild a array, that also gives an error on the IN part of the query, "operator does not exist: bigint = bigint[]"

UPDATE - 14.12.2022 14:12

After few good pointers in the comments I wanted to add the result of EXPLAIN for few versions of this query

Original
Query

SELECT * FROM bi.booking WHERE book_id IN (SELECT DISTINCT(book_id) FROM bi.temp_new_booking_history)

EXPLAIN

"Nested Loop  (cost=177.00..39787.58 rows=625697 width=373)"
"  ->  HashAggregate  (cost=76.58..80.23 rows=366 width=8)"
"        Group Key: temp_new_booking_history.book_id"
"        ->  Seq Scan on temp_new_booking_history  (cost=0.00..75.66 rows=366 width=8)"
"  ->  Foreign Scan on booking  (cost=100.43..108.47 rows=1 width=1538)"

Original with hardcoded list of IDs
Query

EXPLAIN SELECT * FROM keahotelsl26.booking WHERE book_id IN (1,2,3,4,...,366);

EXPLAIN

"Foreign Scan on booking  (cost=100.42..3047.70 rows=366 width=1538)"

Suggestiond from Laurenz Albe
Query

EXPLAIN SELECT b.* FROM bi.booking AS b WHERE EXISTS (SELECT FROM bi.temp_new_booking_history AS h WHERE b.book_id = h.book_id)

EXPLAIN

"Nested Loop  (cost=177.00..39783.92 rows=312848 width=373)"
"  ->  HashAggregate  (cost=76.58..80.23 rows=366 width=8)"
"        Group Key: h.book_id"
"        ->  Seq Scan on temp_new_booking_history h  (cost=0.00..75.66 rows=366 width=8)"
"  ->  Foreign Scan on booking b  (cost=100.43..108.47 rows=1 width=1538)"


问:
Flutter - Error: Could not find the correct Provider<CartProvider> above this CartTrolleyScreen Widget
I have the following screens :
ShopPlaceholder Screen
Shop Screen
Cart Screen

Shop Placeholder Screen Code

```<code>class ShopPlaceHolderScreen extends StatelessWidget {
  const ShopPlaceHolderScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CartProvider(),
      child: Builder(builder: (BuildContext context) {
        return ShopScreen();
      }),
    );
  }
</code>```

Shop Screen

```<code>
  @override
  Widget build(BuildContext context) {

    cart = Provider.of<CartProvider>(context);

    return ChangeNotifierProvider(
      create: (_) => CartProvider(),
      child: Builder(builder: (BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: NetworkImage(
</code>```

Cart Screen

```<code>@override
  Widget build(BuildContext context) {
    final cart = Provider.of<CartProvider>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Shopping Cart'),
        elevation: 0.0,
        backgroundColor: Colors.green,
        centerTitle: true,
        actions: [
          Center(
            child: Badge(
              badgeContent: Consumer<CartProvider>(
                builder: (context, value, child) {
                  return Text(value.getCounter().toString(),
                      style: TextStyle(color: Colors.white));
                },
              ),
              animationDuration: Duration(milliseconds: 300),
              animationType: BadgeAnimationType.slide,
              child: Icon(Icons.shopping_cart),
            ),
          ),
          SizedBox(width: 20.0)
        ],
      ),
</code>```

Problem  : if i add my products to from the Shop Screen and click further to go to Cart screen it throws an error Flutter - Error: Could not find the correct Provider above this CartTrolleyScreen Widget however is replace the code in Shop Placeholder Screen with the one below the Cart Screen displays without any error. I do not want to return MaterailApp in ShopScreen Placeholder as it messing up my onGenerate routes is there a way i cannot return that Material App in ShopScreen Placeholder and instead return something else that wont throw an error in the Cart Screen Page?

```<code>// @override
  // Widget build(BuildContext context) {
  //   return ChangeNotifierProvider(
  //     create: (_) => CartProvider(),
  //     child: Builder(builder: (BuildContext context) {
  //       return MaterialApp(
  //         debugShowCheckedModeBanner: false,
  //         theme: ThemeData(
  //           colorScheme:
  //               ColorScheme.fromSwatch().copyWith(secondary: Colors.green),
  //         ),
  //         home: const ShopScreen(),
  //       );
  //     }),
  //   );
  // }
</code>```

I have tried to return the Scaffold widget in the Shop Placeholder Screen as shown below and it throws that error Flutter - Error: Could not find the correct Provider above this CartTrolleyScreen Widget

```<code>@override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CartProvider(),
      child: Builder(builder: (BuildContext context) {
        return ShopScreen();
      }),
    );
  }
</code>```

Body:
I have the following screens :
ShopPlaceholder Screen
Shop Screen
Cart Screen

Shop Placeholder Screen Code

class ShopPlaceHolderScreen extends StatelessWidget {
  const ShopPlaceHolderScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CartProvider(),
      child: Builder(builder: (BuildContext context) {
        return ShopScreen();
      }),
    );
  }

Shop Screen

  @override
  Widget build(BuildContext context) {

    cart = Provider.of<CartProvider>(context);

    return ChangeNotifierProvider(
      create: (_) => CartProvider(),
      child: Builder(builder: (BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: NetworkImage(

Cart Screen

@override
  Widget build(BuildContext context) {
    final cart = Provider.of<CartProvider>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Shopping Cart'),
        elevation: 0.0,
        backgroundColor: Colors.green,
        centerTitle: true,
        actions: [
          Center(
            child: Badge(
              badgeContent: Consumer<CartProvider>(
                builder: (context, value, child) {
                  return Text(value.getCounter().toString(),
                      style: TextStyle(color: Colors.white));
                },
              ),
              animationDuration: Duration(milliseconds: 300),
              animationType: BadgeAnimationType.slide,
              child: Icon(Icons.shopping_cart),
            ),
          ),
          SizedBox(width: 20.0)
        ],
      ),

Problem  : if i add my products to from the Shop Screen and click further to go to Cart screen it throws an error Flutter - Error: Could not find the correct Provider above this CartTrolleyScreen Widget however is replace the code in Shop Placeholder Screen with the one below the Cart Screen displays without any error. I do not want to return MaterailApp in ShopScreen Placeholder as it messing up my onGenerate routes is there a way i cannot return that Material App in ShopScreen Placeholder and instead return something else that wont throw an error in the Cart Screen Page?

// @override
  // Widget build(BuildContext context) {
  //   return ChangeNotifierProvider(
  //     create: (_) => CartProvider(),
  //     child: Builder(builder: (BuildContext context) {
  //       return MaterialApp(
  //         debugShowCheckedModeBanner: false,
  //         theme: ThemeData(
  //           colorScheme:
  //               ColorScheme.fromSwatch().copyWith(secondary: Colors.green),
  //         ),
  //         home: const ShopScreen(),
  //       );
  //     }),
  //   );
  // }

I have tried to return the Scaffold widget in the Shop Placeholder Screen as shown below and it throws that error Flutter - Error: Could not find the correct Provider above this CartTrolleyScreen Widget

@override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CartProvider(),
      child: Builder(builder: (BuildContext context) {
        return ShopScreen();
      }),
    );
  }


问:
how to count the days passed in a python pandas dataframe
i have the following dataframe

```<code>    Datetime
0   2022-06-01 00:00:00
1   2022-06-01 00:01:00
2   2022-06-01 00:02:00
3   2022-06-01 00:03:00
4   2022-06-01 00:04:00
5   2022-06-01 00:05:00
</code>```

that it is year-month-day
i want to count what day is
or example
for tje 2022-06-01 i want to have a variable that will be equal to day= days of january + days of february + ... + one day of june ..
the same for the 2022-06-02 ..
untill a final date
does anybody knows what i've got to use in order to do that?

Body:
i have the following dataframe

    Datetime
0   2022-06-01 00:00:00
1   2022-06-01 00:01:00
2   2022-06-01 00:02:00
3   2022-06-01 00:03:00
4   2022-06-01 00:04:00
5   2022-06-01 00:05:00

that it is year-month-day
i want to count what day is
or example
for tje 2022-06-01 i want to have a variable that will be equal to day= days of january + days of february + ... + one day of june ..
the same for the 2022-06-02 ..
untill a final date
does anybody knows what i've got to use in order to do that?


问:
speed up python process (huge data search)
```<code>for data in DBS:
            if any(elem1 in data for elem1 in set_deletelist):
                h.write(data +'\n')
            else:
                pass
</code>```

A script that only writes out URLs that exist in 750,000 rows (set_deletelist) (set type) of a 1,000,000 row (DBS) (set type)takes 10,000 hours to finish processing.
Is there a good way to speed up the process?

I have changed from a list type to a set type, but it seems that further speed-up is needed.
The environment used is ec2 of aws.

Body:
for data in DBS:
            if any(elem1 in data for elem1 in set_deletelist):
                h.write(data +'\n')
            else:
                pass

A script that only writes out URLs that exist in 750,000 rows (set_deletelist) (set type) of a 1,000,000 row (DBS) (set type)takes 10,000 hours to finish processing.
Is there a good way to speed up the process?

I have changed from a list type to a set type, but it seems that further speed-up is needed.
The environment used is ec2 of aws.


问:
Flutter windows build, false positive antivirus
am trying to build lancher for some game, and after finish programing and build it for windows, all fine,
But when i give it to someone thire antivairus give alarm for torgan, and some authers there browsers delete it after installing immediately even virus total give me that virus total report,

Notice:
I want the app single file exe,
Tryed winrar method, its worst in virus total