问:
Vaadin - Button not doing anything
I have a application developed in Vaadin, SpringBoot and Java running in a docker container.

My problem is that one of the buttons is not doing anything or if it is doing something then I think that an exception is being thrown.

If the last scenario is what indeed is happening, where can I consult my printed messages? Note that my application is being deployed to Tomcat.

In my application I have a view

View

```<code>@Component
@Scope("prototype")
@Route(value = "categories", layout = MainLayout.class)
@PageTitle("Categories | Vaadin CRM")
@PermitAll
public class CategoryView extends VerticalLayout {
    Grid<Category> grid = new Grid<>(Category.class);
    TextField filterText = new TextField();
    CategoryForm form;
    CrmService service;

    public CategoryView(CrmService service) {
        this.service = service;
        addClassName("category-view");
        setSizeFull();
        configureGrid();

        form = new CategoryForm();
        form.setWidth("25em");
        form.addListener(CategoryForm.SaveEvent.class, this::saveCategory);
        form.addListener(CategoryForm.DeleteEvent.class, this::deleteCategory);
        form.addListener(CategoryForm.CloseEvent.class, e -> closeEditor());

        FlexLayout content = new FlexLayout(grid, form);
        content.setFlexGrow(2, grid);
        content.setFlexGrow(1, form);
        content.setFlexShrink(0, form);
        content.addClassNames("content", "gap-m");
        content.setSizeFull();

        add(getToolbar(), content);
        updateList();
        closeEditor();
        grid.asSingleSelect()
                .addValueChangeListener(event -> editCategory(event.getValue()));
    }

    private void configureGrid() {
        grid.addClassNames("category-grid");
        grid.setSizeFull();
        grid.setColumns("description");
        grid.getColumns().forEach(col -> col.setAutoWidth(true));
    }

    private HorizontalLayout getToolbar() {
        filterText.setPlaceholder("Filter by description...");
        filterText.setClearButtonVisible(true);
        filterText.setValueChangeMode(ValueChangeMode.LAZY);
        filterText.addValueChangeListener(e -> updateList());

        Button addCategoryButton = new Button("Add category");
        addCategoryButton.addClickListener(click -> addCategory());

        HorizontalLayout toolbar =
                new HorizontalLayout(filterText, addCategoryButton);
        toolbar.addClassName("toolbar");
        return toolbar;
    }

    private void saveCategory(CategoryForm.SaveEvent event) {
        service.saveCategory(event.getCategory());
        updateList();
        closeEditor();
    }

    private void deleteCategory(CategoryForm.DeleteEvent event) {
        service.deleteCategory(event.getCategory());
        updateList();
        closeEditor();
    }

    public void editCategory(Category category) {
        if (category == null) {
            closeEditor();
        } else {
            form.setCategory(category);
            form.setVisible(true);
            addClassName("editing");
        }
    }

    void addCategory() {
        grid.asSingleSelect().clear();
        editCategory(new Category());
    }

    private void closeEditor() {
        form.setCategory(null);
        form.setVisible(false);
        removeClassName("editing");
    }

    private void updateList() {
        grid.setItems(service.findAllCategories(filterText.getValue()));
    }

}
</code>```

And this view uses a form for when I want to add a category

Form

```<code>public class CategoryForm extends FormLayout {
    TextField description = new TextField("Description");
    Binder<Category> binder = new BeanValidationBinder<>(Category.class);
    Button save = new Button("Save");
    Button delete = new Button("Delete");
    Button close = new Button("Cancel");
    private Category category;

    public CategoryForm() {
        addClassName("category-form");
        binder.bindInstanceFields(this);
        add(description, createButtonsLayout());
    }

    private HorizontalLayout createButtonsLayout() {
        save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
        close.addThemeVariants(ButtonVariant.LUMO_TERTIARY);

        save.addClickShortcut(Key.ENTER);
        close.addClickShortcut(Key.ESCAPE);

        save.addClickListener(event -> validateAndSave());
        delete.addClickListener(
                event -> fireEvent(new DeleteEvent(this, category)));
        close.addClickListener(event -> fireEvent(new CloseEvent(this)));

        binder.addStatusChangeListener(e -> save.setEnabled(binder.isValid()));

        return new HorizontalLayout(save, delete, close);
    }

    public void setCategory(Category category) {
        this.category = category;
        binder.readBean(category);
    }

    private void validateAndSave() {
        try {
            binder.writeBean(category);
            fireEvent(new SaveEvent(this, category));
        } catch (ValidationException e) {
            e.printStackTrace();
            System.err.println("ERRO");
        }
    }

    public <T extends ComponentEvent<?>> Registration addListener(
            Class<T> eventType, ComponentEventListener<T> listener) {
        return getEventBus().addListener(eventType, listener);
    }

    // Events
    public static abstract class CategoryFormEvent
            extends ComponentEvent<CategoryForm> {
        private final Category category;

        protected CategoryFormEvent(CategoryForm source, Category category) {
            super(source, false);
            this.category = category;
        }

        public Category getCategory() {
            return category;
        }
    }

    public static class SaveEvent extends CategoryFormEvent {
        SaveEvent(CategoryForm source, Category category) {
            super(source, category);
        }
    }

    public static class DeleteEvent extends CategoryFormEvent {
        DeleteEvent(CategoryForm source, Category category) {
            super(source, category);
        }

    }

    public static class CloseEvent extends CategoryFormEvent {
        CloseEvent(CategoryForm source) {
            super(source, null);
        }
    }
</code>```

Service

```<code>@Service
public class CrmService {

    private final ContactRepository contactRepository;
    private final CompanyRepository companyRepository;
    private final StatusRepository statusRepository;
    private final CategoryRepository categoryRepository;
    private final CustomerRepository customerRepository;

    public CrmService(ContactRepository contactRepository,
                      CompanyRepository companyRepository,
                      StatusRepository statusRepository,
                      CategoryRepository categoryRepository,
                      CustomerRepository customerRepository){
        this.contactRepository = contactRepository;
        this.companyRepository = companyRepository;
        this.statusRepository = statusRepository;
        this.categoryRepository = categoryRepository;
        this.customerRepository = customerRepository;
    }

     public List<Category> findAllCategories(String stringFilter) {
        if (stringFilter == null || stringFilter.isEmpty()) {
            return categoryRepository.findAll();
        } else {
            return categoryRepository.search(stringFilter);
        }
    }

    public void deleteCategory(Category category) {
        categoryRepository.delete(category);
    }

    public void saveCategory(Category category) {
        if (category == null) {
            System.err.println(
                    "Category is null. Are you sure you have connected your form to the application?");
            return;
        }
        categoryRepository.save(category);
    }
}
</code>```

Repository

```<code>public interface CategoryRepository extends JpaRepository<Category, Integer> {

    @Query("select c from Category c " +
        "where lower(c.description) like lower(concat('%', :searchTerm, '%')) ")
    List<Category> search(@Param("searchTerm") String searchTerm);

}
</code>```

Is there any way to debug what is indeed happening?

Title: Vaadin - Button not doing anything

Body:
I have a application developed in Vaadin, SpringBoot and Java running in a docker container.

My problem is that one of the buttons is not doing anything or if it is doing something then I think that an exception is being thrown.

If the last scenario is what indeed is happening, where can I consult my printed messages? Note that my application is being deployed to Tomcat.

In my application I have a view

View

@Component
@Scope("prototype")
@Route(value = "categories", layout = MainLayout.class)
@PageTitle("Categories | Vaadin CRM")
@PermitAll
public class CategoryView extends VerticalLayout {
    Grid<Category> grid = new Grid<>(Category.class);
    TextField filterText = new TextField();
    CategoryForm form;
    CrmService service;

    public CategoryView(CrmService service) {
        this.service = service;
        addClassName("category-view");
        setSizeFull();
        configureGrid();

        form = new CategoryForm();
        form.setWidth("25em");
        form.addListener(CategoryForm.SaveEvent.class, this::saveCategory);
        form.addListener(CategoryForm.DeleteEvent.class, this::deleteCategory);
        form.addListener(CategoryForm.CloseEvent.class, e -> closeEditor());

        FlexLayout content = new FlexLayout(grid, form);
        content.setFlexGrow(2, grid);
        content.setFlexGrow(1, form);
        content.setFlexShrink(0, form);
        content.addClassNames("content", "gap-m");
        content.setSizeFull();

        add(getToolbar(), content);
        updateList();
        closeEditor();
        grid.asSingleSelect()
                .addValueChangeListener(event -> editCategory(event.getValue()));
    }

    private void configureGrid() {
        grid.addClassNames("category-grid");
        grid.setSizeFull();
        grid.setColumns("description");
        grid.getColumns().forEach(col -> col.setAutoWidth(true));
    }

    private HorizontalLayout getToolbar() {
        filterText.setPlaceholder("Filter by description...");
        filterText.setClearButtonVisible(true);
        filterText.setValueChangeMode(ValueChangeMode.LAZY);
        filterText.addValueChangeListener(e -> updateList());

        Button addCategoryButton = new Button("Add category");
        addCategoryButton.addClickListener(click -> addCategory());

        HorizontalLayout toolbar =
                new HorizontalLayout(filterText, addCategoryButton);
        toolbar.addClassName("toolbar");
        return toolbar;
    }

    private void saveCategory(CategoryForm.SaveEvent event) {
        service.saveCategory(event.getCategory());
        updateList();
        closeEditor();
    }

    private void deleteCategory(CategoryForm.DeleteEvent event) {
        service.deleteCategory(event.getCategory());
        updateList();
        closeEditor();
    }

    public void editCategory(Category category) {
        if (category == null) {
            closeEditor();
        } else {
            form.setCategory(category);
            form.setVisible(true);
            addClassName("editing");
        }
    }

    void addCategory() {
        grid.asSingleSelect().clear();
        editCategory(new Category());
    }

    private void closeEditor() {
        form.setCategory(null);
        form.setVisible(false);
        removeClassName("editing");
    }

    private void updateList() {
        grid.setItems(service.findAllCategories(filterText.getValue()));
    }

}

And this view uses a form for when I want to add a category

Form

public class CategoryForm extends FormLayout {
    TextField description = new TextField("Description");
    Binder<Category> binder = new BeanValidationBinder<>(Category.class);
    Button save = new Button("Save");
    Button delete = new Button("Delete");
    Button close = new Button("Cancel");
    private Category category;

    public CategoryForm() {
        addClassName("category-form");
        binder.bindInstanceFields(this);
        add(description, createButtonsLayout());
    }

    private HorizontalLayout createButtonsLayout() {
        save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
        delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
        close.addThemeVariants(ButtonVariant.LUMO_TERTIARY);

        save.addClickShortcut(Key.ENTER);
        close.addClickShortcut(Key.ESCAPE);

        save.addClickListener(event -> validateAndSave());
        delete.addClickListener(
                event -> fireEvent(new DeleteEvent(this, category)));
        close.addClickListener(event -> fireEvent(new CloseEvent(this)));

        binder.addStatusChangeListener(e -> save.setEnabled(binder.isValid()));

        return new HorizontalLayout(save, delete, close);
    }

    public void setCategory(Category category) {
        this.category = category;
        binder.readBean(category);
    }

    private void validateAndSave() {
        try {
            binder.writeBean(category);
            fireEvent(new SaveEvent(this, category));
        } catch (ValidationException e) {
            e.printStackTrace();
            System.err.println("ERRO");
        }
    }

    public <T extends ComponentEvent<?>> Registration addListener(
            Class<T> eventType, ComponentEventListener<T> listener) {
        return getEventBus().addListener(eventType, listener);
    }

    // Events
    public static abstract class CategoryFormEvent
            extends ComponentEvent<CategoryForm> {
        private final Category category;

        protected CategoryFormEvent(CategoryForm source, Category category) {
            super(source, false);
            this.category = category;
        }

        public Category getCategory() {
            return category;
        }
    }

    public static class SaveEvent extends CategoryFormEvent {
        SaveEvent(CategoryForm source, Category category) {
            super(source, category);
        }
    }

    public static class DeleteEvent extends CategoryFormEvent {
        DeleteEvent(CategoryForm source, Category category) {
            super(source, category);
        }

    }

    public static class CloseEvent extends CategoryFormEvent {
        CloseEvent(CategoryForm source) {
            super(source, null);
        }
    }

Service

@Service
public class CrmService {

    private final ContactRepository contactRepository;
    private final CompanyRepository companyRepository;
    private final StatusRepository statusRepository;
    private final CategoryRepository categoryRepository;
    private final CustomerRepository customerRepository;

    public CrmService(ContactRepository contactRepository,
                      CompanyRepository companyRepository,
                      StatusRepository statusRepository,
                      CategoryRepository categoryRepository,
                      CustomerRepository customerRepository){
        this.contactRepository = contactRepository;
        this.companyRepository = companyRepository;
        this.statusRepository = statusRepository;
        this.categoryRepository = categoryRepository;
        this.customerRepository = customerRepository;
    }

     public List<Category> findAllCategories(String stringFilter) {
        if (stringFilter == null || stringFilter.isEmpty()) {
            return categoryRepository.findAll();
        } else {
            return categoryRepository.search(stringFilter);
        }
    }

    public void deleteCategory(Category category) {
        categoryRepository.delete(category);
    }

    public void saveCategory(Category category) {
        if (category == null) {
            System.err.println(
                    "Category is null. Are you sure you have connected your form to the application?");
            return;
        }
        categoryRepository.save(category);
    }
}

Repository

public interface CategoryRepository extends JpaRepository<Category, Integer> {

    @Query("select c from Category c " +
        "where lower(c.description) like lower(concat('%', :searchTerm, '%')) ")
    List<Category> search(@Param("searchTerm") String searchTerm);

}

Is there any way to debug what is indeed happening?


来源: stackexchange

问:
Trying to manually unwind the callstack using asm and stackdump
I have some stack dump, an elf with debug symbols as well as the original source code. Since this code runs in an embedded environment, and we cannot connect JTAG, the only information we have is the stack dump which is produced by the hard fault handler. I'm trying to reconstruct the callstack from the dump, but something here doesn't add up. Code is running on ARM Cortex M4.

The real callstack:

```<code>Example of a crashing function
time_t calcCurrentTime(void) ->
    uint32_t calcDiff(void) ->
        void voidFunction(void) ->
            void voidFunctionWith1Param(int param) ->
                int intFunction(void) ->
                    int intFunctionWithParam(int param) ->
                        void crashingFunction(void) ->
                            (*nullPtrFunction)(void)()
</code>```

The stack:

On the left, the stack address, on the right the value at that address.

```<code>0xc0e1fe8 0x0000002b, r0
0xc0e1fec 0x0000000a, r1
0xc0e1ff0 0x00026390, r2
0xc0e1ff4 0x00000000, r3
0xc0e1ff8 0x77dd6416, r12
0xc0e1ffc 0x18e1877b, lr
0xc0e2000 0x00000000, pc
0xc0e2004 0x60000000, xpsr
0xc0e2008 0x12000000
0xc0e200c 0x18e18793, lr to crashingFunction
0xc0e2010 0x0000014e
0xc0e2014 0x18e187ab, lr to intFunctionWithParam
0xc0e2018 0x12000000
0xc0e201c 0x18e187c1, lr to intFunction
0xc0e2020 0x12000000
0xc0e2024 0x18e187e3, lr to voidFunctionWith1Param
0xc0e2028 0x00000000
0xc0e202c 0x18e18811, lr to voidFunction
0xc0e2030 0x00000000
0xc0e2034 0x00022d68
0xc0e2038 0x00000000
0xc0e203c 0x18e18837, lr to calcDiff
0xc0e2040 0x00000000
0xc0e2044 0x18e4f899
0xc0e2048 0x00022d68
0xc0e204c 0x00000000
0xc0e2050 0x18e6b00c
0xc0e2054 0x00022d68
0xc0e2058 0x18e0f529, lr to whoever called calcCurrentTime
...
</code>```

The assembly:

```<code>========   void __stdcall crashingFunction(void)   ========

    18e18768 08 b5           push       { r3, lr }
    18e1876a 04 48           ldr        r0, "Entered crashingFunction\r\n"
    18e1876c 44 f0 58 f8     bl         iprintf
    18e18770 03 48           ldr        r0, "About to execute crashing func\r\n"

    18e18772 44 f0 55 f8     bl         iprintf
    18e18776 00 23           movs       r3,#0x0
    18e18778 98 47           blx        r3
    18e1877a 08 bd           pop        { r3, pc }

========   int __stdcall intFunctionWithParam(int param)   ========

    18e18784 10 b5           push       { r4, lr }
    18e18786 04 46           mov        r4,r0
    18e18788 03 48           ldr        r0, "Entered intFunctionWithParam\r\n"

    18e1878a 44 f0 49 f8     bl         iprintf
    18e1878e ff f7 eb ff     bl         crashingFunction
    18e18792 60 1d           adds       r0,r4,#0x5
    18e18794 10 bd           pop        { r4, pc }

========   int __stdcall intFunction(void)   ========

    18e1879c 10 b5           push       { r4, lr }
    18e1879e 84 b0           sub        sp,#0x10
    18e187a0 0d 48           ldr        r0, "Entered intFunction\r\n"
    18e187a2 44 f0 3d f8     bl         iprintf
    18e187a6 02 23           movs       r3,#0x2
    18e187a8 01 93           str        r3,[sp,#arr[0]]
    18e187aa 05 23           movs       r3,#0x5
    18e187ac 02 93           str        r3,[sp,#arr[1]]
    18e187ae 01 20           movs       r0,#0x1
    18e187b0 ff f7 e8 ff     bl         intFunctionWithParam
    18e187b4 03 90           str        r0,[sp,#arr[2]]
    18e187b6 00 24           movs       r4,#0x0
    18e187b8 08 e0           b          loopEnd
loopStart:
    18e187ba 04 ab           add        r3,sp,#0x10
    18e187bc 03 eb 84 03     add.w      r3,r3,r4, lsl #0x2
    18e187c0 53 f8 0c 1c     ldr.w      r1,[r3,#-0xc]
    18e187c4 05 48           ldr        r0, "Got value: %d"

    18e187c6 44 f0 2b f8     bl         iprintf
    18e187ca 01 34           adds       r4,#0x1
loopEnd:
    18e187cc 02 2c           cmp        r4,#0x2
    18e187ce f4 dd           ble        loopStart
    18e187d0 0a 20           movs       r0,#0xa
    18e187d2 04 b0           add        sp,#0x10
    18e187d4 10 bd           pop        { r4, pc }

========   void __stdcall voidFunctionWith1Param(int param)   ========

    18e187e0 08 b5           push       { r3, lr }
    18e187e2 05 48           ldr        r0, "Entered voidFunctionWith1Param\r\n"

    18e187e4 44 f0 1c f8     bl         iprintf
    18e187e8 ff f7 d8 ff     bl         intFunction
    18e187ec 01 46           mov        r1,r0
    18e187ee 03 48           ldr        r0, "Result from a is %d\r\n"

    18e187f0 44 f0 16 f8     bl         iprintf
    18e187f4 08 bd           pop        { r3, pc }

========   void __stdcall voidFunction(void)   ========

    18e18800    push       { r3, lr }
    18e18802    ldr        r0, "Entered voidFunction\r\n"

    18e18804    bl         iprintf
    18e18808    movs       r0,#0x1
    18e1880a    bl         voidFunctionWith1Param
    18e1880e    ldr        r0, "Done!"

    18e18810    bl         iprintf
    18e18814    pop        { r3, pc }

========   uint __stdcall calcDiff(void)   ========

    18e18820 38 b5           push       { r3, r4, r5, lr }
    18e18822 e8 f7 e7 ff     bl         notRelatedFunc             ; Saves milliseconds to r3
    18e18826 0a 4d           ldr        r5,[0x18e18850]            ; r5 = 1000
    18e18828 a5 fb 00 30     umull      r3,r0,r5,r0
    18e1882c 84 09           lsrs       r4,r0,#0x6                 ; miliseconds / 1000
    18e1882e 09 4b           ldr        r3,[0x18e18854]
    18e18830 18 68           ldr        r0,[r3,#0x0]               ; globalVariable
    18e18832 a5 fb 00 30     umull      r3,r0,r5,r0
    18e18836 85 09           lsrs       r5,r0,#0x6                 ; globalVariable / 1000
    18e18838 ff f7 e2 ff     bl         voidFunction
    18e1883c ac 42           cmp        r4,r5
    18e1883e 05 d8           bhi        notRelatedFunc2
    ...

</code>```

The questions:

LR to calcCurrentTime was lost. How is this possible?

To get to the next LR from 0xc0e202c we had to add 16, not 8. Despite voidFunction being the most unremarkable function of the bunch. It has no variables defined on the stack. So why is there such a gap in the stack?

I'm trying to figure out the rules in order to manually unwind the call stack.

Thank you.

ContentLicense: CC BY-SA 4.0

Body:
I have some stack dump, an elf with debug symbols as well as the original source code. Since this code runs in an embedded environment, and we cannot connect JTAG, the only information we have is the stack dump which is produced by the hard fault handler. I'm trying to reconstruct the callstack from the dump, but something here doesn't add up. Code is running on ARM Cortex M4.

The real callstack:

Example of a crashing function
time_t calcCurrentTime(void) ->
    uint32_t calcDiff(void) ->
        void voidFunction(void) ->
            void voidFunctionWith1Param(int param) ->
                int intFunction(void) ->
                    int intFunctionWithParam(int param) ->
                        void crashingFunction(void) ->
                            (*nullPtrFunction)(void)()

The stack:

On the left, the stack address, on the right the value at that address.

0xc0e1fe8 0x0000002b, r0
0xc0e1fec 0x0000000a, r1
0xc0e1ff0 0x00026390, r2
0xc0e1ff4 0x00000000, r3
0xc0e1ff8 0x77dd6416, r12
0xc0e1ffc 0x18e1877b, lr
0xc0e2000 0x00000000, pc
0xc0e2004 0x60000000, xpsr
0xc0e2008 0x12000000
0xc0e200c 0x18e18793, lr to crashingFunction
0xc0e2010 0x0000014e
0xc0e2014 0x18e187ab, lr to intFunctionWithParam
0xc0e2018 0x12000000
0xc0e201c 0x18e187c1, lr to intFunction
0xc0e2020 0x12000000
0xc0e2024 0x18e187e3, lr to voidFunctionWith1Param
0xc0e2028 0x00000000
0xc0e202c 0x18e18811, lr to voidFunction
0xc0e2030 0x00000000
0xc0e2034 0x00022d68
0xc0e2038 0x00000000
0xc0e203c 0x18e18837, lr to calcDiff
0xc0e2040 0x00000000
0xc0e2044 0x18e4f899
0xc0e2048 0x00022d68
0xc0e204c 0x00000000
0xc0e2050 0x18e6b00c
0xc0e2054 0x00022d68
0xc0e2058 0x18e0f529, lr to whoever called calcCurrentTime
...

The assembly:

========   void __stdcall crashingFunction(void)   ========

    18e18768 08 b5           push       { r3, lr }
    18e1876a 04 48           ldr        r0, "Entered crashingFunction\r\n"
    18e1876c 44 f0 58 f8     bl         iprintf
    18e18770 03 48           ldr        r0, "About to execute crashing func\r\n"

    18e18772 44 f0 55 f8     bl         iprintf
    18e18776 00 23           movs       r3,#0x0
    18e18778 98 47           blx        r3
    18e1877a 08 bd           pop        { r3, pc }

========   int __stdcall intFunctionWithParam(int param)   ========

    18e18784 10 b5           push       { r4, lr }
    18e18786 04 46           mov        r4,r0
    18e18788 03 48           ldr        r0, "Entered intFunctionWithParam\r\n"

    18e1878a 44 f0 49 f8     bl         iprintf
    18e1878e ff f7 eb ff     bl         crashingFunction
    18e18792 60 1d           adds       r0,r4,#0x5
    18e18794 10 bd           pop        { r4, pc }

========   int __stdcall intFunction(void)   ========

    18e1879c 10 b5           push       { r4, lr }
    18e1879e 84 b0           sub        sp,#0x10
    18e187a0 0d 48           ldr        r0, "Entered intFunction\r\n"
    18e187a2 44 f0 3d f8     bl         iprintf
    18e187a6 02 23           movs       r3,#0x2
    18e187a8 01 93           str        r3,[sp,#arr[0]]
    18e187aa 05 23           movs       r3,#0x5
    18e187ac 02 93           str        r3,[sp,#arr[1]]
    18e187ae 01 20           movs       r0,#0x1
    18e187b0 ff f7 e8 ff     bl         intFunctionWithParam
    18e187b4 03 90           str        r0,[sp,#arr[2]]
    18e187b6 00 24           movs       r4,#0x0
    18e187b8 08 e0           b          loopEnd
loopStart:
    18e187ba 04 ab           add        r3,sp,#0x10
    18e187bc 03 eb 84 03     add.w      r3,r3,r4, lsl #0x2
    18e187c0 53 f8 0c 1c     ldr.w      r1,[r3,#-0xc]
    18e187c4 05 48           ldr        r0, "Got value: %d"

    18e187c6 44 f0 2b f8     bl         iprintf
    18e187ca 01 34           adds       r4,#0x1
loopEnd:
    18e187cc 02 2c           cmp        r4,#0x2
    18e187ce f4 dd           ble        loopStart
    18e187d0 0a 20           movs       r0,#0xa
    18e187d2 04 b0           add        sp,#0x10
    18e187d4 10 bd           pop        { r4, pc }

========   void __stdcall voidFunctionWith1Param(int param)   ========

    18e187e0 08 b5           push       { r3, lr }
    18e187e2 05 48           ldr        r0, "Entered voidFunctionWith1Param\r\n"

    18e187e4 44 f0 1c f8     bl         iprintf
    18e187e8 ff f7 d8 ff     bl         intFunction
    18e187ec 01 46           mov        r1,r0
    18e187ee 03 48           ldr        r0, "Result from a is %d\r\n"

    18e187f0 44 f0 16 f8     bl         iprintf
    18e187f4 08 bd           pop        { r3, pc }

========   void __stdcall voidFunction(void)   ========

    18e18800    push       { r3, lr }
    18e18802    ldr        r0, "Entered voidFunction\r\n"

    18e18804    bl         iprintf
    18e18808    movs       r0,#0x1
    18e1880a    bl         voidFunctionWith1Param
    18e1880e    ldr        r0, "Done!"

    18e18810    bl         iprintf
    18e18814    pop        { r3, pc }

========   uint __stdcall calcDiff(void)   ========

    18e18820 38 b5           push       { r3, r4, r5, lr }
    18e18822 e8 f7 e7 ff     bl         notRelatedFunc             ; Saves milliseconds to r3
    18e18826 0a 4d           ldr        r5,[0x18e18850]            ; r5 = 1000
    18e18828 a5 fb 00 30     umull      r3,r0,r5,r0
    18e1882c 84 09           lsrs       r4,r0,#0x6                 ; miliseconds / 1000
    18e1882e 09 4b           ldr        r3,[0x18e18854]
    18e18830 18 68           ldr        r0,[r3,#0x0]               ; globalVariable
    18e18832 a5 fb 00 30     umull      r3,r0,r5,r0
    18e18836 85 09           lsrs       r5,r0,#0x6                 ; globalVariable / 1000
    18e18838 ff f7 e2 ff     bl         voidFunction
    18e1883c ac 42           cmp        r4,r5
    18e1883e 05 d8           bhi        notRelatedFunc2
    ...

The questions:

LR to calcCurrentTime was lost. How is this possible?

To get to the next LR from 0xc0e202c we had to add 16, not 8. Despite voidFunction being the most unremarkable function of the bunch. It has no variables defined on the stack. So why is there such a gap in the stack?

I'm trying to figure out the rules in order to manually unwind the call stack.

Thank you.


问:
How do I style an element based on a sibling with the same parent, that comes after it?
So, there is a page that has a structure like this:

<video id="need_to_select"></video>

```
<p>I want to style the video element based on a class of an element which has the same parent. Problem is, the element with the class comes after the video element.</p>
<p>I know that</p>
<pre class="lang-css prettyprint-override"><code>.some_class ~ video {}
</code>```

doesn't work, because the video element comes before the class. Neither does

video ~ .some_class {}
```

because only the element with the class is styled and not the video.

So how do I go about styling the video based on the class?

Body:
So, there is a page that has a structure like this:

<video id="need_to_select"></video>

I want to style the video element based on a class of an element which has the same parent. Problem is, the element with the class comes after the video element.

I know that

.some_class ~ video {}

doesn't work, because the video element comes before the class. Neither does

video ~ .some_class {}

because only the element with the class is styled and not the video.

So how do I go about styling the video based on the class?


问:
keptn get upstream repository not found error while creating project
I'm trying to work with Keptn but When i'm trying to create a keptn project with a git remote repository, i'm getting the error

```<code>The project could not be created: upstream repository not found.
</code>```

Fisrt, the repo i've created is completly empty. And when i use the same repo with the same token key in a online keptn tutorial, it works there.

I follow all the instructions in keptn website but i don't understand where the problem come from.

Body:
I'm trying to work with Keptn but When i'm trying to create a keptn project with a git remote repository, i'm getting the error

The project could not be created: upstream repository not found.

Fisrt, the repo i've created is completly empty. And when i use the same repo with the same token key in a online keptn tutorial, it works there.

I follow all the instructions in keptn website but i don't understand where the problem come from.


问:
streaming two react components using renderToPipeableStream
I am trying to stream an html page with two react components

```<code>HomeHeaderComponent and HomeSearchComponent
</code>```

, only the first part of the html has been render to the browser along with the first component

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

having issue streaming and rendering rest of content

Im expecting to have the rest of the content be rendered see code below

```<code>import { fileURLToPath } from 'url'
import { dirname } from 'path'
import React from "react";
import { renderToPipeableStream } from "react-dom/server";
import pug from 'pug';
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
import HomeSearchComponent from "../../client/home/home-search";
import HomeHeaderComponent from "../../client/home/home-header";

function StreamComponent(res, Component) {
  return new Promise((resolve, reject)=> {
    let stream = renderToPipeableStream(<Component />, {
      onShellReady() {
        stream.pipe(res)
      },
      onShellError(err){
        console.log('error')
        reject(err)
      },
      onError(err) {
        console.log('error')
        reject(err)
      },
      onAllReady() {
        resolve("component stream complete")
      }
    })
  })
}

async function Home(req, res, next) {
  let protocol = process.env.NODE_ENV === "development" ? "http" : "https";
  let url = protocol + "://" + req.get("host");

  const compiledFunction = pug.compileFile(__dirname + "/home.pug");
  let html = compiledFunction({ url });
  let parts = html.toString().split("<!--component-->"); // html split into 3 parts

  res.write(parts[0]);

  await StreamComponent(res, HomeHeaderComponent).catch((err)=> { next(err) });

  res.write(parts[1]);

  await StreamComponent(res, HomeSearchComponent).catch((err)=> { next(err) });

  res.write(parts[2]);

  res.end();

}

export default Home;

</code>```

Body:
I am trying to stream an html page with two react components

HomeHeaderComponent and HomeSearchComponent

, only the first part of the html has been render to the browser along with the first component

HomeHeaderComponent

having issue streaming and rendering rest of content

Im expecting to have the rest of the content be rendered see code below

import { fileURLToPath } from 'url'
import { dirname } from 'path'
import React from "react";
import { renderToPipeableStream } from "react-dom/server";
import pug from 'pug';
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
import HomeSearchComponent from "../../client/home/home-search";
import HomeHeaderComponent from "../../client/home/home-header";

function StreamComponent(res, Component) {
  return new Promise((resolve, reject)=> {
    let stream = renderToPipeableStream(<Component />, {
      onShellReady() {
        stream.pipe(res)
      },
      onShellError(err){
        console.log('error')
        reject(err)
      },
      onError(err) {
        console.log('error')
        reject(err)
      },
      onAllReady() {
        resolve("component stream complete")
      }
    })
  })
}

async function Home(req, res, next) {
  let protocol = process.env.NODE_ENV === "development" ? "http" : "https";
  let url = protocol + "://" + req.get("host");

  const compiledFunction = pug.compileFile(__dirname + "/home.pug");
  let html = compiledFunction({ url });
  let parts = html.toString().split(""); // html split into 3 parts

  res.write(parts[0]);

  await StreamComponent(res, HomeHeaderComponent).catch((err)=> { next(err) });

  res.write(parts[1]);

  await StreamComponent(res, HomeSearchComponent).catch((err)=> { next(err) });

  res.write(parts[2]);

  res.end();

}

export default Home;


问:
Hibernate not creating table in MySQL (IntelliJ/SpringBoot/Maven)
I have no clue why my Hibernate ORM is not automatically creating a table.. I have successfully established a MySQL connection.

These are the dependencies:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.authenticatie</groupId>
    <artifactId>authenticatie</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>authenticatie</name>
    <description>Backend authenticatie</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>18</source>
                    <target>18</target>
                </configuration>
            </plugin>
</code>```

This is the Entity:

```<code>import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.*;

@Entity
public class Postzegel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private int prijs;
    //    private Image;
    public Postzegel() {
    }

    public Postzegel(int Id, int Prijs) {
        this.id = Id;
        this.prijs = Prijs;
    }

    public int getId() {
        return id;
    }

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

    public int getPrijs() {
        return prijs;
    }

    public void setPrijs(int prijs) {
        this.prijs = prijs;
    }
}
</code>```

This is the application properties:

```<code>#configuration
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3307/pakketjesauthenticatiedb
spring.datasource.username=pakketjesauthenticatiedb
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
</code>```

I don't really know witch information I have to provide to be able to find a solution, I will add a photo showing the successful connection with the database.

Body:
I have no clue why my Hibernate ORM is not automatically creating a table.. I have successfully established a MySQL connection.

These are the dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/>
    </parent>
    <groupId>com.authenticatie</groupId>
    <artifactId>authenticatie</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>authenticatie</name>
    <description>Backend authenticatie</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>18</source>
                    <target>18</target>
                </configuration>
            </plugin>

This is the Entity:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.*;

@Entity
public class Postzegel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private int prijs;
    //    private Image;
    public Postzegel() {
    }

    public Postzegel(int Id, int Prijs) {
        this.id = Id;
        this.prijs = Prijs;
    }

    public int getId() {
        return id;
    }

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

    public int getPrijs() {
        return prijs;
    }

    public void setPrijs(int prijs) {
        this.prijs = prijs;
    }
}

This is the application properties:

#configuration
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3307/pakketjesauthenticatiedb
spring.datasource.username=pakketjesauthenticatiedb
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

I don't really know witch information I have to provide to be able to find a solution, I will add a photo showing the successful connection with the database.


问:
How to display a pandas dataframe in tkinter
I have a pandas dataframe which consists of a html table scraped from the web. I would like to display this dataframe in Tkinter. How would  be able to do this? I was thinking maybe the use of treeview, but I'm not sure how to specifically display a dataframe using treeview. If it's the case where I cannot display a pandas dataframe or it's too complicated for me because I'm very new to pandas dataframes, would it be better to store my scraped html table in a different format (instead of a dataframe) that would be easier to display in tkinter? Thanks in advance</p>


问:
Setting image quality using UIGraphicsPDFRenderer
Trying to add a Aztec barcode to a PDF using UIGraphicsPDFRenderer my issue is that the result is blurry thought the fix was setting interpolationQuality, Thanks for your help.</p>
```<code>  let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 70.8661, height: 70.8661))

    return renderer.pdfData{ ctx in

            ctx.beginPage()
            ctx.cgContext.interpolationQuality = .none //Doesn't do anything

            let barcode = generateQRCode(from: UUID().description)
            barcode.draw(in: CGRect(x: 0, y: 0, width: 70.8661, height: 70.8661))

    }

   func generateQRCode(from string: String) -> UIImage {
       filter.message = Data(string.utf8)

       if let outputImage = filter.outputImage {
           if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) {
                return  UIImage(cgImage: cgimg)
           }
       }

    return UIImage()
  }
</code>```

Body:
Trying to add a Aztec barcode to a PDF using UIGraphicsPDFRenderer my issue is that the result is blurry thought the fix was setting interpolationQuality, Thanks for your help.

  let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 70.8661, height: 70.8661))

    return renderer.pdfData{ ctx in

            ctx.beginPage()
            ctx.cgContext.interpolationQuality = .none //Doesn't do anything

            let barcode = generateQRCode(from: UUID().description)
            barcode.draw(in: CGRect(x: 0, y: 0, width: 70.8661, height: 70.8661))

    }

   func generateQRCode(from string: String) -> UIImage {
       filter.message = Data(string.utf8)

       if let outputImage = filter.outputImage {
           if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) {
                return  UIImage(cgImage: cgimg)
           }
       }

    return UIImage()
  }


Title: How to copy a list of lists?

Body:
I need A to be a copy of C
How can I copy nested lists?

Attempt:

b = [["1","1","1"],["1","1","1"],["1","1","1"]]
c = [["2","2","2"],["2","2","2"],["2","2","2"]]
a = c.copy()

Result:

'list' object has no attribute 'copy'

a = c does not work

Attempt:

b = [["1","1","1"],["1","1","1"],["1","1","1"]]
c = [["2","2","2"],["2","2","2"],["2","2","2"]]
a = c
for y in range(0,3):
  for x in range(0,3):
    c[x][y] = b[2-x][2-y]
print(a)

Result:

[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']]


问:
Why does TypeScript think that string union is any string when used as a key?
Trying to use a union of strings as a key:

```<code>type Union = 'yes' | 'no'
const fn = (t: Union) => {
    const x: Record<Union, string> = { [t]: 'test' }
}
</code>```

Results in an error:

```<code>Type '{ [x: string]: string; }' is missing the following properties from type 'Record<Union, string>': yes, no
</code>```

Playground

I would expect that type of this expression:

```<code>{ [t]: 'test' }
</code>```

Is:

```<code>{ [x in Union]: string; }
</code>```

And not

```<code>{ [x: string]: string; }
</code>```

Body:
Trying to use a union of strings as a key:

type Union = 'yes' | 'no'
const fn = (t: Union) => {
    const x: Record<Union, string> = { [t]: 'test' }
}

Results in an error:

Type '{ [x: string]: string; }' is missing the following properties from type 'Record<Union, string>': yes, no

Playground

I would expect that type of this expression:

{ [t]: 'test' }

Is:

{ [x in Union]: string; }

And not

{ [x: string]: string; }


问:
Why does React render functional component and JSX element differently?
When I assign a React component like this...

<MaterialTable components={{ Toolbar: props => <CustomToolbar {...props} /> }} />
```
<p>...or like this...</p>
<pre class="lang-js prettyprint-override"><code><MaterialTable components={{ Toolbar: props => CustomToolbar(props) }} />
</code>```

...it appears that React renders it differently than if it was assigned like this

<MaterialTable components={{ Toolbar: CustomToolbar }} />
```

Instructions to reproduce it:

Go to this codesandbox

Select a row from the table, then click on the button at the top right. The dropdown menu will pop-up on the top left of the page rather than near the button.

Comment out line 56, then uncomment line 54, then repeat the previous step. Now the dropdown menu will pop-up near the button, as expected.

I believe this happens because the dropdown menu loses the reference to the button when its parent (the toolbar) is rendered.

Any idea how to overcome this?

Body:
When I assign a React component like this...

<MaterialTable components={{ Toolbar: props => <CustomToolbar {...props} /> }} />

...or like this...

<MaterialTable components={{ Toolbar: props => CustomToolbar(props) }} />

...it appears that React renders it differently than if it was assigned like this

<MaterialTable components={{ Toolbar: CustomToolbar }} />

Instructions to reproduce it:

Go to this codesandbox

Select a row from the table, then click on the button at the top right. The dropdown menu will pop-up on the top left of the page rather than near the button.

Comment out line 56, then uncomment line 54, then repeat the previous step. Now the dropdown menu will pop-up near the button, as expected.

I believe this happens because the dropdown menu loses the reference to the button when its parent (the toolbar) is rendered.

Any idea how to overcome this?


问:
How to get the value of searchBar.text of one VC and use it in another file of the project in swift?
I've been looking for the answer everywhere and could't find any.. Is there any way I can access the value of searchBar.text in another file? I have the delegate set in my SearchVC but I also have a custom tableView cell in another file.

I need the value of the SearchBar of my SearchVC to use in FirstDefinitionVC for decoding the word from the searchBar and use it for finding the audio URL.

All works fine while I call the function inside the searchBarSearchButtonClicked method but I can find no way to pass that String into FirstDefintionVC.

The relevant searchVC code :
var word = ""
`

```<code>extension SearchVC: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        // { (data: [WordData], [Definitions])
        word = searchBar.text!
        wordManager.performRequest(word: word) { data in
            self.wordData = data
            self.searchButtonPressed = true
            //                print(data)
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        fetchAudio(word: word) { data in   //this one works fine
            DispatchQueue.main.async {
                self.wordData = data
            }
        }
    }

    func fetchAudio(word: String, comp: @escaping ([WordData])-> Void) {
        let wordURL = "https://api.dictionaryapi.dev/api/v2/entries/en/"
        let urlString = "\(wordURL)\(word)"

        if let url = URL(string: urlString) {
            let dataTask = URLSession.shared.dataTask(with: url, completionHandler: {
                (data,response,error) in
                guard let data = data, error == nil else {
                    print("Error occured while accessing data with URL")
                    return
                }

                do {
                    let decoded = try JSONDecoder().decode([WordData].self, from: data)
                    comp(decoded)
                    if let sound = decoded[0].phonetics[0].audio,
                       let sound2 = decoded[0].phonetics[1].audio {
                        print("sound = \(sound)")
                        let nonEmpty = (sound != "") ? sound : sound2 //write switch cases or another ternary with more urls to choose from if both are empty
                        self.audioUrl = URL(string: nonEmpty)
                        //            url = URL(string: sound2)

                        do {
                            try AVAudioSession.sharedInstance().setMode(.default)
                            try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)

                            self.player = AVPlayer(url: self.audioUrl!)

                            guard let player = self.player else { return }

                            player.play()
                        } catch let error {
                            print(error.localizedDescription)
                        }

                    }
                    //comp(decoded, entries.self)
                } catch {
                    print("Error occured while decoding JSON into Swift structure \(error)")
                }
            })
            dataTask.resume()
        }
    }
</code>```

I need to call the searchBar.text value in another file inside this IBAction of class FirstDefinitionVC:
`

```<code>   @IBAction func pronunciationButton(_ sender: UIButton) {

        searchVC.fetchAudio(word: searchVC.word) { data in
            self.wordData = data
        }
    }
</code>```

This was one of my approaches to this, I tried to create a global model Word with an initializer also and it didn't work. Is there any way around it?

Body:
I've been looking for the answer everywhere and could't find any.. Is there any way I can access the value of searchBar.text in another file? I have the delegate set in my SearchVC but I also have a custom tableView cell in another file.

I need the value of the SearchBar of my SearchVC to use in FirstDefinitionVC for decoding the word from the searchBar and use it for finding the audio URL.

All works fine while I call the function inside the searchBarSearchButtonClicked method but I can find no way to pass that String into FirstDefintionVC.

The relevant searchVC code :
var word = ""
`

extension SearchVC: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        // { (data: [WordData], [Definitions])
        word = searchBar.text!
        wordManager.performRequest(word: word) { data in
            self.wordData = data
            self.searchButtonPressed = true
            //                print(data)
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        fetchAudio(word: word) { data in   //this one works fine
            DispatchQueue.main.async {
                self.wordData = data
            }
        }
    }

    func fetchAudio(word: String, comp: @escaping ([WordData])-> Void) {
        let wordURL = "https://api.dictionaryapi.dev/api/v2/entries/en/"
        let urlString = "\(wordURL)\(word)"

        if let url = URL(string: urlString) {
            let dataTask = URLSession.shared.dataTask(with: url, completionHandler: {
                (data,response,error) in
                guard let data = data, error == nil else {
                    print("Error occured while accessing data with URL")
                    return
                }

                do {
                    let decoded = try JSONDecoder().decode([WordData].self, from: data)
                    comp(decoded)
                    if let sound = decoded[0].phonetics[0].audio,
                       let sound2 = decoded[0].phonetics[1].audio {
                        print("sound = \(sound)")
                        let nonEmpty = (sound != "") ? sound : sound2 //write switch cases or another ternary with more urls to choose from if both are empty
                        self.audioUrl = URL(string: nonEmpty)
                        //            url = URL(string: sound2)

                        do {
                            try AVAudioSession.sharedInstance().setMode(.default)
                            try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)

                            self.player = AVPlayer(url: self.audioUrl!)

                            guard let player = self.player else { return }

                            player.play()
                        } catch let error {
                            print(error.localizedDescription)
                        }

                    }
                    //comp(decoded, entries.self)
                } catch {
                    print("Error occured while decoding JSON into Swift structure \(error)")
                }
            })
            dataTask.resume()
        }
    }

I need to call the searchBar.text value in another file inside this IBAction of class FirstDefinitionVC:
`

   @IBAction func pronunciationButton(_ sender: UIButton) {

        searchVC.fetchAudio(word: searchVC.word) { data in
            self.wordData = data
        }
    }

This was one of my approaches to this, I tried to create a global model Word with an initializer also and it didn't work. Is there any way around it?


问:
chrome.webRequest.onBeforeRequest didn't work in manifest version 3
In my chrome extension with manifest V2 I was using chrome.webRequest.onBeforeRequest to get all requests of current tab. Here is

const dataSet = {};
chrome.webRequest.onBeforeRequest.addListener(function (details) {

    if (details && details.url && details.type == "image") {
        if (!dataSet[tabId]) {
            dataSet[tabId] = new Set([]);
        }
        const currentSet = dataSet[tabId];
        currentSet.add(details.url);
    }

}, {
    urls: ["<all_urls>"]
});
```
<p>I'm trying same code in manifest version 3 but event didn't triggers. Also I've tried this workaround but it still didn't works.</p>
<pre class="lang-js prettyprint-override"><code>chrome.webNavigation.onBeforeNavigate.addListener(function(){

   // this event is not being triggered
   chrome.webRequest.onBeforeRequest.addListener(function(details){

   },{urls: ["<all_urls>"],types: ["main_frame"]});

},{
    url: [{hostContains:"domain"}]
});
</code>```

Also tried to use webNavigation.onHistoryStateUpdated but still onBeforeRequest didn't triggers

chrome.webNavigation.onHistoryStateUpdated.addListener((details) => {
    console.log('wake me up', details);
    chrome.webRequest.onBeforeRequest.addListener(
        (details) => {
          console.log(details);
        },
        {
          urls: ['<all_urls>'],

        },

      );
  });
```

Console output of background page

Body:
In my chrome extension with manifest V2 I was using chrome.webRequest.onBeforeRequest to get all requests of current tab. Here is

const dataSet = {};
chrome.webRequest.onBeforeRequest.addListener(function (details) {

    if (details && details.url && details.type == "image") {
        if (!dataSet[tabId]) {
            dataSet[tabId] = new Set([]);
        }
        const currentSet = dataSet[tabId];
        currentSet.add(details.url);
    }

}, {
    urls: ["<all_urls>"]
});

I'm trying same code in manifest version 3 but event didn't triggers. Also I've tried this workaround but it still didn't works.

chrome.webNavigation.onBeforeNavigate.addListener(function(){

   // this event is not being triggered
   chrome.webRequest.onBeforeRequest.addListener(function(details){

   },{urls: ["<all_urls>"],types: ["main_frame"]});

},{
    url: [{hostContains:"domain"}]
});

Also tried to use webNavigation.onHistoryStateUpdated but still onBeforeRequest didn't triggers

chrome.webNavigation.onHistoryStateUpdated.addListener((details) => {
    console.log('wake me up', details);
    chrome.webRequest.onBeforeRequest.addListener(
        (details) => {
          console.log(details);
        },
        {
          urls: ['<all_urls>'],

        },

      );
  });

Console output of background page


问:
Clipping a 3d triangle with one vertex behind the camera
I'm working on a 3D renderer in MS-DOS in C, and I'm trying to fill 3D triangles onto the screen.

Here's a screenshot of it working.

It works fine, but when one vertex is behind the near clipping plane, it starts looking like this.

Or maybe this,

or this.

I understand when one vertex is behind the camera, the original triangle is split into two. When I tried to recreate this procedure, the program draws the triangles incorrectly. I'd like to show you my steps for rendering the triangle.

Step 1: For each three vertices of the triangle, the camera will move to (0, 0, 0) and will face 0 degrees for both the yaw and pitch. The vertex will be translated and rotated along with it.

Step 2: Check if the vertex is behind the near clipping plane (z = 0.01). If so, increment "behindZ". Go back to step 1 unless all 3 vertices are tested.

Step 3: Now that the program has tested all 3 of the vertices, if behindZ < 3, go to step 4. Otherwise, quit the whole rendering process.

Step 4: Check if behindZ equals 0, 1, or 2. Let's say it equals 1. Then the program sets the coordinates for the two visible vertices on the screen. For the vertex that's behind the near clipping plane, convert those to two vertices that intersect the z = 0.01 line.

Step 5: Render the two triangles: A triangle with the vertices 0, 1, & 2, and a triangle with 0, 2, & 3.

If those steps are too vague, I'd be happy to share my source code. I think my problem has to do with step 4. How do I fix it?


问:
Wordpress - How to create dynamic affiliate link that includes page title
What's up team,

What I'm trying to achieve in wordpress is add a dynamic affiliate link that includes the page title which leads to an external website's search page.

For example.

The post page or page  is called   www.website.com/blog/red-ball  or www.website.com/red-ball
And I want to add a link to an affiliate's search page using the page's title. So I need the dynamic url to look like this www.affiliate.com/search?=red-ball

Now I dont have a problem doing this manually. But if I have 5 different affiliates and 1000 products, i really dont want to be going to each page and doing this one by one. What im looking for is to add a button preferably thru a shortcode that will add a button to the page for a specific affiliate with his url and the button automatically appends the page title to it.
This way I can add 5, 6, 7 or how many other affiliate partners I want and the button will lead to the partners affiliate search page automatically querying my page keywords.

Anyone have an solution or idea on how to do this?
Thank you,
Red


问:
calling php function in same file
Am calling 2 functions and 1 through script

```<code><function1>
<function2>

.... calling script....
</code>```

```<code><script language="javascript">

 function showModelNewCar(str)
 {
    url = "getmodel.php?s="+str;
    getRequest(url,"txtHint");
 }
</script>
</code>```

and executing in search page

```<code><select name="brand" class="list-box" id="brand"  lang="" title="Brand" onchange="showModelNewCar(this.value)" required>
                <option value="" selected="selected" style='padding-left:10px;'>Select Make</option>
                <?php echo brand_drop_down();?>

              </select>
                    </div>
                    <div class="search-box-left">Model </div>
                    <div class="search-box-right">
                    <div id="txtHint">
                    <select name="model" class="list-box"  id="model"  lang="" title="Model">
                     <option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
                     <?php //echo $this->model;?>
                    </select>
</code>```

Now i dont intend to use in getmodel.php in a separate file, rather add that function in this file only

```<code>    <function1>
    <function2>
function showModelNewCar(){
   .......entire function pasted......
    $list.='</select>';
}

<script type="text/javascript" src="ajax.js"></script>
    <select name="brand" class="list-box" id="brand"  lang="" title="Brand" onchange="showModelNewCar(this.value)" required>
                    <option value="" selected="selected" style='padding-left:10px;'>Select Make</option>
                    <?php echo brand_drop_down();?>

                  </select>
                        </div>
                        <div class="search-box-left">Model </div>
                        <div class="search-box-right">
                        <div id="txtHint">
                        <select name="model" class="list-box"  id="model"  lang="" title="Model">
                         <option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
                         <?php //echo $this->model;?>
                        </select>
</code>```

But how to execute same as no txthint is there, so that field value of Model is changed on the fly when brand is selected. thanks

Title: calling php function in same file

Body:
Am calling 2 functions and 1 through script

<function1>
<function2>

.... calling script....

and executing in search page

<select name="brand" class="list-box" id="brand"  lang="" title="Brand" onchange="showModelNewCar(this.value)" required>
                <option value="" selected="selected" style='padding-left:10px;'>Select Make</option>
                <?php echo brand_drop_down();?>

              </select>

Model

                    <select name="model" class="list-box"  id="model"  lang="" title="Model">
                     <option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
                     <?php //echo $this->model;?>
                    </select>

Now i dont intend to use in getmodel.php in a separate file, rather add that function in this file only

    <function1>
    <function2>
function showModelNewCar(){
   .......entire function pasted......
    $list.='</select>';
}

    <select name="brand" class="list-box" id="brand"  lang="" title="Brand" onchange="showModelNewCar(this.value)" required>
                    <option value="" selected="selected" style='padding-left:10px;'>Select Make</option>
                    <?php echo brand_drop_down();?>

                  </select>

Model

                        <select name="model" class="list-box"  id="model"  lang="" title="Model">
                         <option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
                         <?php //echo $this->model;?>
                        </select>

But how to execute same as no txthint is there, so that field value of Model is changed on the fly when brand is selected. thanks


问:
Opencl bruteforce program how can i fix errors
```<code>#include <iostream>
#include <string>
#include <chrono>
#include <vector>
#include <CL/cl.hpp>

const std::string PASSWORD_CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

void brute_force(const std::string& password) {
</code>```
```<code>std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);

cl::Platform platform = platforms[0];

std::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);

cl::Device device = devices[0];

cl::Context context(device);

cl::CommandQueue queue(context, device);
</code>```

HERE std::ifstream kernel_file("brute_force_kernel.cl");
HERE std::string kernel_source((std::istreambuf_iterator(kernel_file)), std::istreambuf_iterator());
cl::Program program(context, kernel_source);

```<code>program.build();

cl::Kernel kernel(program, "brute_force");

cl::Buffer password_buffer(context, CL_MEM_READ_ONLY, password.length());
cl::Buffer password_len_buffer(context, CL_MEM_READ_ONLY, sizeof(int));

queue.enqueueWriteBuffer(password_buffer, CL_TRUE, 0, password.length(), password.data());
</code>```

HERE queue.enqueueWriteBuffer(password_len_buffer, CL_TRUE, 0, sizeof(int), &password.length());

```<code>kernel.setArg(0, password_buffer);
kernel.setArg(1, password_len_buffer);

std::vector<cl::NDRange> global_work_sizes;
for (int len = 1; len <= password.length(); len++) {
    global_work_sizes.emplace_back(std::pow(PASSWORD_CHARSET.length(), len));
}

auto start = std::chrono::high_resolution_clock::
    auto start = std::chrono::high_resolution_clock::now();  // Record the start time.
for (auto global_work_size : global_work_sizes) {
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, global_work_size, cl::NullRange);

    queue.finish();

    int found = 0;
</code>```

HERE queue.enqueueReadBuffer(output_buffer, CL_TRUE, 0, sizeof(int), &found);

```<code>    if (found == 1) {
        auto end = std::chrono::high_resolution_clock::now();  // Record the end time.
        std::chrono::duration<double> elapsed = end - start;  // Calculate the elapsed time.
        std::cout << "The password is: " << password << std::endl;
        std::cout << "Elapsed time: " << elapsed.count() << " seconds" << std::endl;
        break;
    }
}
</code>```

I installed https://github.com/ProjectPhysX/OpenCL-Wrapper/tree/master/src/OpenCL this folder into my project folder and set it by Additional Include Directories there are errors i dont understand but they dont look like a big deal

Body:
#include <iostream>
#include <string>
#include <chrono>
#include <vector>
#include <CL/cl.hpp>

const std::string PASSWORD_CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

void brute_force(const std::string& password) {

std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);

cl::Platform platform = platforms[0];

std::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);

cl::Device device = devices[0];

cl::Context context(device);

cl::CommandQueue queue(context, device);

HERE std::ifstream kernel_file("brute_force_kernel.cl");
HERE std::string kernel_source((std::istreambuf_iterator(kernel_file)), std::istreambuf_iterator());
cl::Program program(context, kernel_source);

program.build();

cl::Kernel kernel(program, "brute_force");

cl::Buffer password_buffer(context, CL_MEM_READ_ONLY, password.length());
cl::Buffer password_len_buffer(context, CL_MEM_READ_ONLY, sizeof(int));

queue.enqueueWriteBuffer(password_buffer, CL_TRUE, 0, password.length(), password.data());

HERE queue.enqueueWriteBuffer(password_len_buffer, CL_TRUE, 0, sizeof(int), &password.length());

kernel.setArg(0, password_buffer);
kernel.setArg(1, password_len_buffer);

std::vector<cl::NDRange> global_work_sizes;
for (int len = 1; len <= password.length(); len++) {
    global_work_sizes.emplace_back(std::pow(PASSWORD_CHARSET.length(), len));
}

auto start = std::chrono::high_resolution_clock::
    auto start = std::chrono::high_resolution_clock::now();  // Record the start time.
for (auto global_work_size : global_work_sizes) {
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, global_work_size, cl::NullRange);

    queue.finish();

    int found = 0;

HERE queue.enqueueReadBuffer(output_buffer, CL_TRUE, 0, sizeof(int), &found);

    if (found == 1) {
        auto end = std::chrono::high_resolution_clock::now();  // Record the end time.
        std::chrono::duration<double> elapsed = end - start;  // Calculate the elapsed time.
        std::cout << "The password is: " << password << std::endl;
        std::cout << "Elapsed time: " << elapsed.count() << " seconds" << std::endl;
        break;
    }
}

I installed https://github.com/ProjectPhysX/OpenCL-Wrapper/tree/master/src/OpenCL this folder into my project folder and set it by Additional Include Directories there are errors i dont understand but they dont look like a big deal


问:
How can I return an object from an SQL query that fits my pydantic schema?

Problem

I am trying to understand how to return an object from an SQL query that will fit the schema of my pydantic models in FastApi. I am able to do this successfully when I use a SQL Alchemy query, but I am unable to do this when I use a Raw SQL query. I could use some help understanding what is different about the two situations.
I've labeled the situations as follows:

Situation 1: Successful Object Returned Using SQL Alchemy Query

Situation 2: Failed Attempt to Return Object Using Raw SQL

Situation 1: Successful Object Returned Using SQL Alchemy Query

  upvote_subquery = select(
      Vote.upvote
    ).where(
      and_
      (Vote.user_id == current_user.id),
      (Vote.post_id == Post.id)
    ).correlate(models.Post)

  posts_query = db.query(
      Post,
      func.count(Vote.post_id).filter(Vote.upvote == True).label("upvotes"),
      func.count(Vote.post_id).filter(Vote.upvote == False).label("downvotes"),
      (upvote_subquery).label('upvote'),
      (Post.owner_id == current_user.id).label("owner")
    ).join(
      Vote, Vote.post_id == Post.id, isouter=True
    ).group_by(
      Post.id
    )

  post = post_query.all()
  return posts
```
<h4>Here is the SQL that this python code translates to</h4>
<pre class="lang-sql prettyprint-override"><code>SELECT
posts.id AS posts_id,
posts.title AS posts_title,
posts.content AS posts_content,
posts.published AS posts_published,
posts.created_at AS posts_created_at,
posts.owner_id AS posts_owner_id,
count(votes.post_id) FILTER (WHERE votes.upvote = true) AS upvotes,
count(votes.post_id) FILTER (WHERE votes.upvote = false) AS downvotes,
(SELECT votes.upvote
 FROM votes
 WHERE votes.user_id = %(user_id_1)s AND votes.post_id = posts.id
) AS upvote,
posts.owner_id = %(owner_id_1)s AS owner
FROM posts
LEFT OUTER JOIN votes ON votes.post_id = posts.id GROUP BY posts.id
</code>```

This Query returns a list of tuples and each tuple looks like this:

(
<app.models.Post object at 0x112ca3130>,
0,
0,
None,
False
)

Situation 2: Failed Attempt to Return Object Using Raw SQL

sql = text(
    '''
    SELECT
    posts.id AS posts_id,
    posts.title AS posts_title,
    posts.content AS posts_content,
    posts.published AS posts_published,
    posts.created_at AS posts_created_at,
    posts.owner_id AS posts_owner_id,
    count(votes.post_id) FILTER (WHERE votes.upvote = true) AS upvotes,
    count(votes.post_id) FILTER (WHERE votes.upvote = false) AS downvotes,
    (SELECT votes.upvote
    FROM votes
    WHERE votes.user_id = :user_id AND votes.post_id = posts.id
    ) AS upvote,
    posts.owner_id = :user_id AS owner
    FROM posts
    LEFT OUTER JOIN votes ON votes.post_id = posts.id GROUP BY posts.id
    '''
  )

  posts_query = engine.execute(sql, user_id=current_user.id)
  posts = posts_query.all()
  return posts
```
<p>This Query returns a list of tuples and each tuple looks like this:</p>
<p>(
57,
'Another Post',
'Another Post',
True,
datetime.datetime(2022, 12, 9, 20, 9, 8, 260773, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400))),
1,
0,
0,
None,
False
)</p>
<h1>My Question</h1>
<p>The two queries, when viewed in there SQL format seem to be nearly identical with the exception of the syntax for placeholders. Is there some reason why the Raw SQL query does not return <app.models.Post object at 0x112ca3130> in its tuples, and if so, is there a way to get the Raw SQL query to return <app.models.Post object at 0x112ca3130> in its tuples? I want the query to return:</p>
<blockquote>
<p>(
<app.models.Post object at 0x112ca3130>,
0,
0,
None,
False
)</p>
</blockquote>
<p>because my schema for the data looks like this:</p>
<pre class="lang-py prettyprint-override"><code>class PostOut(BaseModel):
  Post: Post
  upvotes: int
  downvotes: int
  upvote: Optional[bool]
  owner: bool

  class Config:
    orm_mode = True
</code>```

Post contains the relevant data that is contained in <app.models.Post object at 0x112ca3130>

Thank you in advance for taking the time to read this and consider any advice or possible solutions to my issue. If I can do anything to clarify the problem, please let me know!

Body:
Problem

I am trying to understand how to return an object from an SQL query that will fit the schema of my pydantic models in FastApi. I am able to do this successfully when I use a SQL Alchemy query, but I am unable to do this when I use a Raw SQL query. I could use some help understanding what is different about the two situations.
I've labeled the situations as follows:

Situation 1: Successful Object Returned Using SQL Alchemy Query

Situation 2: Failed Attempt to Return Object Using Raw SQL

Situation 1: Successful Object Returned Using SQL Alchemy Query

  upvote_subquery = select(
      Vote.upvote
    ).where(
      and_
      (Vote.user_id == current_user.id),
      (Vote.post_id == Post.id)
    ).correlate(models.Post)

  posts_query = db.query(
      Post,
      func.count(Vote.post_id).filter(Vote.upvote == True).label("upvotes"),
      func.count(Vote.post_id).filter(Vote.upvote == False).label("downvotes"),
      (upvote_subquery).label('upvote'),
      (Post.owner_id == current_user.id).label("owner")
    ).join(
      Vote, Vote.post_id == Post.id, isouter=True
    ).group_by(
      Post.id
    )

  post = post_query.all()
  return posts

Here is the SQL that this python code translates to

SELECT
posts.id AS posts_id,
posts.title AS posts_title,
posts.content AS posts_content,
posts.published AS posts_published,
posts.created_at AS posts_created_at,
posts.owner_id AS posts_owner_id,
count(votes.post_id) FILTER (WHERE votes.upvote = true) AS upvotes,
count(votes.post_id) FILTER (WHERE votes.upvote = false) AS downvotes,
(SELECT votes.upvote
 FROM votes
 WHERE votes.user_id = %(user_id_1)s AND votes.post_id = posts.id
) AS upvote,
posts.owner_id = %(owner_id_1)s AS owner
FROM posts
LEFT OUTER JOIN votes ON votes.post_id = posts.id GROUP BY posts.id

This Query returns a list of tuples and each tuple looks like this:

(
<app.models.Post object at 0x112ca3130>,
0,
0,
None,
False
)

Situation 2: Failed Attempt to Return Object Using Raw SQL

sql = text(
    '''
    SELECT
    posts.id AS posts_id,
    posts.title AS posts_title,
    posts.content AS posts_content,
    posts.published AS posts_published,
    posts.created_at AS posts_created_at,
    posts.owner_id AS posts_owner_id,
    count(votes.post_id) FILTER (WHERE votes.upvote = true) AS upvotes,
    count(votes.post_id) FILTER (WHERE votes.upvote = false) AS downvotes,
    (SELECT votes.upvote
    FROM votes
    WHERE votes.user_id = :user_id AND votes.post_id = posts.id
    ) AS upvote,
    posts.owner_id = :user_id AS owner
    FROM posts
    LEFT OUTER JOIN votes ON votes.post_id = posts.id GROUP BY posts.id
    '''
  )

  posts_query = engine.execute(sql, user_id=current_user.id)
  posts = posts_query.all()
  return posts

This Query returns a list of tuples and each tuple looks like this:

(
57,
'Another Post',
'Another Post',
True,
datetime.datetime(2022, 12, 9, 20, 9, 8, 260773, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400))),
1,
0,
0,
None,
False
)

My Question

The two queries, when viewed in there SQL format seem to be nearly identical with the exception of the syntax for placeholders. Is there some reason why the Raw SQL query does not return <app.models.Post object at 0x112ca3130> in its tuples, and if so, is there a way to get the Raw SQL query to return <app.models.Post object at 0x112ca3130> in its tuples? I want the query to return:

(
<app.models.Post object at 0x112ca3130>,
0,
0,
None,
False
)

because my schema for the data looks like this:

class PostOut(BaseModel):
  Post: Post
  upvotes: int
  downvotes: int
  upvote: Optional[bool]
  owner: bool

  class Config:
    orm_mode = True

Post contains the relevant data that is contained in <app.models.Post object at 0x112ca3130>

Thank you in advance for taking the time to read this and consider any advice or possible solutions to my issue. If I can do anything to clarify the problem, please let me know!


问:
How to remove the channel dimension within a Pytorch Model
I'm trying to create a GAN that generates audio data. Using a standard GAN that consists only of Conv2d layers has not provided good results, so I'm trying to add an LSTM layer to the model. However, the output of my last Conv2d layer shape is (None, 1 ,256, 64). This is not a valid shape for the LSTM layer and I'm trying to drop the "1" dim of the previous layer, as I don't think it is needed.

I've tried torch.reshape, torch.squeeze, and just indexing the tensor to remove that dim, but all result in shape errors.

How can I add an LSTM layer to this model, and input the correct shape?

```<code>class Generator(nn.Module):
    def __init__(self, channels_noise, channels_img, features_g):
        super(Generator, self).__init__()
        self.net = nn.Sequential(
            # Input: N x channels_noise x 1 x 1
            self._block(channels_noise, features_g * 16, (16,4), 1, 0),  # img: 4x4
            self._block(features_g * 16, features_g * 8, 4, 2, 1),  # img: 8x8
            self._block(features_g * 8, features_g * 4, 4, 2, 1),  # img: 16x16
            self._block(features_g * 4, features_g * 2, 4, 2, 1),  # img: 32x32
            nn.ConvTranspose2d(
                features_g * 2, channels_img, kernel_size=4, stride=2, padding=1
            ),

            # Output: N x channels_img x 64 x 64
            nn.Tanh(),
        )
        self.lstm = nn.LSTM(input_size=64, hidden_size=10)

    def _block(self, in_channels, out_channels, kernel_size, stride, padding):
        return nn.Sequential(
            nn.ConvTranspose2d(
                in_channels, out_channels, kernel_size, stride, padding, bias=False,
            ),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
        )

    def forward(self, x):
        x = self.net(x)
        x = x[:,0,:,:]
        lstm_out, _ = self.lstm(x)
        return lstm_out
</code>```

Body:
I'm trying to create a GAN that generates audio data. Using a standard GAN that consists only of Conv2d layers has not provided good results, so I'm trying to add an LSTM layer to the model. However, the output of my last Conv2d layer shape is (None, 1 ,256, 64). This is not a valid shape for the LSTM layer and I'm trying to drop the "1" dim of the previous layer, as I don't think it is needed.

I've tried torch.reshape, torch.squeeze, and just indexing the tensor to remove that dim, but all result in shape errors.

How can I add an LSTM layer to this model, and input the correct shape?

class Generator(nn.Module):
    def __init__(self, channels_noise, channels_img, features_g):
        super(Generator, self).__init__()
        self.net = nn.Sequential(
            # Input: N x channels_noise x 1 x 1
            self._block(channels_noise, features_g * 16, (16,4), 1, 0),  # img: 4x4
            self._block(features_g * 16, features_g * 8, 4, 2, 1),  # img: 8x8
            self._block(features_g * 8, features_g * 4, 4, 2, 1),  # img: 16x16
            self._block(features_g * 4, features_g * 2, 4, 2, 1),  # img: 32x32
            nn.ConvTranspose2d(
                features_g * 2, channels_img, kernel_size=4, stride=2, padding=1
            ),

            # Output: N x channels_img x 64 x 64
            nn.Tanh(),
        )
        self.lstm = nn.LSTM(input_size=64, hidden_size=10)

    def _block(self, in_channels, out_channels, kernel_size, stride, padding):
        return nn.Sequential(
            nn.ConvTranspose2d(
                in_channels, out_channels, kernel_size, stride, padding, bias=False,
            ),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
        )

    def forward(self, x):
        x = self.net(x)
        x = x[:,0,:,:]
        lstm_out, _ = self.lstm(x)
        return lstm_out


问:
How to connect to MongoDB replica set?
I want to connect to MongoDB cluster using

```<code>mongodb://localhost:27017
</code>```

It shows me an error

```<code>getaddrinfo ENOTFOUND messenger-mongodb-1
</code>```

This is my docker-compose.yml file

version: '3'
services:
  messenger-mongodb-1:
    container_name: messenger-mongodb-1
    image: mongo:6.0.3
    command: mongod --replSet messenger-mongodb-replica-set --bind_ip_all
    ports:
      - 27017:27017
    networks:
      - messenger-mongodb-cluster
    volumes:
      - messenger-mongodb-1-data:/data/db
    depends_on:
      - messenger-mongodb-2
      - messenger-mongodb-3
    healthcheck:
      test: test $$(echo "rs.initiate({_id:\"messenger-mongodb-replica-set\",members:[{_id:0,host:\"messenger-mongodb-1\"},{_id:1,host:\"messenger-mongodb-2\"},{_id:2,host:\"messenger-mongodb-3\"}]}).ok || rs.status().ok" | mongo --quiet) -eq 1
      interval: 10s
      start_period: 30s

  messenger-mongodb-2:
    container_name: messenger-mongodb-2
    image: mongo:6.0.3
    command: mongod --replSet messenger-mongodb-replica-set --bind_ip_all
    ports:
      - 27018:27017
    networks:
      - messenger-mongodb-cluster
    environment:
      - MONGO_INITDB_DATABASE=messenger-db
    volumes:
      - messenger-mongodb-2-data:/data/db

  messenger-mongodb-3:
    container_name: messenger-mongodb-3
    image: mongo:6.0.3
    command: mongod --replSet messenger-mongodb-replica-set --bind_ip_all
    ports:
      - 27019:27017
    networks:
      - messenger-mongodb-cluster
    environment:
      - MONGO_INITDB_DATABASE=messenger-db
    volumes:
      - messenger-mongodb-3-data:/data/db

networks:
  messenger-mongodb-cluster:

volumes:
  messenger-mongodb-1-data:
  messenger-mongodb-2-data:
  messenger-mongodb-3-data:
```
<p>I run it like</p>
```docker-compose up -d
```

How can I connect to my replica set?

I want to use it for the local development of my node.js application

My operating system is Windows 11 Pro

Title: How to connect to MongoDB replica set?

Body:
I want to connect to MongoDB cluster using

mongodb://localhost:27017

It shows me an error

getaddrinfo ENOTFOUND messenger-mongodb-1

This is my docker-compose.yml file

version: '3'
services:
  messenger-mongodb-1:
    container_name: messenger-mongodb-1
    image: mongo:6.0.3
    command: mongod --replSet messenger-mongodb-replica-set --bind_ip_all
    ports:
      - 27017:27017
    networks:
      - messenger-mongodb-cluster
    volumes:
      - messenger-mongodb-1-data:/data/db
    depends_on:
      - messenger-mongodb-2
      - messenger-mongodb-3
    healthcheck:
      test: test $$(echo "rs.initiate({_id:\"messenger-mongodb-replica-set\",members:[{_id:0,host:\"messenger-mongodb-1\"},{_id:1,host:\"messenger-mongodb-2\"},{_id:2,host:\"messenger-mongodb-3\"}]}).ok || rs.status().ok" | mongo --quiet) -eq 1
      interval: 10s
      start_period: 30s

  messenger-mongodb-2:
    container_name: messenger-mongodb-2
    image: mongo:6.0.3
    command: mongod --replSet messenger-mongodb-replica-set --bind_ip_all
    ports:
      - 27018:27017
    networks:
      - messenger-mongodb-cluster
    environment:
      - MONGO_INITDB_DATABASE=messenger-db
    volumes:
      - messenger-mongodb-2-data:/data/db

  messenger-mongodb-3:
    container_name: messenger-mongodb-3
    image: mongo:6.0.3
    command: mongod --replSet messenger-mongodb-replica-set --bind_ip_all
    ports:
      - 27019:27017
    networks:
      - messenger-mongodb-cluster
    environment:
      - MONGO_INITDB_DATABASE=messenger-db
    volumes:
      - messenger-mongodb-3-data:/data/db

networks:
  messenger-mongodb-cluster:

volumes:
  messenger-mongodb-1-data:
  messenger-mongodb-2-data:
  messenger-mongodb-3-data:

I run it like

docker-compose up -d

How can I connect to my replica set?

I want to use it for the local development of my node.js application

My operating system is Windows 11 Pro


问:
How to get "grey" back ground color to the text block area as shown in image using slack kit builder
Here I am attaching the image for reference. Thanks in advance.


问:
Android SpeechRecognizer: How to start listening directly after stopping it
According to this documentation about Android SpeechRecognizer when calling startListening() shortly after stopListening() clients must wait until onResults or onError are invoked before calling startListening() again.

If you call startListening() directly after stopListening() SpeechRecognizer will not start listening again. So how can I check if onResults or onError are invoked?

Example code:
I have a button that should end the listening, clears the textView with the transcription results and starts listening again:

```<code>btnDelete = findViewById(R.id.btnDelete);
returnedText = findViewById(R.id.transcript);

btnDelete.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        speech.stopListening();
        returnedText.setText("");
        speech.startListening(recognizerIntent);
    }
});
</code>```

The code stops listening, clears the textView but doesn't start listening again.

Thank you.

Body:
According to this documentation about Android SpeechRecognizer when calling startListening() shortly after stopListening() clients must wait until onResults or onError are invoked before calling startListening() again.

If you call startListening() directly after stopListening() SpeechRecognizer will not start listening again. So how can I check if onResults or onError are invoked?

Example code:
I have a button that should end the listening, clears the textView with the transcription results and starts listening again:

btnDelete = findViewById(R.id.btnDelete);
returnedText = findViewById(R.id.transcript);

btnDelete.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        speech.stopListening();
        returnedText.setText("");
        speech.startListening(recognizerIntent);
    }
});

The code stops listening, clears the textView but doesn't start listening again.

Thank you.


问:
Redirect 301 htaccess is using previous changes I made of it
This is my htaccess

```<code>Options All -Indexes
ErrorDocument 404 http://localhost/proyecto-dwes-main2/errors/404.php
Redirect 301 /proyecto-dwes-main2/index.php http://localhost/proyecto-dwes-main2/errors/underConstruction.php
</code>```

The syntax of redirect is: Redirect 301 /oldpage/ /newpage/
Before the actual version of my htaccess, I tested the /oldpage with other files of my project. Now is redirecting all the files I tested with it previously, plus the actual /oldpage of the htaccess.
I am using xampp.

I have tried to restart the apache service but it doesnt work. I have no idea what is happening

Body:
This is my htaccess

Options All -Indexes
ErrorDocument 404 http://localhost/proyecto-dwes-main2/errors/404.php
Redirect 301 /proyecto-dwes-main2/index.php http://localhost/proyecto-dwes-main2/errors/underConstruction.php

The syntax of redirect is: Redirect 301 /oldpage/ /newpage/
Before the actual version of my htaccess, I tested the /oldpage with other files of my project. Now is redirecting all the files I tested with it previously, plus the actual /oldpage of the htaccess.
I am using xampp.

I have tried to restart the apache service but it doesnt work. I have no idea what is happening


问:
How to develop Nexus 3 repository plugin?
In my team, we want to create our own Nexus plugin (for Nexus 3) to prevent or allow some packages to be downloaded based on our own custom rules.

I know about such a solution as Nexus Firewall, but we can not use it, since it is not free.

I have tried to find documentation or a guide on how to make your own plugin but was not able to find any decent resources.

Links I found:

Nexus development guide (To be honest not that good guide)

The same question to sonotype team (but about nexus2)

Snyk plugin - great example but no way a strict documentation

It would be really helpful if anyone can give any advice on where to start first or provide any helpful links to use.


问:
i can not configure easymde rtl into react
i did not know react-mde does not have rtl option . i tried to find mde rtl . and i find

and i configure into my new-post.js file excatly based on my search in stack over flow

but it gives me error how can i fix this error

i want use easymde rtl  package into my blog post section . but it gives me error in vscode

i followed this question and answers but it seems it does not work for me . can some one tell me what is wrong ?

Error when trying to import npm package (easyMDE) in application.js - (Uncaught ReferenceError: EasyMDE is not defined)

here is my new-post.js file that i need mde editor rtl

```<code>import 'easymde/dist/easymde.min.css';
import { useContext, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import SimpleMDE from 'react-simplemde-editor';
import tw from 'twin.macro';
import Error from '../../common/Error';
import LoadingSpinner from '../../common/LoadingSpinner';
import RouteWrapper from '../../common/RouteWrapper';
import socketContext from '../../context/SocketContext';
import { selectCurrentUser } from '../../core/features/auth/authSlice';
import { useCreatePostMutation } from '../../core/features/posts/postsApiSlice';
import { useGetUserDashboardQuery } from '../../core/features/users/usersApiSlice';
import useBase64 from '../../hooks/useBase64';
import useRequireAuth from '../../hooks/useRequireAuth';
import  EasyMDE from 'easymde';

const NewPost = () => {
  const [title, setTitle] = useState('');
  const [file, setFile] = useState('');
  const [body, setBody] = useState('');
  const [tags, setTags] = useState('');
  const [isTagsFocused, setIsTagsFocused] = useState(false);
  const [inputsFilled, setInputsFilled] = useState(false);
  const filePickerRef = useRef();
  const titleRef = useRef();
  const [createPost, { isLoading, isError }] = useCreatePostMutation();
  const navigate = useNavigate();
  const currentUser = useSelector(selectCurrentUser);
  const dispatch = useDispatch();
  const previewURL = useBase64(file);
  const { isAuthed, handleAuth } = useRequireAuth();
  const { socket } = useContext(socketContext);
  const { data: user } = useGetUserDashboardQuery(currentUser.username);

  useEffect(() => titleRef.current.focus(), []);

  useEffect(() => {
    if (title && file && body && tags) setInputsFilled(true);
    else setInputsFilled(false);
  }, [title, file, body, tags]);

  const handleSubmit = async () => {
    if (inputsFilled) {
      if (isAuthed) {
        try {
          const { id } = await createPost({
            title,
            file: previewURL,
            body,
            tags,
            authorUsername: currentUser.username,
          }).unwrap();

          socket.emit('post', {
            sender: currentUser,
            receivers: user?.followers,
            post: { title, id },
          });

          setTitle('');
          setFile('');
          setBody('');
          setTags('');

          navigate('/');
        } catch (err) {
          console.log(err);
        }
      } else handleAuth();
    }
  };

  return (
    <RouteWrapper>
      <Wrapper>
        {isLoading && <LoadingSpinner />}
        {!isLoading && (
          <NewPostWrapper>
            <Heading>create post</Heading>
            <InputWrapper>
              <Label dir='rtl' htmlFor='title'>title</Label>
              <Input
                dir='rtl'
                ref={titleRef}
                id='title'
                value={title}
                onBlur={e => setTitle(prev => prev.trim())}
                onChange={e => setTitle(e.target.value)}
                required
              />
            </InputWrapper>
            <InputWrapper>
              <Input
                type='file'
                ref={filePickerRef}
                onChange={e => setFile(e.target.files[0])}
                style={{ display: 'none' }}
                required
              />

            </InputWrapper>
            <InputWrapper>

      // this does not have rtl option :
    {/* <SimpleMDE value={body} onChange={setBody} required /> */}

           <textarea>
            {var easyMDE = new EasyMDE({element: document.getElementById('my-textarea')})

             { window.EasyMDE = EasyMDE}
            </textarea>

            </InputWrapper>
            <InputWrapper>
              <Label htmlFor='tags'>
               tags
                {isTagsFocused && (
                  <Span>tags</Span>
                )}
              </Label>
              <Input
                id='tags'
                value={tags}
                onFocus={() => setIsTagsFocused(true)}
                onBlur={() => setIsTagsFocused(false)}
                onChange={e => setTags(e.target.value.replace(/ /g, ''))}
                required
              />
            </InputWrapper>
            <Submit onClick={handleSubmit}>تایید</Submit>
            {isError && <Error>failed try more</Error>}
            {!inputsFilled && <Error>something missing</Error>}
          </NewPostWrapper>
        )}
      </Wrapper>
    </RouteWrapper>
  );
};
</code>```

Body:
i did not know react-mde does not have rtl option . i tried to find mde rtl . and i find

and i configure into my new-post.js file excatly based on my search in stack over flow

but it gives me error how can i fix this error

i want use easymde rtl  package into my blog post section . but it gives me error in vscode

i followed this question and answers but it seems it does not work for me . can some one tell me what is wrong ?

Error when trying to import npm package (easyMDE) in application.js - (Uncaught ReferenceError: EasyMDE is not defined)

here is my new-post.js file that i need mde editor rtl

import 'easymde/dist/easymde.min.css';
import { useContext, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import SimpleMDE from 'react-simplemde-editor';
import tw from 'twin.macro';
import Error from '../../common/Error';
import LoadingSpinner from '../../common/LoadingSpinner';
import RouteWrapper from '../../common/RouteWrapper';
import socketContext from '../../context/SocketContext';
import { selectCurrentUser } from '../../core/features/auth/authSlice';
import { useCreatePostMutation } from '../../core/features/posts/postsApiSlice';
import { useGetUserDashboardQuery } from '../../core/features/users/usersApiSlice';
import useBase64 from '../../hooks/useBase64';
import useRequireAuth from '../../hooks/useRequireAuth';
import  EasyMDE from 'easymde';

const NewPost = () => {
  const [title, setTitle] = useState('');
  const [file, setFile] = useState('');
  const [body, setBody] = useState('');
  const [tags, setTags] = useState('');
  const [isTagsFocused, setIsTagsFocused] = useState(false);
  const [inputsFilled, setInputsFilled] = useState(false);
  const filePickerRef = useRef();
  const titleRef = useRef();
  const [createPost, { isLoading, isError }] = useCreatePostMutation();
  const navigate = useNavigate();
  const currentUser = useSelector(selectCurrentUser);
  const dispatch = useDispatch();
  const previewURL = useBase64(file);
  const { isAuthed, handleAuth } = useRequireAuth();
  const { socket } = useContext(socketContext);
  const { data: user } = useGetUserDashboardQuery(currentUser.username);

  useEffect(() => titleRef.current.focus(), []);

  useEffect(() => {
    if (title && file && body && tags) setInputsFilled(true);
    else setInputsFilled(false);
  }, [title, file, body, tags]);

  const handleSubmit = async () => {
    if (inputsFilled) {
      if (isAuthed) {
        try {
          const { id } = await createPost({
            title,
            file: previewURL,
            body,
            tags,
            authorUsername: currentUser.username,
          }).unwrap();

          socket.emit('post', {
            sender: currentUser,
            receivers: user?.followers,
            post: { title, id },
          });

          setTitle('');
          setFile('');
          setBody('');
          setTags('');

          navigate('/');
        } catch (err) {
          console.log(err);
        }
      } else handleAuth();
    }
  };

  return (
    <RouteWrapper>
      <Wrapper>
        {isLoading && <LoadingSpinner />}
        {!isLoading && (
          <NewPostWrapper>
            <Heading>create post</Heading>
            <InputWrapper>
              title
              <Input
                dir='rtl'
                ref={titleRef}
                id='title'
                value={title}
                onBlur={e => setTitle(prev => prev.trim())}
                onChange={e => setTitle(e.target.value)}
                required
              />
            </InputWrapper>
            <InputWrapper>
              <Input
                type='file'
                ref={filePickerRef}
                onChange={e => setFile(e.target.files[0])}
                style={{ display: 'none' }}
                required
              />

            </InputWrapper>
            <InputWrapper>

      // this does not have rtl option :
    {/* <SimpleMDE value={body} onChange={setBody} required /> */}

           <textarea>
            {var easyMDE = new EasyMDE({element: document.getElementById('my-textarea')})

             { window.EasyMDE = EasyMDE}
            </textarea>

            </InputWrapper>
            <InputWrapper>

               tags
                {isTagsFocused && (
                  tags
                )}

              <Input
                id='tags'
                value={tags}
                onFocus={() => setIsTagsFocused(true)}
                onBlur={() => setIsTagsFocused(false)}
                onChange={e => setTags(e.target.value.replace(/ /g, ''))}
                required
              />
            </InputWrapper>
            <Submit onClick={handleSubmit}>تایید</Submit>
            {isError && <Error>failed try more</Error>}
            {!inputsFilled && <Error>something missing</Error>}
          </NewPostWrapper>
        )}
      </Wrapper>
    </RouteWrapper>
  );
};