问:
Protobuf does not generate appropriate declarations
[UPDATE]
It seems that protobuf_generate_cpp uses absolute paths.
Invoking protobuf compiler manually specifying relative path seems to generate valid sources.

Manual:

/usr/bin/protoc --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build shmiw/metadata/metadata.proto

produces: (metadata.pb.h)

::DescriptorTable descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto;

Name contains subdirectories

Whereas when compiling by protobuf_generate_cpp from cmake, it invokes protobuf compiler with command:

/usr/bin/protoc --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build -I /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata/metadata.proto

which produces "invalid" names that can't be used later on by other packages: (metadata.pb.h)

::DescriptorTable descriptor_table_metadata_2eproto;

I've got some problem with protobuf. I've got 3 proto files. The first one is a proto file that contains an option that all other proto files use. All proto files are organized in the same structure, and each of them belongs to a separate package. I want to generate all .h and .cc files and then put them into one single static library.
Project structure is as follows:

```<code>/root-dir
-CMakeLists.txt (1)
-shm-iw/
  - CMakeLists.txt (2)
  - bci
    - CMakeLists.txt (3)
    - bci.proto
  - icon
    - CMakeLists.txt (4)
    - icon.proto
  - metadata
    - CMakeLists.txt (5)
    - metadata.proto
</code>```

Root CMakeLists.txt (1)

```<code>cmake_minimum_required(VERSION 3.12)

project(shm-iw CXX)

set(SHM-IW_VERSION 0.1)

find_package(Protobuf REQUIRED)

include_directories(${CMAKE_BINARY_DIR})
set (Protobuf_IMPORT_DIRS ${CMAKE_SOURCE_DIR} )

add_subdirectory(shm-iw)
</code>```

shm-iw CMakeLists.txt (2)

```<code>cmake_minimum_required(VERSION 3.12)

add_subdirectory(metadata)
add_subdirectory(bci)
add_subdirectory(icon)
</code>```

bci CMakeLists.txt (3)

```<code>cmake_minimum_required(VERSION 3.12)

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS
  bci.proto
)

add_library(bci_objlib OBJECT
  ${PROTO_SRCS}
  ${PROTO_HDRS}
)
target_link_libraries(bci_objlib metadata_objlib)

add_dependencies(bci_objlib metadata_objlib)
</code>```

bci.proto

```<code>syntax = "proto3";

/* Board Control Interface */

import "shmiw/metadata/metadata.proto"; //Note the path to metadata.proto

package shm.iw.bci;

enum IndicatorType {
  Status = 0;
  Warning = 1;
  Maintenance = 2;
  Fault = 3;
}
enum IndicatorState {
  SteadyOff = 0;
  SteadyOn = 1;
  Blink = 2;
};

message GetVisualIndicationReq
{
  option (shm.iw.metadata.MESSAGE_NUMBER) = 0x1000101;
  IndicatorType indicator = 1;
}

message GetVisualIndicationCfm
{
  option (shm.iw.metadata.MESSAGE_NUMBER) = 0x1000102;

  IndicatorType indicator = 1;
  IndicatorState state = 2;
}
</code>```

metadata CMakeLists.txt (5)

```<code>cmake_minimum_required(VERSION 3.12)

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS
  metadata.proto
)

add_library(metadata_objlib OBJECT
  ${PROTO_SRCS}
  ${PROTO_HDRS}
)
</code>```

metadata.proto

```<code>syntax = "proto3";

import "google/protobuf/descriptor.proto";

package shm.iw.metadata;

extend google.protobuf.MessageOptions {
  uint32 MESSAGE_NUMBER = 50001;
}
</code>```

I skipped icon directory as it's almost the same as bci directory, they just have different messages but it's not relevant now.

When I'm compiling I'm getting an error

shm-iw/build/shm-iw/bci/bci.pb.cc:183:6: error: ‘::descriptor_table_shm_2diw_2fmetadata_2fmetadata_2eproto’ has not been declared
183 |   &::descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto,
|      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Looking at the metadata.pb.h we've got something like this:

extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_metadata_2eproto;

Let's compare the name of the missing declaration and the declaration generated in metadata.pb.h

metadata.pb.h: descriptor_table_metadata_2eproto

bci.pb.c:  descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto

They look very similar to each other, but the second one has a few additional words: shm, iw, metadata, which seem to correspond to import path defined in bci.proto

import "shmiw/metadata/metadata.proto";

What's the reason why it happens? Why does the protobuf compiler not generate the metadata's "decriptor_tabele*" accordingly to the package which is defined in metadata.proto?

答:
Protoc handling of path names is pretty confusing, but here are the basics:

Input file names are separated to include dir and relative path.

Relative path determines the name of the symbols that go into generated files.

Include dir must match a directory given with -I.

If no -I arguments are given, there is always an implicit -I .

Based on this, we can figure out why it works the way it works for you:

Case 1: relative path

```<code>/usr/bin/protoc
  --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build
  shmiw/metadata/metadata.proto
</code>```

No -I is given, so -I . is assumed. The relative path is shmiw/metadata/metadata.proto, giving the symbol name of descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto. The 2f and 2e stand for / and . which are not valid in symbol names.

Case 2: absolute path

```<code>/usr/bin/protoc
   --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build
   -I /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata
   /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata/metadata.proto
</code>```

Now the path relative to -I directory is just metadata.proto. Thus you get descriptor_table_metadata_2eproto as the symbol name.

Case 3: absolute path, but same symbol name as case 1

```<code>/usr/bin/protoc
   --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build
   -I /home/pp/Projects/SmartHomeManagement/shm-iw
   /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata/metadata.proto
</code>```

After this simple change to -I directory, it will give the same symbol name as in case 1.

Body:
[UPDATE]
It seems that protobuf_generate_cpp uses absolute paths.
Invoking protobuf compiler manually specifying relative path seems to generate valid sources.

Manual:

/usr/bin/protoc --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build shmiw/metadata/metadata.proto

produces: (metadata.pb.h)

::DescriptorTable descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto;

Name contains subdirectories

Whereas when compiling by protobuf_generate_cpp from cmake, it invokes protobuf compiler with command:

/usr/bin/protoc --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build -I /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata/metadata.proto

which produces "invalid" names that can't be used later on by other packages: (metadata.pb.h)

::DescriptorTable descriptor_table_metadata_2eproto;

I've got some problem with protobuf. I've got 3 proto files. The first one is a proto file that contains an option that all other proto files use. All proto files are organized in the same structure, and each of them belongs to a separate package. I want to generate all .h and .cc files and then put them into one single static library.
Project structure is as follows:

/root-dir
-CMakeLists.txt (1)
-shm-iw/
  - CMakeLists.txt (2)
  - bci
    - CMakeLists.txt (3)
    - bci.proto
  - icon
    - CMakeLists.txt (4)
    - icon.proto
  - metadata
    - CMakeLists.txt (5)
    - metadata.proto

Root CMakeLists.txt (1)

cmake_minimum_required(VERSION 3.12)

project(shm-iw CXX)

set(SHM-IW_VERSION 0.1)

find_package(Protobuf REQUIRED)

include_directories(${CMAKE_BINARY_DIR})
set (Protobuf_IMPORT_DIRS ${CMAKE_SOURCE_DIR} )

add_subdirectory(shm-iw)

shm-iw CMakeLists.txt (2)

cmake_minimum_required(VERSION 3.12)

add_subdirectory(metadata)
add_subdirectory(bci)
add_subdirectory(icon)

bci CMakeLists.txt (3)

cmake_minimum_required(VERSION 3.12)

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS
  bci.proto
)

add_library(bci_objlib OBJECT
  ${PROTO_SRCS}
  ${PROTO_HDRS}
)
target_link_libraries(bci_objlib metadata_objlib)

add_dependencies(bci_objlib metadata_objlib)

bci.proto

syntax = "proto3";

/* Board Control Interface */

import "shmiw/metadata/metadata.proto"; //Note the path to metadata.proto

package shm.iw.bci;

enum IndicatorType {
  Status = 0;
  Warning = 1;
  Maintenance = 2;
  Fault = 3;
}
enum IndicatorState {
  SteadyOff = 0;
  SteadyOn = 1;
  Blink = 2;
};

message GetVisualIndicationReq
{
  option (shm.iw.metadata.MESSAGE_NUMBER) = 0x1000101;
  IndicatorType indicator = 1;
}

message GetVisualIndicationCfm
{
  option (shm.iw.metadata.MESSAGE_NUMBER) = 0x1000102;

  IndicatorType indicator = 1;
  IndicatorState state = 2;
}

metadata CMakeLists.txt (5)

cmake_minimum_required(VERSION 3.12)

protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS
  metadata.proto
)

add_library(metadata_objlib OBJECT
  ${PROTO_SRCS}
  ${PROTO_HDRS}
)

metadata.proto

syntax = "proto3";

import "google/protobuf/descriptor.proto";

package shm.iw.metadata;

extend google.protobuf.MessageOptions {
  uint32 MESSAGE_NUMBER = 50001;
}

I skipped icon directory as it's almost the same as bci directory, they just have different messages but it's not relevant now.

When I'm compiling I'm getting an error

shm-iw/build/shm-iw/bci/bci.pb.cc:183:6: error: ‘::descriptor_table_shm_2diw_2fmetadata_2fmetadata_2eproto’ has not been declared
183 |   &::descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto,
|      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Looking at the metadata.pb.h we've got something like this:

extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_metadata_2eproto;

Let's compare the name of the missing declaration and the declaration generated in metadata.pb.h

metadata.pb.h: descriptor_table_metadata_2eproto

bci.pb.c:  descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto

They look very similar to each other, but the second one has a few additional words: shm, iw, metadata, which seem to correspond to import path defined in bci.proto

import "shmiw/metadata/metadata.proto";

What's the reason why it happens? Why does the protobuf compiler not generate the metadata's "decriptor_tabele*" accordingly to the package which is defined in metadata.proto?

Body:
Protoc handling of path names is pretty confusing, but here are the basics:

Input file names are separated to include dir and relative path.

Relative path determines the name of the symbols that go into generated files.

Include dir must match a directory given with -I.

If no -I arguments are given, there is always an implicit -I .

Based on this, we can figure out why it works the way it works for you:

Case 1: relative path

/usr/bin/protoc
  --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build
  shmiw/metadata/metadata.proto

No -I is given, so -I . is assumed. The relative path is shmiw/metadata/metadata.proto, giving the symbol name of descriptor_table_shmiw_2fmetadata_2fmetadata_2eproto. The 2f and 2e stand for / and . which are not valid in symbol names.

Case 2: absolute path

/usr/bin/protoc
   --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build
   -I /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata
   /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata/metadata.proto

Now the path relative to -I directory is just metadata.proto. Thus you get descriptor_table_metadata_2eproto as the symbol name.

Case 3: absolute path, but same symbol name as case 1

/usr/bin/protoc
   --cpp_out /home/pp/Projects/SmartHomeManagement/shm-iw/build
   -I /home/pp/Projects/SmartHomeManagement/shm-iw
   /home/pp/Projects/SmartHomeManagement/shm-iw/shmiw/metadata/metadata.proto

After this simple change to -I directory, it will give the same symbol name as in case 1.


来源: stackexchange

问:
Resources for field data on BLE transfer speeds
I'm currently working on a research project which revolves around me getting to know the transfer speeds of BLE in a simple setting. To be specific, I'll be working with an Arduino Nano 33 BLE board. I'm well aware that BLE v5 is capable of reaching speeds of up to 1Mb/s (Mega-bits/s) but is unrealistic in real-world applications. Are there any resources that I can get the transfer speeds of BLE? If not, I'm guessing I will have to work with an experimental setup for finding the speeds for my specific use-case. Thank you in advance!</p>

答:
The Bluetooth Radio on the Arduino Nano 33 BLE is built into the NRF52840 MCU.

More information on the Radio is found here:
https://infocenter.nordicsemi.com/topic/ps_nrf52840/radio.html?cp=4_0_0_5_19

There are definitely ways to determine real throughput of this peripheral, you just need a packet sniffer (link below) or have a transmitter/receiver board-to-board setup.

Packet Sniffer:
https://www.nordicsemi.com/Products/Development-tools/nRF-Sniffer-for-Bluetooth-LE

The board-to-board setup will have the relay serially send the number of packets received to a PC for analysis. You could configure the relay board to send the number of packets received within a certain interval (using the Timers in the NRF52840 with <microsecond precision).

If your project changes and you no longer need to use BLE and you would like to increase throughput to ~1.5Mbps, I developed and tested a working configuration of the NRF52840's Radio on the Arduino Nano 33 BLE. Link below.

https://forum.arduino.cc/t/stream-binary-data-from-arduino-nano-33-ble-to-pc-via-ble/917206

ContentLicense: CC BY-SA 4.0


问:
How to remove language link from Polylang language switcher when a language has published content?
The problem: All languages that have published content show up in the language switcher which is situated in the main navigation bar. As I only have a few pages in Swedish and users are directed directly to them, I would like to remove the link to the Swedish language translation from the main navigation.

Solution: After searching forums and reading posts here on Stack Overflow, it seems that the best way to go (if I've understood correctly) is to create a function in the theme functions.php file and add a filter to the switcher that removes Swedish if found. This is also where any wise words would be appreciated; how to go about creating an appropriate filter?

This is what I have so far. However, my site crashes when I try it out.

```<code>function trim_language_switcher() {
    $del_val = 'sv'; // Value to be deleted
    if(function_exists('pll_the_languages')) {
        $languages = pll_the_languages(array('raw'=>) // Get raw data as array
        if (($key = array_search($del_val, $languages)) !== false) { // Get key for value
            unset($languages[$key]);
        }
        return $languages;
    }
}
add_filter( 'pll_the_languages', 'trim_language_switcher' );
</code>```

Any help is greatly appreciated!

答:
Your $languages variable is not correctly set and there is also a typo (missing ")").
You should do this instead:

```<code>$languages = pll_the_languages( array( 'raw'=> 1 ) );
</code>```

But here you are trying to call the pll_the_languages() function inside the filter pll_the_languages which is applied by the previous function.
In the documentation you can see that the filter will pass two arguments to your hooked function trim_language_switcher().
To remove Swedish links you have to parse the $output parameter and remove the links before returning it.

Body:
The problem: All languages that have published content show up in the language switcher which is situated in the main navigation bar. As I only have a few pages in Swedish and users are directed directly to them, I would like to remove the link to the Swedish language translation from the main navigation.

Solution: After searching forums and reading posts here on Stack Overflow, it seems that the best way to go (if I've understood correctly) is to create a function in the theme functions.php file and add a filter to the switcher that removes Swedish if found. This is also where any wise words would be appreciated; how to go about creating an appropriate filter?

This is what I have so far. However, my site crashes when I try it out.

function trim_language_switcher() {
    $del_val = 'sv'; // Value to be deleted
    if(function_exists('pll_the_languages')) {
        $languages = pll_the_languages(array('raw'=>) // Get raw data as array
        if (($key = array_search($del_val, $languages)) !== false) { // Get key for value
            unset($languages[$key]);
        }
        return $languages;
    }
}
add_filter( 'pll_the_languages', 'trim_language_switcher' );

Any help is greatly appreciated!

Body:
Your $languages variable is not correctly set and there is also a typo (missing ")").
You should do this instead:

$languages = pll_the_languages( array( 'raw'=> 1 ) );

But here you are trying to call the pll_the_languages() function inside the filter pll_the_languages which is applied by the previous function.
In the documentation you can see that the filter will pass two arguments to your hooked function trim_language_switcher().
To remove Swedish links you have to parse the $output parameter and remove the links before returning it.


问:
iOs push notification compatible with PHP 5.2 or less
I implemented push notifications using APNS-PHP http://code.google.com/p/apns-php/ on my server. I now have to move it to a server that has php  5.2.17  and I sadly found out that apns-php  does not support php versions lower than 5.3.

Is there any way of implementing php push notifications without updating the server (witch is out of the question)?

In other words Is there any other api that can work with older PHP?

答: Have you looked at UrbanAirship. Allows sending of a million messages a month free and no hassle creating your own server!</p>

ContentLicense: CC BY-SA 3.0


问:
How to replace only the leading zeros with NA?
How can I replace leading zeros with NAs? suppose I have the following example:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})
</code>```

the goal is to have the following result:

```<code> c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0
</code>```

but doing the following will not work since it will replace all and not just the leading zeros:

```<code>df[np.abs(df) < 1e-50] = np.nan
</code>```

答:
I think you got the sign wrong.

if you switch to

```<code>df[np.abs(df) < 1e-50] = np.nan
</code>```

it should work as intended.

Body:
How can I replace leading zeros with NAs? suppose I have the following example:

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})

the goal is to have the following result:

 c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0

but doing the following will not work since it will replace all and not just the leading zeros:

df[np.abs(df) < 1e-50] = np.nan

Body:
I think you got the sign wrong.

if you switch to

df[np.abs(df) < 1e-50] = np.nan

it should work as intended.


问:
Django 4.0 - Saving Multiple Options using MultipleChoiceField
I am trying to save Multiple Choice Fields in an array inside my database

I have no idea how to do this, I have a working solution by using the standard ChoiceField but it only saves one option at the moment

I want my values inside the database to show as for example "Beavers, Cubs" or "Scouts, Cubs"

How can I change my current code to do this?

(This is only my 2nd question so any constructive criticism will be appreciated)

models.py

class User(AbstractBaseUser, PermissionsMixin):
    # A full User model with admin-compliant permissions that uses a full-length email field as the username
    # Email and password are required but all other fields are optional
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    username = models.CharField(max_length=50, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    section = models.CharField(max_length=30)
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin site.'))
    is_executive = models.BooleanField(_('executive status'), default=False,
        help_text=_('Designates that this user is part of the executive committee.'))
    is_superuser = models.BooleanField(_('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlencode(self.email)

    def get_full_name(self):
        # Returns the first_name plus the last_name, with a space in between
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        # Returns the short name (first name) for the user
        return self.first_name
```
<p>views.py</p>
<pre class="lang-py prettyprint-override"><code>def register(request):
    articles = Article.objects.filter(status=1).order_by('-date_posted')[:2]
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.username = request.POST.get('username')
            user.section = request.POST.get('section')
            user.second_section = request.POST.get('second_section')
            user.save()
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('login')
    else:
        form = UserRegisterForm()

    context = {
        'title': 'Register',
        'articles': articles,
        'form': form,
    }

    return render(request, 'accounts/register.html', context)
</code>```

forms.py

SECTION = [
    ('Beavers', 'Beavers'),
    ('Cubs', 'Cubs'),
    ('Scouts', 'Scouts'),
]

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    section = forms.ChoiceField(label='Childs Section', choices=SECTION, widget=forms.RadioSelect,
        help_text='Please select the section that your child currently attends.')
    """
    section = forms.MultipleChoiceField(label='Childs Section', choices=SECTION, widget=forms.CheckboxSelectMultiple,
        help_text='Please select the section(s) that your child currently attends.')
    """
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'section']
```

答:
Its always a good practice to have your choice filed in your backend before adding it to your forms.py like so :

```<code>
SECTION = (('BC', 'Beaver Cubs',),('SC', 'Scout Cubs',))

class User(AbstractBaseUser, PermissionsMixin):
    # A full User model with admin-compliant permissions that uses a full-length email field as the username
    # Email and password are required but all other fields are optional
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    username = models.CharField(max_length=50, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    # Here we make the selection of our section in choice filed
    section = models.CharField(choices=SECTION, max_length=10)

    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin site.'))
    is_executive = models.BooleanField(_('executive status'), default=False,
        help_text=_('Designates that this user is part of the executive committee.'))
    is_superuser = models.BooleanField(_('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlencode(self.email)

    def get_full_name(self):
        # Returns the first_name plus the last_name, with a space in between
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        # Returns the short name (first name) for the user
        return self.first_name

</code>```

then we add the field to our form like so :

```<code>
lass UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password1',
        'password2', 'section']
         widgets = {
            'section': forms.Select(attrs={'class': 'custom-select md-form'}),
        }

#  This is as clean and good practice
</code>```

Body:
I am trying to save Multiple Choice Fields in an array inside my database

I have no idea how to do this, I have a working solution by using the standard ChoiceField but it only saves one option at the moment

I want my values inside the database to show as for example "Beavers, Cubs" or "Scouts, Cubs"

How can I change my current code to do this?

(This is only my 2nd question so any constructive criticism will be appreciated)

models.py

class User(AbstractBaseUser, PermissionsMixin):
    # A full User model with admin-compliant permissions that uses a full-length email field as the username
    # Email and password are required but all other fields are optional
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    username = models.CharField(max_length=50, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    section = models.CharField(max_length=30)
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin site.'))
    is_executive = models.BooleanField(_('executive status'), default=False,
        help_text=_('Designates that this user is part of the executive committee.'))
    is_superuser = models.BooleanField(_('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlencode(self.email)

    def get_full_name(self):
        # Returns the first_name plus the last_name, with a space in between
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        # Returns the short name (first name) for the user
        return self.first_name

views.py

def register(request):
    articles = Article.objects.filter(status=1).order_by('-date_posted')[:2]
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.username = request.POST.get('username')
            user.section = request.POST.get('section')
            user.second_section = request.POST.get('second_section')
            user.save()
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('login')
    else:
        form = UserRegisterForm()

    context = {
        'title': 'Register',
        'articles': articles,
        'form': form,
    }

    return render(request, 'accounts/register.html', context)

forms.py

SECTION = [
    ('Beavers', 'Beavers'),
    ('Cubs', 'Cubs'),
    ('Scouts', 'Scouts'),
]

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    section = forms.ChoiceField(label='Childs Section', choices=SECTION, widget=forms.RadioSelect,
        help_text='Please select the section that your child currently attends.')
    """
    section = forms.MultipleChoiceField(label='Childs Section', choices=SECTION, widget=forms.CheckboxSelectMultiple,
        help_text='Please select the section(s) that your child currently attends.')
    """
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'section']

Body:
Its always a good practice to have your choice filed in your backend before adding it to your forms.py like so :

SECTION = (('BC', 'Beaver Cubs',),('SC', 'Scout Cubs',))

class User(AbstractBaseUser, PermissionsMixin):
    # A full User model with admin-compliant permissions that uses a full-length email field as the username
    # Email and password are required but all other fields are optional
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    username = models.CharField(max_length=50, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    # Here we make the selection of our section in choice filed
    section = models.CharField(choices=SECTION, max_length=10)

    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin site.'))
    is_executive = models.BooleanField(_('executive status'), default=False,
        help_text=_('Designates that this user is part of the executive committee.'))
    is_superuser = models.BooleanField(_('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without explicitly assigning them.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlencode(self.email)

    def get_full_name(self):
        # Returns the first_name plus the last_name, with a space in between
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        # Returns the short name (first name) for the user
        return self.first_name

then we add the field to our form like so :

lass UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    class Meta:
        model = User
        fields = ['username', 'email', 'first_name', 'last_name', 'password1',
        'password2', 'section']
         widgets = {
            'section': forms.Select(attrs={'class': 'custom-select md-form'}),
        }

#  This is as clean and good practice


问:
Github keeps performing external checks even after removing the webhook
We have some checks for our Github repo that run in Jenkins via a Webhook. We moved them to another CI server but, even after disabling/removing the Jenkins Webhook from the repo, the old PRs still triggers the old Jenkins checks and fail. New PRs are not affected.

How can we clean or remove this old/stale checks for existing PRs?

答:
After struggling here, we found out that the checks are tied to the commit. So, even if you create new branches or PRs, if they share the same commit, the checks will be reused.

After pushing a new commit, the checks were refreshed and the stale ones were removed.


问:
Evenly push values from a flat array into same positioned rows of a 2d array
I need to evenly/synchronously push values from my second array into the rows of my first array.

The arrays which have the same size, but with different keys and depths.  The first is an array of rows and the second is a flat array.

```<code>$array1 = [
    12 => [130, 28, 1],
    19 => [52, 2, 3],
    34 => [85, 10, 5]
]

$array2 = [4, 38, 33]
</code>```

Preferred result:

```<code>[
    12 => [130, 28, 1, 4],
    19 => [52, 2, 3, 38],
    34 => [85, 10, 5, 33]
]
</code>```

(I would like to keep the same indices of array 1, however it is not mandatory.)

I have tried these methods, but none of them work because the first array keys are unpredictable.

```<code>$final = [];
foreach ($array1 as $idx => $val) {
    $final = [$val, $array2[$idx]];
}
</code>```

Another:

```<code>foreach ($array1 as $index => $subArray) {
    $array1 [$index][] = $array2[$index];
}
</code>```

答:
An example using foreach

<?php

$a = [
    2 => [130, 28, 1, 1, 6],
    3 => [52, 2, 3, 3, 27]
];

$b = [5, 38];

$output = [];
$idx = 0;
foreach ($a as $key => $value) {
    $value[] = $b[$idx];
    $output[$key] = $value;
    ++$idx;
}

print_r($output);
```

Sandbox HERE

Body:
I need to evenly/synchronously push values from my second array into the rows of my first array.

The arrays which have the same size, but with different keys and depths.  The first is an array of rows and the second is a flat array.

$array1 = [
    12 => [130, 28, 1],
    19 => [52, 2, 3],
    34 => [85, 10, 5]
]

$array2 = [4, 38, 33]

Preferred result:

[
    12 => [130, 28, 1, 4],
    19 => [52, 2, 3, 38],
    34 => [85, 10, 5, 33]
]

(I would like to keep the same indices of array 1, however it is not mandatory.)

I have tried these methods, but none of them work because the first array keys are unpredictable.

$final = [];
foreach ($array1 as $idx => $val) {
    $final = [$val, $array2[$idx]];
}

Another:

foreach ($array1 as $index => $subArray) {
    $array1 [$index][] = $array2[$index];
}

Body:
An example using foreach

<?php

$a = [
    2 => [130, 28, 1, 1, 6],
    3 => [52, 2, 3, 3, 27]
];

$b = [5, 38];

$output = [];
$idx = 0;
foreach ($a as $key => $value) {
    $value[] = $b[$idx];
    $output[$key] = $value;
    ++$idx;
}

print_r($output);

Sandbox HERE


答:
You can loop $array1 using a foreach to get the current key $index

Get the value from $array2 by using a counter as the array key which, is incremented by 1 for every iteration.

Then add the value to the end of the current array.

```<code>$array1 = [
    2 => [130, 28, 1, 1, 6],
    3 => [52, 2, 3, 3, 27],
    13 => [41, 20, 27, 13, 37]
];
$array2 = [89, 99, 109];

$counter = 0;
foreach ($array1 as $index => $subArray) {
    $array1[$index][] = $array2[$counter++];
}

print_r($array1);
</code>```

Output

```<code>Array
(
    [2] => Array
        (
            [0] => 130
            [1] => 28
            [2] => 1
            [3] => 1
            [4] => 6
            [5] => 89
        )

    [3] => Array
        (
            [0] => 52
            [1] => 2
            [2] => 3
            [3] => 3
            [4] => 27
            [5] => 99
        )

    [13] => Array
        (
            [0] => 41
            [1] => 20
            [2] => 27
            [3] => 13
            [4] => 37
            [5] => 109
        )

)
</code>```

See a PHP demo.

Title: Evenly push values from a flat array into same positioned rows of a 2d array

Body:
You can loop $array1 using a foreach to get the current key $index

Get the value from $array2 by using a counter as the array key which, is incremented by 1 for every iteration.

Then add the value to the end of the current array.

$array1 = [
    2 => [130, 28, 1, 1, 6],
    3 => [52, 2, 3, 3, 27],
    13 => [41, 20, 27, 13, 37]
];
$array2 = [89, 99, 109];

$counter = 0;
foreach ($array1 as $index => $subArray) {
    $array1[$index][] = $array2[$counter++];
}

print_r($array1);

Output

Array
(
    [2] => Array
        (
            [0] => 130
            [1] => 28
            [2] => 1
            [3] => 1
            [4] => 6
            [5] => 89
        )

    [3] => Array
        (
            [0] => 52
            [1] => 2
            [2] => 3
            [3] => 3
            [4] => 27
            [5] => 99
        )

    [13] => Array
        (
            [0] => 41
            [1] => 20
            [2] => 27
            [3] => 13
            [4] => 37
            [5] => 109
        )

)

See a PHP demo.


问:
GWT Development mode not working (configuring web.xml)
My application is working great in development mode (with GWT-RPC calls), however whenever I try to test it using production mode (by removing the ?gwt.codesvr=127.0.0.1:9997 part of the URL), it used to give me a blank page.

I manually checked the VoitureTourisme.html file and modified the voitureTourisme.nocache.js file's path to a working one (this means that my Web.xml isn't configured properly, right? then why does it work in dev mode?)

Now it looks like this

but it used to be

src="com.devsys.calculateur.voitureTourisme.VoitureTourisme/com.devsys.calculateur.voitureTourisme.VoitureTourisme.nocache.js"
when I first compiled.
Because I tried different variations and compiled a few times, I now got 2 module folders inside my war : "voitureTourisme" and the other with the full path as shown above.

I'm pretty sure I'm confusing how to properly configure the VoitureTourisme.gwt.xml and Web.XML files, because I wouldn't have to manually correct the compiled html file if I did.
After I fixed it manually (which I shouldn't have to do), my RPC calls showed a 404 error because they didn't find my servlet for the service (bad url).

Hopefully you can show me what's wrong and why with my configuration

Web.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <!-- TODO: Add <servlet> tags for each servlet here. -->
    <!-- TODO: Add <servlet-mapping> tags for each <servlet> here. -->
    <!-- TODO: Optionally add a <welcome-file-list> tag to display a welcome file. -->
     <!-- Servlets -->
  <servlet>
    <servlet-name>calculateurDataService</servlet-name>
    <servlet-class>com.devsys.calculateur.voitureTourisme.server.form.CalculateurDataServiceImpl</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>calculateurDataService</servlet-name>
    <url-pattern>/com.devsys.calculateur.voitureTourisme.VoitureTourisme/calculateurDataService</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

VoitureTourisme.gwt.xml

```<code><module>
    <inherits name="com.google.gwt.user.User"/>
    <inherits name="com.google.gwt.user.theme.standard.Standard"/>
    <inherits name="com.devsys.util.XmlUtil"/>
    <inherits name="com.devsys.util.UrlUtil"/>
    <inherits name="com.google.gwt.i18n.I18N"/>
    <entry-point class="com.devsys.calculateur.voitureTourisme.client.VoitureTourisme"/>
</module>
</code>```

I also have my service interface using

```<code>@RemoteServiceRelativePath("calculateurDataService")
</code>```

Is that correct? Should I use it?

答:
i think the problem is module name related. Try adding this line of your gwt.xml before inherits begin:

```<code><module rename-to='voituretourisme'>
</code>```

and then in your web.xml file try changing  to :

```<code><url-pattern>/voituretourisme/calculateurDataService</url-pattern>
</code>```

your html file should be like :

```<code><script language="javascript" src="voituretourisme/voituretourisme.nocache.js"></script>
</code>```

mind case sensitivity and I beleive this should compile correctly and work both in development mode and production mode.

Body:
My application is working great in development mode (with GWT-RPC calls), however whenever I try to test it using production mode (by removing the ?gwt.codesvr=127.0.0.1:9997 part of the URL), it used to give me a blank page.

I manually checked the VoitureTourisme.html file and modified the voitureTourisme.nocache.js file's path to a working one (this means that my Web.xml isn't configured properly, right? then why does it work in dev mode?)

Now it looks like this

but it used to be

src="com.devsys.calculateur.voitureTourisme.VoitureTourisme/com.devsys.calculateur.voitureTourisme.VoitureTourisme.nocache.js"
when I first compiled.
Because I tried different variations and compiled a few times, I now got 2 module folders inside my war : "voitureTourisme" and the other with the full path as shown above.

I'm pretty sure I'm confusing how to properly configure the VoitureTourisme.gwt.xml and Web.XML files, because I wouldn't have to manually correct the compiled html file if I did.
After I fixed it manually (which I shouldn't have to do), my RPC calls showed a 404 error because they didn't find my servlet for the service (bad url).

Hopefully you can show me what's wrong and why with my configuration

Web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

  <servlet>
    <servlet-name>calculateurDataService</servlet-name>
    <servlet-class>com.devsys.calculateur.voitureTourisme.server.form.CalculateurDataServiceImpl</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>calculateurDataService</servlet-name>
    <url-pattern>/com.devsys.calculateur.voitureTourisme.VoitureTourisme/calculateurDataService</url-pattern>
  </servlet-mapping>
</web-app>

VoitureTourisme.gwt.xml

<module>
    <inherits name="com.google.gwt.user.User"/>
    <inherits name="com.google.gwt.user.theme.standard.Standard"/>
    <inherits name="com.devsys.util.XmlUtil"/>
    <inherits name="com.devsys.util.UrlUtil"/>
    <inherits name="com.google.gwt.i18n.I18N"/>
    <entry-point class="com.devsys.calculateur.voitureTourisme.client.VoitureTourisme"/>
</module>

I also have my service interface using

@RemoteServiceRelativePath("calculateurDataService")

Is that correct? Should I use it?

Body:
i think the problem is module name related. Try adding this line of your gwt.xml before inherits begin:

<module rename-to='voituretourisme'>

and then in your web.xml file try changing  to :

<url-pattern>/voituretourisme/calculateurDataService</url-pattern>

your html file should be like :

<script language="javascript" src="voituretourisme/voituretourisme.nocache.js"></script>

mind case sensitivity and I beleive this should compile correctly and work both in development mode and production mode.


问:
How to write file with data is Uint8Array?
I have some problems write file ( image ) to folder.

my script I get Uint8Array() from image

```<code>var arrayBuffer = event.target.result
var byteArray = new Uint8Array(arrayBuffer);
</code>```

Then, I used "json.dumps", objData['imagedata'] is "var byteArray "

```<code>print(objData['imagedata'])
print("=========================================================================")
user_encode_data = json.dumps(objData['imagedata']).encode('utf-8')
print(user_encode_data)
</code>```

Example image is print(user_encode_data) then I saved it in mysql with data type as longblob.

```<code>read_blob(1,"./MainArchives/images/data.png")

def read_blob(author_id, filename):
   query = *my syntax query*
   ...
   photo = cursor.fetchone()[0] // "photo" is "user_encode_data" when I get back from mysql => as mentioned above *
   write_file(photo, filename)
</code>```

And Finally is function "write_file"

```<code>def write_file(data, filename):
   with open(filename, 'wb') as f:
       f.write(data)
</code>```

And i get error as: ==>
TypeError: a bytes-like object is required, not 'str'

答:
You opened the file in wb mode which means write binary data to the file whereas ur data is in str format. Try changing your data to binary format or if you dont want that you can simply do it by</p>
```<code>def write_file(data, filename):
   with open(filename, 'w') as f:
       f.write(data)
</code>```

Body:
I have some problems write file ( image ) to folder.

my script I get Uint8Array() from image

var arrayBuffer = event.target.result
var byteArray = new Uint8Array(arrayBuffer);

Then, I used "json.dumps", objData['imagedata'] is "var byteArray "

print(objData['imagedata'])
print("=========================================================================")
user_encode_data = json.dumps(objData['imagedata']).encode('utf-8')
print(user_encode_data)

Example image is print(user_encode_data) then I saved it in mysql with data type as longblob.

read_blob(1,"./MainArchives/images/data.png")

def read_blob(author_id, filename):
   query = *my syntax query*
   ...
   photo = cursor.fetchone()[0] // "photo" is "user_encode_data" when I get back from mysql => as mentioned above *
   write_file(photo, filename)

And Finally is function "write_file"

def write_file(data, filename):
   with open(filename, 'wb') as f:
       f.write(data)

And i get error as: ==>
TypeError: a bytes-like object is required, not 'str'

Body:
You opened the file in wb mode which means write binary data to the file whereas ur data is in str format. Try changing your data to binary format or if you dont want that you can simply do it by

def write_file(data, filename):
   with open(filename, 'w') as f:
       f.write(data)


问:
Why does "L.insert(it--, i);" behave differently from "L.insert(it, i); it--;"?
These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different results. Where is my understanding off?

list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it--, i);
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 2 5 0 4 1 3
}
```
<pre class="lang-cpp prettyprint-override"><code>list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it, i);
        it--;
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 5 4 3 2 1 0
}
</code>```

答:
Consider exactly when the post-decrement happens.  In the second case, obviously the insert happens, modifying the list itself.  The iterator is still valid, pointing now at the second entry.  Then the decrement is computed, moving the iterator to the first entry.

In the first case, however, the post-decrement "makes a copy" of the iterator, performs the decrement, and returns the previous version.  That means that the new value of the iterator is computed before the insert happens, which is invalid since it already points at the first element.  Note that the insert still happens correctly, because the post-decrement returns the original and still-valid iterator.

This is not about post- vs. pre- decrement behavior.  It's about when the side-effect of the decrement actually happens.  See https://en.cppreference.com/w/cpp/language/eval_order, specifically

When calling a function (whether or not the function is inline, and
whether or not explicit function call syntax is used), every value
computation and side effect associated with any argument expression,
or with the postfix expression designating the called function, is
sequenced before execution of every expression or statement in the
body of the called function.

Body:
These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different results. Where is my understanding off?

list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it--, i);
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 2 5 0 4 1 3
}

list<int> L;

int main() {
    L.push_back(0);
    L.push_front(1);
    auto it = L.begin();
    for (int i = 2; i <= 5; i++) {
        L.insert(it, i);
        it--;
    }
    for (auto num : L) {
        printf("%d ", num);
    }
    // 5 4 3 2 1 0
}


问:
SQLServer - Is it possible to divide the results of the same column?
I have a table containing the input and output parameters of different APIs. Here is the structure of my database :

```<code>API : API_ID (PK), API_URI, API_DATE, API_DESCRIPTION

RELATION : API_PAR_ID (PK), APIPAR_API_ID (FK), APIPAR_PAR_ID (FK)

Parametre : PAR_ID (PK), PAR_NOM, PAR_TYPE
</code>```

The only way to differentiate if a parameter is input or output is the type.
If the type is NULL ? It is an output parameter.

So, I would like to know if it is possible in a simple query to make the difference between the two. That is, in my SELECT displayed in one column the name of the input parameters  and in another the output parameters, something that could look like this

SELECT
    [PAR_NOM] AS [INPUT]
    , [PAR_NOM] AS [OUPUT]
    , [PAR_type]
FROM Parametre AS P
    INNER JOIN RELATION AS R
        ON P.[PAR_ID] = R.[APIPAR_PAR_ID]
WHERE [APIPAR_PAR_ID] = 10```
</div>
</div>
</p>
<p>Or do I have to make two requests? One to get the input parameters, and another one for the output parameters?
Knowing that the columns are important because I intend to use them in an API</p>
<p>Sample data :</p>
```API : 1, 'API/DOC/V1', '08/02/2022', 'First api'
API : 2, 'API/SERVER/V1', '10/01/2022', 'Api call for the server'
API : 3, 'API/CITY/V2', '15/03/2022', 'Api to get name of cities'

PARAMETRE : 1, CODE_PO, 'string'
PARAMETRE : 2, REF_SO, NULL
PARAMETRE : 3, NB_AR, NULL

RELATION : 1, 1, 1
RELATION : 2, 1, 2
RELATION : 3, 2, 3
```
<p>Exemple result :</p>
```INPUT       OUTPUT      par_type
code_po     NULL        string
NULL        REF_SO      NULL
NULL        NB_AR       NULL
```

答:
Your question is difficult to understand, but I think you can use a simple case to determine when the parameter is null or not

You can try it out yourself at this Fiddle

```<code>select case when p.PAR_TYPE is not null then p.PAR_NOM else null end as INPUT,
       case when p.PAR_TYPE is null then p.PAR_NOM else null end as OUTPUT,
       p.PAR_TYPE
from   Parametre p
</code>```

Body:
I have a table containing the input and output parameters of different APIs. Here is the structure of my database :

API : API_ID (PK), API_URI, API_DATE, API_DESCRIPTION

RELATION : API_PAR_ID (PK), APIPAR_API_ID (FK), APIPAR_PAR_ID (FK)

Parametre : PAR_ID (PK), PAR_NOM, PAR_TYPE

The only way to differentiate if a parameter is input or output is the type.
If the type is NULL ? It is an output parameter.

So, I would like to know if it is possible in a simple query to make the difference between the two. That is, in my SELECT displayed in one column the name of the input parameters  and in another the output parameters, something that could look like this

SELECT
    [PAR_NOM] AS [INPUT]
    , [PAR_NOM] AS [OUPUT]
    , [PAR_type]
FROM Parametre AS P
    INNER JOIN RELATION AS R
        ON P.[PAR_ID] = R.[APIPAR_PAR_ID]
WHERE [APIPAR_PAR_ID] = 10

Or do I have to make two requests? One to get the input parameters, and another one for the output parameters?
Knowing that the columns are important because I intend to use them in an API

Sample data :

API : 1, 'API/DOC/V1', '08/02/2022', 'First api'
API : 2, 'API/SERVER/V1', '10/01/2022', 'Api call for the server'
API : 3, 'API/CITY/V2', '15/03/2022', 'Api to get name of cities'

PARAMETRE : 1, CODE_PO, 'string'
PARAMETRE : 2, REF_SO, NULL
PARAMETRE : 3, NB_AR, NULL

RELATION : 1, 1, 1
RELATION : 2, 1, 2
RELATION : 3, 2, 3

Exemple result :

INPUT       OUTPUT      par_type
code_po     NULL        string
NULL        REF_SO      NULL
NULL        NB_AR       NULL

Body:
Your question is difficult to understand, but I think you can use a simple case to determine when the parameter is null or not

You can try it out yourself at this Fiddle

select case when p.PAR_TYPE is not null then p.PAR_NOM else null end as INPUT,
       case when p.PAR_TYPE is null then p.PAR_NOM else null end as OUTPUT,
       p.PAR_TYPE
from   Parametre p


问:
Capturing an array inside text file
I have a program that, unfortunately, saves some information in a text file, making the text file almost like a database. So I decided to create a front end that is able to handle it.

An example of what's in the file:

```<code>Host {
  Name = test1
  Address = 192.168.0.1
  Port = 8080
 }

Host {
  Name = test2
  Address = 192.168.0.2
  Port = 8080
 }
</code>```

To start I'm using fwrite() to insert new Hosts at the end of the file. But when I try to edit the Hosts through functions using seek() it doesn't work well because it counts byte by byte.
Ok, so I tried to create an array for this, to try to edit the data like the "Name". I'm actually basing a lot on this article: how to convert a string with brackets to an array in php.

```<code>Array ( [Host ] => Array ( [ Name = test1 Address = 192.168.0.1 Port = 8080 ] => Array ( ) ) )
</code>```

Can anyone guide me in the right way to do it?

My code:

```<code><?php
    $input = shell_exec("cat /etc/Program/Hosts.conf");

                    $output = array();
                    $pointer = &$output;

                    while( ($index = strpos( $input, '{')) !== false) {
                        if( $index != 0)  {
                            $key = substr( $input, 0, $index);
                            $pointer[$key] = array();
                            $pointer = &$pointer[$key];
                            $input = substr( $input, $index);
                            continue;
                        }
                        $end_index = strpos( $input, '}');
                        $array_key = substr( $input, $index + 1, $end_index - 1);
                        $pointer[$array_key] = array();
                        $pointer = &$pointer[$array_key];
                        $input = substr( $input, $end_index + 1);
                    }

                    print_r( $output);
?>
</code>```

答:
You can use file() to convert the file to array of lines and then manipulate the array to get array of hosts. Try this

```<code>function hostsToArray($filepath){
    $file  = array_map('trim', file($filepath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    $array = [];
    $i     = 0;

    foreach ($file as $line) {
        if( $line === 'Host {' ){
            $array[$i] = [];
        }else if( $line === '}' ){
            $i++;
        }else{
            list($key, $value) = explode(' = ', $line);
            $array[$i][$key] = $value;
        }
    }

    return $array;
}

$hosts = hostsToArray('/etc/Program/Hosts.conf');
print_r($hosts);
</code>```

Title: Capturing an array inside text file

Body:
I have a program that, unfortunately, saves some information in a text file, making the text file almost like a database. So I decided to create a front end that is able to handle it.

An example of what's in the file:

Host {
  Name = test1
  Address = 192.168.0.1
  Port = 8080
 }

Host {
  Name = test2
  Address = 192.168.0.2
  Port = 8080
 }

To start I'm using fwrite() to insert new Hosts at the end of the file. But when I try to edit the Hosts through functions using seek() it doesn't work well because it counts byte by byte.
Ok, so I tried to create an array for this, to try to edit the data like the "Name". I'm actually basing a lot on this article: how to convert a string with brackets to an array in php.

Array ( [Host ] => Array ( [ Name = test1 Address = 192.168.0.1 Port = 8080 ] => Array ( ) ) )

Can anyone guide me in the right way to do it?

My code:

<?php
    $input = shell_exec("cat /etc/Program/Hosts.conf");

                    $output = array();
                    $pointer = &$output;

                    while( ($index = strpos( $input, '{')) !== false) {
                        if( $index != 0)  {
                            $key = substr( $input, 0, $index);
                            $pointer[$key] = array();
                            $pointer = &$pointer[$key];
                            $input = substr( $input, $index);
                            continue;
                        }
                        $end_index = strpos( $input, '}');
                        $array_key = substr( $input, $index + 1, $end_index - 1);
                        $pointer[$array_key] = array();
                        $pointer = &$pointer[$array_key];
                        $input = substr( $input, $end_index + 1);
                    }

                    print_r( $output);
?>

Body:
You can use file() to convert the file to array of lines and then manipulate the array to get array of hosts. Try this

function hostsToArray($filepath){
    $file  = array_map('trim', file($filepath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    $array = [];
    $i     = 0;

    foreach ($file as $line) {
        if( $line === 'Host {' ){
            $array[$i] = [];
        }else if( $line === '}' ){
            $i++;
        }else{
            list($key, $value) = explode(' = ', $line);
            $array[$i][$key] = $value;
        }
    }

    return $array;
}

$hosts = hostsToArray('/etc/Program/Hosts.conf');
print_r($hosts);


问:
How to search a directory path within a file using vi editor
I want  to search for a directory path within a file in vi editor. How can I do that ?</p>

答: Using CentOS Linux 8.5 with vim 8.0, I was able to search a path within a text file edited via "vi myFile.txt" by escaping the path delimiter "/" with a "" character.  Example: To look for /var/lib within myFile.txt, I run "vi myFile.txt" and in the editing session enter:  \/var\/lib.


问:
Some SVGs work in Nextjs and some not, why?
I've struggled with svgs from here, when I tried using them in my Nextjs app.
They won't show as background-image or image itself. I've tried svgs from other places and they work, I couldn't find out why?

This doesn't work. This is inside that file:

```<code><svg width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M10.25 6.75L4.75 12L10.25 17.25"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19.25 12H5"/></svg>
</code>```

This does work. This is inside that file:

```<code><?xml version="1.0" ?><svg width="128px" height="128px" viewBox="0 0 128 128" data-name="Layer 1" id="Layer_1" xmlns="http://www.w3.org/2000/svg"><defs><style>.cls-1{fill:#231f20;}</style></defs><title/><path class="cls-1" d="M87.59,23.4H40.41a17,17,0,0,0-17,17V87.6a17,17,0,0,0,17,17H87.59a17,17,0,0,0,17-17V40.4A17,17,0,0,0,87.59,23.4Zm0,77.2H66.14V97.4a2,2,0,0,0-4,0v3.2H40.41a13,13,0,0,1-13-13V66H31a2,2,0,1,0,0-4H27.41V40.4a13,13,0,0,1,13-13H62.14v3a2,2,0,0,0,4,0v-3H87.59a13,13,0,0,1,13,13V62H97a2,2,0,0,0,0,4h3.61V87.6A13,13,0,0,1,87.59,100.6Z"/><path class="cls-1" d="M77.15,73.08l-11-8.92L66,37.82a2,2,0,0,0-2-2h0a2,2,0,0,0-2,2l.14,27.29a2,2,0,0,0,.74,1.54l11.75,9.52a2,2,0,0,0,1.26.45,2,2,0,0,0,1.56-.74A2,2,0,0,0,77.15,73.08Z"/></svg>
</code>```

I've tried copying some elements from svg that works to the one that doesn't, but to no success. When I convert first svg into png it works again... I've tried changing stroke color and clearing cache too.

Edit:

in index.tsx:

```<code>import style from './task.module.css'

const Task= () => {
    return <div className={style.test}>
        <img src="/arrow-left.svg" alt="" />
    </div>
}

export default Task
</code>```

in task.module.css

```<code>.test{
    display: inline-block;
    width: 3rem;
    height: 3rem;
    background-image: url(/arrow-left.svg);
    background-position: center;
    background-size: 2rem;
    background-repeat: no-repeat;
}
</code>```

答:
Add the xmlns attribute when referring external svg files

xmlns="http://www.w3.org/2000/svg" so your arrow.svg becomes

```<code> <svg width="24" height="24" fill="none" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M10.25 6.75L4.75 12L10.25 17.25"
            />
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M19.25 12H5"
            />
          </svg>
</code>```

Here is a very well drafted explanation of why

and your arrow working - https://stackblitz.com/edit/nextjs-vhje7s?file=pages%2Findex.js

Body:
I've struggled with svgs from here, when I tried using them in my Nextjs app.
They won't show as background-image or image itself. I've tried svgs from other places and they work, I couldn't find out why?

This doesn't work. This is inside that file:

<svg width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M10.25 6.75L4.75 12L10.25 17.25"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19.25 12H5"/></svg>

This does work. This is inside that file:

<?xml version="1.0" ?><svg width="128px" height="128px" viewBox="0 0 128 128" data-name="Layer 1" id="Layer_1" xmlns="http://www.w3.org/2000/svg"><defs></defs><title/><path class="cls-1" d="M87.59,23.4H40.41a17,17,0,0,0-17,17V87.6a17,17,0,0,0,17,17H87.59a17,17,0,0,0,17-17V40.4A17,17,0,0,0,87.59,23.4Zm0,77.2H66.14V97.4a2,2,0,0,0-4,0v3.2H40.41a13,13,0,0,1-13-13V66H31a2,2,0,1,0,0-4H27.41V40.4a13,13,0,0,1,13-13H62.14v3a2,2,0,0,0,4,0v-3H87.59a13,13,0,0,1,13,13V62H97a2,2,0,0,0,0,4h3.61V87.6A13,13,0,0,1,87.59,100.6Z"/><path class="cls-1" d="M77.15,73.08l-11-8.92L66,37.82a2,2,0,0,0-2-2h0a2,2,0,0,0-2,2l.14,27.29a2,2,0,0,0,.74,1.54l11.75,9.52a2,2,0,0,0,1.26.45,2,2,0,0,0,1.56-.74A2,2,0,0,0,77.15,73.08Z"/></svg>

I've tried copying some elements from svg that works to the one that doesn't, but to no success. When I convert first svg into png it works again... I've tried changing stroke color and clearing cache too.

Edit:

in index.tsx:

import style from './task.module.css'

const Task= () => {
    return

}

export default Task

in task.module.css

.test{
    display: inline-block;
    width: 3rem;
    height: 3rem;
    background-image: url(/arrow-left.svg);
    background-position: center;
    background-size: 2rem;
    background-repeat: no-repeat;
}

Body:
Add the xmlns attribute when referring external svg files

xmlns="http://www.w3.org/2000/svg" so your arrow.svg becomes

 <svg width="24" height="24" fill="none" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M10.25 6.75L4.75 12L10.25 17.25"
            />
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M19.25 12H5"
            />
          </svg>

Here is a very well drafted explanation of why

and your arrow working - https://stackblitz.com/edit/nextjs-vhje7s?file=pages%2Findex.js


问:
Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource
I am trying to run the spring boot application not able to access H2 database

```<code>   spring.datasource.initialization-mode=embedded
    spring.datasource.url=jdbc:h2:mem:bitsapi;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    spring.datasource.username=sa
    spring.datasource.password=
</code>```

these how my pom.xml i have added dependency's

```<code><dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>2.7.9</version>
    <scope>compile</scope>
</dependency>
</code>```

when i run the the application am getting failed to bind properties

```<code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-13 12:01:39,685 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource:

    Property: driverclassname
    Value: org.h2.Driver
    Origin: "driverClassName" from property source "source"
    Reason: Failed to load driver class org.h2.Driver in either of HikariConfig class loader or Thread context classloader

Action:

Update your application's configuration
</code>```

答:
I was getting above error,

when trying to bring-up my spring-boot application in intellij.

The mistake I was making was

After changing in "build.gradle" file,

(ie adding runtimeOnly('com.h2database:h2'))

I did NOT do the "Reload gradle project",

that's why above error was coming.

Once completed "Reload gradle project", above error was gone.

Body:
I am trying to run the spring boot application not able to access H2 database

   spring.datasource.initialization-mode=embedded
    spring.datasource.url=jdbc:h2:mem:bitsapi;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    spring.datasource.username=sa
    spring.datasource.password=

these how my pom.xml i have added dependency's

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>2.7.9</version>
    <scope>compile</scope>
</dependency>

when i run the the application am getting failed to bind properties

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-13 12:01:39,685 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under '' to com.zaxxer.hikari.HikariDataSource:

    Property: driverclassname
    Value: org.h2.Driver
    Origin: "driverClassName" from property source "source"
    Reason: Failed to load driver class org.h2.Driver in either of HikariConfig class loader or Thread context classloader

Action:

Update your application's configuration


问:
How to test custom file upload React component?
I have a React component to upload files. Below is part of the code that handles the file selection and once files are selected, it will display thumbnails.

I want to use RTL to test the file selection: clicking button which is EvidenceUploaderPanel, this opens the file selector input element, then choosing files.

This will also make the requests to upload the files as they are selected.

But I have no idea how to start.

```<code>function UploadScreen({
  title,
  maxNumberOfUploadFiles = 3,
  acceptedFileTypes,
}: Props) {
  const [documents, setDocuments] = useState<FileObject[]>([]);

  const handleFileSelection = (files: FileList) => {

    const documentsWithThumbnails = Array.from(files).map((file) => {
      // here I also make a request to upload each file.
      return {
        file,
        thumbnailURL: URL.createObjectURL(file),
        name: file.name,
      };
    });
    setDocuments((currentDocuments) => [...currentDocuments, ...documentsWithThumbnails]);
  };

  const inputRef = useRef(
    (() => {
      const element = document.createElement('input');
      element.multiple = true;
      element.type = 'file';
      element.accept = acceptedFileTypes?.join(',') || IMAGE_MIME_TYPES.join(',');
      element.addEventListener('change', () => {
        if (element.files && documents.length + element.files.length < maxNumberOfUploadFiles) {
          handleFileSelection(element.files);
          element.value = '';
        }
      });

      return element;
    })(),
  );

  const handleOpenFileClicker = () => {
    inputRef.current.click();
  };

  return (
    <div>
      <h2 className="container">{title}</h2>
       {documents.length > 0 ? (
        <section>
          <div className="body-text">
           Add files
          </div>
          <div className="thumbnail-container">
            {documents.map((doc) => {
              return (
                <BaseThumbnail
                  src={doc?.thumbnailURL}
                  key={doc.name}
                  deleteAction={() => {
                    deleteDocument(doc.name);
                  }}
                />
              );
            })}
          </div>
          <Link onPress={handleOpenFileClicker}>
            Add photos
          </Link>
        </section>
      ) : (
        <section>
          <div className="text">
            Add files
          </div>
          <div className="upload-container" />
          <EvidenceUploaderPanel
            labelText="upload files"
            openFilePicker={handleOpenFileClicker}
          />
        </section>
       )}
    </div>
  );
}

</code>```

答:
Have you thought about maybe using cypress for this?
They have a nice built in function that does exactly what you want and the setup Is really easy.

I’d recommend you using the cypress component testing for react, they have an entire page on their website’s docs explaining how to set it up. And than you can just mount the file selection component and use their cy.selectFile() method.

Good luck :)

Body:
I have a React component to upload files. Below is part of the code that handles the file selection and once files are selected, it will display thumbnails.

I want to use RTL to test the file selection: clicking button which is EvidenceUploaderPanel, this opens the file selector input element, then choosing files.

This will also make the requests to upload the files as they are selected.

But I have no idea how to start.

function UploadScreen({
  title,
  maxNumberOfUploadFiles = 3,
  acceptedFileTypes,
}: Props) {
  const [documents, setDocuments] = useState<FileObject[]>([]);

  const handleFileSelection = (files: FileList) => {

    const documentsWithThumbnails = Array.from(files).map((file) => {
      // here I also make a request to upload each file.
      return {
        file,
        thumbnailURL: URL.createObjectURL(file),
        name: file.name,
      };
    });
    setDocuments((currentDocuments) => [...currentDocuments, ...documentsWithThumbnails]);
  };

  const inputRef = useRef(
    (() => {
      const element = document.createElement('input');
      element.multiple = true;
      element.type = 'file';
      element.accept = acceptedFileTypes?.join(',') || IMAGE_MIME_TYPES.join(',');
      element.addEventListener('change', () => {
        if (element.files && documents.length + element.files.length < maxNumberOfUploadFiles) {
          handleFileSelection(element.files);
          element.value = '';
        }
      });

      return element;
    })(),
  );

  const handleOpenFileClicker = () => {
    inputRef.current.click();
  };

  return (

{title}

       {documents.length > 0 ? (

           Add files

            {documents.map((doc) => {
              return (
                <BaseThumbnail
                  src={doc?.thumbnailURL}
                  key={doc.name}
                  deleteAction={() => {
                    deleteDocument(doc.name);
                  }}
                />
              );
            })}

          <Link onPress={handleOpenFileClicker}>
            Add photos
          </Link>

      ) : (

            Add files

          <EvidenceUploaderPanel
            labelText="upload files"
            openFilePicker={handleOpenFileClicker}
          />

       )}

  );
}


答:
Here's a slightly different option using dplyr::c_across() which gives you handy access to tidyselect semantics

library(tidyverse)

d <- structure(list(year = 2001:2004, max1 = c(10L, 103L, 21L, 27L), max2 = c(101L, 19L, 23L, 28L), max3 = c(87L, 88L, 89L, 91L)), class = "data.frame", row.names = c(NA, -4L))

d %>%
  rowwise() %>%
  mutate(max = max(c_across(starts_with("max"))), .keep = "unused") %>%
  ungroup()
#> # A tibble: 4 x 2
#>    year   max
#>   <int> <int>
#> 1  2001   101
#> 2  2002   103
#> 3  2003    89
#> 4  2004    91
```
<hr />
<h2>Benchmarking</h2>
<p>For what it's worth there are some performance differences which would probably only matter if your dataset is very large but worth noting. The solution from @Gregor Thomas is by far the fastest.</p>
<pre class="lang-r prettyprint-override"><code>library(microbenchmark)
microbenchmark(
# Dan Adams
c_across = d %>%
  rowwise() %>%
  mutate(max = max(c_across(starts_with("max"))), .keep = "unused") %>%
  ungroup(),

# MonJeanJean
max_all = d %>%
  rowwise() %>%
  mutate(MAX = max(max1, max2, max3)) %>%
  select(year, MAX),

# Greg
do.call = d %>%
  transmute(YEAR = year, MAX = do.call(pmax, unname(across(starts_with(
    "max"
  ))))),

# Gregor Thomas
apply = data.frame(
  year = d$year,
  max = apply(d[-1], 1, max))
)
#> Unit: microseconds
#>      expr    min      lq      mean   median       uq     max neval  cld
#>  c_across 6928.9 8123.20  9548.682  9187.00 10709.95 17595.6   100   c
#>   max_all 7890.5 9016.35 10473.327 10176.90 11366.65 16389.5   100    d
#>   do.call 3392.3 3976.20  4609.419  4473.55  4981.30  9282.5   100  b
#>     apply  349.1  470.20   567.896   535.05   670.70  1017.7   100 a
</code>```

Created on 2022-02-08 by the reprex package (v2.0.1)

Title: how to get max from multiple columns in R

Body:
INPUT:-
 year max1 max2 max3
2001   10  101   87
2002  103   19   88
2003   21   23   89
2004   27   28   91

OUTPUT:-

YEAR    MAX

2001     101

2002     103

2003      89

2004      91

Body:
Here's a slightly different option using dplyr::c_across() which gives you handy access to tidyselect semantics

library(tidyverse)

d <- structure(list(year = 2001:2004, max1 = c(10L, 103L, 21L, 27L), max2 = c(101L, 19L, 23L, 28L), max3 = c(87L, 88L, 89L, 91L)), class = "data.frame", row.names = c(NA, -4L))

d %>%
  rowwise() %>%
  mutate(max = max(c_across(starts_with("max"))), .keep = "unused") %>%
  ungroup()
#> # A tibble: 4 x 2
#>    year   max
#>   <int> <int>
#> 1  2001   101
#> 2  2002   103
#> 3  2003    89
#> 4  2004    91

Benchmarking

For what it's worth there are some performance differences which would probably only matter if your dataset is very large but worth noting. The solution from @Gregor Thomas is by far the fastest.

library(microbenchmark)
microbenchmark(
# Dan Adams
c_across = d %>%
  rowwise() %>%
  mutate(max = max(c_across(starts_with("max"))), .keep = "unused") %>%
  ungroup(),

# MonJeanJean
max_all = d %>%
  rowwise() %>%
  mutate(MAX = max(max1, max2, max3)) %>%
  select(year, MAX),

# Greg
do.call = d %>%
  transmute(YEAR = year, MAX = do.call(pmax, unname(across(starts_with(
    "max"
  ))))),

# Gregor Thomas
apply = data.frame(
  year = d$year,
  max = apply(d[-1], 1, max))
)
#> Unit: microseconds
#>      expr    min      lq      mean   median       uq     max neval  cld
#>  c_across 6928.9 8123.20  9548.682  9187.00 10709.95 17595.6   100   c
#>   max_all 7890.5 9016.35 10473.327 10176.90 11366.65 16389.5   100    d
#>   do.call 3392.3 3976.20  4609.419  4473.55  4981.30  9282.5   100  b
#>     apply  349.1  470.20   567.896   535.05   670.70  1017.7   100 a

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
Update value of associative array with corresponding value from second array in php
I have the following arrays in php:

Array1:

```<code>array(
    "0" => array(
        "book_title" => "Book Title 1",
        "date_added_wp" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "book review 1",
        "read" => "0",
        "selected" => "0"
    ),
    "1" => array(
        "book_title" => "Book Title 2",
        "date_added_wp" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "book review 2",
        "read" => "0",
        "selected" => "0"
    ),
    "2" => array(
        "book_title" => "Book Title 3",
        "date_added_wp" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "book review 3",
        "read" => "0",
        "selected" => "0"
    )
);
</code>```

Array2:

```<code>array(
    "0" => array(
        "book_title" => "Book Title 1",
        "read" => "0",
        "selected" => "1"
    ),
    "1" => array(
        "book_title" => "Book Title 2",
        "read" => "1",
        "selected" => "1"
    )
);
</code>```

I need to get the values of "read" and "selected" from the second array based on matching "book_title" field as follows:

Result:

```<code> array(
    "0" => array(
        "book_title" => "Book Title 1",
        "date_added" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "review text 1",
        "read" => "0",
        "selected" => "1"
    ),
    "1" => array(
        "book_title" => "Book Title 2",
        "date_added" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "review text 2",
        "read" => "1",
        "selected" => "1"
    ),
    "2" => array(
        "book_title" => "Book Title 3",
        "date_added" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "review text 3",
        "read" => "0",
        "selected" => "0"
    )
);
</code>```

It is that I can remove the "read" and "selected" fields from Array1 but, it will have to be added back to the Result as a new field.
I did try array_merge() as below:

```<code>$result = [];
        foreach (array_merge($Array1, $Array2) as $row) {
            $result[$row->book_title] = ($result[$row->book_title] ?? []) + $row;
        }
</code>```

And, a few other iterations too, just can't seem to work this out. Any help is welcome.

答:
Try this code -</p>
```<code> foreach($Array2 as $k=>$v){
     if($Array2[$k]['book_title'] == $Array1[$k]['book_title']){
         $Array1[$k]['read'] = $Array2[$k]['read'];
         $Array1[$k]['selected'] = $Array2[$k]['selected'];
     }
 }
 echo "```";
 print_r($Array1);
</code>```

Body:
I have the following arrays in php:

Array1:

array(
    "0" => array(
        "book_title" => "Book Title 1",
        "date_added_wp" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "book review 1",
        "read" => "0",
        "selected" => "0"
    ),
    "1" => array(
        "book_title" => "Book Title 2",
        "date_added_wp" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "book review 2",
        "read" => "0",
        "selected" => "0"
    ),
    "2" => array(
        "book_title" => "Book Title 3",
        "date_added_wp" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "book review 3",
        "read" => "0",
        "selected" => "0"
    )
);

Array2:

array(
    "0" => array(
        "book_title" => "Book Title 1",
        "read" => "0",
        "selected" => "1"
    ),
    "1" => array(
        "book_title" => "Book Title 2",
        "read" => "1",
        "selected" => "1"
    )
);

I need to get the values of "read" and "selected" from the second array based on matching "book_title" field as follows:

Result:

 array(
    "0" => array(
        "book_title" => "Book Title 1",
        "date_added" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "review text 1",
        "read" => "0",
        "selected" => "1"
    ),
    "1" => array(
        "book_title" => "Book Title 2",
        "date_added" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "review text 2",
        "read" => "1",
        "selected" => "1"
    ),
    "2" => array(
        "book_title" => "Book Title 3",
        "date_added" => "2022-01-31",
        "author" => "xxx",
        "book_review" => "review text 3",
        "read" => "0",
        "selected" => "0"
    )
);

It is that I can remove the "read" and "selected" fields from Array1 but, it will have to be added back to the Result as a new field.
I did try array_merge() as below:

$result = [];
        foreach (array_merge($Array1, $Array2) as $row) {
            $result[$row->book_title] = ($result[$row->book_title] ?? []) + $row;
        }

And, a few other iterations too, just can't seem to work this out. Any help is welcome.

Body:
Try this code -

 foreach($Array2 as $k=>$v){
     if($Array2[$k]['book_title'] == $Array1[$k]['book_title']){
         $Array1[$k]['read'] = $Array2[$k]['read'];
         $Array1[$k]['selected'] = $Array2[$k]['selected'];
     }
 }
 echo "<pre>";
 print_r($Array1);


问:
Getting all group names in signalr
ok so I have this code

```<code>var c = GlobalHost.ConnectionManager.GetHubContext<SomeHubClass>().Clients;
</code>```

now from this the Clients returns an IHubConext that has IHubConnectionContext that has an IGroupManager Groups. now is there anyway to get all the group names from this? Is this even possible with the signalR interface or do I have to track all the groups for each hub myself?

答:
You CAN ACTUALLY GET all group names using reflection (because all fields that we need are private) like I did, also here is how I dug it:
IGroupManager -> _lifetimeManager -> _groups -> _groups</p>
```<code>IGroupManager groupManager = signalRHubContext.Groups;

object lifetimeManager = groupManager.GetType().GetRuntimeFields()
    .Single(fi => fi.Name == "_lifetimeManager")
    .GetValue(groupManager);

object groupsObject = lifetimeManager.GetType().GetRuntimeFields()
    .Single(fi => fi.Name == "_groups")
    .GetValue(lifetimeManager);

IDictionary groupsDictionary = groupsObject.GetType().GetRuntimeFields()
    .Single(fi => fi.Name == "_groups")
    .GetValue(groupsObject) as IDictionary;

List<string> groupNames = groupsDictionary.Keys.Cast<string>().ToList();
</code>```

Title: Getting all group names in signalr

Body:
ok so I have this code

var c = GlobalHost.ConnectionManager.GetHubContext<SomeHubClass>().Clients;

now from this the Clients returns an IHubConext that has IHubConnectionContext that has an IGroupManager Groups. now is there anyway to get all the group names from this? Is this even possible with the signalR interface or do I have to track all the groups for each hub myself?

Body:
You CAN ACTUALLY GET all group names using reflection (because all fields that we need are private) like I did, also here is how I dug it:
IGroupManager -> _lifetimeManager -> _groups -> _groups

IGroupManager groupManager = signalRHubContext.Groups;

object lifetimeManager = groupManager.GetType().GetRuntimeFields()
    .Single(fi => fi.Name == "_lifetimeManager")
    .GetValue(groupManager);

object groupsObject = lifetimeManager.GetType().GetRuntimeFields()
    .Single(fi => fi.Name == "_groups")
    .GetValue(lifetimeManager);

IDictionary groupsDictionary = groupsObject.GetType().GetRuntimeFields()
    .Single(fi => fi.Name == "_groups")
    .GetValue(groupsObject) as IDictionary;

List<string> groupNames = groupsDictionary.Keys.Cast<string>().ToList();


问:
Using single cell in loop as trigger to to copy multiple ranges VBA
The macro is working with hard coded inputs but I need loops for debugging and future growth.  I don't know the best way to set this up.

Range("b3:b8:) are the cells I would like to loop over.

If cell.value = 1 then

Set var1 = range("a3:aq3")  (* This range always has the same row number as cell in loop*)

Set var2 = range("a9:aq9")  (*This range always 6 greater than row of cell in loop.)

End if

Next cell
Thanks

答:
Loop Through Rows of a Range

```<code>Option Explicit

Sub LoopThroughRows()

    Const srgAddress As String = "A3:AQ8"
    Const scCol As Long = 2
    Const sCriteria As String = "1"

    Dim sws As Worksheet: Set sws = ActiveSheet ' improve, e.g.:
    'Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    'Dim sws As Worksheet: Set sws = wb.Worksheets("Sheet1")

    Dim srg As Range: Set srg = sws.Range(srgAddress) ' last use of 'sws'
    Dim srCount As Long: srCount = srg.Rows.Count

    Dim srg1 As Range
    Dim srg2 As Range
    Dim sCell As Range
    Dim sr As Long

    For Each sCell In srg.Columns(scCol).Cells ' don't forget '.Cells'!
        sr = sr + 1 ' monitoring each range row (not worksheet row)
        If CStr(sCell.Value) = sCriteria Then ' also avoiding error values
            Set srg1 = srg.Rows(sr)
            Set srg2 = srg1.Offset(srCount)
            ' Continue... e.g.:
            Debug.Print sr, sCell.Address(0, 0), _
                srg1.Address(0, 0), srg2.Address(0, 0)
        Else ' not equal to sCriteria (usually do nothing)
            ' e.g.:
            Debug.Print sr, sCell.Address(0, 0), "Nope."
        End If
    Next sCell

End Sub
</code>```

Body:
Loop Through Rows of a Range

Option Explicit

Sub LoopThroughRows()

    Const srgAddress As String = "A3:AQ8"
    Const scCol As Long = 2
    Const sCriteria As String = "1"

    Dim sws As Worksheet: Set sws = ActiveSheet ' improve, e.g.:
    'Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    'Dim sws As Worksheet: Set sws = wb.Worksheets("Sheet1")

    Dim srg As Range: Set srg = sws.Range(srgAddress) ' last use of 'sws'
    Dim srCount As Long: srCount = srg.Rows.Count

    Dim srg1 As Range
    Dim srg2 As Range
    Dim sCell As Range
    Dim sr As Long

    For Each sCell In srg.Columns(scCol).Cells ' don't forget '.Cells'!
        sr = sr + 1 ' monitoring each range row (not worksheet row)
        If CStr(sCell.Value) = sCriteria Then ' also avoiding error values
            Set srg1 = srg.Rows(sr)
            Set srg2 = srg1.Offset(srCount)
            ' Continue... e.g.:
            Debug.Print sr, sCell.Address(0, 0), _
                srg1.Address(0, 0), srg2.Address(0, 0)
        Else ' not equal to sCriteria (usually do nothing)
            ' e.g.:
            Debug.Print sr, sCell.Address(0, 0), "Nope."
        End If
    Next sCell

End Sub


问:
How to get a Listenable from a Riverpod Provider?
I want to use go_router (https://pub.dev/packages/go_router#redirection) together with Riverpod.

I have a Provider and a StreamProvider, which I would like to combine into a Listenable so it can be used as the refreshListenable param of GoRouter.

I guess I need combine the Provider and a StreamProvider into some kind of Provider (how?).

What is the easiest way to create a Listenable from a Provider?

Edit: I understand that this 'negates' the point of Riverpod, but the app is all setup with Riverpod already and I would just like to add go_router.

答:
If you want to use the riverpod intensively, you can navigate with it directly, without go_router.
There is interesting issue here: river_pod issues 1122</p>


问:
Why does laravel resize my website on mobile?
I'm currently building my first site in laravel but i ran into an issue. When i inspect or view the site on mobile everything is much smaller than it should be. I inspected the font size and it says everything should be correct however everything is way smaller on the whole website than it should be.

Is there a hidden setting or something that i need to switch off? I Use tailwind for my css on all websites but this never happens on my wordpress sites.

答:
It's not laravel, it's your HTML that doesn't set the scale for mobile.
You need to set the device width and initial scale for the website to show at the same scale as browser

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

More here: https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag

Body:
It's not laravel, it's your HTML that doesn't set the scale for mobile.
You need to set the device width and initial scale for the website to show at the same scale as browser

<meta name="viewport" content="width=device-width, initial-scale=1">

More here: https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag


问:
How to replace only the leading zeros with NA?
How can I replace leading zeros with NAs? suppose I have the following example:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})
</code>```

the goal is to have the following result:

```<code> c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0
</code>```

but doing the following will not work since it will replace all and not just the leading zeros:

```<code>df[np.abs(df) < 1e-50] = np.nan
</code>```

答:
Similar to mozways' answer, but with assignment and cummin:

```<code>df[df.eq(0).cummin()] = pd.NA
</code>```

Demo:

```<code>>>> df
    c1   c2
0  0.0  1.0
1  0.0  1.0
2  1.0  1.0
3  0.0  0.0
>>> df.eq(0).cummin()
      c1     c2
0   True  False
1   True  False
2  False  False
3  False  False
>>> df[df.eq(0).cummin()] = pd.NA
>>> df
    c1   c2
0  NaN  1.0
1  NaN  1.0
2  1.0  1.0
3  0.0  0.0
</code>```

Body:
How can I replace leading zeros with NAs? suppose I have the following example:

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})

the goal is to have the following result:

 c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0

but doing the following will not work since it will replace all and not just the leading zeros:

df[np.abs(df) < 1e-50] = np.nan

Body:
Similar to mozways' answer, but with assignment and cummin:

df[df.eq(0).cummin()] = pd.NA

Demo:

>>> df
    c1   c2
0  0.0  1.0
1  0.0  1.0
2  1.0  1.0
3  0.0  0.0
>>> df.eq(0).cummin()
      c1     c2
0   True  False
1   True  False
2  False  False
3  False  False
>>> df[df.eq(0).cummin()] = pd.NA
>>> df
    c1   c2
0  NaN  1.0
1  NaN  1.0
2  1.0  1.0
3  0.0  0.0