问:
ROS Installation error ( ROS Kinetic in Ubuntu 16.04 )
The sequence of steps listed in http://wiki.ros.org/kinetic/Installat... have been followed. (Trying to install ROS kinetic in Ubuntu 16.04) Error when entering the following command :

```<code>$sudo apt-get install ros-kinetic-desktop-full
</code>```

Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation:

The following packages have unmet dependencies: ros-kinetic-desktop-full : Depends: ros-kinetic-desktop but it is not going to be installed Depends: ros-kinetic-perception but it is not going to be installed Depends: ros-kinetic-simulators but it is not going to be installed Depends: ros-kinetic-urdf-tutorial but it is not going to be installed E: Unable to correct problems, you have held broken packages.

答: If there is an update on your Linux, you should take it. And then follow the instructions in order. You may need to open new terminal windows after installation.</p>

Body:
The sequence of steps listed in http://wiki.ros.org/kinetic/Installat... have been followed. (Trying to install ROS kinetic in Ubuntu 16.04) Error when entering the following command :

$sudo apt-get install ros-kinetic-desktop-full

Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation:

The following packages have unmet dependencies: ros-kinetic-desktop-full : Depends: ros-kinetic-desktop but it is not going to be installed Depends: ros-kinetic-perception but it is not going to be installed Depends: ros-kinetic-simulators but it is not going to be installed Depends: ros-kinetic-urdf-tutorial but it is not going to be installed E: Unable to correct problems, you have held broken packages.


来源: stackexchange

问:
specific border + background color for button
I would to display a button with material ui who would look like this :

However, I manage only to do this for the moment :

Here is my current code. If you can tell me where I do block and how to achieve, I would really appreciate.

```<code>iconButton: {
    background:
        'linear-gradient(#222, #222),
        linear-gradient(to right, white, black, white) !important',
    borderRadius: '1rem !important',
    border: '4px solid transparent !important',
    backgroundRepeat: 'no-repeat !important',
    backgroundOrigin: 'padding-box, border-box !important',
    borderWidth: '10px !important',
    position: 'relative !important',

    '& ::before': {
        content: '""',
        position: 'absolute',
        top: '-5px',
        bottom: '-5px',
        left: '-5px',
        right: '-5px',
        border: '6px solid #222',
        borderRadius: '0.8rem',
    },
}
</code>```

Cheers everyone

答:
try adding inside and outside shadow to it. check https://www.cssmatic.com/box-shadow for more details.</p>
```<code>.shadow {
 -webkit-box-shadow: 0px 0px 3px 3px rgba(0,0,0,0.75) ,inset 0px 0px 3px 3px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 0px 3px 3px rgba(0,0,0,0.75), inset 0px 0px 3px 3px rgba(0,0,0,0.75);
box-shadow: 0px 0px 3px 3px rgba(0,0,0,0.75) ,inset 0px 0px 3px 3px rgba(0,0,0,0.75);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would to display a button with material ui who would look like this :

However, I manage only to do this for the moment :

Here is my current code. If you can tell me where I do block and how to achieve, I would really appreciate.

iconButton: {
    background:
        'linear-gradient(#222, #222),
        linear-gradient(to right, white, black, white) !important',
    borderRadius: '1rem !important',
    border: '4px solid transparent !important',
    backgroundRepeat: 'no-repeat !important',
    backgroundOrigin: 'padding-box, border-box !important',
    borderWidth: '10px !important',
    position: 'relative !important',

    '& ::before': {
        content: '""',
        position: 'absolute',
        top: '-5px',
        bottom: '-5px',
        left: '-5px',
        right: '-5px',
        border: '6px solid #222',
        borderRadius: '0.8rem',
    },
}

Cheers everyone

Body:
try adding inside and outside shadow to it. check https://www.cssmatic.com/box-shadow for more details.

.shadow {
 -webkit-box-shadow: 0px 0px 3px 3px rgba(0,0,0,0.75) ,inset 0px 0px 3px 3px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 0px 3px 3px rgba(0,0,0,0.75), inset 0px 0px 3px 3px rgba(0,0,0,0.75);
box-shadow: 0px 0px 3px 3px rgba(0,0,0,0.75) ,inset 0px 0px 3px 3px rgba(0,0,0,0.75);
}


问:
microprofile-config.properties as ConfigMap in Openliberty
This example shows how to use ConfigMaps with openliberty.

The problem to me is that you have to create a section for the env variable in each of kubernetes deployment.

```<code>containers:
      - name: system-container
        image: system:1.0-SNAPSHOT
        ports:
        - containerPort: 9080
        # Set the environment variables
        env:
        - name: CONTEXT_ROOT
          valueFrom:
            configMapKeyRef:
              name: sys-app-root
              key: contextRoot
        - name: SYSTEM_APP_USERNAME
          valueFrom:
            secretKeyRef:
              name: sys-app-credentials
              key: username
        - name: SYSTEM_APP_PASSWORD
          valueFrom:
            secretKeyRef:
              name: sys-app-credentials
              key: password
</code>```

Wouldn't it be just easier to upload microprofile-config.properties as

a ConfigMap and mount it as volume to the right location?

答:
Since you're using open-liberty I also think that creating your own config-map using microprofile-config.properties file will be good idea.

According to this documentation:

MicroProfile Config allows you to define configuration values, which are referred to as "config property" values, in a huge range of locations that are known as ConfigSources.

To load all the key pairs one can use envForm (just like @Gus suggested).

According to this documentation:
One can use envForm to define all of the ConfigMap's data as container environment variables.

The key from the ConfigMap becomes the environment variable name in the Pod.

Here is the example of use envForm:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - configMapRef:
          name: special-config
  restartPolicy: Never
```
<p>To load all the key pairs you need this scrap:</p>
<pre class="lang-yaml prettyprint-override"><code>      envFrom:
      - configMapRef:
          name: special-config
</code>```

See also this and this documentations.

Body:
This example shows how to use ConfigMaps with openliberty.

The problem to me is that you have to create a section for the env variable in each of kubernetes deployment.

containers:
      - name: system-container
        image: system:1.0-SNAPSHOT
        ports:
        - containerPort: 9080
        # Set the environment variables
        env:
        - name: CONTEXT_ROOT
          valueFrom:
            configMapKeyRef:
              name: sys-app-root
              key: contextRoot
        - name: SYSTEM_APP_USERNAME
          valueFrom:
            secretKeyRef:
              name: sys-app-credentials
              key: username
        - name: SYSTEM_APP_PASSWORD
          valueFrom:
            secretKeyRef:
              name: sys-app-credentials
              key: password

Wouldn't it be just easier to upload microprofile-config.properties as

a ConfigMap and mount it as volume to the right location?

Body:
Since you're using open-liberty I also think that creating your own config-map using microprofile-config.properties file will be good idea.

According to this documentation:

MicroProfile Config allows you to define configuration values, which are referred to as "config property" values, in a huge range of locations that are known as ConfigSources.

To load all the key pairs one can use envForm (just like @Gus suggested).

According to this documentation:
One can use envForm to define all of the ConfigMap's data as container environment variables.

The key from the ConfigMap becomes the environment variable name in the Pod.

<a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#:%7E:text=apiVersion%3A%20v1%0Akind%3A%20Pod%0Ametadata%3A%0A%20%20name%3A%20dapi%2Dtest%2Dpod%0Aspec%3A%0A%20%20containers%3A%0A%20%20%20%20%2D%20name%3A%20test%2Dcontainer%0A%20%20%20%20%20%20image%3A%20k8s.gcr.io/busybox%0A%20%20%20%20%20%20command%3A%20%5B%20%22/bin/sh%22%2C%20%22%2Dc%22%2C%20%22env%22%20%5D%0A%20%20%20%20%20%20envFrom%3A%0A%20%20%20%20%20%20%2D%20configMapRef%3A%0A%20%20%20%20%20%20%20%20%20%20name%3A%20special%2Dconfig%0A%20%20restartPolicy%3A%20Never" rel="nofollow noreferrer">Here is the example of use envForm:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - configMapRef:
          name: special-config
  restartPolicy: Never

To load all the key pairs you need this scrap:

      envFrom:
      - configMapRef:
          name: special-config

See also this and this documentations.


问:
Unzip and load keras model python google colab
I'm trying to load and unzip a Keras model simulataneously in Google CoLab and have tried a few combinations, I need something like

```<code>my_model = tf.keras.models.load_model(unzip '../content/my_folder/my_model.zip')
</code>```

but I get an invalid syntax error. How would I do this?

答:
Bash commands in Google Colab have to be preceded with !. The following line of code will unzip the my_model.zip to your current working directory, which is /content folder:

```<code>! unzip '../content/my_folder/my_model.zip'
</code>```

After that you can use the filename of the unzipped model to load it:

```<code>my_model = tf.keras.models.load_model('filename')
</code>```

Body:
I'm trying to load and unzip a Keras model simulataneously in Google CoLab and have tried a few combinations, I need something like

my_model = tf.keras.models.load_model(unzip '../content/my_folder/my_model.zip')

but I get an invalid syntax error. How would I do this?

Body:
Bash commands in Google Colab have to be preceded with !. The following line of code will unzip the my_model.zip to your current working directory, which is /content folder:

! unzip '../content/my_folder/my_model.zip'

After that you can use the filename of the unzipped model to load it:

my_model = tf.keras.models.load_model('filename')


问:
How can I make a CSS triangle the same height as it's parent element?
I'm trying to match this layout here:

I want one section with an equal split.  The left side has a background color and the other does not.  This issue I'm running into is that I want the triangle that is attached to the left side the SAME height as the element itself.  If I give it a set height then additional/newer content will throw this off.  How can I make this happen?  Here is what I'm working with:

```<code><section class='panel panel--standard u-bgColorSplitForm service-cta'>
    <div class="container">
        <?php if (have_rows('service_cta_group')) :
            while (have_rows('service_cta_group')) : the_row();
                $kicker = get_sub_field('kicker');
                $headline = get_sub_field('headline');
                $copy =  get_sub_field('copy');
                $form_header = get_sub_field('form_header');
                $form_id = get_sub_field('form_id');
        ?>
                <div class="grid">
                    <div class="grid__col--6 split-left">
                        <h4><?php echo $kicker; ?></h4>
                        <h3><?php echo $headline; ?></h3>
                        <p><?php echo $copy; ?></p>
                    </div>
                    <div class="grid__col--6">
                        <!-- Form will be added here -->
                    </div>
                </div>
    </div>
<?php endwhile;
        endif; ?>
</section>

.service-cta {
  position: relative;
  h4 {
    font-family: $font-stack-secondary;
    font-style: italic;
  }
  h3 {
    font-weight: 400;
  }
}

.split-left {
  position: relative;
  // triangle
  &::after {
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    top: 0;
    right: -100px;
    z-index: 1;
    border-top: 120px solid transparent;
    border-left: 75px solid $color-primary-tint;
    border-bottom: 120px solid transparent;
    transition: $transition-base;

    @include create-mq($md-width) {
      border-top: 150px solid transparent;
      border-left: 100px solid $color-primary-tint;
      border-bottom: 150px solid transparent;
    }
  }
}
</code>```

答:
It is messy trying to paint a triangle using borders.

Modern browsers have a clip-path property. We can use that to clip the chevron shape out of a pseudo element. If we use a polygon with % positioning of the vertices it will automatically adjust to any alteration in the dimensions of the element.

Here is a simple example in pure CSS:

.chevron {
  position: relative;
  width: 50vmin;
  height: 20vmin;
  border: solid 1px black;
  overflow: hidden;
  /* note this bg put in to stop 1 screen pixel white lines appearing at some zoom levels */
  background-image: linear-gradient(to right, red 0 50%, transparent 50% 100%);
}

.chevron::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: inline-block;
  background: red;
  clip-path: polygon(0 0, 50% 0, 60% 50%, 50% 100%, 0 100%);
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="chevron"></div></code>```

Body:
I'm trying to match this layout here:

I want one section with an equal split.  The left side has a background color and the other does not.  This issue I'm running into is that I want the triangle that is attached to the left side the SAME height as the element itself.  If I give it a set height then additional/newer content will throw this off.  How can I make this happen?  Here is what I'm working with:

        <?php if (have_rows('service_cta_group')) :
            while (have_rows('service_cta_group')) : the_row();
                $kicker = get_sub_field('kicker');
                $headline = get_sub_field('headline');
                $copy =  get_sub_field('copy');
                $form_header = get_sub_field('form_header');
                $form_id = get_sub_field('form_id');
        ?>

<?php echo $kicker; ?>

<?php echo $headline; ?>

<?php echo $copy; ?>

<?php endwhile;
        endif; ?>

.service-cta {
  position: relative;
  h4 {
    font-family: $font-stack-secondary;
    font-style: italic;
  }
  h3 {
    font-weight: 400;
  }
}

.split-left {
  position: relative;
  // triangle
  &::after {
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    top: 0;
    right: -100px;
    z-index: 1;
    border-top: 120px solid transparent;
    border-left: 75px solid $color-primary-tint;
    border-bottom: 120px solid transparent;
    transition: $transition-base;

    @include create-mq($md-width) {
      border-top: 150px solid transparent;
      border-left: 100px solid $color-primary-tint;
      border-bottom: 150px solid transparent;
    }
  }
}

Body:
It is messy trying to paint a triangle using borders.

Modern browsers have a clip-path property. We can use that to clip the chevron shape out of a pseudo element. If we use a polygon with % positioning of the vertices it will automatically adjust to any alteration in the dimensions of the element.

Here is a simple example in pure CSS:

.chevron {
  position: relative;
  width: 50vmin;
  height: 20vmin;
  border: solid 1px black;
  overflow: hidden;
  /* note this bg put in to stop 1 screen pixel white lines appearing at some zoom levels */
  background-image: linear-gradient(to right, red 0 50%, transparent 50% 100%);
}

.chevron::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: inline-block;
  background: red;
  clip-path: polygon(0 0, 50% 0, 60% 50%, 50% 100%, 0 100%);
  z-index: -1;
}

<div class="chevron"></div>


问:
Proper use of new/delete
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

```<code>void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}
</code>```

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?

答:
You only want to delete the object when you're completely finished using it. Once you delete it, you shouldn't attempt to refer to it again.

In a typical case, you just want to put objects themselves (rather that pointers to objects) in your vector. That will create a copy of the object when you add it to the vector, and automatically destroy the object when you erase it from the vector or the vector itself is destroyed.

ContentLicense: CC BY-SA 3.0

Title: Proper use of new/delete

Body:
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?


问:
boost::pool_allocator significantly slower than std::allocator
I am learning about memory pool, and trying to utilize boost::pool_allocator in my project. According to the documment, I made a small test about time cost:

template <typename Alloc>
void test()
{
    using namespace std::chrono;
    auto t0 = high_resolution_clock::now();
    for (int i = 0; i < 1000; ++i) {
        std::vector<int, Alloc> vec;
        for (int j = 0; j < 10000; ++j)
            vec.push_back(i + j);
    }
    auto t1 = high_resolution_clock::now();
    auto time_ms = duration<double>(t1 - t0).count() * 1e3;
    cout << "time cost: " << time_ms << " ms" << endl;
}

int main()
{
    test<std::allocator<int>>();
    test<boost::pool_allocator<int>>();
}
```
<p>And the result is:</p>
```time cost: 3.97602 ms
time cost: 91.3943 ms
```

The Boost doc says:

Pools are generally used when there is a lot of allocation and deallocation of small objects.

So I expect boost::pool_allocator cost less time than std::allocator in the code above, but the test result shows it's much worse.

Am I using boost::pool_allocator wrong? In what situation can I obtain a speedup by using memory pool (or just Boost pool/pool_allocator)?

答:
For reference:

```<code>template <typename T,
    typename UserAllocator = default_user_allocator_new_delete,
    typename Mutex = details::pool::default_mutex,
    unsigned NextSize = 32,
    unsigned MaxSize = 0>
class pool_allocator;
</code>```

I thought maybe the locking was to blame. Also, there could be better hinting.

Let's test! Live On Compiler Explorer

```<code>#include <boost/core/demangle.hpp>
#include <boost/pool/pool_alloc.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>

using namespace std::chrono_literals;
auto static now = std::chrono::high_resolution_clock::now;

template <typename Alloc> void test(int run, Alloc alloc = {}) {
    auto load = [=](bool RESERVE, unsigned ITERATIONS = 1'000, unsigned SIZE = 10'000) {
        for (unsigned i = 0; i < ITERATIONS; ++i) {
            std::vector<int, Alloc> vec(alloc);
            if (RESERVE)
                vec.reserve(SIZE);
            for (unsigned j = 0; j < SIZE; ++j)
                vec.push_back(i + j);
        }
    };

    auto lap_time = [t0 = now()]() mutable {
        return now() - std::exchange(t0, now());
    };

    load(false); auto without_reserve = lap_time() / 1.0ms;
    load(true);  auto with_reserve    = lap_time() / 1.0ms;

    std::cout << "run " << run                                             //
              << " naive:    " << std::setw(7) << without_reserve << "ms"  //
              << " reserved: " << std::setw(7) << with_reserve    << "ms"  //
              << "(" << boost::core::demangle(typeid(Alloc).name()) << ")" //
              << std::endl;
}

void run_tests(int run) {
    test<std::allocator<int>>(run);

    using NullMx    = boost::details::pool::null_mutex;
    using Mx        = boost::details::pool::default_mutex;
    using Malloc    = boost::default_user_allocator_malloc_free;
    using NewDelete = boost::default_user_allocator_new_delete;

    //
    // no hints
    //
    test<boost::pool_allocator<int, Malloc,    NullMx>>(run);
    test<boost::pool_allocator<int, NewDelete, NullMx>>(run);
    test<boost::pool_allocator<int, Malloc,    Mx>>(run);
    test<boost::pool_allocator<int, NewDelete, Mx>>(run);

    //
    // hinted
    //
    test<boost::pool_allocator<int, Malloc,    NullMx, 1'000, 0>>(run);
    test<boost::pool_allocator<int, NewDelete, NullMx, 1'000, 0>>(run);
    test<boost::pool_allocator<int, Malloc,    Mx,     1'000, 0>>(run);
    test<boost::pool_allocator<int, NewDelete, Mx,     1'000, 0>>(run);
}

int main()
{
    std::cout << std::fixed << std::setprecision(3);

    for (int run : {1,2,3}) {
        auto t0 = now();
        run_tests(run);
        std::cout << " -- Done (" << (now() - t0) / 1.ms << "ms)" << std::endl;
    }
}
</code>```

Compiler Explorer is showing some real inconsistent spikes; my own machine doesn't:

```<code>run 1 naive:      8.025ms reserved:   5.412ms(std::allocator<int>)
run 1 naive:     92.212ms reserved:  31.166ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:     93.466ms reserved:  29.901ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:     92.488ms reserved:  29.883ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 1 naive:     92.450ms reserved:  29.824ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 1 naive:     82.879ms reserved:  27.478ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:     82.775ms reserved:  28.187ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:     83.189ms reserved:  27.404ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 1 naive:     83.159ms reserved:  27.468ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (947.595ms)
run 2 naive:      8.007ms reserved:   5.543ms(std::allocator<int>)
run 2 naive:     92.225ms reserved:  29.882ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:     92.311ms reserved:  29.805ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:     92.601ms reserved:  29.873ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 2 naive:     92.421ms reserved:  30.028ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 2 naive:     83.028ms reserved:  27.493ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:     82.822ms reserved:  27.427ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:     83.230ms reserved:  27.493ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 2 naive:     83.104ms reserved:  27.466ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (944.958ms)
run 3 naive:      8.068ms reserved:   5.422ms(std::allocator<int>)
run 3 naive:     92.282ms reserved:  29.880ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:     92.064ms reserved:  29.960ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:     92.339ms reserved:  29.928ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 3 naive:     92.977ms reserved:  29.890ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 3 naive:     82.906ms reserved:  27.388ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:     82.784ms reserved:  27.585ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:     83.157ms reserved:  28.233ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 3 naive:     83.098ms reserved:  27.466ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (945.629ms)
</code>```

Still, clearly, always slower. Let's profile

Profiler

Comparing just standard allocator to boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>:

standard allocator causes 48k calls to new/delete, resulting in as many underlying calls to malloc/free

pool allocator shows vastly reduced numbers:

and for malloc/free:

So far so good! What is taking so much time then?

Where unordered_malloc inlines into a big number of lines from various Boost Pool headers. The top offenders are inlined from boost/pool/simple_segregated_storage.hpp: (second column are percentage of cost relative to parent):

Those lines are in try_malloc_n

```<code>template <typename SizeType>
void * simple_segregated_storage<SizeType>::try_malloc_n(
    void * & start, size_type n, const size_type partition_size)
{
  void * iter = nextof(start);
  while (--n != 0)
  {
    void * next = nextof(iter);
    if (next != static_cast<char *>(iter) + partition_size)
    {
      // next == 0 (end-of-list) or non-contiguous chunk found
      start = iter;
      return 0;
    }
    iter = next;
  }
  return iter;
}
</code>```

Which self-describes as:

The function attempts to find n contiguous chunks of size partition_size in the free list, starting at start. If it succeds, it returns the last chunk in that contiguous sequence, so that the sequence is known by [start, {retval}] If it fails, it does do either because it's at the end of the free list or hits a non-contiguous chunk. In either case, it will return 0, and set start to the last considered chunk. You are at the end of the free list if nextof(start) == 0. Otherwise, start points to the last chunk in the contiguous sequence, and nextof(start) points to the first chunk in the next contiguous sequence (assuming an ordered free list).

It does appear, then that the chasing of free blocks on the segregated heap is too costly in this type of scenario after all. A little napkin calculation shows that try_malloc_n takes 99.75% of the higher-level unordered_malloc call we saw earlier.

SHOCK: Alternative Implementation?

During my investigations I found a number of defines that can be used to get more insight, e.g.:

```<code>#define NDEBUG
//#define BOOST_POOL_INSTRUMENT 1
//#define BOOST_POOL_VALIDATE 1
//#define BOOST_POOL_VALGRIND 1
</code>```

Now, I used VALIDATE/INSTRUMENT observing the expected effect (very verbose output and slight performance degradation).

From reading the name/code I would have expected BOOST_POOL_VALGRIND to similarly degrade performance (after all, it should probably do extra work to avoid false positive memory errors when running Valgrind, right?). Much to my surprise, defining it makes the whole thing run lightning fast: Live On Compiler Explorer

```<code>run 1 naive:      8.166ms reserved:   5.267ms(std::allocator<int>)
run 1 naive:      9.713ms reserved:   5.267ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:      8.853ms reserved:   5.226ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:      8.990ms reserved:   5.282ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 1 naive:      8.899ms reserved:   5.246ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 1 naive:      8.620ms reserved:   5.237ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:      8.622ms reserved:   5.247ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:      8.963ms reserved:   5.257ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 1 naive:      8.990ms reserved:   5.271ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (127.276ms)
run 2 naive:      7.965ms reserved:   5.208ms(std::allocator<int>)
run 2 naive:      8.503ms reserved:   5.236ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:      8.809ms reserved:   5.254ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:      8.954ms reserved:   5.278ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 2 naive:      8.878ms reserved:   5.279ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 2 naive:      8.694ms reserved:   5.243ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:      8.661ms reserved:   5.249ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:      8.920ms reserved:   5.248ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 2 naive:      8.952ms reserved:   5.261ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (125.680ms)
run 3 naive:      7.949ms reserved:   5.221ms(std::allocator<int>)
run 3 naive:      8.498ms reserved:   5.238ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:      8.813ms reserved:   5.230ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:      9.033ms reserved:   5.279ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 3 naive:      8.909ms reserved:   5.252ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 3 naive:      8.605ms reserved:   5.244ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:      8.623ms reserved:   5.246ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:      8.918ms reserved:   5.247ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 3 naive:      8.969ms reserved:   5.268ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
</code>```

Sadly looking at the details confirms that it is cheating by delegating to standard library direclty (while adding some overhead with sets of free_list/used_list addresses).

Summary

Yes, the standard pool/simple_segregated_storage implementation performs badly under this load. Whether or not this is actually a bug I cannot tell with certainty, but it sure seems like it, going by the documentation (that you mentioned as well).

Body:
I am learning about memory pool, and trying to utilize boost::pool_allocator in my project. According to the documment, I made a small test about time cost:

template <typename Alloc>
void test()
{
    using namespace std::chrono;
    auto t0 = high_resolution_clock::now();
    for (int i = 0; i < 1000; ++i) {
        std::vector<int, Alloc> vec;
        for (int j = 0; j < 10000; ++j)
            vec.push_back(i + j);
    }
    auto t1 = high_resolution_clock::now();
    auto time_ms = duration<double>(t1 - t0).count() * 1e3;
    cout << "time cost: " << time_ms << " ms" << endl;
}

int main()
{
    test<std::allocator<int>>();
    test<boost::pool_allocator<int>>();
}

And the result is:

time cost: 3.97602 ms
time cost: 91.3943 ms

The Boost doc says:

Pools are generally used when there is a lot of allocation and deallocation of small objects.

So I expect boost::pool_allocator cost less time than std::allocator in the code above, but the test result shows it's much worse.

Am I using boost::pool_allocator wrong? In what situation can I obtain a speedup by using memory pool (or just Boost pool/pool_allocator)?

Body:
For reference:

template <typename T,
    typename UserAllocator = default_user_allocator_new_delete,
    typename Mutex = details::pool::default_mutex,
    unsigned NextSize = 32,
    unsigned MaxSize = 0>
class pool_allocator;

I thought maybe the locking was to blame. Also, there could be better hinting.

Let's test! Live On Compiler Explorer

#include <boost/core/demangle.hpp>
#include <boost/pool/pool_alloc.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>

using namespace std::chrono_literals;
auto static now = std::chrono::high_resolution_clock::now;

template <typename Alloc> void test(int run, Alloc alloc = {}) {
    auto load = [=](bool RESERVE, unsigned ITERATIONS = 1'000, unsigned SIZE = 10'000) {
        for (unsigned i = 0; i < ITERATIONS; ++i) {
            std::vector<int, Alloc> vec(alloc);
            if (RESERVE)
                vec.reserve(SIZE);
            for (unsigned j = 0; j < SIZE; ++j)
                vec.push_back(i + j);
        }
    };

    auto lap_time = [t0 = now()]() mutable {
        return now() - std::exchange(t0, now());
    };

    load(false); auto without_reserve = lap_time() / 1.0ms;
    load(true);  auto with_reserve    = lap_time() / 1.0ms;

    std::cout << "run " << run                                             //
              << " naive:    " << std::setw(7) << without_reserve << "ms"  //
              << " reserved: " << std::setw(7) << with_reserve    << "ms"  //
              << "(" << boost::core::demangle(typeid(Alloc).name()) << ")" //
              << std::endl;
}

void run_tests(int run) {
    test<std::allocator<int>>(run);

    using NullMx    = boost::details::pool::null_mutex;
    using Mx        = boost::details::pool::default_mutex;
    using Malloc    = boost::default_user_allocator_malloc_free;
    using NewDelete = boost::default_user_allocator_new_delete;

    //
    // no hints
    //
    test<boost::pool_allocator<int, Malloc,    NullMx>>(run);
    test<boost::pool_allocator<int, NewDelete, NullMx>>(run);
    test<boost::pool_allocator<int, Malloc,    Mx>>(run);
    test<boost::pool_allocator<int, NewDelete, Mx>>(run);

    //
    // hinted
    //
    test<boost::pool_allocator<int, Malloc,    NullMx, 1'000, 0>>(run);
    test<boost::pool_allocator<int, NewDelete, NullMx, 1'000, 0>>(run);
    test<boost::pool_allocator<int, Malloc,    Mx,     1'000, 0>>(run);
    test<boost::pool_allocator<int, NewDelete, Mx,     1'000, 0>>(run);
}

int main()
{
    std::cout << std::fixed << std::setprecision(3);

    for (int run : {1,2,3}) {
        auto t0 = now();
        run_tests(run);
        std::cout << " -- Done (" << (now() - t0) / 1.ms << "ms)" << std::endl;
    }
}

Compiler Explorer is showing some real inconsistent spikes; my own machine doesn't:

run 1 naive:      8.025ms reserved:   5.412ms(std::allocator<int>)
run 1 naive:     92.212ms reserved:  31.166ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:     93.466ms reserved:  29.901ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:     92.488ms reserved:  29.883ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 1 naive:     92.450ms reserved:  29.824ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 1 naive:     82.879ms reserved:  27.478ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:     82.775ms reserved:  28.187ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:     83.189ms reserved:  27.404ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 1 naive:     83.159ms reserved:  27.468ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (947.595ms)
run 2 naive:      8.007ms reserved:   5.543ms(std::allocator<int>)
run 2 naive:     92.225ms reserved:  29.882ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:     92.311ms reserved:  29.805ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:     92.601ms reserved:  29.873ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 2 naive:     92.421ms reserved:  30.028ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 2 naive:     83.028ms reserved:  27.493ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:     82.822ms reserved:  27.427ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:     83.230ms reserved:  27.493ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 2 naive:     83.104ms reserved:  27.466ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (944.958ms)
run 3 naive:      8.068ms reserved:   5.422ms(std::allocator<int>)
run 3 naive:     92.282ms reserved:  29.880ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:     92.064ms reserved:  29.960ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:     92.339ms reserved:  29.928ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 3 naive:     92.977ms reserved:  29.890ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 3 naive:     82.906ms reserved:  27.388ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:     82.784ms reserved:  27.585ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:     83.157ms reserved:  28.233ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 3 naive:     83.098ms reserved:  27.466ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (945.629ms)

Still, clearly, always slower. Let's profile

Profiler

Comparing just standard allocator to boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>:

standard allocator causes 48k calls to new/delete, resulting in as many underlying calls to malloc/free

pool allocator shows vastly reduced numbers:

and for malloc/free:

So far so good! What is taking so much time then?

Where unordered_malloc inlines into a big number of lines from various Boost Pool headers. The top offenders are inlined from boost/pool/simple_segregated_storage.hpp: (second column are percentage of cost relative to parent):

Those lines are in try_malloc_n

template <typename SizeType>
void * simple_segregated_storage<SizeType>::try_malloc_n(
    void * & start, size_type n, const size_type partition_size)
{
  void * iter = nextof(start);
  while (--n != 0)
  {
    void * next = nextof(iter);
    if (next != static_cast<char *>(iter) + partition_size)
    {
      // next == 0 (end-of-list) or non-contiguous chunk found
      start = iter;
      return 0;
    }
    iter = next;
  }
  return iter;
}

Which self-describes as:

The function attempts to find n contiguous chunks of size partition_size in the free list, starting at start. If it succeds, it returns the last chunk in that contiguous sequence, so that the sequence is known by [start, {retval}] If it fails, it does do either because it's at the end of the free list or hits a non-contiguous chunk. In either case, it will return 0, and set start to the last considered chunk. You are at the end of the free list if nextof(start) == 0. Otherwise, start points to the last chunk in the contiguous sequence, and nextof(start) points to the first chunk in the next contiguous sequence (assuming an ordered free list).

It does appear, then that the chasing of free blocks on the segregated heap is too costly in this type of scenario after all. A little napkin calculation shows that try_malloc_n takes 99.75% of the higher-level unordered_malloc call we saw earlier.

SHOCK: Alternative Implementation?

During my investigations I found a number of defines that can be used to get more insight, e.g.:

#define NDEBUG
//#define BOOST_POOL_INSTRUMENT 1
//#define BOOST_POOL_VALIDATE 1
//#define BOOST_POOL_VALGRIND 1

Now, I used VALIDATE/INSTRUMENT observing the expected effect (very verbose output and slight performance degradation).

From reading the name/code I would have expected BOOST_POOL_VALGRIND to similarly degrade performance (after all, it should probably do extra work to avoid false positive memory errors when running Valgrind, right?). Much to my surprise, defining it makes the whole thing run lightning fast: Live On Compiler Explorer

run 1 naive:      8.166ms reserved:   5.267ms(std::allocator<int>)
run 1 naive:      9.713ms reserved:   5.267ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:      8.853ms reserved:   5.226ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 1 naive:      8.990ms reserved:   5.282ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 1 naive:      8.899ms reserved:   5.246ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 1 naive:      8.620ms reserved:   5.237ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:      8.622ms reserved:   5.247ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 1 naive:      8.963ms reserved:   5.257ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 1 naive:      8.990ms reserved:   5.271ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (127.276ms)
run 2 naive:      7.965ms reserved:   5.208ms(std::allocator<int>)
run 2 naive:      8.503ms reserved:   5.236ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:      8.809ms reserved:   5.254ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 2 naive:      8.954ms reserved:   5.278ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 2 naive:      8.878ms reserved:   5.279ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 2 naive:      8.694ms reserved:   5.243ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:      8.661ms reserved:   5.249ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 2 naive:      8.920ms reserved:   5.248ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 2 naive:      8.952ms reserved:   5.261ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)
 -- Done (125.680ms)
run 3 naive:      7.949ms reserved:   5.221ms(std::allocator<int>)
run 3 naive:      8.498ms reserved:   5.238ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:      8.813ms reserved:   5.230ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 32u, 0u>)
run 3 naive:      9.033ms reserved:   5.279ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 32u, 0u>)
run 3 naive:      8.909ms reserved:   5.252ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 32u, 0u>)
run 3 naive:      8.605ms reserved:   5.244ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:      8.623ms reserved:   5.246ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, boost::details::pool::null_mutex, 1000u, 0u>)
run 3 naive:      8.918ms reserved:   5.247ms(boost::pool_allocator<int, boost::default_user_allocator_malloc_free, std::mutex, 1000u, 0u>)
run 3 naive:      8.969ms reserved:   5.268ms(boost::pool_allocator<int, boost::default_user_allocator_new_delete, std::mutex, 1000u, 0u>)

Sadly looking at the details confirms that it is cheating by delegating to standard library direclty (while adding some overhead with sets of free_list/used_list addresses).

Summary

Yes, the standard pool/simple_segregated_storage implementation performs badly under this load. Whether or not this is actually a bug I cannot tell with certainty, but it sure seems like it, going by the documentation (that you mentioned as well).


问:
Xcode intellisense meaning of letters in colored boxes like f,T,C,M,P,C,K,# etc
Recently, I have started using Xcode 4 for developing iOS apps.

In Xcode intellisense's autocomplete box, there are some letters in colored boxes before every suggestion. I know that they represent the property of the word we are typing like f,T,C,M,P,C,K,# etc.

Is there some kind of glossary available to find their quick meanings?

Meanings of f,C,T,# are understandable (function, class etc) but there are many others which I dont know. I assume these letters are standard across all IDEs like Visual Studio, Netbeans etc. Correct me if I am wrong.

Please suggest.

答:
I was searching for the meaning behind the "rM" icon. I finally found the answer (many thanks to kennytm):

The "rM" symbol represents a recursive method.


问:
tcpdump output is diffferent than pcap file
I am trying to understand what should be correct command in which i can get tcpdump command output same as pcap file have.

Current commmand : tcpdump  -s 0 -A -vvv -i eth0 port 5060

It's output is same as below :

E..G.M..@.
... .T.<......3`.

While on pcap same packate have below output :

```<code>I�b��))A�U�&E�{@a� ���O����S
</code>```

How can i get same output as showing in pcap file using tcpdump command ?

Thanks in advance for your help.

答:
As @Jboullianne surmised, you're probably just viewing the raw pcap file by printing it to a terminal window.

Pcap files are not text files, and the "terminal emulator" program that provides your terminal window is probably assuming the text it's seeing is UTF-8; not all sequences of raw bytes are valid UTF-8.  The � is probably the Unicode "REPLACEMENT CHARACTER", which the terminal is putting out as a replacement for invalid UTF-8 sequences.

And not everything in a pcap file is packet data, so some of those "weird characters" don't correspond to packet data.

Tcpdump has no option to print the bytes of the packet as UTF-8, so there's no way for the packet dump to show the packet data in that form.

Body:
I am trying to understand what should be correct command in which i can get tcpdump command output same as pcap file have.

Current commmand : tcpdump  -s 0 -A -vvv -i eth0 port 5060

It's output is same as below :

E..G.M..@.
... .T.<......3`.

While on pcap same packate have below output :

I�b��))A�U�&E�{@a� ���O����S

How can i get same output as showing in pcap file using tcpdump command ?

Thanks in advance for your help.


问:
I deleted erased all content from my emulator device in iOS, after this, i cant insert or read in my sqlite db
I erased my device content and settings and since that i cant insert nothing into my sqlite db.
My query to create the table runs and the tables are created ( i can see in the db browser) but my methos to insert and read just stoped working.

What can i do ?

I already tried to create antoher db with another name ans doesnt work.

```<code>enter cclass DBHelper {
init()
{
    db = openDatabase()
    createTable()
}

let dbPath: String = "prescriptionDB.sqlite"
var db:OpaquePointer?

func createTable() {
    let createTableString = "CREATE TABLE IF NOT EXISTS prescriptions(Id INTEGER PRIMARY KEY  AUTOINCREMENT ,name TEXT ,timeToTime TEXT ,firstTime TEXT);"
    var createTableStatement: OpaquePointer? = nil
    if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK
    {
        if sqlite3_step(createTableStatement) == SQLITE_DONE
        {
            print("prescriptions table created.")
        } else {
            print("prescriptions table could not be created.")
        }
    } else {
        print("CREATE TABLE statement could not be prepared.")
    }
    sqlite3_finalize(createTableStatement)
}

func insert(name: String, timeToTime: String, firstTime: String) {
    let insertStatementString = "INSERT INTO prescriptions (name, timeToTime, firstTime) VALUES (?, ?, ?);"
    var insertStatement: OpaquePointer? = nil

    if sqlite3_prepare_v2(db, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {
        sqlite3_bind_text(insertStatement, 1, (name as NSString).utf8String, -1, nil)
        sqlite3_bind_text(insertStatement, 2, (timeToTime as NSString).utf8String, -1, nil)
        sqlite3_bind_text(insertStatement, 3, (firstTime as NSString).utf8String, -1, nil)

        if sqlite3_step(insertStatement) == SQLITE_DONE {
            print("Successfully inserted row.")
        } else {
            print("Could not insert row.")
        }
    } else {
        print("INSERT statement could not be prepared.")
    }
    sqlite3_finalize(insertStatement)
}

func openDatabase() -> OpaquePointer? {
    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent(dbPath)
    var db: OpaquePointer? = nil
    if sqlite3_open(fileURL.path, &db) != SQLITE_OK
    {
        print("error opening database")
        return nil
    }
    else
    {
        print("Successfully opened connection to database at \(dbPath)")
        return db
    }
}

func read() -> [Prescription] {
    let queryStatementString = "SELECT * FROM prescriptions;"
    var queryStatement: OpaquePointer? = nil
    var psns : [Prescription] = []
    if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
        while sqlite3_step(queryStatement) == SQLITE_ROW {
            let id = sqlite3_column_int(queryStatement, 0)
            let name = String(describing: String(cString: sqlite3_column_text(queryStatement, 1)))
            let timeToTime = String(describing: String(cString: sqlite3_column_text(queryStatement, 2)))
            let firstTime = String(describing: String(cString: sqlite3_column_text(queryStatement, 3)))
            psns.append(Prescription(name: name, timeToTime: timeToTime, id: Int(id), firstTime: firstTime))
            print("Query Result:")
            print("\(id) | \(name) | \(timeToTime) | \(firstTime)")
        }
    } else {
        print("SELECT statement could not be prepared")
    }
    sqlite3_finalize(queryStatement)
    return psns
}ode here
</code>```

答: It was a mistake. The issues is beacuse my insert method war not beeing called in this version, so, when i tried to read from db, there is no rows, so, it returns false</p>

Body:
I erased my device content and settings and since that i cant insert nothing into my sqlite db.
My query to create the table runs and the tables are created ( i can see in the db browser) but my methos to insert and read just stoped working.

What can i do ?

I already tried to create antoher db with another name ans doesnt work.

enter cclass DBHelper {
init()
{
    db = openDatabase()
    createTable()
}

let dbPath: String = "prescriptionDB.sqlite"
var db:OpaquePointer?

func createTable() {
    let createTableString = "CREATE TABLE IF NOT EXISTS prescriptions(Id INTEGER PRIMARY KEY  AUTOINCREMENT ,name TEXT ,timeToTime TEXT ,firstTime TEXT);"
    var createTableStatement: OpaquePointer? = nil
    if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK
    {
        if sqlite3_step(createTableStatement) == SQLITE_DONE
        {
            print("prescriptions table created.")
        } else {
            print("prescriptions table could not be created.")
        }
    } else {
        print("CREATE TABLE statement could not be prepared.")
    }
    sqlite3_finalize(createTableStatement)
}

func insert(name: String, timeToTime: String, firstTime: String) {
    let insertStatementString = "INSERT INTO prescriptions (name, timeToTime, firstTime) VALUES (?, ?, ?);"
    var insertStatement: OpaquePointer? = nil

    if sqlite3_prepare_v2(db, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {
        sqlite3_bind_text(insertStatement, 1, (name as NSString).utf8String, -1, nil)
        sqlite3_bind_text(insertStatement, 2, (timeToTime as NSString).utf8String, -1, nil)
        sqlite3_bind_text(insertStatement, 3, (firstTime as NSString).utf8String, -1, nil)

        if sqlite3_step(insertStatement) == SQLITE_DONE {
            print("Successfully inserted row.")
        } else {
            print("Could not insert row.")
        }
    } else {
        print("INSERT statement could not be prepared.")
    }
    sqlite3_finalize(insertStatement)
}

func openDatabase() -> OpaquePointer? {
    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent(dbPath)
    var db: OpaquePointer? = nil
    if sqlite3_open(fileURL.path, &db) != SQLITE_OK
    {
        print("error opening database")
        return nil
    }
    else
    {
        print("Successfully opened connection to database at \(dbPath)")
        return db
    }
}

func read() -> [Prescription] {
    let queryStatementString = "SELECT * FROM prescriptions;"
    var queryStatement: OpaquePointer? = nil
    var psns : [Prescription] = []
    if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
        while sqlite3_step(queryStatement) == SQLITE_ROW {
            let id = sqlite3_column_int(queryStatement, 0)
            let name = String(describing: String(cString: sqlite3_column_text(queryStatement, 1)))
            let timeToTime = String(describing: String(cString: sqlite3_column_text(queryStatement, 2)))
            let firstTime = String(describing: String(cString: sqlite3_column_text(queryStatement, 3)))
            psns.append(Prescription(name: name, timeToTime: timeToTime, id: Int(id), firstTime: firstTime))
            print("Query Result:")
            print("\(id) | \(name) | \(timeToTime) | \(firstTime)")
        }
    } else {
        print("SELECT statement could not be prepared")
    }
    sqlite3_finalize(queryStatement)
    return psns
}ode here


问:
Rewrite ASP.NET page output
A little background: I am trying to create a lightweight cookieless database-backed user session using a highly striped down ASP.NET implementation. This site audience will be mobile users connecting via celluar networks, so the page sizes need to be very small. I am not using the .NET session, viewstate, etc. and most page contain very few if any server controls.

I want to be able to process the output of a page request so I can modify internal links in the response with my own session information. I have read that there was an ISAPI filter to allow cookieless sessions pre-ASP.NET. That is basically what I want to build, just inside the application.

Has anyone done anything like this? I'm already inheiriting the System.Web.UI.Page class for my page base for other reasons. It seems like I should be able to do something from here.

Thanks

答:
Look into using an HttpModule for this. You can process the entire response on the way out.

You might also be able to do something with a base class - perhaps go through all the server-side controls that might have links in them on the PreRenderComplete event. This wouldn't help you with HTML  tags, though.

OwnerDisplayName: Paul

ContentLicense: CC BY-SA 2.5

Title: Rewrite ASP.NET page output

Body:
Look into using an HttpModule for this. You can process the entire response on the way out.

You might also be able to do something with a base class - perhaps go through all the server-side controls that might have links in them on the PreRenderComplete event. This wouldn't help you with HTML <A> tags, though.

OwnerDisplayName: John Saunders


问:
SSIS: Passing record set into a Stored Proc
I'm using SSIS with SQL Server 2005, I want to pass a data set as a parameter into a sproc. Inside the sproc, I have to process the records and insert into some destination table.
Is there a direct way to do it in SSIS(passing data set as a parameter part)?
Or do I've to convert the table records into XML and then pass it as parameters..</p>

答:
I am not aware of any way to pass the entire data set into a stored proc (other than by converting to xml).

The alternative is to move your logic from your stored proc and set SSIS up to manage the destination logic.


问:
How to call function with generic params in typescript
I am trying to create something like this as below

```<code>export function f1(param1: string, param2: string) {
    console.log('Hello', param1, param2);
}

export function f2(param3: string) {
    console.log('world', param3);
}

interface Metadata {
    functionName: string;
    functionParams: any;
}

const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', {functionName: 'f1', functionParams: {param1: 'any', param2:'any1'}}],
    ['action2', {functionName: 'f2', functionParams: {param3: 'any2'}}]
])
</code>```

So basically I want to call f1 or f2 function after reading it through a testMap. The idea is to store all action and their mappings against a function and execute actions in one go instead of creating multiple if and else statements.

Can somebody help I can achieve this ?

答:
You can't reference and call a function by passing its name as a string (without doing some eval black magic that I cannot in good conscience recommend). Instead, you should pass the function itself:

export function f1(param1: string, param2: string) { }

export function f2(param3: string) { }

// Change your interface to accept a function instead of a string:
interface Metadata {
    invoke: (...args: any[]) => any;
    functionParams: any[];
}

// Pass f1 or f2 (the function references) instead of 'f1' or 'f2':
const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', { invoke: f1, functionParams: ['any', 'any1'] }],
    ['action2', { invoke: f2, functionParams: ['any2'] }]
])
```

Playground example

Body:
I am trying to create something like this as below

export function f1(param1: string, param2: string) {
    console.log('Hello', param1, param2);
}

export function f2(param3: string) {
    console.log('world', param3);
}

interface Metadata {
    functionName: string;
    functionParams: any;
}

const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', {functionName: 'f1', functionParams: {param1: 'any', param2:'any1'}}],
    ['action2', {functionName: 'f2', functionParams: {param3: 'any2'}}]
])

So basically I want to call f1 or f2 function after reading it through a testMap. The idea is to store all action and their mappings against a function and execute actions in one go instead of creating multiple if and else statements.

Can somebody help I can achieve this ?

Body:
You can't reference and call a function by passing its name as a string (without doing some eval black magic that I cannot in good conscience recommend). Instead, you should pass the function itself:

export function f1(param1: string, param2: string) { }

export function f2(param3: string) { }

// Change your interface to accept a function instead of a string:
interface Metadata {
    invoke: (...args: any[]) => any;
    functionParams: any[];
}

// Pass f1 or f2 (the function references) instead of 'f1' or 'f2':
const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', { invoke: f1, functionParams: ['any', 'any1'] }],
    ['action2', { invoke: f2, functionParams: ['any2'] }]
])

<a href="https://www.typescriptlang.org/play?target=99#code/GYVwdgxgLglg9mABMAjACgA4EMBOWC2KAXIgM5Q4xgDmANItnvgEwnmU0CUiA3gLAAoRMMQQEpOABsApgDpJcamgDkACWmSFy%20owIoduAs04BuQQF9Bg0JFgJkzTIfwBmNhSrVu-ISLFgJGXlFFQB3OBxJABNtBmcXUwsrAQB6FMQAYQALLBppRABPOBAcRCooaRxgLAh8qDhEGtqMKEbkcGh4JCpyaSwoxDhgNvZPIkFyyuraxABZaSh%20rEXeQREysAA3OABraRI0WSPcalISXIKAbQBdbgBeAD5GsAKzX2EbToQABWcz56u1zelgEgjSiF%20pFIyBQg1KwGYiDQUCy%20U%20diQOGkwEq0kg0lI3B6FX6g2GylQyjhiApzGU4wE-nIiAq5FmWAwJHZGAAPKMaPR5ososssE87ogwNJQnMOXyPAK5gslosHmhLmsRJdlDUMShYjwNts9iRUPR0V1fkx-tqLrEdS99ddEOZrrRNcJbV8wHT6IaqMb9g5zR0MVaCDaHQU6c7XYJbslwQBRAAe0ggIAqDOAESRTNalzABGkfvatktf3oAd2%20VdZJZBKg3O8HtE4ikcgUSmU1Z2nliRfwJZpoRgKLiTAWlTOsQtPz%20nFbvekhyOc7A4fwhOBgiAA" rel="nofollow noreferrer">Playground example


问:
Nexus Repository Manager stuck in 'Storage facet cleanup' loop
I've been stuck in this loop for a few days now. I've tried running different version of Nexus (3.37.0, 3.37.1, 3.37.2, 3.37.3) and restarting the deployment through OpenShift multiple times.

It was working normally for months until February 6th, then I lost access to the web console and my repository mirrors became inaccessible.

I've searched the site multiple times and haven't found anything that's worked so far.

Some of the nexus logs are below, but it has just repeated going from RUNNING to WAITING (OK) for days so I clipped them:

```<code>-------------------------------------------------

Started Sonatype Nexus OSS 3.37.3-02

-------------------------------------------------
2022-02-07 18:10:00,021+0000 INFO  [quartz-9-thread-1] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-07 18:10:00,041+0000 INFO  [quartz-9-thread-1] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)
2022-02-07 18:20:00,011+0000 INFO  [quartz-9-thread-2] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-07 18:20:00,018+0000 INFO  [quartz-9-thread-2] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)
2022-02-07 18:30:00,007+0000 INFO  [quartz-9-thread-3] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-07 18:30:00,013+0000 INFO  [quartz-9-thread-3] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)
...
...
...
2022-02-09 19:50:00,003+0000 INFO  [quartz-9-thread-20] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-09 19:50:00,008+0000 INFO  [quartz-9-thread-20] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)
</code>```

答: Okay, turns out my OpenShift service was only connecting to deployments with a particular name nexus-2 and the current deployment was nexus-3. I removed that filter, and I was able to access it again. Thanks to @rseddon for pointing out that this log was not in fact the problem, prompting me to look for the answer elsewhere.

Body:
I've been stuck in this loop for a few days now. I've tried running different version of Nexus (3.37.0, 3.37.1, 3.37.2, 3.37.3) and restarting the deployment through OpenShift multiple times.

It was working normally for months until February 6th, then I lost access to the web console and my repository mirrors became inaccessible.

I've searched the site multiple times and haven't found anything that's worked so far.

Some of the nexus logs are below, but it has just repeated going from RUNNING to WAITING (OK) for days so I clipped them:

-------------------------------------------------

Started Sonatype Nexus OSS 3.37.3-02

-------------------------------------------------
2022-02-07 18:10:00,021+0000 INFO  [quartz-9-thread-1] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-07 18:10:00,041+0000 INFO  [quartz-9-thread-1] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)
2022-02-07 18:20:00,011+0000 INFO  [quartz-9-thread-2] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-07 18:20:00,018+0000 INFO  [quartz-9-thread-2] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)
2022-02-07 18:30:00,007+0000 INFO  [quartz-9-thread-3] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-07 18:30:00,013+0000 INFO  [quartz-9-thread-3] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)
...
...
...
2022-02-09 19:50:00,003+0000 INFO  [quartz-9-thread-20] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change WAITING -> RUNNING
2022-02-09 19:50:00,008+0000 INFO  [quartz-9-thread-20] *SYSTEM org.sonatype.nexus.quartz.internal.task.QuartzTaskInfo - Task 'Storage facet cleanup' [repository.storage-facet-cleanup] state change RUNNING -> WAITING (OK)


答: C++ is not C# or Java or whatever.  You are using raw pointers, which you should probably not do.  When you delete the just-allocated object, it's gone and cannot be used anymore.  That you store a pointer to it in the vector that appears to persist beyond the function's scope is an error.</p>

Title: Proper use of new/delete


问:
Not retrieving .notConnectedToInternet URLSession
So I'm trying to get URLSession URLError.code .notConnectedToInternet but all I'm getting is Code(rawValue: -1020) when using URLSession when disconnecting from the internet.

```<code>URLSession.shared.dataTask(with: url) { data, _, error in
       if let error = error {
          print("error.code \((error as! URLError).code)")
          //prints - error.code Code(rawValue: -1020)

            if (error as! URLError).code == .notConnectedToInternet {
                print("no internet")
                //doesn't print
                return
            }
        }
</code>```

答:
error code -1020 means dataNotAllowed. It means the connection failed because data use isn’t currently allowed on the device.

What you are trying to catch notConnectedToInternet error code -1009 means connection failed because the device isn’t connected to the internet.

So notConnectedToInternet is not same as dataNotAllowed. In this case check your device settings.

Body:
So I'm trying to get URLSession URLError.code .notConnectedToInternet but all I'm getting is Code(rawValue: -1020) when using URLSession when disconnecting from the internet.

URLSession.shared.dataTask(with: url) { data, _, error in
       if let error = error {
          print("error.code \((error as! URLError).code)")
          //prints - error.code Code(rawValue: -1020)

            if (error as! URLError).code == .notConnectedToInternet {
                print("no internet")
                //doesn't print
                return
            }
        }


问:
I am trying to filter images by specific likes which I have entered by I am not able to figure it how
I am trying to filter images by specific likes which I have entered by I am not able to figure it how.

I have 2 main classes and first one is InputSlider as below:

```<code>import * as React from "react";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid";
import Typography from "@mui/material/Typography";
import Slider from "@mui/material/Slider";
import MuiInput from "@mui/material/Input";
import ThumbDownIcon from "@mui/icons-material/ThumbDown";
import ThumbUpIcon from "@mui/icons-material/ThumbUp";

const Input = styled(MuiInput)`
  width: 42px;
`;

const InputSlider = () => {
  const [value, setValue] = React.useState(500);

  const handleSliderChange = (event, newValue) => {
    setValue(newValue);
  };

  const handleInputChange = (event) => {
    setValue(event.target.value === "" ? "" : Number(event.target.value));
  };

  const handleBlur = () => {
    if (value < 0) {
      setValue(0);
    } else if (value > 500) {
      setValue(500);
    }
  };
  let likeCountByFilter = { value };
  console.log(likeCountByFilter);

  return (
    <Box sx={{ width: 800 }}>
      <Typography id="input-slider" textAlign={"center"}>
        Likes
      </Typography>
      <Grid container spacing={2} alignItems="center">
        <Grid item>
          <ThumbDownIcon />
        </Grid>
        <Grid item xs>
          <Slider
            value={typeof value === "number" ? value : 0}
            onChange={handleSliderChange}
            aria-labelledby="input-slider"
          />
        </Grid>
        <Grid item>
          <ThumbUpIcon />
        </Grid>
        <Grid item>
          <Input
            value={value}
            size="small"
            onChange={handleInputChange}
            onBlur={handleBlur}
            inputProps={{
              step: 1,
              min: 0,
              max: 10000,
              type: "number",
              "aria-labelledby": "input-slider",
            }}
          />
        </Grid>
      </Grid>
    </Box>
  );
};

export default InputSlider;
</code>```

and Second one is:

```<code>import React, { useState } from "react";
import ImageList from "@mui/material/ImageList";
import ImageListItem from "@mui/material/ImageListItem";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/icons-material/CheckBox";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import Favorite from "@mui/icons-material/Favorite";
import FavoriteBorder from "@mui/icons-material/Favorite";
import InputSlider from "./InputSlider";
import { itemData } from "./itemData";

const NewImageCorouse = ({ photos }) => {
  return (
    <ImageList cols={3}>
      {photos.map((item) => (
        <ImageListItem key={item.img}>
          <img
            src={`${item.img}?w=164&h=164&fit=crop&auto=format`}
            srcSet={`${item.img}?w=164&h=164&fit=crop&auto=format&dpr=2 2x`}
            alt={item.title}
            loading="lazy"
          />
          <div style={{}}>
            <FormControlLabel
              control={
                <FavoriteBorder icon={<FavoriteBorder />} name="checkedH" />
              }
              label={`${item.likeCount} Likes`}
            />
          </div>
        </ImageListItem>
      ))}
    </ImageList>
  );
};

export default NewImageCorouse;
</code>```

I have data in itemData.js and there I have likeCount for each object.
I am trying to solve how I can only show the photos when I try to input like count in Slider it will show only photos which have likes only more than input amount.

```<code>export const itemData = [
  {
    id: 1,
    img: "https://images.unsplash.com/photo-1551963831-b3b1ca40c98e",
    title: "Breakfast",
    likeCount: 10,
  },
  {
    id: 2,
    img: "https://images.unsplash.com/photo-1551782450-a2132b4ba21d",
    title: "Burger",
    likeCount: 15,
  },
  {
    id: 3,
    img: "https://images.unsplash.com/photo-1522770179533-24471fcdba45",
    title: "Camera",
    likeCount: 28,
  },
  {
    id: 4,
    img: "https://images.unsplash.com/photo-1444418776041-9c7e33cc5a9c",
    title: "Coffee",
    likeCount: 187,
  },
  {
    id: 5,
    img: "https://images.unsplash.com/photo-1533827432537-70133748f5c8",
    title: "Hats",
    likeCount: 74,
  },
  {
    id: 6,
    img: "https://images.unsplash.com/photo-1558642452-9d2a7deb7f62",
    title: "Honey",
    likeCount: 898,
  },
  {
    id: 7,
    img: "https://images.unsplash.com/photo-1516802273409-68526ee1bdd6",
    title: "Basketball",
    likeCount: 127,
  },
  {
    id: 8,
    img: "https://images.unsplash.com/photo-1518756131217-31eb79b20e8f",
    title: "Fern",
    likeCount: 3,
  },
  {
    id: 9,
    img: "https://images.unsplash.com/photo-1597645587822-e99fa5d45d25",
    title: "Mushrooms",
    likeCount: 54,
  },
  {
    id: 10,
    img: "https://images.unsplash.com/photo-1567306301408-9b74779a11af",
    title: "Tomato basil",
    likeCount: 14,
  },
  {
    id: 11,
    img: "https://images.unsplash.com/photo-1471357674240-e1a485acb3e1",
    title: "Sea star",
    likeCount: 28,
  },
  {
    id: 12,
    img: "https://images.unsplash.com/photo-1589118949245-7d38baf380d6",
    title: "Bike",
    likeCount: 247,
  },
];
</code>```

答:
You need a way to pass back out the slider value, and then filter the photos array prop that is passed to NewImageCorouse.

Use an useEffect hook to call an onChange handler for the InputSlider.

```<code>const InputSlider = ({ onChange = () => {} }) => {
  const [value, setValue] = React.useState(500);

  React.useEffect(() => {
    onChange(value);
  }, [onChange, value]);

  const handleSliderChange = (event, newValue) => {
    setValue(newValue);
  };

  const handleInputChange = (event) => {
    setValue(event.target.value === "" ? "" : Number(event.target.value));
  };

  const handleBlur = () => {
    if (value < 0) {
      setValue(0);
    } else if (value > 500) {
      setValue(500);
    }
  };

  return (
    <Box sx={{ width: 800 }}>
      <Typography id="input-slider" textAlign={"center"}>
        Likes
      </Typography>
      <Grid container spacing={2} alignItems="center">
        <Grid item>
          <ThumbDownIcon />
        </Grid>
        <Grid item xs>
          <Slider
            min={0}
            max={1000}
            step={1}
            value={typeof value === "number" ? value : 0}
            onChange={handleSliderChange}
            aria-labelledby="input-slider"
          />
        </Grid>
        <Grid item>
          <ThumbUpIcon />
        </Grid>
        <Grid item>
          <Input
            value={value}
            size="small"
            onChange={handleInputChange}
            onBlur={handleBlur}
            inputProps={{
              step: 1,
              min: 0,
              max: 1000,
              type: "number",
              "aria-labelledby": "input-slider"
            }}
          />
        </Grid>
      </Grid>
    </Box>
  );
};
</code>```

Filter the itemData array that is passed as photos prop by the saved "likes" value.

```<code>function App() {
  const [likes, setLikes] = React.useState(0);

  return (
    <div>
      <InputSlider onChange={setLikes} />

      <NewImageCorouse
        photos={itemData.filter(({ likeCount }) => likeCount > likes)}
      />
    </div>
  );
}
</code>```

Body:
I am trying to filter images by specific likes which I have entered by I am not able to figure it how.

I have 2 main classes and first one is InputSlider as below:

import * as React from "react";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid";
import Typography from "@mui/material/Typography";
import Slider from "@mui/material/Slider";
import MuiInput from "@mui/material/Input";
import ThumbDownIcon from "@mui/icons-material/ThumbDown";
import ThumbUpIcon from "@mui/icons-material/ThumbUp";

const Input = styled(MuiInput)`
  width: 42px;
`;

const InputSlider = () => {
  const [value, setValue] = React.useState(500);

  const handleSliderChange = (event, newValue) => {
    setValue(newValue);
  };

  const handleInputChange = (event) => {
    setValue(event.target.value === "" ? "" : Number(event.target.value));
  };

  const handleBlur = () => {
    if (value < 0) {
      setValue(0);
    } else if (value > 500) {
      setValue(500);
    }
  };
  let likeCountByFilter = { value };
  console.log(likeCountByFilter);

  return (
    <Box sx={{ width: 800 }}>
      <Typography id="input-slider" textAlign={"center"}>
        Likes
      </Typography>
      <Grid container spacing={2} alignItems="center">
        <Grid item>
          <ThumbDownIcon />
        </Grid>
        <Grid item xs>
          <Slider
            value={typeof value === "number" ? value : 0}
            onChange={handleSliderChange}
            aria-labelledby="input-slider"
          />
        </Grid>
        <Grid item>
          <ThumbUpIcon />
        </Grid>
        <Grid item>
          <Input
            value={value}
            size="small"
            onChange={handleInputChange}
            onBlur={handleBlur}
            inputProps={{
              step: 1,
              min: 0,
              max: 10000,
              type: "number",
              "aria-labelledby": "input-slider",
            }}
          />
        </Grid>
      </Grid>
    </Box>
  );
};

export default InputSlider;

and Second one is:

import React, { useState } from "react";
import ImageList from "@mui/material/ImageList";
import ImageListItem from "@mui/material/ImageListItem";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/icons-material/CheckBox";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import Favorite from "@mui/icons-material/Favorite";
import FavoriteBorder from "@mui/icons-material/Favorite";
import InputSlider from "./InputSlider";
import { itemData } from "./itemData";

const NewImageCorouse = ({ photos }) => {
  return (
    <ImageList cols={3}>
      {photos.map((item) => (
        <ImageListItem key={item.img}>
          <img
            src={`${item.img}?w=164&h=164&fit=crop&auto=format`}
            srcSet={`${item.img}?w=164&h=164&fit=crop&auto=format&dpr=2 2x`}
            alt={item.title}
            loading="lazy"
          />

            <FormControlLabel
              control={
                <FavoriteBorder icon={<FavoriteBorder />} name="checkedH" />
              }
              label={`${item.likeCount} Likes`}
            />

        </ImageListItem>
      ))}
    </ImageList>
  );
};

export default NewImageCorouse;

I have data in itemData.js and there I have likeCount for each object.
I am trying to solve how I can only show the photos when I try to input like count in Slider it will show only photos which have likes only more than input amount.

export const itemData = [
  {
    id: 1,
    img: "https://images.unsplash.com/photo-1551963831-b3b1ca40c98e",
    title: "Breakfast",
    likeCount: 10,
  },
  {
    id: 2,
    img: "https://images.unsplash.com/photo-1551782450-a2132b4ba21d",
    title: "Burger",
    likeCount: 15,
  },
  {
    id: 3,
    img: "https://images.unsplash.com/photo-1522770179533-24471fcdba45",
    title: "Camera",
    likeCount: 28,
  },
  {
    id: 4,
    img: "https://images.unsplash.com/photo-1444418776041-9c7e33cc5a9c",
    title: "Coffee",
    likeCount: 187,
  },
  {
    id: 5,
    img: "https://images.unsplash.com/photo-1533827432537-70133748f5c8",
    title: "Hats",
    likeCount: 74,
  },
  {
    id: 6,
    img: "https://images.unsplash.com/photo-1558642452-9d2a7deb7f62",
    title: "Honey",
    likeCount: 898,
  },
  {
    id: 7,
    img: "https://images.unsplash.com/photo-1516802273409-68526ee1bdd6",
    title: "Basketball",
    likeCount: 127,
  },
  {
    id: 8,
    img: "https://images.unsplash.com/photo-1518756131217-31eb79b20e8f",
    title: "Fern",
    likeCount: 3,
  },
  {
    id: 9,
    img: "https://images.unsplash.com/photo-1597645587822-e99fa5d45d25",
    title: "Mushrooms",
    likeCount: 54,
  },
  {
    id: 10,
    img: "https://images.unsplash.com/photo-1567306301408-9b74779a11af",
    title: "Tomato basil",
    likeCount: 14,
  },
  {
    id: 11,
    img: "https://images.unsplash.com/photo-1471357674240-e1a485acb3e1",
    title: "Sea star",
    likeCount: 28,
  },
  {
    id: 12,
    img: "https://images.unsplash.com/photo-1589118949245-7d38baf380d6",
    title: "Bike",
    likeCount: 247,
  },
];

Body:
You need a way to pass back out the slider value, and then filter the photos array prop that is passed to NewImageCorouse.

Use an useEffect hook to call an onChange handler for the InputSlider.

const InputSlider = ({ onChange = () => {} }) => {
  const [value, setValue] = React.useState(500);

  React.useEffect(() => {
    onChange(value);
  }, [onChange, value]);

  const handleSliderChange = (event, newValue) => {
    setValue(newValue);
  };

  const handleInputChange = (event) => {
    setValue(event.target.value === "" ? "" : Number(event.target.value));
  };

  const handleBlur = () => {
    if (value < 0) {
      setValue(0);
    } else if (value > 500) {
      setValue(500);
    }
  };

  return (
    <Box sx={{ width: 800 }}>
      <Typography id="input-slider" textAlign={"center"}>
        Likes
      </Typography>
      <Grid container spacing={2} alignItems="center">
        <Grid item>
          <ThumbDownIcon />
        </Grid>
        <Grid item xs>
          <Slider
            min={0}
            max={1000}
            step={1}
            value={typeof value === "number" ? value : 0}
            onChange={handleSliderChange}
            aria-labelledby="input-slider"
          />
        </Grid>
        <Grid item>
          <ThumbUpIcon />
        </Grid>
        <Grid item>
          <Input
            value={value}
            size="small"
            onChange={handleInputChange}
            onBlur={handleBlur}
            inputProps={{
              step: 1,
              min: 0,
              max: 1000,
              type: "number",
              "aria-labelledby": "input-slider"
            }}
          />
        </Grid>
      </Grid>
    </Box>
  );
};

Filter the itemData array that is passed as photos prop by the saved "likes" value.

function App() {
  const [likes, setLikes] = React.useState(0);

  return (
    <div>
      <InputSlider onChange={setLikes} />

      <NewImageCorouse
        photos={itemData.filter(({ likeCount }) => likeCount > likes)}
      />
    </div>
  );
}


问:
Primeng p-table sorting is not sorting data
I'm creating some p-table and I tried to add sorting but it's not working. Sorting icon is visible, animation of icon works, data in table is rendering but it is not sorting on header click. I found Primeng documentation and I think I did everything that I should. I've tried a few solutions that I've found in internet but nothing helped me.

my cols in ts file:

Data is beeing fetched from API as array of objects (array example below - there is more data in real data array of course):

const products = [
      {
        id: "1",
        node: {
          index: "0",
          name: "Some product name",
          price: 20.4,
          discount: 0,
          grossPrice: 24.8,
          count: 5,
          info: "Some info"
        }

      }
    ]```
</div>
</div>
</p>
<p>my html file:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <p-table [columns]="cols" [value]="products" sortMode="multiple">
          <ng-template pTemplate="header" let-columns>
            <tr class="ig-table-tr">
              <th *ngFor="let col of columns" [class]="col.class" [pSortableColumn]="col.field" [width]="col.width">
                {{ col.header }}
                <ng-container *ngIf="col.field !== 'info' && col.field !== 'add'">
                  <p-sortIcon [field]="col.field"></p-sortIcon>
                </ng-container>
              </th>
            </tr>
          </ng-template>
          <ng-template pTemplate="body" let-product let-columns="columns">
            <tr class="ig-table-tr">
                <td *ngFor="let col of columns">
                  <ng-container *ngIf="col.field !== 'add'">
                    {{product.node[col.field]}}
                  </ng-container>
                </td>
            </tr>
          </ng-template>
        </p-table></code>```

答:
After about hour of trying to find a solution finally I've found it. The problem is with getting field from object. It is a bit strange for me but works. If product object is inside a key (node here) of array object it doesn't work so I've changed it.

Example below that doesn't work:

const products = [
      {
        id: "1",
        node: {
          index: "0",
          name: "Some product name",
          price: 20.4,
          discount: 0,
          grossPrice: 24.8,
          count: 5,
          info: "Some info"
        }
      }
    ]```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ng-container *ngIf="col.field !== 'addCart'">
  {{product.node[col.field]}}
</ng-container></code>```

Example below that works:

const products = [
      {
        index: "0",
        name: "Some product name",
        price: 20.4,
        discount: 0,
        grossPrice: 24.8,
        count: 5,
        info: "Some info"
      }
  ]```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ng-container *ngIf="col.field !== 'add'">
  {{product[col.field]}}
</ng-container></code>```

Body:
I'm creating some p-table and I tried to add sorting but it's not working. Sorting icon is visible, animation of icon works, data in table is rendering but it is not sorting on header click. I found Primeng documentation and I think I did everything that I should. I've tried a few solutions that I've found in internet but nothing helped me.

my cols in ts file:

Data is beeing fetched from API as array of objects (array example below - there is more data in real data array of course):

const products = [
      {
        id: "1",
        node: {
          index: "0",
          name: "Some product name",
          price: 20.4,
          discount: 0,
          grossPrice: 24.8,
          count: 5,
          info: "Some info"
        }

      }
    ]

my html file:

          <ng-template pTemplate="header" let-columns>

                {{ col.header }}
                <ng-container *ngIf="col.field !== 'info' && col.field !== 'add'">

                </ng-container>

          </ng-template>
          <ng-template pTemplate="body" let-product let-columns="columns">

                  <ng-container *ngIf="col.field !== 'add'">
                    {{product.node[col.field]}}
                  </ng-container>

          </ng-template>

Body:
After about hour of trying to find a solution finally I've found it. The problem is with getting field from object. It is a bit strange for me but works. If product object is inside a key (node here) of array object it doesn't work so I've changed it.

Example below that doesn't work:

const products = [
      {
        id: "1",
        node: {
          index: "0",
          name: "Some product name",
          price: 20.4,
          discount: 0,
          grossPrice: 24.8,
          count: 5,
          info: "Some info"
        }
      }
    ]

<ng-container *ngIf="col.field !== 'addCart'">
  {{product.node[col.field]}}
</ng-container>

Example below that works:

const products = [
      {
        index: "0",
        name: "Some product name",
        price: 20.4,
        discount: 0,
        grossPrice: 24.8,
        count: 5,
        info: "Some info"
      }
  ]

<ng-container *ngIf="col.field !== 'add'">
  {{product[col.field]}}
</ng-container>


问:
View protocol messages of pcap file in linux command line
I am trying to view diameter messages captured in pcap file using tcpdump -r .
But I am not able to see the diameter message.
Is there any other command to view the diameter messages in a pcap file in linux command line.

Thanks in advance.

答: As Steffen Ullrich says, use tshark - tshark -r {capture file} for one-line summaries (same as the packet list in Wireshark), or tshark -V -r {capture file} for detailed information (same as the packet details in Wireshark).


问:
Non-nullable instance field must be initialized (data persistence)
I want to correct the error of the code.
My Problem is:

Non-nullable instance fields must be initialized.

答:
Non-nullable fields are supposed to get initialized during the object creation, which is even before the constructor body is executed. To do so use an initialization list like

Course(dynamic obj): _id = obj['id'], _name = obj['name'] {}
```


问:
Absolute positioning messed up in Safari
I tried to do a mouseover fade effect with jQuery. The idea is to have two images positioned on top of each other in this way.

```<code><img class="img-circle webdesign " src="assets/img/webdesign_.png" style="position: absolute;" >
<img class="img-circle" src="assets/img/webdesign_hover.png">
</code>```

It works well with Chrome. Screenshot ( http://cl.ly/image/0f3M0f2q1t2S )

However, i am having this issue with Safari ( http://cl.ly/image/44290O3n1X0b )

You can see both images when the page loads even though, the grayscale one should appear on top of the coloured one and hides the latter.

Suggestions?

答:
This did the trick for me in a similar challenge:</p>
```<code>position: absolute;
top: 8px;
margin-left: 14px;
</code>```

Body:
I tried to do a mouseover fade effect with jQuery. The idea is to have two images positioned on top of each other in this way.

It works well with Chrome. Screenshot ( http://cl.ly/image/0f3M0f2q1t2S )

However, i am having this issue with Safari ( http://cl.ly/image/44290O3n1X0b )

You can see both images when the page loads even though, the grayscale one should appear on top of the coloured one and hides the latter.

Suggestions?

Body:
This did the trick for me in a similar challenge:

position: absolute;
top: 8px;
margin-left: 14px;


问:
Remove Tab Spaces in VBScript
I have a delimited string containing tabs, and when I do Trim for the string it is not working. For normal space and double spaces Trim is working properly. Below is my code.

```<code>Dim arrStr
arrStr = Split("Customer|Customer Address               |Account", "|")
If (Trim(arrStr(1)) = "First Lane") Then
    WScript.Echo "Inside If"
End If
WScript.Echo "Outside If"
</code>```

I tried with LTrim, RTrim and Trim, but nothing works. I also tried writing custom methods to trim tabs like below, but that also does not work. Any help here please?

```<code>Function customTrim(str)
    Dim re
    Set re = New RegExp
    re.Pattern = "^\t*"
    re.Multiline = False
    customTrim = re.Replace(str, "")
End Function
</code>```

答:
str=replace(str,vbTab,"")

I love regex but this is simpler. It will remove leading, trailing and internal tabs. If you only want to remove some tabs, then definitely go the regex route.

Title: Remove Tab Spaces in VBScript

Body:
I have a delimited string containing tabs, and when I do Trim for the string it is not working. For normal space and double spaces Trim is working properly. Below is my code.

Dim arrStr
arrStr = Split("Customer|Customer Address               |Account", "|")
If (Trim(arrStr(1)) = "First Lane") Then
    WScript.Echo "Inside If"
End If
WScript.Echo "Outside If"

I tried with LTrim, RTrim and Trim, but nothing works. I also tried writing custom methods to trim tabs like below, but that also does not work. Any help here please?

Function customTrim(str)
    Dim re
    Set re = New RegExp
    re.Pattern = "^\t*"
    re.Multiline = False
    customTrim = re.Replace(str, "")
End Function


问:
Unable to push an element of type child to a vector of type base using shared_ptr
Based on this answer, it appears the following code should work:

File Board.h:

```<code>std::vector<std::shared_ptr<Piece>> pawnRow;
for (int x = 0; x < 8; x++)
{
     pawnRow.push_back(std::make_shared<Pawn>());
}
</code>```

For reference Pawn.h:

```<code>#include "Piece.h"

class Pawn : Piece
{};
</code>```

Instead I'm getting: error: no matching function for call to 'std::vector<std::shared_ptr<Piece> >::push_back(std::shared_ptr<Pawn>)'

What am I missing here? My ultimate goal is to have a vector of "pieces" that I can call functions like possibleMoveLocations() that will call the overloaded function in the child class.

Using C++20, gcc version 11.2.0 (MSYS2), Windows 11

答:
As per @Barry's comment, I had to inherit Piece publicly like so:

```<code>#include "Piece.h"

class Pawn : public Piece
{};
</code>```

The code compiled just fine thereafter!

Body:
Based on this answer, it appears the following code should work:

File Board.h:

std::vector<std::shared_ptr<Piece>> pawnRow;
for (int x = 0; x < 8; x++)
{
     pawnRow.push_back(std::make_shared<Pawn>());
}

For reference Pawn.h:

#include "Piece.h"

class Pawn : Piece
{};

Instead I'm getting: error: no matching function for call to 'std::vector<std::shared_ptr<Piece> >::push_back(std::shared_ptr<Pawn>)'

What am I missing here? My ultimate goal is to have a vector of "pieces" that I can call functions like possibleMoveLocations() that will call the overloaded function in the child class.

Using C++20, gcc version 11.2.0 (MSYS2), Windows 11

Body:
As per @Barry's comment, I had to inherit Piece publicly like so:

#include "Piece.h"

class Pawn : public Piece
{};

The code compiled just fine thereafter!