问:
How to make interactable image windows with tkinter and opencv?
I need help to finish an assignment for school please.

What I have to do is modify pre-exisiting code to make an application that browses images from the file explorer and it adds them into its display so that when you click on them, a window pops-up and you can interact with it by clicking the image.

There are also some specifications:

Multiple images have to be interactable at the same time. This means that when an image is clicked and a window appears, if another image is clicked then another window appears with that other image on it and the previous window stays open and both of them are independent from each other (what I do with one image doesn't affect the other).

It should be possible to merge the images by a factor between 0 and 1  and save the result on disk.

So far I have made a class called AppFrame in order to do the assignment:

```<code>class AppFrame(tkinter.Frame):
    window_: Tk
    button_image_dictionary_: {Label}
    isModePoint_: bool
    isModeRect_: bool
    isDragging_: bool
    box_: dict
    button_explore_: tkinter.Button
    button_exit_: tkinter.Button
    help_txt_: str
    about_txt_: str
    fontFace_: int
    fontScale_: float
    thickness_: int

def __init__(self, window: Tk, *args, **kwargs, ):
    tkinter.Frame.__init__(self, *args, **kwargs)
    self.bind_class("buttons", "<Button-3>", self.delete_image)
    self.bind_class("buttons", "<Button-2>", self.delete_image)
    self.bind_class("buttons", "<Button-1>", self.display_image)
    self.window_ = window
    self.button_image_dictionary_ = {}
    self.isModePoint_ = False
    self.isModeRect_ = False
    self.isDragging_ = False
    self.box_ = {
        'x': 0,
        'y': 0,
        'width': 0,
        'height': 0
    }
    self.button_explore_ = Button(self.window_,
                                  text="Browse Files",
                                  command=lambda: self.get_button_image(filedialog.askopenfilename(
                                      initialdir="/",
                                      title="Select a File",
                                      filetypes=(
                                          ("PNG files",
                                           "*.png*"),
                                          ("JPG files",
                                           "*.jpg*"),
                                          ("GIF files",
                                           "*.gif*"),
                                      ))),
                                  )

    self.button_exit_ = Button(self.window_,
                               text="Exit",
                               command=exit)

    self.help_txt_ = "Hot keys: \n" \
                     "\tESC - quit the program\n" \
                     "\tp - draw a point\n" \
                     "\tr - draw a rectangle\n" \
                     "\t0 - clean image\n"
    self.about_txt_ = "\nThis program demonstrated the IO() function\n" \
                      "Call:\n" \
                      "./IO [image_name1]\n"

    self.fontFace_ = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX
    self.fontScale_ = 0.4
    self.thickness_ = 1
    self.button_explore_.pack()
    self.button_exit_.pack()

def help(self):
    print(self.help_txt_)

def about(self):
    print(self.about_txt_)
    help()

def my_mouse_callback_selectPoint(self, evt, x, y, flags, param):
    image = param
    if evt == cv2.EVENT_LBUTTONDOWN:
        seed = (x, y)
        print(" Selection of point (" + str(x) + ", " + str(y) + ")\n")
        # draw a red circle
        cv2.circle(image,  # the dest image
                   seed, 10,  # center point and radius
                   (0, 0, 255),  # the color; red
                   1, 8, 0);  # thickness, line type, shift
        cv2.putText(image, "p", seed, self.fontFace_, self.fontScale_, (0, 0, 255), self.thickness_, 8)
        cv2.imshow("Display window", image)

def my_mouse_callback_drawrectangle(self, evt, x, y, flags, param):

    image = param

    if evt == cv2.EVENT_MOUSEMOVE:
        if self.isDragging_:
            self.box_['width'] = x - self.box_['x']
            self.box_['height'] = y - self.box_['y']
    elif evt == cv2.EVENT_LBUTTONDOWN:
        self.isDragging_ = True
        self.box_ = {
            'x': x,
            'y': y,
            'width': 0,
            'height': 0
        }
        print(" Coins 1 (" + str(x) + ", " + str(y) + ")\n")
    elif evt == cv2.EVENT_LBUTTONUP:
        self.isDragging_ = False
        print(" Coins 2 (" + str(x) + ", " + str(y) + ")\n")
        if self.box_['width'] < 0:
            self.box_['x'] += self.box_['width']
            self.box_['width'] *= -1
        if self.box_['height'] < 0:
            self.box_['y'] += self.box_['height']
            self.box_['height'] *= -1

        cv2.rectangle(image, (self.box_['x'], self.box_['y']), (self.box_['x'] + self.box_['width'],
                                                                self.box_['y'] + self.box_['height']),
                      (0xff, 0x00, 0x00))
        cv2.imshow("Display window", image)
        print("Draw a rectangle mode is OFF\n")
        self.help()

def my_mouse_callback(self, evt, x, y, flags, param):
    if self.isModePoint_:
        self.my_mouse_callback_selectPoint(evt, x, y, flags, param)
    elif self.isModeRect_:
        self.my_mouse_callback_drawrectangle(evt, x, y, flags, param)

def close_window_(self, filename: str):
    print("Exiting ...\n")
    cv2.destroyWindow(filename)

def toggle_draw_point_mode_(self):
    self.isModePoint_ = not self.isModePoint_
    self.isModeRect_ = False
    if self.isModePoint_:
        print("Draw a point mode is ON\n")
    else:
        print("Draw a point mode is OFF\n")
        self.help()

def toggle_draw_rectagle_mode_(self):
    self.isModePoint_ = False
    self.isModeRect_ = not self.isModeRect_
    if self.isModeRect_:
        print("Draw a rectangle mode is ON\n")
    else:
        print("Draw a rectangle mode is OFF\n")
        self.help()

def clean_image(self, imageinit):
    print("Remettre l'image initiale\n")
    image = imageinit.copy()
    cv2.imshow("Display window", image)  # Show our image inside it.
    self.help()

def display_image(self, event):
    filename: str = event.widget.name
    imageinit = cv2.imread(filename, cv2.IMREAD_COLOR)  # Read the file
    image = imageinit.copy()  # the working space for the image

    cv2.namedWindow("Display window", cv2.WINDOW_AUTOSIZE)  # Create a window for display.
    cv2.setMouseCallback("Display window", self.my_mouse_callback, image)  # Set mouse handler to be onMouse

    self.help()  # Shows the list of the keys

    cv2.imshow("Display window", image)  # Show our image inside it.
    self.window_.bind('<Escape>', lambda: self.close_window_(filename=filename))
    self.window_.bind('p', self.toggle_draw_point_mode_)
    self.window_.bind('r', self.toggle_draw_rectagle_mode_)
    self.window_.bind('0', lambda : self.clean_image(imageinit=imageinit))

def delete_image(self, event):
    filename: str = event.widget.name
    button: Label = self.button_image_dictionary_.pop(filename)
    button.destroy()
    self.pack()

def get_button_image(self, filename: str):
    if filename in self.button_image_dictionary_.keys():
        print("Image already stored")
        return
    photo = PhotoImage(file=filename)
    photo_image = photo.subsample(2)
    button = Label(self, image=photo_image, text=filename)
    button.photo_image = photo_image
    button.name = filename
    new_tags = button.bindtags() + ("buttons",)
    button.bindtags(new_tags)
    button.pack()
    self.button_image_dictionary_[filename] = button

def begin(self):
    self.window_.mainloop()
</code>```

The function I use to create the button-images is this:

```<code>    def get_button_image(self, filename: str):
    if filename in self.button_image_dictionary_.keys():
        print("Image already stored")
        return
    photo = PhotoImage(file=filename)
    photo_image = photo.subsample(2)
    button = Label(self, image=photo_image, text=filename)
    button.photo_image = photo_image
    button.name = filename
    new_tags = button.bindtags() + ("buttons",)
    button.bindtags(new_tags)
    button.pack()
    self.button_image_dictionary_[filename] = button
</code>```

And to create the new window I use this:

```<code>    def display_image(self, event):
    filename: str = event.widget.name
    imageinit = cv2.imread(filename, cv2.IMREAD_COLOR)  # Read the file
    image = imageinit.copy()  # the working space for the image

    cv2.namedWindow("Display window", cv2.WINDOW_AUTOSIZE)  # Create a window for display.
    cv2.setMouseCallback("Display window", self.my_mouse_callback, image)  # Set mouse handler to be onMouse

    self.help()  # Shows the list of the keys

    cv2.imshow("Display window", image)  # Show our image inside it.
    self.window_.bind('<Escape>', lambda: self.close_window_(filename=filename))
    self.window_.bind('p', self.toggle_draw_point_mode_)
    self.window_.bind('r', self.toggle_draw_rectagle_mode_)
    self.window_.bind('0', lambda : self.clean_image(imageinit=imageinit))
</code>```

The pre-exisiting code is in the my_mouse_callback methods and I am not allowed to change the logic on those. I was only allowed to change it to put it inside the class.

But well the problem is whenever I try to click on the image it doesn't draw anything on them when I set isModePoint or isModeRect to true...

Also when I click on one image, a window pops up but when I click on another one, the window gets replaced by another when they should both stay intact.

I would appreciate a lot any help for those problems.

Body:
I need help to finish an assignment for school please.

What I have to do is modify pre-exisiting code to make an application that browses images from the file explorer and it adds them into its display so that when you click on them, a window pops-up and you can interact with it by clicking the image.

There are also some specifications:

Multiple images have to be interactable at the same time. This means that when an image is clicked and a window appears, if another image is clicked then another window appears with that other image on it and the previous window stays open and both of them are independent from each other (what I do with one image doesn't affect the other).

It should be possible to merge the images by a factor between 0 and 1  and save the result on disk.

So far I have made a class called AppFrame in order to do the assignment:

class AppFrame(tkinter.Frame):
    window_: Tk
    button_image_dictionary_: {Label}
    isModePoint_: bool
    isModeRect_: bool
    isDragging_: bool
    box_: dict
    button_explore_: tkinter.Button
    button_exit_: tkinter.Button
    help_txt_: str
    about_txt_: str
    fontFace_: int
    fontScale_: float
    thickness_: int

def __init__(self, window: Tk, *args, **kwargs, ):
    tkinter.Frame.__init__(self, *args, **kwargs)
    self.bind_class("buttons", "<Button-3>", self.delete_image)
    self.bind_class("buttons", "<Button-2>", self.delete_image)
    self.bind_class("buttons", "<Button-1>", self.display_image)
    self.window_ = window
    self.button_image_dictionary_ = {}
    self.isModePoint_ = False
    self.isModeRect_ = False
    self.isDragging_ = False
    self.box_ = {
        'x': 0,
        'y': 0,
        'width': 0,
        'height': 0
    }
    self.button_explore_ = Button(self.window_,
                                  text="Browse Files",
                                  command=lambda: self.get_button_image(filedialog.askopenfilename(
                                      initialdir="/",
                                      title="Select a File",
                                      filetypes=(
                                          ("PNG files",
                                           "*.png*"),
                                          ("JPG files",
                                           "*.jpg*"),
                                          ("GIF files",
                                           "*.gif*"),
                                      ))),
                                  )

    self.button_exit_ = Button(self.window_,
                               text="Exit",
                               command=exit)

    self.help_txt_ = "Hot keys: \n" \
                     "\tESC - quit the program\n" \
                     "\tp - draw a point\n" \
                     "\tr - draw a rectangle\n" \
                     "\t0 - clean image\n"
    self.about_txt_ = "\nThis program demonstrated the IO() function\n" \
                      "Call:\n" \
                      "./IO [image_name1]\n"

    self.fontFace_ = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX
    self.fontScale_ = 0.4
    self.thickness_ = 1
    self.button_explore_.pack()
    self.button_exit_.pack()

def help(self):
    print(self.help_txt_)

def about(self):
    print(self.about_txt_)
    help()

def my_mouse_callback_selectPoint(self, evt, x, y, flags, param):
    image = param
    if evt == cv2.EVENT_LBUTTONDOWN:
        seed = (x, y)
        print(" Selection of point (" + str(x) + ", " + str(y) + ")\n")
        # draw a red circle
        cv2.circle(image,  # the dest image
                   seed, 10,  # center point and radius
                   (0, 0, 255),  # the color; red
                   1, 8, 0);  # thickness, line type, shift
        cv2.putText(image, "p", seed, self.fontFace_, self.fontScale_, (0, 0, 255), self.thickness_, 8)
        cv2.imshow("Display window", image)

def my_mouse_callback_drawrectangle(self, evt, x, y, flags, param):

    image = param

    if evt == cv2.EVENT_MOUSEMOVE:
        if self.isDragging_:
            self.box_['width'] = x - self.box_['x']
            self.box_['height'] = y - self.box_['y']
    elif evt == cv2.EVENT_LBUTTONDOWN:
        self.isDragging_ = True
        self.box_ = {
            'x': x,
            'y': y,
            'width': 0,
            'height': 0
        }
        print(" Coins 1 (" + str(x) + ", " + str(y) + ")\n")
    elif evt == cv2.EVENT_LBUTTONUP:
        self.isDragging_ = False
        print(" Coins 2 (" + str(x) + ", " + str(y) + ")\n")
        if self.box_['width'] < 0:
            self.box_['x'] += self.box_['width']
            self.box_['width'] *= -1
        if self.box_['height'] < 0:
            self.box_['y'] += self.box_['height']
            self.box_['height'] *= -1

        cv2.rectangle(image, (self.box_['x'], self.box_['y']), (self.box_['x'] + self.box_['width'],
                                                                self.box_['y'] + self.box_['height']),
                      (0xff, 0x00, 0x00))
        cv2.imshow("Display window", image)
        print("Draw a rectangle mode is OFF\n")
        self.help()

def my_mouse_callback(self, evt, x, y, flags, param):
    if self.isModePoint_:
        self.my_mouse_callback_selectPoint(evt, x, y, flags, param)
    elif self.isModeRect_:
        self.my_mouse_callback_drawrectangle(evt, x, y, flags, param)

def close_window_(self, filename: str):
    print("Exiting ...\n")
    cv2.destroyWindow(filename)

def toggle_draw_point_mode_(self):
    self.isModePoint_ = not self.isModePoint_
    self.isModeRect_ = False
    if self.isModePoint_:
        print("Draw a point mode is ON\n")
    else:
        print("Draw a point mode is OFF\n")
        self.help()

def toggle_draw_rectagle_mode_(self):
    self.isModePoint_ = False
    self.isModeRect_ = not self.isModeRect_
    if self.isModeRect_:
        print("Draw a rectangle mode is ON\n")
    else:
        print("Draw a rectangle mode is OFF\n")
        self.help()

def clean_image(self, imageinit):
    print("Remettre l'image initiale\n")
    image = imageinit.copy()
    cv2.imshow("Display window", image)  # Show our image inside it.
    self.help()

def display_image(self, event):
    filename: str = event.widget.name
    imageinit = cv2.imread(filename, cv2.IMREAD_COLOR)  # Read the file
    image = imageinit.copy()  # the working space for the image

    cv2.namedWindow("Display window", cv2.WINDOW_AUTOSIZE)  # Create a window for display.
    cv2.setMouseCallback("Display window", self.my_mouse_callback, image)  # Set mouse handler to be onMouse

    self.help()  # Shows the list of the keys

    cv2.imshow("Display window", image)  # Show our image inside it.
    self.window_.bind('<Escape>', lambda: self.close_window_(filename=filename))
    self.window_.bind('p', self.toggle_draw_point_mode_)
    self.window_.bind('r', self.toggle_draw_rectagle_mode_)
    self.window_.bind('0', lambda : self.clean_image(imageinit=imageinit))

def delete_image(self, event):
    filename: str = event.widget.name
    button: Label = self.button_image_dictionary_.pop(filename)
    button.destroy()
    self.pack()

def get_button_image(self, filename: str):
    if filename in self.button_image_dictionary_.keys():
        print("Image already stored")
        return
    photo = PhotoImage(file=filename)
    photo_image = photo.subsample(2)
    button = Label(self, image=photo_image, text=filename)
    button.photo_image = photo_image
    button.name = filename
    new_tags = button.bindtags() + ("buttons",)
    button.bindtags(new_tags)
    button.pack()
    self.button_image_dictionary_[filename] = button

def begin(self):
    self.window_.mainloop()

The function I use to create the button-images is this:

    def get_button_image(self, filename: str):
    if filename in self.button_image_dictionary_.keys():
        print("Image already stored")
        return
    photo = PhotoImage(file=filename)
    photo_image = photo.subsample(2)
    button = Label(self, image=photo_image, text=filename)
    button.photo_image = photo_image
    button.name = filename
    new_tags = button.bindtags() + ("buttons",)
    button.bindtags(new_tags)
    button.pack()
    self.button_image_dictionary_[filename] = button

And to create the new window I use this:

    def display_image(self, event):
    filename: str = event.widget.name
    imageinit = cv2.imread(filename, cv2.IMREAD_COLOR)  # Read the file
    image = imageinit.copy()  # the working space for the image

    cv2.namedWindow("Display window", cv2.WINDOW_AUTOSIZE)  # Create a window for display.
    cv2.setMouseCallback("Display window", self.my_mouse_callback, image)  # Set mouse handler to be onMouse

    self.help()  # Shows the list of the keys

    cv2.imshow("Display window", image)  # Show our image inside it.
    self.window_.bind('<Escape>', lambda: self.close_window_(filename=filename))
    self.window_.bind('p', self.toggle_draw_point_mode_)
    self.window_.bind('r', self.toggle_draw_rectagle_mode_)
    self.window_.bind('0', lambda : self.clean_image(imageinit=imageinit))

The pre-exisiting code is in the my_mouse_callback methods and I am not allowed to change the logic on those. I was only allowed to change it to put it inside the class.

But well the problem is whenever I try to click on the image it doesn't draw anything on them when I set isModePoint or isModeRect to true...

Also when I click on one image, a window pops up but when I click on another one, the window gets replaced by another when they should both stay intact.

I would appreciate a lot any help for those problems.


来源: stackexchange

问:
Add a User to Teams groups by .CSV
I'm trying to make a simple Powershell script to add a user to few groups determined by .csv file for new users and stuff.
I took for help this article : https://www.sharepointdiary.com/2021/08/bulk-add-users-to-microsoft-teams-using-powershell.html?

I may be mistaking with .csv/ForEach/Try all together.

The error I get is "-GroupID" in Add-TeamUser gets a "null" so it won't work.
Replacing "$GrpName" to an actual group name in the Get-Team command works.
So the problem must be the .csv reading... I guess.'

```<code>\#Connect Microsoft Teams
Connect-MicrosoftTeams

\#Select .csv with browsing
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = \[Environment\]::GetFolderPath('Desktop')
Filter = "CSV (\*.csv) | \*.csv"
}
$null = $FileBrowser.ShowDialog()
$CSVPath = $FileBrowser.FileName
$inputHeaders = 'Group', 'Role'

\#Select User name
$UserTeams = Read-Host "Name of User"

\#Import Groups by .csv
$Import = Import-Csv -Path $CSVPath -Delimiter ";" -Header $inputHeaders| ForEach-Object {

\#Transform group name into group ID
$GrpName = $Import.Group
$TeamID = Get-Team | Where {$\_.DisplayName -eq $GrpName} | Select -ExpandProperty GroupID
$Role = $Import.Role

\#Add User to the Groups
Add-TeamUser -GroupId $TeamID -User $UserTeams -Role $Role
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Add a User to Teams groups by .CSV

Body:
I'm trying to make a simple Powershell script to add a user to few groups determined by .csv file for new users and stuff.
I took for help this article : https://www.sharepointdiary.com/2021/08/bulk-add-users-to-microsoft-teams-using-powershell.html?

I may be mistaking with .csv/ForEach/Try all together.

The error I get is "-GroupID" in Add-TeamUser gets a "null" so it won't work.
Replacing "$GrpName" to an actual group name in the Get-Team command works.
So the problem must be the .csv reading... I guess.'

\#Connect Microsoft Teams
Connect-MicrosoftTeams

\#Select .csv with browsing
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = \[Environment\]::GetFolderPath('Desktop')
Filter = "CSV (\*.csv) | \*.csv"
}
$null = $FileBrowser.ShowDialog()
$CSVPath = $FileBrowser.FileName
$inputHeaders = 'Group', 'Role'

\#Select User name
$UserTeams = Read-Host "Name of User"

\#Import Groups by .csv
$Import = Import-Csv -Path $CSVPath -Delimiter ";" -Header $inputHeaders| ForEach-Object {

\#Transform group name into group ID
$GrpName = $Import.Group
$TeamID = Get-Team | Where {$\_.DisplayName -eq $GrpName} | Select -ExpandProperty GroupID
$Role = $Import.Role

\#Add User to the Groups
Add-TeamUser -GroupId $TeamID -User $UserTeams -Role $Role
}


问:
trying to plot a beautiful image using the dataset
I want to plot an image something similar to this image by using the data provided here data

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

inp_data=np.loadtxt("data")
fig = plt.figure(figsize=(8.5, 12.0))
ax1 = fig.add_axes([0.25, 0.55, 0.2, 0.04])
plt.setp(ax1.spines.values(), linewidth=0.5)
ax1.minorticks_on()
ax1.imshow(inp_data,aspect='auto')
plt.show()
</code>```

Here problem is that, the image is going blank even after the adjustment of vmin and vmax.
I hope experts may help me overcoming this problem and help me plotting a beautiful plot.
Thanks in advance.

Body:
I want to plot an image something similar to this image by using the data provided here data

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import ticker

inp_data=np.loadtxt("data")
fig = plt.figure(figsize=(8.5, 12.0))
ax1 = fig.add_axes([0.25, 0.55, 0.2, 0.04])
plt.setp(ax1.spines.values(), linewidth=0.5)
ax1.minorticks_on()
ax1.imshow(inp_data,aspect='auto')
plt.show()

Here problem is that, the image is going blank even after the adjustment of vmin and vmax.
I hope experts may help me overcoming this problem and help me plotting a beautiful plot.
Thanks in advance.


问:
How to access Ads Data Hub?
Unable to access Ad Data Hub using this link https://adsdatahub.google.com/u/0/ .

When I go to this link -> https://adsdatahub.google.com/u/0/ , it gives me a message saying "You do not have access to this application. Your account may not be associated with an active Ads Data Hub customer.".
When I read a lot more about it I have understood I need to contact the support, but when I try to reach this link https://support.google.com/ads-data-hub/contact/adh_support , it gives me an error saying "Sorry, this page can't be found.".
Please could anyone help me with accessing the adh account or reaching out to the support.

Title: How to access Ads Data Hub?


Title: Convert pixel values stored in text file to image

Body:
I've been trying to find a way to convert text files with pixels values into images (no matter the format) in R but I couldn't find a way to do it.
I found solutions for MatLab and Python, for example.

I have a file with 520 x 640 pixels with values from 0 to 255.

This is a small piece of it.

mid1al <- read.table("C:/Users/u015/Mid1_R_Al.txt", header = FALSE, sep = ";")
mid1al <- mid1al[1:20,1:20]

dput(mid1al)
structure(list(V1 = c(84L, 79L, 97L, 67L, 98L, 113L, 77L, 46L,
41L, 37L, 42L, 46L, 23L, 28L, 24L, 34L, 45L, 51L, 24L, 24L),
    V2 = c(118L, 107L, 105L, 82L, 87L, 108L, 100L, 40L, 71L,
    74L, 81L, 55L, 41L, 25L, 22L, 58L, 53L, 38L, 26L, 36L), V3 = c(103L,
    116L, 128L, 82L, 77L, 104L, 97L, 50L, 65L, 78L, 98L, 111L,
    86L, 59L, 35L, 51L, 43L, 46L, 33L, 47L), V4 = c(114L, 91L,
    90L, 96L, 103L, 98L, 86L, 36L, 50L, 65L, 98L, 125L, 86L,
    32L, 24L, 36L, 36L, 44L, 34L, 43L), V5 = c(68L, 70L, 85L,
    85L, 100L, 111L, 61L, 12L, 42L, 70L, 103L, 103L, 45L, 27L,
    18L, 27L, 32L, 43L, 51L, 41L), V6 = c(43L, 87L, 85L, 89L,
    130L, 123L, 78L, 43L, 15L, 39L, 62L, 44L, 27L, 14L, 19L,
    61L, 83L, 90L, 88L, 88L), V7 = c(20L, 72L, 116L, 124L, 133L,
    133L, 103L, 56L, 21L, 9L, 19L, 26L, 18L, 32L, 67L, 92L, 100L,
    105L, 94L, 79L), V8 = c(69L, 96L, 120L, 144L, 142L, 101L,
    96L, 46L, 14L, 4L, 8L, 2L, 24L, 73L, 96L, 106L, 103L, 116L,
    109L, 74L), V9 = c(118L, 122L, 134L, 135L, 133L, 98L, 57L,
    20L, 5L, 5L, 2L, 14L, 51L, 89L, 117L, 95L, 103L, 93L, 104L,
    77L), V10 = c(122L, 107L, 127L, 147L, 128L, 88L, 24L, 11L,
    10L, 4L, 10L, 31L, 74L, 104L, 113L, 107L, 109L, 99L, 103L,
    45L), V11 = c(105L, 120L, 114L, 132L, 125L, 112L, 51L, 6L,
    3L, 9L, 18L, 49L, 82L, 111L, 111L, 96L, 92L, 81L, 75L, 18L
    ), V12 = c(98L, 104L, 103L, 126L, 147L, 128L, 61L, 26L, 2L,
    9L, 18L, 50L, 105L, 103L, 101L, 98L, 74L, 53L, 18L, 1L),
    V13 = c(107L, 91L, 108L, 109L, 138L, 114L, 88L, 33L, 2L,
    4L, 9L, 61L, 71L, 77L, 78L, 83L, 43L, 38L, 8L, 5L), V14 = c(53L,
    60L, 43L, 49L, 104L, 128L, 72L, 44L, 6L, 8L, 10L, 24L, 35L,
    27L, 33L, 37L, 31L, 24L, 10L, 5L), V15 = c(13L, 16L, 11L,
    27L, 62L, 78L, 73L, 30L, 8L, 7L, 31L, 66L, 66L, 33L, 13L,
    27L, 16L, 18L, 12L, 7L), V16 = c(11L, 12L, 7L, 3L, 16L, 35L,
    45L, 13L, 5L, 7L, 22L, 74L, 73L, 31L, 16L, 43L, 35L, 14L,
    15L, 8L), V17 = c(15L, 16L, 7L, 8L, 1L, 5L, 15L, 13L, 31L,
    33L, 22L, 34L, 38L, 17L, 18L, 41L, 39L, 26L, 19L, 12L), V18 = c(9L,
    15L, 7L, 2L, 2L, 5L, 5L, 25L, 50L, 55L, 35L, 25L, 14L, 8L,
    18L, 44L, 36L, 36L, 19L, 0L), V19 = c(15L, 16L, 4L, 6L, 4L,
    6L, 22L, 45L, 59L, 48L, 56L, 58L, 52L, 30L, 22L, 46L, 41L,
    50L, 23L, 7L), V20 = c(20L, 7L, 4L, 2L, 6L, 14L, 40L, 55L,
    74L, 60L, 69L, 74L, 60L, 56L, 38L, 45L, 67L, 39L, 25L, 11L
    )), row.names = c(NA, 20L), class = "data.frame")

Is there a way to create this image in Rstudio?


问:
Set label size for industrial printer via PowerShell or bash
At the moment I am struggling with our ways of working in my place. Guys are generating sample labels which have barcode on them, due to huge number of operators they cannot use their own accounts as it defaults the settings each time, they are trying to print even though I have set print settings on printer which is Novexx 6406 6" printer.

I would like to generate or create a PowerShell or bash script which we will then run on each account via group policy, and I would like to do the following.

print speed - 4"/s
darkness -80
width-102 mm
height- 72 mm

no padding at any side so set it to 0mm for top bottom left & right
and I need the label to be going horizontal.

I'm new to bash & PowerShell so I am looking to get started & any help would be appreciated.
Forward to explain scenario better the sample labels are being printed out from web-based app in edge browser.

Any further questions needed for resolution please reach out

Searching online however to no avail


问:
MCNP output folder name
In the Mcnp simulation, the output files were produced by adding letters such as c, p, o to the end of the original file's name.

Recently, it automatically generates output filenames like outr, outs, outt. That is, while the original file name was "sample", the output file name was "sampleo","sampler", but now it is called "outr" regardless of the original file name. How can I revert this situation?

Title: MCNP output folder name


问:
Timeseries error: could not convert string to float: '2015-04-01'
I am trying to run a time series but I am having a problem.
I have two columns in my df2 dataset.
'Close' which is the closing values from APPL and 'Date_New' which is the date. Close is float64 and Date_New is Object.

I have been working to change the date to different formats, but my friends work book has the date as an object and so I don't know why his date as object format works in the exact same code, but mine doesn't.

1.

```<code>    Close   Date_New
0   40.72   2015-04-01
1   40.29   2015-04-02
2   41.55   2015-04-06
3   41.53   2015-04-07
4   41.42   2015-04-08

df1['Date_New']=pd.to_datetime(df1['Date_New'])
</code>```

I then bring in pd.to_datetime to change Date_New to a datetime format to change the date format from Years/Months/Dates to Months/Dates/Years. I found a data workbook that had it's date in this format and the time series works for it. By bringing in this datetime the format for my date does change to Month/Date/Year and Date_New is now datetime64[ns], how ever this does not solve the problem.

```<code>df1['Date_New']=pd.to_datetime(df1['Date_New'])
df1['Date_New'].dt.strftime('%m/%d/%Y')
</code>```

But then when I type df.head() it goes back to 2015-04-01 year/month/day format. (I don't know if this is affecting the error)

I then assign X to Date_New and rehape (-1,1)

```<code>X = df1['Date_New'].index.astype("int64").values.reshape(-1, 1) // 10**9 #X assigned and int reshaped
X
</code>```

This gives me this array

```<code>array([[0],
       [0],
       [0],
       ...,
       [0],
       [0],
       [0]
</code>```

I then convert Date_New to string so it is no longer a datetime

```<code>df1['Date_New'] = df1['Date_New'].astype('string')
xticks = pd.date_range(start = df1.index.min(), end = df1.index.max(), freq = 'D') #range of dates

X = df1[['Date_New']].values
y = df1['Close'].values
</code>```

I then run my Train/Test and assign X to my date column.

```<code>X
array([['2015-04-01'],
       ['2015-04-02'],
       ['2015-04-06'],
       ...,
       ['2021-03-29'],
       ['2021-03-30'],
       ['2021-03-31']], dtype=object)
</code>```

I then run this function

```<code># function to evaluate and plot a regressor on a given feature set
def eval_on_features(features, target, regressor): #def function has features X, Target y and I am using regressor model
    # split the given features into a training and a test set
    X_train, X_test = features[:n_train], features[n_train:]
    # also split the target array
    y_train, y_test = target[:n_train], target[n_train:]
    regressor.fit(X_train, y_train) #fiting the regressor to the X_train, y_train
    print("Test-set R^2: {:.2f}".format(regressor.score(X_test, y_test)))
    y_pred = regressor.predict(X_test)
    y_pred_train = regressor.predict(X_train)
    plt.figure(figsize = (10, 3))

    plt.xticks(range(0, len(X), 8), xticks.strftime("%a %m-%d"), rotation = 90, ha = "left")

    plt.plot(range(n_train), y_train, label = "train")
    plt.plot(range(n_train, len(y_test) + n_train), y_test, '-', label = "test")
    plt.plot(range(n_train), y_pred_train, '--', label = "prediction train")

    plt.plot(range(n_train, len(y_test) + n_train), y_pred, '--', label = "prediction test")
    plt.legend(loc = (1.01, 0))
    plt.xlabel("Date")
    plt.ylabel("Sales")
</code>```

When I run it on the RandomForestRegressor, I get the Error.

```<code>from sklearn.ensemble import RandomForestRegressor
regressor = RandomForestRegressor(n_estimators = 100, random_state = 1)
eval_on_features(X, y, regressor)

      8 # Call the method eval_on_features() to calculate the R^2 and plot
----> 9 eval_on_features(X, y, regressor) #eval function on features

4 frames
/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    744                     array = array.astype(dtype, casting="unsafe", copy=False)
    745                 else:
--> 746                     array = np.asarray(array, order=order, dtype=dtype)
    747             except ComplexWarning as complex_warning:
    748                 raise ValueError(
 ValueError: could not convert string to float: '2015-04-01'
</code>```

Body:
I am trying to run a time series but I am having a problem.
I have two columns in my df2 dataset.
'Close' which is the closing values from APPL and 'Date_New' which is the date. Close is float64 and Date_New is Object.

I have been working to change the date to different formats, but my friends work book has the date as an object and so I don't know why his date as object format works in the exact same code, but mine doesn't.

1.

    Close   Date_New
0   40.72   2015-04-01
1   40.29   2015-04-02
2   41.55   2015-04-06
3   41.53   2015-04-07
4   41.42   2015-04-08

df1['Date_New']=pd.to_datetime(df1['Date_New'])

I then bring in pd.to_datetime to change Date_New to a datetime format to change the date format from Years/Months/Dates to Months/Dates/Years. I found a data workbook that had it's date in this format and the time series works for it. By bringing in this datetime the format for my date does change to Month/Date/Year and Date_New is now datetime64[ns], how ever this does not solve the problem.

df1['Date_New']=pd.to_datetime(df1['Date_New'])
df1['Date_New'].dt.strftime('%m/%d/%Y')

But then when I type df.head() it goes back to 2015-04-01 year/month/day format. (I don't know if this is affecting the error)

I then assign X to Date_New and rehape (-1,1)

X = df1['Date_New'].index.astype("int64").values.reshape(-1, 1) // 10**9 #X assigned and int reshaped
X

This gives me this array

array([[0],
       [0],
       [0],
       ...,
       [0],
       [0],
       [0]

I then convert Date_New to string so it is no longer a datetime

df1['Date_New'] = df1['Date_New'].astype('string')
xticks = pd.date_range(start = df1.index.min(), end = df1.index.max(), freq = 'D') #range of dates

X = df1[['Date_New']].values
y = df1['Close'].values

I then run my Train/Test and assign X to my date column.

X
array([['2015-04-01'],
       ['2015-04-02'],
       ['2015-04-06'],
       ...,
       ['2021-03-29'],
       ['2021-03-30'],
       ['2021-03-31']], dtype=object)

I then run this function

# function to evaluate and plot a regressor on a given feature set
def eval_on_features(features, target, regressor): #def function has features X, Target y and I am using regressor model
    # split the given features into a training and a test set
    X_train, X_test = features[:n_train], features[n_train:]
    # also split the target array
    y_train, y_test = target[:n_train], target[n_train:]
    regressor.fit(X_train, y_train) #fiting the regressor to the X_train, y_train
    print("Test-set R^2: {:.2f}".format(regressor.score(X_test, y_test)))
    y_pred = regressor.predict(X_test)
    y_pred_train = regressor.predict(X_train)
    plt.figure(figsize = (10, 3))

    plt.xticks(range(0, len(X), 8), xticks.strftime("%a %m-%d"), rotation = 90, ha = "left")

    plt.plot(range(n_train), y_train, label = "train")
    plt.plot(range(n_train, len(y_test) + n_train), y_test, '-', label = "test")
    plt.plot(range(n_train), y_pred_train, '--', label = "prediction train")

    plt.plot(range(n_train, len(y_test) + n_train), y_pred, '--', label = "prediction test")
    plt.legend(loc = (1.01, 0))
    plt.xlabel("Date")
    plt.ylabel("Sales")

When I run it on the RandomForestRegressor, I get the Error.

from sklearn.ensemble import RandomForestRegressor
regressor = RandomForestRegressor(n_estimators = 100, random_state = 1)
eval_on_features(X, y, regressor)

      8 # Call the method eval_on_features() to calculate the R^2 and plot
----> 9 eval_on_features(X, y, regressor) #eval function on features

4 frames
/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    744                     array = array.astype(dtype, casting="unsafe", copy=False)
    745                 else:
--> 746                     array = np.asarray(array, order=order, dtype=dtype)
    747             except ComplexWarning as complex_warning:
    748                 raise ValueError(
 ValueError: could not convert string to float: '2015-04-01'


问:
Apache module is not enabled
Attempting to use directives for an Apache module that is not enabled will result in apachectl configtest messages like the following:Example Error Output
(13)Permission denied: AH00957: HTTP: attempt to connect to 127.0.0.1:9090 (127.0.0.1) failed
The Apache error log may have more information.

I tried verifying logs and searched the error in online but unable to find anything. Can someone please help with the same.

Title: Apache module is not enabled


问:
Cannot find declaration of element 'xsd:schema'
Unmarshalling using jaxb keeps displaying same error. The xsd content is listed below, followed by the error. Grateful for any help.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="HouseName" type="xsd:string"/>
</xsd:schema>
</code>```

Error: lineNumber: 2; columnNumber: 58; cvc-elt.1: Cannot find the declaration of element 'xsd:schema'.]

```<code>

I tried without using the xsd on a simple xml file and it worked fine, I tried generating the xsd from a simple xml. But when I tried and include the SchemaFactory.newInstance to XMLConstants.W3C_XML_SCHEMA_NS_URI and the schema filename and run the unmarshaller it displays the error above. I checked previous comments about similar situations but they do not apply.
</code>```

Body:
Unmarshalling using jaxb keeps displaying same error. The xsd content is listed below, followed by the error. Grateful for any help.

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="HouseName" type="xsd:string"/>
</xsd:schema>

Error: lineNumber: 2; columnNumber: 58; cvc-elt.1: Cannot find the declaration of element 'xsd:schema'.]

I tried without using the xsd on a simple xml file and it worked fine, I tried generating the xsd from a simple xml. But when I tried and include the SchemaFactory.newInstance to XMLConstants.W3C_XML_SCHEMA_NS_URI and the schema filename and run the unmarshaller it displays the error above. I checked previous comments about similar situations but they do not apply.


问:
Flutter schedule notifications
anybody knows how to set local notification to show everyday another notification but with the same title cause with my code i get only the same notification body over and over again. I'm struggling for some days working on it. Anybody knows how to make it work?
Here's my notification code:

```<code>
  Future<void> showNotification(int id, String title, String body) async {
    await flutterLocalNotificationsPlugin.periodicallyShow(
      id,
      title,
      body,
      RepeatInterval.everyMinute,
      const NotificationDetails(
        // Android details
        android: AndroidNotificationDetails('main_channel', 'Main Channel',
            channelDescription: "ashwin",
            importance: Importance.max,
            priority: Priority.max),
        // iOS details
        iOS: DarwinNotificationDetails(
          sound: 'default.wav',
          presentAlert: true,
          presentBadge: true,
          presentSound: true,
        ),
      ),
      androidAllowWhileIdle:
          true, // To show notification even when the app is closed
    );
  }
</code>```

I want to schedule different notification when notification it s called.

Title: Flutter schedule notifications

Body:
anybody knows how to set local notification to show everyday another notification but with the same title cause with my code i get only the same notification body over and over again. I'm struggling for some days working on it. Anybody knows how to make it work?
Here's my notification code:

  Future<void> showNotification(int id, String title, String body) async {
    await flutterLocalNotificationsPlugin.periodicallyShow(
      id,
      title,
      body,
      RepeatInterval.everyMinute,
      const NotificationDetails(
        // Android details
        android: AndroidNotificationDetails('main_channel', 'Main Channel',
            channelDescription: "ashwin",
            importance: Importance.max,
            priority: Priority.max),
        // iOS details
        iOS: DarwinNotificationDetails(
          sound: 'default.wav',
          presentAlert: true,
          presentBadge: true,
          presentSound: true,
        ),
      ),
      androidAllowWhileIdle:
          true, // To show notification even when the app is closed
    );
  }

I want to schedule different notification when notification it s called.


问:
IdentitServer4 System.InvalidOperationException: 'No storage mechanism for grants specified
I'm trying to build a simple project using Asp.Net Core and Identity Server 4. But I'm faced with the error

No storage mechanism for grants specified. Use the 'AddInMemoryPersistedGrants' extension method to register a development version"

..My Startup class is:
`

```<code>public void ConfigureService(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddInMemoryApiResources(Config.GetAllApiResources())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryClients(Config.GetClients())
                .AddDeveloperSigningCredential();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIdentityServer();
        }
</code>```

`

Notice, when I use AddInMemoryPersistedGrants method, nothing is changed- still the same error. How can I fix it?

Body:
I'm trying to build a simple project using Asp.Net Core and Identity Server 4. But I'm faced with the error

No storage mechanism for grants specified. Use the 'AddInMemoryPersistedGrants' extension method to register a development version"

..My Startup class is:
`

public void ConfigureService(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddInMemoryApiResources(Config.GetAllApiResources())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryClients(Config.GetClients())
                .AddDeveloperSigningCredential();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIdentityServer();
        }

`

Notice, when I use AddInMemoryPersistedGrants method, nothing is changed- still the same error. How can I fix it?


问:
Using thymeleaf file linkage for css and js
I am trying to change my CSS and JS filepaths from absolute file locations to Thymeleaf syntax . I just started working with Thymeleaf so I am quite new to its functionalities. Hopefully someone can provide me the right syntax or point me in the right direction. Appreciate the possible help in advance.

I tried the following options as I found in online documentation.tried code snippet online I came across the information that for CSS and JavaScript files, the default directory is src/main/resources/static. my project structure however is as followed. project structure


问:
got error can not find openssl while building although I have installed openssl
when I build my program I get this error:I have installed openssl and the error shows me that can not find the appropriate openssl , should I install something else or installing openssl somewhere else?
I am using ubuntu 22.04

```<code>BUILD_TYPE not set, using debug
RUNNING SCRIPT build

Re-using content of build directory
Passing the following script args to command
Building debug without unit tests.
-- Running cmake version 3.22.1
-- CMAKE_MODULE_PATH is /home/proj/src/cmake
-- MySQL 8.0.27
-- Source directory /home/proj/src/
-- Binary directory /home/proj/src/build-debug
-- CMAKE_GENERATOR: Ninja
-- SIZEOF_VOIDP 8
-- Packaging as: mysql-8.0.27-Linux-x86_64
-- Found /usr/local/include/boost/version.hpp
-- BOOST_VERSION_NUMBER is #define BOOST_VERSION 107300
-- BOOST_INCLUDE_DIR /usr/local/include
-- NUMA library missing or required version not available
-- ZLIB_VERSION (bundled) is 1.2.11
-- ZSTD_LEGACY_SUPPORT not defined!
-- ZSTD_VERSION (bundled) is 1.5.0
-- OPENSSL_INCLUDE_DIR = /usr/include
-- OPENSSL_LIBRARY = /usr/lib/x86_64-linux-gnu/libssl.so
-- CRYPTO_LIBRARY = /usr/lib/x86_64-linux-gnu/libcrypto.so
-- OPENSSL_MAJOR_VERSION =
-- OPENSSL_MINOR_VERSION =
-- OPENSSL_FIX_VERSION =
-- Looking for SHA512_DIGEST_LENGTH
-- Looking for SHA512_DIGEST_LENGTH - found
--
 Cannot find appropriate system libraries for WITH_SSL=system.
 Make sure you have specified a supported SSL version.
 Valid options are :
 system (use the OS openssl library),
 yes (synonym for system),
 </path/to/custom/openssl/installation>

 CMake Error at cmake/ssl.cmake:61 (MESSAGE):
 Please install the appropriate openssl developer package.

Call Stack (most recent call first):
 cmake/ssl.cmake:319 (FATAL_SSL_NOT_FOUND_ERROR)
 CMakeLists.txt:1613 (MYSQL_CHECK_SSL)

-- Configuring incomplete, errors occurred!
</code>```

while I have installed openssl before in usr/include as when I run the command whereis openssl it shows me that it has installed before.

```<code>whereis openssl
openssl: /usr/include/openssl /usr/share/man/man1/openssl.1ssl.gz
</code>```

Body:
when I build my program I get this error:I have installed openssl and the error shows me that can not find the appropriate openssl , should I install something else or installing openssl somewhere else?
I am using ubuntu 22.04

BUILD_TYPE not set, using debug
RUNNING SCRIPT build

Re-using content of build directory
Passing the following script args to command
Building debug without unit tests.
-- Running cmake version 3.22.1
-- CMAKE_MODULE_PATH is /home/proj/src/cmake
-- MySQL 8.0.27
-- Source directory /home/proj/src/
-- Binary directory /home/proj/src/build-debug
-- CMAKE_GENERATOR: Ninja
-- SIZEOF_VOIDP 8
-- Packaging as: mysql-8.0.27-Linux-x86_64
-- Found /usr/local/include/boost/version.hpp
-- BOOST_VERSION_NUMBER is #define BOOST_VERSION 107300
-- BOOST_INCLUDE_DIR /usr/local/include
-- NUMA library missing or required version not available
-- ZLIB_VERSION (bundled) is 1.2.11
-- ZSTD_LEGACY_SUPPORT not defined!
-- ZSTD_VERSION (bundled) is 1.5.0
-- OPENSSL_INCLUDE_DIR = /usr/include
-- OPENSSL_LIBRARY = /usr/lib/x86_64-linux-gnu/libssl.so
-- CRYPTO_LIBRARY = /usr/lib/x86_64-linux-gnu/libcrypto.so
-- OPENSSL_MAJOR_VERSION =
-- OPENSSL_MINOR_VERSION =
-- OPENSSL_FIX_VERSION =
-- Looking for SHA512_DIGEST_LENGTH
-- Looking for SHA512_DIGEST_LENGTH - found
--
 Cannot find appropriate system libraries for WITH_SSL=system.
 Make sure you have specified a supported SSL version.
 Valid options are :
 system (use the OS openssl library),
 yes (synonym for system),
 </path/to/custom/openssl/installation>

 CMake Error at cmake/ssl.cmake:61 (MESSAGE):
 Please install the appropriate openssl developer package.

Call Stack (most recent call first):
 cmake/ssl.cmake:319 (FATAL_SSL_NOT_FOUND_ERROR)
 CMakeLists.txt:1613 (MYSQL_CHECK_SSL)

-- Configuring incomplete, errors occurred!

while I have installed openssl before in usr/include as when I run the command whereis openssl it shows me that it has installed before.

whereis openssl
openssl: /usr/include/openssl /usr/share/man/man1/openssl.1ssl.gz


问:
df2gspread is missing an attribute to upload a pandas dataframe to google sheets, is there a workaround?
I'm trying to upload a pandas dataframe to google sheets, and I'm following this step by step guide:https://towardsdatascience.com/using-python-to-push-your-pandas-dataframe-to-google-sheets-de69422508f

I'm using the df2gspread to upload the dataframe, however the I get an error saying this attribute:

https://df2gspread.readthedocs.io/en/latest/examples.html#df2gspread.df2gspread.upload

doesn't exist?

I tried df2gspread.df2gspread.upload, which then gave me this error

I have tried

dict(vars(df2gspread)).keys()
```
<p>which gave me the output</p>
<pre class="lang-py prettyprint-override"><code>dict_keys(
    [
        "__name__",
        "__doc__",
        "__package__",
        "__loader__",
        "__spec__",
        "__path__",
        "__file__",
        "__cached__",
        "__builtins__",
    ]
)
</code>```

Is there a workaround for this?

Body:
I'm trying to upload a pandas dataframe to google sheets, and I'm following this step by step guide:https://towardsdatascience.com/using-python-to-push-your-pandas-dataframe-to-google-sheets-de69422508f

I'm using the df2gspread to upload the dataframe, however the I get an error saying this attribute:

https://df2gspread.readthedocs.io/en/latest/examples.html#df2gspread.df2gspread.upload

doesn't exist?

I tried df2gspread.df2gspread.upload, which then gave me this error

I have tried

dict(vars(df2gspread)).keys()

which gave me the output

dict_keys(
    [
        "__name__",
        "__doc__",
        "__package__",
        "__loader__",
        "__spec__",
        "__path__",
        "__file__",
        "__cached__",
        "__builtins__",
    ]
)

Is there a workaround for this?


问:
replace the kscreenlocker_greet
Sorry my English language

I need the following

If you launch the menu -Start -> Shutdown -> Lock

Then you can see the lock screen

Now press CTRL + ALT +F2

let's log in to this terminal under the root user

And let's see the running processes ps -eH | less

We will see the process tree, and who started whom

You can find the following

ksmserver -> kscreenlocker_greet

If you look at how kscreenlocker_greet was launched using ps -aux | grep greet

Then we will see the following

/usr/libexec/kf5/kscreenlocker_greet --immediateLock --ksldfd

Is it possible somewhere (I hope it's not hard code) to replace this command with another command or an application being launched? And if so, where can it be found? Very necessary!

I would like to replace the command call with another application.

Title: replace the kscreenlocker_greet


问:
CSRF in Tests stopped working with Spring Boot 3 and Spring Security 6
We got the problem described here and used the solution linked there and provided by Spring.

The solution fixes our end-to-end using WebClient and a filter function, but unfortunately introduces Problems with our REST-controller unit tests, that stop working.

The relevant cecurity configuration using the documented answer:

```<code>// Enable CSRF security
http.csrf { csrfConfigurer ->
    // see https://docs.spring.io/spring-security/reference/5.8/migration/servlet/exploits.html#_i_am_using_angularjs_or_another_javascript_framework
    val tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse()
    val delegate = XorCsrfTokenRequestAttributeHandler()
    // set the name of the attribute the CsrfToken will be populated on
    delegate.setCsrfRequestAttributeName("_csrf")
    // Use only the handle() method of XorCsrfTokenRequestAttributeHandler and the
    // default implementation of resolveCsrfTokenValue() from CsrfTokenRequestHandler
    val requestHandler = CsrfTokenRequestHandler(delegate::handle)

    csrfConfigurer.csrfTokenRepository(tokenRepository)
    csrfConfigurer.csrfTokenRequestHandler(requestHandler)

}
</code>```

This configuration fixes our end-to-end-tests using a WebClient with the FilterFunction:

```<code>override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> =
    next.exchange(request)
        .flatMap { response: ClientResponse ->
            if (response.statusCode().is4xxClientError) {
                val csrfCookie = response.cookies().getFirst("XSRF-TOKEN")
                if (csrfCookie != null) {
                    val retryRequest: ClientRequest = ClientRequest.from(request)
                        .headers { httpHeaders -> httpHeaders.set("X-XSRF-TOKEN", csrfCookie.value) }
                        .cookies { cookies -> cookies.add("XSRF-TOKEN", csrfCookie.value) }
                        .build()
                    return@flatMap next.exchange(retryRequest)
                }
            }
            Mono.just(response)
        }
</code>```

The failing tests look like this:

```<code>@Test
fun `create tender with copyFrom null should succeed and return 201 and the uuid`() {
    mockMvc
        .perform(
            post("/api/my/endpoint")
                .param("title", "Angebot 1")
                .param("copyFrom", null)
                .with(user(tendererTestUsers[0]))
                .with(csrf())
        )
        .andExpectAll(
            status().isCreated,
            content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON),
            jsonPath("$", `is`(notNullValue()))
        )
</code>```

Debugging leads to a mismatching CSRF-Token provided as shown in this screenshot. Most likely we need to update the test's csrf configuration; anyone any clue on how to do that?

Using the pre-Spring-Boot-3 CSRF security configuration makes the mock-Tests work again, but then the end-to-end-tests fail...

Body:
We got the problem described here and used the solution linked there and provided by Spring.

The solution fixes our end-to-end using WebClient and a filter function, but unfortunately introduces Problems with our REST-controller unit tests, that stop working.

The relevant cecurity configuration using the documented answer:

// Enable CSRF security
http.csrf { csrfConfigurer ->
    // see https://docs.spring.io/spring-security/reference/5.8/migration/servlet/exploits.html#_i_am_using_angularjs_or_another_javascript_framework
    val tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse()
    val delegate = XorCsrfTokenRequestAttributeHandler()
    // set the name of the attribute the CsrfToken will be populated on
    delegate.setCsrfRequestAttributeName("_csrf")
    // Use only the handle() method of XorCsrfTokenRequestAttributeHandler and the
    // default implementation of resolveCsrfTokenValue() from CsrfTokenRequestHandler
    val requestHandler = CsrfTokenRequestHandler(delegate::handle)

    csrfConfigurer.csrfTokenRepository(tokenRepository)
    csrfConfigurer.csrfTokenRequestHandler(requestHandler)

}

This configuration fixes our end-to-end-tests using a WebClient with the FilterFunction:

override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> =
    next.exchange(request)
        .flatMap { response: ClientResponse ->
            if (response.statusCode().is4xxClientError) {
                val csrfCookie = response.cookies().getFirst("XSRF-TOKEN")
                if (csrfCookie != null) {
                    val retryRequest: ClientRequest = ClientRequest.from(request)
                        .headers { httpHeaders -> httpHeaders.set("X-XSRF-TOKEN", csrfCookie.value) }
                        .cookies { cookies -> cookies.add("XSRF-TOKEN", csrfCookie.value) }
                        .build()
                    return@flatMap next.exchange(retryRequest)
                }
            }
            Mono.just(response)
        }

The failing tests look like this:

@Test
fun `create tender with copyFrom null should succeed and return 201 and the uuid`() {
    mockMvc
        .perform(
            post("/api/my/endpoint")
                .param("title", "Angebot 1")
                .param("copyFrom", null)
                .with(user(tendererTestUsers[0]))
                .with(csrf())
        )
        .andExpectAll(
            status().isCreated,
            content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON),
            jsonPath("$", `is`(notNullValue()))
        )

Debugging leads to a mismatching CSRF-Token provided as shown in this screenshot. Most likely we need to update the test's csrf configuration; anyone any clue on how to do that?

Using the pre-Spring-Boot-3 CSRF security configuration makes the mock-Tests work again, but then the end-to-end-tests fail...


问:
how to use Camera2 from rtmp with sceneform. I want to start live streaming from my android app and want to add Augmented reality model in camera view
Youtube livestreaming is working seperately and Augmented reality is also working seperately. I want to merge both together. I  want to start live streaming  with Augmented reality view of camera. Is it possible?
I am using https://github.com/SceneView/sceneform-android for  Augmented reality  and
https://github.com/pedroSG94/rtmp-rtsp-stream-client-java for opening camera and sending data packets to youtube.</p>


问:
Intelliji IDEA cannot run single test unless all tests are built successfully
Using Intelliji Community Edition 2022.03 on windows 11, working with Maven 3.6.3 and Java-8.
Been experiencing strange issue: I cannot run single Junit||Blueprint test if that test has problem, the IDE always try to build the whole test file and then failed at that single problematic test. So the situation end up being I have to run all the test successfully in order to run single test. I am sure it is related to my local environment, because my colleges have no such problem we have everything the same. and I also have no such problem in linux VM.

I have tried

install unintall different versions of IDE

Modify test to not build before run, works, but if I change code, no auto detection, so barely

Any wise men got some ideas please ?


问:
Run query for each database in a list and append results
I have the below code to pull the row and column counts from each table within a database (e.g., db1). But I have several databases (e.g., db1, db2 etc.) , so manually updating the database name in the USE statement for every run isn't very convenient. Is there a way to pass a list of database names in a cursor (or something else that allows iteration) and then run the below query for every database in the list, appending the results from each run? I can get the list of database names from this query select name from master.dbo.sysdatabases where name like '%db%'.

```<code>USE [db1]

;with [rowCount] as
(
    SELECT  DB_NAME() as [DB_Name],
            QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName],
            SUM(sPTN.Rows) AS [RowCount]
    FROM    SYS.OBJECTS AS sOBJ
    INNER JOIN SYS.PARTITIONS AS sPTN
        ON sOBJ.object_id = sPTN.object_id
    WHERE
        sOBJ.type = 'U'
        AND sOBJ.is_ms_shipped = 0x0
        AND index_id < 2 -- 0:Heap, 1:Clustered
    GROUP BY
        sOBJ.schema_id
        ,sOBJ.name
)
,columnCount as
(
    select
        QUOTENAME(col.TABLE_SCHEMA) + '.' + QUOTENAME(col.TABLE_NAME) AS [TableName],
        count(*) as ColumnCount
    from INFORMATION_SCHEMA.COLUMNS col
    inner join INFORMATION_SCHEMA.TABLES tbl
        on col.TABLE_SCHEMA = tbl.TABLE_SCHEMA
        and col.TABLE_NAME = tbl.TABLE_NAME
        and tbl.TABLE_TYPE <> 'view'
    group by
        QUOTENAME(col.TABLE_SCHEMA) + '.' + QUOTENAME(col.TABLE_NAME)
)
select r.[DB_Name], r.TableName, r.[RowCount], c.ColumnCount
from [rowCount] r
inner join columnCount c
    on r.TableName = c.TableName
ORDER BY r.[TableName]
</code>```

Body:
I have the below code to pull the row and column counts from each table within a database (e.g., db1). But I have several databases (e.g., db1, db2 etc.) , so manually updating the database name in the USE statement for every run isn't very convenient. Is there a way to pass a list of database names in a cursor (or something else that allows iteration) and then run the below query for every database in the list, appending the results from each run? I can get the list of database names from this query select name from master.dbo.sysdatabases where name like '%db%'.

USE [db1]

;with [rowCount] as
(
    SELECT  DB_NAME() as [DB_Name],
            QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName],
            SUM(sPTN.Rows) AS [RowCount]
    FROM    SYS.OBJECTS AS sOBJ
    INNER JOIN SYS.PARTITIONS AS sPTN
        ON sOBJ.object_id = sPTN.object_id
    WHERE
        sOBJ.type = 'U'
        AND sOBJ.is_ms_shipped = 0x0
        AND index_id < 2 -- 0:Heap, 1:Clustered
    GROUP BY
        sOBJ.schema_id
        ,sOBJ.name
)
,columnCount as
(
    select
        QUOTENAME(col.TABLE_SCHEMA) + '.' + QUOTENAME(col.TABLE_NAME) AS [TableName],
        count(*) as ColumnCount
    from INFORMATION_SCHEMA.COLUMNS col
    inner join INFORMATION_SCHEMA.TABLES tbl
        on col.TABLE_SCHEMA = tbl.TABLE_SCHEMA
        and col.TABLE_NAME = tbl.TABLE_NAME
        and tbl.TABLE_TYPE <> 'view'
    group by
        QUOTENAME(col.TABLE_SCHEMA) + '.' + QUOTENAME(col.TABLE_NAME)
)
select r.[DB_Name], r.TableName, r.[RowCount], c.ColumnCount
from [rowCount] r
inner join columnCount c
    on r.TableName = c.TableName
ORDER BY r.[TableName]


问:
How to access child element properties with Puppeteer
I am current trying to use Puppeteer to access the innerText of child elements with await page.$eval('.container') , but am unable to get any properties when I console.log the result. All I get are empty objects like this { '0': {}, '1': {}, '2': {} }. Below is an example of the HTML I am trying to get the innerText from.

A

B

C

```
<p>The code I've tried so far</p>
<pre class="lang-js prettyprint-override"><code>import puppeteer,{ executablePath } from "puppeteer"

(async () => {
    const browser = await puppeteer.launch({
        headless: true,
        executablePath: executablePath(),
      });
    const page = await browser.newPage();
    await page.goto('http://localhost:5000/test_child.html',{
        waitUntil: 'networkidle2',
      });
    let child = await page.$eval('.container', e =>e.children);
      console.log(child)
    await browser.close();

})()
</code>```

Body:
I am current trying to use Puppeteer to access the innerText of child elements with await page.$eval('.container') , but am unable to get any properties when I console.log the result. All I get are empty objects like this { '0': {}, '1': {}, '2': {} }. Below is an example of the HTML I am trying to get the innerText from.

A

B

C

The code I've tried so far

import puppeteer,{ executablePath } from "puppeteer"

(async () => {
    const browser = await puppeteer.launch({
        headless: true,
        executablePath: executablePath(),
      });
    const page = await browser.newPage();
    await page.goto('http://localhost:5000/test_child.html',{
        waitUntil: 'networkidle2',
      });
    let child = await page.$eval('.container', e =>e.children);
      console.log(child)
    await browser.close();

})()


问:
Making a new column base on the value the row has in Mysql
I not so sure how to explain this but I want to have rows in my table to create a new column if there is a value and create null if it does not exist. Here is some visual to show what I mean.

id_restaurant_type is the primary key

id_restaurant is the id of the restaurant

Type is the type of restaurant it is (For example, 1 might mean japanese restaurant)

id_restaurant_type
id_restaurant
type

1
1
1

2
1
2

3
2
3

As you can see there is two rows with the same id restaurant. I am trying to combine them together by putting the type into new column

id_restaurant_type
id_restaurant
type1
type2

1
1
1
2

2
2
3
NULL

(End result)

and then the same thing if there is more types

(Before)

idrestaurant_type
id_restaurant
type

1
1
1

2
1
2

3
1
3

4
2
3

5
3
3

(After)

idrestaurant_type
id_restaurant
type1
type2
type3

1
1
1
2
3

2
2
3
null
null

3
3
3
null
null

Is it possible to do such a thing?

(sry I am quite new to Mysql)

I cant think much for the answer as I cant find any method to help me do this.


问:
Using and freezing pre-trained weights when fine-tuning YOLOv7-tiny detector
I'd like to retrain a YOLOv7-tiny Object Detector on a custom dataset with 4 classes.
According to the README of the official git repo in order to transfer learn one should pass the pre-trained weights as argument:

```<code>python train.py --workers 8 --device 0 --batch-size 32 --data data/custom.yaml --img 640 640 --cfg cfg/training/yolov7-custom.yaml --weights 'yolov7_training.pt' --name yolov7-custom --hyp data/hyp.scratch.custom.yaml
</code>```

As for the normal YOLOv7 model, there are the weight files yolov7.pt  and yolov7_training.pt  present in the repo (see here). What´s the difference between these two and which should be used in which occasion?
Also there's a yolov7-tiny.pt  weight file, but no respective yolov7-tiny_training.pt  file. Is there a particular reason for that?

Also I learned that for Transfer Learning it's helpful to "freeze" the base models weights (make them untrainable) first, then train the new model on the new dataset, so only the new weights get adjusted. After that you can "unthaw" the frozen weights to fine-tune the entire model. The train.py script has a --freeze argument to freeze backbone layers.
Is this approach recommended for retraining YOLOv7? If so, should you freeze all 50 backbone layers of YOLOv7 (and would that command be --freeze 50 or smth. different)? And how would you then unthaw these layers and resume the training of said model?

Body:
I'd like to retrain a YOLOv7-tiny Object Detector on a custom dataset with 4 classes.
According to the README of the official git repo in order to transfer learn one should pass the pre-trained weights as argument:

python train.py --workers 8 --device 0 --batch-size 32 --data data/custom.yaml --img 640 640 --cfg cfg/training/yolov7-custom.yaml --weights 'yolov7_training.pt' --name yolov7-custom --hyp data/hyp.scratch.custom.yaml

As for the normal YOLOv7 model, there are the weight files yolov7.pt  and yolov7_training.pt  present in the repo (see here). What´s the difference between these two and which should be used in which occasion?
Also there's a yolov7-tiny.pt  weight file, but no respective yolov7-tiny_training.pt  file. Is there a particular reason for that?

Also I learned that for Transfer Learning it's helpful to "freeze" the base models weights (make them untrainable) first, then train the new model on the new dataset, so only the new weights get adjusted. After that you can "unthaw" the frozen weights to fine-tune the entire model. The train.py script has a --freeze argument to freeze backbone layers.
Is this approach recommended for retraining YOLOv7? If so, should you freeze all 50 backbone layers of YOLOv7 (and would that command be --freeze 50 or smth. different)? And how would you then unthaw these layers and resume the training of said model?


问:
C# Aes Encryption IV and Key Size
I am quite new to AES Encryption and therefore have some question about IV and Key

The code I have written works, i can both encrypt and decrypt a String

Just for fun i tried to go on a Website https://www.devglan.com/online-tools/aes-encryption-decryption

And tried to see if the website can decrypt, if i give the same key and IV. but I ran into an error

The website said "Length of secret key should be 32 for 256 bits key size"

and "Length of initialization vector must be 16 with AES."

Is there anything I have done wrong?

```<code> static void Main(string[] args)
        {

           byte[] key = GenerateRandomByteArray(32);
            Console.WriteLine($"Key: {Convert.ToBase64String(key)}");
            byte[] encrypted = EncryptMessage("test message", key);
            Console.WriteLine($"Encrypted : {Convert.ToBase64String(encrypted)}");
            string decrypted = DecryptMessage(encrypted, key);
            Console.WriteLine($"Decrypted: {decrypted}");
            Console.ReadLine();
        }
        private static byte[] GenerateRandomByteArray(int size)
        {
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                byte[] buffer = new byte[size];
                rng.GetBytes(buffer);
                return buffer;
            }
        }
        public static byte[] EncryptMessage(string mess, byte[] secretkey)
        {
            byte[] encrypted;
            using (Aes aes = Aes.Create())
            {

                aes.Key = secretkey;
                //Generates a IV with 16 random bytes
                aes.IV = GenerateRandomByteArray(16);

                Console.WriteLine($"IV: {Convert.ToBase64String(aes.IV)}");

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Writes the IV, so when we decrypt we can get the first 16 bytes where IV i located
                            msEncrypt.Write(aes.IV, 0, aes.IV.Length);
                            //Write all data to the stream.
                            swEncrypt.Write(mess);
                        }

                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }

        public static string DecryptMessage(byte[] mess, byte[] key)
        {
            string plaintext = null;

            // Create an Aes object
            using (Aes aes = Aes.Create())
            {
                //Sets the AES key
                aes.Key = key;
                using (MemoryStream msDecrypt = new MemoryStream(mess))
                {
                    //Reads the first 16 bytes from the message which is where the IV i stored
                    byte[] iv = new byte[aes.BlockSize / 8];
                    msDecrypt.Read(iv, 0, iv.Length);
                    //Sets the IV
                    aes.IV = iv;

                    // Create a decryptor to perform the stream transform.
                    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                    // Create the streams used for decryption.
                    //using (MemoryStream msDecrypt = new MemoryStream(mess))
                    //{
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }
</code>```

Is i remember right GenerateRandomByteArray(32) is 256 bits for Key
And GenerateRandomByteArray(16) is 128 bits for IV

Output from Console:

```<code>Key: 3dmQoxqrAyoc5kMKQIQl8Hp4UVVCE8B64S19iNZOQRY=
IV: kO1nKUs08c/8mrlbHj3/xQ==
Encrypted : kO1nKUs08c/8mrlbHj3/xR43S5L3BJ5Ueg01xngw93I=
Decrypted: test message
</code>```

Title: C# Aes Encryption IV and Key Size

Body:
I am quite new to AES Encryption and therefore have some question about IV and Key

The code I have written works, i can both encrypt and decrypt a String

Just for fun i tried to go on a Website https://www.devglan.com/online-tools/aes-encryption-decryption

And tried to see if the website can decrypt, if i give the same key and IV. but I ran into an error

The website said "Length of secret key should be 32 for 256 bits key size"

and "Length of initialization vector must be 16 with AES."

Is there anything I have done wrong?

 static void Main(string[] args)
        {

           byte[] key = GenerateRandomByteArray(32);
            Console.WriteLine($"Key: {Convert.ToBase64String(key)}");
            byte[] encrypted = EncryptMessage("test message", key);
            Console.WriteLine($"Encrypted : {Convert.ToBase64String(encrypted)}");
            string decrypted = DecryptMessage(encrypted, key);
            Console.WriteLine($"Decrypted: {decrypted}");
            Console.ReadLine();
        }
        private static byte[] GenerateRandomByteArray(int size)
        {
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                byte[] buffer = new byte[size];
                rng.GetBytes(buffer);
                return buffer;
            }
        }
        public static byte[] EncryptMessage(string mess, byte[] secretkey)
        {
            byte[] encrypted;
            using (Aes aes = Aes.Create())
            {

                aes.Key = secretkey;
                //Generates a IV with 16 random bytes
                aes.IV = GenerateRandomByteArray(16);

                Console.WriteLine($"IV: {Convert.ToBase64String(aes.IV)}");

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Writes the IV, so when we decrypt we can get the first 16 bytes where IV i located
                            msEncrypt.Write(aes.IV, 0, aes.IV.Length);
                            //Write all data to the stream.
                            swEncrypt.Write(mess);
                        }

                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }

        public static string DecryptMessage(byte[] mess, byte[] key)
        {
            string plaintext = null;

            // Create an Aes object
            using (Aes aes = Aes.Create())
            {
                //Sets the AES key
                aes.Key = key;
                using (MemoryStream msDecrypt = new MemoryStream(mess))
                {
                    //Reads the first 16 bytes from the message which is where the IV i stored
                    byte[] iv = new byte[aes.BlockSize / 8];
                    msDecrypt.Read(iv, 0, iv.Length);
                    //Sets the IV
                    aes.IV = iv;

                    // Create a decryptor to perform the stream transform.
                    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                    // Create the streams used for decryption.
                    //using (MemoryStream msDecrypt = new MemoryStream(mess))
                    //{
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }

Is i remember right GenerateRandomByteArray(32) is 256 bits for Key
And GenerateRandomByteArray(16) is 128 bits for IV

Output from Console:

Key: 3dmQoxqrAyoc5kMKQIQl8Hp4UVVCE8B64S19iNZOQRY=
IV: kO1nKUs08c/8mrlbHj3/xQ==
Encrypted : kO1nKUs08c/8mrlbHj3/xR43S5L3BJ5Ueg01xngw93I=
Decrypted: test message


问:
Error on getting thumbnail_url field with Business Discovery API (Instagram Graph)
I'm trying to get thumbnail_url using Business Discovery API (LINK) and get an error.

Docs says: You can use both nested requests and field expansion to get public fields for a Business or Creator Account's media objects.

In IGMedia docs says:  thumbnail_url - Public

So my working request:

```<code>{page-id}?fields=business_discovery.username(nike){media{media_url,media_type,children{media_url}}}.
</code>```

Response:

And, if I add thumbnail_url field in request:

```<code>{page-id}?fields=business_discovery.username(nike){media{media_url,media_type,thumbnail_url,children{media_url}}}
</code>```

Error:

```<code>{
  "error": {
    "message": "(#100) Please read documentation for supported fields.",
    "type": "OAuthException",
    "code": 100,
    "fbtrace_id": "A2sUKUDWUyAJjyQErkGjx7b"
  }
}
</code>```

It’s not the end. If I add thumbnail_url in children expansion, from response disappears all CAROUSEL_ALBUM posts.

Request:

```<code>{page-id}?fields=business_discovery.username(nike){media{media_url,media_type,children{media_url,thumbnail_url}}}
</code>```

Response:

So my questions:
Is it a bug (seems like that it)? Or docs are not updated?
Is there other official way to get thumbnail_url using Business Discovery API?

Sorry about long read :)

Body:
I'm trying to get thumbnail_url using Business Discovery API (LINK) and get an error.

Docs says: You can use both nested requests and field expansion to get public fields for a Business or Creator Account's media objects.

In IGMedia docs says:  thumbnail_url - Public

So my working request:

{page-id}?fields=business_discovery.username(nike){media{media_url,media_type,children{media_url}}}.

Response:

And, if I add thumbnail_url field in request:

{page-id}?fields=business_discovery.username(nike){media{media_url,media_type,thumbnail_url,children{media_url}}}

Error:

{
  "error": {
    "message": "(#100) Please read documentation for supported fields.",
    "type": "OAuthException",
    "code": 100,
    "fbtrace_id": "A2sUKUDWUyAJjyQErkGjx7b"
  }
}

It’s not the end. If I add thumbnail_url in children expansion, from response disappears all CAROUSEL_ALBUM posts.

Request:

{page-id}?fields=business_discovery.username(nike){media{media_url,media_type,children{media_url,thumbnail_url}}}

Response:

So my questions:
Is it a bug (seems like that it)? Or docs are not updated?
Is there other official way to get thumbnail_url using Business Discovery API?

Sorry about long read :)


问:
How to set up HTTPS communication using Apache HttpClient
I am trying to gather and store URLs and associated metadata from the Cochrane Library review collection (https://www.cochranelibrary.com/cdsr/reviews/topics) for a project. But when I do a regular HTTP Get requests I get a timed out 419 error.

HttpResponseProxy{HTTP/1.1 419 status code 419 [Date: Thu, 08 Dec 2022 11:36:36 GMT, Content-Length: 0, Connection: keep-alive, Cf-Railgun: direct (starting new WAN connection), CF-Cache-Status: DYNAMIC, Server: cloudflare, CF-RAY: 7765344b8cb53338-EWR] [Content-Length: 0,Chunked: false]}

My only requirements for this project are java 1.7 and Apache HttpClient 4.5

This is my code to reproduce the error:

```<code>SSLContext sslContext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
   .setSSLSocketFactory(sslConnectionFactory)
   .build();
HttpGet request = new HttpGet("https://www.cochranelibrary.com/");
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println(entity);
httpClient.close();
response.close();
</code>```

Body:
I am trying to gather and store URLs and associated metadata from the Cochrane Library review collection (https://www.cochranelibrary.com/cdsr/reviews/topics) for a project. But when I do a regular HTTP Get requests I get a timed out 419 error.

HttpResponseProxy{HTTP/1.1 419 status code 419 [Date: Thu, 08 Dec 2022 11:36:36 GMT, Content-Length: 0, Connection: keep-alive, Cf-Railgun: direct (starting new WAN connection), CF-Cache-Status: DYNAMIC, Server: cloudflare, CF-RAY: 7765344b8cb53338-EWR] [Content-Length: 0,Chunked: false]}

My only requirements for this project are java 1.7 and Apache HttpClient 4.5

This is my code to reproduce the error:

SSLContext sslContext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
   .setSSLSocketFactory(sslConnectionFactory)
   .build();
HttpGet request = new HttpGet("https://www.cochranelibrary.com/");
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println(entity);
httpClient.close();
response.close();


问:
React / Javascript return GraphQL query when loaded
I'm a rookie in Javascript & React, but I've researched, tried & failed for x amount of days now - including taking an online course in Javascript.

```<code>import { useQuery } from "@apollo/client";
import React, { useEffect, useState, Suspense } from 'react'
import { GET_COLLECTIONS } from '../graphql/queries'
import { isEmpty, isNull } from 'lodash'
import { useNavigate } from 'react-router-dom'

async function FetchCollections() {
  let collections;

  //Perform the query to GraphQL API
  let { data, loading, error } = await useQuery(GET_COLLECTIONS);

  //When data is not empty we parse out collections in the response and returns it
  if (!isEmpty(data)) {
    collections = data.collections.collections;
    collections = JSON.parse(collections);
    return await collections;
  } else { console.log("FetchCollections / Waiting for respnse..") }
}

export const Collections = () => {
  const navigate = useNavigate();

  let collections;
  Promise.resolve(FetchCollections())
    .then(data => {
      collections = data;
    });

  let nodes;
  let relationships;

  const ref = React.useRef(null);
  useEffect(() => {
    if (!isEmpty(collections)) {
      nodes = collections.nodes;
      nodes = nodes.join() //Creates a string of the array
      console.log("Nodes fetched : " + nodes)
    }
  }, [collections, navigate])

  return (
    <>
      {console.log("Return : " + nodes)}
      test : {nodes}
    </>
  )
}
</code>```

Console output:

```<code>Return : undefined
Nodes fetched : string1,string2,string3
</code>```

How can I hold the return (test: {nodes}) until the nodes variable holds data?

Body:
I'm a rookie in Javascript & React, but I've researched, tried & failed for x amount of days now - including taking an online course in Javascript.

import { useQuery } from "@apollo/client";
import React, { useEffect, useState, Suspense } from 'react'
import { GET_COLLECTIONS } from '../graphql/queries'
import { isEmpty, isNull } from 'lodash'
import { useNavigate } from 'react-router-dom'

async function FetchCollections() {
  let collections;

  //Perform the query to GraphQL API
  let { data, loading, error } = await useQuery(GET_COLLECTIONS);

  //When data is not empty we parse out collections in the response and returns it
  if (!isEmpty(data)) {
    collections = data.collections.collections;
    collections = JSON.parse(collections);
    return await collections;
  } else { console.log("FetchCollections / Waiting for respnse..") }
}

export const Collections = () => {
  const navigate = useNavigate();

  let collections;
  Promise.resolve(FetchCollections())
    .then(data => {
      collections = data;
    });

  let nodes;
  let relationships;

  const ref = React.useRef(null);
  useEffect(() => {
    if (!isEmpty(collections)) {
      nodes = collections.nodes;
      nodes = nodes.join() //Creates a string of the array
      console.log("Nodes fetched : " + nodes)
    }
  }, [collections, navigate])

  return (
    <>
      {console.log("Return : " + nodes)}
      test : {nodes}
    </>
  )
}

Console output:

Return : undefined
Nodes fetched : string1,string2,string3

How can I hold the return (test: {nodes}) until the nodes variable holds data?


问:
Python Sphinx does not generate HTML output
I am new to Sphinx, and have tried to follow the documentation and guidance from books and YouTube videos.
My classes and functions are documented like using autodoc:

```<code>class Person:
'''
This class describes a person
'''
def __init__(self):
    self.name = ''
    self.birth_date = date.today()
    self.gender = ''

def set_date_of_birth(self, year: int, month: int, day: int):
    '''
    Sets the value of the birth date.
    :param year: The year.
    :param month: The month.
    :param day: The day.
    :return: None.
    '''
    self.birth_date = date(year, month, day)
</code>```

After launching sphinx-quickstart and make html afterwards, an index.html is created that only contains empty Index, Module Index, and Search Page, but no reference to the code whatever.

conf.py contains extensions as follows:

```<code>extensions = [ 'sphinx.ext.autodoc',
           'sphinx.ext.doctest',
           'sphinx.ext.intersphinx'
          ]
</code>```

Obviously something is wrong or missing, but what? The test project does not use virtual environment, but a global interpreter instead (Python 3.10, is this of importance?).
The project itself is in PyCharm.
I would be thankful for a working and comprehensible example.

Body:
I am new to Sphinx, and have tried to follow the documentation and guidance from books and YouTube videos.
My classes and functions are documented like using autodoc:

class Person:
'''
This class describes a person
'''
def __init__(self):
    self.name = ''
    self.birth_date = date.today()
    self.gender = ''

def set_date_of_birth(self, year: int, month: int, day: int):
    '''
    Sets the value of the birth date.
    :param year: The year.
    :param month: The month.
    :param day: The day.
    :return: None.
    '''
    self.birth_date = date(year, month, day)

After launching sphinx-quickstart and make html afterwards, an index.html is created that only contains empty Index, Module Index, and Search Page, but no reference to the code whatever.

conf.py contains extensions as follows:

extensions = [ 'sphinx.ext.autodoc',
           'sphinx.ext.doctest',
           'sphinx.ext.intersphinx'
          ]

Obviously something is wrong or missing, but what? The test project does not use virtual environment, but a global interpreter instead (Python 3.10, is this of importance?).
The project itself is in PyCharm.
I would be thankful for a working and comprehensible example.


问:
How to create the timeline for an issue in zube?
I tried to create the sprint in zube(Project Management Tool) but unable to create the timeline for any issues based on which I should see the burn down chart.

I tried to create the sprint in zube(Project Management Tool) but unable to create the timeline for any issues based on which I should see the burn down chart. Expecting to set up the timeline based on which the burndown chart can be visible.


问:
Angular Material (Flat-Tree) to display nested objects in tree structure and enable serach
I have the requirement to display the the following nested objects to display in tree stricture and able to search.(similar to below example)

I searched many examples to achieve this (there are example for the simple tree structure could not find one with multiple nested objects).

I have tried the following but its not working(I have tried nested tree did not work) ,can anyone please help if you came across the scenario.

List of Interfaces

```<code> export interface EXAMPLE1{
  aname:string;
  example2:EXAMPLE2[]
}

export interface EXAMPLE2{
  aname?:string;
  example3:EXAMPLE3[]
}

export interface EXAMPLE3{
  aname:string;
  example4:EXAMPLE4[]
}

export interface EXAMPLE4{
  aname:string;
}
</code>```

tree-view.component.html

```<code><mat-form-field>
  <mat-label>Filter</mat-label>
  <input matInput minlength="2" (keyup)="applyFilter(input.value)" placeholder="Filter" #input>
</mat-form-field>
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <!-- This is the tree node template for leaf nodes -->
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>
    <!-- use a disabled button to provide padding for tree leaf -->
    <button mat-icon-button disabled></button>
    {{node.name}}
  </mat-tree-node>
  <!-- This is the tree node template for expandable nodes -->
  <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding>
    <button mat-icon-button matTreeNodeToggle
            [attr.aria-label]="'Toggle ' + node.name">
      <mat-icon class="mat-icon-rtl-mirror">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.name}}
  </mat-tree-node>
</mat-tree>
</code>```

tree-view.component.ts

```<code>export interface EXAMPLE1{
  aname:string;
  example2:EXAMPLE2[]
}

export interface EXAMPLE2{
  aname?:string;
  example3:EXAMPLE3[]
}

export interface EXAMPLE3{
  aname:string;
  example4:EXAMPLE4[]
}

export interface EXAMPLE4{
  aname:string;
}

const TREE_DATA1: SOModel[] = [
    EXAMPLE1:[
        {
          aname:"example1-Name",
          example2:[
                {
                    aname:"example2-Name",
                    example3: [
                         {
                           aname:"example3-Name",
                           example4:[
                               {
                                   aname:"example4-Name"

                               }
                           ]
                         }
                    ]
                }
          ]
        }
    ];

@Component({
  selector: 'app-tree-view',
  templateUrl: './tree-view.component.html',
  styleUrls: ['./tree-view.component.scss']
})
export class TreeViewComponent {

 // private _transformer = (node: FoodNode, level: number) => {
    private _transformer = (node: SOModel, level: number) => {
    return {
      expandable: !!node.example2 && node.example2.length > 0,
      name: node.aname,
      level: level
    };
  };

  treeControl = new FlatTreeControl<TreeFlatNode>(
    node => node.level,
    node => node.expandable
  );

  treeFlattener = new MatTreeFlattener(
    this._transformer,
    node => node.level,
    node => node.expandable,
    node => node.example2
  );

  dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);

  constructor() {
    this.dataSource.data = TREE_DATA;
  }

  hasChild = (_: number, node: TreeFlatNode) => node.expandable;

  // filter recursively on a text string using property object value
  filterRecursive(filterText: string, array: any[], property: string) {
    let filteredData;

    //make a copy of the data so we don't mutate the original
    function copy(o: any) {
      return Object.assign({}, o);
    }

    // has string
    if (filterText) {
      // need the string to match the property value
      filterText = filterText.toLowerCase();
      // copy obj so we don't mutate it and filter
      filteredData = array.map(copy).filter(function x(y) {
        if (y[property].toLowerCase().includes(filterText)) {
          return true;
        }
        // if children match
        if (y.children) {
          return (y.children = y.children.map(copy).filter(x)).length;
        }
      });
      // no string, return whole array
    } else {
      filteredData = array;
    }

    return filteredData;
  }

  // pass mat input string to recursive function and return data
  filterTree(filterText: string) {
    // use filter input text, return filtered TREE_DATA, use the 'name' object value
    this.dataSource.data = this.filterRecursive(filterText, TREE_DATA, 'name');
  }

  // filter string from mat input filter
  applyFilter(filterText: string) {
    this.filterTree(filterText);
    // show / hide based on state of filter string
    if (filterText) {
      this.treeControl.expandAll();
    } else {
      this.treeControl.collapseAll();
    }
  }

}
</code>```

Body:
I have the requirement to display the the following nested objects to display in tree stricture and able to search.(similar to below example)

I searched many examples to achieve this (there are example for the simple tree structure could not find one with multiple nested objects).

I have tried the following but its not working(I have tried nested tree did not work) ,can anyone please help if you came across the scenario.

List of Interfaces

 export interface EXAMPLE1{
  aname:string;
  example2:EXAMPLE2[]
}

export interface EXAMPLE2{
  aname?:string;
  example3:EXAMPLE3[]
}

export interface EXAMPLE3{
  aname:string;
  example4:EXAMPLE4[]
}

export interface EXAMPLE4{
  aname:string;
}

tree-view.component.html

<mat-form-field>
  <mat-label>Filter</mat-label>
  <input matInput minlength="2" (keyup)="applyFilter(input.value)" placeholder="Filter" #input>
</mat-form-field>
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">

  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>

    <button mat-icon-button disabled></button>
    {{node.name}}
  </mat-tree-node>

  <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding>
    <button mat-icon-button matTreeNodeToggle
            [attr.aria-label]="'Toggle ' + node.name">
      <mat-icon class="mat-icon-rtl-mirror">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.name}}
  </mat-tree-node>
</mat-tree>

tree-view.component.ts

export interface EXAMPLE1{
  aname:string;
  example2:EXAMPLE2[]
}

export interface EXAMPLE2{
  aname?:string;
  example3:EXAMPLE3[]
}

export interface EXAMPLE3{
  aname:string;
  example4:EXAMPLE4[]
}

export interface EXAMPLE4{
  aname:string;
}

const TREE_DATA1: SOModel[] = [
    EXAMPLE1:[
        {
          aname:"example1-Name",
          example2:[
                {
                    aname:"example2-Name",
                    example3: [
                         {
                           aname:"example3-Name",
                           example4:[
                               {
                                   aname:"example4-Name"

                               }
                           ]
                         }
                    ]
                }
          ]
        }
    ];

@Component({
  selector: 'app-tree-view',
  templateUrl: './tree-view.component.html',
  styleUrls: ['./tree-view.component.scss']
})
export class TreeViewComponent {

 // private _transformer = (node: FoodNode, level: number) => {
    private _transformer = (node: SOModel, level: number) => {
    return {
      expandable: !!node.example2 && node.example2.length > 0,
      name: node.aname,
      level: level
    };
  };

  treeControl = new FlatTreeControl<TreeFlatNode>(
    node => node.level,
    node => node.expandable
  );

  treeFlattener = new MatTreeFlattener(
    this._transformer,
    node => node.level,
    node => node.expandable,
    node => node.example2
  );

  dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);

  constructor() {
    this.dataSource.data = TREE_DATA;
  }

  hasChild = (_: number, node: TreeFlatNode) => node.expandable;

  // filter recursively on a text string using property object value
  filterRecursive(filterText: string, array: any[], property: string) {
    let filteredData;

    //make a copy of the data so we don't mutate the original
    function copy(o: any) {
      return Object.assign({}, o);
    }

    // has string
    if (filterText) {
      // need the string to match the property value
      filterText = filterText.toLowerCase();
      // copy obj so we don't mutate it and filter
      filteredData = array.map(copy).filter(function x(y) {
        if (y[property].toLowerCase().includes(filterText)) {
          return true;
        }
        // if children match
        if (y.children) {
          return (y.children = y.children.map(copy).filter(x)).length;
        }
      });
      // no string, return whole array
    } else {
      filteredData = array;
    }

    return filteredData;
  }

  // pass mat input string to recursive function and return data
  filterTree(filterText: string) {
    // use filter input text, return filtered TREE_DATA, use the 'name' object value
    this.dataSource.data = this.filterRecursive(filterText, TREE_DATA, 'name');
  }

  // filter string from mat input filter
  applyFilter(filterText: string) {
    this.filterTree(filterText);
    // show / hide based on state of filter string
    if (filterText) {
      this.treeControl.expandAll();
    } else {
      this.treeControl.collapseAll();
    }
  }

}