问:
Transmute string to list of dictionaries with double quotes
I am working on python code to convert object to list of dictionaries in double quotes.
Below are the steps:

Script calls api endpoint returns below output.

```<code>    output:[{value:10,mode:"low",unit:"kg"},
            {value:5,mode:"intermediate",unit:"kg"},
            {value:10,mode:"expert",unit:"kg"},
            {value:2,mode:"admin",unit:"kg"}]
</code>```

My goal is to convert this data to list of dictionary objects.

I tried to convert above output to json format using json.loads :

json.loads(re.sub(r'(\w+?):', r'"\1":', output))

but double quotes are getting replaced with single quotes.

I tried

json.dumps(re.sub(r'(\w+?):', r'"\1":', output))

but this returned below string instead of list of dictionaries.

```<code>    [{"value":10,"mode":"low","unit":"kg"},
     {"value":5,"mode":"intermediate","unit":"kg"},
     {"value":10,"mode":"expert",unit:"kg"},
     {"value":2,"mode":"admin","unit":"kg"}]
</code>```

My questions:

Is there is a way to convert above string to list of dictionaries in double quotes?

Can I add new dictionary object {"value":5,"mode":"admin","unit":"kg"} to above list in double quotes?

Please help.

答: The type of quotes you're using isn't stored in the dictionary. You can (though shouldn't for style reasons) mix double and single quotes as much as you want, as long as each individual string is wrapped in the same type of quotes on either side. CPython outputs dictionaries using single quotes but that's an implementation detail and doesn't mean anything. When converting to a JSON string, double quotes will be written as that is what the JSON spec requires.</p>

Body:
I am working on python code to convert object to list of dictionaries in double quotes.
Below are the steps:

Script calls api endpoint returns below output.

    output:[{value:10,mode:"low",unit:"kg"},
            {value:5,mode:"intermediate",unit:"kg"},
            {value:10,mode:"expert",unit:"kg"},
            {value:2,mode:"admin",unit:"kg"}]

My goal is to convert this data to list of dictionary objects.

I tried to convert above output to json format using json.loads :

json.loads(re.sub(r'(\w+?):', r'"\1":', output))

but double quotes are getting replaced with single quotes.

I tried

json.dumps(re.sub(r'(\w+?):', r'"\1":', output))

but this returned below string instead of list of dictionaries.

    [{"value":10,"mode":"low","unit":"kg"},
     {"value":5,"mode":"intermediate","unit":"kg"},
     {"value":10,"mode":"expert",unit:"kg"},
     {"value":2,"mode":"admin","unit":"kg"}]

My questions:

Is there is a way to convert above string to list of dictionaries in double quotes?

Can I add new dictionary object {"value":5,"mode":"admin","unit":"kg"} to above list in double quotes?

Please help.


来源: stackexchange

问:
make uses "cc" instead of "arm-none-eabi-as"
I have a problem when building a program with makefile. There is only a problem when make tries to compile assembly file named "startup.S". It looks like make uses compiler "cc" even if i specify "arm-none-eabi-as" in a makefile (take a look at variable AS).

Here is my makefile:

```<code>SHELL := /bin/bash
ROOT := $(shell pwd)
INC := $(ROOT)/inc
SRC := $(ROOT)/src
STR := $(ROOT)/str
EXE := exe
AS := arm-none-eabi-as -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
GCC := arm-none-eabi-gcc -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
LDSCRIPT := test.ld
LD := arm-none-eabi-ld -T $(LDSCRIPT)
HEADERS := $(notdir $(wildcard $(INC)/*.h))
SOURCES_GCC := $(notdir $(wildcard $(SRC)/*.c))
SOURCES_AS := $(notdir $(wildcard $(STR)/*.S))
OBJECTS_GCC := $(SOURCES_GCC:.c=.o)
OBJECTS_AS := $(SOURCES_AS:.S=.o)
VPATH := $(STR):$(SRC):$(INC)

all : $(EXE)
    @echo konec postopka: izvrsljiv program po imenu $(EXE) se nahaja v mapi $(ROOT)
$(EXE) : $(OBJECTS_AS) $(OBJECTS_GCC)
    @echo objekti so: $(OBJECTS_AS) $(OBJECTS_GCC)
    @echo headerji so: $(HEADERS)
    @echo linkanje objektov v izvrsljiv program...
    $(LD) -o $@ $^
%.o : %.S %h
    @echo prevajanje ASSEMBLY izvornih datotek...
    $(AS) -o $@  $<
%.o : %.c %h
    @echo prevajanje C izvornih datotek...
    $(GCC) -o $@ $<
.PHONY : clean
clean :
    @echo brisanje objektov
    rm *.o
    @echo brisanje izvrsljivega programa
    rm $(EXE)
</code>```

Here is the error i get when typing comand make in a terminal. It clearly tells that "cc" doesnt understand assembly language, and this error is somewhat expected.

```<code>cc    -c -o startup.o /home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S: Assembler messages:
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:4: Error: no such instruction: `b Reset_Handler'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:5: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:6: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:7: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:8: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:9: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:10: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:11: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:14: Error: no such instruction: `ldr sp,=stack_top'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:15: Error: no such instruction: `bl c_entry'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:16: Error: no such instruction: `b .'
</code>```

If i try to compile it manualy using "arm-none-eabi-as startup.S" it compiles fine...

My question would be, why does make uses cc instead arm-none-eabi-as? What am i missing here?

After all of your proposal i managed to make a makefile, that looks like this and it is working:

```<code>SHELL := /bin/bash
ROOT := $(shell pwd)
INC := $(ROOT)/inc
SRC := $(ROOT)/src
STR := $(ROOT)/str
EXE := exe
AS := arm-none-eabi-as -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
CC := arm-none-eabi-gcc -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
LDSCRIPT := ldscript_iram_gnu.ld
LD := arm-none-eabi-ld -T $(LDSCRIPT)
HEADERS := $(notdir $(wildcard $(INC)/*.h))
SOURCES_CC := $(notdir $(wildcard $(SRC)/*.c))
SOURCES_AS := $(notdir $(wildcard $(STR)/*.S))
OBJECTS_CC := $(SOURCES_CC:.c=.o)
OBJECTS_AS := $(SOURCES_AS:.S=.o)
VPATH := $(STR):$(SRC):$(INC)

all : $(EXE)
    @echo konec postopka: izvrsljiv program po imenu $(EXE) se nahaja v mapi $(ROOT)
$(EXE) : $(OBJECTS_AS) $(OBJECTS_CC)
    @echo objekti so: $(OBJECTS_AS) $(OBJECTS_CC)
    @echo headerji so: $(HEADERS)
    @echo linkanje objektov v izvrsljiv program...
    $(LD) -o $@ $^
%.o : %.S
    @echo prevajanje ASSEMBLY izvornih datotek...
    $(AS) -o $@  $<
%.o : %.h

%.o : %.c
    @echo prevajanje C izvornih datotek...
    $(CC) -o $@ $<
%.o : %.h

.PHONY : clean
clean :
    @echo brisanje objektov
    rm *.So
    rm *.o
    @echo brisanje izvrsljivega programa
    rm $(EXE)
</code>```

When i tried to use same makefile in other project (project for which my makefile has been built from the beginning) which also has same tree structure i get some errors:

```<code>make all
objekti so: timer_example.o
headerji so: ea3131_board.h ffconf.h ff.h integer.h lpc313x_cgu_driver.h lpc313x_cgu.h lpc313x_cgu_switchbox.h lpc313x_chip.h lpc313x_crc_driver.h lpc313x_dmac.h lpc313x_dma_driver.h lpc313x_evt_driver.h lpc313x_evt_router.h lpc313x_i2c_driver.h lpc313x_i2c.h lpc313x_intc_driver.h lpc313x_intc.h lpc313x_ioconf_driver.h lpc313x_ioconf.h lpc313x_mci_driver.h lpc313x_mci.h lpc313x_nandc.h lpc313x_nand_driver.h lpc313x_spi_driver.h lpc313x_spi.h lpc313x_sysreg.h lpc313x_timer_driver.h lpc313x_timer.h lpc313x_uart_driver.h lpc313x_uart.h lpc313x_wdt_driver.h lpc313x_wdt.h lpc31xx_vmem_driver.h lpc_api.h lpc_arm922t_arch.h lpc_arm922t_cp15_driver.h lpc_arm_arch.h lpc_bmp.h lpc_colors.h lpc_fat16.h lpc_fat16_private.h lpc_fonts.h lpc_heap.h lpc_helvr10.h lpc_irq_fiq.h lpc_lbecc.h lpc_lcd_params.h lpc_line_parser.h lpc_nandflash_params.h lpc_params.h lpc_rom8x16.h lpc_rom8x8.h lpc_sdmmc.h lpc_string.h lpc_swim_font.h lpc_swim.h lpc_swim_image.h lpc_types.h lpc_winfreesystem14x16.h lpc_x5x7.h lpc_x6x13.h
linkanje objektov v izvrsljiv program...
arm-none-eabi-ld -T ldscript_iram_gnu.ld -o exe timer_example.o
ea3131_startup_entry.o: In function `clearzi_exit':
(.text+0x170): undefined reference to `ea3131_init'
timer_example.o: In function `timer0_user_interrupt':
timer_example.c:(.text+0x15c): undefined reference to `timer_ioctl'
timer_example.o: In function `uart_string_write':
timer_example.c:(.text+0x1dc): undefined reference to `strlen'
timer_example.c:(.text+0x208): undefined reference to `uart_write'
timer_example.o: In function `c_entry':
timer_example.c:(.text+0x258): undefined reference to `ea3131_board_init'
timer_example.c:(.text+0x260): undefined reference to `cp15_set_vmmu_addr'
timer_example.c:(.text+0x268): undefined reference to `int_initialize'
timer_example.c:(.text+0x274): undefined reference to `int_install_irq_handler'
timer_example.c:(.text+0x280): undefined reference to `timer_open'
timer_example.c:(.text+0x2a4): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x2bc): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x2d4): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x2e0): undefined reference to `uart_open'
timer_example.c:(.text+0x2f8): undefined reference to `memcpy'
timer_example.c:(.text+0x32c): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x334): undefined reference to `int_enable'
timer_example.c:(.text+0x38c): undefined reference to `sprintf'
make: *** [exe] Error 1
</code>```

It looks to me that my makefile is doing OK now, but there are some unresolved references within my project which have nothing to do with my makefile. Still i need your conformation that my makefile is doing OK. Thank you all.

Regards.

答:
Your .o file for assembly is overwrittent by the .o rule for .c file. You don't have to end your object file in .o Try this instead :

```<code>OBJECTS_AS := $(SOURCES_AS:.S=.os)
</code>```

And your assembly rule becomes :

```<code>%.os : %.S %h
    @echo prevajanje ASSEMBLY izvornih datotek...
    $(AS) -o $@  $<
</code>```

Of course you could us .o_assembly or whatever. Object file have to end with .o only if you use implicit rules.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem when building a program with makefile. There is only a problem when make tries to compile assembly file named "startup.S". It looks like make uses compiler "cc" even if i specify "arm-none-eabi-as" in a makefile (take a look at variable AS).

Here is my makefile:

SHELL := /bin/bash
ROOT := $(shell pwd)
INC := $(ROOT)/inc
SRC := $(ROOT)/src
STR := $(ROOT)/str
EXE := exe
AS := arm-none-eabi-as -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
GCC := arm-none-eabi-gcc -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
LDSCRIPT := test.ld
LD := arm-none-eabi-ld -T $(LDSCRIPT)
HEADERS := $(notdir $(wildcard $(INC)/*.h))
SOURCES_GCC := $(notdir $(wildcard $(SRC)/*.c))
SOURCES_AS := $(notdir $(wildcard $(STR)/*.S))
OBJECTS_GCC := $(SOURCES_GCC:.c=.o)
OBJECTS_AS := $(SOURCES_AS:.S=.o)
VPATH := $(STR):$(SRC):$(INC)

all : $(EXE)
    @echo konec postopka: izvrsljiv program po imenu $(EXE) se nahaja v mapi $(ROOT)
$(EXE) : $(OBJECTS_AS) $(OBJECTS_GCC)
    @echo objekti so: $(OBJECTS_AS) $(OBJECTS_GCC)
    @echo headerji so: $(HEADERS)
    @echo linkanje objektov v izvrsljiv program...
    $(LD) -o $@ $^
%.o : %.S %h
    @echo prevajanje ASSEMBLY izvornih datotek...
    $(AS) -o $@  $<
%.o : %.c %h
    @echo prevajanje C izvornih datotek...
    $(GCC) -o $@ $<
.PHONY : clean
clean :
    @echo brisanje objektov
    rm *.o
    @echo brisanje izvrsljivega programa
    rm $(EXE)

Here is the error i get when typing comand make in a terminal. It clearly tells that "cc" doesnt understand assembly language, and this error is somewhat expected.

cc    -c -o startup.o /home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S: Assembler messages:
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:4: Error: no such instruction: `b Reset_Handler'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:5: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:6: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:7: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:8: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:9: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:10: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:11: Error: no such instruction: `b .'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:14: Error: no such instruction: `ldr sp,=stack_top'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:15: Error: no such instruction: `bl c_entry'
/home/ziga/Dropbox/diploma/86x_linux/IDE_eclipse/eclipse_projects/makefile_8/str/startup.S:16: Error: no such instruction: `b .'

If i try to compile it manualy using "arm-none-eabi-as startup.S" it compiles fine...

My question would be, why does make uses cc instead arm-none-eabi-as? What am i missing here?

After all of your proposal i managed to make a makefile, that looks like this and it is working:

SHELL := /bin/bash
ROOT := $(shell pwd)
INC := $(ROOT)/inc
SRC := $(ROOT)/src
STR := $(ROOT)/str
EXE := exe
AS := arm-none-eabi-as -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
CC := arm-none-eabi-gcc -mcpu=arm926ej-s -c -Wall -I $(INC) -I$(SRC) -I $(STR)
LDSCRIPT := ldscript_iram_gnu.ld
LD := arm-none-eabi-ld -T $(LDSCRIPT)
HEADERS := $(notdir $(wildcard $(INC)/*.h))
SOURCES_CC := $(notdir $(wildcard $(SRC)/*.c))
SOURCES_AS := $(notdir $(wildcard $(STR)/*.S))
OBJECTS_CC := $(SOURCES_CC:.c=.o)
OBJECTS_AS := $(SOURCES_AS:.S=.o)
VPATH := $(STR):$(SRC):$(INC)

all : $(EXE)
    @echo konec postopka: izvrsljiv program po imenu $(EXE) se nahaja v mapi $(ROOT)
$(EXE) : $(OBJECTS_AS) $(OBJECTS_CC)
    @echo objekti so: $(OBJECTS_AS) $(OBJECTS_CC)
    @echo headerji so: $(HEADERS)
    @echo linkanje objektov v izvrsljiv program...
    $(LD) -o $@ $^
%.o : %.S
    @echo prevajanje ASSEMBLY izvornih datotek...
    $(AS) -o $@  $<
%.o : %.h

%.o : %.c
    @echo prevajanje C izvornih datotek...
    $(CC) -o $@ $<
%.o : %.h

.PHONY : clean
clean :
    @echo brisanje objektov
    rm *.So
    rm *.o
    @echo brisanje izvrsljivega programa
    rm $(EXE)

When i tried to use same makefile in other project (project for which my makefile has been built from the beginning) which also has same tree structure i get some errors:

make all
objekti so: timer_example.o
headerji so: ea3131_board.h ffconf.h ff.h integer.h lpc313x_cgu_driver.h lpc313x_cgu.h lpc313x_cgu_switchbox.h lpc313x_chip.h lpc313x_crc_driver.h lpc313x_dmac.h lpc313x_dma_driver.h lpc313x_evt_driver.h lpc313x_evt_router.h lpc313x_i2c_driver.h lpc313x_i2c.h lpc313x_intc_driver.h lpc313x_intc.h lpc313x_ioconf_driver.h lpc313x_ioconf.h lpc313x_mci_driver.h lpc313x_mci.h lpc313x_nandc.h lpc313x_nand_driver.h lpc313x_spi_driver.h lpc313x_spi.h lpc313x_sysreg.h lpc313x_timer_driver.h lpc313x_timer.h lpc313x_uart_driver.h lpc313x_uart.h lpc313x_wdt_driver.h lpc313x_wdt.h lpc31xx_vmem_driver.h lpc_api.h lpc_arm922t_arch.h lpc_arm922t_cp15_driver.h lpc_arm_arch.h lpc_bmp.h lpc_colors.h lpc_fat16.h lpc_fat16_private.h lpc_fonts.h lpc_heap.h lpc_helvr10.h lpc_irq_fiq.h lpc_lbecc.h lpc_lcd_params.h lpc_line_parser.h lpc_nandflash_params.h lpc_params.h lpc_rom8x16.h lpc_rom8x8.h lpc_sdmmc.h lpc_string.h lpc_swim_font.h lpc_swim.h lpc_swim_image.h lpc_types.h lpc_winfreesystem14x16.h lpc_x5x7.h lpc_x6x13.h
linkanje objektov v izvrsljiv program...
arm-none-eabi-ld -T ldscript_iram_gnu.ld -o exe timer_example.o
ea3131_startup_entry.o: In function `clearzi_exit':
(.text+0x170): undefined reference to `ea3131_init'
timer_example.o: In function `timer0_user_interrupt':
timer_example.c:(.text+0x15c): undefined reference to `timer_ioctl'
timer_example.o: In function `uart_string_write':
timer_example.c:(.text+0x1dc): undefined reference to `strlen'
timer_example.c:(.text+0x208): undefined reference to `uart_write'
timer_example.o: In function `c_entry':
timer_example.c:(.text+0x258): undefined reference to `ea3131_board_init'
timer_example.c:(.text+0x260): undefined reference to `cp15_set_vmmu_addr'
timer_example.c:(.text+0x268): undefined reference to `int_initialize'
timer_example.c:(.text+0x274): undefined reference to `int_install_irq_handler'
timer_example.c:(.text+0x280): undefined reference to `timer_open'
timer_example.c:(.text+0x2a4): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x2bc): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x2d4): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x2e0): undefined reference to `uart_open'
timer_example.c:(.text+0x2f8): undefined reference to `memcpy'
timer_example.c:(.text+0x32c): undefined reference to `timer_ioctl'
timer_example.c:(.text+0x334): undefined reference to `int_enable'
timer_example.c:(.text+0x38c): undefined reference to `sprintf'
make: *** [exe] Error 1

It looks to me that my makefile is doing OK now, but there are some unresolved references within my project which have nothing to do with my makefile. Still i need your conformation that my makefile is doing OK. Thank you all.

Regards.

Body:
Your .o file for assembly is overwrittent by the .o rule for .c file. You don't have to end your object file in .o Try this instead :

OBJECTS_AS := $(SOURCES_AS:.S=.os)

And your assembly rule becomes :

%.os : %.S %h
    @echo prevajanje ASSEMBLY izvornih datotek...
    $(AS) -o $@  $<

Of course you could us .o_assembly or whatever. Object file have to end with .o only if you use implicit rules.


问:
Displaying custom selected dates from db in JQuery multiple calendars on the page
I am working on a login system where user can register multiple products with availability calenders attached to them. Whole site works on ajax response.

Problem is that when a user select a uploaded product first time and view the calender, previously saved dates displays alright as selected. But after that not matter how many products he switches to, it keeps showing same dates data on calendar.

Below is my code:

```<code>jQuery(document).ready(function ($) {

// Click Function On Calendar Tab
$("#tabCalendar").click(function(){
    var productId = $("#productId").val();
    $.ajax({
        type:'POST',
        url:'../ajax/listing_availabily_dates_fetch.php',
        data: "&productId=" + productId,
        datatype: 'json',
        success:function(response){
            startTheCalendar(response);
        }
    });
});

function startTheCalendar(response){
    $("#show-next-month").calendar({
        num_next_month: 11,
        num_prev_month: 0,
        unavailable: response, // This is where dates should update
        onSelectDate: function(date, month, year, thisEvent){
            var dateData = [year, month, date].join('-');
            selected = response;
            dateClickEvent(dateData, thisEvent);
        }
    });
}

// function dateClickEvent(dateData, thisEvent) {}

});
</code>```

Looking for help.

答:
I was looking for the solution in wrong direction, or may be more complicated one. I thought it would be easier if I could refresh plugin data, for which I even started creating a custom function in plugin itself.

To my surprise and in absence of any help, it was fairly easy:

HTML:

```<code><div id="calendar-holder">
    <div id="calendar" ></div>
</div>
</code>```

JQuery:

```<code>function startTheCalendar(response){

    $("#calendar-holder").html("");
    $("#calendar-holder").html('<div id="calendar" ></div>');

    if(response == ""){ response = []; }

    $("#show-next-month").calendar({
        num_next_month: 11,
        num_prev_month: 0,
        unavailable: response, // This is where dates should update
        onSelectDate: function(date, month, year, thisEvent){
            var dateData = [year, month, date].join('-');
            selected = response;
            dateClickEvent(dateData, thisEvent);
        }
    });
}
</code>```

I just had to clear the plugin data from HTML and repopulate it.

ContentLicense: CC BY-SA 4.0

Body:
I am working on a login system where user can register multiple products with availability calenders attached to them. Whole site works on ajax response.

Problem is that when a user select a uploaded product first time and view the calender, previously saved dates displays alright as selected. But after that not matter how many products he switches to, it keeps showing same dates data on calendar.

Below is my code:

jQuery(document).ready(function ($) {

// Click Function On Calendar Tab
$("#tabCalendar").click(function(){
    var productId = $("#productId").val();
    $.ajax({
        type:'POST',
        url:'../ajax/listing_availabily_dates_fetch.php',
        data: "&productId=" + productId,
        datatype: 'json',
        success:function(response){
            startTheCalendar(response);
        }
    });
});

function startTheCalendar(response){
    $("#show-next-month").calendar({
        num_next_month: 11,
        num_prev_month: 0,
        unavailable: response, // This is where dates should update
        onSelectDate: function(date, month, year, thisEvent){
            var dateData = [year, month, date].join('-');
            selected = response;
            dateClickEvent(dateData, thisEvent);
        }
    });
}

// function dateClickEvent(dateData, thisEvent) {}

});

Looking for help.

Body:
I was looking for the solution in wrong direction, or may be more complicated one. I thought it would be easier if I could refresh plugin data, for which I even started creating a custom function in plugin itself.

To my surprise and in absence of any help, it was fairly easy:

HTML:

<div id="calendar-holder">
    <div id="calendar" ></div>
</div>

JQuery:

function startTheCalendar(response){

    $("#calendar-holder").html("");
    $("#calendar-holder").html('<div id="calendar" ></div>');

    if(response == ""){ response = []; }

    $("#show-next-month").calendar({
        num_next_month: 11,
        num_prev_month: 0,
        unavailable: response, // This is where dates should update
        onSelectDate: function(date, month, year, thisEvent){
            var dateData = [year, month, date].join('-');
            selected = response;
            dateClickEvent(dateData, thisEvent);
        }
    });
}

I just had to clear the plugin data from HTML and repopulate it.


问:
How can I disable all contraints in my postgresql?
I have a PostgreSQL database with tables that have more than 500 billions rows. I'm trying to delete around 6 millions row but it's takes more than 4 minutes. I need to optimize those delete operation to make an useful system.

I think a good idea could be to disable constraints and triggers and then enable it back, so my questions are:

How can I disable all constraints?
And, is it possible to disable relations between tables?

Right now, I just disable the triggers using this:

```<code>Alter table "table_name" disable all
</code>```

And enable it back using this:

```<code>Alter table "table_name" enable all
</code>```

Edit

This is the query result with triggers enabled.

```<code>  Delete on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=296995.938..296995.938 rows=0 loops=1)
  Buffers: shared hit=6000000 read=420811 dirtied=93346 written=51646
  ->  Seq Scan on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=7977.126..19798.361 rows=6000000 loops=1)
        Filter: ("Id" < 23000000)
        Rows Removed by Filter: 34218414
        Buffers: shared read=420811 dirtied=49228 written=51646
Planning Time: 304.085 ms
Execution Time: 296995.963 ms
</code>```

Disabling all triggers I improve the performance reducing the execution time from 5 minutes to 3 minutes.

```<code>Alter table "table_name" disable trigger all
</code>```

However, I need to improve more delete operations. Any idea?

答:
The correct statement to disable all triggers on a table is

```<code>ALTER TABLE atable DISABLE TRIGGER ALL;
</code>```

This will disable all triggers and foreign key constraints defined on the table, since foreign key constraints are implemented by system triggers in PostgreSQL.

It will also disable deferrable primary key, unique and exclusion constraints, which are also implemented with triggers. Non-deferrable primary key, unique and exclusion constraints have no associated triggers and are not affected.

You can later re-enable these constraints by enabling the triggers, but there won't be any check for consistency. Because that is dangerous, disabling such triggers requires superuser privileges.

An alternative way to disable trigger-based constraints is to set the session_replication_role parameter to replica, which also requires superuser privileges.

The only way to disable check constraints and non-deferrable primary key, unique and exclusion constraints is to drop them and later re-create them. The latter will take some time as it checks the table for consistency, but you may still win out, since it will make data modifications faster.

For reference see the documentation of ALTER TABLE.

Body:
I have a PostgreSQL database with tables that have more than 500 billions rows. I'm trying to delete around 6 millions row but it's takes more than 4 minutes. I need to optimize those delete operation to make an useful system.

I think a good idea could be to disable constraints and triggers and then enable it back, so my questions are:

How can I disable all constraints?
And, is it possible to disable relations between tables?

Right now, I just disable the triggers using this:

Alter table "table_name" disable all

And enable it back using this:

Alter table "table_name" enable all

Edit

This is the query result with triggers enabled.

  Delete on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=296995.938..296995.938 rows=0 loops=1)
  Buffers: shared hit=6000000 read=420811 dirtied=93346 written=51646
  ->  Seq Scan on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=7977.126..19798.361 rows=6000000 loops=1)
        Filter: ("Id" < 23000000)
        Rows Removed by Filter: 34218414
        Buffers: shared read=420811 dirtied=49228 written=51646
Planning Time: 304.085 ms
Execution Time: 296995.963 ms

Disabling all triggers I improve the performance reducing the execution time from 5 minutes to 3 minutes.

Alter table "table_name" disable trigger all

However, I need to improve more delete operations. Any idea?

Body:
The correct statement to disable all triggers on a table is

ALTER TABLE atable DISABLE TRIGGER ALL;

This will disable all triggers and foreign key constraints defined on the table, since foreign key constraints are implemented by system triggers in PostgreSQL.

It will also disable deferrable primary key, unique and exclusion constraints, which are also implemented with triggers. Non-deferrable primary key, unique and exclusion constraints have no associated triggers and are not affected.

You can later re-enable these constraints by enabling the triggers, but there won't be any check for consistency. Because that is dangerous, disabling such triggers requires superuser privileges.

An alternative way to disable trigger-based constraints is to set the session_replication_role parameter to replica, which also requires superuser privileges.

The only way to disable check constraints and non-deferrable primary key, unique and exclusion constraints is to drop them and later re-create them. The latter will take some time as it checks the table for consistency, but you may still win out, since it will make data modifications faster.

For reference see the documentation of ALTER TABLE.


问:
Azure LetsEncrypt cannot access .well-known/acme-challenge for my function
I am trying to enable SSL for my azure function using the letsencrypt site-extension for azure as described here. I was following the instructions in that wiki and on this website.

However, I get an error when it tries to verify the website.

The error indicates that the acme-challenge page cannot be accessed (404).

This is my web.config under .well-known/:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <clear />
      <add name="ACMEStaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
    </handlers>
    <staticContent>
      <remove fileExtension="." />
      <mimeMap fileExtension="." mimeType="text/plain" />
    </staticContent>
  </system.webServer>
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>
</code>```

Does anyone have any ideas on what could be going wrong?

答:
Here's how you can do that.

In your function app, create a new proxy for the challenge directory (this is required as the challenge will be a http get to /.well-known/acme-challenge/, and per default a function in a function app will only answer on /api/.

You can setup the proxy in the following way.

proxies.json

```<code>{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "LetsEncryptProxy": {
      "matchCondition": {
        "route": "/.well-known/acme-challenge/{code}"
      },
      "backendUri": "http://%WEBSITE_HOSTNAME%/api/letsencrypt/.well-known/acme-challenge/{code}"
    }
  }
}
</code>```

The important setting here is the Route Template: /.well-known/acme-challenge/{*rest} this will match all request that goes to the challenge directory.

Please note that proxies are a preview feature and you have to enable it, for it to work.

Reference:
https://github.com/sjkp/letsencrypt-siteextension/wiki/Azure-Functions-Support
https://blog.bitscry.com/2018/07/06/using-lets-encrypt-ssl-certificates-with-azure-functions/

Body:
I am trying to enable SSL for my azure function using the letsencrypt site-extension for azure as described here. I was following the instructions in that wiki and on this website.

However, I get an error when it tries to verify the website.

The error indicates that the acme-challenge page cannot be accessed (404).

This is my web.config under .well-known/:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <clear />
      <add name="ACMEStaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
    </handlers>
    <staticContent>
      <remove fileExtension="." />
      <mimeMap fileExtension="." mimeType="text/plain" />
    </staticContent>
  </system.webServer>
  <system.web>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

Does anyone have any ideas on what could be going wrong?

Body:
Here's how you can do that.

In your function app, create a new proxy for the challenge directory (this is required as the challenge will be a http get to /.well-known/acme-challenge/, and per default a function in a function app will only answer on /api/.

You can setup the proxy in the following way.

proxies.json

{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "LetsEncryptProxy": {
      "matchCondition": {
        "route": "/.well-known/acme-challenge/{code}"
      },
      "backendUri": "http://%WEBSITE_HOSTNAME%/api/letsencrypt/.well-known/acme-challenge/{code}"
    }
  }
}

The important setting here is the Route Template: /.well-known/acme-challenge/{*rest} this will match all request that goes to the challenge directory.

Please note that proxies are a preview feature and you have to enable it, for it to work.

Reference:
https://github.com/sjkp/letsencrypt-siteextension/wiki/Azure-Functions-Support
https://blog.bitscry.com/2018/07/06/using-lets-encrypt-ssl-certificates-with-azure-functions/


问:
Upload file (> 4MB) to OneDrive using Graph API
I am trying to upload files to OneDrive using Graph API. The below code works fine when I upload files with size lesser than 4MB but it shows an error when I try to upload files more than 4 MB. I went through this documentation but still, I am not sure how can I get this work.

Below is my working code for files less than 4MB.

```<code>using (var client = new HttpClient())
{
    var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

    byte[] sContents = System.IO.File.ReadAllBytes(filePath);
    var content = new ByteArrayContent(sContents);

    var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}
</code>```

Please help

答:
For files bigger then 4MB you need to create an uploadSession that you POST to this URL:

```<code>https://graph.microsoft.com/v1.0/me/drive/root:/{item-path}:/createUploadSession
</code>```

Pass an array of items,

```<code>{
  "item": {
    "@odata.type": "microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior": "rename",
    "name": "largefile.dat"
  }
}
</code>```

I use "@microsoft.graph.conflictBehavior": "overwrite", instead of rename.

The response will provide an upload url to upload the file in batches

```<code>{
  "uploadUrl": "https://sn3302.up.1drv.com/up/fe6987415ace7X4e1eF866337",
  "expirationDateTime": "2015-01-29T09:21:55.523Z"
}
</code>```

I don't have a c# example but here's a PHP one:

$url = $result['uploadUrl'];
$fragSize = 1024*1024*4;
$file = file_get_contents($source);
$fileSize = strlen($file);
$numFragments = ceil($fileSize / $fragSize);
$bytesRemaining = $fileSize;
$i = 0;
$response = null;

while ($i < $numFragments) {
    $chunkSize = $numBytes = $fragSize;
    $start = $i * $fragSize;
    $end = $i * $fragSize + $chunkSize - 1;
    $offset = $i * $fragSize;

    if ($bytesRemaining < $chunkSize) {
        $chunkSize = $numBytes = $bytesRemaining;
        $end = $fileSize - 1;
    }

    if ($stream = fopen($source, 'r')) {
        // get contents using offset
        $data = stream_get_contents($stream, $chunkSize, $offset);
        fclose($stream);
    }

    $contentRange = " bytes " . $start . "-" . $end . "/" . $fileSize;
    $headers = array(
        "Content-Length: $numBytes",
        "Content-Range: $contentRange"
    );

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $server_output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    $bytesRemaining = $bytesRemaining - $chunkSize;
    $i++;
}
```

Body:
I am trying to upload files to OneDrive using Graph API. The below code works fine when I upload files with size lesser than 4MB but it shows an error when I try to upload files more than 4 MB. I went through this documentation but still, I am not sure how can I get this work.

Below is my working code for files less than 4MB.

using (var client = new HttpClient())
{
    var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

    byte[] sContents = System.IO.File.ReadAllBytes(filePath);
    var content = new ByteArrayContent(sContents);

    var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}

Please help

Body:
For files bigger then 4MB you need to create an uploadSession that you POST to this URL:

https://graph.microsoft.com/v1.0/me/drive/root:/{item-path}:/createUploadSession

Pass an array of items,

{
  "item": {
    "@odata.type": "microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior": "rename",
    "name": "largefile.dat"
  }
}

I use "@microsoft.graph.conflictBehavior": "overwrite", instead of rename.

The response will provide an upload url to upload the file in batches

{
  "uploadUrl": "https://sn3302.up.1drv.com/up/fe6987415ace7X4e1eF866337",
  "expirationDateTime": "2015-01-29T09:21:55.523Z"
}

I don't have a c# example but here's a PHP one:

$url = $result['uploadUrl'];
$fragSize = 1024*1024*4;
$file = file_get_contents($source);
$fileSize = strlen($file);
$numFragments = ceil($fileSize / $fragSize);
$bytesRemaining = $fileSize;
$i = 0;
$response = null;

while ($i < $numFragments) {
    $chunkSize = $numBytes = $fragSize;
    $start = $i * $fragSize;
    $end = $i * $fragSize + $chunkSize - 1;
    $offset = $i * $fragSize;

    if ($bytesRemaining < $chunkSize) {
        $chunkSize = $numBytes = $bytesRemaining;
        $end = $fileSize - 1;
    }

    if ($stream = fopen($source, 'r')) {
        // get contents using offset
        $data = stream_get_contents($stream, $chunkSize, $offset);
        fclose($stream);
    }

    $contentRange = " bytes " . $start . "-" . $end . "/" . $fileSize;
    $headers = array(
        "Content-Length: $numBytes",
        "Content-Range: $contentRange"
    );

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $server_output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    $bytesRemaining = $bytesRemaining - $chunkSize;
    $i++;
}


问:
Changing shape of textview in Android framework
I am working on android frameworks. I need to modify the shape of the textview such that it should have rounded corners. Can you please help me with this issue?</p>

答:
XML file saved at res/drawable/gradient_box.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>
</code>```

This layout XML applies the shape drawable to a View:

```<code><TextView
    android:background="@drawable/gradient_box"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content" />
</code>```

This application code gets the shape drawable and applies it to a View:
Resources res = getResources();
Drawable shape = res. getDrawable(R.drawable.gradient_box);

```<code>TextView tv = (TextView)findViewByID(R.id.textview);
tv.setBackground(shape);
</code>```

Copy&Paste from http://developer.android.com/guide/topics/resources/drawable-resource.html, first result when you google "android textView rounded corners"

[EDIT]

As you want to change the source of the android framework, you can alter the style of the TextView by altering the default Drawables. In the sources the various Drawables are grouped in an inner class called Drawables:

```<code>class Drawables {
        final Rect mCompoundRect = new Rect();
        Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight;
        int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight;
        int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight;
        int mDrawablePadding;
    }
</code>```

Just alter these Drawables as you like and you have redefined TextView.

I'm referring to that version of the TextView sources.

Body:
XML file saved at res/drawable/gradient_box.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

This layout XML applies the shape drawable to a View:

<TextView
    android:background="@drawable/gradient_box"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content" />

This application code gets the shape drawable and applies it to a View:
Resources res = getResources();
Drawable shape = res. getDrawable(R.drawable.gradient_box);

TextView tv = (TextView)findViewByID(R.id.textview);
tv.setBackground(shape);

Copy&Paste from http://developer.android.com/guide/topics/resources/drawable-resource.html, first result when you google "android textView rounded corners"

[EDIT]

As you want to change the source of the android framework, you can alter the style of the TextView by altering the default Drawables. In the sources the various Drawables are grouped in an inner class called Drawables:

class Drawables {
        final Rect mCompoundRect = new Rect();
        Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight;
        int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight;
        int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight;
        int mDrawablePadding;
    }

Just alter these Drawables as you like and you have redefined TextView.

I'm referring to that version of the TextView sources.


问:
componentDidMount not getting props value
I'm performing the change password option with react-redux-firestore. Password changing is working fine if everything entered is correct. If any authentication error receive, error is dispatched and that should be displayed to the user.  Whenever authentication error received I was handling it as follows to show error message within render

```<code>{authError ? this.openSnackbar({ message: '{authError}' }) : null}
</code>```

but this makes a infinite loop.

Later added componentDidMount() method. This will prevent from looping through, but I'm not able to show the error message.

```<code>    componentDidMount = () => {
        const { authError } = this.props;
        console.log(authError)
        if (authError) {
            this.setState(
                {
                    loading: false,
                    message: '{authError}',
                    open: true
                },
                () => {
                    alert(this.state.open);
                }
            )
        }

    };
</code>```

when I do console.log(authError).. it's not showing the error message.

on button click how can I show the error message?

Any help Appreciated.

change password component

```<code>import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import IconButton from '@material-ui/core/IconButton';
import { connect } from 'react-redux'
import { compose } from 'redux'
import { changePassword } from '../../store/actions/auth'

const styles = {

    textField: {
        fontSize: '5px'
    },

};

class ChangePassword extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            open: false,
            message: '',
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: ''
        }
    }
    componentDidMount = () => {
        const { authError } = this.props;
        console.log('did mount called')
        console.log(authError)
        if (authError) {
            this.setState(
                {
                    loading: false,
                    message: '{authError}',
                    open: true
                },
                () => {
                    alert(this.state.open);
                }
            )
        }

    };
    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    openSnackbar = ({ message }) => {
        this.setState({
            open: true,
            message
        });
    };
    handleSubmit = (e) => {
        e.preventDefault();
        let curpass = this.state.cp_currentPassword
        let newpass = this.state.cp_newPassword
        this.setState({ loading: true });
        this.props.changePassword(curpass, newpass, this.passwordUpdated)
    }
    passwordUpdated = () => {
        this.setState({
            message: 'Password changed Successfully.!',
            open: true,
            loading: false
        });
    };

    render() {
        const { classes, auth, authError } = this.props;

        console.log(authError)
        const { loading } = this.state;
        const message = (
            <span
                id="snackbar-message-id"
                dangerouslySetInnerHTML={{ __html: this.state.message }}
            />
        );
        if (!auth.uid) return <Redirect to='/signin' />
        return (
            <div>
                {/* {authError ? this.openSnackbar({ message: '{authError}' }) : null} */}

                <GridContainer>
                    <GridItem xs={12} sm={12} md={12}>

                        <Card>
                            <CardHeader color="warning">
                                <h4 className={classes.cardTitleWhite}>Change Password</h4>
                            </CardHeader>
                            <form >
                                <GridContainer>
                                    <GridItem xs={12} sm={12} md={6}>
                                        <CardBody>
                                            <GridContainer>
                                                <GridItem xs={12} sm={12} md={12}>

                                                    <TextField
                                                        id="cp_currentPassword"
                                                        label="Current Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_currentPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>

                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_newPassword"
                                                        label="New Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_newPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_confirmPassword"
                                                        label="Confirm Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_confirmPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                            </GridContainer>

                                        </CardBody>
                                        <CardFooter>

                                            <Button color="warning" onClick={(e) => this.handleSubmit(e)} disabled={loading}>
                                                {loading && <CircularProgress style={{ color: 'white', height: '20px', width: '20px', marginRight: '10px' }} />}
                                                Change Password
                      </Button>
                                        </CardFooter>
                                    </GridItem>
                                </GridContainer>
                            </form>
                        </Card>

                    </GridItem>

                </GridContainer>

                <Snackbar
                    open={this.state.open}
                    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
                    message={message}
                    variant="error"
                    onClose={() => this.setState({ open: false, message: '' })}
                    action={
                        <IconButton
                            key="close"
                            aria-label="Close"
                            color="inherit"
                            className={classes.close}
                            onClick={() => this.setState({ open: false, message: '' })}
                        >
                            <CloseIcon className={classes.icon} />
                        </IconButton>
                    }
                    autoHideDuration={3000}
                />
            </div>
        )
    }
}
const mapstateToProps = (state) => {
    return {
        auth: state.firebase.auth,
        authError: state.authroot.autherr
    }
}
const mapDispatchtoProps = (dispatch, getState) => {
    return {
        changePassword: (currentPassword, newPassword, passwordUpdated) => { dispatch(changePassword(currentPassword, newPassword, passwordUpdated)) }
    }
}
export default compose(
    withStyles(styles),
    connect(mapstateToProps, mapDispatchtoProps)
)(ChangePassword);
</code>```

auth action

```<code>export const changePassword = (currentPassword, newPassword, func) => {
    return (dispatch, getState, { getFirebase }) => {
        const firebase = getFirebase();
        var user = firebase.auth().currentUser;
        var cred = firebase.auth.EmailAuthProvider.credential(
            user.email, currentPassword);
            // reauthenticateAndRetrieveDataWithCredential
        user.reauthenticateWithCredential(cred)
            .then(() => {
                user.updatePassword(newPassword).then(() => {
                    console.log("Password updated!");
                    func();
                }).catch((error) => { dispatch({ type: 'CHANGEPASSWORD_ERR', error }) });
            }).catch((error) => {
                dispatch({ type: 'CHANGEPASSWORD_CURRPSW_ERR', error })
            });

    }
}
</code>```

auth reducer

```<code> case 'CHANGEPASSWORD_SUCCESS':
            return {
                ...state,
                 //action.func

            };
            case 'CHANGEPASSWORD_CURRPSW_ERR':
            return {
                ...state,
                autherr: action.error.message

            };
            case 'CHANGEPASSWORD_ERR':
                return {
                    ...state,
                    autherr: action.error.message

                };
</code>```

答:
Just set the open prop of Snackbar component straight from the props like,</p>

```<code><Snackbar
    open={!!this.props.authError}
    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
    message={message}
    variant="error"
    onClose={() => this.setState({ open: false, message: '' })}
    action={
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            className={classes.close}
            onClick={() =>{have a action dispatch for clear error added into the reducer}}
        >
            <CloseIcon className={classes.icon} />
        </IconButton>
    }
    autoHideDuration={3000}
/>
</code>```

Body:
I'm performing the change password option with react-redux-firestore. Password changing is working fine if everything entered is correct. If any authentication error receive, error is dispatched and that should be displayed to the user.  Whenever authentication error received I was handling it as follows to show error message within render

{authError ? this.openSnackbar({ message: '{authError}' }) : null}

but this makes a infinite loop.

Later added componentDidMount() method. This will prevent from looping through, but I'm not able to show the error message.

    componentDidMount = () => {
        const { authError } = this.props;
        console.log(authError)
        if (authError) {
            this.setState(
                {
                    loading: false,
                    message: '{authError}',
                    open: true
                },
                () => {
                    alert(this.state.open);
                }
            )
        }

    };

when I do console.log(authError).. it's not showing the error message.

on button click how can I show the error message?

Any help Appreciated.

change password component

import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import IconButton from '@material-ui/core/IconButton';
import { connect } from 'react-redux'
import { compose } from 'redux'
import { changePassword } from '../../store/actions/auth'

const styles = {

    textField: {
        fontSize: '5px'
    },

};

class ChangePassword extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            open: false,
            message: '',
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: ''
        }
    }
    componentDidMount = () => {
        const { authError } = this.props;
        console.log('did mount called')
        console.log(authError)
        if (authError) {
            this.setState(
                {
                    loading: false,
                    message: '{authError}',
                    open: true
                },
                () => {
                    alert(this.state.open);
                }
            )
        }

    };
    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    openSnackbar = ({ message }) => {
        this.setState({
            open: true,
            message
        });
    };
    handleSubmit = (e) => {
        e.preventDefault();
        let curpass = this.state.cp_currentPassword
        let newpass = this.state.cp_newPassword
        this.setState({ loading: true });
        this.props.changePassword(curpass, newpass, this.passwordUpdated)
    }
    passwordUpdated = () => {
        this.setState({
            message: 'Password changed Successfully.!',
            open: true,
            loading: false
        });
    };

    render() {
        const { classes, auth, authError } = this.props;

        console.log(authError)
        const { loading } = this.state;
        const message = (

        );
        if (!auth.uid) return <Redirect to='/signin' />
        return (

                {/* {authError ? this.openSnackbar({ message: '{authError}' }) : null} */}

                <GridContainer>
                    <GridItem xs={12} sm={12} md={12}>

                        <Card>
                            <CardHeader color="warning">

Change Password

                            </CardHeader>
                            <form >
                                <GridContainer>
                                    <GridItem xs={12} sm={12} md={6}>
                                        <CardBody>
                                            <GridContainer>
                                                <GridItem xs={12} sm={12} md={12}>

                                                    <TextField
                                                        id="cp_currentPassword"
                                                        label="Current Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_currentPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>

                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_newPassword"
                                                        label="New Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_newPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_confirmPassword"
                                                        label="Confirm Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_confirmPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                            </GridContainer>

                                        </CardBody>
                                        <CardFooter>

                                            <Button color="warning" onClick={(e) => this.handleSubmit(e)} disabled={loading}>
                                                {loading && <CircularProgress style={{ color: 'white', height: '20px', width: '20px', marginRight: '10px' }} />}
                                                Change Password
                      </Button>
                                        </CardFooter>
                                    </GridItem>
                                </GridContainer>
                            </form>
                        </Card>

                    </GridItem>

                </GridContainer>

                <Snackbar
                    open={this.state.open}
                    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
                    message={message}
                    variant="error"
                    onClose={() => this.setState({ open: false, message: '' })}
                    action={
                        <IconButton
                            key="close"
                            aria-label="Close"
                            color="inherit"
                            className={classes.close}
                            onClick={() => this.setState({ open: false, message: '' })}
                        >
                            <CloseIcon className={classes.icon} />
                        </IconButton>
                    }
                    autoHideDuration={3000}
                />

        )
    }
}
const mapstateToProps = (state) => {
    return {
        auth: state.firebase.auth,
        authError: state.authroot.autherr
    }
}
const mapDispatchtoProps = (dispatch, getState) => {
    return {
        changePassword: (currentPassword, newPassword, passwordUpdated) => { dispatch(changePassword(currentPassword, newPassword, passwordUpdated)) }
    }
}
export default compose(
    withStyles(styles),
    connect(mapstateToProps, mapDispatchtoProps)
)(ChangePassword);

auth action

export const changePassword = (currentPassword, newPassword, func) => {
    return (dispatch, getState, { getFirebase }) => {
        const firebase = getFirebase();
        var user = firebase.auth().currentUser;
        var cred = firebase.auth.EmailAuthProvider.credential(
            user.email, currentPassword);
            // reauthenticateAndRetrieveDataWithCredential
        user.reauthenticateWithCredential(cred)
            .then(() => {
                user.updatePassword(newPassword).then(() => {
                    console.log("Password updated!");
                    func();
                }).catch((error) => { dispatch({ type: 'CHANGEPASSWORD_ERR', error }) });
            }).catch((error) => {
                dispatch({ type: 'CHANGEPASSWORD_CURRPSW_ERR', error })
            });

    }
}

auth reducer

 case 'CHANGEPASSWORD_SUCCESS':
            return {
                ...state,
                 //action.func

            };
            case 'CHANGEPASSWORD_CURRPSW_ERR':
            return {
                ...state,
                autherr: action.error.message

            };
            case 'CHANGEPASSWORD_ERR':
                return {
                    ...state,
                    autherr: action.error.message

                };

Body:
Just set the open prop of Snackbar component straight from the props like,

<Snackbar
    open={!!this.props.authError}
    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
    message={message}
    variant="error"
    onClose={() => this.setState({ open: false, message: '' })}
    action={
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            className={classes.close}
            onClick={() =>{have a action dispatch for clear error added into the reducer}}
        >
            <CloseIcon className={classes.icon} />
        </IconButton>
    }
    autoHideDuration={3000}
/>


问:
boto3 - get all required API calls for a specific method in boto3
Given a service name and list of actions, I need to find out which API calls are required in the boto3 method. suggestions?

I've tried for example getting a code object of the boto3 code and examine there through something like :

```<code>iam = boto3.client('iam')

code = iam.list_roles.__code__
</code>```

but even if i have the exact location of the call, can't find what API calls are required (HTTP-Post/ GET / etc..)

答:
Solved.
I found that every service client has an  '.meta.method_to_api_mapping' field
that return exactly what i meant. </p>

Body:
Given a service name and list of actions, I need to find out which API calls are required in the boto3 method. suggestions?

I've tried for example getting a code object of the boto3 code and examine there through something like :

iam = boto3.client('iam')

code = iam.list_roles.__code__

but even if i have the exact location of the call, can't find what API calls are required (HTTP-Post/ GET / etc..)


问:
Automatic completion
Is there a way to reach the second picture automatically?

Google Doc Example.

https://docs.google.com/spreadsheets/d/1eKpvC9I59l3zGmzYhSHE5UU9yFMMxCcuQ6Ww2zoCf6Q/edit?usp=sharing

Direct example:

cell [3] -> A

cells [4,5,6,7,8,9] -> empty

cell [10] -> B

cells [11,12,13,14,15,16]  -> empty

What i need automatically:

cell [3] -> A

cells [4,5,6,7,8,9] -> A

cell [10] -> B

cells [11,12,13,14,15,16]  -> B

答:
Assume the data is in column A.

In column B you should use the formula:

```<code>=if(isblank(a3),b2,a3)
</code>```

You use this formula for the entire range which you want filled. You fill it in B3, hit . Then copy / paste the B3 cell to the entire range down.

That should do it.

Note: you cannot use this approach in-place. You need to create the "beautiful" data in a separate temporary range, and then do a copy / paste of values-only of the beautiful data into the original range. After that, you can delete the temporary range.

An alternative is the following:

In the empty cells use the formula:

```<code>=a3  (in cell a4)
=a4  (in cell a5)
</code>```

and so on (cell ranges taken from attached screenshot, not from Google Docs)

Title: Automatic completion

Body:
Assume the data is in column A.

In column B you should use the formula:

=if(isblank(a3),b2,a3)

You use this formula for the entire range which you want filled. You fill it in B3, hit . Then copy / paste the B3 cell to the entire range down.

That should do it.

Note: you cannot use this approach in-place. You need to create the "beautiful" data in a separate temporary range, and then do a copy / paste of values-only of the beautiful data into the original range. After that, you can delete the temporary range.

An alternative is the following:

In the empty cells use the formula:

=a3  (in cell a4)
=a4  (in cell a5)

and so on (cell ranges taken from attached screenshot, not from Google Docs)


问:
django model inline dynamic default value for foreignKey
I have these 3 models in models.py

```<code>class Customer(models.Model):
    name = models.CharField(max_length=50)
    ....

class Agent(django.contrib.auth.models.User):
    regions = models.CharField(max_length=50, choices={...})
    ....

class Payment(models.Model):
    added_by = models.ForeignKey(Agent)
    customer = models.ForeignKey(Customer)
    date = models.DateField(default=datetime.date.today())
    amount = models.IntegerField(default=0)
</code>```

and also in my admin.py, I have these classes:

```<code>class PaymentInline(admin.TabularInline):
     model = Payment
     extra = 0

class CustomerAdmin(admin.ModelAdmin):
    inlines = [PaymentInline,]
</code>```

Question#1:
is it possible to have the 'agent' field pre-set to the current logged in Agent in 'PaymentInline' in Customer change page.
we can preset the value for the agent field, just like the way that django does for 'Customer' field, which is hidden from the inline already.

Question#2:
or is there a way to construct a link, with the customer_id and agent_id "hardcoded" in the url; and in the add payment page, we could have the default and non-editable values for customer field and agent field
for example,
this url[1] will link us to the normal add page, but with the customer_field and agent_feild set to Agent.objects.get(id=1) and Customer.objects.get(id=1). (Or we can hide these 2 fields since they are non-editable anyway)

[1]http://localhost:8000/admin/my_app/payment/add/?customer_id=1&agent_id=1

Any thoughts?

Thanks

Max

答:
A TabularInline is an InlineModelAdmin and as such let's you define formfield_for_foreignkey():</p>

```<code>class PaymentInline(admin.TabularInline):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'added_by':
            kwargs['initial'] = request.user.id
            return db_field.formfield(**kwargs)
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
        )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have these 3 models in models.py

class Customer(models.Model):
    name = models.CharField(max_length=50)
    ....

class Agent(django.contrib.auth.models.User):
    regions = models.CharField(max_length=50, choices={...})
    ....

class Payment(models.Model):
    added_by = models.ForeignKey(Agent)
    customer = models.ForeignKey(Customer)
    date = models.DateField(default=datetime.date.today())
    amount = models.IntegerField(default=0)

and also in my admin.py, I have these classes:

class PaymentInline(admin.TabularInline):
     model = Payment
     extra = 0

class CustomerAdmin(admin.ModelAdmin):
    inlines = [PaymentInline,]

Question#1:
is it possible to have the 'agent' field pre-set to the current logged in Agent in 'PaymentInline' in Customer change page.
we can preset the value for the agent field, just like the way that django does for 'Customer' field, which is hidden from the inline already.

Question#2:
or is there a way to construct a link, with the customer_id and agent_id "hardcoded" in the url; and in the add payment page, we could have the default and non-editable values for customer field and agent field
for example,
this url[1] will link us to the normal add page, but with the customer_field and agent_feild set to Agent.objects.get(id=1) and Customer.objects.get(id=1). (Or we can hide these 2 fields since they are non-editable anyway)

[1]http://localhost:8000/admin/my_app/payment/add/?customer_id=1&agent_id=1

Any thoughts?

Thanks

Max

Body:
A TabularInline is an InlineModelAdmin and as such let's you define formfield_for_foreignkey():

class PaymentInline(admin.TabularInline):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'added_by':
            kwargs['initial'] = request.user.id
            return db_field.formfield(**kwargs)
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
        )


问:
Nginx container fails to start on Cloud Run
I'm attempting to serve simple static page with Nginx on Cloud Run. But the container fails to properly start serving.

Container is starting, as shown by the debug lines echoed from docker-entrypoint.sh:

```<code>2019-05-26T22:19:02.340289Z testing config
2019-05-26T22:19:02.433935Z nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
2019-05-26T22:19:02.434903Z nginx: configuration file /etc/nginx/nginx.conf test is successful
2019-05-26T22:19:02.436605Z starting on 8080
2019-05-26T22:19:02.487188Z2019/05/26 22:19:02 [alert] 6#6: prctl(PR_SET_DUMPABLE) failed (22: Invalid argument)
</code>```

and eventually terminates

```<code>2019-05-26T22:20:00.153060259ZContainer terminated by the container manager on signal 9.
</code>```

In order to conform with the Cloud Run service contract specifically listening on $PORT the docker-entrypoint.sh performs $PORT substitution in conf.d/*.conf.

```<code>FROM nginx:1.15-alpine

COPY nginx-default.conf.template /etc/nginx/conf.d/default.conf.template

COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["nginx", "-g", "daemon off;"]
</code>```

I'm pretty confident issue lies within docker-entrypoint.sh because once $PORT is hardcoded as 8080 and image looks like this:

```<code>FROM nginx:1.15-alpine

COPY nginx-default.conf /etc/nginx/conf.d/default.conf
</code>```

Cloud Run "runs" fine.

The code performing the substitution:

export NGINX_PORT=${PORT:-8080}
for f in $(find /etc/nginx/conf.d/ -type f -name '*.conf'); do
  envsubst '$NGINX_PORT' < $f > $f
done
```

NOTE: reading < $f and writing > $f to the same file works as tested by running the container locally.

Expected

nginx configuration gets $PORT placeholder substituted with actual values

container runs and listens on $PORT on Cloud Run

Actual

container fails to run on Cloud Run

container runs and listens on $PORT locally

答:
fixed by replacing

```<code>for f in $(find /etc/nginx/conf.d/ -type f -name '*.conf'); do
  envsubst '$NGINX_PORT' < $f > $f
done
</code>```

with

```<code>sed -i "s/\${NGINX_PORT}/${NGINX_PORT}/g" /etc/nginx/conf.d/*.conf
</code>```

and changing $NGINX_PORT -> ${NGINX_PORT} in *.conf files to avoid substitution ambiguities

Body:
I'm attempting to serve simple static page with Nginx on Cloud Run. But the container fails to properly start serving.

Container is starting, as shown by the debug lines echoed from docker-entrypoint.sh:

2019-05-26T22:19:02.340289Z testing config
2019-05-26T22:19:02.433935Z nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
2019-05-26T22:19:02.434903Z nginx: configuration file /etc/nginx/nginx.conf test is successful
2019-05-26T22:19:02.436605Z starting on 8080
2019-05-26T22:19:02.487188Z2019/05/26 22:19:02 [alert] 6#6: prctl(PR_SET_DUMPABLE) failed (22: Invalid argument)

and eventually terminates

2019-05-26T22:20:00.153060259ZContainer terminated by the container manager on signal 9.

In order to conform with the Cloud Run service contract specifically listening on $PORT the docker-entrypoint.sh performs $PORT substitution in conf.d/*.conf.

FROM nginx:1.15-alpine

COPY nginx-default.conf.template /etc/nginx/conf.d/default.conf.template

COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["nginx", "-g", "daemon off;"]

I'm pretty confident issue lies within docker-entrypoint.sh because once $PORT is hardcoded as 8080 and image looks like this:

FROM nginx:1.15-alpine

COPY nginx-default.conf /etc/nginx/conf.d/default.conf

Cloud Run "runs" fine.

The code performing the substitution:

export NGINX_PORT=${PORT:-8080}
for f in $(find /etc/nginx/conf.d/ -type f -name '*.conf'); do
  envsubst '$NGINX_PORT' < $f > $f
done

NOTE: reading < $f and writing > $f to the same file works as tested by running the container locally.

Expected

nginx configuration gets $PORT placeholder substituted with actual values

container runs and listens on $PORT on Cloud Run

Actual

container fails to run on Cloud Run

container runs and listens on $PORT locally

Body:
fixed by replacing

for f in $(find /etc/nginx/conf.d/ -type f -name '*.conf'); do
  envsubst '$NGINX_PORT' < $f > $f
done

with

sed -i "s/\${NGINX_PORT}/${NGINX_PORT}/g" /etc/nginx/conf.d/*.conf

and changing $NGINX_PORT -> ${NGINX_PORT} in *.conf files to avoid substitution ambiguities


问:
getYesterdayDate_yyyy_MM_dd() this method with return type java.sql.date
i want to create a method java.sql.Date getYesterdayDate_yyyy_MM_dd() using java 8 get yesterday date and formatted it then it is converted in string how to convert string in sql date i try date.valuof is throwing exception</p>

答:
```<code>LocalDateTime yesterday = LocalDateTime.now().minusDays(1);

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
  String formattedDate = yesterday.format(formatter);

  System.out.println("formattedDate="+formattedDate);

  // formattedDate=27-05-2019 11:58:35
</code>```


答:
As explained in the debug module documentation, the var option is expecting a variable name, not a scalar for output. You are getting an error because \ is not expected in a variable name. Running the playbook with -vvv will give you a little more explanations.

In this case you need to use the msg option.

```<code>- hosts: localhost
  gather_facts: false
  vars:
    account_id: 123
  tasks:
    - name: Add \ to path
      debug:
        msg: "base_dir/{{ account_id }}/path/to/G\\$/subdirectory/html/"
</code>```

Result

```<code>PLAY [localhost] ***************************************************************

TASK [Add \ to path] ***********************************************************
ok: [localhost] => {
    "msg": "base_dir/123/path/to/G\\$/subdirectory/html/"
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
</code>```

Title: Ansible PLaybook: Escape '$' in Linux path

Body:
I have a path which looks like this -

base_dir/123/path/to/G\$/subdirectory/html/

When I try to set this path in Ansible playbook, it throws error. If add \$ to escape '\', it throws unexpected failure error.

Playbkook -

- hosts: localhost
  vars:
    account_id: 123
  tasks:
  - name: Add \ to path
    debug:
      var: "base_dir/{{ account_id }}/path/to/G\\$/subdirectory/html/"

Result -

TASK [Gathering Facts] *************************************************************************************************************************************************
task path: /playbooks/example_path.yml:2
ok: [localhost]
META: ran handlers

TASK [Add \ to path] ***************************************************************************************************************************************************
task path: /playbooks/exmaple_path.yml:6
fatal: [localhost]: FAILED! => {
    "msg": "Unexpected failure during module execution."
}

PLAY RECAP *************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1

Body:
As explained in the debug module documentation, the var option is expecting a variable name, not a scalar for output. You are getting an error because \ is not expected in a variable name. Running the playbook with -vvv will give you a little more explanations.

In this case you need to use the msg option.

- hosts: localhost
  gather_facts: false
  vars:
    account_id: 123
  tasks:
    - name: Add \ to path
      debug:
        msg: "base_dir/{{ account_id }}/path/to/G\\$/subdirectory/html/"

Result

PLAY [localhost] ***************************************************************

TASK [Add \ to path] ***********************************************************
ok: [localhost] => {
    "msg": "base_dir/123/path/to/G\\$/subdirectory/html/"
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


问:
Can I check for an omitted HTTP request with Citrus framework?
I have built a testsuite for a service orchestration with Citrus framework.

In one case, when the former request results in an "empty" response, the last orchestration step, a HTTP request, is skipped.

How can I test that this last request is NOT executed? I did not found a way to do this.

When I do not check this with an explicit expectation, the test is successful no matter if a request is executed or not.

I have an HTTP server simulation in place to respond according to the request. What I was looking for is something like

```<code>runner.http(action -> action.server(simulation)
    .receiveNothingDuring(5000)
);
</code>```

to wait for 5 seconds for a request to arrive and SUCCEED if nothing arrives. This is kind of the inverse of the normal receive assertion.

答:
You can use the receiveTimeout action that is exactly what you need:

runner.receiveTimeout(action -> action.endpoint(simulation)
                    .timeout(5000));
```

See also descriptions in docs

Body:
I have built a testsuite for a service orchestration with Citrus framework.

In one case, when the former request results in an "empty" response, the last orchestration step, a HTTP request, is skipped.

How can I test that this last request is NOT executed? I did not found a way to do this.

When I do not check this with an explicit expectation, the test is successful no matter if a request is executed or not.

I have an HTTP server simulation in place to respond according to the request. What I was looking for is something like

runner.http(action -> action.server(simulation)
    .receiveNothingDuring(5000)
);

to wait for 5 seconds for a request to arrive and SUCCEED if nothing arrives. This is kind of the inverse of the normal receive assertion.

Body:
You can use the receiveTimeout action that is exactly what you need:

runner.receiveTimeout(action -> action.endpoint(simulation)
                    .timeout(5000));

See also descriptions in docs


问:
Android resource linking failed when trying to use custom font in styles.xml
I'm trying to use custom fonts with new "android:fontFamily" attribute, added in Android O. While this works fin in xml:

```<code>android:fontFamily="@font/sf_pro_text_semibold"
</code>```

using same construction in styles.xml like this:

```<code><item name="android:fontFamily">@font/sf_pro_text_semibold"</item>
</code>```

leads to following build error:

```<code>Execution failed for task ':app:processDebugResources'.
</code>```

Android resource linking failed
    C:\Users\anro.gradle\caches\transforms-2\files-2.1\4125ed89f50d00591f7f19265a14b826\res\values\values.xml: AAPT: error: resource font/sf_pro_text_semibold" (aka com.example.fonttesting:font/sf_pro_text_semibold") not found.

Lots of tutorials say that it should work, but it doesn't. I suppose the problem is in build.gradle file, but I don't even know what to try to make it work (Downgrading to older support library version is not a good solution). Here is my build.gradle file:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "com.example.fonttesting"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
</code>```

So, does anybody know how to make custom fonts in styles.xml work with androidx?

答:
AAPT: error: resource font/sf_pro_text_semibold" (aka com.example.fonttesting:font/sf_pro_text_semibold") not found.

There is a typo:

Remove the " char:

```<code><item name="android:fontFamily">@font/sf_pro_text_semibold</item>
</code>```

instead of

```<code><item name="android:fontFamily">@font/sf_pro_text_semibold"</item>
</code>```

Body:
I'm trying to use custom fonts with new "android:fontFamily" attribute, added in Android O. While this works fin in xml:

android:fontFamily="@font/sf_pro_text_semibold"

using same construction in styles.xml like this:

<item name="android:fontFamily">@font/sf_pro_text_semibold"</item>

leads to following build error:

Execution failed for task ':app:processDebugResources'.

Android resource linking failed
    C:\Users\anro.gradle\caches\transforms-2\files-2.1\4125ed89f50d00591f7f19265a14b826\res\values\values.xml: AAPT: error: resource font/sf_pro_text_semibold" (aka com.example.fonttesting:font/sf_pro_text_semibold") not found.

Lots of tutorials say that it should work, but it doesn't. I suppose the problem is in build.gradle file, but I don't even know what to try to make it work (Downgrading to older support library version is not a good solution). Here is my build.gradle file:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "com.example.fonttesting"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

So, does anybody know how to make custom fonts in styles.xml work with androidx?

Body:
AAPT: error: resource font/sf_pro_text_semibold" (aka com.example.fonttesting:font/sf_pro_text_semibold") not found.

There is a typo:

Remove the " char:

<item name="android:fontFamily">@font/sf_pro_text_semibold</item>

instead of

<item name="android:fontFamily">@font/sf_pro_text_semibold"</item>


问:
Not able to login to Salesforce application through JMeter
Not able to login into Salesforce Application through JMeter.

Please help.

I am providing correct Username and Password but still not able to login successfully.

答:
Please note that with username and password only it will not work. You need to correlate all the dynamic value which maintains the state of the application like sessionID, X-CSRF token etc.
So, record two scripts and compare the dynamic parameters and then correlate them.
For more information on correlation please check this. and correlation sales force.</p>


问:
move files that no not contain specific string
I would like to move files using mv that do not contain the letter S in the filename. Could not find anyhting in the mv manual. Maybe combination with find or grep? It has to be case-sensitive.

input:

```<code>  file1
  fileS1
  file2
  fileS2
</code>```

file to move:

```<code>  file1
  file2
</code>```

答:
You can use find with the -not flag for example.

find /path/to/source/dir -type f -not -name '*S*' \
    | xargs mv -t /path/to/target/dir
```

Body:
I would like to move files using mv that do not contain the letter S in the filename. Could not find anyhting in the mv manual. Maybe combination with find or grep? It has to be case-sensitive.

input:

  file1
  fileS1
  file2
  fileS2

file to move:

  file1
  file2


问:
What are the often misunderstood concepts in C++?
What are the often misunderstood concepts in c++?</p>

答:
Free functions are not bad just because they are not within a class C++ is not an OOP language alone, but builds upon a whole stack of techniques.

I've heard it many times when people say free functions (those in namespaces and global namespace) are a "relict of C times" and should be avoided. Quite the opposite is true. Free functions allow to decouple functions from specific classes and allow reuse of functionality. It's also recommended to use free functions instead of member functions if the function don't need access to implementation details - because this will eliminate cascading changes when one changes the implementation of a class among other advantages.

This is also reflected in the language: The range-based for loop in C++0x (next C++ version released very soon) will be based on free function calls. It will get begin / end iterators by calling the free functions begin and end.

OwnerDisplayName: rajKumar

LastEditorDisplayName: starblue

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
Changing window.navigator within puppeteer to bypass antibot system
I'm trying to make my online bot undetectable. I read number of articles how to do it and I took all tips together and used them. One of them is to change window.navigator.webdriver.

I managed to change window.navigator.webdriver within puppeteer by this code:

```<code>await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, 'webdriver', {
        get: () => undefined
    });
});
</code>```

I'm bypassing this test just fine:

However this test is still laughing at me somehow:

Why WEBDRIVER is inconsistent?

答:
Try this,

First, remove the definition, it will not work if you define and delete from prototype.

```<code>Object.defineProperty(navigator, 'webdriver', ()=>{}) // <-- delete this part
</code>```

Replace your code with this one.

```<code>delete navigator.__proto__.webdriver;
</code>```

Result:

Why does it work?

Removing directly just remove the instance of the object rather than the actual definition. The getter and setter is still there, so browser can find it.

However if you remove from the actual prototype, it will not exist at all in any instance anymore.

Additional Tips

You mentioned you want to make your app undetectable, there are many plugins which achieve the same, for example this package called puppeteer-extra-plugin-stealth includes some cool anti-bot detection techniques. Sometimes it's better to just reuse some packages than to re-create a solution over and over again.

PS: I might be wrong above the above explanation, feel free to guide me so I can improve the answer.

Body:
I'm trying to make my online bot undetectable. I read number of articles how to do it and I took all tips together and used them. One of them is to change window.navigator.webdriver.

I managed to change window.navigator.webdriver within puppeteer by this code:

await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, 'webdriver', {
        get: () => undefined
    });
});

I'm bypassing this test just fine:

However this test is still laughing at me somehow:

Why WEBDRIVER is inconsistent?

Body:
Try this,

First, remove the definition, it will not work if you define and delete from prototype.

Object.defineProperty(navigator, 'webdriver', ()=>{}) // <-- delete this part

Replace your code with this one.

delete navigator.__proto__.webdriver;

Result:

Why does it work?

Removing directly just remove the instance of the object rather than the actual definition. The getter and setter is still there, so browser can find it.

However if you remove from the actual prototype, it will not exist at all in any instance anymore.

Additional Tips

You mentioned you want to make your app undetectable, there are many plugins which achieve the same, for example this package called puppeteer-extra-plugin-stealth includes some cool anti-bot detection techniques. Sometimes it's better to just reuse some packages than to re-create a solution over and over again.

PS: I might be wrong above the above explanation, feel free to guide me so I can improve the answer.


问:
How do I get monitor resolution in Python?
What is the simplest way to get monitor resolution (preferably in a tuple)? </p>

答:
If you are working on Windows OS, you can use OS module to get it:

```<code>import os
cmd = 'wmic desktopmonitor get screenheight, screenwidth'
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))
</code>```

It will return a tuple (Y,X) where Y is the vertical size and X is the horizontal size. This code works on Python 2 and Python 3

UPDATE

For Windows 8/8.1/10, the above answer doesn't work, use the next one instead:

```<code>import os
cmd = "wmic path Win32_VideoController get CurrentVerticalResolution,CurrentHorizontalResolution"
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))
</code>```

Body:
If you are working on Windows OS, you can use OS module to get it:

import os
cmd = 'wmic desktopmonitor get screenheight, screenwidth'
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))

It will return a tuple (Y,X) where Y is the vertical size and X is the horizontal size. This code works on Python 2 and Python 3

UPDATE

For Windows 8/8.1/10, the above answer doesn't work, use the next one instead:

import os
cmd = "wmic path Win32_VideoController get CurrentVerticalResolution,CurrentHorizontalResolution"
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))


问:
How to add only one currency for paypal payment
I am integrating PayPal with one of my websites but the problem is that they want Indian customers to pay in INR only but it is actually complicating things.

The way I am integrating PayPal in my website is taken from the question which is described over here.

https://forum.yiiframework.com/t/yii2-paypal-integration/126032

But when Indian customers are trying to pay using USD the payment fails how can I avoid this problem I just want only one currency implementation in my website

答:
I got this from PayPal support:

Unfortunately domestic transaction is not possible to receive in USD and similarly international transaction should be in USD. There is no way to have single currency for both the transactions. Thanks and regards,


问:
RegEx for matching specific numeric patterns
I want to match numbers without signs or operator, So I came up this regex.

```<code>echo "-123 +1234" | grep -Po '(?<=-)123 (?<=\+)1234'
</code>```

but it's not matching the string. Why two lookbehind not working? If I do

```<code>echo "-123 +1234" | grep -Po '(?<=-)123
</code>```

I get the correct result 123 but when I do grep -Po '(?<=-)123 (?<=\+)1234' the second part is not matching.

My desired result:

```<code>123 1234
</code>```

答:
In regex patterns, ab means a followed by b, which is another way of saying b preceded by a. Don't forget that (?<=...) matches zero characters from the perspective of the surrounding pattern, so it's as if it wasn't there from the point of view of the surrounding pattern. This means that (?<=-)123 (?<=\+)1234 will match a subset of what 123 1234 matches. It's of particular interest that the pattern will only match if 1234 is preceded by a space.

The subset of strings that match are those where 123 is preceded by a - (thanks to (?<=-)) and 1234 is preceded by a + (thanks to (?<=\+)). It's of particular interest that the pattern will only match if 1234 is preceded by a +.

Since (?<=-)123 (?<=\+)1234 will only match if 1234 is preceded by a space and preceded by a +, it will never match.

It's not clear what you want.

Maybe you want this?

```<code>$ echo "-123 +1234" | grep -Po '\d+'
123
1234
</code>```

Maybe you want this?

```<code>$ echo "-123 +1234" | perl -nle'@m=/\d+/g; print "@m" if @m'
123 1234
</code>```

Maybe you want this?

```<code>$ echo "-123 +1234" | perl -nle'print "$1 $2" if /-(\d+) \+(\d+)/'
123 1234
</code>```

Body:
I want to match numbers without signs or operator, So I came up this regex.

echo "-123 +1234" | grep -Po '(?<=-)123 (?<=\+)1234'

but it's not matching the string. Why two lookbehind not working? If I do

echo "-123 +1234" | grep -Po '(?<=-)123

I get the correct result 123 but when I do grep -Po '(?<=-)123 (?<=\+)1234' the second part is not matching.

My desired result:

123 1234

Body:
In regex patterns, ab means a followed by b, which is another way of saying b preceded by a. Don't forget that (?<=...) matches zero characters from the perspective of the surrounding pattern, so it's as if it wasn't there from the point of view of the surrounding pattern. This means that (?<=-)123 (?<=\+)1234 will match a subset of what 123 1234 matches. It's of particular interest that the pattern will only match if 1234 is preceded by a space.

The subset of strings that match are those where 123 is preceded by a - (thanks to (?<=-)) and 1234 is preceded by a + (thanks to (?<=\+)). It's of particular interest that the pattern will only match if 1234 is preceded by a +.

Since (?<=-)123 (?<=\+)1234 will only match if 1234 is preceded by a space and preceded by a +, it will never match.

It's not clear what you want.

Maybe you want this?

$ echo "-123 +1234" | grep -Po '\d+'
123
1234

Maybe you want this?

$ echo "-123 +1234" | perl -nle'@m=/\d+/g; print "@m" if @m'
123 1234

Maybe you want this?

$ echo "-123 +1234" | perl -nle'print "$1 $2" if /-(\d+) \+(\d+)/'
123 1234