问:
How do I update data using SheetJS library while preserving cell styles?
I want to update data in an (existing) Excel file (some cells) using SheetJS library.
I'm trying something like this:

  import * as XLSX from 'xlsx';

  const data = [['one', 'two']]

  const wb = XLSX.readFile(filePath);
  const ws = wb.Sheets[wb.SheetNames[0]];
  XLSX.utils.sheet_add_aoa(ws, data);
  XLSX.writeFile(wb, filePath, { bookType:"xlsx" });
```

This works, but the problem is that it also resets the style for the target cells. I would like to keep all styles like they were before the update (i.e. column width, color, whatever). How can I achieve this, i.e. which function should I use to update the values only?

Body:
I want to update data in an (existing) Excel file (some cells) using SheetJS library.
I'm trying something like this:

  import * as XLSX from 'xlsx';

  const data = [['one', 'two']]

  const wb = XLSX.readFile(filePath);
  const ws = wb.Sheets[wb.SheetNames[0]];
  XLSX.utils.sheet_add_aoa(ws, data);
  XLSX.writeFile(wb, filePath, { bookType:"xlsx" });

This works, but the problem is that it also resets the style for the target cells. I would like to keep all styles like they were before the update (i.e. column width, color, whatever). How can I achieve this, i.e. which function should I use to update the values only?


来源: stackexchange

问:
Text corrupts when saving ggplot object to pdf
I create a plot from data in R using ggplot2. When saving the ggplot object to a png file, the plot looks exactly as it should (see picture). When saving the same ggplot object to a pdf, all text corrupts. Anyone knows a solution?

Results of png/pdf

```<code> data <- data.frame(matrix(nrow=50, ncol=3)) # Generate sample data
 colnames(data) <- c("LUT", "Climate", "parameter")
 data$LUT <- c("EM", "EP", "IM", "OF", "CF")
 data$Climate <- rep(c("amb", "fut"), each=5)
 for(i in 1:25){
 data$parameter[data$Climate=="amb"][i] <- sample(10:110,1)
 data$parameter[data$Climate=="fut"][i] <- sample(0:100,1)
 }

 data

 test_figure <- ggplot(aes(y=parameter, x=LUT, color=Climate), data=data)+ # Generate ggplot object
 geom_point()+
 scale_colour_manual(values=c("amb" = "#007089", "fut" = "#60c3d9"))+
 stat_summary(
 geom = "point",
 fun.y = "mean",
size = 5,
shape = 17)+
stat_summary(fun.data = mean_se, geom = "errorbar")+ # add errorbar
ylab("test_lab")+
theme(text = element_text(size = 22),
plot.title = element_text(size=25),

axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18),
axis.title.y=element_text(size=17))

ggsave("test.figure.png", test_figure) # Save as png / pdf
pdf("test_figure.pdf")
print(test_figure)
dev.off()

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I create a plot from data in R using ggplot2. When saving the ggplot object to a png file, the plot looks exactly as it should (see picture). When saving the same ggplot object to a pdf, all text corrupts. Anyone knows a solution?

Results of png/pdf

 data <- data.frame(matrix(nrow=50, ncol=3)) # Generate sample data
 colnames(data) <- c("LUT", "Climate", "parameter")
 data$LUT <- c("EM", "EP", "IM", "OF", "CF")
 data$Climate <- rep(c("amb", "fut"), each=5)
 for(i in 1:25){
 data$parameter[data$Climate=="amb"][i] <- sample(10:110,1)
 data$parameter[data$Climate=="fut"][i] <- sample(0:100,1)
 }

 data

 test_figure <- ggplot(aes(y=parameter, x=LUT, color=Climate), data=data)+ # Generate ggplot object
 geom_point()+
 scale_colour_manual(values=c("amb" = "#007089", "fut" = "#60c3d9"))+
 stat_summary(
 geom = "point",
 fun.y = "mean",
size = 5,
shape = 17)+
stat_summary(fun.data = mean_se, geom = "errorbar")+ # add errorbar
ylab("test_lab")+
theme(text = element_text(size = 22),
plot.title = element_text(size=25),

axis.text.y = element_text(size=18),
axis.text.x = element_text(size=18),
axis.title.y=element_text(size=17))

ggsave("test.figure.png", test_figure) # Save as png / pdf
pdf("test_figure.pdf")
print(test_figure)
dev.off()


问:
How to do search based on different parameter along with optional option
I am creating a functionality for search where user can select the desired option and based on that it should filter the record from DB and display the response with pagination

This is my search page.
https://i.imgur.com/coO3BCJ.png

This is my entity class

@Entity
@Table(name = "userDetails")
public class UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)

private int age;
    private String manglik;
    private String maritalStatus;
    private String manglikStatus;
    private String religion;
    private String caste;
    private String location;
```
<p>and this is my Repository class...</p>
<pre class="lang-java prettyprint-override"><code>public interface UserDetailsRepository extends JpaRepository<UserDetails, Integer>, JpaSpecificationExecutor<UserDetails> {
</code>```

So, please help me how do I fetch the record and show the result to user with pagination.

I have tried with all the possibilities based on my experience but I am unable to perform search. As these all fields are optionals, so, User can select any of the field. Main issue I am getting with to get the result between specified fields only and result should be showing with pagination.

Please help me how do I make it function?

Body:
I am creating a functionality for search where user can select the desired option and based on that it should filter the record from DB and display the response with pagination

This is my search page.
https://i.imgur.com/coO3BCJ.png

This is my entity class

@Entity
@Table(name = "userDetails")
public class UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)

private int age;
    private String manglik;
    private String maritalStatus;
    private String manglikStatus;
    private String religion;
    private String caste;
    private String location;

and this is my Repository class...

public interface UserDetailsRepository extends JpaRepository<UserDetails, Integer>, JpaSpecificationExecutor<UserDetails> {

So, please help me how do I fetch the record and show the result to user with pagination.

I have tried with all the possibilities based on my experience but I am unable to perform search. As these all fields are optionals, so, User can select any of the field. Main issue I am getting with to get the result between specified fields only and result should be showing with pagination.

Please help me how do I make it function?


问:
I have added custom fields to checkout page. Can't update_post_meta with them
I have added custom fields to the checkout page.
If the cart has more then 2 items in it, then the fields populate under billing.
For every other item in the cart, 3 more fields are generated.

The problem is the I cant save them to the post meta.

The first snipped prints them on the checkout page.

```<code>add_action( 'woocommerce_after_order_notes', 'person_details' );

function person_details($checkout) {
    global $woocommerce;
$count = $woocommerce->cart->cart_contents_count;
$i = 1;
       for($k=2; $k<= $count; $k++) {
        $i++;
           print ('<h4>Моля попълнете данни за участник '.$i.'</h4>');
        woocommerce_form_field( 'cstm_full_name'.$i, array(
            'type'          => 'text',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Две имена'),
            'placeholder'   => __(''),
            'required'      =>true,
            ),
            $checkout->get_value( 'cstm_full_name'.$i ));
        echo '<div class="clear"></div>';
        woocommerce_form_field( 'cstm_egn'.$i, array(
            'type'          => 'text',
            'class'         => array('my-field-class form-row-first'),
            'label'         => __('Длъжност'),
            'placeholder'   => __(''),
            'required'      =>true,
            ),
            $checkout->get_value( 'cstm_egn'.$i ));
        echo '<div class="clear"></div>';
        woocommerce_form_field( 'cstm_address'.$i, array(
            'type'          => 'textarea',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Имейл'),
            'placeholder'   => __(''),
            'required'      =>true,
            ),
            $checkout->get_value( 'cstm_address'.$i ));
}
}
</code>```

The second should save them to the post meta:

```<code>
add_action('woocommerce_checkout_update_order_meta', 'customise_checkout_field_update_order_meta');

function customise_checkout_field_update_order_meta($order_id)
{
    global $woocommerce;
$count = $woocommerce->cart->cart_contents_count;
$i = 1;
       for($k=2; $k<= $count; $k++) {
        $i++;
    if (!empty($_POST['cstm_full_name'.$i])) {
        update_post_meta($order_id, 'Name of Attendee'.$i, sanitize_text_field($_POST['cstm_full_name'.$i]));
    }
    if (!empty($_POST['cstm_egn'.$i])) {
        update_post_meta($order_id, 'EGN of Attendee'.$i, sanitize_text_field($_POST['cstm_egn'.$i]));
    }
    if (!empty($_POST['cstm_address'.$i])) {
        update_post_meta($order_id, 'Address of Attendee'.$i, sanitize_text_field($_POST['cstm_address'.$i]));
    }
}
}
</code>```

I have no clue how to proceed. So far I have changed bits of the code, but with no result.

Body:
I have added custom fields to the checkout page.
If the cart has more then 2 items in it, then the fields populate under billing.
For every other item in the cart, 3 more fields are generated.

The problem is the I cant save them to the post meta.

The first snipped prints them on the checkout page.

add_action( 'woocommerce_after_order_notes', 'person_details' );

function person_details($checkout) {
    global $woocommerce;
$count = $woocommerce->cart->cart_contents_count;
$i = 1;
       for($k=2; $k<= $count; $k++) {
        $i++;
           print ('
Моля попълнете данни за участник '.$i.'
');
        woocommerce_form_field( 'cstm_full_name'.$i, array(
            'type'          => 'text',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Две имена'),
            'placeholder'   => __(''),
            'required'      =>true,
            ),
            $checkout->get_value( 'cstm_full_name'.$i ));
        echo '

';
        woocommerce_form_field( 'cstm_egn'.$i, array(
            'type'          => 'text',
            'class'         => array('my-field-class form-row-first'),
            'label'         => __('Длъжност'),
            'placeholder'   => __(''),
            'required'      =>true,
            ),
            $checkout->get_value( 'cstm_egn'.$i ));
        echo '

';
        woocommerce_form_field( 'cstm_address'.$i, array(
            'type'          => 'textarea',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Имейл'),
            'placeholder'   => __(''),
            'required'      =>true,
            ),
            $checkout->get_value( 'cstm_address'.$i ));
}
}

The second should save them to the post meta:

add_action('woocommerce_checkout_update_order_meta', 'customise_checkout_field_update_order_meta');

function customise_checkout_field_update_order_meta($order_id)
{
    global $woocommerce;
$count = $woocommerce->cart->cart_contents_count;
$i = 1;
       for($k=2; $k<= $count; $k++) {
        $i++;
    if (!empty($_POST['cstm_full_name'.$i])) {
        update_post_meta($order_id, 'Name of Attendee'.$i, sanitize_text_field($_POST['cstm_full_name'.$i]));
    }
    if (!empty($_POST['cstm_egn'.$i])) {
        update_post_meta($order_id, 'EGN of Attendee'.$i, sanitize_text_field($_POST['cstm_egn'.$i]));
    }
    if (!empty($_POST['cstm_address'.$i])) {
        update_post_meta($order_id, 'Address of Attendee'.$i, sanitize_text_field($_POST['cstm_address'.$i]));
    }
}
}

I have no clue how to proceed. So far I have changed bits of the code, but with no result.


问:
Listen to Postgresql Notify channel in FastApi
I am currently having a small backend using FastApi and PostgresQl. I want to add some realtime chat capabilities. I use sqlalchemy for the database interactions. I read up on Postgres Notify and Listen and it seems like exactly what I need.

But I am struggling to implement it in my application. Do you know how to listen to Postgres channels, preferably using sqlachemy and utilizing FastApi's async capabilities?

I tried to find a sqlachemy function that implements the desired behavior and I couldn't find one. I found an example with psycopg2 but I don't know how to implement it in a non blocking async manner.

Any help will be much appreciated :)


问:
How to access an image from inside the function using Tkinter and Python?
Some things went not quite how I expected.

I am currently developing a GUI via Tkinter in Python. The idea is to create an interface, which allows me to select 2 jpg or png formatted pictures from my computer, resize them and show in two separate square frames. Once it is done, there is a third frame with the third button underneath, which supposed to start an animation (sequential image transitions) with the further involvement of pictures 1 and 2. I have no problem with importing these images in frames, however, when I try to access my global image variable inside the function (which is bound to the button) in order to convert an image to the array of pixels, the compiler finds no value stored in the variable.

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
from tkinter import Canvas
from numpy import asarray
import numpy as np

window = Tk()
window.title("Image Transitions")
window.geometry("1200x800")
window.config(background="CornflowerBlue")
window.maxsize(1200, 800)

title1 = Label(window, text="Image 1", width=20)
title1.place(x=180, y=175)
title1.configure(bg="CornflowerBlue")

title2 = Label(window, text="Image 2", width=20)
title2.place(x=530, y=175)
title2.configure(bg="CornflowerBlue")

title3 = Label(window, text="Image Transitions", width=20)
title3.place(x=880, y=175)
title3.configure(bg="CornflowerBlue")

button1 = Button(window, text="Upload Image 1", width=20, command=lambda:browse_Image1())
button1.place(x=180, y=510)

button2 = Button(window, text="Upload Image 2", width=20, command=lambda:browse_Image2())
button2.place(x=530, y=510)

canvas1 = Canvas(window, width=300, height=300)
canvas1.pack()
canvas1.configure(bg="LightSkyBlue")
canvas1.place(x=100, y=200)

canvas2 = Canvas(window, width=300, height=300)
canvas2.pack()
canvas2.configure(bg="LightSkyBlue")
canvas2.place(x=450, y=200)

canvas3 = Canvas(window, width=300, height=300)
canvas3.pack()
canvas3.configure(bg="LightSkyBlue")
canvas3.place(x=800, y=200)

def browse_Image1():
    global image_first

    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img = Image.open(filename)
    img = img.resize((300, 300))
    image_first = ImageTk.PhotoImage(img)

    label = Label(window, image=image_first)
    label.pack()
    label.place(x=100, y=200)

def browse_Image2():
    global image_second
    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img2 = Image.open(filename)
    img2 = img2.resize((300, 300))
    image_second = ImageTk.PhotoImage(img2)

    label = Label(window, image=image_second)
    label.pack()
    label.place(x=450, y=200)

ImageA_Width, ImageA_Height = image_first.size
data_A_norm = asarray(image_first) / 255.0
data_B_norm = asarray(image_second) / 255.0

window.mainloop()
```

As far as I understand, in order to access an image stored in a variable I need to call this function. However, in my case it is prohibited, as the “Select file” window will be called again.

I need to somehow do both things:

Execute the command: choose and import images by pressing button.

Get access to the imported images stored in variables to perform animations.

How can I do both?

Body:
Some things went not quite how I expected.

I am currently developing a GUI via Tkinter in Python. The idea is to create an interface, which allows me to select 2 jpg or png formatted pictures from my computer, resize them and show in two separate square frames. Once it is done, there is a third frame with the third button underneath, which supposed to start an animation (sequential image transitions) with the further involvement of pictures 1 and 2. I have no problem with importing these images in frames, however, when I try to access my global image variable inside the function (which is bound to the button) in order to convert an image to the array of pixels, the compiler finds no value stored in the variable.

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
from tkinter import Canvas
from numpy import asarray
import numpy as np

window = Tk()
window.title("Image Transitions")
window.geometry("1200x800")
window.config(background="CornflowerBlue")
window.maxsize(1200, 800)

title1 = Label(window, text="Image 1", width=20)
title1.place(x=180, y=175)
title1.configure(bg="CornflowerBlue")

title2 = Label(window, text="Image 2", width=20)
title2.place(x=530, y=175)
title2.configure(bg="CornflowerBlue")

title3 = Label(window, text="Image Transitions", width=20)
title3.place(x=880, y=175)
title3.configure(bg="CornflowerBlue")

button1 = Button(window, text="Upload Image 1", width=20, command=lambda:browse_Image1())
button1.place(x=180, y=510)

button2 = Button(window, text="Upload Image 2", width=20, command=lambda:browse_Image2())
button2.place(x=530, y=510)

canvas1 = Canvas(window, width=300, height=300)
canvas1.pack()
canvas1.configure(bg="LightSkyBlue")
canvas1.place(x=100, y=200)

canvas2 = Canvas(window, width=300, height=300)
canvas2.pack()
canvas2.configure(bg="LightSkyBlue")
canvas2.place(x=450, y=200)

canvas3 = Canvas(window, width=300, height=300)
canvas3.pack()
canvas3.configure(bg="LightSkyBlue")
canvas3.place(x=800, y=200)

def browse_Image1():
    global image_first

    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img = Image.open(filename)
    img = img.resize((300, 300))
    image_first = ImageTk.PhotoImage(img)

    label = Label(window, image=image_first)
    label.pack()
    label.place(x=100, y=200)

def browse_Image2():
    global image_second
    filename = filedialog.askopenfilename(
    initialdir = "/",
    title = "Select a File",
    filetypes = (("2D - JPG", "*.jpg*"), ("2D - PNG", "*.png*"), ("all files", "*.*")))

    img2 = Image.open(filename)
    img2 = img2.resize((300, 300))
    image_second = ImageTk.PhotoImage(img2)

    label = Label(window, image=image_second)
    label.pack()
    label.place(x=450, y=200)

ImageA_Width, ImageA_Height = image_first.size
data_A_norm = asarray(image_first) / 255.0
data_B_norm = asarray(image_second) / 255.0

window.mainloop()

As far as I understand, in order to access an image stored in a variable I need to call this function. However, in my case it is prohibited, as the “Select file” window will be called again.

I need to somehow do both things:

Execute the command: choose and import images by pressing button.

Get access to the imported images stored in variables to perform animations.

How can I do both?


问:
Can not create an organizational repository from a template with github API
I want to create an organizational repository with "internal" visibility (as it is the only way to create repositories in my org) in github but from a template.

So far I have been able to create an empty repository by doing the following: (note the option 'visibility: internal')

```<code>curl --location --request POST 'https://api.github.com/orgs/MYORGANIZATION/repos' \
--header 'Accept: application/vnd.github+json' \
--header 'Authorization: Bearer 123123' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name": "repo-by-github-api",
    "description": "This is your first repository",
    "visibility": "internal"
}'
</code>```

This returns 201.

Now when creating a repository from a template: (note that there is no 'visibility: internal' option as it is not available)

```<code>curl --location --request POST 'https://api.github.com/repos/Louis3797/awesome-readme-template/generate' \
--header 'Accept: application/vnd.github+json' \
--header 'Authorization: Bearer 123123' \
--header 'Content-Type: application/json' \
--data-raw '{
    "owner": "MYORGANIZATION",
    "name": "repo-by-github-api",
    "description": "This is your first repository"
}'
</code>```

This returns 403 forbidden with a body that contains:

```<code>{
    "message": "Forbidden",
    "errors": [
        {
            ...
            "message": "MyGithubAccount123 cannot create a repository for MYORGANIZATION.",
            ...
}
</code>```

The API token I'm using has all the permissions. I'm also following this documentation: https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#create-a-repository-using-a-template

What am I doing wrong? Is this a bug, as there is no way to configure the visibility option?

Body:
I want to create an organizational repository with "internal" visibility (as it is the only way to create repositories in my org) in github but from a template.

So far I have been able to create an empty repository by doing the following: (note the option 'visibility: internal')

curl --location --request POST 'https://api.github.com/orgs/MYORGANIZATION/repos' \
--header 'Accept: application/vnd.github+json' \
--header 'Authorization: Bearer 123123' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name": "repo-by-github-api",
    "description": "This is your first repository",
    "visibility": "internal"
}'

This returns 201.

Now when creating a repository from a template: (note that there is no 'visibility: internal' option as it is not available)

curl --location --request POST 'https://api.github.com/repos/Louis3797/awesome-readme-template/generate' \
--header 'Accept: application/vnd.github+json' \
--header 'Authorization: Bearer 123123' \
--header 'Content-Type: application/json' \
--data-raw '{
    "owner": "MYORGANIZATION",
    "name": "repo-by-github-api",
    "description": "This is your first repository"
}'

This returns 403 forbidden with a body that contains:

{
    "message": "Forbidden",
    "errors": [
        {
            ...
            "message": "MyGithubAccount123 cannot create a repository for MYORGANIZATION.",
            ...
}

The API token I'm using has all the permissions. I'm also following this documentation: https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#create-a-repository-using-a-template

What am I doing wrong? Is this a bug, as there is no way to configure the visibility option?


问:
Detox 18.16.0 not running with Cucumber - giving an error ChildProcessError: Command failed: /usr/bin/xcrun
I am attempting to build a detox/cucumber POC and am following a course.

The course is based using detox "18.16.0" and the app I am testing against is a simple react native app.

I can build the App on IOS and Android both from Terminal and on Xcode and Android Studio but when I run

```<code>npm run detox:e2e:ios-debug
</code>```

I get the following error.

```<code>    npm run detox:e2e:ios-debug

> pqaa_detox@0.0.1 detox:e2e:ios-debug
> DETOX_CONFIGURATION=ios.sim.debug npx cucumber-js

This Node.js version (v19.3.0) has not been tested with this version of Cucumber; it should work normally, but please raise an issue if you see anything unexpected.
detox[54382] INFO:  [DetoxServer.js] server listening on localhost:61972...
detox[54382] ERROR: [exec.js/EXEC_FAIL, #4] "/usr/bin/xcrun simctl terminate 91B7DFFE-A3B6-461B-A93F-06CF8A1A560B org.reactjs.native.example.pqaa-detox" failed with code = 3, stdout and stderr:

detox[54382] ERROR: [exec.js/EXEC_FAIL, #4]
detox[54382] ERROR: [exec.js/EXEC_FAIL, #4] An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=3):
The operation couldn’t be completed. found nothing to terminate
found nothing to terminate

F-

Failures:

1) Scenario: I execute Detox test # e2e/features/onboarding/initialtest.feature:3
   ✖ Before # e2e/features/step_definitions/Hooks.js:9
       ChildProcessError: Command failed: /usr/bin/xcrun simctl terminate 91B7DFFE-A3B6-461B-A93F-06CF8A1A560B org.reactjs.native.example.pqaa-detox
       An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=3):
       The operation couldn’t be completed. found nothing to terminate
       found nothing to terminate
        `/usr/bin/xcrun simctl terminate 91B7DFFE-A3B6-461B-A93F-06CF8A1A560B org.reactjs.native.example.pqaa-detox` (exited with error code 3)
           at callback (/Users/richardcariven/Repos/Detox_Project/node_modules/child-process-promise/lib/index.js:33:27)
           at ChildProcess.exithandler (node:child_process:427:5)
           at ChildProcess.emit (node:events:513:28)
           at maybeClose (node:internal/child_process:1098:16)
           at Socket.<anonymous> (node:internal/child_process:456:11)
           at Socket.emit (node:events:513:28)
           at Pipe.<anonymous> (node:net:305:12)
   - Given I start Detox # e2e/features/step_definitions/OnboardingSteps.js:5

1 scenario (1 failed)
1 step (1 skipped)
0m05.269s (executing steps: 0m01.419s)
┌──────────────────────────────────────────────────────────────────────────────┐
│ Share your Cucumber Report with your team at https://reports.cucumber.io     │
│                                                                              │
│ Command line option:    --publish                                            │
│ Environment variable:   CUCUMBER_PUBLISH_ENABLED=true                        │
│                                                                              │
│ More information at https://cucumber.io/docs/cucumber/environment-variables/ │
│                                                                              │
│ To disable this message, add this to your ./cucumber.js:                     │
│ module.exports = { default: '--publish-quiet' }                              │
└──────────────────────────────────────────────────────────────────────────────┘
</code>```

package.json

```<code>    {
  "name": "pqaa_detox",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android:build": "react-native run-android",
    "ios:build": "react-native run-ios",
    "start": "react-native start",
    "detox:build:ios-debug": "detox build --configuration ios.sim.debug",
    "detox:e2e:ios-debug": "DETOX_CONFIGURATION=ios.sim.debug npx cucumber-js",
    "detox:build:android-debug": "detox build --configuration android.emu.debug",
    "detox:e2e:android-debug": "DETOX_CONFIGURATION=android.emu.debug npx cucumber-js"
  },
  "dependencies": {
    "@react-native-community/async-storage": "1.12.1",
    "@react-native-community/datetimepicker": "3.5.2",
    "@react-native-community/masked-view": "0.1.11",
    "@react-native-picker/picker": "1.16.7",
    "moment": "2.29.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-native": "0.63.4",
    "react-native-calendars": "1.1266.0",
    "react-native-date-picker": "4.0.0",
    "react-native-elements": "3.4.2",
    "react-native-gesture-handler": "1.10.3",
    "react-native-maps": "0.29.3",
    "react-native-reanimated": "1.13.0",
    "react-native-safe-area-context": "3.3.2",
    "react-native-screens": "3.4.0",
    "react-native-splash-screen": "3.2.0",
    "react-native-vector-icons": "8.1.0",
    "react-navigation": "4.4.4",
    "react-navigation-stack": "2.10.4",
    "react-navigation-tabs": "2.11.1"
  },
  "devDependencies": {
    "@babel/core": "7.15.5",
    "@babel/register": "^7.18.9",
    "@babel/runtime": "7.15.4",
    "@cucumber/cucumber": "^8.9.1",
    "@react-native-community/eslint-config": "3.0.1",
    "babel-jest": "27.1.0",
    "detox": "18.16.0",
    "eslint": "7.32.0",
    "jest": "27.1.0",
    "metro-react-native-babel-preset": "0.66.2",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

Hooks

```<code>    import { BeforeAll, Before, AfterAll } from "@cucumber/cucumber";
import { init, cleanup } from "detox";
import { detox as config } from "../../../package.json";

BeforeAll({ timeout: 60 * 1000 }, async () => {
  await init(config);
});

Before(async () => {
  await device.launchApp({ newInstance: true });
});

AfterAll(async () => {
  await cleanup();
});
</code>```

Steps

```<code>import { Given, setDefaultTimeout } from "@cucumber/cucumber";

setDefaultTimeout(120 * 1000);

Given('I start Detox', {timeout: 60 * 1000}, async () => {
  console.log('Test Started');
});
</code>```

cucumber.js

```<code>    const arguments = [
    '--require-module @babel/register',
    'e2e/features/*/*.feature'
].join(' ');

module.exports = {
    default: arguments
}
</code>```

.detoxrc.js

```<code>module.exports = {
    "configurations": {
        "ios.sim.debug": {
          "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/pqaa_detox.app",
          "build": "xcodebuild -workspace ios/pqaa_detox.xcworkspace -scheme pqaa_detox -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
          "type": "ios.simulator",
          "device": {
            "type": "iPhone 12 Pro"
          }
        },
        "android.emu.debug": {
          "binaryPath": "android/app/build/outputs/apk/debug/app-debug.apk",
          "build": "cd android && ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug && cd .. ",
          "type": "android.emulator",
          "device": {
            "avdName": "Nexus_6_detox_inspect ",
          }
        }
    }
}
</code>```

Body:
I am attempting to build a detox/cucumber POC and am following a course.

The course is based using detox "18.16.0" and the app I am testing against is a simple react native app.

I can build the App on IOS and Android both from Terminal and on Xcode and Android Studio but when I run

npm run detox:e2e:ios-debug

I get the following error.

    npm run detox:e2e:ios-debug

> pqaa_detox@0.0.1 detox:e2e:ios-debug
> DETOX_CONFIGURATION=ios.sim.debug npx cucumber-js

This Node.js version (v19.3.0) has not been tested with this version of Cucumber; it should work normally, but please raise an issue if you see anything unexpected.
detox[54382] INFO:  [DetoxServer.js] server listening on localhost:61972...
detox[54382] ERROR: [exec.js/EXEC_FAIL, #4] "/usr/bin/xcrun simctl terminate 91B7DFFE-A3B6-461B-A93F-06CF8A1A560B org.reactjs.native.example.pqaa-detox" failed with code = 3, stdout and stderr:

detox[54382] ERROR: [exec.js/EXEC_FAIL, #4]
detox[54382] ERROR: [exec.js/EXEC_FAIL, #4] An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=3):
The operation couldn’t be completed. found nothing to terminate
found nothing to terminate

F-

Failures:

1) Scenario: I execute Detox test # e2e/features/onboarding/initialtest.feature:3
   ✖ Before # e2e/features/step_definitions/Hooks.js:9
       ChildProcessError: Command failed: /usr/bin/xcrun simctl terminate 91B7DFFE-A3B6-461B-A93F-06CF8A1A560B org.reactjs.native.example.pqaa-detox
       An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=3):
       The operation couldn’t be completed. found nothing to terminate
       found nothing to terminate
        `/usr/bin/xcrun simctl terminate 91B7DFFE-A3B6-461B-A93F-06CF8A1A560B org.reactjs.native.example.pqaa-detox` (exited with error code 3)
           at callback (/Users/richardcariven/Repos/Detox_Project/node_modules/child-process-promise/lib/index.js:33:27)
           at ChildProcess.exithandler (node:child_process:427:5)
           at ChildProcess.emit (node:events:513:28)
           at maybeClose (node:internal/child_process:1098:16)
           at Socket.<anonymous> (node:internal/child_process:456:11)
           at Socket.emit (node:events:513:28)
           at Pipe.<anonymous> (node:net:305:12)
   - Given I start Detox # e2e/features/step_definitions/OnboardingSteps.js:5

1 scenario (1 failed)
1 step (1 skipped)
0m05.269s (executing steps: 0m01.419s)
┌──────────────────────────────────────────────────────────────────────────────┐
│ Share your Cucumber Report with your team at https://reports.cucumber.io     │
│                                                                              │
│ Command line option:    --publish                                            │
│ Environment variable:   CUCUMBER_PUBLISH_ENABLED=true                        │
│                                                                              │
│ More information at https://cucumber.io/docs/cucumber/environment-variables/ │
│                                                                              │
│ To disable this message, add this to your ./cucumber.js:                     │
│ module.exports = { default: '--publish-quiet' }                              │
└──────────────────────────────────────────────────────────────────────────────┘

package.json

    {
  "name": "pqaa_detox",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android:build": "react-native run-android",
    "ios:build": "react-native run-ios",
    "start": "react-native start",
    "detox:build:ios-debug": "detox build --configuration ios.sim.debug",
    "detox:e2e:ios-debug": "DETOX_CONFIGURATION=ios.sim.debug npx cucumber-js",
    "detox:build:android-debug": "detox build --configuration android.emu.debug",
    "detox:e2e:android-debug": "DETOX_CONFIGURATION=android.emu.debug npx cucumber-js"
  },
  "dependencies": {
    "@react-native-community/async-storage": "1.12.1",
    "@react-native-community/datetimepicker": "3.5.2",
    "@react-native-community/masked-view": "0.1.11",
    "@react-native-picker/picker": "1.16.7",
    "moment": "2.29.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-native": "0.63.4",
    "react-native-calendars": "1.1266.0",
    "react-native-date-picker": "4.0.0",
    "react-native-elements": "3.4.2",
    "react-native-gesture-handler": "1.10.3",
    "react-native-maps": "0.29.3",
    "react-native-reanimated": "1.13.0",
    "react-native-safe-area-context": "3.3.2",
    "react-native-screens": "3.4.0",
    "react-native-splash-screen": "3.2.0",
    "react-native-vector-icons": "8.1.0",
    "react-navigation": "4.4.4",
    "react-navigation-stack": "2.10.4",
    "react-navigation-tabs": "2.11.1"
  },
  "devDependencies": {
    "@babel/core": "7.15.5",
    "@babel/register": "^7.18.9",
    "@babel/runtime": "7.15.4",
    "@cucumber/cucumber": "^8.9.1",
    "@react-native-community/eslint-config": "3.0.1",
    "babel-jest": "27.1.0",
    "detox": "18.16.0",
    "eslint": "7.32.0",
    "jest": "27.1.0",
    "metro-react-native-babel-preset": "0.66.2",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}

Hooks

    import { BeforeAll, Before, AfterAll } from "@cucumber/cucumber";
import { init, cleanup } from "detox";
import { detox as config } from "../../../package.json";

BeforeAll({ timeout: 60 * 1000 }, async () => {
  await init(config);
});

Before(async () => {
  await device.launchApp({ newInstance: true });
});

AfterAll(async () => {
  await cleanup();
});

Steps

import { Given, setDefaultTimeout } from "@cucumber/cucumber";

setDefaultTimeout(120 * 1000);

Given('I start Detox', {timeout: 60 * 1000}, async () => {
  console.log('Test Started');
});

cucumber.js

    const arguments = [
    '--require-module @babel/register',
    'e2e/features/*/*.feature'
].join(' ');

module.exports = {
    default: arguments
}

.detoxrc.js

module.exports = {
    "configurations": {
        "ios.sim.debug": {
          "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/pqaa_detox.app",
          "build": "xcodebuild -workspace ios/pqaa_detox.xcworkspace -scheme pqaa_detox -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
          "type": "ios.simulator",
          "device": {
            "type": "iPhone 12 Pro"
          }
        },
        "android.emu.debug": {
          "binaryPath": "android/app/build/outputs/apk/debug/app-debug.apk",
          "build": "cd android && ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug && cd .. ",
          "type": "android.emulator",
          "device": {
            "avdName": "Nexus_6_detox_inspect ",
          }
        }
    }
}


问:
How to replace a value in a column based of the criteria of another column?
I accidentally changed a value that now shows the same value as another variable but I just need to change it back to what it was. Using SQL Server.

I need to change the value 'Cell B' that is associated with the value 'Cell 3' how do i achieve this? I tried using a case statement but I don't understand how to use it without changing all the values that contain 'Cell B'. Hope this make sense, sorry I'm new with SQL.

Column A
Column B

Cell 1
Cell A

Cell 2
Cell B

Cell 3
Cell B

Cell 4
Cell D


问:
Insert a div in specific position - php, joomla
The issue is the following. This code loads items and displays them on the page. Now I want to place a specific div tag after the first item in the second position and only on the start page and only once. I have solved the home page problem. But unfortunately I can't get it to appear once at the second position. How can I do that? Thank you very much.

Original Code:
`

```<code>  <?php
                    $i = 0;
                    $s = 0;
                    $t = count($items);
                    foreach ($items as $item) : ?>
                        <?php if ($i % $cols == 0): /* start new row */ ?>
                            <div class="row-articles equal-height">
                        <?php endif ?>
                        <div class="col col-xs-12 col-sm-<?php echo $col_width ?> magazine-item">
                            <?php echo JATemplateHelper::render($item, 'joomla.content.intro', array('item' => $item, 'params' => $aparams)); ?>

                        </div>
                        <?php if (++$i % $cols == 0 || $i == $t): /* close row */ ?>
                            </div>
                        <?php endif ?>
                    <?php endforeach; ?>
</code>```

`

Code with specific div tag:
`

```<code>  <?php
                    $i = 0;
                    $s = 0;
                    $t = count($items);
                    foreach ($items as $item) : ?>
                        <?php if ($i % $cols == 0): /* start new row */ ?>
                            <div class="row-articles equal-height">
                        <?php endif ?>
                        <div class="col col-xs-12 col-sm-<?php echo $col_width ?> magazine-item">
                            <?php echo JATemplateHelper::render($item, 'joomla.content.intro', array('item' => $item, 'params' => $aparams)); ?>
                            <?php
                            $app = JFactory::getApplication();
                            $menu = $app->getMenu();
                            if ($menu->getActive() == $menu->getDefault()) {
                                echo '<div id="nativendo-homepage-' . ++$s . '"></div>' ;}?>
                        </div>
                        <?php if (++$i % $cols == 0 || $i == $t): /* close row */ ?>
                            </div>
                        <?php endif ?>
                    <?php endforeach; ?>
</code>```

`

what i tried:

`

```<code>$i = 0;
                    $s = 0;
                    $app = JFactory::getApplication();
                    $menu = $app->getMenu();
                    $t = count($items);
                    foreach ($items as $item) : ?>
                        <?php if ($i % $cols == 0): /* start new row */ ?>
                            <div class="row-articles equal-height">
                        <?php endif ?>
                        <div class="col col-xs-12 col-sm-<?php echo $col_width ?> magazine-item">
                            <?php echo JATemplateHelper::render($item, 'joomla.content.intro', array('item' => $item, 'params' => $aparams));?>
                        </div>

                      <?php
                            $k = count(array($item));
                            if ($menu->getActive() == $menu->getDefault() && $i == 2):
                                echo '<div class="col col-xs-12 col-sm-' . $col_width . ' magazine-item"><div id="nativendo-homepage-' . ++$s . $k . '"></div></div>'  ; endif ?>

                        <?php if (++$i % $cols == 0 || $i == $t): /* close row */ ?>
                            </div>
                        <?php endif ?>
                    <?php endforeach; ?>
</code>```

`

Body:
The issue is the following. This code loads items and displays them on the page. Now I want to place a specific div tag after the first item in the second position and only on the start page and only once. I have solved the home page problem. But unfortunately I can't get it to appear once at the second position. How can I do that? Thank you very much.

Original Code:
`

  <?php
                    $i = 0;
                    $s = 0;
                    $t = count($items);
                    foreach ($items as $item) : ?>
                        <?php if ($i % $cols == 0): /* start new row */ ?>

                        <?php endif ?>
                        <div class="col col-xs-12 col-sm-<?php echo $col_width ?> magazine-item">
                            <?php echo JATemplateHelper::render($item, 'joomla.content.intro', array('item' => $item, 'params' => $aparams)); ?>

                        <?php if (++$i % $cols == 0 || $i == $t): /* close row */ ?>

                        <?php endif ?>
                    <?php endforeach; ?>

`

Code with specific div tag:
`

  <?php
                    $i = 0;
                    $s = 0;
                    $t = count($items);
                    foreach ($items as $item) : ?>
                        <?php if ($i % $cols == 0): /* start new row */ ?>

                        <?php endif ?>
                        <div class="col col-xs-12 col-sm-<?php echo $col_width ?> magazine-item">
                            <?php echo JATemplateHelper::render($item, 'joomla.content.intro', array('item' => $item, 'params' => $aparams)); ?>
                            <?php
                            $app = JFactory::getApplication();
                            $menu = $app->getMenu();
                            if ($menu->getActive() == $menu->getDefault()) {
                                echo '

' ;}?>

                        <?php if (++$i % $cols == 0 || $i == $t): /* close row */ ?>

                        <?php endif ?>
                    <?php endforeach; ?>

`

what i tried:

`

$i = 0;
                    $s = 0;
                    $app = JFactory::getApplication();
                    $menu = $app->getMenu();
                    $t = count($items);
                    foreach ($items as $item) : ?>
                        <?php if ($i % $cols == 0): /* start new row */ ?>

                        <?php endif ?>
                        <div class="col col-xs-12 col-sm-<?php echo $col_width ?> magazine-item">
                            <?php echo JATemplateHelper::render($item, 'joomla.content.intro', array('item' => $item, 'params' => $aparams));?>

                      <?php
                            $k = count(array($item));
                            if ($menu->getActive() == $menu->getDefault() && $i == 2):
                                echo '

'  ; endif ?>

                        <?php if (++$i % $cols == 0 || $i == $t): /* close row */ ?>

                        <?php endif ?>
                    <?php endforeach; ?>

`


问:
jquery signalR with angular 14, how to handle server events
I'm building a new version of the old angularjs app using angular 14, the backend was built using .Net MVC. I'm using jquery signalR library 2.4.3, and successfully started the connection with the SignalR. And now I want to know how to receive the server events.</p>
```<code>createHubConnection(user: any) {
    if (user.line) {
      $.connection.hub.url = this.hubUrl;
      $.connection.hub.qs = {
        bearer_token: access_token,
        line: user.line,
        userid: user.id,
      };

      $.connection.hub
        .start({ transport: ['webSockets'] })
        .done((res) => {
          console.log('started succesfully.');
        })
        .fail(() => {
          console.log('started with errors.');
        });
    }
  }
</code>```

Body:
I'm building a new version of the old angularjs app using angular 14, the backend was built using .Net MVC. I'm using jquery signalR library 2.4.3, and successfully started the connection with the SignalR. And now I want to know how to receive the server events.

createHubConnection(user: any) {
    if (user.line) {
      $.connection.hub.url = this.hubUrl;
      $.connection.hub.qs = {
        bearer_token: access_token,
        line: user.line,
        userid: user.id,
      };

      $.connection.hub
        .start({ transport: ['webSockets'] })
        .done((res) => {
          console.log('started succesfully.');
        })
        .fail(() => {
          console.log('started with errors.');
        });
    }
  }


问:
ytchannel.publishedvideotitles = ("c++ for beginners 1", "Html & css video 1", "c++ oop video 1"); its giving error no match for 'operator='
on that line, the compiler is stating the problem no match for 'operator=' and there is no clue  why

I just wanted to output a list of ("c++ for beginners 1", "Html & css video 1", "c++ oop video 1");


问:
How to have a minimum amount of delay in each navigation's completion in React Router?
Consider the code below:

```<code>function Root()
{
   const navigation = useNavigation();

   return <>
      <SideBar />
      {navigation.state === 'loading'
      ? (
         <div className="overlay"></div>
      )
      : (
         <div className="main">
            <Outlet />
         </div>
      )}
   </>
}
</code>```

My goal here is very simple: when the new page's data is loading, an overlay div is shown on the page until the loading completes.

Now the problem that I am facing is as follows: since the different pages of my SPA are just hardcoded pieces of text, not obtaining any information from the backend at all, there is absolutely zero latency in the navigation. This is good but the problem is that on such zero latency navigation, I get a blink overlay effect, which is undesirable.

What I want instead is to have a minimum delay for each navigation. That is, if the navigation actually completes in almost 0s, I'd still like to get the loading overlay to display for 500ms.

And if the navigation actually completes in, let's say, 3s, I'd like to get the loading overlay to display for 3s.

How can I do this?

Body:
Consider the code below:

function Root()
{
   const navigation = useNavigation();

   return <>
      <SideBar />
      {navigation.state === 'loading'
      ? (

      )
      : (

            <Outlet />

      )}
   </>
}

My goal here is very simple: when the new page's data is loading, an overlay div is shown on the page until the loading completes.

Now the problem that I am facing is as follows: since the different pages of my SPA are just hardcoded pieces of text, not obtaining any information from the backend at all, there is absolutely zero latency in the navigation. This is good but the problem is that on such zero latency navigation, I get a blink overlay effect, which is undesirable.

What I want instead is to have a minimum delay for each navigation. That is, if the navigation actually completes in almost 0s, I'd still like to get the loading overlay to display for 500ms.

And if the navigation actually completes in, let's say, 3s, I'd like to get the loading overlay to display for 3s.

How can I do this?


问:
Why does TDisplay.Index differ from the Windows Index?
I want to list the displays on a system in the same sequence as they are indexed on Windows Settings.

I have two monitors attached to my system, but in Delphi the Screen.Displays array appears to be in the wrong sequence E.G. With two horizontally positioned displays, Display Index 0 relates to the rightmost display which is listed as display 2 in Windows Settings. Likewise, Display Index 1 relates to the leftmost display which is listed as display 1 in Windows Settings. How can I be certain to get the Indexes in the same order as they are listed within the operating system (PC and Mac)?


问:
How to implement $\delta$ shift parameter in categorical variable for multiple imputation sensitivity analysis?
Suppose I was given a data as the following.

```<code>id1=rep(1:10,2)
trt=c(rep(1,10),rep(0,10))
outcome=rnorm(20)
set.seed(1005)
missing=c()
for(i in outcome){
  if(rbinom(1,1,0.8*abs(i/max(abs(outcome))))==1){
    missing=c(missing,which(outcome==i))
  }
}
missing
trt[missing]=NA
dat=data.frame(id=id1,trt=as.factor(trt),outcome=outcome)
a1=mice::mice(dat,method=c('','logreg',''))
</code>```

I can use mice to impute the data first and then conduct analysis on a1 where I assume the outcome and id predicts trt by logistic regression. In fact, only outcome predicts trt here. a1$formulas$trt will access the formula for imputation. I want to modify the formula here so that there is a constant offset.

```<code>forms_a1=a1$formulas
forms_a1$trt=as.formula(trt~outcome+offset(2))

mice::mice(dat,method=c('','logreg',''),formulas = forms_a1)
</code>```

However, mice gives the following output.

```<code>iter imp variable
  1   1  trtError in model.frame.default(formula, data = data, na.action = na.pass) :
  variable lengths differ (found for 'offset(2)')
</code>```

$Q1:$ How do I offset intercept here? I think I could add an extra column as variable to offset and modify formula and predictormatrix. The $\delta$ shift was implemented here(https://stefvanbuuren.name/fimd/sec-sensitivity.html) for continuous variable case. However, it seems that this may change estimated coefficients.

$Q2:$ If I am interested in offsetting a slope say by 10*id in above formula, how would I do so?

Body:
Suppose I was given a data as the following.

id1=rep(1:10,2)
trt=c(rep(1,10),rep(0,10))
outcome=rnorm(20)
set.seed(1005)
missing=c()
for(i in outcome){
  if(rbinom(1,1,0.8*abs(i/max(abs(outcome))))==1){
    missing=c(missing,which(outcome==i))
  }
}
missing
trt[missing]=NA
dat=data.frame(id=id1,trt=as.factor(trt),outcome=outcome)
a1=mice::mice(dat,method=c('','logreg',''))

I can use mice to impute the data first and then conduct analysis on a1 where I assume the outcome and id predicts trt by logistic regression. In fact, only outcome predicts trt here. a1$formulas$trt will access the formula for imputation. I want to modify the formula here so that there is a constant offset.

forms_a1=a1$formulas
forms_a1$trt=as.formula(trt~outcome+offset(2))

mice::mice(dat,method=c('','logreg',''),formulas = forms_a1)

However, mice gives the following output.

iter imp variable
  1   1  trtError in model.frame.default(formula, data = data, na.action = na.pass) :
  variable lengths differ (found for 'offset(2)')

$Q1:$ How do I offset intercept here? I think I could add an extra column as variable to offset and modify formula and predictormatrix. The $\delta$ shift was implemented here(https://stefvanbuuren.name/fimd/sec-sensitivity.html) for continuous variable case. However, it seems that this may change estimated coefficients.

$Q2:$ If I am interested in offsetting a slope say by 10*id in above formula, how would I do so?


问:
How can I use a struct type as the dictionary key type when serializing a Dictionary with Protobuf?
I have the following declaration for a class:

    [Serializable]
    [ProtoContract]
    public class TheClass : TheBaseClass // Not the real names!
    {
        public TheClass(Guid operationId, Dictionary<MyStruct, int> expectedNumbers)
        {
            // Initializing inherited properties.
            this.OperationId = operationId;
            this.ExpectedNumbers = expectedNumbers;
        }

        [MessagePackMember(10)]
        [ProtoMember(10)]
        public Dictionary<MyStruct, int> ExpectedNumbers { get; set; } =
            new Dictionary<MyStruct, int>();
    }
```

MyStruct is a struct type, and it also has decorations for ProtoBuf to (de)serialize it.

It looks like ExpectedNumbers is not being (de)serialized correctly, as I've seen some NullReferenceExceptions being thrown while iterating over this dictionary, specifically when retrieving the Key of the dictionary.

I have two questions now:

Can complex-type Dictionaries be (de)serialized using Protobuf?

What is wrong with the decoration for ExpectedNumbers?

Thank you!

Body:
I have the following declaration for a class:

    [Serializable]
    [ProtoContract]
    public class TheClass : TheBaseClass // Not the real names!
    {
        public TheClass(Guid operationId, Dictionary<MyStruct, int> expectedNumbers)
        {
            // Initializing inherited properties.
            this.OperationId = operationId;
            this.ExpectedNumbers = expectedNumbers;
        }

        [MessagePackMember(10)]
        [ProtoMember(10)]
        public Dictionary<MyStruct, int> ExpectedNumbers { get; set; } =
            new Dictionary<MyStruct, int>();
    }

MyStruct is a struct type, and it also has decorations for ProtoBuf to (de)serialize it.

It looks like ExpectedNumbers is not being (de)serialized correctly, as I've seen some NullReferenceExceptions being thrown while iterating over this dictionary, specifically when retrieving the Key of the dictionary.

I have two questions now:

Can complex-type Dictionaries be (de)serialized using Protobuf?

What is wrong with the decoration for ExpectedNumbers?

Thank you!


问:
Setting up a different encryption key for each record of a model in a Laravel 9 website

Introduction

For a website I'm working on, I will be storing confidential information that I need encrypted.

The way Laravel currently handles things, they encrypt each record with the same APP_KEY that's stored in the .env by default. I think I should be able to take that same APP_KEY and decrypt all the information in my production database as long as I have access to the production .env.

If so, I don't think that's a proper away to handle security for my case. Let's say I hire an admin for my production site and they turn out to be malicious. All they need to do to get access to all the users' sensitive details is take that APP_KEY and run the decryption.

If that's the case, I would rather have it work like this:

The user creates a record that has a "secret" field

A random string is generated to encrypt the data passed to the "secret" field and is then given to the user

If the user wants to access the data in the "secret" field, they have to use the key given to them; I nor anyone else should be able to decrypt that field without knowing the key given to the user

For my specific case, a client program will handle accessing the site's API and storing the encryption key and other details safely, so the user doesn't have to think about this.

My questions are the following:

Is the current encryption scheme Laravel uses safe from malicious admins?

If not, how would I go about best implementing the latter scheme?

Are there vulnerabilities with the latter schema as well, and if so, how can I improve it?

What I've Done

I've looked at the docs on this issue. I've also looked into the Model::encryptUsing feature, which allows for custom encryption.

I think I can implement the above if, when running the action that creates the record, I use Model::encryptUsing, but I haven't tested it yet.

If it ends up working, I will post the answer here.


问:
Unable to import fiftyone in sagemaker jupyter notebook
I am using python version 3.7.12 in sagemaker jupyter notebook.

I could do a !pip install fiftyone in the notebook but when I am trying to import fiftyone as fo it is giving me below error:

ConnectionError: Could not connect to 'mongod'

I have gone through its github repository but couldn't find a way to resolve this issue. And I tried implementing some of the answers provided for fiftyone's installation in Linux but it didn't work either.


问:
Pandas dataFrame.style.highlight_max() and .highlight_min() for multiindex dataset
For the following dataset which has multi-indexes  Activity->Facility Size->Year
my goal is to apply style.highlight_max() & style.highlight_min() for Column (Employee Count) in each group individually (Large, Medium, and Small),is there a way to do it while still maintaining the same shape of the dataframe as below without separating each group apart.

```<code>                                         Facility Count  Employee Count  \
 Activity             Facility Size Year
 Computer Programming Large         2010              59            3830
                                    2011              60            3912
                                    2012              63            4111
                                    2013              66            4273
                                    2014              73            4730
                                    2015              81            5066
                                    2016              85            5347
                                    2017              86            5426
                                    2018              86            7256
                      Medium        2010             168            1418
                                    2011             179            1509
                                    2012             190            1601
                                    2013             191            1615
                                    2014             211            1779
                                    2015             228            1922
                                    2016             229            1972
                                    2017             233            2017
                                    2018             235            2640
                      Small         2010             182             431
                                    2011             185             438
                                    2012             194             459
                                    2013             202             478
                                    2014             226             535
                                    2015             226             572
                                    2016             235             604
                                    2017             243             623
                                    2018             244             687
</code>```

I have tried getting each group separately by using .groupby(level=0) but that is not what I want since it separates each group apart not as one dataframe

Thank you

Body:
For the following dataset which has multi-indexes  Activity->Facility Size->Year
my goal is to apply style.highlight_max() & style.highlight_min() for Column (Employee Count) in each group individually (Large, Medium, and Small),is there a way to do it while still maintaining the same shape of the dataframe as below without separating each group apart.

                                         Facility Count  Employee Count  \
 Activity             Facility Size Year
 Computer Programming Large         2010              59            3830
                                    2011              60            3912
                                    2012              63            4111
                                    2013              66            4273
                                    2014              73            4730
                                    2015              81            5066
                                    2016              85            5347
                                    2017              86            5426
                                    2018              86            7256
                      Medium        2010             168            1418
                                    2011             179            1509
                                    2012             190            1601
                                    2013             191            1615
                                    2014             211            1779
                                    2015             228            1922
                                    2016             229            1972
                                    2017             233            2017
                                    2018             235            2640
                      Small         2010             182             431
                                    2011             185             438
                                    2012             194             459
                                    2013             202             478
                                    2014             226             535
                                    2015             226             572
                                    2016             235             604
                                    2017             243             623
                                    2018             244             687

I have tried getting each group separately by using .groupby(level=0) but that is not what I want since it separates each group apart not as one dataframe

Thank you


问:
Converting a programme to classes (Python Turtle)
So for an assignment I have to convert a programme which we made for the previous assignment into a programme which does the same but then include classes. When the code is run it is supposed to show this(but with three turtles):

Here is the original code:

```<code>from turtle import *
import random
import sys

def setup_race(n_turtles):
    ''' Setups a race of length 320 pixels with the given number of racers '''

    # Checks function input
    if n_turtles < 2 or n_turtles > 4:
        print('setup_race: invalid n_turtles, must be 2 <= n_turtles <= 4',
              file=sys.stderr)
        return None

    # Initializes function values
    race_length = 320
    n_gaps = 8
    gap_dist = race_length/n_gaps
    speed(500)

    # Go to starting location
    penup()
    x_loc_start = -140
    goto(x_loc_start, 140)

    # Draw race lines
    for step in range(n_gaps+1):
        write(step, align='center')
        right(90)
        for num in range(8):
            penup()
            forward(10)
            pendown()
            forward(10)
        penup()
        backward(160)
        left(90)
        forward(gap_dist)
    hideturtle()

    # Create and place turtles
    colors = ['red', 'blue', 'orange', 'green']
    y_loc = [100, 70, 40, 10]
    turtles = []
    for i in range(n_turtles):
        turtles.append(Turtle())
        turtles[i].color(colors[i])
        turtles[i].shape('turtle')

        turtles[i].penup()
        turtles[i].goto(x_loc_start, y_loc[i])
        turtles[i].pendown()
        swirl(turtles[i])

    return turtles

def swirl(t):
    ''' Makes the given turtle instance swirl'''
    nb_turns = 2
    for turn in range(nb_turns):
        t.right(360/nb_turns)

def nod(t):
    ''' Makes the given turtle instance nod '''
    t.left(45)
    t.right(90)
    t.left(45)

# Extension function
def move(t):
    '''A random number is generalized(int) and used as a step to go forward for the turtle'''
    step = random.randint(1, 16)
    t.forward(step)
    return step

if __name__ == "__main__":
    setup_race(2)
</code>```

`

This is my attempt at making it in classes:
`

```<code>from turtle import *
import random

class race(Turtle):

    def __init__(self, score):
        Turtle.__init__(self)
        self.score = int(score)
        # self.race_length = 0

    def setup_race(self, n_turtles):
        ''' Setups a race of length 320 pixels with the given number of racers '''

        race_length = 320
        n_gaps = 8
        gap_dist = race_length/n_gaps
        self.speed(500)

        # Go to starting location
        self.penup()
        x_loc_start = -140
        self.goto(x_loc_start, 140)

        # Draw race lines
        for step in range(n_gaps+1):
            self.write(step, align='center')
            self.right(90)
            for num in range(8):
                self.penup()
                self.forward(10)
                self.pendown()
                self.forward(10)
            self.penup()
            self.backward(160)
            self.left(90)
            self.forward(gap_dist)
        self.hideturtle()

        # Create and place turtles
        colors = ['red', 'blue', 'orange', 'green']
        y_loc = [100, 70, 40, 10]

        # turtles = []
        for i in range(n_turtles):
            # turtles.append(self)
            self.color(colors[i])
            self.shape('turtle')

            self.penup()
            self.goto(x_loc_start, y_loc[i])
            self.pendown()
            self.swirl()
            # swirl(turtles[i])
        # self.done()
        return turtles

    def swirl(self):
        ''' Makes the given turtle instance swirl'''
        nb_turns = 2
        for turn in range(nb_turns):
            self.right(360/nb_turns)

    def nod(self):
        ''' Makes the given turtle instance nod '''
        self.left(45)
        self.right(90)
        self.left(45)

    def move(self):
        '''A random number is generalized(int) and used as a step to go forward for the turtle'''
        step = random.randint(1, 16)
        self.forward(step)
        return step

def main():
    start = race(0)
    start.setup_race(2)

if __name__ == "__main__":
    main()

</code>```

My code works up until creating and placing the turtles. There are no errors shown with this code.
Right now the code for adding the turtles in a seperate list is in comments:

```<code>turtles = []
</code>```

When I tried running that part, it didn't give me an error code either but it also didn't do anything. So there are still no turtles being created and placed at the starting line.

Body:
So for an assignment I have to convert a programme which we made for the previous assignment into a programme which does the same but then include classes. When the code is run it is supposed to show this(but with three turtles):

Here is the original code:

from turtle import *
import random
import sys

def setup_race(n_turtles):
    ''' Setups a race of length 320 pixels with the given number of racers '''

    # Checks function input
    if n_turtles < 2 or n_turtles > 4:
        print('setup_race: invalid n_turtles, must be 2 <= n_turtles <= 4',
              file=sys.stderr)
        return None

    # Initializes function values
    race_length = 320
    n_gaps = 8
    gap_dist = race_length/n_gaps
    speed(500)

    # Go to starting location
    penup()
    x_loc_start = -140
    goto(x_loc_start, 140)

    # Draw race lines
    for step in range(n_gaps+1):
        write(step, align='center')
        right(90)
        for num in range(8):
            penup()
            forward(10)
            pendown()
            forward(10)
        penup()
        backward(160)
        left(90)
        forward(gap_dist)
    hideturtle()

    # Create and place turtles
    colors = ['red', 'blue', 'orange', 'green']
    y_loc = [100, 70, 40, 10]
    turtles = []
    for i in range(n_turtles):
        turtles.append(Turtle())
        turtles[i].color(colors[i])
        turtles[i].shape('turtle')

        turtles[i].penup()
        turtles[i].goto(x_loc_start, y_loc[i])
        turtles[i].pendown()
        swirl(turtles[i])

    return turtles

def swirl(t):
    ''' Makes the given turtle instance swirl'''
    nb_turns = 2
    for turn in range(nb_turns):
        t.right(360/nb_turns)

def nod(t):
    ''' Makes the given turtle instance nod '''
    t.left(45)
    t.right(90)
    t.left(45)

# Extension function
def move(t):
    '''A random number is generalized(int) and used as a step to go forward for the turtle'''
    step = random.randint(1, 16)
    t.forward(step)
    return step

if __name__ == "__main__":
    setup_race(2)

`

This is my attempt at making it in classes:
`

from turtle import *
import random

class race(Turtle):

    def __init__(self, score):
        Turtle.__init__(self)
        self.score = int(score)
        # self.race_length = 0

    def setup_race(self, n_turtles):
        ''' Setups a race of length 320 pixels with the given number of racers '''

        race_length = 320
        n_gaps = 8
        gap_dist = race_length/n_gaps
        self.speed(500)

        # Go to starting location
        self.penup()
        x_loc_start = -140
        self.goto(x_loc_start, 140)

        # Draw race lines
        for step in range(n_gaps+1):
            self.write(step, align='center')
            self.right(90)
            for num in range(8):
                self.penup()
                self.forward(10)
                self.pendown()
                self.forward(10)
            self.penup()
            self.backward(160)
            self.left(90)
            self.forward(gap_dist)
        self.hideturtle()

        # Create and place turtles
        colors = ['red', 'blue', 'orange', 'green']
        y_loc = [100, 70, 40, 10]

        # turtles = []
        for i in range(n_turtles):
            # turtles.append(self)
            self.color(colors[i])
            self.shape('turtle')

            self.penup()
            self.goto(x_loc_start, y_loc[i])
            self.pendown()
            self.swirl()
            # swirl(turtles[i])
        # self.done()
        return turtles

    def swirl(self):
        ''' Makes the given turtle instance swirl'''
        nb_turns = 2
        for turn in range(nb_turns):
            self.right(360/nb_turns)

    def nod(self):
        ''' Makes the given turtle instance nod '''
        self.left(45)
        self.right(90)
        self.left(45)

    def move(self):
        '''A random number is generalized(int) and used as a step to go forward for the turtle'''
        step = random.randint(1, 16)
        self.forward(step)
        return step

def main():
    start = race(0)
    start.setup_race(2)

if __name__ == "__main__":
    main()

My code works up until creating and placing the turtles. There are no errors shown with this code.
Right now the code for adding the turtles in a seperate list is in comments:

turtles = []

When I tried running that part, it didn't give me an error code either but it also didn't do anything. So there are still no turtles being created and placed at the starting line.


问:
Spring Cloud Function logging in AWS Lambda
I created an AWS Lambda function with a Java 11 Corretto runtime. I then created a spring cloud function application and deployed it to the Lambda function. I used slf4j for the logs. For some reason, I just can't see anything in the CloudWatch logs but when I test it locally in my console, logs appear.

Here's the code that I deployed.

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

  private static final Logger log = LoggerFactory.getLogger(DeliveryCostFunction.class);

  private APIGatewayProxyResponseEvent response(String body, Integer statusCode) {
    return new APIGatewayProxyResponseEvent()
        .withHeaders(Map.of("Content-Type", "application/json", "Access-Control-Allow-Origin", "*"))
        .withBody(body).withStatusCode(statusCode);
  }

  public APIGatewayProxyResponseEvent testFunction(APIGatewayProxyRequestEvent event) {
    log.info("Request Event={}", event.toString());
    return response("This is a sample body", 200);
  }

  @Bean
  public Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> handleRequest() {
    return this::testFunction;
  }
}
</code>```

The log message that I wrote won't appear in the CloudWatch logs.
The logs after executing the Lambda function

However, if I write the log before returning the test function, the logs appear.

```<code>  @Bean
  public Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> handleRequest() {
    log.info("This is a sample log");
    return this::testFunction;
  }
</code>```

Logs appear

If this is the case, then I have no way to get the request event when I invoke the Lambda function from API gateway.

I've read Spring Cloud Function's documentation over and over again but there was no mention of proper logging. Is there a way to make the logs from the spring cloud function appear in the CloudWatch logs?

Body:
I created an AWS Lambda function with a Java 11 Corretto runtime. I then created a spring cloud function application and deployed it to the Lambda function. I used slf4j for the logs. For some reason, I just can't see anything in the CloudWatch logs but when I test it locally in my console, logs appear.

Here's the code that I deployed.

@Configuration
public class DeliveryCostFunction {

  private static final Logger log = LoggerFactory.getLogger(DeliveryCostFunction.class);

  private APIGatewayProxyResponseEvent response(String body, Integer statusCode) {
    return new APIGatewayProxyResponseEvent()
        .withHeaders(Map.of("Content-Type", "application/json", "Access-Control-Allow-Origin", "*"))
        .withBody(body).withStatusCode(statusCode);
  }

  public APIGatewayProxyResponseEvent testFunction(APIGatewayProxyRequestEvent event) {
    log.info("Request Event={}", event.toString());
    return response("This is a sample body", 200);
  }

  @Bean
  public Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> handleRequest() {
    return this::testFunction;
  }
}

The log message that I wrote won't appear in the CloudWatch logs.
The logs after executing the Lambda function

However, if I write the log before returning the test function, the logs appear.

  @Bean
  public Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> handleRequest() {
    log.info("This is a sample log");
    return this::testFunction;
  }

Logs appear

If this is the case, then I have no way to get the request event when I invoke the Lambda function from API gateway.

I've read Spring Cloud Function's documentation over and over again but there was no mention of proper logging. Is there a way to make the logs from the spring cloud function appear in the CloudWatch logs?


问:
Zoom & pan with trackpad on web without clicking
I'm trying to add the panning & zoom functionality on web & desktop for both trackpad & touch (without a modifier, click or key).

The main issue i'm facing is that the widgets I am using i.e. GestureDetector/onScale, InteractiveViewer(based on onScale)... are always working on desktop as I expect but fail to work on web: On web, zoom is fine but the only way to pan is by a tap + a 2 fingers swipe.

I am not sure if this is a limitation of browsers/js, flutter implementation or If I am missing something.

Do you have any approach to implement this?

Relevant links:

https://github.com/flutter/engine/pull/36342

https://kenneth.io/post/detecting-multi-touch-trackpad-gestures-in-javascript

I have both behaviors implemented via onPointerSignal but it only works because I make a difference between panning & zooming by pressing a specific key on top of a simple scroll event.

onPointerPanZoomStart from Listener is trackpad-specific but only works on windows.

Web/js seems to be using the ctrlKey attached to a mouse event to filter pan zoom & zoom trackpad event.

At the moment i'm exploring MultiTapGestureRecognizer and if supported by web and not touch specific, will allow me to get different pointer ids and calculate proper deltas.


问:
Cookie lost on Azure B2C login/logout
I have a .net 6 MVC application where I am authenticating with Azure B2C and storing the token in local Docker Redis instance.

Data protection keys are also stored in Redis.

The issue I have is that when I either log in or out something is happening with the session and I am loosing cookies that I previous set. For example a cookie that hold the user acceptance for non essential cookies.

Setting up Redis

```<code>var redisConnection = configuration.GetConnectionString("RedisConnection");

services
    .AddDataProtection()
    .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConnection), "EPR_AC_DataProtectionKeys");

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnection;
    options.InstanceName = configuration.GetValue<string>("RedisInstanceName");
});

services.AddSession(options =>
{
    options.Cookie.Name = configuration.GetValue<string>("CookieOptions:SessionCookieName");
    options.IdleTimeout = TimeSpan.FromMinutes(configuration.GetValue<int>("SessionIdleTimeOutMinutes"));
    options.Cookie.HttpOnly = true;
});

</code>```

Setting up token authentication

```<code>services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAdB2C"))
    .EnableTokenAcquisitionToCallDownstreamApi(new string[] {"https://dummytenant.onmicrosoft.com/myapp-uat/access"})
    .AddDistributedTokenCaches();
</code>```

Title: Cookie lost on Azure B2C login/logout

Body:
I have a .net 6 MVC application where I am authenticating with Azure B2C and storing the token in local Docker Redis instance.

Data protection keys are also stored in Redis.

The issue I have is that when I either log in or out something is happening with the session and I am loosing cookies that I previous set. For example a cookie that hold the user acceptance for non essential cookies.

Setting up Redis

var redisConnection = configuration.GetConnectionString("RedisConnection");

services
    .AddDataProtection()
    .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConnection), "EPR_AC_DataProtectionKeys");

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnection;
    options.InstanceName = configuration.GetValue<string>("RedisInstanceName");
});

services.AddSession(options =>
{
    options.Cookie.Name = configuration.GetValue<string>("CookieOptions:SessionCookieName");
    options.IdleTimeout = TimeSpan.FromMinutes(configuration.GetValue<int>("SessionIdleTimeOutMinutes"));
    options.Cookie.HttpOnly = true;
});

Setting up token authentication

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAdB2C"))
    .EnableTokenAcquisitionToCallDownstreamApi(new string[] {"https://dummytenant.onmicrosoft.com/myapp-uat/access"})
    .AddDistributedTokenCaches();


问:
Nuxt3 and Vuetify3 - get initial state of useDisplay() props if SSR is enabled
The project uses Nuxt3 and Vuetify3 stack.
I've started to work on an adaptive mobile layout.

To manage different layout I use useDisplay() as per official docs.

It works fine if SSR is disabled. But if it's enabled, it'll always return the initial value of params because the server didn't know anything about the client.

export const vuetify = createVuetify({
  ssr: true
})
```

What is the best way to handle that?

Playground

Body:
The project uses Nuxt3 and Vuetify3 stack.
I've started to work on an adaptive mobile layout.

To manage different layout I use useDisplay() as per official docs.

It works fine if SSR is disabled. But if it's enabled, it'll always return the initial value of params because the server didn't know anything about the client.

export const vuetify = createVuetify({
  ssr: true
})

What is the best way to handle that?

<a href="https://play.vuetifyjs.com/#eNp9UstuwjAQ/JWVL1BB4qqPC4KKSr322gvmEJIFXOKHbAeoEP/eTRxQgNJcovXMzuyOPTuwbYVBLn/Sb89GTCprXIAD5A6zgF8RgyMsnVHQa7k9oYXGfUPNjfYBWgAml439g9AA3rsRBFeh0McHodmQvVubUgsZjn3upA3gMVT2TejzAA6XXVuyPENGf5pKByzuESqPH9LbMvtr8jjwAXayCOshKLOQJRJv0mnr05iRp/yKkEhKt1lZIQxAMMh0Uf8GUSYiQo95XIcWoSKgIrGAVAGMt0lm6w2BPipUJnVbNXXAfUiWEssCCDQFlhPByJ1M+KmLd9rqIgqOeceIwo0xENPSnRpNITe3IFrACzaC5qQ+o1zqWrB1CNaPOK+03azS3Cg+JYw7CloqTAqjps/pU/ryygvpQ/c8Ra+ShTM7j44cBRt2xOvQ7xm0MOk+pq3s6TGS5I0UJ/0tusShLtCh+3fuK+7F7FfYzfy155HeKmVZSr3xVzHmvolwNq8pxyGL0kRu9mDzX+jPInM=" rel="nofollow noreferrer">Playground


问:
Athena: botocore.errorfactory.InvalidRequestException while creating table
When trying to create an Athena table I get the following error

botocore.errorfactory.InvalidRequestException: An error occurred (InvalidRequestException) when calling the StartQueryExecution operation: line 6:5: mismatched input 'CREATE'. Expecting: '(',

My creation query is the following

```<code>CREATE EXTERNAL TABLE IF NOT EXISTS `logos_v0`(
  `uuid` bigint,
  `source` string,
  `company_name` string,
  `company_logo` string
)
PARTITIONED BY (
  `year` string,
  `month` string,
  `version` bigint)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION
  's3://staging-datalake/datalake-raw/companies/logos/v0'
TBLPROPERTIES (
  'classification'='parquet',
  'compressionType'='snappy',
  'projection.enabled'='false',
  'typeOfData'='file')
</code>```

Python execution

I tried sending the query with Awswrangler

```<code>import awswrangler as wr

query = CREATE_LOGOS # This one is the query I wrote before
wr.athena.read_sql_query(query, database='datalake_raw')
</code>```

Additional note

This query is running fine if I copy it into Athena and run it there. Can someone explain me why it does not work for python?

Body:
When trying to create an Athena table I get the following error

botocore.errorfactory.InvalidRequestException: An error occurred (InvalidRequestException) when calling the StartQueryExecution operation: line 6:5: mismatched input 'CREATE'. Expecting: '(',

My creation query is the following

CREATE EXTERNAL TABLE IF NOT EXISTS `logos_v0`(
  `uuid` bigint,
  `source` string,
  `company_name` string,
  `company_logo` string
)
PARTITIONED BY (
  `year` string,
  `month` string,
  `version` bigint)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION
  's3://staging-datalake/datalake-raw/companies/logos/v0'
TBLPROPERTIES (
  'classification'='parquet',
  'compressionType'='snappy',
  'projection.enabled'='false',
  'typeOfData'='file')

Python execution

I tried sending the query with Awswrangler

import awswrangler as wr

query = CREATE_LOGOS # This one is the query I wrote before
wr.athena.read_sql_query(query, database='datalake_raw')

Additional note

This query is running fine if I copy it into Athena and run it there. Can someone explain me why it does not work for python?


问:
How to round 6.25 to 6.3 and 6.24 to 6.2 in Python?
How to round 6.25 to 6.3 and 6.24 to 6.2 in Python?

The 'round' function is rounding 6.25 to 6.2:

```<code>mynum = 6.25
print(round(mynum, 1))
</code>```

produces 6.2 and I really need it to produce 6.3
It seems to only round up with 6 like 6.26 produces 6.3

Just to be clear: I want 6.25 to round to 6.3 and 6.24 to round to 6.2

Body:
How to round 6.25 to 6.3 and 6.24 to 6.2 in Python?

The 'round' function is rounding 6.25 to 6.2:

mynum = 6.25
print(round(mynum, 1))

produces 6.2 and I really need it to produce 6.3
It seems to only round up with 6 like 6.26 produces 6.3

Just to be clear: I want 6.25 to round to 6.3 and 6.24 to round to 6.2


问:
How to model data for both offline as well as for online customers in mongoDB?
I'm trying to build a database for a store, which receives online orders. However, people also go there to buy stuff physically.

For online customers, we have all sorts of data such as:

id, name, email, address, contact, etc.

However, we don't have any physical customer information. Just the customer id or cashier id who served them.

How can I model the data in this scenario?

Customer collection

```<code>{
   _id: 122..,
   type: online
   name: xyz,
   address: xyz,
   email: xyz,
   contact: 123..,
},
{
   _id: 234,
   type: offline

}
</code>```

Is this correct??

Body:
I'm trying to build a database for a store, which receives online orders. However, people also go there to buy stuff physically.

For online customers, we have all sorts of data such as:

id, name, email, address, contact, etc.

However, we don't have any physical customer information. Just the customer id or cashier id who served them.

How can I model the data in this scenario?

Customer collection

{
   _id: 122..,
   type: online
   name: xyz,
   address: xyz,
   email: xyz,
   contact: 123..,
},
{
   _id: 234,
   type: offline

}

Is this correct??


问:
Referencing HOST's localhost from a Windows container that runs NGINX
Environment: Windows 10 Pro, Docker Desktop: 4.15.0, Running Windows containers

I am new to the world of Docker and NGINX.

Trying to run NGINX inside a Windows Server Core container. That NGINX should proxy traffic from https://localhost to a website that runs on the host itself at https://localhost:54321.

The problem is that when browsing to https://localhost, I am getting Bad Gateway error from NGINX.

Things I tried:

using host.docker.internal instead of localhost inside the container, in NGINX config -- doesn't work

adding localhost using --add-host -- apparently not supported on Windows

--network="host" doesn't work -- apparently not supported on Windows

tried adding [Host IP] localhost to windows/system32/drivers/etc/hosts in the container

Ideally, inside the container, I want localhost to point to the HOST's IP. How can I do that considering I am running Windows containers.

Thank you


问:
how to remove hover frame from dash navbar when using dash bootstrap components
I am using dash bootstrap components and I would like to remove the black border on hover on the header. also if I remove the 404 page from the navbar, the 404 does not work when i enter a page that does not exist.

any help appreciated.

Thank you.

```<code>dbc_css = ("https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.7/dbc.min.css")

app = Dash(__name__,
           use_pages=True,
           title='Portfolio Optimization',
           external_stylesheets=[dbc.themes.SLATE,dbc_css]
           )

load_figure_template("slate")
</code>```

and the header code is:

```<code>header = dbc.Navbar(
dbc.Container(
    [
        html.A(
            dbc.Row(
                dbc.Col(dbc.NavbarBrand("brandName")),
                align="center",
                className="g-0",
            ),
            href="/",
            style={"textDecoration": "none"},
        ),
        dbc.Row(
            [
                dbc.NavbarToggler(id="navbar-toggler"),
                dbc.Collapse(
                    dbc.Nav(
                        [
                            dbc.NavItem(dbc.NavLink('Home',               href='/')),
                            dbc.NavItem(dbc.NavLink('About',              href='/about')),
                            dbc.NavItem(dbc.NavLink('Help',               href='/help')),
                            dbc.NavItem(dbc.NavLink('404',                href='/404')),

                        ],
                        # make sure nav takes up the full width for auto
                        # margin to get applied
                        className="w-100"
                    ),
                    id="navbar-collapse",
                    is_open=False,
                    navbar=True,

                ),
            ],
            # the row should expand to fill the available horizontal space
            className="flex-grow-1",
        ),
    ],
    fluid=True,

),
dark=True,
color="dark",
className="dbc"
)
</code>```

Body:
I am using dash bootstrap components and I would like to remove the black border on hover on the header. also if I remove the 404 page from the navbar, the 404 does not work when i enter a page that does not exist.

any help appreciated.

Thank you.

dbc_css = ("https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.7/dbc.min.css")

app = Dash(__name__,
           use_pages=True,
           title='Portfolio Optimization',
           external_stylesheets=[dbc.themes.SLATE,dbc_css]
           )

load_figure_template("slate")

and the header code is:

header = dbc.Navbar(
dbc.Container(
    [
        html.A(
            dbc.Row(
                dbc.Col(dbc.NavbarBrand("brandName")),
                align="center",
                className="g-0",
            ),
            href="/",
            style={"textDecoration": "none"},
        ),
        dbc.Row(
            [
                dbc.NavbarToggler(id="navbar-toggler"),
                dbc.Collapse(
                    dbc.Nav(
                        [
                            dbc.NavItem(dbc.NavLink('Home',               href='/')),
                            dbc.NavItem(dbc.NavLink('About',              href='/about')),
                            dbc.NavItem(dbc.NavLink('Help',               href='/help')),
                            dbc.NavItem(dbc.NavLink('404',                href='/404')),

                        ],
                        # make sure nav takes up the full width for auto
                        # margin to get applied
                        className="w-100"
                    ),
                    id="navbar-collapse",
                    is_open=False,
                    navbar=True,

                ),
            ],
            # the row should expand to fill the available horizontal space
            className="flex-grow-1",
        ),
    ],
    fluid=True,

),
dark=True,
color="dark",
className="dbc"
)


问:
Stripe payment intent search api throwing error
I am getting an error:call to undefined method stripe\paymentintent::search()

The code reference url is on search stripe payment intents using php library.

```<code>$stripe = new \Stripe\StripeClient('sk_test_51KgTvKAFnFm5ESP8EPiYuUOkkuXT2SXWKa6kRcmLRIn14Q2QllFSibG6VLyejUNnigCagqttfLfrjvcFZTmZtuY000kcoaH4tS');
$stripe->paymentIntents->search(['query' => 'status:\'succeeded\' AND metadata[\'order_id\']:\'6735\'',]);
</code>```

Body:
I am getting an error:call to undefined method stripe\paymentintent::search()

The code reference url is on search stripe payment intents using php library.

$stripe = new \Stripe\StripeClient('sk_test_51KgTvKAFnFm5ESP8EPiYuUOkkuXT2SXWKa6kRcmLRIn14Q2QllFSibG6VLyejUNnigCagqttfLfrjvcFZTmZtuY000kcoaH4tS');
$stripe->paymentIntents->search(['query' => 'status:\'succeeded\' AND metadata[\'order_id\']:\'6735\'',]);


问:
Kivy painter.export_to_png is returning a empty image
I am making a tester for my AI. The only thing left is saving the image. But when i press predict, i want the program to store the current state of the canvas. But instead it saves an empty image.</p>
```<code>from random import random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Line
from kivy.uix.boxlayout import BoxLayout
from kivy.core.image import Image as CoreImage

class MyPaintApp(App):

    def build(self):
        img = Image.open('my_number.png').convert('L')
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear')
        predictbtn = Button(text='Predict')
        clearbtn.bind(on_release=self.clear_canvas)
        predictbtn.bind(on_press=self.saveimage)
        #predictbtn.bind(on_press=self.predict(img))
        parent.add_widget(self.painter)
        boxlayout = BoxLayout()
        boxlayout.add_widget(clearbtn)
        boxlayout.add_widget(predictbtn)
        parent.add_widget(boxlayout)
        return parent

    def clear_canvas(self, obj):
        self.painter.canvas.clear()
    def saveimage(self, obj):
        result = self.painter.export_to_png("my_number.png")
        print(result)
    #def predict(self, obj):
        #print("Predicting")
        #testprediction(obj)

if __name__ == '__main__':
    MyPaintApp().run()
</code>```

Body:
I am making a tester for my AI. The only thing left is saving the image. But when i press predict, i want the program to store the current state of the canvas. But instead it saves an empty image.

from random import random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Line
from kivy.uix.boxlayout import BoxLayout
from kivy.core.image import Image as CoreImage

class MyPaintApp(App):

    def build(self):
        img = Image.open('my_number.png').convert('L')
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear')
        predictbtn = Button(text='Predict')
        clearbtn.bind(on_release=self.clear_canvas)
        predictbtn.bind(on_press=self.saveimage)
        #predictbtn.bind(on_press=self.predict(img))
        parent.add_widget(self.painter)
        boxlayout = BoxLayout()
        boxlayout.add_widget(clearbtn)
        boxlayout.add_widget(predictbtn)
        parent.add_widget(boxlayout)
        return parent

    def clear_canvas(self, obj):
        self.painter.canvas.clear()
    def saveimage(self, obj):
        result = self.painter.export_to_png("my_number.png")
        print(result)
    #def predict(self, obj):
        #print("Predicting")
        #testprediction(obj)

if __name__ == '__main__':
    MyPaintApp().run()