问:
Path to file is not found on server but is locally
This might be a centuries old battle between local and server..

I am developing an Azure Function in Node and I've implemented multithreading using worker_threads. I'm also using Typescript so I had to make some translation layer so that my typescript is compiled into javascript when run by the worker thread. This all works fine locally.

Now when I deploy my code to Azure I'm getting an error stating: Cannot find module '/home/site/wwwroot/orchestrator/services/main-service.ts' Require stack: - /home/site/wwwroot/orchestrator/utils/worker.js

Now I'm doing the following. I'm calling the create_worker function in my orchestrator like this:

```<code># imports

const queueTrigger: AzureFunction = async function (
  azureContext: Context
): Promise<void> {
  const message: SearchCommand = azureContext.bindings.myQueueItem;
  try {
    const configuration = azureContext.bindings.orchestratorConfiguration;

    const search_grid = await geocoding_service(
      message.location,
      process.env.GEOCODING_API_KEY!,
      configuration[0].ratio_lat,
      configuration[0].ratio_lng
    );

    const chunked_places_service = chunkify_array(search_grid, 2);

    const workerPromises: unknown[] = [];

    for (let i = 0; i < 2; i++) {
      workerPromises.push(
        create_worker("./orchestrator/utils/worker.js", {
          places_urls: chunked_places_service[i],
          path: "../services/places-service.ts",
        })
      );
    }

    const settled = await Promise.allSettled(
      workerPromises
    );

    const fulfilled: unknown[] =
      settled
        .filter(isFulfilled)
        .map((element) => element.value)
        .flat(1);

  } catch (error) {
    azureContext.log("Error occurred while processing \n" + error);
  }
};

export default queueTrigger;

</code>```

And this is the create_worker function:

```<code>import { Worker } from "worker_threads";

const create_worker = (file: string, workerData: {}) =>
  new Promise<void>((resolve, reject) => {
    const worker = new Worker(file, {
      workerData: workerData,
    });

    worker.on("message", resolve);
    worker.on("error", reject);
    worker.on("exit", (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });

export default create_worker;
</code>```

Now then I have a file which functions as the intermediary between my typescript code and the worker_thread, like this:

```<code>const path = require("path");
const { workerData } = require("worker_threads");

require("ts-node").register();
require(path.resolve(__dirname, workerData.path));
</code>```

I think the error originates from this javascript. On the server it seems to not be able to find the typescript file. On my local machine it does work so I'm a bit confused about what's going on here. Does anyone have an idea?

Body:
This might be a centuries old battle between local and server..

I am developing an Azure Function in Node and I've implemented multithreading using worker_threads. I'm also using Typescript so I had to make some translation layer so that my typescript is compiled into javascript when run by the worker thread. This all works fine locally.

Now when I deploy my code to Azure I'm getting an error stating: Cannot find module '/home/site/wwwroot/orchestrator/services/main-service.ts' Require stack: - /home/site/wwwroot/orchestrator/utils/worker.js

Now I'm doing the following. I'm calling the create_worker function in my orchestrator like this:

# imports

const queueTrigger: AzureFunction = async function (
  azureContext: Context
): Promise<void> {
  const message: SearchCommand = azureContext.bindings.myQueueItem;
  try {
    const configuration = azureContext.bindings.orchestratorConfiguration;

    const search_grid = await geocoding_service(
      message.location,
      process.env.GEOCODING_API_KEY!,
      configuration[0].ratio_lat,
      configuration[0].ratio_lng
    );

    const chunked_places_service = chunkify_array(search_grid, 2);

    const workerPromises: unknown[] = [];

    for (let i = 0; i < 2; i++) {
      workerPromises.push(
        create_worker("./orchestrator/utils/worker.js", {
          places_urls: chunked_places_service[i],
          path: "../services/places-service.ts",
        })
      );
    }

    const settled = await Promise.allSettled(
      workerPromises
    );

    const fulfilled: unknown[] =
      settled
        .filter(isFulfilled)
        .map((element) => element.value)
        .flat(1);

  } catch (error) {
    azureContext.log("Error occurred while processing \n" + error);
  }
};

export default queueTrigger;

And this is the create_worker function:

import { Worker } from "worker_threads";

const create_worker = (file: string, workerData: {}) =>
  new Promise<void>((resolve, reject) => {
    const worker = new Worker(file, {
      workerData: workerData,
    });

    worker.on("message", resolve);
    worker.on("error", reject);
    worker.on("exit", (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });

export default create_worker;

Now then I have a file which functions as the intermediary between my typescript code and the worker_thread, like this:

const path = require("path");
const { workerData } = require("worker_threads");

require("ts-node").register();
require(path.resolve(__dirname, workerData.path));

I think the error originates from this javascript. On the server it seems to not be able to find the typescript file. On my local machine it does work so I'm a bit confused about what's going on here. Does anyone have an idea?


来源: stackexchange

问:
How to add a new column to one snowflake table from another snowflake table based on two join keys from databricks notebook?
I have data I've pulled from a S3 bucket and placed into a pyspark dataframe, this data has a few columns of interest: user_id, user_sign_up_dt, special_data. Inside my databricks notebook I make a sf connection string like so:

```<code>my_df.write.format("snowflake") \
    .option("sfurl", "some_url") \
    .option("sfuser", "some_user") \
    .option("sfpassword", "some_pwd") \
    .option("sfdatabase", "some_db") \
    .option("sfwarehouse", "some_warehouse") \
    .option("role", "some_role") \
    .option("dbtable", "some_table") \
    .mode("overwrite") \
    .save()
</code>```

Once I run that above code, I can then go into sf and see that table has been generated.

Now I have a pre-existing table in snowflake that I would like to add data from "some_table" to, call it "other_table".

What I've tried doing is making another connection to snowflake and then make two temp tables based on the two tables that are now in sf then join on the shared column: "user_id", "user_sign_up_dt" like so:

```<code>conn = snowflake.connector.connect(
user = "some_user",
password = "some_password",
account = "some_account",
warehouse = "some_warehouse",
database = "some_database",
schema = "some_schema"
_

# then to make the two temp tables:
OTHER_TABLE = spark.read.format("snowflake) \
...
# same set up as before except load

OTHER_TABLE.createOrReplaceTempView("OTHER_TABLE_tmp")

SOME_TABLE = spark.read.format("snowflake") \
...

# same set up
SOME_TABLE.createOrReplaceTempView("SOME_TABLE_tmp")
</code>```

Now that I have two temp tables I join on them and load that data into OTHER_TABLE.

```<code>join_query = """
MERGE INTO OTHER_TABLE_tmp
USING SOME_TABLE_tmp
ON OTHER_TABLE_tmp.user_id = SOME_TABLE_tmp.user_id
AND OTHER_TABLE_tmp.user_sign_up_dt = SOME_TABLE_tmp.user_sign_up_dt
WHEN MATCHED THEN UPDATE SET OTHER_TABLE_tmp.special_data = SOME_TABLE_tmp.special_data
"""

spark.sql(join_query)
</code>```

This doesn't work and I get the following exception:

AnalysisException: cannot resolve OTHER_TABLE_tmp.special_data in MERGE command given columnns [OTHER_TABLE_tmp.acct_dt, OTHER_TABLE_tmp.active_accts...]

Is there a more effective way to do this inside of databricks?

Thank you

ContentLicense: CC BY-SA 4.0

Body:
I have data I've pulled from a S3 bucket and placed into a pyspark dataframe, this data has a few columns of interest: user_id, user_sign_up_dt, special_data. Inside my databricks notebook I make a sf connection string like so:

my_df.write.format("snowflake") \
    .option("sfurl", "some_url") \
    .option("sfuser", "some_user") \
    .option("sfpassword", "some_pwd") \
    .option("sfdatabase", "some_db") \
    .option("sfwarehouse", "some_warehouse") \
    .option("role", "some_role") \
    .option("dbtable", "some_table") \
    .mode("overwrite") \
    .save()

Once I run that above code, I can then go into sf and see that table has been generated.

Now I have a pre-existing table in snowflake that I would like to add data from "some_table" to, call it "other_table".

What I've tried doing is making another connection to snowflake and then make two temp tables based on the two tables that are now in sf then join on the shared column: "user_id", "user_sign_up_dt" like so:

conn = snowflake.connector.connect(
user = "some_user",
password = "some_password",
account = "some_account",
warehouse = "some_warehouse",
database = "some_database",
schema = "some_schema"
_

# then to make the two temp tables:
OTHER_TABLE = spark.read.format("snowflake) \
...
# same set up as before except load

OTHER_TABLE.createOrReplaceTempView("OTHER_TABLE_tmp")

SOME_TABLE = spark.read.format("snowflake") \
...

# same set up
SOME_TABLE.createOrReplaceTempView("SOME_TABLE_tmp")

Now that I have two temp tables I join on them and load that data into OTHER_TABLE.

join_query = """
MERGE INTO OTHER_TABLE_tmp
USING SOME_TABLE_tmp
ON OTHER_TABLE_tmp.user_id = SOME_TABLE_tmp.user_id
AND OTHER_TABLE_tmp.user_sign_up_dt = SOME_TABLE_tmp.user_sign_up_dt
WHEN MATCHED THEN UPDATE SET OTHER_TABLE_tmp.special_data = SOME_TABLE_tmp.special_data
"""

spark.sql(join_query)

This doesn't work and I get the following exception:

AnalysisException: cannot resolve OTHER_TABLE_tmp.special_data in MERGE command given columnns [OTHER_TABLE_tmp.acct_dt, OTHER_TABLE_tmp.active_accts...]

Is there a more effective way to do this inside of databricks?

Thank you


问:
How can I add a classpath entry to the Kotlin Interactive Shell?
How can I add a classpath entry to the Kotlin Interactive Shell?</p>


问:
How to Change Kubernetes Prefix of Fields in Fluent-Bit on AWS EKS
I've got my cluster with Fluent-Bit configured so that it sends logs to CloudWatch (copied from CW Log Insights):

```<code>Field Value
@ingestionTime  1671383680308
@log    123456789012:/aws/containerinsights/SharedEksCluster/application
@logStream  ip-10-0-93-77.eu-central-1.compute.internal-application.var.log.containers.cloudwatch-agent-7rpsz_aws-observability_cloudwatch-agent-3b16590c6634d6ca81ff934b1d83535d19a30569d1029e16bc5126302774b21d.log
@message    {"stream":"stderr","logtag":"F","log":"2022-12-18T17:14:35Z I! no pod is found for namespace:aws-observability,podName:fluent-bit-wlbd5, refresh the cache now...","kubernetes":{"pod_name":"cloudwatch-agent-7rpsz","namespace_name":"aws-observability","pod_id":"04055679-85c7-424f-a352-c05affa0bb2a","labels":{"controller-revision-hash":"866589df77","name":"cloudwatch-agent","pod-template-generation":"2"},"host":"ip-10-0-93-77.eu-central-1.compute.internal","container_name":"cloudwatch-agent","docker_id":"3b16590c6634d6ca81ff934b1d83535d19a30569d1029e16bc5126302774b21d","container_hash":"docker.io/amazon/cloudwatch-agent@sha256:33f0072c93d614b5dd32f044549f3d764d05a42f068e852e94bdd849098852c7","container_image":"docker.io/amazon/cloudwatch-agent:1.247354.0b251981"}}
@timestamp  1671383675465
kubernetes.container_hash   docker.io/amazon/cloudwatch-agent@sha256:33f0072c93d614b5dd32f044549f3d764d05a42f068e852e94bdd849098852c7
kubernetes.container_image  docker.io/amazon/cloudwatch-agent:1.247354.0b251981
kubernetes.container_name   cloudwatch-agent
kubernetes.docker_id    3b16590c6634d6ca81ff934b1d83535d19a30569d1029e16bc5126302774b21d
kubernetes.host ip-10-0-93-77.eu-central-1.compute.internal
kubernetes.labels.controller-revision-hash  866589df77
kubernetes.labels.name  cloudwatch-agent
kubernetes.labels.pod-template-generation   2
kubernetes.namespace_name   aws-observability
kubernetes.pod_id   04055679-85c7-424f-a352-c05affa0bb2a
kubernetes.pod_name cloudwatch-agent-7rpsz
log 2022-12-18T17:14:35Z I! no pod is found for namespace:aws-observability,podName:fluent-bit-wlbd5, refresh the cache now...
logtag  F
stream  stderr
</code>```

As you can see, K8S specific fields are prefixed with kubernetes. Is there any way to change the prefix to k8s, to make it shorter? I couldn't find anything in the documentation. Thanks.

Body:
I've got my cluster with Fluent-Bit configured so that it sends logs to CloudWatch (copied from CW Log Insights):

Field Value
@ingestionTime  1671383680308
@log    123456789012:/aws/containerinsights/SharedEksCluster/application
@logStream  ip-10-0-93-77.eu-central-1.compute.internal-application.var.log.containers.cloudwatch-agent-7rpsz_aws-observability_cloudwatch-agent-3b16590c6634d6ca81ff934b1d83535d19a30569d1029e16bc5126302774b21d.log
@message    {"stream":"stderr","logtag":"F","log":"2022-12-18T17:14:35Z I! no pod is found for namespace:aws-observability,podName:fluent-bit-wlbd5, refresh the cache now...","kubernetes":{"pod_name":"cloudwatch-agent-7rpsz","namespace_name":"aws-observability","pod_id":"04055679-85c7-424f-a352-c05affa0bb2a","labels":{"controller-revision-hash":"866589df77","name":"cloudwatch-agent","pod-template-generation":"2"},"host":"ip-10-0-93-77.eu-central-1.compute.internal","container_name":"cloudwatch-agent","docker_id":"3b16590c6634d6ca81ff934b1d83535d19a30569d1029e16bc5126302774b21d","container_hash":"docker.io/amazon/cloudwatch-agent@sha256:33f0072c93d614b5dd32f044549f3d764d05a42f068e852e94bdd849098852c7","container_image":"docker.io/amazon/cloudwatch-agent:1.247354.0b251981"}}
@timestamp  1671383675465
kubernetes.container_hash   docker.io/amazon/cloudwatch-agent@sha256:33f0072c93d614b5dd32f044549f3d764d05a42f068e852e94bdd849098852c7
kubernetes.container_image  docker.io/amazon/cloudwatch-agent:1.247354.0b251981
kubernetes.container_name   cloudwatch-agent
kubernetes.docker_id    3b16590c6634d6ca81ff934b1d83535d19a30569d1029e16bc5126302774b21d
kubernetes.host ip-10-0-93-77.eu-central-1.compute.internal
kubernetes.labels.controller-revision-hash  866589df77
kubernetes.labels.name  cloudwatch-agent
kubernetes.labels.pod-template-generation   2
kubernetes.namespace_name   aws-observability
kubernetes.pod_id   04055679-85c7-424f-a352-c05affa0bb2a
kubernetes.pod_name cloudwatch-agent-7rpsz
log 2022-12-18T17:14:35Z I! no pod is found for namespace:aws-observability,podName:fluent-bit-wlbd5, refresh the cache now...
logtag  F
stream  stderr

As you can see, K8S specific fields are prefixed with kubernetes. Is there any way to change the prefix to k8s, to make it shorter? I couldn't find anything in the documentation. Thanks.


问:
How can I edit and transfer output tables from R?
I am working with R for analyzing data for my research paper. I have run some regressions and marginal effects and would like to get the output in a format that I can include in my research paper (best would be tables as images). How can I do this?

I have tried using the sumtable() command, but it only provides a table that summarizes the overall data that I am using and not the specific regressions or the marginal effect output.
I have also used htmlreg() but as far as I know it is only for regressions, and I do not know how to transfer the html output into my word document where I am writing the paper.


问:
After debugging for a while, my program runs without system errors, however I want to improve pytesseract accuracy
I am creating a program in which a user inputs an image of their grades (will add input function later) and then that image is processed through OpenCV, and then to Pytesseract which extracts the grades from the image. I have experimented with PSMs, OpenCV commands, and more but am still not able to get a desired output from Pytesseract. I want my  Here is my program:

import cv2
import pytesseract
import numpy as np

# Set the path to the tesseract executable
pytesseract.pytesseract.tesseract_cmd = "C:\\Users\\hypro\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe"

imgo = cv2.imread('C:\\Users\hypro\Pictures\image5.png')
#Alternatively: can be skipped if you have a Blackwhite image
gray = cv2.cvtColor(imgo, cv2.COLOR_RGB2GRAY)
gray, img_bin = cv2.threshold(gray,128,255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
gray = cv2.bitwise_not(img_bin)

kernel = np.ones((2, 2), np.uint8)
img1 = cv2.erode(gray, kernel, iterations=1)
img2 = cv2.dilate(img1, kernel, iterations=1)
#img = cv2.GaussianBlur(img, (1, 1), 0)
img3 = cv2.equalizeHist(img2)
# Encode the image as a JPEG
_, encoded_image = cv2.imencode('.jpg', img2)
print(encoded_image)
# Convert the encoded image to a string
image_bytes = encoded_image.tobytes()
# Convert the bytes object back to an image object
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Pass the image object to image_to_string()
out_below = pytesseract.image_to_string(image, lang='eng', config='--psm 4 -c tessedit_char_whitelist=0123456789QEMSWX')
print("OPENCV OUTPUT: ", out_below)
for i in range(6):
    print("")
upload_output = pytesseract.image_to_string(imgo, lang='eng', config='--psm 4 -c tessedit_char_whitelist=0123456789QEMSWX')
print("NO EDITING OUTPUT: ", upload_output)
```
<p>I found so far that PSM 4 works best with my image, and surprisingly, the original image has done best when put through pytesseract. I have used other test images with pytesseract, and they have worked, so no issue with pytesseract.</p>
<p>Here is the test image I use:
Here is the image after OpenCV tampering:</p>
<p>Here is the output that the program emits:</p>
```[255 216 255 ... 127 255 217]
OPENCV OUTPUT:  W9W2EXSME

9595XE

9971008

9799XE

95100

100100

---(6 spaces removed for readability)---

NO EDITING OUTPUT:  1W2E1S

895EXE97

9595EXE5

999710098

9799EXE98

EXE

9510097

100100
```

Body:
I am creating a program in which a user inputs an image of their grades (will add input function later) and then that image is processed through OpenCV, and then to Pytesseract which extracts the grades from the image. I have experimented with PSMs, OpenCV commands, and more but am still not able to get a desired output from Pytesseract. I want my  Here is my program:

import cv2
import pytesseract
import numpy as np

# Set the path to the tesseract executable
pytesseract.pytesseract.tesseract_cmd = "C:\\Users\\hypro\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe"

imgo = cv2.imread('C:\\Users\hypro\Pictures\image5.png')
#Alternatively: can be skipped if you have a Blackwhite image
gray = cv2.cvtColor(imgo, cv2.COLOR_RGB2GRAY)
gray, img_bin = cv2.threshold(gray,128,255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
gray = cv2.bitwise_not(img_bin)

kernel = np.ones((2, 2), np.uint8)
img1 = cv2.erode(gray, kernel, iterations=1)
img2 = cv2.dilate(img1, kernel, iterations=1)
#img = cv2.GaussianBlur(img, (1, 1), 0)
img3 = cv2.equalizeHist(img2)
# Encode the image as a JPEG
_, encoded_image = cv2.imencode('.jpg', img2)
print(encoded_image)
# Convert the encoded image to a string
image_bytes = encoded_image.tobytes()
# Convert the bytes object back to an image object
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Pass the image object to image_to_string()
out_below = pytesseract.image_to_string(image, lang='eng', config='--psm 4 -c tessedit_char_whitelist=0123456789QEMSWX')
print("OPENCV OUTPUT: ", out_below)
for i in range(6):
    print("")
upload_output = pytesseract.image_to_string(imgo, lang='eng', config='--psm 4 -c tessedit_char_whitelist=0123456789QEMSWX')
print("NO EDITING OUTPUT: ", upload_output)

I found so far that PSM 4 works best with my image, and surprisingly, the original image has done best when put through pytesseract. I have used other test images with pytesseract, and they have worked, so no issue with pytesseract.

Here is the test image I use:
Here is the image after OpenCV tampering:

Here is the output that the program emits:

[255 216 255 ... 127 255 217]
OPENCV OUTPUT:  W9W2EXSME

9595XE

9971008

9799XE

95100

100100

---(6 spaces removed for readability)---

NO EDITING OUTPUT:  1W2E1S

895EXE97

9595EXE5

999710098

9799EXE98

EXE

9510097

100100


问:
How to keep an incoming socket HTTP POST connection open after reading the body of the request
I have a HTTP server written in PHP which code looks like this:

```<code><?php
    $address = '0.0.0.0';
    $port = 8080;

    $server = socket_create(AF_INET, SOCK_STREAM, 0);

    socket_bind($server, $address, $port);

    socket_listen($server);

    while(true){
        $client = socket_accept($server);

        $request = socket_read($client, 1024);

        if (preg_match('/Content-Length: (\d+)/', $request, $matches)) {
            $requestBody = socket_read($client, $contentLength);
        }

        $_POST = $this->getPostParameters($requestBody ?? "");

        // Do some things with the POST parameters

        $response = "HTTP/1.1 200 OK\r\n";
        $response .= "Content-Type: text/text\r\n";
        $response .= "Connection: close\r\n\r\n";
        $response .= "a cool response";
        socket_write($client, $response);
    }

</code>```

But the response comes never to the client (a browser), as it seems to close the connection after the second socket_read() function (the one that reads the body). How can I keep this connection open and send a response?

There are checks to check whetever it is a POST request or not and getPostParameters works as expected.

Body:
I have a HTTP server written in PHP which code looks like this:

<?php
    $address = '0.0.0.0';
    $port = 8080;

    $server = socket_create(AF_INET, SOCK_STREAM, 0);

    socket_bind($server, $address, $port);

    socket_listen($server);

    while(true){
        $client = socket_accept($server);

        $request = socket_read($client, 1024);

        if (preg_match('/Content-Length: (\d+)/', $request, $matches)) {
            $requestBody = socket_read($client, $contentLength);
        }

        $_POST = $this->getPostParameters($requestBody ?? "");

        // Do some things with the POST parameters

        $response = "HTTP/1.1 200 OK\r\n";
        $response .= "Content-Type: text/text\r\n";
        $response .= "Connection: close\r\n\r\n";
        $response .= "a cool response";
        socket_write($client, $response);
    }

But the response comes never to the client (a browser), as it seems to close the connection after the second socket_read() function (the one that reads the body). How can I keep this connection open and send a response?

There are checks to check whetever it is a POST request or not and getPostParameters works as expected.


问:
React: CSS imported within (sub)component does not "unload" (so, remains) when rendered components change
I have two components, we can choose by button-click, which to be render.
Inside the components I import CSS (different CSS for different component, of course).
The components are working (rendering) well, but both CSS remain, so the styles are mixed.
Why remain both CSS loaded when the rendered compponent change, and how could I solve this?

Thank you.

This is the begin of the second (sub)component to render (the first is the same with "1" instead of "2")

```<code>import './nagynap2.css';
export default function Template2(props:any)
{ }
</code>```

And this is the part of the main component, whith the dynamic render:

```<code>if(currenttemplateIndex == 1) { return <Template1 {...props} /> }
if(currenttemplateIndex == 2) { return <Template2 {...props} /> }
</code>```

I have tried every ideo to solve it, but none of them works. :)

Body:
I have two components, we can choose by button-click, which to be render.
Inside the components I import CSS (different CSS for different component, of course).
The components are working (rendering) well, but both CSS remain, so the styles are mixed.
Why remain both CSS loaded when the rendered compponent change, and how could I solve this?

Thank you.

This is the begin of the second (sub)component to render (the first is the same with "1" instead of "2")

import './nagynap2.css';
export default function Template2(props:any)
{ }

And this is the part of the main component, whith the dynamic render:

if(currenttemplateIndex == 1) { return <Template1 {...props} /> }
if(currenttemplateIndex == 2) { return <Template2 {...props} /> }

I have tried every ideo to solve it, but none of them works. :)


问:
Dedupe Log Entries
I'm not a programmer or developer and I have a Python 3 programming issue that I can't seem to solve.

I have a Suricata log file named alerts.log with examples of the following data inside.  There are hundreds of these lines in the alerts.log file and a lot of the lines are duplicates, such as below, except for the date-time stamps.

11/10/2022-08:32:29.891692  [**] [1:2210054:1] SURICATA STREAM excessive retransmissions [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-08:34:21.185990  [**] [1:2210054:1] SURICATA STREAM excessive retransmissions [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-08:34:21.246621  [**] [1:2210054:1] SURICATA STREAM excessive retransmissions [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-12:47:06.318702  [**] [1:2210038:2] SURICATA STREAM FIN out of window [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-12:47:06.537754  [**] [1:2210038:2] SURICATA STREAM FIN out of window [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-12:47:06.969727  [**] [1:2210038:2] SURICATA STREAM FIN out of window [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/14/2022-10:45:56.543566  [**] [1:2230027:1] SURICATA TLS certificate invalid der [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/14/2022-10:45:56.555059  [**] [1:2230027:1] SURICATA TLS certificate invalid der [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/14/2022-10:45:56.555386  [**] [1:2230027:1] SURICATA TLS certificate invalid der [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
```
<p>I'm interested in writing only the <strong>unique</strong> Message and corresponding <code>GID:SID</code> to another file.  The Message and the <code>GID:SID</code> on the same line of course go with each other such as:</p>
<pre class="lang-none prettyprint-override"><code>Message = SURICATA STREAM excessive retransmissions
GID:SID = 1:2210054
</code>```

An example of the Message and corresponding GID:SID needed format to be written to another file from the above example data, deduped, would be:

\# SURICATA STREAM excessive retransmissions
1:2210054

\# SURICATA STREAM FIN out of window
1:2210038

\# SURICATA TLS certificate invalid der
1:2230027
```
<p>The following code is what I have written, and it does write the output in the format needed to another file, but I can't seem to write the deduped Message with the corresponding <code>GID:SID</code>:</p>
<pre class="lang-py prettyprint-override"><code>content = open('alerts.log', "r").readlines()
sid_outfile = "test.txt"
unique = []
with open(sid_outfile, "w") as f:
    for line in content:
        pattern = re.search(r"\[(\d:\d+):\d] (.*?) \[", line)
        if pattern not in unique:
            unique.append(pattern)
        if unique:
            f.write("# " + pattern.group(2) + "\n")
            f.write(pattern.group(1) + "\n\n")
</code>```

I've also tried the set() method with no luck in the code -

unique = set()
unique.add(pattern)
```

Anyone have an ideas on how the code needs to be written in order to write the deduped format needed to another file?  Any assistance would be most helpful.

Thank you.

Title: Dedupe Log Entries

Body:
I'm not a programmer or developer and I have a Python 3 programming issue that I can't seem to solve.

I have a Suricata log file named alerts.log with examples of the following data inside.  There are hundreds of these lines in the alerts.log file and a lot of the lines are duplicates, such as below, except for the date-time stamps.

11/10/2022-08:32:29.891692  [**] [1:2210054:1] SURICATA STREAM excessive retransmissions [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-08:34:21.185990  [**] [1:2210054:1] SURICATA STREAM excessive retransmissions [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-08:34:21.246621  [**] [1:2210054:1] SURICATA STREAM excessive retransmissions [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-12:47:06.318702  [**] [1:2210038:2] SURICATA STREAM FIN out of window [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-12:47:06.537754  [**] [1:2210038:2] SURICATA STREAM FIN out of window [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/10/2022-12:47:06.969727  [**] [1:2210038:2] SURICATA STREAM FIN out of window [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/14/2022-10:45:56.543566  [**] [1:2230027:1] SURICATA TLS certificate invalid der [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/14/2022-10:45:56.555059  [**] [1:2230027:1] SURICATA TLS certificate invalid der [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}
11/14/2022-10:45:56.555386  [**] [1:2230027:1] SURICATA TLS certificate invalid der [**] [Classification: Generic Protocol Command Decode] [Priority: 3] {TCP}

I'm interested in writing only the unique Message and corresponding GID:SID to another file.  The Message and the GID:SID on the same line of course go with each other such as:

Message = SURICATA STREAM excessive retransmissions
GID:SID = 1:2210054

An example of the Message and corresponding GID:SID needed format to be written to another file from the above example data, deduped, would be:

\# SURICATA STREAM excessive retransmissions
1:2210054

\# SURICATA STREAM FIN out of window
1:2210038

\# SURICATA TLS certificate invalid der
1:2230027

The following code is what I have written, and it does write the output in the format needed to another file, but I can't seem to write the deduped Message with the corresponding GID:SID:

content = open('alerts.log', "r").readlines()
sid_outfile = "test.txt"
unique = []
with open(sid_outfile, "w") as f:
    for line in content:
        pattern = re.search(r"\[(\d:\d+):\d] (.*?) \[", line)
        if pattern not in unique:
            unique.append(pattern)
        if unique:
            f.write("# " + pattern.group(2) + "\n")
            f.write(pattern.group(1) + "\n\n")

I've also tried the set() method with no luck in the code -

unique = set()
unique.add(pattern)

Anyone have an ideas on how the code needs to be written in order to write the deduped format needed to another file?  Any assistance would be most helpful.

Thank you.


问:
C open mp wrong calculation without print
```<code>#include<stdio.h>
#include<omp.h>
#include<stdlib.h>

float FloatRandomizer(float a, float b)
{
    float randomNumber = (a + (float)rand() / (float)(RAND_MAX / b));

    if (randomNumber > b)
        randomNumber = randomNumber - a;

    return randomNumber;
}

float F(float x)
{
    return x * x;
}

int main()
{
    int n = 1000000;

    float a;
    printf("a = "); scanf_s("%f", &a);

    float b;
    printf("b = "); scanf_s("%f", &b);

    float temp = (b - a) / n;

    float sum = 0;
    int i;

#pragma omp parallel for shared(sum)
    for (i = 0; i < n; i++)
    {
        float randomNumber = FloatRandomizer(a, b);
        sum = sum + F(randomNumber);
        //printf("threadNum = %d\nsum = %f\n", omp_get_thread_num(), sum);
    }

    float result = temp * sum;
    printf("result = %f", result);
}
</code>```

There are not to much things to say. I am trying to get definite integral within given [a,b] range with Monte-Carlo method. So basically everything works, problems started when I wrote #pragma open mp for statement, it calculates result(that for a = 0 and b = 1 should be 1/3) in wrong way without commented line within for loop but with printf it calculates it correctly. I can't understand the problem

Without printf:

With printf for same a and b(last line of big output):

I am using Microsoft Windows 10 and Microsoft Visual Studio.

Body:
#include<stdio.h>
#include<omp.h>
#include<stdlib.h>

float FloatRandomizer(float a, float b)
{
    float randomNumber = (a + (float)rand() / (float)(RAND_MAX / b));

    if (randomNumber > b)
        randomNumber = randomNumber - a;

    return randomNumber;
}

float F(float x)
{
    return x * x;
}

int main()
{
    int n = 1000000;

    float a;
    printf("a = "); scanf_s("%f", &a);

    float b;
    printf("b = "); scanf_s("%f", &b);

    float temp = (b - a) / n;

    float sum = 0;
    int i;

#pragma omp parallel for shared(sum)
    for (i = 0; i < n; i++)
    {
        float randomNumber = FloatRandomizer(a, b);
        sum = sum + F(randomNumber);
        //printf("threadNum = %d\nsum = %f\n", omp_get_thread_num(), sum);
    }

    float result = temp * sum;
    printf("result = %f", result);
}

There are not to much things to say. I am trying to get definite integral within given [a,b] range with Monte-Carlo method. So basically everything works, problems started when I wrote #pragma open mp for statement, it calculates result(that for a = 0 and b = 1 should be 1/3) in wrong way without commented line within for loop but with printf it calculates it correctly. I can't understand the problem

Without printf:

With printf for same a and b(last line of big output):

I am using Microsoft Windows 10 and Microsoft Visual Studio.


问:
How to capture all the data of a dynamic list
I'm scraping a list that changes over time
the problem is that:
As new values are added the old ones are hidden.
so I need to continue the list but only if the sequence is not in it as you can see in the pictures

I got the first list
then I tried to get the index where the new list differs from the previous one
then add to the first list the new list from the generated index.

```<code>def achar_ind(lista: list, nova_lista: list):
    inds: list = []
    ind: list = []
    for i in enumerate(nova_lista):
        for k in lista:
            if i[1] == k:
                if not ind:
                    ind += [i[0]]
                else:
                    if ind[-1] + 1 == i[0]:
                        # print(f'**********************\t{i[0]}')
                        ind += [i[0]]
                    else:
                        inds += [ind]
                        ind = [i[0]]

                break
    inds += [ind]
    return inds
</code>```
```<code>def add(lista: list, nova_lista: list):
    a: list = []
    a += max(achar_ind(lista, nova_lista), key=len)
    return a[-1]
</code>```
```<code>grafico += [x for x in novo_grafico[add(grafico, novo_grafico)+1:] if len(novo_grafico) - 1 != add(grafico, novo_grafico)]
</code>```

Body:
I'm scraping a list that changes over time
the problem is that:
As new values are added the old ones are hidden.
so I need to continue the list but only if the sequence is not in it as you can see in the pictures

I got the first list
then I tried to get the index where the new list differs from the previous one
then add to the first list the new list from the generated index.

def achar_ind(lista: list, nova_lista: list):
    inds: list = []
    ind: list = []
    for i in enumerate(nova_lista):
        for k in lista:
            if i[1] == k:
                if not ind:
                    ind += [i[0]]
                else:
                    if ind[-1] + 1 == i[0]:
                        # print(f'**********************\t{i[0]}')
                        ind += [i[0]]
                    else:
                        inds += [ind]
                        ind = [i[0]]

                break
    inds += [ind]
    return inds

def add(lista: list, nova_lista: list):
    a: list = []
    a += max(achar_ind(lista, nova_lista), key=len)
    return a[-1]

grafico += [x for x in novo_grafico[add(grafico, novo_grafico)+1:] if len(novo_grafico) - 1 != add(grafico, novo_grafico)]


问:
Uncaught TypeError: Cannot call a class as a function
I am getting an Error while giving store value in index.js

Store.js

```<code>import { legacy_createStore as createStore, combineReducers, applyMiddleware } from "redux";
import thunk from 'react-thunk';
import { composeWithDevTools} from 'redux-devtools-extension'
import { productReducer } from "./reducers/productReducer";

const reducer = combineReducers({
    products:productReducer,
});
let initialState = {};
const middleware = [thunk];
const  store = createStore(reducer,  initialState, composeWithDevTools(applyMiddleware(...middleware)));

export default store;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {Provider} from 'react-redux';
import store from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

</code>```

I am expecting that something is missing in script.js file

Body:
I am getting an Error while giving store value in index.js

Store.js

import { legacy_createStore as createStore, combineReducers, applyMiddleware } from "redux";
import thunk from 'react-thunk';
import { composeWithDevTools} from 'redux-devtools-extension'
import { productReducer } from "./reducers/productReducer";

const reducer = combineReducers({
    products:productReducer,
});
let initialState = {};
const middleware = [thunk];
const  store = createStore(reducer,  initialState, composeWithDevTools(applyMiddleware(...middleware)));

export default store;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {Provider} from 'react-redux';
import store from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

I am expecting that something is missing in script.js file


问:
Code completion with antlr4-c3: getting recursive scope
I am trying to use the code completion with antlr4-c3.

Suppose that the list of suggestions for the function argument depends on the function's name. So for the following expression

```<code>foo(bar(...))
</code>```

I want to get a list of ["foo", "bar"] so that I can perform autocompletion where the dots are.

Here is the grammar example:

```<code>grammar Scope;

expression:
      function
    | INT
;

function:
    NAME '(' expression ')'
;

NAME: [a-z]+;
INT:  [0-9]+;
WS:        [ \n\r\t] -> channel(HIDDEN);

</code>```

This is my attempt to get this information:

```<code>        const inputStream = CharStreams.fromString("foo(bar(123))");
        const lexer = new ScopeLexer(inputStream);
        const tokenStream = new CommonTokenStream(lexer);

        const parser = new ScopeParser(tokenStream);
        const errorListener = new ErrorListener();
        parser.addErrorListener(errorListener);
        parser.expression();

        const core = new c3.CodeCompletionCore(parser);

        core.preferredRules = new Set([ScopeParser.RULE_function]);

        const candidates = core.collectCandidates(5);

        console.log("=================== rules ======================");
        for (const [key, value] of candidates.rules) {
            console.log(key, value);
            let functions = candidates.rules.get(ScopeParser.RULE_function)?.ruleList;
            console.log(functions);
        }
</code>```

but all it returns is this:

```<code>=================== rules ======================
1 { startTokenIndex: 0, ruleList: [ 0 ] }
[ 0 ]
</code>```

Any suggestions how to get the list of function names?

If I turn on the debug information

```<code>        core.showDebugOutput=true;
        core.showRuleStack=true;
</code>```

I could see that the stack of functions I am looking for was created internally, but then the stack is unwound before returning the candidate object.

```<code><0> Current state: [0 rule start] in expression
expression
<0> Current state: [6 block start] in expression
expression
<0> Current state: [5 basic] in expression
expression
<0> Current state: [4 basic] in expression
expression
  <0> Current state: [2 rule start] in function
expression
function
  <0> Current state: [8 basic] in function
expression
function
=====> consumed:  NAME
  <1> Current state: [9 basic] in function
expression
function
=====> consumed:  '('
  <2> Current state: [10 basic] in function
expression
function
    <2> Current state: [0 rule start] in expression
expression
function
expression
    <2> Current state: [6 block start] in expression
expression
function
expression
    <2> Current state: [5 basic] in expression
expression
function
expression
    <2> Current state: [4 basic] in expression
expression
function
expression
      <2> Current state: [2 rule start] in function
expression
function
expression
function
      <2> Current state: [8 basic] in function
expression
function
expression
function
=====> consumed:  NAME
      <3> Current state: [9 basic] in function
expression
function
expression
function
=====> consumed:  '('
      <4> Current state: [10 basic] in function
expression
function
expression
function
        <4> Current state: [0 rule start] in expression
expression
function
expression
function
expression
        <4> Current state: [6 block start] in expression
expression
function
expression
function
expression
        <4> Current state: [5 basic] in expression
expression
function
expression
function
expression
=====> consumed:  INT
        <<5>> Current state: [7 block end] in expression
expression
function
expression
function
expression
        <<5>> Current state: [1 rule stop] in expression
expression
function
expression
function
expression
        <4> Current state: [4 basic] in expression
expression
function
expression
function
expression
      <<5>> Current state: [11 basic] in function
expression
function
expression
function
=====> collected:  function

</code>```

PS. The original problem originated from JSONPath grammar. Within filters, I need to build the list of names. The list is determined by the absolute path up to this point.

Body:
I am trying to use the code completion with antlr4-c3.

Suppose that the list of suggestions for the function argument depends on the function's name. So for the following expression

foo(bar(...))

I want to get a list of ["foo", "bar"] so that I can perform autocompletion where the dots are.

Here is the grammar example:

grammar Scope;

expression:
      function
    | INT
;

function:
    NAME '(' expression ')'
;

NAME: [a-z]+;
INT:  [0-9]+;
WS:        [ \n\r\t] -> channel(HIDDEN);

This is my attempt to get this information:

        const inputStream = CharStreams.fromString("foo(bar(123))");
        const lexer = new ScopeLexer(inputStream);
        const tokenStream = new CommonTokenStream(lexer);

        const parser = new ScopeParser(tokenStream);
        const errorListener = new ErrorListener();
        parser.addErrorListener(errorListener);
        parser.expression();

        const core = new c3.CodeCompletionCore(parser);

        core.preferredRules = new Set([ScopeParser.RULE_function]);

        const candidates = core.collectCandidates(5);

        console.log("=================== rules ======================");
        for (const [key, value] of candidates.rules) {
            console.log(key, value);
            let functions = candidates.rules.get(ScopeParser.RULE_function)?.ruleList;
            console.log(functions);
        }

but all it returns is this:

=================== rules ======================
1 { startTokenIndex: 0, ruleList: [ 0 ] }
[ 0 ]

Any suggestions how to get the list of function names?

If I turn on the debug information

        core.showDebugOutput=true;
        core.showRuleStack=true;

I could see that the stack of functions I am looking for was created internally, but then the stack is unwound before returning the candidate object.

<0> Current state: [0 rule start] in expression
expression
<0> Current state: [6 block start] in expression
expression
<0> Current state: [5 basic] in expression
expression
<0> Current state: [4 basic] in expression
expression
  <0> Current state: [2 rule start] in function
expression
function
  <0> Current state: [8 basic] in function
expression
function
=====> consumed:  NAME
  <1> Current state: [9 basic] in function
expression
function
=====> consumed:  '('
  <2> Current state: [10 basic] in function
expression
function
    <2> Current state: [0 rule start] in expression
expression
function
expression
    <2> Current state: [6 block start] in expression
expression
function
expression
    <2> Current state: [5 basic] in expression
expression
function
expression
    <2> Current state: [4 basic] in expression
expression
function
expression
      <2> Current state: [2 rule start] in function
expression
function
expression
function
      <2> Current state: [8 basic] in function
expression
function
expression
function
=====> consumed:  NAME
      <3> Current state: [9 basic] in function
expression
function
expression
function
=====> consumed:  '('
      <4> Current state: [10 basic] in function
expression
function
expression
function
        <4> Current state: [0 rule start] in expression
expression
function
expression
function
expression
        <4> Current state: [6 block start] in expression
expression
function
expression
function
expression
        <4> Current state: [5 basic] in expression
expression
function
expression
function
expression
=====> consumed:  INT
        <<5>> Current state: [7 block end] in expression
expression
function
expression
function
expression
        <<5>> Current state: [1 rule stop] in expression
expression
function
expression
function
expression
        <4> Current state: [4 basic] in expression
expression
function
expression
function
expression
      <<5>> Current state: [11 basic] in function
expression
function
expression
function
=====> collected:  function

PS. The original problem originated from JSONPath grammar. Within filters, I need to build the list of names. The list is determined by the absolute path up to this point.


问:
Correct trade direction at market open
How can I read the trade direction Long/Short of the last trade and trigger it when the market opens. Otherwise, with a time unit of 30 minutes, the script has to wait 30 minutes before it can be traded. It would therefore be great if you could read the last direction that is displayed in the premarket in tradingview and start a trade directly when the market opens. Is that possible? The question is, can I read the previous trade in Tradingview Premarket and can it be triggered as a trade on the first candle? In addition, the trade should only be executed once by the market open.</p>
```<code>is_long = strategy.position_size[1] > 0
is_short = strategy.position_size[1] < 0

if(is_long and barstate.islast and start_richt == 0)
    alertLongEntry = input.string("Test Long {{ticker}}!", "Alert Message Long Entry: ", group = "Alert Settings")
    strategy.entry("GL", strategy.long, alert_message = alertLongEntry)

if(is_short and barstate.islast and start_richt == 0)
    alertShortEntry = input.string("Test Short {{ticker}}!", "Alert Message Short Entry: ", group = "Alert Settings")
    strategy.entry("GS", strategy.long, alert_message = alertShortEntry)

</code>```

Title: Correct trade direction at market open

Body:
How can I read the trade direction Long/Short of the last trade and trigger it when the market opens. Otherwise, with a time unit of 30 minutes, the script has to wait 30 minutes before it can be traded. It would therefore be great if you could read the last direction that is displayed in the premarket in tradingview and start a trade directly when the market opens. Is that possible? The question is, can I read the previous trade in Tradingview Premarket and can it be triggered as a trade on the first candle? In addition, the trade should only be executed once by the market open.

is_long = strategy.position_size[1] > 0
is_short = strategy.position_size[1] < 0

if(is_long and barstate.islast and start_richt == 0)
    alertLongEntry = input.string("Test Long {{ticker}}!", "Alert Message Long Entry: ", group = "Alert Settings")
    strategy.entry("GL", strategy.long, alert_message = alertLongEntry)

if(is_short and barstate.islast and start_richt == 0)
    alertShortEntry = input.string("Test Short {{ticker}}!", "Alert Message Short Entry: ", group = "Alert Settings")
    strategy.entry("GS", strategy.long, alert_message = alertShortEntry)


问:
Qt - Custom Window title bar
I want to implement a custom window frame in my application and have been looking for a solution to this problem for a long time. And everywhere I searched, it was only said about the Qt::FramelessWindowHint flag and that you need to implement the functions of moving and resizing the window yourself. But I need to have other functions like window binding and win + arrow key combinations (if we are talking about windows).

I have come across the startSystemMove() and startSystemResize() functions but they don't work properly with the Qt::FramelessWindowHint and Qt::CustomizeWindowHint flags.
A good example for an application that has all these features is Telegram Desktop which also uses Qt.

Title: Qt - Custom Window title bar


问:
Firefox: Print Preview generating first page blank and also the header and foooter overlapping in print view
Browse this url in firefox and open print preview
https://webexpostage.primoportal.com/#/p/8037-229134-CZ-OR

Print preview should not display the first empty page.


问:
Providing a default value to a parameter that uses ArgumentCompletions attribute
Here is a distilled version of my function:

```<code>function Get-CommandBar{
    [CmdletBinding()]
    [Alias("GCom")]
    Param(
        [Parameter()]
        [string]$Path = $pwd,
        [Parameter()]
        [ArgumentCompletions('Path', 'Copy')]
        $ActiveTab = 'Path',
        [Switch]$ActiveVideo,
        [Switch]$AllTabs
        )

        begin{

        }
        process {
            Switch ($PSBoundParameters.Keys){
                'ActiveTab'{
                    If ($ActiveTab -eq "Path"){
                        "Path"
                    }elseif($ActiveTab -eq "Copy"){
                        "Copy"
                    }
                }
                'AllTabs'{
                    "All Tabs"
                }
                'ActiveVideo'{
                    "Active Video"

                }
         }
        }
}
</code>```

 get-CommandBar -ActiveTab Path outputs:

```<code>Path
</code>```

 get-CommandBar -ActiveTab Copy outputs:

```<code>Copy
</code>```

But trying just get-CommandBar -ActiveTab, instead of Path, it outputs an error:

```<code>Get-CommandBar: Missing an argument for parameter 'ActiveTab'. Specify a parameter of type 'System.Object' and try again.
</code>```

What gives? Shouldnt $ActiveTab = 'Path' be sufficient? Information on ArgumentCompletions seems to be sparse out here.m
Any help would be wonderfull.

Body:
Here is a distilled version of my function:

function Get-CommandBar{
    [CmdletBinding()]
    [Alias("GCom")]
    Param(
        [Parameter()]
        [string]$Path = $pwd,
        [Parameter()]
        [ArgumentCompletions('Path', 'Copy')]
        $ActiveTab = 'Path',
        [Switch]$ActiveVideo,
        [Switch]$AllTabs
        )

        begin{

        }
        process {
            Switch ($PSBoundParameters.Keys){
                'ActiveTab'{
                    If ($ActiveTab -eq "Path"){
                        "Path"
                    }elseif($ActiveTab -eq "Copy"){
                        "Copy"
                    }
                }
                'AllTabs'{
                    "All Tabs"
                }
                'ActiveVideo'{
                    "Active Video"

                }
         }
        }
}

 get-CommandBar -ActiveTab Path outputs:

Path

 get-CommandBar -ActiveTab Copy outputs:

Copy

But trying just get-CommandBar -ActiveTab, instead of Path, it outputs an error:

Get-CommandBar: Missing an argument for parameter 'ActiveTab'. Specify a parameter of type 'System.Object' and try again.

What gives? Shouldnt $ActiveTab = 'Path' be sufficient? Information on ArgumentCompletions seems to be sparse out here.m
Any help would be wonderfull.


问:
Asus Aura SDK not changing the colors of the RGB devices (Python)
Not sure why this is not working, as I followed the tutorial on ASUS's website:

Python Tutorial

```<code>import win32com.client

print('hello!')
auraSDK = win32com.client.Dispatch('aura.sdk.1')

auraSDK.SwitchMode()
devices = auraSDK.Enumerate(0)

for dev in devices:
    for i in range(dev.Lights.Count):
        dev.Lights(i).color = 0x00FF0000
    dev.Apply()

print('done')
</code>```

I can see that the instance of aura SDK is properly created, as in Armoury Crate the SDK goes into 'standby' mode, but none of the colors change on the devices.

The line:

```<code>devices = auraSDK.Enumerate(0)
</code>```

is supposed to return a collection of all the devices, which are accessed and the colors are changed with the for-in loop. Not really sure where I went wrong here and any help is greatly appreciated.

Body:
Not sure why this is not working, as I followed the tutorial on ASUS's website:

Python Tutorial

import win32com.client

print('hello!')
auraSDK = win32com.client.Dispatch('aura.sdk.1')

auraSDK.SwitchMode()
devices = auraSDK.Enumerate(0)

for dev in devices:
    for i in range(dev.Lights.Count):
        dev.Lights(i).color = 0x00FF0000
    dev.Apply()

print('done')

I can see that the instance of aura SDK is properly created, as in Armoury Crate the SDK goes into 'standby' mode, but none of the colors change on the devices.

The line:

devices = auraSDK.Enumerate(0)

is supposed to return a collection of all the devices, which are accessed and the colors are changed with the for-in loop. Not really sure where I went wrong here and any help is greatly appreciated.


问:
Firebase signInWithPopup function does not return correct error
I have this following code for retrieving user data with Facebook provider. I encountered an error, regarding users already stored with the same credentials.

Furthermore, I found a solution, implemented it, but it depends on the parameter error.

It should be an object, Firebase documentation even says it should be an object.

Has anyone encountered this problem ?
It is really bugging me out.

```<code>async loginWithFacebook() {
    try {
      const userCred = await signInWithPopup(
        this.auth,
        new FacebookAuthProvider()
      );
      return {
        user: userCred.user,
      };
    } catch (error) {
      console.log(error);

      return {
        error: "Some error occured",
      };
    }
  }
</code>```

I tried to use a different sign in method, but nothing changed.

Body:
I have this following code for retrieving user data with Facebook provider. I encountered an error, regarding users already stored with the same credentials.

Furthermore, I found a solution, implemented it, but it depends on the parameter error.

It should be an object, Firebase documentation even says it should be an object.

Has anyone encountered this problem ?
It is really bugging me out.

async loginWithFacebook() {
    try {
      const userCred = await signInWithPopup(
        this.auth,
        new FacebookAuthProvider()
      );
      return {
        user: userCred.user,
      };
    } catch (error) {
      console.log(error);

      return {
        error: "Some error occured",
      };
    }
  }

I tried to use a different sign in method, but nothing changed.


问:
How to invoke a custom code generating target before a VC++ project is compiled with VS 2019?
I have a solution with C# and C++ projects. Visual Studio 2019 is what is being used to build. I have a target that generates a .h file which affects all the native projects (i.e. C++ projects).
I like this target be invoked before compiling any C++ code.

How do I do it?

I added a property like below and rebuilt the C++ project. I don't see MyGenFiles getting invoked.

<BeforeClCompileTargets>$(BeforeClCompileTargets);MyGenFiles</BeforeClCompileTargets>

Update

Above is the right approach to get this done. It happened to be my verifications that was the problem. I added a message task as Jonathan suggested, I could see the target getting invoked.


问:
how to increase or get desired distance along the X axis in BoxPlot?
How do I manually set the distances along the X-axis so I can read all the column names properly?

Code

```<code>trainData[trainData.columns].plot(kind='box',widths=0.1, grid = True)
</code>```

Body:
How do I manually set the distances along the X-axis so I can read all the column names properly?

Code

trainData[trainData.columns].plot(kind='box',widths=0.1, grid = True)


问:
How to add a top title above the header line
I need to add a TITLE just above header using Pandas script.

```<code>Sl_No  Departure    Arrival
 1      UK          India
 2      US          India
 3      France      India
 4      New York    Singapore
 5      Tokyo       Singapore
</code>```

I tried the below script but I'm not sure what changes I need to do in order to add TTITLE(top title)

```<code>    import os
    os.chdir("/dev/alb_shrd/alb/alb_prj/Files/albt/alt/scrpts")

    # Reading the csv file

    import pandas as pd
    print(pd.__file__)
    col_names=["Sl_No","Departure","Arrival"]

    df_new  = pd.read_csv("SourceFile.csv", quotechar='"',names=col_names, sep="|",skiprows=1, low_memory=False,error_bad_lines=False,header=None).dropna(axis=1, how="all")

header = pd.MultiIndex.from_product([["TOP TITLE"],list(df_new.columns)])
df_new.head()

pd.DataFrame(df_new.to_numpy(), None , columns = header).head()

    # Saving xlsx file

    file = f"SourceFile_{pd.Timestamp('now').strftime('%Y%m%d_%I%M')}.xlsx"
    df_new.to_excel(file, index=False)
</code>```

Can anyone guide me how to add title at the top of the excel?

Thanks!

Body:
I need to add a TITLE just above header using Pandas script.

Sl_No  Departure    Arrival
 1      UK          India
 2      US          India
 3      France      India
 4      New York    Singapore
 5      Tokyo       Singapore

I tried the below script but I'm not sure what changes I need to do in order to add TTITLE(top title)

    import os
    os.chdir("/dev/alb_shrd/alb/alb_prj/Files/albt/alt/scrpts")

    # Reading the csv file

    import pandas as pd
    print(pd.__file__)
    col_names=["Sl_No","Departure","Arrival"]

    df_new  = pd.read_csv("SourceFile.csv", quotechar='"',names=col_names, sep="|",skiprows=1, low_memory=False,error_bad_lines=False,header=None).dropna(axis=1, how="all")

header = pd.MultiIndex.from_product([["TOP TITLE"],list(df_new.columns)])
df_new.head()

pd.DataFrame(df_new.to_numpy(), None , columns = header).head()

    # Saving xlsx file

    file = f"SourceFile_{pd.Timestamp('now').strftime('%Y%m%d_%I%M')}.xlsx"
    df_new.to_excel(file, index=False)

Can anyone guide me how to add title at the top of the excel?

Thanks!


问:
Preview mode on Google Tag Manager does not work for me (timeout)
A timeout occurred while attempting to connect

Could not connect to localhost


问:
Bind shape object to axis/position and make transition based on condition
I'm trying to create rectangle shapes that move to the left at the same time as the x axis, and these rectangles should shrink and disappear when they reach the y-axis. For testing purposes, the transition starts when clicking on the bottom left button and a fiddle can be found here.

As a quick overview of the code, basically my rectangles width is determined by the space between a capitalised letter and it's small form in a given string (eg. RJjR would produce a rectangle of size 3 (R..r) and of size 1 (Jj)) so I have a function that computes the distances and thus the sizes.

So an idea would be to bind the rectangles to some coordinates of my x-axis, and they would then move at the same time the x-axis moves. It would be very useful as I could precompute all the rectangles positions, create them with enter() and then simply make my x-axis transition, carrying the rectangles with it. If this is not possible, any other idea would be appreciated.

Right now these 2 transitions are independent, and I make my axis transition by changing its domain but I have a feeling it's not the right way to do what I want

Another thing I'm trying to achieve and can't seem to accomplish is to make the rectangles shrink to 0 when they reach x=0. I tried to make a transition that would reduce their width to 0 however this transitions occurs after the second one while I would want the rectangles to start shrinking as soon as they reach x=0 and I'm unsure how to that. I searched for conditional transitions but couldn't find anything that fit my objective.

For now this is what I have for the transitions:

```<code>
            function triggerMovement(){

                x.domain([15,keys.length])

                sVg.selectAll("rect")
               .transition()
               .duration(5000)
               .attr("x", 0)
               .transition()
               .attr("width", 0)

                // Update the axis
                sVg.select(".x_axis")
                .transition()
                .duration(5000)
                .call(d3.axisBottom(x))
            }
</code>```

To get an overview of the end result I'm trying to get, imagine a frieze of size 0-100 with rectangles of size 2 at some specific positions, say x=10, x=20 and x=50. At first the x-axis would only show the domain [0,15] and only the first rectangle would be visible. Then the x-axis would start transitioning to the left, the rect at x=10 would start shrinking when the x-tick = 10 reaches the y-axis, then the 2nd and 3rd rectangles would appear and disappear the same way.

Thank you for your help and let me know if I'm not clear enough.

Body:
I'm trying to create rectangle shapes that move to the left at the same time as the x axis, and these rectangles should shrink and disappear when they reach the y-axis. For testing purposes, the transition starts when clicking on the bottom left button and a fiddle can be found here.

As a quick overview of the code, basically my rectangles width is determined by the space between a capitalised letter and it's small form in a given string (eg. RJjR would produce a rectangle of size 3 (R..r) and of size 1 (Jj)) so I have a function that computes the distances and thus the sizes.

So an idea would be to bind the rectangles to some coordinates of my x-axis, and they would then move at the same time the x-axis moves. It would be very useful as I could precompute all the rectangles positions, create them with enter() and then simply make my x-axis transition, carrying the rectangles with it. If this is not possible, any other idea would be appreciated.

Right now these 2 transitions are independent, and I make my axis transition by changing its domain but I have a feeling it's not the right way to do what I want

Another thing I'm trying to achieve and can't seem to accomplish is to make the rectangles shrink to 0 when they reach x=0. I tried to make a transition that would reduce their width to 0 however this transitions occurs after the second one while I would want the rectangles to start shrinking as soon as they reach x=0 and I'm unsure how to that. I searched for conditional transitions but couldn't find anything that fit my objective.

For now this is what I have for the transitions:

            function triggerMovement(){

                x.domain([15,keys.length])

                sVg.selectAll("rect")
               .transition()
               .duration(5000)
               .attr("x", 0)
               .transition()
               .attr("width", 0)

                // Update the axis
                sVg.select(".x_axis")
                .transition()
                .duration(5000)
                .call(d3.axisBottom(x))
            }

To get an overview of the end result I'm trying to get, imagine a frieze of size 0-100 with rectangles of size 2 at some specific positions, say x=10, x=20 and x=50. At first the x-axis would only show the domain [0,15] and only the first rectangle would be visible. Then the x-axis would start transitioning to the left, the rect at x=10 would start shrinking when the x-tick = 10 reaches the y-axis, then the 2nd and 3rd rectangles would appear and disappear the same way.

Thank you for your help and let me know if I'm not clear enough.


问:
Getting spot gold price without API
Apparently it was possible to query spot gold data using Pandas Datareader, but when I run the query mentioned in the issue, I get an error.  Alternative methods welcome.

```<code>import pandas as pd
from pandas_datareader import data
import yfinance as yf
yf.pdr_override()

data.DataReader("GOLDAMGBD228NLBM", data_source="fred", start="2022-06-01")
</code>```

GOLDAMGBD228NLBM: No data found for this date range, symbol may be delisted

Title: Getting spot gold price without API

Body:
Apparently it was possible to query spot gold data using Pandas Datareader, but when I run the query mentioned in the issue, I get an error.  Alternative methods welcome.

import pandas as pd
from pandas_datareader import data
import yfinance as yf
yf.pdr_override()

data.DataReader("GOLDAMGBD228NLBM", data_source="fred", start="2022-06-01")

GOLDAMGBD228NLBM: No data found for this date range, symbol may be delisted


问:
Failed to load resource: the server responded with a status of 400 (Bad Request)
Error

```<code>SyntaxError: Unexpected token " in JSON at position 0
</code>```

API

```<code>localhost:5000/api/notes/addnote
</code>```

Backend fetch

```<code>{
  "title": "msy nsssode",
  "description": "msy nessssw node",
  "tag": "youtsube",
  "_id": "639f52fe3229edcb8fbaff02",
  "date": "1671385854719",
  "__v": 0
}
</code>```

Front End

```<code>import React from "react";
import noteContext from "./noteContext";
import { useState } from "react";

const NoteState = (props) =\> {
const host = "http://localhost:5000/"
const noteInitial = \[\]

    const [notes, setNotes] = useState(noteInitial)

    //Add a Note
    const addNote = async (title, description, tag) => {
        //Fatch Note

        const response = await fetch(`${host}api/notes/addnote`, {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            headers: {
                'Content-Type': 'application/json',
                'auth-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7InVzZXIiOnsiaWQiOiI2Mzk4YmE5ZDc5YzUyYzc0ZWNiMTljODkifX0sImlhdCI6MTY3MDk1MzYyOX0.P_NkVud_5_kpOrCTOG9nMAxFowNT5VKslboBcYeDJXk'
            },
            body: JSON.stringify(title, description, tag) // body data type must match "Content-Type" header
        });
        const json = await response.json(); // parses JSON response into native JavaScript objects
        console.log(json)

        console.log("adding a new note")
        const note = {
            "_id": "639a00edea0a1c6ab5jjje19b6e7",
            "title": title,
            "description": description,
            "tag": tag,
            "date": "1671037166242",
            "__v": 0
        };
        setNotes(notes.concat(note))
    }

    return (
        <noteContext.Provider value={{addNote}}>
            {props.children};
        </noteContext.Provider>
    )

}

export default NoteState;
</code>```

API is not fetched when I want to add notes by input tag.
the same has been showing, when I am modified by modal.

Body:
Error

SyntaxError: Unexpected token " in JSON at position 0

API

localhost:5000/api/notes/addnote

Backend fetch

{
  "title": "msy nsssode",
  "description": "msy nessssw node",
  "tag": "youtsube",
  "_id": "639f52fe3229edcb8fbaff02",
  "date": "1671385854719",
  "__v": 0
}

Front End

import React from "react";
import noteContext from "./noteContext";
import { useState } from "react";

const NoteState = (props) =\> {
const host = "http://localhost:5000/"
const noteInitial = \[\]

    const [notes, setNotes] = useState(noteInitial)

    //Add a Note
    const addNote = async (title, description, tag) => {
        //Fatch Note

        const response = await fetch(`${host}api/notes/addnote`, {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            headers: {
                'Content-Type': 'application/json',
                'auth-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7InVzZXIiOnsiaWQiOiI2Mzk4YmE5ZDc5YzUyYzc0ZWNiMTljODkifX0sImlhdCI6MTY3MDk1MzYyOX0.P_NkVud_5_kpOrCTOG9nMAxFowNT5VKslboBcYeDJXk'
            },
            body: JSON.stringify(title, description, tag) // body data type must match "Content-Type" header
        });
        const json = await response.json(); // parses JSON response into native JavaScript objects
        console.log(json)

        console.log("adding a new note")
        const note = {
            "_id": "639a00edea0a1c6ab5jjje19b6e7",
            "title": title,
            "description": description,
            "tag": tag,
            "date": "1671037166242",
            "__v": 0
        };
        setNotes(notes.concat(note))
    }

    return (
        <noteContext.Provider value={{addNote}}>
            {props.children};
        </noteContext.Provider>
    )

}

export default NoteState;

API is not fetched when I want to add notes by input tag.
the same has been showing, when I am modified by modal.


问:
.NET: Calling a cshtml.cs function in cshtml , trying to get a user input passed onto the arguments in the cshtmly.cs function
I have looked at these links : I am trying to pass two user inputs onto the the add function which takes two parameters. Most of the searches reference asp.net. Was looking to do it just on .net.

Calling a C# function when input is changed in cshtml

Call function from cshtml to cshtml.cs using Models

Call function from cshtml to cshtml.cs using Models

@page
@model DropdownModel
@{
    ViewData["Title"] = "Calculator";
    ViewData["Add"] = "The Calculator";
}

@ViewData["Title"]

    @MyPortal.Pages.DropdownModel.Addnumber.Addnumbers(3,2);

Use this page for a calculator project.
```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>  public class Addnumber
        {
            public static int Addnumbers(int firstnum , int secnum)
            {
                return firstnum + secnum;

            }
        }</code>```

Body:
I have looked at these links : I am trying to pass two user inputs onto the the add function which takes two parameters. Most of the searches reference asp.net. Was looking to do it just on .net.

Calling a C# function when input is changed in cshtml

Call function from cshtml to cshtml.cs using Models

Call function from cshtml to cshtml.cs using Models

@page
@model DropdownModel
@{
    ViewData["Title"] = "Calculator";
    ViewData["Add"] = "The Calculator";
}

@ViewData["Title"]

    @MyPortal.Pages.DropdownModel.Addnumber.Addnumbers(3,2);

Use this page for a calculator project.

  public class Addnumber
        {
            public static int Addnumbers(int firstnum , int secnum)
            {
                return firstnum + secnum;

            }
        }


问:
Download and run a Kotlin file after building the app
I have this repository of Kotlin files that contain some code. I have a way in the app where I can connect the repository and download the files, but I want to be able to run the downloaded Kotlin file after building the app. This means that the order of operations would be something along the lines of:

Build the App -> Give the app the Repository Link inside the App -> Download the Kotlin Files -> Run the Kotlin Files

So my Question is if there is a possibility to Run Kotlin Files after building the app. If so how do you do it?

Thanks and Regards


问:
react-native-fs, expo-file-system and rn-fetch-blob, will not overwrite a file on android simulator and real device
I am trying to overwrite an image with a new image on Ios works perefctly, but on android it only creates the file the first time and then you cannot ovewrite it. I tried react-native-fs, expo-file-system and rn-fetch-blob, all give me the same result. I am using android 10 on real device and android 12 simulator.

react-native-fs

```<code>  const path = "file://" + RNFS.DocumentDirectoryPath + "/sign.png";

   RNFS.writeFile(
        path,
        signature.replace("data:image/png;base64,", ""),
        "base64"
      )
        .then(() => {
          dispatch(createSignature(path));
        })
        .catch(console.error);
</code>```

expo

```<code> const path = FileSystem.cacheDirectory + "sign.png";
      FileSystem.writeAsStringAsync(
        path,
        signature.replace("data:image/png;base64,", ""),
        { encoding: FileSystem.EncodingType.Base64 }
      )
        .then(() => FileSystem.getInfoAsync(path))
        .then(() => dispatch(createSignature(path)))
        .catch(console.error);
      setSign(signature);
</code>```

rn-fetch-blob

```<code>      RNFetchBlob.fs
        .writeFile(
          `${RNFetchBlob.fs.dirs.DocumentDir}/sign.png`,
          signature.replace("data:image/png;base64,", ""),
          "base64"
        )
        .then(() => {
          dispatch(createSignature(path));
        })
        .catch((e) => console.log(e));
</code>```

Body:
I am trying to overwrite an image with a new image on Ios works perefctly, but on android it only creates the file the first time and then you cannot ovewrite it. I tried react-native-fs, expo-file-system and rn-fetch-blob, all give me the same result. I am using android 10 on real device and android 12 simulator.

react-native-fs

  const path = "file://" + RNFS.DocumentDirectoryPath + "/sign.png";

   RNFS.writeFile(
        path,
        signature.replace("data:image/png;base64,", ""),
        "base64"
      )
        .then(() => {
          dispatch(createSignature(path));
        })
        .catch(console.error);

expo

 const path = FileSystem.cacheDirectory + "sign.png";
      FileSystem.writeAsStringAsync(
        path,
        signature.replace("data:image/png;base64,", ""),
        { encoding: FileSystem.EncodingType.Base64 }
      )
        .then(() => FileSystem.getInfoAsync(path))
        .then(() => dispatch(createSignature(path)))
        .catch(console.error);
      setSign(signature);

rn-fetch-blob

      RNFetchBlob.fs
        .writeFile(
          `${RNFetchBlob.fs.dirs.DocumentDir}/sign.png`,
          signature.replace("data:image/png;base64,", ""),
          "base64"
        )
        .then(() => {
          dispatch(createSignature(path));
        })
        .catch((e) => console.log(e));


问:
Counting photos inside drawable folder
Is it possible to count quantity of images inside Resources/drawable folder in Xamarin?

I've been trying few methods and nothing works for me. For example I've been using Directory.GetFiles but Visual Studio didn't recognize path (When I paste it to File Explorer This path works).

Title: Counting photos inside drawable folder


问:
jenkins pipeline when is evaluating to false though file exits
any hint why WHEN expression is evaluating to FALSE ? I tried this solution but no luck

```<code>    stage('Code Coverage Tests') {
        steps {
            container('main') {
                catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                    sh '''
                    pwd
                    echo testinfo > /coverage-data/_coverage_report.dat
                    ls -ltr /coverage-data/
                    '''.stripIndent()
                }
            }
        }
    }
    stage('Code Coverage Scan') {
        when { expression { return fileExists ('/coverage-data/_coverage_report.dat') } }
        steps {
</code>```

output shows file exits.

```<code>+ ls -ltr /coverage-data/
total 4
-rw-r--r-- 1 jenkins jenkins 9 Dec 18 18:13 _coverage_report.dat
+ pwd
[Pipeline] stage
[Pipeline] { (Code Coverage Scan)
[Pipeline] fileExists
Stage "Code Coverage Scan" skipped due to when conditional
</code>```

Body:
any hint why WHEN expression is evaluating to FALSE ? I tried this solution but no luck

    stage('Code Coverage Tests') {
        steps {
            container('main') {
                catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                    sh '''
                    pwd
                    echo testinfo > /coverage-data/_coverage_report.dat
                    ls -ltr /coverage-data/
                    '''.stripIndent()
                }
            }
        }
    }
    stage('Code Coverage Scan') {
        when { expression { return fileExists ('/coverage-data/_coverage_report.dat') } }
        steps {

output shows file exits.

+ ls -ltr /coverage-data/
total 4
-rw-r--r-- 1 jenkins jenkins 9 Dec 18 18:13 _coverage_report.dat
+ pwd
[Pipeline] stage
[Pipeline] { (Code Coverage Scan)
[Pipeline] fileExists
Stage "Code Coverage Scan" skipped due to when conditional


问:
Sign existing app from apk to aab problem
I have an  android app that i always upload to google play as an apk with a keystore from 2018 and I use google signing which is recommended as they say, recently I signed the app and exported it as an aab with the same  old keystore but now old users can't update the app and new users can't install the app

Can anyone help me please ,is  What i did is wrong and if so  How to fix it


问:
Is there a way to handle abort in Jenkins such that a user will not be able to abort more than once?
When a user aborts a Jenkins job, the abort process starts asynchronously but the user will not be aware of that and might click abort once again which would force the job to end abruptly. Lets say there are some destroy commands in my abort section and force abort prevents the destroy operation to complete properly.

Is there any way to handle this such that a user will not be able to abort a Jenkins job more than once?


问:
.Net MAUI ListView ignores FlexLayout options and gets height of window
When a ListView is present in FlexLayout (column) it ignores the flex height configuration in a strange way: it is spaced correctly in relation to others, but cuts off some items from ItemSource at the end when the size is too small.

Here's an example for list of 20 items:

Here's the code for the inner flex:

```<code>        <FlexLayout FlexLayout.Grow="1"
                Direction="Column"
                JustifyContent="Start"
                AlignContent="Start"
                >
        <Label Text="This is spaced correctly"
               FlexLayout.Shrink="0"
               />
        <ListView x:Name="MessagesListView"
                  ItemsSource="{Binding Messages}"
                  HasUnevenRows="True"
                  FlexLayout.Grow="0"
                  FlexLayout.Shrink="1"

                  >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Content}"
                              Detail="{Binding FromUserName}"
                              DetailColor="Aquamarine"
                              />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Label Text="This is spaced correctly"
               FlexLayout.Shrink="0"
               />
    </FlexLayout>
</code>```

As you can see, 5 items are impossible to view

How can I fix the scroll to go to the end of the list so that I can view all items in a collection?

Body:
When a ListView is present in FlexLayout (column) it ignores the flex height configuration in a strange way: it is spaced correctly in relation to others, but cuts off some items from ItemSource at the end when the size is too small.

Here's an example for list of 20 items:

Here's the code for the inner flex:

        <FlexLayout FlexLayout.Grow="1"
                Direction="Column"
                JustifyContent="Start"
                AlignContent="Start"
                >

        <ListView x:Name="MessagesListView"
                  ItemsSource="{Binding Messages}"
                  HasUnevenRows="True"
                  FlexLayout.Grow="0"
                  FlexLayout.Shrink="1"

                  >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Content}"
                              Detail="{Binding FromUserName}"
                              DetailColor="Aquamarine"
                              />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

    </FlexLayout>

As you can see, 5 items are impossible to view

How can I fix the scroll to go to the end of the list so that I can view all items in a collection?


问:
Subscription Credentials Issue in Google Play Certification
I have an Android TV app that is subscription based I am trying to submit to Google Play through the publishing console.

The flow is this:

Free app downloaded -> checks for subscription

If subscribed -> see content.

If not subscribed -> see splash page stating not subscribed -> press subscribe button -> pick subscription length -> go through google play billing flow

There is no other login required/offered.

I have provided Google account credentials for an account that has an active subscription with no 2 factor authentication turned on.

I’ve tested on several Chromecast devices that I can log in with this account and then download the app through a testing track and instantly access content.

However, I keep getting rejected saying they can not access the content with the credentials provided.

Has anyone else hit this roadblock? Am I not doing something right here? It’s frustrating.

I’ve tested on several Chromecast devices that I can log in with this account and then download the app through a testing track and instantly access content.


问:
Remove characters after specific character in whole df pandas
I have a df

```<code>           BTC      ETH
High     23.00000 56.00000
</code>```

the dtype is object and its Decimal(23.00000) and Decimal(56.00000) and build from dict

```<code>{'BTC': {'High': Decimal('23.00000')},
 'ETH': {'High': Decimal('56.00000')}}
</code>```

I need df as

```<code>           BTC      ETH
High        23      56
</code>```

Tried with df.apply, df.split and round values. Nothing worked as expected.

Body:
I have a df

           BTC      ETH
High     23.00000 56.00000

the dtype is object and its Decimal(23.00000) and Decimal(56.00000) and build from dict

{'BTC': {'High': Decimal('23.00000')},
 'ETH': {'High': Decimal('56.00000')}}

I need df as

           BTC      ETH
High        23      56

Tried with df.apply, df.split and round values. Nothing worked as expected.


问:
Cannot find OpenCV module
When I try importing cv2 and running the code I get an error:

```<code>import cv2
ModuleNotFoundError: No module named 'cv2'
</code>```

even though I have used the pip install opencv-python in the command prompt.

I even used

```<code>python -m pip install --upgrade pip
</code>```

in the command prompt to try updating opencv but I keep running into the same problem. How do I resolve this issue?

Title: Cannot find OpenCV module

Body:
When I try importing cv2 and running the code I get an error:

import cv2
ModuleNotFoundError: No module named 'cv2'

even though I have used the pip install opencv-python in the command prompt.

I even used

python -m pip install --upgrade pip

in the command prompt to try updating opencv but I keep running into the same problem. How do I resolve this issue?


问:
Add over and under bars on histogram?
I'm learning Python by redoing my Excel analyses in Python but can't find a way to plot a histogram with over and under limits.

Here is what the histogram looks like in Excel and what I'm trying to replicate:
Excel histogram

And here is what I got in Python:
Python histogram

Here is my the actual code:

```<code>returns = [r for r in df.Returns.tolist() if np.isnan(r)==False]
plt.hist(returns, bins=20, range=(-10, 10), rwidth=0.8)
plt.show()
</code>```

The reason why I added this range limit is to have an "incremental" histogram (combined with this number of bins).

As you can see, my Excel histogram has a <= -10% and >10% bar on the leftmost and rightmost side, but my Python histogram does not.

I can only think of 2 other ways to solve this issue:

Manually plotting the histogram which is extremely inconvenient, especially if the number of bin increases

Counting the number of values under/over the limits and inserting the bar into the histogram. But I was unable to find a way to do so

I suppose there must be a simpler way to do this?

Title: Add over and under bars on histogram?

Body:
I'm learning Python by redoing my Excel analyses in Python but can't find a way to plot a histogram with over and under limits.

Here is what the histogram looks like in Excel and what I'm trying to replicate:
Excel histogram

And here is what I got in Python:
Python histogram

Here is my the actual code:

returns = [r for r in df.Returns.tolist() if np.isnan(r)==False]
plt.hist(returns, bins=20, range=(-10, 10), rwidth=0.8)
plt.show()

The reason why I added this range limit is to have an "incremental" histogram (combined with this number of bins).

As you can see, my Excel histogram has a <= -10% and >10% bar on the leftmost and rightmost side, but my Python histogram does not.

I can only think of 2 other ways to solve this issue:

Manually plotting the histogram which is extremely inconvenient, especially if the number of bin increases

Counting the number of values under/over the limits and inserting the bar into the histogram. But I was unable to find a way to do so

I suppose there must be a simpler way to do this?


问:
mongodb translate pipeline from shell to code
Translating pipelines and queries in mongodb from shell to code requires specific steps.  Could you point me toward a reference on what's required?

For example, a pipeline in mongosh converts to a JSON string for mongolite in r, quotes need to be in added, $ added to field names.

For a pipeline in mongosh what are the steps to convert it to mongolite?
Could you recommend a reference on the differences between shell and code queries in mongodb?


问:
in POWERSHELL, why does system.SYSTEM.NET.SOCKETS.UDPCLIENT fail to show results from udp port?
Here's a code snippet

```<code>$netClient = [System.Net.Sockets.UdpClient]::new()
$netClient.client.SendTimeout = 2
$netClient.client.ReceiveTimeout = 2
$netClient.Connect( $Computer , 53) #i use DNS port as an example
$task = $netClient.ReceiveAsync()
</code>```

$task stays in perpetual "WaitingForActivation"

Maybe I need to "send" first? If so, I'm not sure what to send to check any given UDP port.

```<code>Id IsCompleted Status
-- ----------- ------
1  False       WaitingForActivation
</code>```

I've found many powershell scripts in the wild, but they all provide false positives with this similar code snippet.

Body:
Here's a code snippet

$netClient = [System.Net.Sockets.UdpClient]::new()
$netClient.client.SendTimeout = 2
$netClient.client.ReceiveTimeout = 2
$netClient.Connect( $Computer , 53) #i use DNS port as an example
$task = $netClient.ReceiveAsync()

$task stays in perpetual "WaitingForActivation"

Maybe I need to "send" first? If so, I'm not sure what to send to check any given UDP port.

Id IsCompleted Status
-- ----------- ------
1  False       WaitingForActivation

I've found many powershell scripts in the wild, but they all provide false positives with this similar code snippet.


问:
Custom CLI options in Vite/Rollup
I use Vite 4 and I need to specify custom options in the command line to modify my Vite config (vite.config.js) based on given values:

npm run build -- --custom-option=value

However, the command fails with this error:

CACError: Unknown option '--custom-option'

I've only found that Vite blocks custom commands on purpose. Is there a way to bypass it?

If it helps, these are my scripts in package.json:

```<code>  "scripts": {
    "serve": "vite",
    "build": "vite build --mode=production",
    "dev": "vite build --mode=development"
  }
</code>```

Title: Custom CLI options in Vite/Rollup

Body:
I use Vite 4 and I need to specify custom options in the command line to modify my Vite config (vite.config.js) based on given values:

npm run build -- --custom-option=value

However, the command fails with this error:

CACError: Unknown option '--custom-option'

I've only found that Vite blocks custom commands on purpose. Is there a way to bypass it?

If it helps, these are my scripts in package.json:

  "scripts": {
    "serve": "vite",
    "build": "vite build --mode=production",
    "dev": "vite build --mode=development"
  }


问:
Specific dimens.xml(hYYYdp) file is not working as expected
I have the following dimens file:

I have tested the app in a 240x400px (ldpi) device. So the height's dp is = 400/(120(ldpi)/160)== 533.33dp

So if I am not wrong, dimens.xml(h533dp) will be used by devices whose height's dp is equal or grater to 533dp. So, why if I am testing the app in a device with 533.33dp of height, it is not using the dimens that are defined in dimens.xml(h533dp)? I'm going off my head...


问:
@RabbitListener for multiple object types
In SpringBoot I use RabbitTemplate and @RabbitListener to produce and receive Messages.

I have an abstract class to send and receive RabbitMQ message of a specific type and send those messages to a STOMP web socket.

I use one RabbitMQ topic exchange which is bind to one RabbitMQ queue. In the topic-exchange I send messages (Java objects) of 2 different types and I am using 2 @RabbitListener to consume these messages.

```<code>@Configuration
public class WsRabbitMqConfiguration {

    public static final String WS_EXCHANGE_NAME = "websocket.replication";

    @Getter
    @Value(value = "${spring.application.name}")
    private String routingKey;

    @Bean
    TopicExchange wsReplicationExchange() {
        return new TopicExchange(
                WS_EXCHANGE_NAME,
                true,
                false,
                null);
    }

    @Bean
    public Queue wsReplicationQueue() {
        return new AnonymousQueue();
    }

    @Bean
    public Binding bindingWsAttributeValueQueue(TopicExchange wsReplicationExchange,
                                                Queue wsReplicationQueue) {
        return BindingBuilder
                .bind(wsReplicationQueue)
                .to(wsReplicationExchange)
                .with(routingKey);
    }
}
</code>```
```<code>@RequiredArgsConstructor
public abstract class AbstractWebsocketService<T> implements WebSocketService {

    public static final String HEADER_WS_DESTINATION = "x-Websocket-Destination";

    private final RabbitTemplate rabbitTemplate;
    private final WsRabbitMqConfiguration wsRabbitMqConfiguration;

    @Override
    public final <T> void send(String destination, T payload) {
        rabbitTemplate.convertAndSend(WsRabbitMqConfiguration.WS_EXCHANGE_NAME, wsRabbitMqConfiguration.getRoutingKey(), payload,
                message -> putDestination(message, destination));
    }

    protected abstract void handleWebsocketSending(T payload, String destination);
</code>```
```<code>@Service
public class FooWebSocketService extends AbstractWebsocketService<Foo> {

    public FooWebSocketService(RabbitTemplate rabbitTemplate,
                                          WsRabbitMqConfiguration rabbitMqConfiguration) {
        super(rabbitTemplate, rabbitMqConfiguration);
    }

    @RabbitListener(queues = "#{wsReplicationQueue.name}", ackMode = "NONE")
    protected void handleWebsocketSending(@Payload Foo payload, @Header(HEADER_WS_DESTINATION) String destination) {
        // logic here
    }
}
</code>```
```<code>@Service
public class BarWebSocketService extends AbstractWebsocketService<Bar> {

    public BarWebSocketService(RabbitTemplate rabbitTemplate,
                                          WsRabbitMqConfiguration rabbitMqConfiguration) {
        super(rabbitTemplate, rabbitMqConfiguration);
    }

    @RabbitListener(queues = "#{wsReplicationQueue.name}", ackMode = "NONE")
    protected void handleWebsocketSending(@Payload Bar payload, @Header(HEADER_WS_DESTINATION) String destination) {
        // logic here
    }
}
</code>```

From another service class I want to send RMQ messages, but randomly wrong @RabbitListener is activated.

Eg.

```<code>@Service
@RequiredArgsConstructor
public class TestService {

    private final BarWebSocketService barWebSocketService;

    public void sendMessage(Bar bar) {
        // 1st message
        barWebSocketService.send("bar-destination", bar);
        // 2nd message
        barWebSocketService.send("bar-destination2", bar);
    }
}
</code>```

For the 1st message @RabbitListener in FooWebSocketService is activated (which is wrong) and for the 2nd message @RabbitListener in BarWebSocketService (which is right).

Any suggestions what I am doing wrong? Thank you!

```<code></code>```

Body:
In SpringBoot I use RabbitTemplate and @RabbitListener to produce and receive Messages.

I have an abstract class to send and receive RabbitMQ message of a specific type and send those messages to a STOMP web socket.

I use one RabbitMQ topic exchange which is bind to one RabbitMQ queue. In the topic-exchange I send messages (Java objects) of 2 different types and I am using 2 @RabbitListener to consume these messages.

@Configuration
public class WsRabbitMqConfiguration {

    public static final String WS_EXCHANGE_NAME = "websocket.replication";

    @Getter
    @Value(value = "${spring.application.name}")
    private String routingKey;

    @Bean
    TopicExchange wsReplicationExchange() {
        return new TopicExchange(
                WS_EXCHANGE_NAME,
                true,
                false,
                null);
    }

    @Bean
    public Queue wsReplicationQueue() {
        return new AnonymousQueue();
    }

    @Bean
    public Binding bindingWsAttributeValueQueue(TopicExchange wsReplicationExchange,
                                                Queue wsReplicationQueue) {
        return BindingBuilder
                .bind(wsReplicationQueue)
                .to(wsReplicationExchange)
                .with(routingKey);
    }
}

@RequiredArgsConstructor
public abstract class AbstractWebsocketService<T> implements WebSocketService {

    public static final String HEADER_WS_DESTINATION = "x-Websocket-Destination";

    private final RabbitTemplate rabbitTemplate;
    private final WsRabbitMqConfiguration wsRabbitMqConfiguration;

    @Override
    public final <T> void send(String destination, T payload) {
        rabbitTemplate.convertAndSend(WsRabbitMqConfiguration.WS_EXCHANGE_NAME, wsRabbitMqConfiguration.getRoutingKey(), payload,
                message -> putDestination(message, destination));
    }

    protected abstract void handleWebsocketSending(T payload, String destination);

@Service
public class FooWebSocketService extends AbstractWebsocketService<Foo> {

    public FooWebSocketService(RabbitTemplate rabbitTemplate,
                                          WsRabbitMqConfiguration rabbitMqConfiguration) {
        super(rabbitTemplate, rabbitMqConfiguration);
    }

    @RabbitListener(queues = "#{wsReplicationQueue.name}", ackMode = "NONE")
    protected void handleWebsocketSending(@Payload Foo payload, @Header(HEADER_WS_DESTINATION) String destination) {
        // logic here
    }
}

@Service
public class BarWebSocketService extends AbstractWebsocketService<Bar> {

    public BarWebSocketService(RabbitTemplate rabbitTemplate,
                                          WsRabbitMqConfiguration rabbitMqConfiguration) {
        super(rabbitTemplate, rabbitMqConfiguration);
    }

    @RabbitListener(queues = "#{wsReplicationQueue.name}", ackMode = "NONE")
    protected void handleWebsocketSending(@Payload Bar payload, @Header(HEADER_WS_DESTINATION) String destination) {
        // logic here
    }
}

From another service class I want to send RMQ messages, but randomly wrong @RabbitListener is activated.

Eg.

@Service
@RequiredArgsConstructor
public class TestService {

    private final BarWebSocketService barWebSocketService;

    public void sendMessage(Bar bar) {
        // 1st message
        barWebSocketService.send("bar-destination", bar);
        // 2nd message
        barWebSocketService.send("bar-destination2", bar);
    }
}

For the 1st message @RabbitListener in FooWebSocketService is activated (which is wrong) and for the 2nd message @RabbitListener in BarWebSocketService (which is right).

Any suggestions what I am doing wrong? Thank you!


问:
Python module pyautogui doesn't work properly. OS X
I need to open Telegram.app and using pyautogui method, find a contact using a screenshot, and then write to him. Telegram was opened and the image requirable was seen there. But python has sent the mouse under the dock panel on OS X. Why? Screenshot is located properly, it's inside the directory where code is launched. How can I use this method successfully?

```<code>import os
import pyautogui
from time import sleep
os.system('open /Applications/Telegram.app')
contact = os.path.abspath('contact.png')
sleep(3)
to_click = pyautogui.locateCenterOnScreen(contact)
pyautogui.click(to_click)
</code>```

Body:
I need to open Telegram.app and using pyautogui method, find a contact using a screenshot, and then write to him. Telegram was opened and the image requirable was seen there. But python has sent the mouse under the dock panel on OS X. Why? Screenshot is located properly, it's inside the directory where code is launched. How can I use this method successfully?

import os
import pyautogui
from time import sleep
os.system('open /Applications/Telegram.app')
contact = os.path.abspath('contact.png')
sleep(3)
to_click = pyautogui.locateCenterOnScreen(contact)
pyautogui.click(to_click)