问:
How to get R plotly hover text to differ from x-axis text?
I'm using plotly to graph data for multiple samples that are sorted into different groups

```<code>library(plotly)

# Create example data
example_data <- as.data.frame(matrix(NA, 8, 5))
names(example_data) <- c("sampleID", "groupID", "TotalA", "TotalB", "TotalC")
example_data$Sample <- c("Sample 1", "Sample 2", "Sample 3", "Sample 4", "Sample 5", "Sample 6", "Sample 7", "Sample 8")
example_data$Group <- c("Group 1", "Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2", "Group 2")
example_data$TotalA <- c(11, 14, 32, 12, 28, 22, 30, 4) * 1000000
example_data$TotalB <- c(14, 16, 33, 14, 30, 25, 32, 8) * 1000000
example_data$TotalC <- c(10, 11, 30, 10, 26, 20, 15, 3) * 1000000

# (assume data is always sorted by group)
# first Sample in each Group will be where tick mark is placed on x-axis
example_data1 <- as.vector(example_data[!duplicated(example_data$Group), c('Group','Sample')])

# creating plot
plot_ly(example_data, x=~Sample) %>%
       add_lines(y=~TotalA, name='TotalA', mode='line+markers') %>%
       add_lines(y=~TotalB, name='TotalB', mode='line+markers') %>%
       add_lines(y=~TotalC, name='TotalC', mode='line+markers') %>%
       layout(yaxis=list(title='Number of Reads', hoverformat='.4s'),
              xaxis=list(ticktext=example_data1$Group, tickvals=example_data1$Sample, title='Group', tickangle=90),
              hovermode='x unified')
</code>```

Ideally, the x-axis of the graph would show Group Names and you would see Sample Name when you mouse over the points

This is how it should look -

For Samples 1 and 5, it shows the Group name instead -

It's definitely being caused by the weird way we're adding Group names. When I comment this line out, the mouseover works perfectly

```<code>xaxis=list(ticktext=example_data1$Group, tickvals=example_data1$Sample, title='Group', tickangle=90),
</code>```

Any ideas on how to have Sample names in the hovertext but Group names under the x-axis?

Edit - figured out how to do it with annotations

```<code># (assume data is always sorted by group)
# first Sample in each Group will be where tick mark is placed on x-axis
runid_annotations <- as.vector(example_data[!duplicated(example_data$Group), c('Group','Sample')])
runid_annotations$SampleIndex <- match(runid_annotations$Sample, example_data$Sample) - 1
num_runids <- length(runid_annotations$Sample)

p <- plot_ly(example_data, x=~Sample) %>%
  add_lines(y=~TotalA, name='TotalA', mode='line+markers') %>%
  add_lines(y=~TotalB, name='TotalB', mode='line+markers') %>%
  add_lines(y=~TotalC, name='TotalC', mode='line+markers') %>%
  layout(yaxis=list(title='Number of Reads', hoverformat='.4s'),
         xaxis=list(showticklabels = FALSE, title='Group'),
         margin=list(b=200),
         annotations=list(x = runid_annotations$SampleIndex,  yref="paper", y=-.7, text = runid_annotations$Group, textangle=90, showarrow = F),
         hovermode='x unified')
p
</code>```

Body:
I'm using plotly to graph data for multiple samples that are sorted into different groups

library(plotly)

# Create example data
example_data <- as.data.frame(matrix(NA, 8, 5))
names(example_data) <- c("sampleID", "groupID", "TotalA", "TotalB", "TotalC")
example_data$Sample <- c("Sample 1", "Sample 2", "Sample 3", "Sample 4", "Sample 5", "Sample 6", "Sample 7", "Sample 8")
example_data$Group <- c("Group 1", "Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2", "Group 2")
example_data$TotalA <- c(11, 14, 32, 12, 28, 22, 30, 4) * 1000000
example_data$TotalB <- c(14, 16, 33, 14, 30, 25, 32, 8) * 1000000
example_data$TotalC <- c(10, 11, 30, 10, 26, 20, 15, 3) * 1000000

# (assume data is always sorted by group)
# first Sample in each Group will be where tick mark is placed on x-axis
example_data1 <- as.vector(example_data[!duplicated(example_data$Group), c('Group','Sample')])

# creating plot
plot_ly(example_data, x=~Sample) %>%
       add_lines(y=~TotalA, name='TotalA', mode='line+markers') %>%
       add_lines(y=~TotalB, name='TotalB', mode='line+markers') %>%
       add_lines(y=~TotalC, name='TotalC', mode='line+markers') %>%
       layout(yaxis=list(title='Number of Reads', hoverformat='.4s'),
              xaxis=list(ticktext=example_data1$Group, tickvals=example_data1$Sample, title='Group', tickangle=90),
              hovermode='x unified')

Ideally, the x-axis of the graph would show Group Names and you would see Sample Name when you mouse over the points

This is how it should look -

For Samples 1 and 5, it shows the Group name instead -

It's definitely being caused by the weird way we're adding Group names. When I comment this line out, the mouseover works perfectly

xaxis=list(ticktext=example_data1$Group, tickvals=example_data1$Sample, title='Group', tickangle=90),

Any ideas on how to have Sample names in the hovertext but Group names under the x-axis?

Edit - figured out how to do it with annotations

# (assume data is always sorted by group)
# first Sample in each Group will be where tick mark is placed on x-axis
runid_annotations <- as.vector(example_data[!duplicated(example_data$Group), c('Group','Sample')])
runid_annotations$SampleIndex <- match(runid_annotations$Sample, example_data$Sample) - 1
num_runids <- length(runid_annotations$Sample)

p <- plot_ly(example_data, x=~Sample) %>%
  add_lines(y=~TotalA, name='TotalA', mode='line+markers') %>%
  add_lines(y=~TotalB, name='TotalB', mode='line+markers') %>%
  add_lines(y=~TotalC, name='TotalC', mode='line+markers') %>%
  layout(yaxis=list(title='Number of Reads', hoverformat='.4s'),
         xaxis=list(showticklabels = FALSE, title='Group'),
         margin=list(b=200),
         annotations=list(x = runid_annotations$SampleIndex,  yref="paper", y=-.7, text = runid_annotations$Group, textangle=90, showarrow = F),
         hovermode='x unified')
p


来源: stackexchange

问:
Wrap C++ templates for Python with SWIG
I have seen numerous examples on wrapping template classes with swig for python but what about methods?

Say I have some code that adds and subtracts n numbers of numerous data types :

class Example {
    public:
        template<typename T>
        inline T add(T t) {
            return t;
        }
        template<typename T, typename... Ts>
        inline auto add(T t, Ts... ts) {
            return t + add(ts...);
        }

        template<typename X>
        inline X sub(X x) {
            return x;
        }
        template<typename X, typename... Xy>
        inline auto sub(X x, Xy... xy) {
            return x - sub(xy...);
        }

};
```

Notice the overarching class is not a template but the methods within. In the examples I have seen, I notice the class should be declared for each datatype wanted (int, float). Is there a way to get around having to declare a class for each datatype?

Is this logic 'correct' or should some refactoring be done in my source code?

How would I go about wrapping template methods within a class?

ContentLicense: CC BY-SA 4.0

Title: Wrap C++ templates for Python with SWIG

Body:
I have seen numerous examples on wrapping template classes with swig for python but what about methods?

Say I have some code that adds and subtracts n numbers of numerous data types :

class Example {
    public:
        template<typename T>
        inline T add(T t) {
            return t;
        }
        template<typename T, typename... Ts>
        inline auto add(T t, Ts... ts) {
            return t + add(ts...);
        }

        template<typename X>
        inline X sub(X x) {
            return x;
        }
        template<typename X, typename... Xy>
        inline auto sub(X x, Xy... xy) {
            return x - sub(xy...);
        }

};

Notice the overarching class is not a template but the methods within. In the examples I have seen, I notice the class should be declared for each datatype wanted (int, float). Is there a way to get around having to declare a class for each datatype?

Is this logic 'correct' or should some refactoring be done in my source code?

How would I go about wrapping template methods within a class?


问:
Kotlin Compose Multiplatform, include folders in package used at runtime
I would like to add a folder named lib to the package. It contains dlls I use with JNI. I also have a folder named conf with a json file. Both are in the top directory of the project.
The lib folder is needed only on Windows. So,

How can I add this 2 folders in the final package to use them at runtime ?

And how can I handle the path to distinguish when I run the app with my editor, or whit the final package ?

I know there is this method: resources.srcDirs("resources"), but I'm not sure it's good to use this with dlls and it's will be nice if the json file can be edited by hand.


问:
Python pyproject.toml package_dir, package_data and script for flat-layout directory layout with single file and data in top level directory
I have the following project layout:

```<code>|.
|./mydata (directory)
|./myscript.py (Python file)
</code>```

I would like to package this with pyproject.toml using setuptools including mydata as mydata folder accessible with importlib and myscript.py as project script available on the path after installing with pip.

I think I'm searching the correct ways to specify:

Snippet pyproject.toml:

```<code>[project.scripts]
myscript = "myscript:execute"

[tool.setuptools.package-data]
# ???
</code>```

Body:
I have the following project layout:

|.
|./mydata (directory)
|./myscript.py (Python file)

I would like to package this with pyproject.toml using setuptools including mydata as mydata folder accessible with importlib and myscript.py as project script available on the path after installing with pip.

I think I'm searching the correct ways to specify:

Snippet pyproject.toml:

[project.scripts]
myscript = "myscript:execute"

[tool.setuptools.package-data]
# ???


问:
How to fetch form in Google Sheets and put in some data then download the whole thing as PDF file in React?
Suppose I have an existing predefined form in Google Sheets that contains something like tables with header columns and empty rows (waiting for data to fill in).

I am currently implementing a React web application that collects data from users. In the app, there is going to be a button, which is designed to do these steps that I would like to know if it is possible at all, if so how.

User filled in some data in the web and then clicked the button.

Fetch form from the Google Sheets.

Fill data in the form (in the predefined empty table rows)

Print the result in PDF (let the user download the file via browser)

Any additional third party libraries are acceptable.


问:
Google App Script job fails(UrlFetchApp.fetch)
When I try to get data by below code, it will display("The value 'ASNP' does not exist for the field 'project'."):

```<code>var TOKEN = "key"
var options = {
  contentType: "application/json",
  headers: {"Authorization": " Basic " + TOKEN}
};
var requestUrl = "https://jiracloud.xxx.com.br/rest/api/2/search?startIndex=0&maxResults=2&jql=project=ASNP";
var text = UrlFetchApp.fetch(requestUrl, options).getContentText();
</code>```

But when I request by curl, it works normally:

```<code>curl -H " Basic key" https://jiracloud.xxx.com.br/rest/api/2/search?startIndex=0&maxResults=2&jql=project=ASNP
</code>```

So, I think there are issue on UrlFetchApp.fetch() function.(If I get data form ASGS, it works normally, too.)

For UrlFetchApp.fetch, are there any restrictions on the use of this method? Or is this a bug? Or does my script need improvement?

Body:
When I try to get data by below code, it will display("The value 'ASNP' does not exist for the field 'project'."):

var TOKEN = "key"
var options = {
  contentType: "application/json",
  headers: {"Authorization": " Basic " + TOKEN}
};
var requestUrl = "https://jiracloud.xxx.com.br/rest/api/2/search?startIndex=0&maxResults=2&jql=project=ASNP";
var text = UrlFetchApp.fetch(requestUrl, options).getContentText();

But when I request by curl, it works normally:

curl -H " Basic key" https://jiracloud.xxx.com.br/rest/api/2/search?startIndex=0&maxResults=2&jql=project=ASNP

So, I think there are issue on UrlFetchApp.fetch() function.(If I get data form ASGS, it works normally, too.)

For UrlFetchApp.fetch, are there any restrictions on the use of this method? Or is this a bug? Or does my script need improvement?


问:
Trying to exploit SQL injection
I am trying to exploit a SQLI and I don't understand why my "group_concat" doesn't work.

I managed to extract the name of the database ("games") :

enter image description here

But when I try to extract the tables from this database, I have a syntax error :
enter image description here

Why do I have this syntax error?

PS: This is being done on an hacking learning plateform so no nasty illegal stuff going on.

Title: Trying to exploit SQL injection


问:
(Python, MySQL) print spific column from database
for now my code can print the list of the table, how to print spific column's data from MySQL by python

```<code>import mysql.connector

mydb = mysql.connector.connect(
  host="1xx.xxx.xxx.xxx",
  user="root", # defult user name is root
  password="password",
  database="your_database",
  auth_plugin='mysql_native_password' # In case plugging password is not working
)

mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM your_database")

myresult = mycursor.fetchall()

for row in myresult:
  print("row_01 = ", row[0], )
  print("row_02 = ", row[1])
  print("row_03  = ", row[2])
  print("row_04  = ", row[3], "\n")
</code>```

demo table in MySQL database

if I want to print out the content 4x3 only, how can I improve my code

```<code>+------+-------+------+------+
|row_01|row_02 |row_03|row_04|
+------+-------+------+------+
|  1x1 |  2x1  |  3x1 |  4x1 |
+------+-------+------+------+
|  1x2 |  2x2  |  3x2 |  4x2 |
+------+-------+------+------+
|  1x3 |  2x3  |  3x3 |  4x3 |
+------+-------+------+------+
|  1x4 |  2x4  |  3x4 |  4x4 |
+------+-------+------+------+
</code>```

and my code result for now

```<code>row_01 =  1x1
row_02 =  2x1
row_03  =  3x1
row_04  =  4x1

row_01 =  1x2
row_02 =  2x2
row_03  =  3x2
row_04  =  4x2

row_01 =  1x3
row_02 =  2x3
row_03  =  3x3
row_04  =  4x3

row_01 =  1x4
row_02 =  2x4
row_03  =  3x4
row_04  =  4x4
</code>```

is a dumb question, but how can I just get/print 4x3 or 1x1

ps. I did search relate discussion already, such as

MySQL: Get column name or alias from query

print table row mysql python

I just couldn't get it, Therfore, I ask here as my last step sor

Body:
for now my code can print the list of the table, how to print spific column's data from MySQL by python

import mysql.connector

mydb = mysql.connector.connect(
  host="1xx.xxx.xxx.xxx",
  user="root", # defult user name is root
  password="password",
  database="your_database",
  auth_plugin='mysql_native_password' # In case plugging password is not working
)

mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM your_database")

myresult = mycursor.fetchall()

for row in myresult:
  print("row_01 = ", row[0], )
  print("row_02 = ", row[1])
  print("row_03  = ", row[2])
  print("row_04  = ", row[3], "\n")

demo table in MySQL database

if I want to print out the content 4x3 only, how can I improve my code

+------+-------+------+------+
|row_01|row_02 |row_03|row_04|
+------+-------+------+------+
|  1x1 |  2x1  |  3x1 |  4x1 |
+------+-------+------+------+
|  1x2 |  2x2  |  3x2 |  4x2 |
+------+-------+------+------+
|  1x3 |  2x3  |  3x3 |  4x3 |
+------+-------+------+------+
|  1x4 |  2x4  |  3x4 |  4x4 |
+------+-------+------+------+

and my code result for now

row_01 =  1x1
row_02 =  2x1
row_03  =  3x1
row_04  =  4x1

row_01 =  1x2
row_02 =  2x2
row_03  =  3x2
row_04  =  4x2

row_01 =  1x3
row_02 =  2x3
row_03  =  3x3
row_04  =  4x3

row_01 =  1x4
row_02 =  2x4
row_03  =  3x4
row_04  =  4x4

is a dumb question, but how can I just get/print 4x3 or 1x1

ps. I did search relate discussion already, such as

MySQL: Get column name or alias from query

print table row mysql python

I just couldn't get it, Therfore, I ask here as my last step sor


问:
Bootstrap carousel lazy-load not working (Laravel)
I have made a site using Laravel which contains a page displaying the customer's work. These images are all categorised into different bootstrap carousels and everything is working fine apart from all of the images in the carousel are loading as soon as the page loads. I have tried to implement lazy-load to increase the performance of the site but only the first image is displaying.

Carousel code:

```<code><div id="Example_garden" class="carousel slide lazy-load" data-bs-interval="false">
<div class="carousel-indicators">
    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="0" class="active"
        aria-current="true" aria-label="Slide 1"></button>
    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="1"
        aria-label="Slide 2"></button>
    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="2"
        aria-label="Slide 3"></button>
    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="3"
        aria-label="Slide 4"></button>

</div>
<div class="carousel-inner">
    <div class="carousel-item active">
        <img src="{{ asset('storage/images/example_garden/example_garden_2_large.png') }}"
                alt="Example garden image" class="d-block w-100">
    </div>
    <div class="carousel-item">
        <img data-src="{{ asset('storage/images/example_garden/example_garden_2_large.png') }}"
                alt="Example garden image" class="d-block w-100">
    </div>
    <div class="carousel-item">
        <img data-src="{{ asset('storage/images/example_garden/example_garden_3_large.png') }}"
                alt="Example garden image" class="d-block w-100">
    </div>
    <div class="carousel-item">
        <img data-src="{{ asset('storage/images/example_garden/example_garden_4_large.png') }}"
                alt="Example garden image" class="d-block w-100">
    </div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#Example_garden"
    data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#Example_garden"
    data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
</button>
</code>```

script:

```<code>    $('.carousel.lazy-load').bind('slide.bs.carousel', function (e) {
        var image = $(e.relatedTarget).find('img[data-src]');
        image.attr('src', image.data('src'));
        image.removeAttr('data-src');
    });
});
</code>```

I have used multiple scripts found from other users who are facing the same issue but nothing seems to be helping. Is anyone able to point me in the right direction?

Body:
I have made a site using Laravel which contains a page displaying the customer's work. These images are all categorised into different bootstrap carousels and everything is working fine apart from all of the images in the carousel are loading as soon as the page loads. I have tried to implement lazy-load to increase the performance of the site but only the first image is displaying.

Carousel code:

    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="0" class="active"
        aria-current="true" aria-label="Slide 1"></button>
    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="1"
        aria-label="Slide 2"></button>
    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="2"
        aria-label="Slide 3"></button>
    <button type="button" data-bs-target="#Example_garden" data-bs-slide-to="3"
        aria-label="Slide 4"></button>

<button class="carousel-control-prev" type="button" data-bs-target="#Example_garden"
    data-bs-slide="prev">

    Previous
</button>
<button class="carousel-control-next" type="button" data-bs-target="#Example_garden"
    data-bs-slide="next">

    Next
</button>

script:

    $('.carousel.lazy-load').bind('slide.bs.carousel', function (e) {
        var image = $(e.relatedTarget).find('img[data-src]');
        image.attr('src', image.data('src'));
        image.removeAttr('data-src');
    });
});

I have used multiple scripts found from other users who are facing the same issue but nothing seems to be helping. Is anyone able to point me in the right direction?


问:
Why does my C++ program only output one line into a csv file?
I recently wrote a program that needs to output some information into a csv file. For this example, it's 3 rows, 5 columns. Nothing very complicated. I have a for loop iterating over a map of objects, but that doesn't seem to work properly. It inserts one row into the file instead of the 3 it's supposed to be outputting.

Here is my code:

Iterating over the objects in main:

```<code>std::map<std::string, Customer>::iterator itr_3;
    for(itr_3 = customers.begin(); itr_3 != customers.end(); itr_3++){
        itr_3->second.outputCSVFile();
    }
</code>```

Method that outputs to CSV file:

```<code>void Customer::outputCSVFile(){
    std::ofstream outputFile;
    outputFile.open("output.csv");

    // iterate over the years
    std::map<int, std::map<int, std::vector<int> > >::iterator itr;
    for(itr = monthly_records.begin(); itr != monthly_records.end(); ++itr){
        //iterate over the months
        std::map<int, std::vector<int> >::iterator itr_2;
        for(itr_2 = itr->second.begin(); itr_2 != itr->second.end(); ++itr_2){
            if(itr_2->second[0] != 0){
                outputFile << this->getID() << ",";
                outputFile << itr_2->first << "/" << itr->first << ",";
                outputFile << itr_2->second[0] << ",";
                outputFile << itr_2->second[1] << ",";
                outputFile << itr_2->second[2] << "," << '\n';
            }
        }
    }

}
</code>```

Current output:
Current output
Necessary Output:
Necessary output
Any help is appreciated!

Body:
I recently wrote a program that needs to output some information into a csv file. For this example, it's 3 rows, 5 columns. Nothing very complicated. I have a for loop iterating over a map of objects, but that doesn't seem to work properly. It inserts one row into the file instead of the 3 it's supposed to be outputting.

Here is my code:

Iterating over the objects in main:

std::map<std::string, Customer>::iterator itr_3;
    for(itr_3 = customers.begin(); itr_3 != customers.end(); itr_3++){
        itr_3->second.outputCSVFile();
    }

Method that outputs to CSV file:

void Customer::outputCSVFile(){
    std::ofstream outputFile;
    outputFile.open("output.csv");

    // iterate over the years
    std::map<int, std::map<int, std::vector<int> > >::iterator itr;
    for(itr = monthly_records.begin(); itr != monthly_records.end(); ++itr){
        //iterate over the months
        std::map<int, std::vector<int> >::iterator itr_2;
        for(itr_2 = itr->second.begin(); itr_2 != itr->second.end(); ++itr_2){
            if(itr_2->second[0] != 0){
                outputFile << this->getID() << ",";
                outputFile << itr_2->first << "/" << itr->first << ",";
                outputFile << itr_2->second[0] << ",";
                outputFile << itr_2->second[1] << ",";
                outputFile << itr_2->second[2] << "," << '\n';
            }
        }
    }

}

Current output:
Current output
Necessary Output:
Necessary output
Any help is appreciated!


问:
Sample Implementation of Learning without Forgetting
I am replicating the paper Learning without Forgetting, does anyone know how to replicate the results? Thank you.

I tried replicating it, but I cannot replicate it properly, can anyone help me about this matter? Thank you


问:
How to query SharePoint sites in a multi-geo SharePoint from a specific geo using Beta Graph API?
The Beta Microsoft Graph API supports multi-geo SharePoint (v1.0 non-beta does not support multi-geo).  However, I am having trouble using it to query the SharePoint sites in a specific geo using the C# beta SDK (latest version) from nuget.

Does anyone know how to query either all geos, or only a specific geo?  Right now, we have 3 geos and the API is only returning the US region geo sites, but not the others.


问:
Yup start and end date validation
I am trying to use the yup validation to check for start and end date. End date should not be less than start and Start date should not be more that End date. I currently have this code which works by checking only the end date

```<code>const srSchema = yup.object({
    SRSumStartDate: yup.date().required("Start date is required").typeError("Start date is required"),
    SRSumEndDate: yup.date().when('SRSumStartDate', (start_date, schema) => {
        if (start_date) {
            return schema.min(start_date, 'End date has to be greater than start date');
        }}).required("End date is required").typeError("End date is required")
})
</code>```

However, this code currently has a bug. Entering the start date and then clearing it will cause the error, but the End date can be cleared without any error.

Image of the error:

Image of UI after entering both Start and End date and clearing both fields:

Title: Yup start and end date validation

Body:
I am trying to use the yup validation to check for start and end date. End date should not be less than start and Start date should not be more that End date. I currently have this code which works by checking only the end date

const srSchema = yup.object({
    SRSumStartDate: yup.date().required("Start date is required").typeError("Start date is required"),
    SRSumEndDate: yup.date().when('SRSumStartDate', (start_date, schema) => {
        if (start_date) {
            return schema.min(start_date, 'End date has to be greater than start date');
        }}).required("End date is required").typeError("End date is required")
})

However, this code currently has a bug. Entering the start date and then clearing it will cause the error, but the End date can be cleared without any error.

Image of the error:

Image of UI after entering both Start and End date and clearing both fields:


问:
GeoSpatial ArcGIS loading map in multiple iframes. ERR: Cors
Using: ArcGIS4.1x Java script on my local network and my server has not access to internet.

Background: This is a preexisting project which has a basic structure with a Main Pane and Detail pane as iframes.

When the page loads for the first time a Basemap is loaded with few markers and every marker is linked with a onClick popup to display the details on the marker. (Works fine)

When the user clicks on the popup there is a details pane which opens and the Lat,Long point associated with the marker should load in the new map.

It is basically using the same code as main pane to load the marker, the only difference is it loads detail pane with only one marker(detail pane) instead of 20+ markers ((Main pane)

but when the detail pane is loaded there is an error, the basemap loads but with no marker.

Err:: Access to fetch at 'http://scripts/ArcGIS4.1x/esri/t9n/common.json' from origin 'http://localhost:56145' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Not sure why it is looking at 'http://scripts/...' when the .js files are on the local network.

On loading of the main pane there is no refence to 'http://scripts/...'

Any suggestions?


问:
I cant understand this python code editing excel sheets
I am writing a script that takes all files in directory and deletes first row of the excel file xlsx.

I am confused why this works. specifically this part

```<code># Set the second row as the header and drop it
df.columns = df.iloc[0]

# Drop the first row
df = df.drop(df.index[0:1])

import os
import pandas as pd
import openpyxl
os.chdir("C:/Users/bean/Desktop/EU_DATA - Copy")

# Get list of file names
filenames = os.listdir()

# Iterate over the list of file names
for file in filenames:
    # Read the file using pandas
    df = pd.read_excel(file)

    # Delete the first row

    # Set the second row as the header and drop it
    df.columns = df.iloc[0]

    # Drop the first row
    df = df.drop(df.index[0:1])

    # Open the file in write mode and write the modified dataframe to it
    df.to_excel(file, index=False)
    print(file)
</code>```

Why does the order matter if i switch the iloc and drop index. The code drops the first row of file and set s second row as index. I am confused because I don't get why second row is "first row" value 0 when the original file its value 1 second row. I get the drop index[0:1] which is what I want. Wouldn't it make sense to put that line before the iloc then it would delete first row and then logically the second row from original would become first row which would then make it the column head row.

Please explain I am completely confused.

```<code>import os
import pandas as pd
import openpyxl
os.chdir("C:/Users/bean/Desktop/EU_DATA - Copy")
</code>```

Body:
I am writing a script that takes all files in directory and deletes first row of the excel file xlsx.

I am confused why this works. specifically this part

# Set the second row as the header and drop it
df.columns = df.iloc[0]

# Drop the first row
df = df.drop(df.index[0:1])

import os
import pandas as pd
import openpyxl
os.chdir("C:/Users/bean/Desktop/EU_DATA - Copy")

# Get list of file names
filenames = os.listdir()

# Iterate over the list of file names
for file in filenames:
    # Read the file using pandas
    df = pd.read_excel(file)

    # Delete the first row

    # Set the second row as the header and drop it
    df.columns = df.iloc[0]

    # Drop the first row
    df = df.drop(df.index[0:1])

    # Open the file in write mode and write the modified dataframe to it
    df.to_excel(file, index=False)
    print(file)

Why does the order matter if i switch the iloc and drop index. The code drops the first row of file and set s second row as index. I am confused because I don't get why second row is "first row" value 0 when the original file its value 1 second row. I get the drop index[0:1] which is what I want. Wouldn't it make sense to put that line before the iloc then it would delete first row and then logically the second row from original would become first row which would then make it the column head row.

Please explain I am completely confused.

import os
import pandas as pd
import openpyxl
os.chdir("C:/Users/bean/Desktop/EU_DATA - Copy")


问:
Efficiently iterating over HTML canvas by creating a binary image
So I know there are quite a few posts out there with a similar question, so I am hoping to clearly distinguish between some of the differences between those and this question.

This question could basically be answered if I could find a way to get the binary image representation of the image (which I thought was just a "bitmap" image, but jpegs and pngs are bitmaps). I need 1 channel that is either true or false; the below returns an array of all 4 channels (red, green, blue, alpha). The reason it would be answered is because I could then use Array.slice() to get the subarray of each row and find the first true and last true values with Array.indexOf(true) and Array.lastIndexOf(true) and compute the pixel difference between those, which would already be way more efficient than the current looping process, assuming built-ins are faster than any loop I am going to write. So an example code snippet would look like this (and I mean this is basically what I have):

```<code>function calcImg()
{
    img = null;
    p = new Promise((resolve) => {
        img = document.createElement("img");
        img.src = canvas.toDataURL();
        img.onload = function() {
            resolve();
        }
    }).then(function() {
        c = document.createElement("canvas");
        c.width = img.width;
        c.height = img.height;

        cc = c.getContext("2d");
        cc.drawImage(img, 0, 0);

        imgData = cc.getImageData(0, 0, img.width, img.height).data;
        console.log(imgData.length);

        for (var i = 0; i < c.height; i++)
        {
            // this is this "rows"
            thisRow = imgData.slice(i * cw * 4, (i * cw * 4) + (cw * 4));
            // now I need to average every group of 4 values to get the pixel and store it in its own array
            // then do (newArray of course is the binary array representation of the image):
            first = newArray.indexOf(false);
            last = newArray.lastIndexOf(false);
            // perform extra math
        }
    });

}
</code>```

I know that I can loop over an html canvas and "divy" it up like this poster had it, average each pixel, then use a threshold to say if the pixel is black or white, but that is my current method and slow... The accepted answer provided a bunch of built in functions to handle those transformations and calculations that needed to happen, but nothing that was necessarily (unless I missed something) helpful for my particular case for speeding up the computations.

I thought that maybe I could quickly compute this by grouping four values together and averaging them with something like this - code below:

```<code>function averageEvery(arr, n) {
  if (!arr || !n) {
    return false;
  }
  let groups = [];
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>

    // here we use Math.round() to round
    // the calculated number:
    Math.round(group.reduce(
      (a, b) => a + b
    ) / group.length)
  );

}

console.log(
  averageEvery([1, 2, 4, 5, 6, 7], 3)
);
</code>```

but unfortunately, this wasn't any faster (and was actually noticeably slower).

My last attempt (code below) was to try and use createImageBitmap(), but it returns 4 channels instead of 1 (printing it to the console was enough for me to determine that).

```<code>function calcImg()
{

    createImageBitmap(document.querySelector("canvas"), 0, 0, parseInt(canvas.width), parseInt(canvas.height)).then(function(img)
    {
        c = document.createElement("canvas");
        c.width = img.width;
        c.height = img.height;

        cc = c.getContext("2d");
        cc.drawImage(img, 0, 0);
        imgData = cc.getImageData(0, 0, img.width, img.height).data;
        console.log(imgData);
    });

}
</code>```

So to articulate my goal:

For each row, compute the distance between the far right and far left pixel that is black and sum the total length.

So I am stumped.

EDIT

I got caught up with the above aspect of the question that I forgot to mention that I have fabric.js available, so any answer including / utilizing it is reasonable as well (I am having a hard time finding the post, but I read that you should be using libraries that are built to handle things like this. Despite reading the documentation and looking online for similar questions, I am having a hard time finding a fabric.js solution).

I would also like to mention that this calculation needs to happen as quickly as possible, because it happens frequently.

Thank you for coming to my TedTalk.

Body:
So I know there are quite a few posts out there with a similar question, so I am hoping to clearly distinguish between some of the differences between those and this question.

This question could basically be answered if I could find a way to get the binary image representation of the image (which I thought was just a "bitmap" image, but jpegs and pngs are bitmaps). I need 1 channel that is either true or false; the below returns an array of all 4 channels (red, green, blue, alpha). The reason it would be answered is because I could then use Array.slice() to get the subarray of each row and find the first true and last true values with Array.indexOf(true) and Array.lastIndexOf(true) and compute the pixel difference between those, which would already be way more efficient than the current looping process, assuming built-ins are faster than any loop I am going to write. So an example code snippet would look like this (and I mean this is basically what I have):

function calcImg()
{
    img = null;
    p = new Promise((resolve) => {
        img = document.createElement("img");
        img.src = canvas.toDataURL();
        img.onload = function() {
            resolve();
        }
    }).then(function() {
        c = document.createElement("canvas");
        c.width = img.width;
        c.height = img.height;

        cc = c.getContext("2d");
        cc.drawImage(img, 0, 0);

        imgData = cc.getImageData(0, 0, img.width, img.height).data;
        console.log(imgData.length);

        for (var i = 0; i < c.height; i++)
        {
            // this is this "rows"
            thisRow = imgData.slice(i * cw * 4, (i * cw * 4) + (cw * 4));
            // now I need to average every group of 4 values to get the pixel and store it in its own array
            // then do (newArray of course is the binary array representation of the image):
            first = newArray.indexOf(false);
            last = newArray.lastIndexOf(false);
            // perform extra math
        }
    });

}

I know that I can loop over an html canvas and "divy" it up like this poster had it, average each pixel, then use a threshold to say if the pixel is black or white, but that is my current method and slow... The accepted answer provided a bunch of built in functions to handle those transformations and calculations that needed to happen, but nothing that was necessarily (unless I missed something) helpful for my particular case for speeding up the computations.

I thought that maybe I could quickly compute this by grouping four values together and averaging them with something like this - code below:

function averageEvery(arr, n) {
  if (!arr || !n) {
    return false;
  }
  let groups = [];
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>

    // here we use Math.round() to round
    // the calculated number:
    Math.round(group.reduce(
      (a, b) => a + b
    ) / group.length)
  );

}

console.log(
  averageEvery([1, 2, 4, 5, 6, 7], 3)
);

but unfortunately, this wasn't any faster (and was actually noticeably slower).

My last attempt (code below) was to try and use createImageBitmap(), but it returns 4 channels instead of 1 (printing it to the console was enough for me to determine that).

function calcImg()
{

    createImageBitmap(document.querySelector("canvas"), 0, 0, parseInt(canvas.width), parseInt(canvas.height)).then(function(img)
    {
        c = document.createElement("canvas");
        c.width = img.width;
        c.height = img.height;

        cc = c.getContext("2d");
        cc.drawImage(img, 0, 0);
        imgData = cc.getImageData(0, 0, img.width, img.height).data;
        console.log(imgData);
    });

}

So to articulate my goal:

For each row, compute the distance between the far right and far left pixel that is black and sum the total length.

So I am stumped.

EDIT

I got caught up with the above aspect of the question that I forgot to mention that I have fabric.js available, so any answer including / utilizing it is reasonable as well (I am having a hard time finding the post, but I read that you should be using libraries that are built to handle things like this. Despite reading the documentation and looking online for similar questions, I am having a hard time finding a fabric.js solution).

I would also like to mention that this calculation needs to happen as quickly as possible, because it happens frequently.

Thank you for coming to my TedTalk.


问:
Type of any instance of a class in Typescript
I have a function that crashes if the parameter sent is the instance of any class or is a Function.

So I need to write a Type that shows a compile-time error if we try to pass an instance of a class to that function.
I tried the following but it can disallow only Function

```<code>// type Disallowed = instanceof any
type Disallowed =  Function
type Input<T> = T & (T extends Disallowed ? never : T);

// Accepts anything number, string, bool, json object, ... except instance of class and functions
function saveData<T>(data: Input<T> ) { ... }
class A {}
let foo = new A{}
saveData(foo) // should produce compile error
saveData(()=>{}) // already dissallowed
</code>```

Body:
I have a function that crashes if the parameter sent is the instance of any class or is a Function.

So I need to write a Type that shows a compile-time error if we try to pass an instance of a class to that function.
I tried the following but it can disallow only Function

// type Disallowed = instanceof any
type Disallowed =  Function
type Input<T> = T & (T extends Disallowed ? never : T);

// Accepts anything number, string, bool, json object, ... except instance of class and functions
function saveData<T>(data: Input<T> ) { ... }
class A {}
let foo = new A{}
saveData(foo) // should produce compile error
saveData(()=>{}) // already dissallowed


问:
Zookeeper will create a password for client by sessionId, and so we can forge it by sessionId, is't any security issue?
Zookeeper implement logical as picture show, anyone know it, does is a securty issue?

i try to simulate zookeeper logical, use same method  we can easy get same password by session Id.

```<code>private static final long superSecret = 0XB3415C00L;
static byte[] generatePasswd(long id) {
    Random r = new Random(id ^ superSecret);
    byte[] p = new byte[16];
    r.nextBytes(p);
    return p;
}

public static void main(String[] args) {
    byte[] passwd = new byte[16];

    long sessionId = 11L;

    Random r = new Random(sessionId ^ superSecret);
    r.nextBytes(passwd);

    System.out.println(passwd);

    byte[] ps = generatePasswd(sessionId);

    System.out.println(generatePasswd(sessionId));

    boolean rs = Arrays.equals(passwd, generatePasswd(sessionId));
    System.out.println(rs);
}
</code>```

Body:
Zookeeper implement logical as picture show, anyone know it, does is a securty issue?

i try to simulate zookeeper logical, use same method  we can easy get same password by session Id.

private static final long superSecret = 0XB3415C00L;
static byte[] generatePasswd(long id) {
    Random r = new Random(id ^ superSecret);
    byte[] p = new byte[16];
    r.nextBytes(p);
    return p;
}

public static void main(String[] args) {
    byte[] passwd = new byte[16];

    long sessionId = 11L;

    Random r = new Random(sessionId ^ superSecret);
    r.nextBytes(passwd);

    System.out.println(passwd);

    byte[] ps = generatePasswd(sessionId);

    System.out.println(generatePasswd(sessionId));

    boolean rs = Arrays.equals(passwd, generatePasswd(sessionId));
    System.out.println(rs);
}


问:
Issue Google StarThinker: 'invalid_grant: Bad Request
I've got a Python script to connect data from DV360 to Google Sheets by using the StarThinker framework.
The script was running correctly until a few weeks ago when the work email account of the person who set this up (Python Script, Google Cloud Project, Credential files) was decommissioned as he left the organization.

The Python script has 3 instances:

Clear out a specific spreadsheet

StarThinker instance

Insert data into the spreadsheet

This is the StarThinker instance which is the one flagging the error (RefreshError: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})

#DV360 Report to Google Sheet

!pip3 install git+https://github.com/google/starthinker
!pip3 install starthinker

from starthinker.util.configuration import Configuration

CONFIG = Configuration(
  project="has-apac-prd-has-nz",
  client="client.json",
  service= "service.json",
  user="user.json",
  verbose=True
)

FIELDS = {
  'auth_read':'user',  # Credentials used for reading data.
  'report_id':'1037961641',  # DV360 report ID given in UI, not needed if name used.
  'report_name':'dv360-to-sheet',  # Name of report, not needed if ID used.
  'sheet':'https://docs.google.com/spreadsheets/d/1CfqCANbSpm_40DQ1-Sm7oekboYNsFtzcYeZSnqhdPrk/edit#gid=0',  # Full URL to sheet being written to.
  'tab':'Sheet1',  # Existing tab in sheet to write to.
}

print("Parameters Set To: %s" % FIELDS)

from starthinker.util.configuration import execute
from starthinker.util.recipe import json_set_fields

TASKS = [
  {
    'dbm':{
      'auth':{'field':{'name':'auth_read','kind':'authentication','order':1,'default':'user','description':'Credentials used for reading data.'}},
      'report':{
        'report_id':{'field':{'name':'report_id','kind':'integer','order':1,'default':'','description':'DV360 report ID given in UI, not needed if name used.'}},
        'name':{'field':{'name':'report_name','kind':'string','order':2,'default':'','description':'Name of report, not needed if ID used.'}}
      },
      'out':{
        'sheets':{
          'sheet':{'field':{'name':'sheet','kind':'string','order':3,'default':'','description':'Full URL to sheet being written to.'}},
          'tab':{'field':{'name':'tab','kind':'string','order':4,'default':'','description':'Existing tab in sheet to write to.'}},
          'range':'A1'
        }
      }
    }
  }
]

json_set_fields(TASKS, FIELDS)

execute(CONFIG, TASKS, force=True)```

Here some stuff I've already done:

Created a new report on DV360 under my user

Made sure to have all accesses to DV360 and the spreadsheet

Made sure to have permission for the Google Cloud project

Gave me permission to the star thinker service account.

Created a new client and new service account within GCP and placed these files into the same folder with the python script (made sure to change the name of the files in the script).

Also, when I try to open this URL I see the invalid request issue like below https://accounts.google.com/signin/oauth/error/v2

To finish, there are x3 json files placed in the same folder as the script:

service.json

client.json

user.json

I was able to re-create the first two on Google Cloud (as mentioned above), but couldn't find a way to re-create user.json which I think might be the main issue here.

I would really appreciate some help on this.

Thanks.

Body:
I've got a Python script to connect data from DV360 to Google Sheets by using the StarThinker framework.
The script was running correctly until a few weeks ago when the work email account of the person who set this up (Python Script, Google Cloud Project, Credential files) was decommissioned as he left the organization.

The Python script has 3 instances:

Clear out a specific spreadsheet

StarThinker instance

Insert data into the spreadsheet

This is the StarThinker instance which is the one flagging the error (RefreshError: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})

#DV360 Report to Google Sheet

!pip3 install git+https://github.com/google/starthinker
!pip3 install starthinker

from starthinker.util.configuration import Configuration

CONFIG = Configuration(
  project="has-apac-prd-has-nz",
  client="client.json",
  service= "service.json",
  user="user.json",
  verbose=True
)

FIELDS = {
  'auth_read':'user',  # Credentials used for reading data.
  'report_id':'1037961641',  # DV360 report ID given in UI, not needed if name used.
  'report_name':'dv360-to-sheet',  # Name of report, not needed if ID used.
  'sheet':'https://docs.google.com/spreadsheets/d/1CfqCANbSpm_40DQ1-Sm7oekboYNsFtzcYeZSnqhdPrk/edit#gid=0',  # Full URL to sheet being written to.
  'tab':'Sheet1',  # Existing tab in sheet to write to.
}

print("Parameters Set To: %s" % FIELDS)

from starthinker.util.configuration import execute
from starthinker.util.recipe import json_set_fields

TASKS = [
  {
    'dbm':{
      'auth':{'field':{'name':'auth_read','kind':'authentication','order':1,'default':'user','description':'Credentials used for reading data.'}},
      'report':{
        'report_id':{'field':{'name':'report_id','kind':'integer','order':1,'default':'','description':'DV360 report ID given in UI, not needed if name used.'}},
        'name':{'field':{'name':'report_name','kind':'string','order':2,'default':'','description':'Name of report, not needed if ID used.'}}
      },
      'out':{
        'sheets':{
          'sheet':{'field':{'name':'sheet','kind':'string','order':3,'default':'','description':'Full URL to sheet being written to.'}},
          'tab':{'field':{'name':'tab','kind':'string','order':4,'default':'','description':'Existing tab in sheet to write to.'}},
          'range':'A1'
        }
      }
    }
  }
]

json_set_fields(TASKS, FIELDS)

execute(CONFIG, TASKS, force=True)

Here some stuff I've already done:

Created a new report on DV360 under my user

Made sure to have all accesses to DV360 and the spreadsheet

Made sure to have permission for the Google Cloud project

Gave me permission to the star thinker service account.

Created a new client and new service account within GCP and placed these files into the same folder with the python script (made sure to change the name of the files in the script).

Also, when I try to open this URL I see the invalid request issue like below https://accounts.google.com/signin/oauth/error/v2

To finish, there are x3 json files placed in the same folder as the script:

service.json

client.json

user.json

I was able to re-create the first two on Google Cloud (as mentioned above), but couldn't find a way to re-create user.json which I think might be the main issue here.

I would really appreciate some help on this.

Thanks.


问:
No exported member 'SignaturePadModule' / Cannot find module 'angular2-signaturepad/signature-pad'

Im trying to build an APK of this ionic project im working on. I already installed and updated the import but this still shows. Any help would be appreciated


问:
How to draw refractions from a lass sphere in ray tracing?
I have a simple ray tracer in python, but I couldn’t make refractions in a sphere using any of the guides.

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

def normalize(vector):  # normalize vector
    return vector / np.linalg.norm(vector)

def refracted(vector, norm, n1, n2):  # simulates vector refraction
    n = n1 / n2
    cosI = -np.dot(norm, vector)
    sinT2 = n ** 2 * (1 - cosI ** 2)
    cosT = np.sqrt(1 - sinT2)
    return n * vector + (n * cosI - cosT) * norm

def sphere_intersect(center, radius, ray_ray_origin, ray_ray_direction, glass):
    b = 2 * np.dot(ray_ray_direction, ray_ray_origin - center)
    c = np.linalg.norm(ray_ray_origin - center) ** 2 - radius ** 2
    delta = b ** 2 - 4 * c
    if delta > 0:
        t1 = (-b + np.sqrt(delta)) / 2
        t2 = (-b - np.sqrt(delta)) / 2
        if t1 > 0 and t2 > 0 and not glass:
            # returns min distance to intersection
            return min(t1, t2)
        if glass:
            # returns cords of intersection
            return ray_ray_origin + max(t1, t2) * ray_ray_direction
    return None

def nearest_intersected_object(objects, ray_ray_origin, ray_ray_direction, glass=False):
    distances = [sphere_intersect(obj['center'], obj['radius'], ray_ray_origin, ray_ray_direction, glass) for obj in objects]
    nearest_object = None
    min_distance = np.inf
    for index, distance in enumerate(distances):
        if distance and distance < min_distance:
            min_distance = distance
            nearest_object = objects[index]
    return nearest_object, min_distance

width = 300
height = 200
max_depth = 10

camera = np.array([0, 0, 1])
ratio = float(width) / height
screen = (-1, 1 / ratio, 1, -1 / ratio)  # screen cords

light = {'position': np.array([1, 3, 4])}

objects = [
    {'center': np.array([0.0, 0, 0.3]), 'radius': 0.35, 'type': 'glass'},
    {'center': np.array([0, -9000, 0]), 'radius': 9000 - 0.7, 'color': np.array([0.9, 0.9, 0.9]), 'type': 'sphere'},
]

image = np.zeros((height, width, 3))
for i, y in enumerate(np.linspace(screen[1], screen[3], height)):
    for j, x in enumerate(np.linspace(screen[0], screen[2], width)):

        # screen and start vector

        pixel = np.array([x, y, 0])
        ray_origin = camera
        ray_direction = normalize(pixel - ray_origin)

        # intersection
        nearest_object, min_distance = nearest_intersected_object(objects, ray_origin, ray_direction)
        if nearest_object is None:
            continue  # ray_goes_to_infinity

        intersection = ray_origin + min_distance * ray_direction
        normal_to_surface = normalize(intersection - nearest_object['center'])
        shifted_point = intersection + 1e-5 * normal_to_surface
        # if for type 'glass'
        if nearest_object['type'] == 'glass':
            # 1st refraction
            ray_origin = shifted_point
            ray_direction = refracted(ray_direction, normal_to_surface, 1, 1.5)
            # 2nd refraction
            min_distance = sphere_intersect(nearest_object['center'], nearest_object['radius'], ray_origin, ray_direction, True)
            normal_to_surface = normalize(ray_origin + min_distance * ray_direction - nearest_object['center'])
            intersection = ray_origin + min_distance * ray_direction
            ray_origin = intersection
            ray_direction = refracted(ray_direction, normal_to_surface, 1, 1.5)
            # floor
            nearest_object = objects[1]
            if nearest_object is None:
                continue  # ray_goes_to_infinity

        color = np.zeros(3)
        color += nearest_object['color']
        # chess_floor_to_check_refractions
        if nearest_object['type'] == 'sphere' and (round(intersection[0]) % 2 == 0 and round(intersection[2]) % 2 != 0
                                                or round(intersection[0]) % 2 != 0 and round(
                    intersection[2]) % 2 == 0):
            color = np.zeros(3)
        image[i, j] = np.clip(color, 0, 1)
    print(f'{"%.1f" % (i/height * 100)}% complete')
plt.imsave('shitty_balls.png', image)

</code>```

The problem may be in the refraction function itself, because it behaves very strangely when the angle between the vector and the normal is more than 90 degrees (this appears when the ray leaves the sphere)

For now, here's how I'm trying to simulate refractions (# if for type 'glass'):

find the distance to the first intersection with the sphere, find the normal to the surface

Find the coordinates of this intersection

according to the formula from the Internet, I find the direction of the new vector, taking into account refraction

I repeat the algorithm for the second refraction and exit of the beam from the sphere

P.S. For now, I'll manage with only two refractions without everything else

P.P.S. I don't know exactly about the refraction function, but there is definitely a problem with my 'if for type glass'. After executing this 'if', 'origin' should be outside of the glass ball, but 'origin' is in it.

Body:
I have a simple ray tracer in python, but I couldn’t make refractions in a sphere using any of the guides.

import numpy as np
import matplotlib.pyplot as plt

def normalize(vector):  # normalize vector
    return vector / np.linalg.norm(vector)

def refracted(vector, norm, n1, n2):  # simulates vector refraction
    n = n1 / n2
    cosI = -np.dot(norm, vector)
    sinT2 = n ** 2 * (1 - cosI ** 2)
    cosT = np.sqrt(1 - sinT2)
    return n * vector + (n * cosI - cosT) * norm

def sphere_intersect(center, radius, ray_ray_origin, ray_ray_direction, glass):
    b = 2 * np.dot(ray_ray_direction, ray_ray_origin - center)
    c = np.linalg.norm(ray_ray_origin - center) ** 2 - radius ** 2
    delta = b ** 2 - 4 * c
    if delta > 0:
        t1 = (-b + np.sqrt(delta)) / 2
        t2 = (-b - np.sqrt(delta)) / 2
        if t1 > 0 and t2 > 0 and not glass:
            # returns min distance to intersection
            return min(t1, t2)
        if glass:
            # returns cords of intersection
            return ray_ray_origin + max(t1, t2) * ray_ray_direction
    return None

def nearest_intersected_object(objects, ray_ray_origin, ray_ray_direction, glass=False):
    distances = [sphere_intersect(obj['center'], obj['radius'], ray_ray_origin, ray_ray_direction, glass) for obj in objects]
    nearest_object = None
    min_distance = np.inf
    for index, distance in enumerate(distances):
        if distance and distance < min_distance:
            min_distance = distance
            nearest_object = objects[index]
    return nearest_object, min_distance

width = 300
height = 200
max_depth = 10

camera = np.array([0, 0, 1])
ratio = float(width) / height
screen = (-1, 1 / ratio, 1, -1 / ratio)  # screen cords

light = {'position': np.array([1, 3, 4])}

objects = [
    {'center': np.array([0.0, 0, 0.3]), 'radius': 0.35, 'type': 'glass'},
    {'center': np.array([0, -9000, 0]), 'radius': 9000 - 0.7, 'color': np.array([0.9, 0.9, 0.9]), 'type': 'sphere'},
]

image = np.zeros((height, width, 3))
for i, y in enumerate(np.linspace(screen[1], screen[3], height)):
    for j, x in enumerate(np.linspace(screen[0], screen[2], width)):

        # screen and start vector

        pixel = np.array([x, y, 0])
        ray_origin = camera
        ray_direction = normalize(pixel - ray_origin)

        # intersection
        nearest_object, min_distance = nearest_intersected_object(objects, ray_origin, ray_direction)
        if nearest_object is None:
            continue  # ray_goes_to_infinity

        intersection = ray_origin + min_distance * ray_direction
        normal_to_surface = normalize(intersection - nearest_object['center'])
        shifted_point = intersection + 1e-5 * normal_to_surface
        # if for type 'glass'
        if nearest_object['type'] == 'glass':
            # 1st refraction
            ray_origin = shifted_point
            ray_direction = refracted(ray_direction, normal_to_surface, 1, 1.5)
            # 2nd refraction
            min_distance = sphere_intersect(nearest_object['center'], nearest_object['radius'], ray_origin, ray_direction, True)
            normal_to_surface = normalize(ray_origin + min_distance * ray_direction - nearest_object['center'])
            intersection = ray_origin + min_distance * ray_direction
            ray_origin = intersection
            ray_direction = refracted(ray_direction, normal_to_surface, 1, 1.5)
            # floor
            nearest_object = objects[1]
            if nearest_object is None:
                continue  # ray_goes_to_infinity

        color = np.zeros(3)
        color += nearest_object['color']
        # chess_floor_to_check_refractions
        if nearest_object['type'] == 'sphere' and (round(intersection[0]) % 2 == 0 and round(intersection[2]) % 2 != 0
                                                or round(intersection[0]) % 2 != 0 and round(
                    intersection[2]) % 2 == 0):
            color = np.zeros(3)
        image[i, j] = np.clip(color, 0, 1)
    print(f'{"%.1f" % (i/height * 100)}% complete')
plt.imsave('shitty_balls.png', image)

The problem may be in the refraction function itself, because it behaves very strangely when the angle between the vector and the normal is more than 90 degrees (this appears when the ray leaves the sphere)

For now, here's how I'm trying to simulate refractions (# if for type 'glass'):

find the distance to the first intersection with the sphere, find the normal to the surface

Find the coordinates of this intersection

according to the formula from the Internet, I find the direction of the new vector, taking into account refraction

I repeat the algorithm for the second refraction and exit of the beam from the sphere

P.S. For now, I'll manage with only two refractions without everything else

P.P.S. I don't know exactly about the refraction function, but there is definitely a problem with my 'if for type glass'. After executing this 'if', 'origin' should be outside of the glass ball, but 'origin' is in it.


问:
Resettable guild cooldown for discord.py slash command
I am trying to add a cooldown to a slash command I have written in discord.py. The cooldown will need to be reset in certain cases, so I cannot use the @app_commands.checks.cooldown decorator and instead will have to write a custom cooldown. I have written some code for this but it hasn't worked so far.

My Code:

    def get_ratelimit(self, message) -> typing.Optional[int]:
        bucket = commands.CooldownMapping.from_cooldown(1, 20, commands.BucketType.guild).get_bucket(message)
        return bucket.update_rate_limit()

    @app_commands.command(name="cooldown_test", description="Testing cooldown")
    async def cooldown_test(self, inter):
        limit = self.get_ratelimit(inter)
        if limit == None:
            # some code here as well as condition to reset cooldown

        else:
            await inter.response.send_message(f"This is on a 20 second cooldown.", ephemeral=True)
```

The code does run without errors, but get_ratelimit returns None everytime, therefore bypassing the cooldown. I'm looking for help to fix this issue so that the cooldown works normally (one use per guild every 20 seconds) but can still also be reset in the code. Thanks in advance!

Body:
I am trying to add a cooldown to a slash command I have written in discord.py. The cooldown will need to be reset in certain cases, so I cannot use the @app_commands.checks.cooldown decorator and instead will have to write a custom cooldown. I have written some code for this but it hasn't worked so far.

My Code:

    def get_ratelimit(self, message) -> typing.Optional[int]:
        bucket = commands.CooldownMapping.from_cooldown(1, 20, commands.BucketType.guild).get_bucket(message)
        return bucket.update_rate_limit()

    @app_commands.command(name="cooldown_test", description="Testing cooldown")
    async def cooldown_test(self, inter):
        limit = self.get_ratelimit(inter)
        if limit == None:
            # some code here as well as condition to reset cooldown

        else:
            await inter.response.send_message(f"This is on a 20 second cooldown.", ephemeral=True)

The code does run without errors, but get_ratelimit returns None everytime, therefore bypassing the cooldown. I'm looking for help to fix this issue so that the cooldown works normally (one use per guild every 20 seconds) but can still also be reset in the code. Thanks in advance!


问:
Hyperparameter tunning of CNN model using Bayesian Optimization
I am trying to optimize the hyperparameters of a simple CNN model using Bayesian optimization, but I have been getting an error that I am trying to fix. Can someone please help?

My code:

```<code>
from sklearn.model_selection import train_test_split
from sklearn import datasets
from keras.models import Sequential

iris = datasets.load_iris()
X = iris.data
y = iris.target

def create_model(num_filters, kernel_size, activation_index):
# Create a CNN model with the specified hyperparameters
    activation_map = {0: 'relu', 1: 'sigmoid'}
    activation = activation_map[int(activation_index)]
    model = Sequential()
    model.add(Conv2D(num_filters, kernel_size, activation=activation, input_shape=(4, 1)))
    model.add(MaxPooling2D())
    model.add(Flatten())
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

def objective_function(num_filters, kernel_size, activation_index):
    model = create_model(num_filters, kernel_size, activation_index)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    model.fit(X_train, y_train, epochs=10, verbose=0)
    loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
    return accuracy

bounds = {
'num_filters': (32, 128),
'kernel_size': (3, 7),
'activation_index': (0, 1)
}

optimizer = BayesianOptimization(objective_function, bounds)
optimizer.maximize(init_points=5, n_iter=10)

best_params = optimizer.maximize(init_points=5, n_iter=10)
print("Best hyperparameter values:", best_params['x'])
print("Best model accuracy:", best_params['fun'])
</code>```

The error message:

ValueError: The `kernel_size` argument must be a tuple of 2 integers. Received: 3.048666679718899

Body:
I am trying to optimize the hyperparameters of a simple CNN model using Bayesian optimization, but I have been getting an error that I am trying to fix. Can someone please help?

My code:

from sklearn.model_selection import train_test_split
from sklearn import datasets
from keras.models import Sequential

iris = datasets.load_iris()
X = iris.data
y = iris.target

def create_model(num_filters, kernel_size, activation_index):
# Create a CNN model with the specified hyperparameters
    activation_map = {0: 'relu', 1: 'sigmoid'}
    activation = activation_map[int(activation_index)]
    model = Sequential()
    model.add(Conv2D(num_filters, kernel_size, activation=activation, input_shape=(4, 1)))
    model.add(MaxPooling2D())
    model.add(Flatten())
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

def objective_function(num_filters, kernel_size, activation_index):
    model = create_model(num_filters, kernel_size, activation_index)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    model.fit(X_train, y_train, epochs=10, verbose=0)
    loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
    return accuracy

bounds = {
'num_filters': (32, 128),
'kernel_size': (3, 7),
'activation_index': (0, 1)
}

optimizer = BayesianOptimization(objective_function, bounds)
optimizer.maximize(init_points=5, n_iter=10)

best_params = optimizer.maximize(init_points=5, n_iter=10)
print("Best hyperparameter values:", best_params['x'])
print("Best model accuracy:", best_params['fun'])

The error message:

ValueError: The `kernel_size` argument must be a tuple of 2 integers. Received: 3.048666679718899


问:
How to connect rig to mesh correctly
I have a nice mesh and a working rig, but how do I make it so when I deform the rig into an animation pose, it also will make the mesh go into that pose? I have tried doing COMMAND-P - Deform - With Weights, but that did nothing.
Video of the bug here:
https://youtu.be/rOiX86wE7tA

Thanks :)

Title: How to connect rig to mesh correctly


问:
VSCode doesn't recognize non-existent file imports in React
On React projects, I'm able to import non-existent files without VSCode underlining the error.

The "App" file is not in my project directory : -

I've reinstalled the ESLint extension and I've also enabled "javascript.validate.enable" in Settings. Is there a way to catch these imports?


问:
Is pid in perf_event_open() actually tid?
Under sample mode, when I test on all cpus, pid = 1:

```<code>fd = perf_event_open(&attr, 1, -1, -1, 0);
</code>```

I always see pid == tid:

```<code>**********************************
value of meta_page: 7fd262ce2000
value of meta_page->data_head: 9838
value of meta_page->data_tail: 9820
value of meta_page->data_size: 10000
The size of the data section is: 18
sample.addr: 0x5622ef76f948
sample.pid: 1
sample.tid: 1
the final current is: 36197080
the final upper bound is: 36197080
**********************************
**********************************
value of meta_page: 7fd262ce2000
value of meta_page->data_head: 9850
value of meta_page->data_tail: 9838
value of meta_page->data_size: 10000
The size of the data section is: 18
sample.addr: 0x7fffc51ef080
sample.pid: 1
sample.tid: 1
the final current is: 36197080
the final upper bound is: 36197080
**********************************
**********************************
value of meta_page: 7fd262ce2000
value of meta_page->data_head: 9850
value of meta_page->data_tail: 9850
value of meta_page->data_size: 10000
Full ring buffer
**********************************

</code>```

I have done the following trials:

a) I bind mysqld to cpu 0 and 1, with taskset -cp 0,1 pidof(mysqld)

b) I test with fd = perf_event_open(&attr, -1, 0, -1, 0);

and I can see many results with pid == pidof(mysqld), which is 2211374 in the following example:

```<code>**********************************
value of meta_page: 7f6fa4a18000
value of meta_page->data_head: 15820
value of meta_page->data_tail: 157e8
value of meta_page->data_size: 10000
The size of the data section is: 38
the header type is: 6
sample.addr: 0x7f8dd802e058
sample.pid: 2211374
sample.tid: 3148307
the final current is: 12784408
the final upper bound is: 12784408
**********************************
**********************************
value of meta_page: 7f6fa4a18000
value of meta_page->data_head: 15858
value of meta_page->data_tail: 15820
value of meta_page->data_size: 10000
The size of the data section is: 38
the header type is: 5
sample.addr: 0x7f8e3ff75d90
sample.pid: 2211374
sample.tid: 3148308
the final current is: 12784408
the final upper bound is: 12784408
**********************************
**********************************
value of meta_page: 7f6fa4a18000
value of meta_page->data_head: 15890
value of meta_page->data_tail: 15858
value of meta_page->data_size: 10000
The size of the data section is: 38
the header type is: 6
sample.addr: 0x7f8da803b6e0
sample.pid: 2211374
sample.tid: 3148306
the final current is: 12784408
the final upper bound is: 12784408
**********************************
</code>```

c) but I can get barely anything testing with fd = perf_event_open(&attr, pidof(mysqld), 0, -1, 0); and fd = perf_event_open(&attr, pidof(mysqld), -1, -1, 0);

d) Quick summary of my tests:

i) I can get desired results when listening on specific CPU for all processes, including mysqld

ii) I can barely get anything when listening for specific process[mysqld], whether listening on all CPU/specific CPU

iii) I can see pid == tid when listening for process with pid = 1

Therefore I think it will be natural to make the assumption that the pid here in perf_event_open(struct perf_event_attr *hw_event, pid_t pid, int cpu, int group_fd, unsigned long flags) is actually tid

Body:
Under sample mode, when I test on all cpus, pid = 1:

fd = perf_event_open(&attr, 1, -1, -1, 0);

I always see pid == tid:

**********************************
value of meta_page: 7fd262ce2000
value of meta_page->data_head: 9838
value of meta_page->data_tail: 9820
value of meta_page->data_size: 10000
The size of the data section is: 18
sample.addr: 0x5622ef76f948
sample.pid: 1
sample.tid: 1
the final current is: 36197080
the final upper bound is: 36197080
**********************************
**********************************
value of meta_page: 7fd262ce2000
value of meta_page->data_head: 9850
value of meta_page->data_tail: 9838
value of meta_page->data_size: 10000
The size of the data section is: 18
sample.addr: 0x7fffc51ef080
sample.pid: 1
sample.tid: 1
the final current is: 36197080
the final upper bound is: 36197080
**********************************
**********************************
value of meta_page: 7fd262ce2000
value of meta_page->data_head: 9850
value of meta_page->data_tail: 9850
value of meta_page->data_size: 10000
Full ring buffer
**********************************

I have done the following trials:

a) I bind mysqld to cpu 0 and 1, with taskset -cp 0,1 pidof(mysqld)

b) I test with fd = perf_event_open(&attr, -1, 0, -1, 0);

and I can see many results with pid == pidof(mysqld), which is 2211374 in the following example:

**********************************
value of meta_page: 7f6fa4a18000
value of meta_page->data_head: 15820
value of meta_page->data_tail: 157e8
value of meta_page->data_size: 10000
The size of the data section is: 38
the header type is: 6
sample.addr: 0x7f8dd802e058
sample.pid: 2211374
sample.tid: 3148307
the final current is: 12784408
the final upper bound is: 12784408
**********************************
**********************************
value of meta_page: 7f6fa4a18000
value of meta_page->data_head: 15858
value of meta_page->data_tail: 15820
value of meta_page->data_size: 10000
The size of the data section is: 38
the header type is: 5
sample.addr: 0x7f8e3ff75d90
sample.pid: 2211374
sample.tid: 3148308
the final current is: 12784408
the final upper bound is: 12784408
**********************************
**********************************
value of meta_page: 7f6fa4a18000
value of meta_page->data_head: 15890
value of meta_page->data_tail: 15858
value of meta_page->data_size: 10000
The size of the data section is: 38
the header type is: 6
sample.addr: 0x7f8da803b6e0
sample.pid: 2211374
sample.tid: 3148306
the final current is: 12784408
the final upper bound is: 12784408
**********************************

c) but I can get barely anything testing with fd = perf_event_open(&attr, pidof(mysqld), 0, -1, 0); and fd = perf_event_open(&attr, pidof(mysqld), -1, -1, 0);

d) Quick summary of my tests:

i) I can get desired results when listening on specific CPU for all processes, including mysqld

ii) I can barely get anything when listening for specific process[mysqld], whether listening on all CPU/specific CPU

iii) I can see pid == tid when listening for process with pid = 1

Therefore I think it will be natural to make the assumption that the pid here in perf_event_open(struct perf_event_attr *hw_event, pid_t pid, int cpu, int group_fd, unsigned long flags) is actually tid


问:
required a bean of type that could not be found when register and autowired using the child class
I have met quite a strange situation, while compiling im my develope and test environment then run my application, it is OK. But when I deploy my code to production environment the code was crashed although compiling was a succeed.

The error is
required a bean of type xxxxxxx that could not be found

The dependencies are all OK, and the application was run well in all my dev and test servers except for prod server.

Here is the simplified project structure:

myproject

    |

    module-common

    |       |

    |       com.myapp.config

    |           |

    |           GlobalSnowFlakeConfig.java

    module-application(dependent on module-common)

           |

           Application.java (springboot main function)

com.myapp.config

           |    |

           |    CustomizedSnowFlakeConfig.java

           com.myapp.service

               |

               TargetService.java

Here is the code:

```<code>@Slf4j
@Configuration
public class GlobalSnowFlakeConfig {
    @Value("${spring.application.name:anonymous}")
    private String applicationName;

    @Value("${server.port}")
    private String port;

    @Bean
    public MachineInfo registerMachineInfo(RedissonUtil redissonUtil, RedisUtils redisUtils) {
        log.info("Loading MachineInfo...");
        return new MachineInfo(redissonUtil, redisUtils, applicationName, port);
    }

    @Bean
    @ConditionalOnMissingBean(Snowflake.class)
    public Snowflake initializeSnowFlake(MachineInfo machineInfo) {
        log.info("Current DataCenterId={} machineId={}", machineInfo.getDataCenterId(), machineInfo.getMachineId());
        return new Snowflake(
                machineInfo.getMachineId(),
                machineInfo.getDataCenterId(),
                true);
    }

}
</code>```
```<code>public class CustomizedSnowFlake extends Snowflake {
    ....the overriding methods and new features....
}
</code>```
```<code>@Slf4j
@Configuration
public class CustomizedSnowFlakeConfig {
    @Bean
    public Snowflake initializeSnowFlake(MachineInfo machineInfo) {
        log.info("Current DataCenterId={} machineId={}", machineInfo.getDataCenterId(), machineInfo.getMachineId());
        return new CustomizedSnowFlake(
                machineInfo.getMachineId(),
                machineInfo.getDataCenterId(),
                true,
                machineInfo.getIp() + ":" + machineInfo.getPort());
    }
}
</code>```
```<code>@Service
@Slf4j
public class WebSocketServiceImpl{
    @Autowired
    private CustomizedSnowFlake snowflake;

    ....other business code....
}
</code>```
```<code>@SpringBootApplication
@ComponentScan(basePackages = {"com.myapp"})
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.myapp.webcommon.api"})
@MapperScan(basePackages = {"com.myapp.mydb.mapper"})
public class Application{
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);
        WebSocketServer.setApplicationContext(applicationContext);
    }
}
</code>```

I think method initializeSnowFlake will override the config of Snowflake and replace the GlobalSnowFlakeConfig's bean of type Snowflake, but the jar file compliled in my prod server can never start up, it will always print required a bean of type xxxx.CustomizedSnowFlake that could not be found.

On the other hand, all the same code compiled in my dev and test server has nothing wrong and good to start.

I have checked my maven and jdk version, There are little differences :

```<code>In prod server

Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
Maven home: /usr/local/maven/apache-maven-3.8.1
Java version: 1.8.0_291, vendor: Oracle Corporation, runtime: /usr/local/java/jdk1.8.0_291/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.10.23-5.al8.x86_64", arch: "amd64", family: "unix"
</code>```
```<code>In test server1

Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
Maven home: /etc/maven/apache-maven-3.8.1
Java version: 1.8.0_292, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-1160.25.1.el7.x86_64", arch: "amd64", family: "unix"

IN test server2

Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/share/maven
Java version: 1.8.0_292, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-1160.31.1.el7.x86_64", arch: "amd64", family: "unix"

</code>```

Although application can be started well by changing return type from Snowflake to CustomizedSnowflake in CustomizedSnowFlakeConfig, I still don't know why my test and dev environment never come up with this problem.

the version of maven and jdk in test server1 and prod server are nearly the same. So I don't think this problem is due to maven version or jdk version.

By debugging into source code of springboot, I have found someting strange.

in DefaultSingletonBeanRegistry, method isTypeMatch will call getSingleton to get the singletonObject named initializeSnowFlake which is defined in CustomizedSnowFlakeConfig, but the jar file compiled in prod server will never have such object returned while the jar file compiled in test/dev server will have one.

I don't know why such singletonObject is not in DefaultSingletonBeanRegistry,everything looks normal.

Body:
I have met quite a strange situation, while compiling im my develope and test environment then run my application, it is OK. But when I deploy my code to production environment the code was crashed although compiling was a succeed.

The error is
required a bean of type xxxxxxx that could not be found

The dependencies are all OK, and the application was run well in all my dev and test servers except for prod server.

Here is the simplified project structure:

myproject

    |

    module-common

    |       |

    |       com.myapp.config

    |           |

    |           GlobalSnowFlakeConfig.java

    module-application(dependent on module-common)

           |

           Application.java (springboot main function)

com.myapp.config

           |    |

           |    CustomizedSnowFlakeConfig.java

           com.myapp.service

               |

               TargetService.java

Here is the code:

@Slf4j
@Configuration
public class GlobalSnowFlakeConfig {
    @Value("${spring.application.name:anonymous}")
    private String applicationName;

    @Value("${server.port}")
    private String port;

    @Bean
    public MachineInfo registerMachineInfo(RedissonUtil redissonUtil, RedisUtils redisUtils) {
        log.info("Loading MachineInfo...");
        return new MachineInfo(redissonUtil, redisUtils, applicationName, port);
    }

    @Bean
    @ConditionalOnMissingBean(Snowflake.class)
    public Snowflake initializeSnowFlake(MachineInfo machineInfo) {
        log.info("Current DataCenterId={} machineId={}", machineInfo.getDataCenterId(), machineInfo.getMachineId());
        return new Snowflake(
                machineInfo.getMachineId(),
                machineInfo.getDataCenterId(),
                true);
    }

}

public class CustomizedSnowFlake extends Snowflake {
    ....the overriding methods and new features....
}

@Slf4j
@Configuration
public class CustomizedSnowFlakeConfig {
    @Bean
    public Snowflake initializeSnowFlake(MachineInfo machineInfo) {
        log.info("Current DataCenterId={} machineId={}", machineInfo.getDataCenterId(), machineInfo.getMachineId());
        return new CustomizedSnowFlake(
                machineInfo.getMachineId(),
                machineInfo.getDataCenterId(),
                true,
                machineInfo.getIp() + ":" + machineInfo.getPort());
    }
}

@Service
@Slf4j
public class WebSocketServiceImpl{
    @Autowired
    private CustomizedSnowFlake snowflake;

    ....other business code....
}

@SpringBootApplication
@ComponentScan(basePackages = {"com.myapp"})
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.myapp.webcommon.api"})
@MapperScan(basePackages = {"com.myapp.mydb.mapper"})
public class Application{
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);
        WebSocketServer.setApplicationContext(applicationContext);
    }
}

I think method initializeSnowFlake will override the config of Snowflake and replace the GlobalSnowFlakeConfig's bean of type Snowflake, but the jar file compliled in my prod server can never start up, it will always print required a bean of type xxxx.CustomizedSnowFlake that could not be found.

On the other hand, all the same code compiled in my dev and test server has nothing wrong and good to start.

I have checked my maven and jdk version, There are little differences :

In prod server

Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
Maven home: /usr/local/maven/apache-maven-3.8.1
Java version: 1.8.0_291, vendor: Oracle Corporation, runtime: /usr/local/java/jdk1.8.0_291/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.10.23-5.al8.x86_64", arch: "amd64", family: "unix"

In test server1

Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)
Maven home: /etc/maven/apache-maven-3.8.1
Java version: 1.8.0_292, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-1160.25.1.el7.x86_64", arch: "amd64", family: "unix"

IN test server2

Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/share/maven
Java version: 1.8.0_292, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-1160.31.1.el7.x86_64", arch: "amd64", family: "unix"

Although application can be started well by changing return type from Snowflake to CustomizedSnowflake in CustomizedSnowFlakeConfig, I still don't know why my test and dev environment never come up with this problem.

the version of maven and jdk in test server1 and prod server are nearly the same. So I don't think this problem is due to maven version or jdk version.

By debugging into source code of springboot, I have found someting strange.

in DefaultSingletonBeanRegistry, method isTypeMatch will call getSingleton to get the singletonObject named initializeSnowFlake which is defined in CustomizedSnowFlakeConfig, but the jar file compiled in prod server will never have such object returned while the jar file compiled in test/dev server will have one.

I don't know why such singletonObject is not in DefaultSingletonBeanRegistry,everything looks normal.


Title: How to compare to dataframes and return matching and non matching

Body:
I have 2 data frames with the same length size. I'm trying to match the first 3 with the other data frame and then the next 3 and so on and so on. Hopefully I'm making sense.

import pandas as pd
import numpy as np

df1    = pd.DataFrame([[100,1,2,4,5,6,8],
                       [87,1,6,20,22,23,34],
                       [99,1,12,13,34,45,46],
                       [64,1,10,14,29,32,33],
                       [55,1,22,13,23,33,35],
                       [66,1,6,7,8,9,10],
                       [77,1,2,3,5,6,8],
                       [811,1,2,5,6,8,10],
                       [118,1,7,8,22,44,56]],
                       columns = ['Id', 'Num1','Num2','Num3','Num4','Num5','Num6'])

df2    = pd.DataFrame([[89,2,4,6,8,10,12],
                       [81,2,7,25,28,33,54],
                       [91,2,13,17,33,45,48],
                       [66,2,20,24,25,36,38],
                       [56,1,24,33,43,53,65],
                       [78,3,14,15,18,19,20],
                       [120,4,10,23,25,26,38],
                       [59,5,22,35,36,38,40],
                       [125,1,17,18,32,44,56]],
                       columns = ['Id', 'Num1','Num2','Num3','Num4','Num5','Num6'])

I would like my result to like this

   match = pd.DataFrame([[100,89,2,4,6,8],
       [100,81,2,],
       [100,91,2],
       [87,89,6],
      [99,89,12],
      [64,56,1,43],
      [64,78,14],
      [55,56,1,33],
      [77,59,5],
      [811,59,5],
      [118,59,22],
      [118,125,1,44,56]],
      columns = ['Id','Id','Num1','Num2','Num3','Num4','Num5','Num6'])


Title: Able to plot 2 graphs in a row but not 3. get ValueError: values must be a 1D array

Body:
This is the dataframe:

Data for last 8 months

                        date     close  volume  change%      obv  compare   close_trend
6  2022-06-30 00:00:00+05:30  18760.40  358433     5.52  1358338     True  18482.242046
7  2022-07-31 00:00:00+05:30  20015.10  252637     6.27  1610975     True  18905.447351
8  2022-08-31 00:00:00+05:30  18739.75  317107    -6.81  1293868    False  19328.826505
9  2022-09-30 00:00:00+05:30  19139.15  561137     2.09  1855005     True  19753.246889
10 2022-10-31 00:00:00+05:30  19246.95  243999     0.56  2099004     True  20179.207712
11 2022-11-30 00:00:00+05:30  20237.80  311138     4.90  2410142     True  20606.824373
12 2022-12-31 00:00:00+05:30  21367.20  386070     5.29  2796212     True  21035.629608
13 2023-01-31 00:00:00+05:30  22250.00  101527     3.97  2897739     True  21464.925515

I am able to plot 2 graphs in a row using matplotlib in jupyter notebook.

            fig = plt.figure(figsize=(7,2))
            plt.subplot(1,2,1)
            plt.plot(df['date'], df['close'], color='red', figure=fig)
            plt.subplot(1,2,2)
            plt.plot(df[['close','close_trend']],figure=fig)
            plt.tight_layout()
            plt.show()

I get:

But when I try to plot 3 graphs like this, I get ValueError: values must be a 1D array

    fig = plt.figure(figsize=(7,2))
    plt.subplot(1,3,1)
    plt.plot(df['date'], df['close'], color='red', figure=fig)
    plt.subplot(1,3,2)
    plt.plot(df[['close','close_trend']],figure=fig)
    plt.subplot(1,3,3)
    plt.plot(df.index, df['obv'],color='blue', figure=fig)
    plt.tight_layout()
    plt.show()

How do I get 3 plots in a row?


问:
How can we call Database Connectionstring from a async function while calling an api
`//Dbconnect.js File

```<code>async function connect() {
  const credential = new DefaultAzureCredential();
  const keyVaultName = "dbconnection";
  const url = "https://" + keyVaultName + ".vault.azure.net";
  const client = new SecretClient(url, credential);

  const connection = await mysql.createConnection({
    host: (await client.getSecret('host')).value,
    user: (await client.getSecret('user')).value,
    password: '',
    database:(await client.getSecret('database')).value,
  });
  connection.connect((err) => {
        if(err){
          console.log('Error connecting to Db');
          return;
        }
        console.log('Connection established successfully');
      });
    return connection;
}
connect().catch((error) => {
  console.error("An error occurred:", error);
  process.exit(1);
});

module.exports.connect = connect;

//APi.js File
const mysql = require('../DbConnect').connect;
exports.customerInformation = async (req, res) => {
    let qry = "select * from customerinformation";
    mysql query(qry, (err, results) => {
    if (err){
    res.status(500).json({response:"500",status:'Failed',message:"Internal Server Error"});
    }
    else {
            if (results.length > 0) {
                 res.status(200).json({response:"200",status:'success',data:results});
            }else{
                 res.status(404).json({response:"404",status:'Failed',message:"Invalid Credential"});
            }
         }
    })
};
</code>```

`

Keyvault secrets are fectched and Connection Is getting established successfully. But when I am Trying to call the  API It is SHowing query is not defined as the error

Body:
`//Dbconnect.js File

async function connect() {
  const credential = new DefaultAzureCredential();
  const keyVaultName = "dbconnection";
  const url = "https://" + keyVaultName + ".vault.azure.net";
  const client = new SecretClient(url, credential);

  const connection = await mysql.createConnection({
    host: (await client.getSecret('host')).value,
    user: (await client.getSecret('user')).value,
    password: '',
    database:(await client.getSecret('database')).value,
  });
  connection.connect((err) => {
        if(err){
          console.log('Error connecting to Db');
          return;
        }
        console.log('Connection established successfully');
      });
    return connection;
}
connect().catch((error) => {
  console.error("An error occurred:", error);
  process.exit(1);
});

module.exports.connect = connect;

//APi.js File
const mysql = require('../DbConnect').connect;
exports.customerInformation = async (req, res) => {
    let qry = "select * from customerinformation";
    mysql query(qry, (err, results) => {
    if (err){
    res.status(500).json({response:"500",status:'Failed',message:"Internal Server Error"});
    }
    else {
            if (results.length > 0) {
                 res.status(200).json({response:"200",status:'success',data:results});
            }else{
                 res.status(404).json({response:"404",status:'Failed',message:"Invalid Credential"});
            }
         }
    })
};

`

Keyvault secrets are fectched and Connection Is getting established successfully. But when I am Trying to call the  API It is SHowing query is not defined as the error


问:
Check DocumentFile is editable text file or not in Android java
```<code>var documentFile = DocumentFile.fromSingleUri(this,uri);

                if(documentFile.isFile() && isEditableFileType(documentFile.getType())){

                    BaseApp.showToast("Y=> "+documentFile.getType());

                }else{

                    BaseApp.showToast("N=> "+documentFile.getType());

                }
</code>```

and isEditableFileType method goes like this
`
private boolean isEditableFileType(@NonNull String fileType){

```<code>    return fileType.equals("application/octet-stream")

        || fileType.equals("text/html")

        || fileType.equals("text/css")

        || fileType.equals("text/plain")

        || fileType.equals("text/xml");

        //|| fileType.equals("h");

}
</code>```

`

the problem is with application/octet-stream

some files with or without extension is with that type but some extension like .jar,.tar.gz are the same type but those are not editable as text content

Body:
var documentFile = DocumentFile.fromSingleUri(this,uri);

                if(documentFile.isFile() && isEditableFileType(documentFile.getType())){

                    BaseApp.showToast("Y=> "+documentFile.getType());

                }else{

                    BaseApp.showToast("N=> "+documentFile.getType());

                }

and isEditableFileType method goes like this
`
private boolean isEditableFileType(@NonNull String fileType){

    return fileType.equals("application/octet-stream")

        || fileType.equals("text/html")

        || fileType.equals("text/css")

        || fileType.equals("text/plain")

        || fileType.equals("text/xml");

        //|| fileType.equals("h");

}

`

the problem is with application/octet-stream

some files with or without extension is with that type but some extension like .jar,.tar.gz are the same type but those are not editable as text content


问:
Is "prettyhtml" the same thing as "prettier" in VS Code?
I have a Vue project. When I go into my VS Code settings, I see an extension called "Vetur". I believe Vetur is what takes care of all code formatting for me. Under settings, when I click into Vetur, it gives me a list of different formatters for JS, CSS, HTML, etc. as they appear within Vue files. Here's a picture:

Picture of Vetur settings

The default formatter set for most things is something called prettier.

However, when I go into settings (which takes me to a file called settings.json), I don't see the word "prettier" there at all! Instead, I see a bunch of settings for other formatters that weren't selected (such as js-beautify-html), and the closest thing to the word "prettier" is the word "prettyhtml".

In the dropdown list for HTML, I do see an option for "prettyhtml", but it warns me that it's deprecated. Here's a screenshot: prettyhtml shown as a dropdown option but says it's deprecated.

When I go into this settings.json, I see this part:

```<code>    "vetur.format.defaultFormatterOptions": {

        "js-beautify-html": {
            "wrap_attributes": "force-expand-multiline"
        },
        "prettyhtml": {
            "printWidth": 100,
            "singleQuote": false,
            "wrapAttributes": false,
            "sortAttributes": false
        }
    }
</code>```

Is "prettyhtml" the same thing as "prettier"?

If not, then why doesn't anything appear in settings.json for "prettier"? There are exactly zero string matches for the word "prettier" in settings.json.

This is all very confusing! Thanks.

Body:
I have a Vue project. When I go into my VS Code settings, I see an extension called "Vetur". I believe Vetur is what takes care of all code formatting for me. Under settings, when I click into Vetur, it gives me a list of different formatters for JS, CSS, HTML, etc. as they appear within Vue files. Here's a picture:

Picture of Vetur settings

The default formatter set for most things is something called prettier.

However, when I go into settings (which takes me to a file called settings.json), I don't see the word "prettier" there at all! Instead, I see a bunch of settings for other formatters that weren't selected (such as js-beautify-html), and the closest thing to the word "prettier" is the word "prettyhtml".

In the dropdown list for HTML, I do see an option for "prettyhtml", but it warns me that it's deprecated. Here's a screenshot: prettyhtml shown as a dropdown option but says it's deprecated.

When I go into this settings.json, I see this part:

    "vetur.format.defaultFormatterOptions": {

        "js-beautify-html": {
            "wrap_attributes": "force-expand-multiline"
        },
        "prettyhtml": {
            "printWidth": 100,
            "singleQuote": false,
            "wrapAttributes": false,
            "sortAttributes": false
        }
    }

Is "prettyhtml" the same thing as "prettier"?

If not, then why doesn't anything appear in settings.json for "prettier"? There are exactly zero string matches for the word "prettier" in settings.json.

This is all very confusing! Thanks.


问:
Adjust ggplot starting point
ggplot tick problem

Print figures using ggplot2 and grid.arrange.
Depending on the number of characters in ylabel, the starting point of the graph is different.
Code needs to be modified to specify the same starting point

And to set the starting point of the x-axis in the vector data

Title: Adjust ggplot starting point