问:
How to make combinations between all items of 2 lists in NetLogo 6.2?
I have the following doubt: I have two lists with three values each and I would like to make combinations between the items in these 2 lists.

For example:
list1 [5 10 15] and list2 [2 4 8]. I would like to have the following combinations:

list3 [[5 2] [10 2] [15 2] [5 4] [10 4] [15 4] [5 8] [10 8] [15 8]]

I was only able to do the following combination:

```<code>let list1 ( list repro1 repro2 repro3 ) ;; input variable in the interface. repro1 = 5; repro2 = 10 and repro3 = 15
  let list2 ( list met1 met2 met3 ) ;; input variable in the interface. met1 = 2; met2 = 4 and met3 = 8
  let list3 ( map [ [ l1 l2 ] -> ( list l1 l2 ) ] list1 list2 )
  print list3 ;; command center: [[5 2] [10 4] [15 8]]
</code>```

Can anybody help me?

Thanks in advance

答:
Excellent work on the example code, thank you for doing that! You were definitely on the right track, you just needed to add an extra map inside the first so that the iteration would happen for each combination, rather than for item 0 in both lists, then item 1 in both lists, then for item 2 in both lists, etc:

```<code>to to combine
  let list1 [5 10 15]
  let list2 [2 4 8]
  let list3 ( reduce sentence ( map [ i -> map [ j -> list i j ] list2 ] list1 ))
  print list3
end
</code>```

Output:

```<code>[[5 2] [5 4] [5 8] [10 2] [10 4] [10 8] [15 2] [15 4] [15 8]]
</code>```

reduce sentence above 'flattens' the list by one level so that you have a single list of lists, rather than a list of lists of lists.

If you want the exact order you indicated above, you can shuffle the order in which you pass the arguments- for example:

```<code>to combine
  let list1 [5 10 15]
  let list2 [2 4 8]
  let list3 ( reduce sentence ( map [ i -> map [ j -> list j i ] list1 ] list2 ))
  print list3
end
</code>```

Gives:

```<code>[[5 2] [10 2] [15 2] [5 4] [10 4] [15 4] [5 8] [10 8] [15 8]]
</code>```

Not sure if the order of the items matters here, just wanted to point that out.

Body:
I have the following doubt: I have two lists with three values each and I would like to make combinations between the items in these 2 lists.

For example:
list1 [5 10 15] and list2 [2 4 8]. I would like to have the following combinations:

list3 [[5 2] [10 2] [15 2] [5 4] [10 4] [15 4] [5 8] [10 8] [15 8]]

I was only able to do the following combination:

let list1 ( list repro1 repro2 repro3 ) ;; input variable in the interface. repro1 = 5; repro2 = 10 and repro3 = 15
  let list2 ( list met1 met2 met3 ) ;; input variable in the interface. met1 = 2; met2 = 4 and met3 = 8
  let list3 ( map [ [ l1 l2 ] -> ( list l1 l2 ) ] list1 list2 )
  print list3 ;; command center: [[5 2] [10 4] [15 8]]

Can anybody help me?

Thanks in advance

Body:
Excellent work on the example code, thank you for doing that! You were definitely on the right track, you just needed to add an extra map inside the first so that the iteration would happen for each combination, rather than for item 0 in both lists, then item 1 in both lists, then for item 2 in both lists, etc:

to to combine
  let list1 [5 10 15]
  let list2 [2 4 8]
  let list3 ( reduce sentence ( map [ i -> map [ j -> list i j ] list2 ] list1 ))
  print list3
end

Output:

[[5 2] [5 4] [5 8] [10 2] [10 4] [10 8] [15 2] [15 4] [15 8]]

reduce sentence above 'flattens' the list by one level so that you have a single list of lists, rather than a list of lists of lists.

If you want the exact order you indicated above, you can shuffle the order in which you pass the arguments- for example:

to combine
  let list1 [5 10 15]
  let list2 [2 4 8]
  let list3 ( reduce sentence ( map [ i -> map [ j -> list j i ] list1 ] list2 ))
  print list3
end

Gives:

[[5 2] [10 2] [15 2] [5 4] [10 4] [15 4] [5 8] [10 8] [15 8]]

Not sure if the order of the items matters here, just wanted to point that out.


来源: stackexchange

问:
Keeping forward slashes in cookie PHP
I am building a log in page.  Right now, there is an expiration on the page that I use a cookie for.  I want the site to redirect back to the page they were on after they log in again.

For this, I use a cookie that has the name of the page stored in it (example, queue.php) and it will take them back.

This method works great if I'm going to a page that is in the same directory, but if I want to go back to a sub-directory, (for example, Deployment/deployment.php) it does not work.

I have tried urlencode(), backslashes, addslashes(), %2F in place of the forward slash, and nothing seems to be working.

This is how I am setting the cookie:

```<code>$url_name = "Deployment/deployment.php";
setcookie("url",$url_name);
</code>```

Any help would be appreciated, I am completely lost.

答:
Can you explain your problem a bit more? I just tried the following, and was able to retrieve the value of the cookie just fine:</p>

```<code><?php
$url = "http://google.com/mail";
echo "Setting cookie with value " . $url . "</br>";
setcookie("url", $url);
echo "The cookie is: " . $_COOKIE['url'] . "</br>";
?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Keeping forward slashes in cookie PHP

Body:
I am building a log in page.  Right now, there is an expiration on the page that I use a cookie for.  I want the site to redirect back to the page they were on after they log in again.

For this, I use a cookie that has the name of the page stored in it (example, queue.php) and it will take them back.

This method works great if I'm going to a page that is in the same directory, but if I want to go back to a sub-directory, (for example, Deployment/deployment.php) it does not work.

I have tried urlencode(), backslashes, addslashes(), %2F in place of the forward slash, and nothing seems to be working.

This is how I am setting the cookie:

$url_name = "Deployment/deployment.php";
setcookie("url",$url_name);

Any help would be appreciated, I am completely lost.

Body:
Can you explain your problem a bit more? I just tried the following, and was able to retrieve the value of the cookie just fine:

<?php
$url = "http://google.com/mail";
echo "Setting cookie with value " . $url . "</br>";
setcookie("url", $url);
echo "The cookie is: " . $_COOKIE['url'] . "</br>";
?>


问:
Azure-Devops: find in which branches a commit is contained
We have workitems in DevOps that have commits linked in them.

I open the Git commit in DevOps and would like to find information about which branches contain the commit.

How can I determine the branches for this commit?

答:
Update: the question has been edited to make more sense in the context of Git because commits may exist on multiple branches, even though Azure DevOps will only show zero or one branches for any specific commit in the UI. To see all of the branches that contain a commit as the question is currently worded, you can use the command line:

git branch --all --contains <commit-ID>

For the original wording of the question, since commits can exist on zero to many branches, it doesn't make sense to display the branch that a commit exists on. (Perhaps it would if there was only one branch that a commit existed on, but that would not be the normal case in a typical repo.)

I just confirmed in Azure DevOps that when you view a commit directly, it does not display any branch information. However, if you are viewing the history of a specific branch, and then click on a commit, you will see the branch name from which you viewed that commit, and it appears in the exact location you specified in your screenshot. If you click the same commit from multiple branches you will see different branch names there depending on which one you clicked on the commit from.

Note that when a branch is displayed, the URL has additional parameters. Here are examples without a branch displayed, and with one displayed:

```<code>commit/aa2fa1e1c344b8b79e012a2b47acf32c445e94b2
</code>```

vs

```<code>commit/aa2fa1e1c344b8b79e012a2b47acf32c445e94b2?refName=refs%2Fheads%2Fmy-branch-name
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Update: the question has been edited to make more sense in the context of Git because commits may exist on multiple branches, even though Azure DevOps will only show zero or one branches for any specific commit in the UI. To see all of the branches that contain a commit as the question is currently worded, you can use the command line:

git branch --all --contains <commit-ID>

For the original wording of the question, since commits can exist on zero to many branches, it doesn't make sense to display the branch that a commit exists on. (Perhaps it would if there was only one branch that a commit existed on, but that would not be the normal case in a typical repo.)

I just confirmed in Azure DevOps that when you view a commit directly, it does not display any branch information. However, if you are viewing the history of a specific branch, and then click on a commit, you will see the branch name from which you viewed that commit, and it appears in the exact location you specified in your screenshot. If you click the same commit from multiple branches you will see different branch names there depending on which one you clicked on the commit from.

Note that when a branch is displayed, the URL has additional parameters. Here are examples without a branch displayed, and with one displayed:

commit/aa2fa1e1c344b8b79e012a2b47acf32c445e94b2

vs

commit/aa2fa1e1c344b8b79e012a2b47acf32c445e94b2?refName=refs%2Fheads%2Fmy-branch-name


问:
Stm32 project configuration using CMake
i have recently switched my stm32 project to CMake to be independent on IDE. Root repository (application) contains multiple submodules (HAL, FreeRTOS etc.) and its CMakeLists.txt includes explicitly every single used file:

```<code>set(EXECUTABLE ${PROJECT_NAME}.elf)

add_executable(${EXECUTABLE}

    # Own sources
    src/main.c
    src/SEGGER_SYSVIEW_Config_FreeRTOS.c
    src/startup_stm32h723zgtx.s
    src/stm32h7xx_hal_timebase_tim.c
    src/system_stm32h7xx.c

    # Base CMSIS and HAL library
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim_ex.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_uart.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc_ex.c

    #long list of HAL c files there...

    # FreeRTOS library
    lib-freertos/croutine.c
    lib-freertos/event_groups.c
    lib-freertos/list.c
    lib-freertos/queue.c
    lib-freertos/stream_buffer.c
    lib-freertos/tasks.c
    lib-freertos/timers.c
    lib-freertos/portable/GCC/ARM_CM7/r0p1/port.c
    lib-freertos/trace/Sample/FreeRTOSV10/SEGGER_SYSVIEW_FreeRTOS.c
    lib-freertos/trace/SEGGER/Syscalls/SEGGER_RTT_Syscalls_GCC.c
    lib-freertos/trace/SEGGER/SEGGER_RTT_ASM_ARMv7M.S
    lib-freertos/trace/SEGGER/SEGGER_RTT_printf.c
    lib-freertos/trace/SEGGER/SEGGER_RTT.c
    lib-freertos/trace/SEGGER/SEGGER_SYSVIEW.c
    )

target_include_directories(${EXECUTABLE}
    PRIVATE
    include
    src

    lib-hal/stm32h7xx/CMSIS/Include
    lib-hal/stm32h7xx/CMSIS/Device/ST/STM32H7xx/Include
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Inc

    lib-freertos/include
    lib-freertos/trace/Config
    lib-freertos/trace/SEGGER
    lib-freertos/trace/Sample/FreeRTOSV10/
    lib-freertos/portable/GCC/ARM_CM7/r0p1
    )
</code>```

This solution works but i know it is not a sustainable approach. So i tried to create library in lib-hal and lib-freertos submodules, specifying their sources and includes

```<code>add_library(lib-hal-stm32h7xx)

target_include_directories(lib-hal-stm32h7xx
    PUBLIC
    CMSIS/Include
    CMSIS/Device/ST/STM32H7xx/Include
    STM32H7xx_HAL_Driver/Inc
    PRIVATE
    STM32H7xx_HAL_Driver/Src
)

target_sources(lib-hal-stm32h7xx
    PRIVATE
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim_ex.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_uart.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc_ex.c

    #long list of HAL c files there...
)
</code>```

and then using

```<code>add_subdirectory(lib-hal/stm32h7xx)
add_subdirectory(lib-freertos)
</code>```

and

```<code>target_link_library(${EXECUTABLE} lib-freertos lib-hal-stm32h7xx)
</code>```

to "import" submodules into application project. But when building the executable, gcc cannot access files stm32h7xx_hal_conf.h and FreeRTOSConfig.h which are located in root directory include. I do not want to put configuration headers into submodules because they are used in multiple projects with different configurations. Is it possible to somehow extend already specified directory search scope for library after adding it into parent project?

File structure of project:

```<code>-src
-include (configuration for lib-hal and lib-freertos included there)
 -lib-hal
  -includes...
  -sources...
 -lib-freertos
  -includes...
  -sources...
</code>```

Thanks in advance for response.

答:
As Tsyvarev mentioned in the comments, you can modify the properties of the target in your project. To keep things clean, I usually create a function for this and place it in a separate file.

Tip: you can also add source files to the target. In case of FreeRTOS, you could add architecture-specific files, in case all your projects don't run on the same MCU family.

```<code>function(configure_freertos target_name)
    target_sources(${target_name}
        PRIVATE
            lib-freertos/portable/GCC/ARM_CM7/r0p1/port.c
    )

    target_include_directories(${target_name}
        PUBLIC
            include
            lib-freertos/portable/GCC/ARM_CM7/r0p1
    )
endfunction()
</code>```

Title: Stm32 project configuration using CMake

Body:
i have recently switched my stm32 project to CMake to be independent on IDE. Root repository (application) contains multiple submodules (HAL, FreeRTOS etc.) and its CMakeLists.txt includes explicitly every single used file:

set(EXECUTABLE ${PROJECT_NAME}.elf)

add_executable(${EXECUTABLE}

    # Own sources
    src/main.c
    src/SEGGER_SYSVIEW_Config_FreeRTOS.c
    src/startup_stm32h723zgtx.s
    src/stm32h7xx_hal_timebase_tim.c
    src/system_stm32h7xx.c

    # Base CMSIS and HAL library
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim_ex.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_uart.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc.c
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc_ex.c

    #long list of HAL c files there...

    # FreeRTOS library
    lib-freertos/croutine.c
    lib-freertos/event_groups.c
    lib-freertos/list.c
    lib-freertos/queue.c
    lib-freertos/stream_buffer.c
    lib-freertos/tasks.c
    lib-freertos/timers.c
    lib-freertos/portable/GCC/ARM_CM7/r0p1/port.c
    lib-freertos/trace/Sample/FreeRTOSV10/SEGGER_SYSVIEW_FreeRTOS.c
    lib-freertos/trace/SEGGER/Syscalls/SEGGER_RTT_Syscalls_GCC.c
    lib-freertos/trace/SEGGER/SEGGER_RTT_ASM_ARMv7M.S
    lib-freertos/trace/SEGGER/SEGGER_RTT_printf.c
    lib-freertos/trace/SEGGER/SEGGER_RTT.c
    lib-freertos/trace/SEGGER/SEGGER_SYSVIEW.c
    )

target_include_directories(${EXECUTABLE}
    PRIVATE
    include
    src

    lib-hal/stm32h7xx/CMSIS/Include
    lib-hal/stm32h7xx/CMSIS/Device/ST/STM32H7xx/Include
    lib-hal/stm32h7xx/STM32H7xx_HAL_Driver/Inc

    lib-freertos/include
    lib-freertos/trace/Config
    lib-freertos/trace/SEGGER
    lib-freertos/trace/Sample/FreeRTOSV10/
    lib-freertos/portable/GCC/ARM_CM7/r0p1
    )

This solution works but i know it is not a sustainable approach. So i tried to create library in lib-hal and lib-freertos submodules, specifying their sources and includes

add_library(lib-hal-stm32h7xx)

target_include_directories(lib-hal-stm32h7xx
    PUBLIC
    CMSIS/Include
    CMSIS/Device/ST/STM32H7xx/Include
    STM32H7xx_HAL_Driver/Inc
    PRIVATE
    STM32H7xx_HAL_Driver/Src
)

target_sources(lib-hal-stm32h7xx
    PRIVATE
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_tim_ex.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_uart.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc.c
    STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_rcc_ex.c

    #long list of HAL c files there...
)

and then using

add_subdirectory(lib-hal/stm32h7xx)
add_subdirectory(lib-freertos)

and

target_link_library(${EXECUTABLE} lib-freertos lib-hal-stm32h7xx)

to "import" submodules into application project. But when building the executable, gcc cannot access files stm32h7xx_hal_conf.h and FreeRTOSConfig.h which are located in root directory include. I do not want to put configuration headers into submodules because they are used in multiple projects with different configurations. Is it possible to somehow extend already specified directory search scope for library after adding it into parent project?

File structure of project:

-src
-include (configuration for lib-hal and lib-freertos included there)
 -lib-hal
  -includes...
  -sources...
 -lib-freertos
  -includes...
  -sources...

Thanks in advance for response.

Body:
As Tsyvarev mentioned in the comments, you can modify the properties of the target in your project. To keep things clean, I usually create a function for this and place it in a separate file.

Tip: you can also add source files to the target. In case of FreeRTOS, you could add architecture-specific files, in case all your projects don't run on the same MCU family.

function(configure_freertos target_name)
    target_sources(${target_name}
        PRIVATE
            lib-freertos/portable/GCC/ARM_CM7/r0p1/port.c
    )

    target_include_directories(${target_name}
        PUBLIC
            include
            lib-freertos/portable/GCC/ARM_CM7/r0p1
    )
endfunction()


问:
.NET Core not showing in target framework dropdown for visual studio 2022
I have installed .NET core 3.1 and verified i can run .NET core 3.1 apps on my machine however when i go to create a new project the dropdown for target frameworks only allows .NET 6.0. I am using visual studio 2022. I am using visual studio 2019 on my laptop and i can add .NET core projects just fine.

Has anyone ran into this?

答:
Open Visual studio installer from start menu

Select Modify from Visual Studio that you want to add

in individual components select .net core or framework that you want to add to your visual studio version


问:
AWS Lambda create EC2 and associate EIP
I am trying to deploy an EC2 instance and associate an EIP to it, but I am getting and error when trying to associate the EIP because the instance is not running. This is my code:

```<code>import boto3
from botocore.exceptions import ClientError

AMI = 'ami-0bf84....'
INSTANCE_TYPE = 't2.micro'
KEY_NAME = 'EC2company'
SUBNET_ID = 'subnet-065....'

ec2 = boto3.client('ec2')

def lambda_handler(event, context):

    instance = ec2.run_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        SubnetId=SUBNET_ID,
        MaxCount=1,
        MinCount=1
    )

    waiter = ec2.get_waiter('instance_running')

    try:
        response = ec2.associate_address(
            AllocationId='eipalloc-0bc.....',
            InstanceId=instance['Instances'][0]['InstanceId'],
        )
        print(response)
    except ClientError as e:
        print(e)
</code>```

I suppose that the issue is related to be applying the waiter in the wrong way, and not sure how i should do it.

答:
As per EC2 waiters, you can create a waiter with:

```<code>waiter = client.get_waiter('instance_running')
</code>```

You then activate the waiter with:

```<code>waiter.wait(InstanceIds=['i-xxx']
</code>```

It polls EC2.Client.describe_instances() every 15 seconds until a successful state is reached. An error is returned after 40 failed checks.

Title: AWS Lambda create EC2 and associate EIP

Body:
I am trying to deploy an EC2 instance and associate an EIP to it, but I am getting and error when trying to associate the EIP because the instance is not running. This is my code:

import boto3
from botocore.exceptions import ClientError

AMI = 'ami-0bf84....'
INSTANCE_TYPE = 't2.micro'
KEY_NAME = 'EC2company'
SUBNET_ID = 'subnet-065....'

ec2 = boto3.client('ec2')

def lambda_handler(event, context):

    instance = ec2.run_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        SubnetId=SUBNET_ID,
        MaxCount=1,
        MinCount=1
    )

    waiter = ec2.get_waiter('instance_running')

    try:
        response = ec2.associate_address(
            AllocationId='eipalloc-0bc.....',
            InstanceId=instance['Instances'][0]['InstanceId'],
        )
        print(response)
    except ClientError as e:
        print(e)

I suppose that the issue is related to be applying the waiter in the wrong way, and not sure how i should do it.

Body:
As per EC2 waiters, you can create a waiter with:

waiter = client.get_waiter('instance_running')

You then activate the waiter with:

waiter.wait(InstanceIds=['i-xxx']

It polls EC2.Client.describe_instances() every 15 seconds until a successful state is reached. An error is returned after 40 failed checks.


问:
Is ESLint a Vim plugin?
Vim Awesome lists ESLint as a plugin: https://vimawesome.com/plugin/eslint. However, also on that page it says "...your plugins (and ESLint) are ..." implying ESLint is not a Vim plugin.

I am trying to work out how to apply ESLint to JavaScript files I am writing in Vim. I would like to do so (at least initially) without any plugins. I think it might help me to achieve this if I knew whether or not ESLint is a Vim plugin or not.

答:
No.  It is a general linter for javascript.  See https://eslint.org/

If you want to use ESLint in Vim, you can use a vim plugin (such as ALE or the eslint vim plugin) to help you.  Or you can use the command line interface eslint offers if you don't want to use plugins.

Title: Is ESLint a Vim plugin?


问:
How Can I Increase My CNN Model's Accuracy
I built a cnn model that classifies facial moods as happy , sad, energetic and neutral faces. I used Vgg16 pre-trained model and freezed all layers. After 50 epoch of training my model's test accuracy is 0.65 validatation loss is about 0.8 .

My train data folder has 16000(4x4000)  , validation data folder has 2000(4x500) and Test data folder has 4000(4x1000) rgb images.

1)What is your suggestion to increase the model accuracy?

2)I have tried to do some prediction with my model , predicted class is always same. What can cause the problem?

What I Have Tried So Far ?

Add dropout layer (0.5)

Add Dense (256, relu) before last layer

Shuff the train and validation datas.

Decrease the learning rate to 1e-5

But I could not the increase validation and test accuracy.

My Codes

```<code>train_src = "/content/drive/MyDrive/Affectnet/train_class/"
val_src = "/content/drive/MyDrive/Affectnet/val_class/"
test_src="/content/drive/MyDrive/Affectnet/test_classs/"

train_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
      rescale=1./255,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,

      )

train_generator = train_datagen.flow_from_directory(
        train_src,
        target_size=(224,224 ),
        batch_size=32,
        class_mode='categorical',
        shuffle=True
        )

validation_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
        rescale=1./255
        )

validation_generator = validation_datagen.flow_from_directory(
        val_src,
        target_size=(224, 224),
        batch_size=32,
        class_mode='categorical',
        shuffle=True
        )
conv_base = tensorflow.keras.applications.VGG16(weights='imagenet',
                  include_top=False,
                  input_shape=(224, 224, 3)
                  )
for layer in conv_base.layers:
  layer.trainable = False

model = tensorflow.keras.models.Sequential()

# VGG16 is added as convolutional layer.
model.add(conv_base)

# Layers are converted from matrices to a vector.
model.add(tensorflow.keras.layers.Flatten())

# Our neural layer is added.
model.add(tensorflow.keras.layers.Dropout(0.5))
model.add(tensorflow.keras.layers.Dense(256, activation='relu'))

model.add(tensorflow.keras.layers.Dense(4, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer=tensorflow.keras.optimizers.Adam(lr=1e-5),
              metrics=['acc'])
history = model.fit_generator(
      train_generator,
      epochs=50,
      steps_per_epoch=100,
      validation_data=validation_generator,
      validation_steps=5,
      workers=8
      )
</code>```

Loss and accuracy

答:
Well a few things. For training set you say you have 16,0000 images. However with a batch size of 32 and steps_per_epoch= 100 then for any given epoch you are only training on 3,200 images. Similarly you have 2000 validation images, but with a batch size of 32 and validation_steps = 5 you are only validating on 5 X 32 = 160 images.
Now Vgg is an OK model but I don't use it because it is very large which increases the training time significantly and there are other models out there for transfer learning that are smaller and even more accurate. I suggest you try using EfficientNetB3. Use the code

```<code>conv_base = tensorflow.keras.applications.EfficientNetB3(weights='imagenet',
                  include_top=False,
                  input_shape=(224, 224, 3)
                  pooling='max'
                  )
</code>```

with pooling='max' you can eliminate the Flatten layer. Also EfficientNet models expect pixels in the range 0 to 255 so remove the rescale=1/255 in your generators.
Next thing to do is to use an adjustable learning rate. This can be done using Keras callbacks. Documentation for that is here. You want to use the ReduceLROnPlateau callback. Documentation for that is here. Set it up to monitor validation loss. My suggested code for that is below

```<code>rlronp=tf.keras.callbacks.ReduceLROnPlateau(monitor="val_loss",factor=0.5,
                                            patience=1, verbose=1)
</code>```

I also recommend you use the callback EarlyStopping. Documentation for that is here. . My recomended code for that is shown below

```<code>estop=tf.keras.callbacks.EarlyStopping( monitor="val_loss", patience=4, verbose=1,
                                        restore_best_weights=True)
</code>```

Now in model.fit include

```<code>callbacks=[rlronp, estop]
</code>```

set your learning rate to .001. Set epochs=50. The estop callback if tripped will return your model loaded with the weights from the epoch with the lowest validation loss. I notice you have the code

```<code>for layer in conv_base.layers:
  layer.trainable = False
</code>```

I know the tutorials tell you to do that but I get better results leaving it trainable and I have done this on hundreds of models.

Body:
I built a cnn model that classifies facial moods as happy , sad, energetic and neutral faces. I used Vgg16 pre-trained model and freezed all layers. After 50 epoch of training my model's test accuracy is 0.65 validatation loss is about 0.8 .

My train data folder has 16000(4x4000)  , validation data folder has 2000(4x500) and Test data folder has 4000(4x1000) rgb images.

1)What is your suggestion to increase the model accuracy?

2)I have tried to do some prediction with my model , predicted class is always same. What can cause the problem?

What I Have Tried So Far ?

Add dropout layer (0.5)

Add Dense (256, relu) before last layer

Shuff the train and validation datas.

Decrease the learning rate to 1e-5

But I could not the increase validation and test accuracy.

My Codes

train_src = "/content/drive/MyDrive/Affectnet/train_class/"
val_src = "/content/drive/MyDrive/Affectnet/val_class/"
test_src="/content/drive/MyDrive/Affectnet/test_classs/"

train_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
      rescale=1./255,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,

      )

train_generator = train_datagen.flow_from_directory(
        train_src,
        target_size=(224,224 ),
        batch_size=32,
        class_mode='categorical',
        shuffle=True
        )

validation_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
        rescale=1./255
        )

validation_generator = validation_datagen.flow_from_directory(
        val_src,
        target_size=(224, 224),
        batch_size=32,
        class_mode='categorical',
        shuffle=True
        )
conv_base = tensorflow.keras.applications.VGG16(weights='imagenet',
                  include_top=False,
                  input_shape=(224, 224, 3)
                  )
for layer in conv_base.layers:
  layer.trainable = False

model = tensorflow.keras.models.Sequential()

# VGG16 is added as convolutional layer.
model.add(conv_base)

# Layers are converted from matrices to a vector.
model.add(tensorflow.keras.layers.Flatten())

# Our neural layer is added.
model.add(tensorflow.keras.layers.Dropout(0.5))
model.add(tensorflow.keras.layers.Dense(256, activation='relu'))

model.add(tensorflow.keras.layers.Dense(4, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer=tensorflow.keras.optimizers.Adam(lr=1e-5),
              metrics=['acc'])
history = model.fit_generator(
      train_generator,
      epochs=50,
      steps_per_epoch=100,
      validation_data=validation_generator,
      validation_steps=5,
      workers=8
      )

Loss and accuracy

Body:
Well a few things. For training set you say you have 16,0000 images. However with a batch size of 32 and steps_per_epoch= 100 then for any given epoch you are only training on 3,200 images. Similarly you have 2000 validation images, but with a batch size of 32 and validation_steps = 5 you are only validating on 5 X 32 = 160 images.
Now Vgg is an OK model but I don't use it because it is very large which increases the training time significantly and there are other models out there for transfer learning that are smaller and even more accurate. I suggest you try using EfficientNetB3. Use the code

conv_base = tensorflow.keras.applications.EfficientNetB3(weights='imagenet',
                  include_top=False,
                  input_shape=(224, 224, 3)
                  pooling='max'
                  )

with pooling='max' you can eliminate the Flatten layer. Also EfficientNet models expect pixels in the range 0 to 255 so remove the rescale=1/255 in your generators.
Next thing to do is to use an adjustable learning rate. This can be done using Keras callbacks. Documentation for that is here. You want to use the ReduceLROnPlateau callback. Documentation for that is here. Set it up to monitor validation loss. My suggested code for that is below

rlronp=tf.keras.callbacks.ReduceLROnPlateau(monitor="val_loss",factor=0.5,
                                            patience=1, verbose=1)

I also recommend you use the callback EarlyStopping. Documentation for that is here. . My recomended code for that is shown below

estop=tf.keras.callbacks.EarlyStopping( monitor="val_loss", patience=4, verbose=1,
                                        restore_best_weights=True)

Now in model.fit include

callbacks=[rlronp, estop]

set your learning rate to .001. Set epochs=50. The estop callback if tripped will return your model loaded with the weights from the epoch with the lowest validation loss. I notice you have the code

for layer in conv_base.layers:
  layer.trainable = False

I know the tutorials tell you to do that but I get better results leaving it trainable and I have done this on hundreds of models.


问:
DropShadow effect for Winform is slow?
I am applying Drop Shadow effect to my borderless win Form by overriding the CreateParams property and it works fine also but I don't know why it slow down the application while I am moving the Form.

My Code:

```<code> private const int CS_DROPSHADOW = 0x20000;
    protected override CreateParams CreateParams
    {
        get
        {
              CreateParams parameters = base.CreateParams;
              if (OSFeature.IsPresent(SystemParameter.DropShadow))
              {
                  parameters.ClassStyle |= CS_DROPSHADOW;
              }
              return parameters;
        }
    }
</code>```

答:
CS_DROPSHADOW creates a region of transparency.  It takes a lot more time to blend the drop shadow with whatever might be underneath and then render it.  This is especially true on Windows 2000/XP.  I think they improved performance for transparency in Windows Vista/7.

This style was originally intended for things like menus, which can't be moved by the user.  The performance of CS_DROPSHADOW was therefore probably not a major concern, either.

Title: DropShadow effect for Winform is slow?

Body:
I am applying Drop Shadow effect to my borderless win Form by overriding the CreateParams property and it works fine also but I don't know why it slow down the application while I am moving the Form.

My Code:

 private const int CS_DROPSHADOW = 0x20000;
    protected override CreateParams CreateParams
    {
        get
        {
              CreateParams parameters = base.CreateParams;
              if (OSFeature.IsPresent(SystemParameter.DropShadow))
              {
                  parameters.ClassStyle |= CS_DROPSHADOW;
              }
              return parameters;
        }
    }


问:
How can I put a txt file (that is in a zip file) in a string, without extracting the zip?
Here is my code:

using (ZipArchive zip = ZipFile.Open(path, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if (entry.Name == "example.txt")
            entry.ExtractToFile(???);
```

The ??? is what I'm having trouble with. I want it to go to a string, not a file on disk.

答:
The first code will get you an Array of String, as if it were "ReadAllLines". The second one will get you a single String (as if it were "ReadAllText").</p>
```<code>List<string> lines = new List<string>();
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
    foreach (ZipArchiveEntry entry in archive.Entries.Where(e_ => e_.Name == "example.txt"))
    {
        Stream stream = entry.Open();
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }
    }
}
string[] result = lines.ToArray();

string result = "";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
    foreach (ZipArchiveEntry entry in archive.Entries.Where(e_ => e_.Name == "example.txt"))
    {
        Stream stream = entry.Open();
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            result = sr.ReadToEnd();
        }
    }
}
</code>```

Body:
Here is my code:

using (ZipArchive zip = ZipFile.Open(path, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if (entry.Name == "example.txt")
            entry.ExtractToFile(???);

The ??? is what I'm having trouble with. I want it to go to a string, not a file on disk.

Body:
The first code will get you an Array of String, as if it were "ReadAllLines". The second one will get you a single String (as if it were "ReadAllText").

List<string> lines = new List<string>();
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
    foreach (ZipArchiveEntry entry in archive.Entries.Where(e_ => e_.Name == "example.txt"))
    {
        Stream stream = entry.Open();
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }
    }
}
string[] result = lines.ToArray();

string result = "";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
    foreach (ZipArchiveEntry entry in archive.Entries.Where(e_ => e_.Name == "example.txt"))
    {
        Stream stream = entry.Open();
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            result = sr.ReadToEnd();
        }
    }
}


问:
Python 3 gives NaN for operation that Python 2 handles
The calculation I'm trying with scipy.stats.hypergeom is giving nan when run in Python 3.9.9 but works fine in Python 2.7.18. I need it to run it in Python 3 because the rest of my program is for that version.

I've tried casting all of the numbers to the same float type and rounding the numbers but nothing seems to make it work for Python 3. I've included my code and the outputs I get for the different versions.

Code

from scipy.stats import hypergeom

k   = 526.8499999999999
nmk = 409.823
n   = 936.6729999999999
m   = 30079.555399999997
N   = 59416.2896

p1 = hypergeom.cdf(k, N, m, n)
p2 = hypergeom.cdf(nmk, N, m, n)

print("p1 = " + str(p1) + " [" + str(type(p1)) + "]")
print("p2 = " + str(p2) + " [" + str(type(p2)) + "]")
```
<h3>Python 2.7.18</h3>
```p1 = 0.999720238917 [<type 'numpy.float64'>]
p2 = 9.96805760427e-06 [<type 'numpy.float64'>]
```
<h3>Python 3.9.9</h3>
```p1 = nan [<class 'numpy.float64'>]
p2 = nan [<class 'numpy.float64'>]
```

Edit: The scipy version I'm using is 0.13.0b1 for Python 2 and 1.8.0 for Python 3.

答: Downgrading scipy from version 1.8.0 to 1.7.3 solved this issue.

Body:
The calculation I'm trying with scipy.stats.hypergeom is giving nan when run in Python 3.9.9 but works fine in Python 2.7.18. I need it to run it in Python 3 because the rest of my program is for that version.

I've tried casting all of the numbers to the same float type and rounding the numbers but nothing seems to make it work for Python 3. I've included my code and the outputs I get for the different versions.

Code

from scipy.stats import hypergeom

k   = 526.8499999999999
nmk = 409.823
n   = 936.6729999999999
m   = 30079.555399999997
N   = 59416.2896

p1 = hypergeom.cdf(k, N, m, n)
p2 = hypergeom.cdf(nmk, N, m, n)

print("p1 = " + str(p1) + " [" + str(type(p1)) + "]")
print("p2 = " + str(p2) + " [" + str(type(p2)) + "]")

Python 2.7.18

p1 = 0.999720238917 [<type 'numpy.float64'>]
p2 = 9.96805760427e-06 [<type 'numpy.float64'>]

Python 3.9.9

p1 = nan [<class 'numpy.float64'>]
p2 = nan [<class 'numpy.float64'>]

Edit: The scipy version I'm using is 0.13.0b1 for Python 2 and 1.8.0 for Python 3.


问:
Chrome Extension - Uncaught TypeError, If popup.js is in the manifest.json
At first I thought it was the chrome.tabs.query as it's the first part of the popup.js and it is highlighted on the extensions error page. .

Uncaught TypeError: Cannot read properties of undefined (reading 'query')

Even after commenting it out and latter removing all code I still got the error when the page was first loaded or reloaded.

I ended up removing it from the manifest.json and even then I had to use the "Load unpacked" option but then the error was gone but the extension still worked.

```<code>  "content_scripts": [{
    "js": ["jquery-2.2.0.min.js", "popup.js"],
    "matches": ["https://www-*"]
  }]
</code>```

I saw a demo that had it in the manifest.json, not sure if it should be there or not but it works without it.

I did not think you were putting them in the manifest.json to be run whenever the web page matched but so they would be available and or part of the extension.

Is it needed in the manifest.json and just ignore the errors?

I also went down the rabbit hole of not running the chrome.tabs.queryfunction in a content.js but only a background.js, but found a fixe before getting that running.

答:
You cannot use chrome.tabs in content scripts, only in background ones.

Check the Chrome official documenation for more information

Body:
At first I thought it was the chrome.tabs.query as it's the first part of the popup.js and it is highlighted on the extensions error page. .

Uncaught TypeError: Cannot read properties of undefined (reading 'query')

Even after commenting it out and latter removing all code I still got the error when the page was first loaded or reloaded.

I ended up removing it from the manifest.json and even then I had to use the "Load unpacked" option but then the error was gone but the extension still worked.

  "content_scripts": [{
    "js": ["jquery-2.2.0.min.js", "popup.js"],
    "matches": ["https://www-*"]
  }]

I saw a demo that had it in the manifest.json, not sure if it should be there or not but it works without it.

I did not think you were putting them in the manifest.json to be run whenever the web page matched but so they would be available and or part of the extension.

Is it needed in the manifest.json and just ignore the errors?

I also went down the rabbit hole of not running the chrome.tabs.queryfunction in a content.js but only a background.js, but found a fixe before getting that running.


问:
Find a substring in cells across multiple columns in a Pandas dataframe
I have a large DataFrame with 50+ columns which I'm simplifying here below:

```<code>students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])
</code>```

I'm trying to find

a) whether there are any instances of '--->' in any of the cells across the DataFrame?

b) if so where? (optional)

So far I've tried 2 approaches

```<code>boolDf = df.isin(['--->']).any().any()
</code>```

this only works for strings not substrings

```<code>columns = list(df)
for col in columns:
    df[col].str.find('--->', 0).any()
</code>```

I get:

```<code>AttributeError: Can only use .str accessor with string values!
</code>```

(I believe this may only work for columns with string types)

Would appreciate any help. Open to other approaches as well.

答:
Get a boolean map of the rows that contain the substring:

```<code>substr_rows = df.apply(lambda x: x.str.contains('--->').any(), axis=1)
</code>```

Do any of the rows contain the substring?

```<code>substr_rows.any()

True
</code>```

which ones?

```<code>substr_rows

0     True
1    False
2    False
3     True
</code>```

Body:
I have a large DataFrame with 50+ columns which I'm simplifying here below:

students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])

I'm trying to find

a) whether there are any instances of '--->' in any of the cells across the DataFrame?

b) if so where? (optional)

So far I've tried 2 approaches

boolDf = df.isin(['--->']).any().any()

this only works for strings not substrings

columns = list(df)
for col in columns:
    df[col].str.find('--->', 0).any()

I get:

AttributeError: Can only use .str accessor with string values!

(I believe this may only work for columns with string types)

Would appreciate any help. Open to other approaches as well.

Body:
Get a boolean map of the rows that contain the substring:

substr_rows = df.apply(lambda x: x.str.contains('--->').any(), axis=1)

Do any of the rows contain the substring?

substr_rows.any()

True

which ones?

substr_rows

0     True
1    False
2    False
3     True


问:
What does this declaration in C# .net mean?
I have the following declaration in .NET. I want to know what exactly this declaration mean (the second line), especially the DoConsoleCancelEvent

```<code>delegate void InternalCancelHandler;

static readonly InternalCancelHandler cancel_handler =
    new InternalCancelHandler (DoConsoleCancelEvent);
</code>```

The DoConsoleCancelEvent is declared as:

```<code>internal static void DoConsoleCancelEvent{...}
</code>```

What is the term used in .NET? Is it .NET reflection?

答:
InternalCancelHandler is a delegate, which is the C# way of holding a reference to a particular method. The first line defines the delegate to refer to a method that has a void return, and takes no parameters (since there is no parameter list.) This definition:

```<code>delegate int InternalCancelHandler(bool boolParam);
</code>```

Defines a delegate that will refer to a method that returns an int and accepts a single bool parameter.

The next line is the declaration of a static, readonly field of that delegate type, which is initialized to a new instance referring to the the DoConsoleCancelEvent method.

With that declaration, you can now call the DoConsoleCancelEvent by invoking the delegate:

```<code>public static void CallDelegate()
{
    // This line will actually call DoConsoleCancelEvent
    MyType.cancel_handler();
}
</code>```

Note that the Handler at the end of the delegate type suggests that it is an event handler, which means it's more likely that you'd want to use it to subscribe to an event:

```<code>public static void EventSub()
{
    // This line makes it so that cancel_handler is called when
    // SomeEvent is fired.  Since cancel_handler actually refers
    // to DoConsoleCancelEvent, it is *that* method that will
    // actually be run
    SomeType.SomeEvent += cancel_handler;
}
</code>```

static means that the field is associated with the Type, and not a particular instance of the Type

readonly means the field can only be assigned during construction of the Type

Body:
I have the following declaration in .NET. I want to know what exactly this declaration mean (the second line), especially the DoConsoleCancelEvent

delegate void InternalCancelHandler;

static readonly InternalCancelHandler cancel_handler =
    new InternalCancelHandler (DoConsoleCancelEvent);

The DoConsoleCancelEvent is declared as:

internal static void DoConsoleCancelEvent{...}

What is the term used in .NET? Is it .NET reflection?

Body:
InternalCancelHandler is a delegate, which is the C# way of holding a reference to a particular method. The first line defines the delegate to refer to a method that has a void return, and takes no parameters (since there is no parameter list.) This definition:

delegate int InternalCancelHandler(bool boolParam);

Defines a delegate that will refer to a method that returns an int and accepts a single bool parameter.

The next line is the declaration of a static, readonly field of that delegate type, which is initialized to a new instance referring to the the DoConsoleCancelEvent method.

With that declaration, you can now call the DoConsoleCancelEvent by invoking the delegate:

public static void CallDelegate()
{
    // This line will actually call DoConsoleCancelEvent
    MyType.cancel_handler();
}

Note that the Handler at the end of the delegate type suggests that it is an event handler, which means it's more likely that you'd want to use it to subscribe to an event:

public static void EventSub()
{
    // This line makes it so that cancel_handler is called when
    // SomeEvent is fired.  Since cancel_handler actually refers
    // to DoConsoleCancelEvent, it is *that* method that will
    // actually be run
    SomeType.SomeEvent += cancel_handler;
}

static means that the field is associated with the Type, and not a particular instance of the Type

readonly means the field can only be assigned during construction of the Type


答:
import pandas as pd

students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])

def find_substr(df:pd.DataFrame,substr:str) -> pd.DataFrame:
    """
    df: pd.DataFrame we want to search
    substr: the string that we are looking for in all string columns
    returns df of boolean values
    """
    # create new df to house bool values (if substring is found)
    new_df = pd.DataFrame()
    # loop through the columns
    for col in df.columns:
        # if the series is a string we will search for it
        if pd.api.types.is_string_dtype(df[col]):
            # the series of our new df represent if we found the substring
            new_df[col] = df[col].str.contains(substr)

    return new_df

found_str = find_substr(df,'--->')

found_str
# -- OUTPUT --
    Name  Balance  Country  Currency
0  False    False     True      True
1  False    False    False     False
2  False    False    False     False
3  False    False     True      True

```

This function should work it gives you a new df of boolean values for each cell where you found the substring.

edit:
This uses pd.Series.str.contains() to find each string that contains your substring. Read more here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html

Title: Find a substring in cells across multiple columns in a Pandas dataframe

Body:
import pandas as pd

students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])

def find_substr(df:pd.DataFrame,substr:str) -> pd.DataFrame:
    """
    df: pd.DataFrame we want to search
    substr: the string that we are looking for in all string columns
    returns df of boolean values
    """
    # create new df to house bool values (if substring is found)
    new_df = pd.DataFrame()
    # loop through the columns
    for col in df.columns:
        # if the series is a string we will search for it
        if pd.api.types.is_string_dtype(df[col]):
            # the series of our new df represent if we found the substring
            new_df[col] = df[col].str.contains(substr)

    return new_df

found_str = find_substr(df,'--->')

found_str
# -- OUTPUT --
    Name  Balance  Country  Currency
0  False    False     True      True
1  False    False    False     False
2  False    False    False     False
3  False    False     True      True

This function should work it gives you a new df of boolean values for each cell where you found the substring.

edit:
This uses pd.Series.str.contains() to find each string that contains your substring. Read more here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html


问:
how to remove peripheral device from devices and printers in python
I want to remove device specific device attached to my computer when i run a script in python but am not able to do this. Have searched on the web with no solution.
link 1  and
link 2

I learnt i can achieve that with power shell but am not able to achieve that.

This code is able to open the cd rom successfully

```<code>import os

os.system('powershell $driveEject = New-Object -comObject Shell.Application; $driveEject.Namespace(17).ParseName("""F:""").InvokeVerb("""Eject""")')
</code>```

I came across this question  how to remove printer from devices and printer which there is no answer for it.

I kindly need assistance achieve such result.

答:
First I prepared a powershell script (s.ps1):

```<code>$driveEject = New-Object -comObject Shell.Application
$driveEject.Namespace(17).ParseName("E:").InvokeVerb("Eject")
</code>```

Then I created a Python script

```<code>import os
os.system('powershell.exe -Command  ./s.ps1  >log.txt')
</code>```

After that I got an error in the log file

```<code>./s.ps1 : s.ps1 cannot be loaded because
running scripts is disabled on this system. For
more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ./s.ps1
+ ~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
</code>```

After reading the article I executed the commands in cmd running under the administrator

```<code>> powershell
Windows PowerShell
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS >  Set-ExecutionPolicy -ExecutionPolicy Unrestricted
</code>```

After that, I was finally able to run the script. And I saw a pop-up in the tray with a message that I can eject the disk.

Body:
I want to remove device specific device attached to my computer when i run a script in python but am not able to do this. Have searched on the web with no solution.
link 1  and
link 2

I learnt i can achieve that with power shell but am not able to achieve that.

This code is able to open the cd rom successfully

import os

os.system('powershell $driveEject = New-Object -comObject Shell.Application; $driveEject.Namespace(17).ParseName("""F:""").InvokeVerb("""Eject""")')

I came across this question  how to remove printer from devices and printer which there is no answer for it.

I kindly need assistance achieve such result.

Body:
First I prepared a powershell script (s.ps1):

$driveEject = New-Object -comObject Shell.Application
$driveEject.Namespace(17).ParseName("E:").InvokeVerb("Eject")

Then I created a Python script

import os
os.system('powershell.exe -Command  ./s.ps1  >log.txt')

After that I got an error in the log file

./s.ps1 : s.ps1 cannot be loaded because
running scripts is disabled on this system. For
more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ./s.ps1
+ ~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

After reading the article I executed the commands in cmd running under the administrator

> powershell
Windows PowerShell
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS >  Set-ExecutionPolicy -ExecutionPolicy Unrestricted

After that, I was finally able to run the script. And I saw a pop-up in the tray with a message that I can eject the disk.


问:
How to listening port in Office (VSTO)?
I wrote a VSTO Add-In for PPT, this extension can send notes to mobile phones in the local area network through websocket service when ppt is playing.

It may be due to security reasons. Port 8080 can only be successfully monitored when ppt is started with administrator privileges. Is there any way to solve it?

```<code>System.Net.HttpListenerException:access denied.
</code>```

答: I think you need to re-design your communication layer in the add-in and service. Add-in is loaded by the host application and can't request admin privileges on its own. Instead, you may consider using any other communication mechanisms that don't require admin privileges. Actually, you are free to use any .net tools and technologies from the VSTO add-in because it is still a .net application. For example, see What Is Windows Communication Foundation.</p>

Title: How to listening port in Office (VSTO)?

Body:
I wrote a VSTO Add-In for PPT, this extension can send notes to mobile phones in the local area network through websocket service when ppt is playing.

It may be due to security reasons. Port 8080 can only be successfully monitored when ppt is started with administrator privileges. Is there any way to solve it?

System.Net.HttpListenerException:access denied.


问:
Why my pod error "Back-off restarting failed container" when I have `imagePullPolicy: "Always"`
Why my pod error "Back-off restarting failed container" when I have imagePullPolicy: "Always", Before It worked but today I deploy it on other machine, it show that error

My Yaml:

```<code>apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: couchdb
  labels:
    app: couch
spec:
  replicas: 3
  serviceName: "couch-service"
  selector:
    matchLabels:
      app: couch
  template:
    metadata:
      labels:
        app: couch # pod label
    spec:
      containers:
      - name: couchdb
        image: couchdb:2.3.1
        imagePullPolicy: "Always"
        env:
        - name: NODE_NETBIOS_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: NODENAME
          value: $(NODE_NETBIOS_NAME).couch-service # FQDN in vm.args
        - name: COUCHDB_USER
          value: admin
        - name: COUCHDB_PASSWORD
          value: admin
        - name: COUCHDB_SECRET
          value: b1709267
        - name: ERL_FLAGS
          value: "-name couchdb@$(NODENAME)"
        - name: ERL_FLAGS
          value: "-setcookie b1709267" #   the “password” used when nodes connect to each other.
        ports:
        - name: couchdb
          containerPort: 5984
        - name: epmd
          containerPort: 4369
        - containerPort: 9100
        volumeMounts:
          - name: couch-pvc
            mountPath: /opt/couchdb/data
  volumeClaimTemplates:
  - metadata:
      name: couch-pvc
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi
      selector:
        matchLabels:
          volume: couch-volume
</code>```

I describe it:

```<code>Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  23s                default-scheduler  Successfully assigned default/couchdb-0 to b1709267node1
  Normal   Pulled     17s                kubelet            Successfully pulled image "couchdb:2.3.1" in 4.368553213s
  Normal   Pulling    16s (x2 over 22s)  kubelet            Pulling image "couchdb:2.3.1"
  Normal   Created    10s (x2 over 17s)  kubelet            Created container couchdb
  Normal   Started    10s (x2 over 17s)  kubelet            Started container couchdb
  Normal   Pulled     10s                kubelet            Successfully pulled image "couchdb:2.3.1" in 6.131837401s
  Warning  BackOff    8s (x2 over 9s)    kubelet            Back-off restarting failed container
</code>```

What shound I do? Thanks

答: Check if you have created secret with correct credentials and added  secret</p>

Body:
Why my pod error "Back-off restarting failed container" when I have imagePullPolicy: "Always", Before It worked but today I deploy it on other machine, it show that error

My Yaml:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: couchdb
  labels:
    app: couch
spec:
  replicas: 3
  serviceName: "couch-service"
  selector:
    matchLabels:
      app: couch
  template:
    metadata:
      labels:
        app: couch # pod label
    spec:
      containers:
      - name: couchdb
        image: couchdb:2.3.1
        imagePullPolicy: "Always"
        env:
        - name: NODE_NETBIOS_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: NODENAME
          value: $(NODE_NETBIOS_NAME).couch-service # FQDN in vm.args
        - name: COUCHDB_USER
          value: admin
        - name: COUCHDB_PASSWORD
          value: admin
        - name: COUCHDB_SECRET
          value: b1709267
        - name: ERL_FLAGS
          value: "-name couchdb@$(NODENAME)"
        - name: ERL_FLAGS
          value: "-setcookie b1709267" #   the “password” used when nodes connect to each other.
        ports:
        - name: couchdb
          containerPort: 5984
        - name: epmd
          containerPort: 4369
        - containerPort: 9100
        volumeMounts:
          - name: couch-pvc
            mountPath: /opt/couchdb/data
  volumeClaimTemplates:
  - metadata:
      name: couch-pvc
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi
      selector:
        matchLabels:
          volume: couch-volume

I describe it:

Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  23s                default-scheduler  Successfully assigned default/couchdb-0 to b1709267node1
  Normal   Pulled     17s                kubelet            Successfully pulled image "couchdb:2.3.1" in 4.368553213s
  Normal   Pulling    16s (x2 over 22s)  kubelet            Pulling image "couchdb:2.3.1"
  Normal   Created    10s (x2 over 17s)  kubelet            Created container couchdb
  Normal   Started    10s (x2 over 17s)  kubelet            Started container couchdb
  Normal   Pulled     10s                kubelet            Successfully pulled image "couchdb:2.3.1" in 6.131837401s
  Warning  BackOff    8s (x2 over 9s)    kubelet            Back-off restarting failed container

What shound I do? Thanks


问:
Typescript: Get the values of an enumeration as a string set
Given this enumeration:

```<code>export enum Example {
  First = 'A',
  Second = 'B'
}
</code>```

Is there a way to construct a type such that the type is 'A' | 'B'?

I know that keyof typeof Example will get me 'First' | 'Second', but I want the values, not the keys.

The use case is that we have enumerations in the code in the client. These values are sent down from the server as strings in the JSON. I want to type the JSON payload as an interface but have the property typed as a string to match the enumeration values.

I realize I could do this:

```<code>export interface Payload {
  someProp?: Example;
}
</code>```

But then in unit tests, we cannot simply copy a payload into the Typescript without errors:

```<code>const examplePayload: Payload = { someProp: 'A' }
</code>```

Results in the error:

```<code>Type '"A"' is not assignable to type 'Example | undefined'.ts(2322)
</code>```

So I'd like to allow it to be the values of the enum, but without hardcoding it like this that would cause maintenance issues when that enum is changed and the type wasn't changed:

```<code>const examplePayload: Payload = { someProp: 'A' | 'B' }
</code>```

Unfortunately I cannot do this to get it cast as a string:

```<code>export type EnumValues<Type> = `${Type[keyof Type]}`;
const s: EnumValues<typeof Example>;
</code>```

Results in:

```<code>Type 'Type[keyof Type]' is not assignable to type 'string | number | bigint | boolean | null | undefined'.
</code>```

I also do not want to use 'A' | 'B' in code as the server values are not always obvious and it is much easier to maintain the code with an enumeration serving as server valid values aliases.

答:
Murphy's law hit (found a solution after asking the question). This seems to work:</p>
```<code>export type EnumValues<Type extends string> = `${Type}`;
enum Example {
  First = 'A',
  Second = 'B'
}
export interface Payload {
  someProp?: EnumValues<Example>;
}
const p: Payload = {
  someProp: 'B'
};
</code>```

Body:
Given this enumeration:

export enum Example {
  First = 'A',
  Second = 'B'
}

Is there a way to construct a type such that the type is 'A' | 'B'?

I know that keyof typeof Example will get me 'First' | 'Second', but I want the values, not the keys.

The use case is that we have enumerations in the code in the client. These values are sent down from the server as strings in the JSON. I want to type the JSON payload as an interface but have the property typed as a string to match the enumeration values.

I realize I could do this:

export interface Payload {
  someProp?: Example;
}

But then in unit tests, we cannot simply copy a payload into the Typescript without errors:

const examplePayload: Payload = { someProp: 'A' }

Results in the error:

Type '"A"' is not assignable to type 'Example | undefined'.ts(2322)

So I'd like to allow it to be the values of the enum, but without hardcoding it like this that would cause maintenance issues when that enum is changed and the type wasn't changed:

const examplePayload: Payload = { someProp: 'A' | 'B' }

Unfortunately I cannot do this to get it cast as a string:

export type EnumValues<Type> = `${Type[keyof Type]}`;
const s: EnumValues<typeof Example>;

Results in:

Type 'Type[keyof Type]' is not assignable to type 'string | number | bigint | boolean | null | undefined'.

I also do not want to use 'A' | 'B' in code as the server values are not always obvious and it is much easier to maintain the code with an enumeration serving as server valid values aliases.

Body:
Murphy's law hit (found a solution after asking the question). This seems to work:

export type EnumValues<Type extends string> = `${Type}`;
enum Example {
  First = 'A',
  Second = 'B'
}
export interface Payload {
  someProp?: EnumValues<Example>;
}
const p: Payload = {
  someProp: 'B'
};


答:
Try this:</p>
```<code>boolDf = df['Country'].where(df['Country'].str.contains('--->'))
df_filter=boolDf.isnull()
df[~df_filter]
</code>```

Body:
Try this:

boolDf = df['Country'].where(df['Country'].str.contains('--->'))
df_filter=boolDf.isnull()
df[~df_filter]


答:
I believe the term you are looking for is Delegate.

In this case, InternalCancelHandler is the delegate. The first line of code creates a delegate that points to your DoConsoleCancelEvent method. The delegate will then be used to call your method at a later point in time.

Title: What does this declaration in C# .net mean?


问:
How can we improve improve docker image size
Can any one help me understand how can we
Try to optimize the Dockerfile by removing all unnecessary cache/files to reduce the image size. and
Removing unnecessary binaries/permissions to improve container security

My docker file look like this

```<code>FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]
</code>```

答:
Well, there is actually some ways to do that I guess:

multi-stage build

```<code># STAGE1
FROM alpine AS stage1
WORKDIR /bin
RUN wget https://link/of/some/binaries -O app1 \
    && chmod +x app1
# Run additional commands if you want

# STAGE2
FROM alpine AS stage2
WORKDIR /usr/local/bin
RUN wget https://link/of/some/binaries -O app2 \
    && chmod +x app2
# Run additional commands if you want

# FINAL STAGE (runtime)
FROM python:3.7-alpine as runtime
COPY --from=stage1  /bin/app1 /bin/app1
COPY --from=stage2 /usr/local/bin/app2 /bin/app2
...
</code>```

this will actually allow you to simply get only the binaries you need that you downloaded on the previous stages.

If you are using apk add and you don't know where things are getting installed you can try to test on an alpine image by running which command

remove cache

```<code>... # Install some stuff...

# Remove Cache
RUN rm -rf /var/cache/apk/*
</code>```

Body:
Can any one help me understand how can we
Try to optimize the Dockerfile by removing all unnecessary cache/files to reduce the image size. and
Removing unnecessary binaries/permissions to improve container security

My docker file look like this

FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]

Body:
Well, there is actually some ways to do that I guess:

multi-stage build

# STAGE1
FROM alpine AS stage1
WORKDIR /bin
RUN wget https://link/of/some/binaries -O app1 \
    && chmod +x app1
# Run additional commands if you want

# STAGE2
FROM alpine AS stage2
WORKDIR /usr/local/bin
RUN wget https://link/of/some/binaries -O app2 \
    && chmod +x app2
# Run additional commands if you want

# FINAL STAGE (runtime)
FROM python:3.7-alpine as runtime
COPY --from=stage1  /bin/app1 /bin/app1
COPY --from=stage2 /usr/local/bin/app2 /bin/app2
...

this will actually allow you to simply get only the binaries you need that you downloaded on the previous stages.

If you are using apk add and you don't know where things are getting installed you can try to test on an alpine image by running which command

remove cache

... # Install some stuff...

# Remove Cache
RUN rm -rf /var/cache/apk/*


问:
How to get no frame on a table in AsciiDoc on GitHub
I want to make a table in AsciiDoc on GitHub with no frame.  My reading of the documentation is that this should work:

```<code>[frame="none",options="header"]
|===
| Foo | Bar
| Widget | Gadget
|===
</code>```

Yet it renders with a frame:

That frame="none" setting should do it.  But it doesn't.  I try it without quotes and its the same.  The options="header" works fine, so I know the interpreter is seeing the line in brackets and taking some action.

Is it possible that GitHub runs some version of AsciiDoc that is not full featured?  If so, is there a site with the details of what does and doesn't work?

Note--this is on our internal corporate instance of GitHub Enterprise, so we may be some versions out of date, or not have some plug-in installed.  Is there a special plug-in that does the trick?  I don't admin the platform, so is there a way I can check versions and plug-ins in any given GitHub platform as an ordinary developer?

We use AsciiDoc pervasively as our GitHub Wiki language, so changing to another one that does tables better is not an option.

All help appreciated!

答:
GitHub runs an official Asciidoctor to provide a nice rendering. However, they also run the generated HTML and CSS through a filtering process to prevent security issues. During that process, they strip off custom class names from a variety (if not all) elements (I don't know the exact details).

Running asciidoctor on your sample document shows a table that looks like this:

```
<p>Whereas their process results in a table that looks like:</p>
<pre class="lang-html prettyprint-override"><code><table>
</code>```

From GitHub's perspective, those kinds of changes mean that tables look the same everywhere on the site.

If you need frameless tables, you'll probably find using GitHub Pages a lot easier because you can use custom (or asciidoctor-provided) CSS in that context.

Body:
I want to make a table in AsciiDoc on GitHub with no frame.  My reading of the documentation is that this should work:

[frame="none",options="header"]
|===
| Foo | Bar
| Widget | Gadget
|===

Yet it renders with a frame:

That frame="none" setting should do it.  But it doesn't.  I try it without quotes and its the same.  The options="header" works fine, so I know the interpreter is seeing the line in brackets and taking some action.

Is it possible that GitHub runs some version of AsciiDoc that is not full featured?  If so, is there a site with the details of what does and doesn't work?

Note--this is on our internal corporate instance of GitHub Enterprise, so we may be some versions out of date, or not have some plug-in installed.  Is there a special plug-in that does the trick?  I don't admin the platform, so is there a way I can check versions and plug-ins in any given GitHub platform as an ordinary developer?

We use AsciiDoc pervasively as our GitHub Wiki language, so changing to another one that does tables better is not an option.

All help appreciated!

Body:
GitHub runs an official Asciidoctor to provide a nice rendering. However, they also run the generated HTML and CSS through a filtering process to prevent security issues. During that process, they strip off custom class names from a variety (if not all) elements (I don't know the exact details).

Running asciidoctor on your sample document shows a table that looks like this:

<table class="tableblock frame-none grid-all stretch">

Whereas their process results in a table that looks like:

<table>

From GitHub's perspective, those kinds of changes mean that tables look the same everywhere on the site.

If you need frameless tables, you'll probably find using GitHub Pages a lot easier because you can use custom (or asciidoctor-provided) CSS in that context.


答:
You could apply str.contains for each column to identify which cell contains a particular string:

```<code>out = df.astype(str).apply(lambda col: col.str.contains('--->'))
</code>```

Output:

```<code>    Name    Age  Balance  Country  Currency
0  False  False    False     True      True
1  False  False    False    False     False
2  False  False    False    False     False
3  False  False    False     True      True
</code>```

Then out.any().any() will produce True.

As a one-liner:

```<code>df.astype(str).apply(lambda col: col.str.contains('--->')).any().any()
</code>```

Body:
You could apply str.contains for each column to identify which cell contains a particular string:

out = df.astype(str).apply(lambda col: col.str.contains('--->'))

Output:

    Name    Age  Balance  Country  Currency
0  False  False    False     True      True
1  False  False    False    False     False
2  False  False    False    False     False
3  False  False    False     True      True

Then out.any().any() will produce True.

As a one-liner:

df.astype(str).apply(lambda col: col.str.contains('--->')).any().any()


问:
Is there a way to null-annotate this return value (not null depending on arguments) or do I need to redesign?
This API definition predates nullability annotations. Is there a way to annotate this correctly or do I need to redesign the API surface?

```<code>    public static IEnumerable<DirectoryEntry> GetDirectoryContents(string path,
        NonExtantDirectoryBehavior nonExtantDirectoryBehavior = NonExtantDirectoryBehavior.Throw,
        FollowSymbolicLinks followSymbolicLinks = FollowSymbolicLinks.Never)
</code>```

nonExtantDirectoryBehavior will always be a constant in the caller; GetDirectoryContents can only return null if the argument's value is ReturnNull.

I have to actually place the attributes rather than use ?, but that's a minor detail.

答:
GetDirectoryContents can only return null if the argument's value is ReturnNull.

The System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute is the closest you could get to that behavior, but it takes a boolean argument.

If you were willing to revise the method signature to make that parameter a boolean or use a separate named method (e.g. TryGetDirectoryContents), you could probably get that kind of behavior. Otherwise, you could just note that the return value can be null in general, or leave it how it is.

Body:
This API definition predates nullability annotations. Is there a way to annotate this correctly or do I need to redesign the API surface?

    public static IEnumerable<DirectoryEntry> GetDirectoryContents(string path,
        NonExtantDirectoryBehavior nonExtantDirectoryBehavior = NonExtantDirectoryBehavior.Throw,
        FollowSymbolicLinks followSymbolicLinks = FollowSymbolicLinks.Never)

nonExtantDirectoryBehavior will always be a constant in the caller; GetDirectoryContents can only return null if the argument's value is ReturnNull.

I have to actually place the attributes rather than use ?, but that's a minor detail.


问:
bitmap size exceeds VM budget Error on Android
I'm loading 100 images from Asset folder to an array object. The pictures are quite small (png ~20k each), and im using this code do to it, and to prevent memory leak & optimized performances:

in a loop:

```<code>// create resized bitmap from asset resource
        InputStream istr = assetManager.open(pics[i]);
        Bitmap b = BitmapFactory.decodeStream(istr);
        b = Bitmap.createScaledBitmap(b, 240, 240, true);
</code>```

where pics[i] is a list of filenames which sits in my Asset folder.

The code works for me, but i still receive from time to time Errors from users (i see it on Developer Console errors):

```<code>java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
at android.graphics.Bitmap.createBitmap(Bitmap.java:435)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)
</code>```

Is there anything i can do to improve it? or this is Android's world, we can never deliever a perfect application?

答:
As a rule of thumb you should only ever need to show what the user can actually see. Holding anything else (graphics) in memory is just icing on the cake. This is why devices with higher resolution screens will have larger heap sizes available.

For example, on a 320x480 screen, you would only need as a minimum, 320x480x4=614400 (600kb).

Taking this concept into mind, you need to consider whether you need to hold 100 Bitmaps in memory. Is the user looking at 100 Bitmaps at one time? In that case you can reduce the quality of the images without degrading the user experience (there are only so many pixels on the screen). Is the user scrolling through 100 Bitmaps? Then dump and load images dynamically as appropriate (with a bit of caching for smoothness).

There is always a workaround.

Body:
I'm loading 100 images from Asset folder to an array object. The pictures are quite small (png ~20k each), and im using this code do to it, and to prevent memory leak & optimized performances:

in a loop:

// create resized bitmap from asset resource
        InputStream istr = assetManager.open(pics[i]);
        Bitmap b = BitmapFactory.decodeStream(istr);
        b = Bitmap.createScaledBitmap(b, 240, 240, true);

where pics[i] is a list of filenames which sits in my Asset folder.

The code works for me, but i still receive from time to time Errors from users (i see it on Developer Console errors):

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
at android.graphics.Bitmap.createBitmap(Bitmap.java:435)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)

Is there anything i can do to improve it? or this is Android's world, we can never deliever a perfect application?


问:
How can I read and decode AVRO messages from Kafka along with their associated kafka key using Benthos?
I am using Benthos to read AVRO-encoded messages from Kafka which have the kafka_key metadata field set to also contain an AVRO-encoded payload. The schemas of these AVRO-encoded payloads are stored in Schema Registry and Benthos has a schema_registry_decode processor for decoding them. I'm looking to produce an output JSON message for each Kafka message containing two fields, one called content containing the decoded AVRO message and the other one called metadata containing the various metadata fields collected by Benthos including the decoded kafka_key payload.

答:
It turns out that one can achieve this using a branch processor like so:

input:
  kafka:
    addresses:
      - localhost:9092
    consumer_group: benthos_consumer_group
    topics:
      - benthos_input

pipeline:
  processors:
    # Decode the message
    - schema_registry_decode:
        url: http://localhost:8081

    # Populate output content field
    - bloblang: |
        root.content = this

    # Decode kafka_key metadata payload and populate output metadata field
    - branch:
        request_map: |
          root = meta("kafka_key")

        processors:
          - schema_registry_decode:
              url: http://localhost:8081

        result_map: |
          root.metadata = meta()
          root.metadata.kafka_key = this

output:
  stdout: {}
```


问:
Convert milliseconds to Time without losing precision
Time.current gives me precision beyond seconds:

```<code>> Time.current
Fri, 11 Feb 2022 23:00:18.253185000 UTC +00:00
> Time.current.to_f
1644620430.942064
</code>```

But Time.at loses the precision :(

```<code>> Time.at(1644620430.942064).utc
2022-02-11 23:00:30 UTC
</code>```

The whole .942064 got truncated. This is messing with some tests that compare dates, because timestamps seem to save with the milliseconds, but I don't know how to create a Time that includes milliseconds

How can I cast a variable of milliseconds into a Time?

答:
I think you're just seeing a formatting problem. Consider:

```<code>Time.at(1644620430.942064).strftime('%Y-%m-%dT%H:%M:%S.%N')
# 2022-02-11T15:00:30.942064046
</code>```

However, if you call to_s:

```<code>Time.at(1644620430.942064).to_s
# "2022-02-11 15:00:30 -0800"
Time.at(1644620430.942064).utc.to_s
# "2022-02-11 23:00:30 UTC"
</code>```

you only get results with one second resolution.

The full precision time is there but you need to be careful to ask for it when you format your time.

Body:
Time.current gives me precision beyond seconds:

> Time.current
Fri, 11 Feb 2022 23:00:18.253185000 UTC +00:00
> Time.current.to_f
1644620430.942064

But Time.at loses the precision :(

> Time.at(1644620430.942064).utc
2022-02-11 23:00:30 UTC

The whole .942064 got truncated. This is messing with some tests that compare dates, because timestamps seem to save with the milliseconds, but I don't know how to create a Time that includes milliseconds

How can I cast a variable of milliseconds into a Time?

Body:
I think you're just seeing a formatting problem. Consider:

Time.at(1644620430.942064).strftime('%Y-%m-%dT%H:%M:%S.%N')
# 2022-02-11T15:00:30.942064046

However, if you call to_s:

Time.at(1644620430.942064).to_s
# "2022-02-11 15:00:30 -0800"
Time.at(1644620430.942064).utc.to_s
# "2022-02-11 23:00:30 UTC"

you only get results with one second resolution.

The full precision time is there but you need to be careful to ask for it when you format your time.


问:
get member count before accessing server discord
Is there any way to get member count on a discord server before actually accessing to it.
Basically all i have is discord.gg url and i need member count

I.E

```<code>https://discord.gg/satoshirunners Satoshi Runners Official Collection
https://discord.gg/pd PixelDucks NFT
https://discord.gg/fancybirds Fancy Birds | Play2Earn
https://discord.gg/ksjZmCS8 CIV WAR |
https://discord.gg/hazemonkeynft Haze Monkey Society - Genesis NFT
https://discord.gg/BoldBadgersSquad Bold Badgers Squad | Bold Badgers Squad | Bold Badgers Squad | Bold Badgers Squad |
https://discord.gg/Sula#3470 bubbles(face)
https://discord.gg/AMZeBFSDhr All Spark Space Game
https://discord.gg/CryptoHasbulla CyptoKoksalbaba
https://discord.gg/PAINTHAMSTERNFT PAINT Hamster Nft
https://discord.gg/cryptonewbird avarta101
</code>```

Need to get member's count of each those servers.

Tried with client.guilds.fetch("") but obviously this works only if it's on my server

```<code>client.guilds.fetch("356230556738125824").then((channel) => {
    console.log(channel)
 }).catch((error) => {
     console.log(error)
 })
</code>```

答:
It is possible.

client.fetchInvite("yourInvite")
    .then(async invite => {
    const guild = await invite.guild.fetch()

    console.log(guild.memberCount)

})
```

Body:
Is there any way to get member count on a discord server before actually accessing to it.
Basically all i have is discord.gg url and i need member count

I.E

https://discord.gg/satoshirunners Satoshi Runners Official Collection
https://discord.gg/pd PixelDucks NFT
https://discord.gg/fancybirds Fancy Birds | Play2Earn
https://discord.gg/ksjZmCS8 CIV WAR |
https://discord.gg/hazemonkeynft Haze Monkey Society - Genesis NFT
https://discord.gg/BoldBadgersSquad Bold Badgers Squad | Bold Badgers Squad | Bold Badgers Squad | Bold Badgers Squad |
https://discord.gg/Sula#3470 bubbles(face)
https://discord.gg/AMZeBFSDhr All Spark Space Game
https://discord.gg/CryptoHasbulla CyptoKoksalbaba
https://discord.gg/PAINTHAMSTERNFT PAINT Hamster Nft
https://discord.gg/cryptonewbird avarta101

Need to get member's count of each those servers.

Tried with client.guilds.fetch("") but obviously this works only if it's on my server

client.guilds.fetch("356230556738125824").then((channel) => {
    console.log(channel)
 }).catch((error) => {
     console.log(error)
 })


问:
Correct way to manage an observable with services in angular
I have a doubt and I need to listen to some pro-angular-user to get the right way to manage this task. I've found tons of opinions about subscribe and async pipe and now I'm more confused then before.

Task: I have a list of topics in homepage. In another page I add/remove topics routine. When I came back to homepage I want that this list is updated. I use a service to manage this stuff.

This is an example code:

Home.page.ts

```<code>import { Component, OnInit } from '@angular/core';
import { TopicService } from '../services/topic.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {

  topics:any;

  constructor(private topicService: topicService){ }

  ngOnInit(){
    this.getTopics();
  }

  //here the first doubt using subscribe, I omit onDestroy with unsubscribe (it's prefered to do with async pipe in view?)
  getTopics(){
    this.topicService.getTopic().subscribe(topics =>{
      this.topics = topics;
    });
  }

}
</code>```

Home.page.html

```<code>...
          <ion-segment-button value="{{topic.id}}" *ngFor="let topic of topics?.data">
            <ion-label>{{topic.title}}</ion-label>
          </ion-segment-button>
...
</code>```

settings.page.ts

```<code>...

  topics:any

  addTopic(topic): Observable<any> {
    return this.topicService.addTopic(topic).subscribe((result)=>{
    this.topics.push(result)
    });
  }

  removeTopic(topic): Observable<any> {
    return this.topicService.removeTopic(topic).subscribe((result)=>{
    this.topics.filter(...)
    });
  }
...
</code>```

topicService.ts

```<code>   topics: Observable<any>;

   getTopics(): Observable<any>{
    this.http.get('/topics').pipe(
    map(result => {
       this.topics.next(result);
     })
    );
   }

   addTopic(topic){
    this.http.post('/topics/add/', {topic} ).pipe(
    map(result => {
       this.topics.next(result);
     })
    );
   }

   removeTopic(topic){...}
</code>```

答:
Well... Question about async pipe in angular is too general. Personally I prefer it over subscribe for better readability, and in some cases you don't have to handle "unsubscribe" manually. Angular HTTPClient service emits "complete" so you don't have to manually unsubscribe. In your case it's not much different than promise, but by utilizing power of Observables you have more control over your incoming data and if you ask me - much cleaner syntax.

Now about correctness of your code. It's almost good but... The topic variable in settings.page.ts is obsolete, you're not subscribing to it anywhere in your code. Also pip(map()) operator should return value, but I will refer to this later.

So first I would change this unnecessary topics: Observable<any>; variable, that require manual subscription handle, and simply return http observable from functions like this:

topicService.ts

```<code>getTopics(): Observable<any>{
  return this.http.get('/topics');
}

addTopic(topic){
  return this.http.post('/topics/add/', {topic} );
}
</code>```

At least from the code you've provided pipe(map(...)) operation was obsolete, and was used incorrectly. The correct way would be to use pipe(map(...)) to modify incoming stream data. Check out official documentation for more details: https://www.learnrxjs.io/learn-rxjs/operators/transformation/map

And in this case your Home.page.ts should be done this way:

```<code>topics:any;

constructor(private topicService: topicService){ }

ngOnInit(){
   this.topicService.getTopic().subscribe(topics =>{
      this.topics = topics;
   });
}
</code>```

Also you could use map to return only "necessary" data if your server API packs response with some "unnecessary" meta.

So in your case instead of manually checking if topics variable has .data property, you could handle this in your service/controller(.component.ts). So once again we might modify our topicService.ts

```<code>getTopics(): Observable<any>{
  return this.http.get('/topics').pipe(map(_topicRes => _topicRes.data));
}
</code>```

In this case map operator will "modify" our HTTP response to only return data property, and of course everything inside data, so your Home.page.html could look like this:

```<code><ion-segment-button value="{{topic.id}}" *ngFor="let topic of topics">
   <ion-label>{{topic.title}}</ion-label>
</ion-segment-button>
</code>```

Anyway, as I've said before -> it all depends on a use case. Play with it, experiment, do some dummy-apps. In time, you will know. Check out some demo projects online.

You should try and resolve data from API by route param like /article/:id. This should be a good practice for you - keyworld: switchMap :) Good luck.

Body:
I have a doubt and I need to listen to some pro-angular-user to get the right way to manage this task. I've found tons of opinions about subscribe and async pipe and now I'm more confused then before.

Task: I have a list of topics in homepage. In another page I add/remove topics routine. When I came back to homepage I want that this list is updated. I use a service to manage this stuff.

This is an example code:

Home.page.ts

import { Component, OnInit } from '@angular/core';
import { TopicService } from '../services/topic.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {

  topics:any;

  constructor(private topicService: topicService){ }

  ngOnInit(){
    this.getTopics();
  }

  //here the first doubt using subscribe, I omit onDestroy with unsubscribe (it's prefered to do with async pipe in view?)
  getTopics(){
    this.topicService.getTopic().subscribe(topics =>{
      this.topics = topics;
    });
  }

}

Home.page.html

...
          <ion-segment-button value="{{topic.id}}" *ngFor="let topic of topics?.data">
            <ion-label>{{topic.title}}</ion-label>
          </ion-segment-button>
...

settings.page.ts

...

  topics:any

  addTopic(topic): Observable<any> {
    return this.topicService.addTopic(topic).subscribe((result)=>{
    this.topics.push(result)
    });
  }

  removeTopic(topic): Observable<any> {
    return this.topicService.removeTopic(topic).subscribe((result)=>{
    this.topics.filter(...)
    });
  }
...

topicService.ts

   topics: Observable<any>;

   getTopics(): Observable<any>{
    this.http.get('/topics').pipe(
    map(result => {
       this.topics.next(result);
     })
    );
   }

   addTopic(topic){
    this.http.post('/topics/add/', {topic} ).pipe(
    map(result => {
       this.topics.next(result);
     })
    );
   }

   removeTopic(topic){...}

Body:
Well... Question about async pipe in angular is too general. Personally I prefer it over subscribe for better readability, and in some cases you don't have to handle "unsubscribe" manually. Angular HTTPClient service emits "complete" so you don't have to manually unsubscribe. In your case it's not much different than promise, but by utilizing power of Observables you have more control over your incoming data and if you ask me - much cleaner syntax.

Now about correctness of your code. It's almost good but... The topic variable in settings.page.ts is obsolete, you're not subscribing to it anywhere in your code. Also pip(map()) operator should return value, but I will refer to this later.

So first I would change this unnecessary topics: Observable<any>; variable, that require manual subscription handle, and simply return http observable from functions like this:

topicService.ts

getTopics(): Observable<any>{
  return this.http.get('/topics');
}

addTopic(topic){
  return this.http.post('/topics/add/', {topic} );
}

At least from the code you've provided pipe(map(...)) operation was obsolete, and was used incorrectly. The correct way would be to use pipe(map(...)) to modify incoming stream data. Check out official documentation for more details: https://www.learnrxjs.io/learn-rxjs/operators/transformation/map

And in this case your Home.page.ts should be done this way:

topics:any;

constructor(private topicService: topicService){ }

ngOnInit(){
   this.topicService.getTopic().subscribe(topics =>{
      this.topics = topics;
   });
}

Also you could use map to return only "necessary" data if your server API packs response with some "unnecessary" meta.

So in your case instead of manually checking if topics variable has .data property, you could handle this in your service/controller(.component.ts). So once again we might modify our topicService.ts

getTopics(): Observable<any>{
  return this.http.get('/topics').pipe(map(_topicRes => _topicRes.data));
}

In this case map operator will "modify" our HTTP response to only return data property, and of course everything inside data, so your Home.page.html could look like this:

<ion-segment-button value="{{topic.id}}" *ngFor="let topic of topics">
   <ion-label>{{topic.title}}</ion-label>
</ion-segment-button>

Anyway, as I've said before -> it all depends on a use case. Play with it, experiment, do some dummy-apps. In time, you will know. Check out some demo projects online.

You should try and resolve data from API by route param like /article/:id. This should be a good practice for you - keyworld: switchMap :) Good luck.


问:
How to use tqdm for JSON file load progress bar?
I'm writing a Python script for JSON file processing. It's basically divided in three procedures: load, encoding and printing. While I've easily created progress bars for encoding and printing using tqdm, I can't figure out how to do it for load.

I've thoroughly read tqdm docs and searched even here, but no clues

```<code>import json
from tqdm import tqdm, trange
from iso3166 import countries

geo_json_events_path = r'/cygdrive/c/elastic/gtd.geojson'

with open(geo_json_events_path) as f:
    data = json.load(f)
</code>```

I expect the progress bar for json.load() method shown.

答:
Here's a slightly more general solution to this for importing json files that have multiple objects:

```<code>def hook(obj):
    for key, value in obj.items():
        pbar = tqdm(value)
        if type(value) is list:
            for _ in pbar:
                pbar.set_description("Loading " + str(key))
    return obj

f = open(r"C:\my_json_file.json")
my_json_file = json.load(f, object_hook=hook)
</code>```

Although it still doesn't show the total progress if you have nested objects, just the progress of importing the current object.

Body:
I'm writing a Python script for JSON file processing. It's basically divided in three procedures: load, encoding and printing. While I've easily created progress bars for encoding and printing using tqdm, I can't figure out how to do it for load.

I've thoroughly read tqdm docs and searched even here, but no clues

import json
from tqdm import tqdm, trange
from iso3166 import countries

geo_json_events_path = r'/cygdrive/c/elastic/gtd.geojson'

with open(geo_json_events_path) as f:
    data = json.load(f)

I expect the progress bar for json.load() method shown.

Body:
Here's a slightly more general solution to this for importing json files that have multiple objects:

def hook(obj):
    for key, value in obj.items():
        pbar = tqdm(value)
        if type(value) is list:
            for _ in pbar:
                pbar.set_description("Loading " + str(key))
    return obj

f = open(r"C:\my_json_file.json")
my_json_file = json.load(f, object_hook=hook)

Although it still doesn't show the total progress if you have nested objects, just the progress of importing the current object.