问:
Compile errors with boost::geometry::buffer
I want to buffer a linestring and getting some compile errors with boost::geometry::buffer.

I have the code below:

```<code>// type definitions
using boost_point = boost::geometry::model::d2::point_xy<double>;
using boost_polygon = boost::geometry::model::polygon<boost_point>;
using boost_multipolygon = boost::geometry::model::multi_polygon<boost_polygon>;

// buffer configurations
const double buffer_distance = 0.5;
const int points_per_circle = 10;
boost::geometry::strategy::buffer::distance_symmetric<double> distance_strategy(buffer_distance);
boost::geometry::strategy::buffer::join_round join_strategy(points_per_circle);
boost::geometry::strategy::buffer::end_round end_strategy(points_per_circle);
boost::geometry::strategy::buffer::point_circle circle_strategy(points_per_circle);
boost::geometry::strategy::buffer::side_straight side_strategy;

// convert 3d polyline to 2d polyline then to boost linestring
std::vector<Eigen::Vector3d> polyline_3d = get_polyline_3d();
std::vector<boost_point> polyline_2d = polyline_3d |
    ranges::view::transform([](const Eigen::Vector3d &point){return point.head<2>();}) |
    ranges::view::transform([](const Eigen::Vector2d &point){return boost::geometry::make<boost_point>(point[0], point[1]);}) |
    ranges::to<std::vector<boost_point>>();
auto ls = boost::geometry::model::linestring<boost_point>(polyline_2d.begin(),polyline_2d.end());

// get a buffered multipolygon from linestring
boost_multipolygon buffered;
boost::geometry::buffer(ls, buffered, distance_strategy, side_strategy, join_strategy, end_strategy, circle_strategy);
</code>```

I'm getting the following compile errors:

```<code>boost/geometry/strategies/distance.hpp:97:5: error: no matching function for call to 'assertion_failed<false>(mpl_::failed************ (boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION::************)(mpl_::assert_::types<boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag>))'
     BOOST_MPL_ASSERT_MSG

boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp:71:13: error: no type named 'type' in 'struct boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::d2::point_xy<double>, boost::geometry::model::d2::point_xy<double>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>'
     >::type ds_strategy_type;
             ^~~~~~~~~~~~~~~~
boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp:75:7: error: no type named 'type' in 'struct boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::d2::point_xy<double>, boost::geometry::model::d2::point_xy<double>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>'
     > strategy_type;
       ^~~~~~~~~~~~~

boost/geometry/strategies/distance.hpp:97:5: error: no matching function for call to 'assertion_failed<false>(mpl_::failed************ (boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION::************)(mpl_::assert_::types<boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag>))'
     BOOST_MPL_ASSERT_MSG

boost/geometry/strategies/comparable_distance_result.hpp:51:8: error: no type named 'type' in 'struct boost::geometry::detail::distance::default_strategy<boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::referring_segment<const boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian> >, boost::geometry::pointlike_tag, boost::geometry::segment_tag, false>'

boost/geometry/algorithms/detail/buffer/buffered_piece_collection.hpp:884:48: error: no matching function for call to 'comparable_distance(boost::geometry::detail::buffer::buffered_piece_collection<boost::geometry::model::ring<boost::geometry::model::d2::point_xy<double>, true, true, std::vector, std::allocator>, boost::geometry::strategy::intersection::cartesian_segments<>, boost::geometry::detail::robust_policy<boost::geometry::model::d2::point_xy<double>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, double> >::robust_point_type&, robust_segment_type&)'
</code>```

I think my usage of buffer is pretty basic, and I'm confused why this would be causing so many compile errors. Am I missing something here?

答:
I cannot reproduce this:

Live On Compiler Explorer

```<code>#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>
#include <range/v3/all.hpp>
#include <Eigen/Eigen>

namespace bg = boost::geometry;

// type definitions
using boost_point        = bg::model::d2::point_xy<double>;
using boost_polygon      = bg::model::polygon<boost_point>;
using boost_multipolygon = bg::model::multi_polygon<boost_polygon>;

std::vector<Eigen::Vector3d> get_polyline_3d() { return {}; }

int main()
{
    using ranges::views::transform;

    // convert 3d polyline to 2d polyline then to boost linestring
    std::vector<Eigen::Vector3d> polyline_3d = get_polyline_3d();
    std::vector<boost_point>     polyline_2d =
        polyline_3d //
        | transform([](const Eigen::Vector3d& point) { return point.head<2>(); }) //
        | transform([](const Eigen::Vector2d& point) { return bg::make<boost_point>(point[0], point[1]); }) //
        | ranges::to<std::vector<boost_point>>();

    auto ls = bg::model::linestring<boost_point>(polyline_2d.begin(),
                                                 polyline_2d.end());

    // get a buffered multipolygon from linestring
    boost_multipolygon buffered;
    {
        // buffer configurations
        const double buffer_distance   = 0.5;
        const int    points_per_circle = 10;

        namespace bs = bg::strategy::buffer;
        bs::distance_symmetric<double> distance_strategy(buffer_distance);
        bs::join_round                 join_strategy(points_per_circle);
        bs::end_round                  end_strategy(points_per_circle);
        bs::point_circle               circle_strategy(points_per_circle);
        bs::side_straight              side_strategy;

        bg::buffer(ls, buffered, distance_strategy, side_strategy, join_strategy,
                end_strategy, circle_strategy);
    }
}
</code>```

Which compiles fine for me on my GCC 10, Boost 1.78, Eigen 3.3.4, Rangev3 (0.11.0-44-g81b6d3f1b). Perhaps you were missing an include?

Body:
I want to buffer a linestring and getting some compile errors with boost::geometry::buffer.

I have the code below:

// type definitions
using boost_point = boost::geometry::model::d2::point_xy<double>;
using boost_polygon = boost::geometry::model::polygon<boost_point>;
using boost_multipolygon = boost::geometry::model::multi_polygon<boost_polygon>;

// buffer configurations
const double buffer_distance = 0.5;
const int points_per_circle = 10;
boost::geometry::strategy::buffer::distance_symmetric<double> distance_strategy(buffer_distance);
boost::geometry::strategy::buffer::join_round join_strategy(points_per_circle);
boost::geometry::strategy::buffer::end_round end_strategy(points_per_circle);
boost::geometry::strategy::buffer::point_circle circle_strategy(points_per_circle);
boost::geometry::strategy::buffer::side_straight side_strategy;

// convert 3d polyline to 2d polyline then to boost linestring
std::vector<Eigen::Vector3d> polyline_3d = get_polyline_3d();
std::vector<boost_point> polyline_2d = polyline_3d |
    ranges::view::transform([](const Eigen::Vector3d &point){return point.head<2>();}) |
    ranges::view::transform([](const Eigen::Vector2d &point){return boost::geometry::make<boost_point>(point[0], point[1]);}) |
    ranges::to<std::vector<boost_point>>();
auto ls = boost::geometry::model::linestring<boost_point>(polyline_2d.begin(),polyline_2d.end());

// get a buffered multipolygon from linestring
boost_multipolygon buffered;
boost::geometry::buffer(ls, buffered, distance_strategy, side_strategy, join_strategy, end_strategy, circle_strategy);

I'm getting the following compile errors:

boost/geometry/strategies/distance.hpp:97:5: error: no matching function for call to 'assertion_failed<false>(mpl_::failed************ (boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION::************)(mpl_::assert_::types<boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag>))'
     BOOST_MPL_ASSERT_MSG

boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp:71:13: error: no type named 'type' in 'struct boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::d2::point_xy<double>, boost::geometry::model::d2::point_xy<double>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>'
     >::type ds_strategy_type;
             ^~~~~~~~~~~~~~~~
boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp:75:7: error: no type named 'type' in 'struct boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::d2::point_xy<double>, boost::geometry::model::d2::point_xy<double>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>'
     > strategy_type;
       ^~~~~~~~~~~~~

boost/geometry/strategies/distance.hpp:97:5: error: no matching function for call to 'assertion_failed<false>(mpl_::failed************ (boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag, void>::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION::************)(mpl_::assert_::types<boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::cartesian_tag, boost::geometry::cartesian_tag>))'
     BOOST_MPL_ASSERT_MSG

boost/geometry/strategies/comparable_distance_result.hpp:51:8: error: no type named 'type' in 'struct boost::geometry::detail::distance::default_strategy<boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, boost::geometry::model::referring_segment<const boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian> >, boost::geometry::pointlike_tag, boost::geometry::segment_tag, false>'

boost/geometry/algorithms/detail/buffer/buffered_piece_collection.hpp:884:48: error: no matching function for call to 'comparable_distance(boost::geometry::detail::buffer::buffered_piece_collection<boost::geometry::model::ring<boost::geometry::model::d2::point_xy<double>, true, true, std::vector, std::allocator>, boost::geometry::strategy::intersection::cartesian_segments<>, boost::geometry::detail::robust_policy<boost::geometry::model::d2::point_xy<double>, boost::geometry::model::point<long long int, 2, boost::geometry::cs::cartesian>, double> >::robust_point_type&, robust_segment_type&)'

I think my usage of buffer is pretty basic, and I'm confused why this would be causing so many compile errors. Am I missing something here?

Body:
I cannot reproduce this:

Live On Compiler Explorer

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>
#include <range/v3/all.hpp>
#include <Eigen/Eigen>

namespace bg = boost::geometry;

// type definitions
using boost_point        = bg::model::d2::point_xy<double>;
using boost_polygon      = bg::model::polygon<boost_point>;
using boost_multipolygon = bg::model::multi_polygon<boost_polygon>;

std::vector<Eigen::Vector3d> get_polyline_3d() { return {}; }

int main()
{
    using ranges::views::transform;

    // convert 3d polyline to 2d polyline then to boost linestring
    std::vector<Eigen::Vector3d> polyline_3d = get_polyline_3d();
    std::vector<boost_point>     polyline_2d =
        polyline_3d //
        | transform([](const Eigen::Vector3d& point) { return point.head<2>(); }) //
        | transform([](const Eigen::Vector2d& point) { return bg::make<boost_point>(point[0], point[1]); }) //
        | ranges::to<std::vector<boost_point>>();

    auto ls = bg::model::linestring<boost_point>(polyline_2d.begin(),
                                                 polyline_2d.end());

    // get a buffered multipolygon from linestring
    boost_multipolygon buffered;
    {
        // buffer configurations
        const double buffer_distance   = 0.5;
        const int    points_per_circle = 10;

        namespace bs = bg::strategy::buffer;
        bs::distance_symmetric<double> distance_strategy(buffer_distance);
        bs::join_round                 join_strategy(points_per_circle);
        bs::end_round                  end_strategy(points_per_circle);
        bs::point_circle               circle_strategy(points_per_circle);
        bs::side_straight              side_strategy;

        bg::buffer(ls, buffered, distance_strategy, side_strategy, join_strategy,
                end_strategy, circle_strategy);
    }
}

Which compiles fine for me on my GCC 10, Boost 1.78, Eigen 3.3.4, Rangev3 (0.11.0-44-g81b6d3f1b). Perhaps you were missing an include?


来源: stackexchange

问:
Installing Mac VSCode extensions now failing with error: Corrupt ZIP: end of central directory record signature not found
After upgrading work Mac to Big Sur, now unable to install any VS Code extensions, where I was able to before. The error message that I am receiving is the following:

[2021-08-18 14:04:53.663] [renderer1] [error] ["validating: Corrupt ZIP: end of central directory record signature not found","    at x.downloadInstallableExtension (vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/sharedProcess/sharedProcessMain.js:54:201021)","    at async x.installGalleryExtension (vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/sharedProcess/sharedProcessMain.js:54:197524)","    at async vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/sharedProcess/sharedProcessMain.js:54:194563"]

I have looked at several stack overflow threads like this one:

Error "end of central directory record signature not found" while installing ionide-fsharp in vscode

I can confirm the following:

My company runs a corporate transparent proxy, so I do not have to enter a proxy in the settings.  I've confirmed that I do not have this set.

I have followed the instructions to download and install the vsix file manually

Downloading looks to be successful, the python extension is 16.5 MB

The installation portion of the downloaded file fails with the same error

Confirmed that I do not have a disk space issues as someone mentioned in the above thread

I have reinstalled VSCode per these instructions: How to completely uninstall vscode on mac

I've attempted installations of VSCode 1.59 (original version) and 1.58.2, same errors

Any suggestions on where to go from here?  I'm not able to install this locally, and can't seem to figure out what may be causing the issue.

I have confirmed with other team members that they're not running into my issue, and they have successfully upgraded to Big Sur.  I don't think that's the cause, but that's the only change to my workstation that I can think of.

答:
This worked for me:

Try downloading the vsix file of the extension from its github release page (make sure the extension version is compatible with your vscode version)

Disable your internet connection and install the vsix file via vscode.

ContentLicense: CC BY-SA 4.0


问:
How can I minimise the scale to have more detailed number using jasperReport?
I'am using jasperReport/ireport 4.0

Using jasper I generate a report contain barChart that contain a lot of informations,
The number on  the x axis is not clear and precise ,from the chart I cant tell how many issue I have ,
when the user read the report he can't tell the right value

How can I minimise the scale to have more detailed number?

My chart:

答:
You'll need to use a chart customizer class to do this. Create a class that implements the JRChartCustomizer interface, then in the customize() method add the following code:

```<code>CategoryPlot plot = (CategoryPlot)jFreeChart.getPlot();
ValueAxis verticalAxis = plot.getRangeAxis();

TickUnits verticalTicks = new TickUnits();
verticalTicks.add(new NumberTickUnit(1));
verticalTicks.add(new NumberTickUnit(2));
verticalTicks.add(new NumberTickUnit(5));
verticalTicks.add(new NumberTickUnit(10));

verticalAxis.setStandardTickUnits(verticalTicks);
</code>```

The chart engine should always pick the smallest tick unit that does not cause the ticks to overlap. Using this code your chart should hopefully place ticks at every value or every 2 values.

ContentLicense: CC BY-SA 3.0

Body:
You'll need to use a chart customizer class to do this. Create a class that implements the JRChartCustomizer interface, then in the customize() method add the following code:

CategoryPlot plot = (CategoryPlot)jFreeChart.getPlot();
ValueAxis verticalAxis = plot.getRangeAxis();

TickUnits verticalTicks = new TickUnits();
verticalTicks.add(new NumberTickUnit(1));
verticalTicks.add(new NumberTickUnit(2));
verticalTicks.add(new NumberTickUnit(5));
verticalTicks.add(new NumberTickUnit(10));

verticalAxis.setStandardTickUnits(verticalTicks);

The chart engine should always pick the smallest tick unit that does not cause the ticks to overlap. Using this code your chart should hopefully place ticks at every value or every 2 values.


问:
How can I backup nifi processes when restarting Kuberntes pod?
I have deployed Nifi on Kuberntes using cetic/helm-nifi helm chart. We are facing a problem, If nifi pod restarts we lost the all processes that we created. Is there any way to keep a backup of the process in nifi canvas.</p>

答:
You might be deploying the helm with default config or you are tweaking any configs also?

i have not used nifi but i think enabling the PVC config for nifi might resolve your resolve.

https://github.com/cetic/helm-nifi/blob/master/values.yaml#L211

You can enable the PVC by changing the values.yaml line number.

```<code>persistence:
  enabled: true
</code>```

if you have already created volumes you can also use it.

Body:
You might be deploying the helm with default config or you are tweaking any configs also?

i have not used nifi but i think enabling the PVC config for nifi might resolve your resolve.

https://github.com/cetic/helm-nifi/blob/master/values.yaml#L211

You can enable the PVC by changing the values.yaml line number.

persistence:
  enabled: true

if you have already created volumes you can also use it.


问:
Failed to resolve: com.github.barteksc:android-pdf-viewer:2.8.1
I am trying use this library in my Project. But i am unable to download it by adding it in gradle build. In fact i am even unable to download any library through gradle. I need to manually download a jar file and add that as a library. But in this case I couldn't find the jar file for PDFviewer.

Build.gradle (Module)

```<code>dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:design:23.0.1'
testCompile 'junit:junit:4.12'
compile files('libs/jsoup-1.8.1.jar')
compile files('libs/log4j-1.2.9.jar')
compile files('libs/picasso-2.5.2.jar')
compile files('libs/json-simple-1.1.jar')
compile files('libs/glide-3.7.0.jar')
compile files('libs/commons-codec-1.9.jar')
compile files('libs/asmack.jar')
compile files('libs/android-logging-log4j-1.0.3.jar')
compile 'com.github.barteksc:android-pdf-viewer:2.8.1'  //unable to add this.
}
</code>```

Build.gradle

```<code>allprojects {
repositories {
    jcenter()
    maven {
        url "https://maven.google.com"
    }
   // google()
   // mavenLocal() // tried everything
}
}
</code>```

I have tried almost everything for the past three days given in SO but still couldn't find any solution to this. It will be helpful even if i get the jar file.

答:
it's a problem with jCenter (deprecated) when he's drop.

add :

```<code>allprojects {repositories {
        mavenCentral()
        google()
        gradlePluginPortal()
    }
}
</code>```

Body:
I am trying use this library in my Project. But i am unable to download it by adding it in gradle build. In fact i am even unable to download any library through gradle. I need to manually download a jar file and add that as a library. But in this case I couldn't find the jar file for PDFviewer.

Build.gradle (Module)

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:design:23.0.1'
testCompile 'junit:junit:4.12'
compile files('libs/jsoup-1.8.1.jar')
compile files('libs/log4j-1.2.9.jar')
compile files('libs/picasso-2.5.2.jar')
compile files('libs/json-simple-1.1.jar')
compile files('libs/glide-3.7.0.jar')
compile files('libs/commons-codec-1.9.jar')
compile files('libs/asmack.jar')
compile files('libs/android-logging-log4j-1.0.3.jar')
compile 'com.github.barteksc:android-pdf-viewer:2.8.1'  //unable to add this.
}

Build.gradle

allprojects {
repositories {
    jcenter()
    maven {
        url "https://maven.google.com"
    }
   // google()
   // mavenLocal() // tried everything
}
}

I have tried almost everything for the past three days given in SO but still couldn't find any solution to this. It will be helpful even if i get the jar file.

Body:
it's a problem with jCenter (deprecated) when he's drop.

add :

allprojects {repositories {
        mavenCentral()
        google()
        gradlePluginPortal()
    }
}


问:
How to make a widget maximum size be equal to the flex value in a row
I have this small code:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),
```
<p>which renders into this:</p>
<p><img src="https://i.stack.imgur.com/ZP2wy.png" alt="enter image description here" /></p>
<p>Notice how the long text is wrapped even though there is still space around the small text.</p>
<p>I would like the small text to only take the size it needs to let the long text take the rest. And if the small text becomes bigger, its maximum size would be the size of the <code>Flexible</code> widget in the row (half of the <code>Row</code> in my example since both <code>Expanded</code> and <code>Flexible</code> have <code>flex: 1</code>).</p>
<p>If the small text is small enough, it should look like:</p>
```| Red text that can be long long long long | Small text |
| long                                     |            |
```
<p>And if the "small" text is long too:</p>
```| Red text that can be long | Small text that is also  |
| long long long long       | very long                |
```

Is there a way to do that?

答:
In the end, I used Yeasin Sheikh's answer so I'm validating it.

But I'm writing this comment to add more precisions on what I have found during my investigations.

At first, I wanted a simple widget like Flexible or Expanded (let's say LooseFlexible) to wrap my widget with:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      LooseFlexible(
        flex: 1
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),
```
<p>but it seems it would go against the way Flutter works.</p>
<p>I took a look a the flutter class <code>RenderFlex</code>, which is the render object the <code>Flex</code> class (a class that <code>Row</code> and <code>Column</code> are extending) returns in the method <code>createRenderObject</code>.
It has a method <code>_computeSizes</code>, and inside it goes through the children (one by one):</p>
<ul>
<li>if it does not have a <code>flex</code> value (<em>"normal widget"</em>):
It gives to the child no max constraint for the layout and gets its size.</li>
<li>if it has a <code>flex</code> value (from <code>Flexible</code> or <code>Expanded</code>):
it accumulates in a <code>totalFlex</code> value the some of all the <code>flex</code> (and <strong>does not</strong> render the child).</li>
</ul>
<p>Then it goes through all the widgets that have a <code>flex</code> value and gives them as a max constraint <code>(flex / totalFlex) * (maxConstraintOfParent - totalSizeOfNonFlexChildren)</code> and layout them with it.</p>
<p>So each child is layout <strong>only once</strong>.</p>
<hr />
<p>If my widget <code>LooseFlexible</code> were to exist, and if we had this code:</p>
<pre class="lang-dart prettyprint-override"><code>Row(
  children: [
    Expanded(flex: 1),
    LooseFlexible(flex: 1),
    Expanded(flex: 1),
  ],
),
</code>```

Let's say the row has a maxWidth of 300. There is no non-flex children and totalFlex = 3.

The 1st Expanded would be laid out with a maxWidth = 100. Since it is an Expanded its width will be 100.

The Flexible widget is also laid out with a maxWidth = 100. But its size could be 50 (and not 100).

Now comes the turn of the last Expanded, if we want it to take the entire remaining space, its size would be 150 which is not the same as the 1st Expanded with the same flex = 1 value. So the first child would need to be re-laid out, which is not following the flutter way of rendering children only once.

Body:
I have this small code:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),

which renders into this:

Notice how the long text is wrapped even though there is still space around the small text.

I would like the small text to only take the size it needs to let the long text take the rest. And if the small text becomes bigger, its maximum size would be the size of the Flexible widget in the row (half of the Row in my example since both Expanded and Flexible have flex: 1).

If the small text is small enough, it should look like:

| Red text that can be long long long long | Small text |
| long                                     |            |

And if the "small" text is long too:

| Red text that can be long | Small text that is also  |
| long long long long       | very long                |

Is there a way to do that?

Body:
In the end, I used Yeasin Sheikh's answer so I'm validating it.

But I'm writing this comment to add more precisions on what I have found during my investigations.

At first, I wanted a simple widget like Flexible or Expanded (let's say LooseFlexible) to wrap my widget with:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      LooseFlexible(
        flex: 1
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),

but it seems it would go against the way Flutter works.

I took a look a the flutter class RenderFlex, which is the render object the Flex class (a class that Row and Column are extending) returns in the method createRenderObject.
It has a method _computeSizes, and inside it goes through the children (one by one):

if it does not have a flex value ("normal widget"):
It gives to the child no max constraint for the layout and gets its size.

if it has a flex value (from Flexible or Expanded):
it accumulates in a totalFlex value the some of all the flex (and does not render the child).

Then it goes through all the widgets that have a flex value and gives them as a max constraint (flex / totalFlex) * (maxConstraintOfParent - totalSizeOfNonFlexChildren) and layout them with it.

So each child is layout only once.

If my widget LooseFlexible were to exist, and if we had this code:

Row(
  children: [
    Expanded(flex: 1),
    LooseFlexible(flex: 1),
    Expanded(flex: 1),
  ],
),

Let's say the row has a maxWidth of 300. There is no non-flex children and totalFlex = 3.

The 1st Expanded would be laid out with a maxWidth = 100. Since it is an Expanded its width will be 100.

The Flexible widget is also laid out with a maxWidth = 100. But its size could be 50 (and not 100).

Now comes the turn of the last Expanded, if we want it to take the entire remaining space, its size would be 150 which is not the same as the 1st Expanded with the same flex = 1 value. So the first child would need to be re-laid out, which is not following the flutter way of rendering children only once.


问:
What is the proper way to comment functions in Python?
Is there a generally accepted way to comment functions in Python? Is the following acceptable?</p>

```<code>#########################################################
# Create a new user
#########################################################
def add(self):
</code>```

答:
The correct way is as follows:

```<code>def search_phone_state(phone_number_start,state,dataframe_path,separator):
   """
   returns records whose phone numbers begin with a phone_number_start and are from state
   """
   dataframe = pd.read_csv(filepath_or_buffer=dataframe_path, sep=separator, header=0)
   return dataframe[(pd.Series(dataframe["Phone"].values.tolist()).str.startswith(phone_number_start, na="False"))& (dataframe["State"]==state)]
</code>```

If you do:

```<code>help(search_phone_state)
</code>```

It will print:

```<code>Help on function search_phone_state in module __main__:

search_phone_state(phone_number_start, state, dataframe_path, separator)
returns records whose phone numbers begin with a phone_number_start and are from state
</code>```

Body:
Is there a generally accepted way to comment functions in Python? Is the following acceptable?

#########################################################
# Create a new user
#########################################################
def add(self):

Body:
The correct way is as follows:

def search_phone_state(phone_number_start,state,dataframe_path,separator):
   """
   returns records whose phone numbers begin with a phone_number_start and are from state
   """
   dataframe = pd.read_csv(filepath_or_buffer=dataframe_path, sep=separator, header=0)
   return dataframe[(pd.Series(dataframe["Phone"].values.tolist()).str.startswith(phone_number_start, na="False"))& (dataframe["State"]==state)]

If you do:

help(search_phone_state)

It will print:

Help on function search_phone_state in module __main__:

search_phone_state(phone_number_start, state, dataframe_path, separator)
returns records whose phone numbers begin with a phone_number_start and are from state


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答:
I think that code needs to be, first and foremost, readable and understandable. So, optimisations that are done, should not be at the expense of readability. However, optimisation is often a trade-off.

Whether or not you should optimise your code depends on your application domain. If you are working on an embedded processor with only 8Mb of memory, then optimisation is probably something that every team member needs to keep in mind, when writing code - optimising for space vs speed.

However, pre-mature optimisation is not useful unless your system has been clearly spec'ed and understood. This is because most programmers do not make good optimisation decisions unless they can factor in the influence of the overall system, including processor architectural factors such as cache memory, hardware threads, pipelines, etc.

OwnerDisplayName: dicroce

ContentLicense: CC BY-SA 2.5

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: sybreon


问:
How do I click a control button with ID using AutoHotkey?
How do I click a control button with ID using AutoHotkey?

I tried Click and ControlClick, but no luck!

```<code>ControlClick Button40

Click Button40
</code>```

答:
You need to give it some information about the window that the control is on. For example, to close the About screen in Notepad on Windows you could use

```<code>ControlClick, Button1, About Notepad ahk_class #32770
</code>```

The format of the command from the docs is

```<code>ControlClick [, Control-or-Pos, WinTitle, WinText, WhichButton, ClickCount, Options, ExcludeTitle, ExcludeText]
</code>```

Body:
How do I click a control button with ID using AutoHotkey?

I tried Click and ControlClick, but no luck!

ControlClick Button40

Click Button40

Body:
You need to give it some information about the window that the control is on. For example, to close the About screen in Notepad on Windows you could use

ControlClick, Button1, About Notepad ahk_class #32770

The format of the command from the docs is

ControlClick [, Control-or-Pos, WinTitle, WinText, WhichButton, ClickCount, Options, ExcludeTitle, ExcludeText]


问:
Passing arguments to cypress request
I have the following method inside my support/index.ts file

```<code>function testSkipping(channel='US', test:any){
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test) // will print nothing

                if (response.body.feature.test) {
                    this.skip();
                }
            }
        }
    )
}
</code>```

I am calling this from my test as follows

```<code>before(() => {
    cy.testSkipping('US','SkipPaymentTests');
})
</code>```

I need to skip the test, when a the provided value of test are set to true. This code is not working. The value of test does not get replaced with SkipPaymentTests

the response of the call is

```<code>{
"SkipPaymentTests":true
}
</code>```

答:
You can use template literals for this:

function testSkipping(channel = 'US', test: any) {
  cy.log(test) // will print SkipPaymentTests

  cy.request({
    method: 'GET',
    url: Cypress.env('EndPoint') + 'features',
    headers: {
      Channel: `${channel}`,
      'Subscription-Key': Cypress.env('sKey'),
    },
  }).then(function (response) {
    if (response?.status === 200) {
      expect(response.body.feature).to.exist
      if (response.body.feature[`${test}`]) {
        this.skip()
      }
    }
  })
}
```

Title: Passing arguments to cypress request

Body:
I have the following method inside my support/index.ts file

function testSkipping(channel='US', test:any){
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test) // will print nothing

                if (response.body.feature.test) {
                    this.skip();
                }
            }
        }
    )
}

I am calling this from my test as follows

before(() => {
    cy.testSkipping('US','SkipPaymentTests');
})

I need to skip the test, when a the provided value of test are set to true. This code is not working. The value of test does not get replaced with SkipPaymentTests

the response of the call is

{
"SkipPaymentTests":true
}


问:
connect to clickhouse DB in R programming
due to RClickhouse package is deprecate so i change to use clickhouse R DBI client but it still doesn't work when i change port to 9009 and below is my code

```<code>library(DBI)
con <- dbConnect(clickhouse::clickhouse(),host="myhost",port=myport,user="my_user",password="my_paswor")
</code>```

this the error

<simpleError in .local(conn, statement, ...): Port 9000 is for
clickhouse-client program You must use port 8123 for HTTP.

答:
You should use 8123 port

8123  -- ClickHouse http protocol (8443 https)

9000  -- ClickHouse tcp protocol (9440 tcp/tls)

9009  -- ClickHouse replication protocol (replicas interconnect)

https://github.com/IMSMWU/RClickhouse -- uses Native tcp proto (9000)

https://github.com/hannesmuehleisen/clickhouse-r  -- uses HTTP proto (8123)

Different libraries and applications implement different protocols.

Body:
due to RClickhouse package is deprecate so i change to use clickhouse R DBI client but it still doesn't work when i change port to 9009 and below is my code

library(DBI)
con <- dbConnect(clickhouse::clickhouse(),host="myhost",port=myport,user="my_user",password="my_paswor")

this the error

<simpleError in .local(conn, statement, ...): Port 9000 is for
clickhouse-client program You must use port 8123 for HTTP.


问:
Passing current page id to a link_to (Ruby/ Rails)
Apologies if this seems a bit vague.

Basically I have a page which loads content based on id. I'm trying to put links withing it like this

```<code><%= link_to 'mypage', {:action => 'mypageload', :id => '1'},{:class=>'mypages'}%>
</code>```

What I'd like to do is pass the id of the current page into this link.

So something like

```<code>:id => 'params[:id]'
</code>```

Is there a way to do this?

答:
Yes, you can use the params variable in the views. In your example you put the params inside quotes making it a string. Just leave those out and you should be fine, like this:</p>

```<code><%= link_to 'mypage', {:action => 'mypageload', :id => params[:id]},{:class=>'mypages'}%>
</code>```

Body:
Apologies if this seems a bit vague.

Basically I have a page which loads content based on id. I'm trying to put links withing it like this

<%= link_to 'mypage', {:action => 'mypageload', :id => '1'},{:class=>'mypages'}%>

What I'd like to do is pass the id of the current page into this link.

So something like

:id => 'params[:id]'

Is there a way to do this?

Body:
Yes, you can use the params variable in the views. In your example you put the params inside quotes making it a string. Just leave those out and you should be fine, like this:

<%= link_to 'mypage', {:action => 'mypageload', :id => params[:id]},{:class=>'mypages'}%>


问:
Place div to the right side of the text
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

答:
Maybe you can try to solve with the js code after documentReady!

```<code>document.querySelectorAll('.first-child').forEach(t => {t.style.width=t.querySelector('span').offsetWidth+'px'})
</code>```

document.querySelectorAll('.first-child').forEach(t => {t.style.width=t.querySelector('span').offsetWidth+'px'})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}</code>```

    Loooooooong teeeeeext

    Short text

```

Title: Place div to the right side of the text

Body:
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

    Loooooooong teeeeeext

    Short text

Body:
Maybe you can try to solve with the js code after documentReady!

document.querySelectorAll('.first-child').forEach(t => {t.style.width=t.querySelector('span').offsetWidth+'px'})

document.querySelectorAll('.first-child').forEach(t => {t.style.width=t.querySelector('span').offsetWidth+'px'})

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

<div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div>


问:
key_load_public: invalid format
I used PuTTY Key Generator to generate a 4096 bit RSA-2 key with a passphrase.

I save the .ppk and an openSSL format public key. The putty format public key doesn't work.

In any case, my error is as follows:

```<code>$ ssh -T git@github.com
key_load_public: invalid format
Enter passphrase for key '/c/Users/Dan/.ssh/id_rsa':
Hi Dan! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

What's the issue?

I use Pageant to load the keys and i use Git Bash to try the ssh connection. I've also loaded the key into GitHub, not sure what i'm doing wrong.

I've tried adding a new line and not adding a new line in GitHub

答:
Generate id_rsa and id_rsa.pub files using the below command :

```<code>ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
</code>```

Then :

```<code>1) Place file in id_rsa.pub into ~/.ssh/id_rsa.pub

2) sudo chmod 600 ~/.ssh/id_rsa.pub

3) Place file id_rsa into ~/.ssh/id_rsa

Now ~/.ssh contains two files..~/.ssh/id_rsa.pub and ~/.ssh/id_rsa

4) ssh-add  ~/.ssh/id_rsa

5) Enter the passphrase entered during creation of id_rsa

Output :

Identity added: /home/jay/.ssh/id_rsa (/home/jay/.ssh/id_rsa)
</code>```

Now you can push pull without entering username password

Title: key_load_public: invalid format

Body:
I used PuTTY Key Generator to generate a 4096 bit RSA-2 key with a passphrase.

I save the .ppk and an openSSL format public key. The putty format public key doesn't work.

In any case, my error is as follows:

$ ssh -T git@github.com
key_load_public: invalid format
Enter passphrase for key '/c/Users/Dan/.ssh/id_rsa':
Hi Dan! You've successfully authenticated, but GitHub does not provide shell access.

What's the issue?

I use Pageant to load the keys and i use Git Bash to try the ssh connection. I've also loaded the key into GitHub, not sure what i'm doing wrong.

I've tried adding a new line and not adding a new line in GitHub

Body:
Generate id_rsa and id_rsa.pub files using the below command :

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Then :

1) Place file in id_rsa.pub into ~/.ssh/id_rsa.pub

2) sudo chmod 600 ~/.ssh/id_rsa.pub

3) Place file id_rsa into ~/.ssh/id_rsa

Now ~/.ssh contains two files..~/.ssh/id_rsa.pub and ~/.ssh/id_rsa

4) ssh-add  ~/.ssh/id_rsa

5) Enter the passphrase entered during creation of id_rsa

Output :

Identity added: /home/jay/.ssh/id_rsa (/home/jay/.ssh/id_rsa)

Now you can push pull without entering username password


问:
Error log about wrong font while I create JLabel on Mac
When I create a new JLabel, I get the following error log in the console:

Warning: the fonts "Times" and "Times" are not available for the Java
logical font "Serif", which may have unexpected appearance or
behavior. Re-enable the "Times" font to remove this warning.

But I do not use this (default) font.

How can I solve this problem or at least suppress the message?

```<code>StringBuilder sb = new StringBuilder();
// sb gets some text here
// ...
JLabel label = new JLabel();
label.setFont(new Font("Classic Console Neue", Font.PLAIN, 18)); // changed font to a valid font
label.setText(sb.toString()); // this line will cause the log entry, but why?

</code>```

A workaround would be to install the Times.ttf on every target computer, but that is not practicable.

答:
The "Times" font is not installed in macOS 12 Monterey.

Java has been updated to take this into account, newer versions of Java should not print the warning and should correctly use a serif font. See JDK-8273358 for more details.

Body:
When I create a new JLabel, I get the following error log in the console:

Warning: the fonts "Times" and "Times" are not available for the Java
logical font "Serif", which may have unexpected appearance or
behavior. Re-enable the "Times" font to remove this warning.

But I do not use this (default) font.

How can I solve this problem or at least suppress the message?

StringBuilder sb = new StringBuilder();
// sb gets some text here
// ...
JLabel label = new JLabel();
label.setFont(new Font("Classic Console Neue", Font.PLAIN, 18)); // changed font to a valid font
label.setText(sb.toString()); // this line will cause the log entry, but why?

A workaround would be to install the Times.ttf on every target computer, but that is not practicable.


问:
Android ScrollView, scroll before visible
how can I set scroll of scrollview to x pixels, before it's even shown?

In ScrollView I have some Views and i know that it will fill screen. Can I scroll to let say second View, so that first View is not visible when activity is started?

Now I have sth like this, but I think it's not perfect, sometimes, I see first View, and then it's scrolled to the second one

```<code>@Override
public void onGlobalLayout() {
    if (mHorizontalScrollView.getChildCount() > 0 && mHorizontalScrollView.getChildAt(0).getWidth() > mScreenWidth) {
            hsv.scrollTo(100, 0);
    }
}
</code>```

EDIT!!

Second attempt was to use http://developer.android.com/reference/android/view/ViewTreeObserver.OnPreDrawListener.html instead of http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
In OnPreDrawListener we can read that At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs. so basically at this point we should adjust scrolling. So I created:

```<code>@Override
public boolean onPreDraw() {
    if (hsv.getChildCount() > 0 && hsv.getChildAt(0).getWidth() > mScreenWidth) {
        hsv.scrollTo(100, 0);
        return false;
    }
    return true;
}
</code>```

but now it's never working for me.

答:
The correct way to do this, is to call scrollTo() on the ScrollView after the view has been through its measurement and layout passes, otherwise the width of the content in the scrollView will be 0, and thus scrollTo() will not scroll to the right position. Usually after the constructor has been called and after the view has been added to its parent.

See http://developer.android.com/guide/topics/ui/how-android-draws.html for more insight on how android draws views.

Body:
how can I set scroll of scrollview to x pixels, before it's even shown?

In ScrollView I have some Views and i know that it will fill screen. Can I scroll to let say second View, so that first View is not visible when activity is started?

Now I have sth like this, but I think it's not perfect, sometimes, I see first View, and then it's scrolled to the second one

@Override
public void onGlobalLayout() {
    if (mHorizontalScrollView.getChildCount() > 0 && mHorizontalScrollView.getChildAt(0).getWidth() > mScreenWidth) {
            hsv.scrollTo(100, 0);
    }
}

EDIT!!

Second attempt was to use http://developer.android.com/reference/android/view/ViewTreeObserver.OnPreDrawListener.html instead of http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
In OnPreDrawListener we can read that At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs. so basically at this point we should adjust scrolling. So I created:

@Override
public boolean onPreDraw() {
    if (hsv.getChildCount() > 0 && hsv.getChildAt(0).getWidth() > mScreenWidth) {
        hsv.scrollTo(100, 0);
        return false;
    }
    return true;
}

but now it's never working for me.


问:
NumberingFormats is always null, why?
I'm writing a program that use OpenXML to read an excel file. The file contains also dates, so i need a function that recognize them. Here on stackoverflow i've found this solution: How to distinguish inline numbers from OLE Automation date numbers in OpenXML SpreadSheet? .

I've tryed to apply it to my code, but every time I get the following error:

"An unhandled exception of type 'System.NullReferenceException' occurred in OpenXML_Prova.exe

Additional information: Object reference not set to an instance of an object."

on the first line of the GetDateTimeCellFormats, in which it seems that NumberingFormats is always null.

Here is the complete code:

```<code>using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace OpenXML_Prova
{
    class Program
    {

        DocumentFormat.OpenXml.Spreadsheet.NumberingFormats numb = new NumberingFormats();

        static uint[] builtInDateTimeNumberFormatIDs = new uint[] { 14, 15, 16, 17, 18, 19, 20, 21, 22, /*27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 45, 46, 47, 50, 51, 52, 53, 54, 55, 56, 57, 58 */};
        static Dictionary<uint, NumberingFormat> builtInDateTimeNumberFormats = builtInDateTimeNumberFormatIDs.ToDictionary(id => id, id => new NumberingFormat { NumberFormatId = id });
        static Regex dateTimeFormatRegex = new Regex(@"((?=([^[]*\[[^[\]]*\])*([^[]*[ymdhs]+[^\]]*))|.*\[(h|mm|ss)\].*)", RegexOptions.Compiled);

        static void Main(string[] args) {
            Program prova = new Program();
            prova.ReadFile();
        }

        void ReadFile()
        {

            var filePath = @"C:\\Users\\m.p\\Desktop\\report_fatturato_brevissimo.xlsx";
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, false))
                {
                    WorkbookPart workbookPart = doc.WorkbookPart;
                    SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
                    SharedStringTable sst = sstpart.SharedStringTable;

                    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                    Worksheet sheet = worksheetPart.Worksheet;

                    var cells = sheet.Descendants<Cell>();
                    var rows = sheet.Descendants<Row>();

                    Console.WriteLine("Row count = {0}", rows.LongCount());
                    Console.WriteLine("Cell count = {0}", cells.LongCount());

                    // Or... via each row
                    foreach (Row row in rows)
                    {
                        foreach (Cell c in row.Elements<Cell>())
                        {
                            if ((c.DataType != null) && (c.DataType == CellValues.SharedString))
                            {
                                int ssid = int.Parse(c.CellValue.Text);
                                string str = sst.ChildElements[ssid].InnerText;
                                Console.Write/*Line*/(/*"Shared string {0}: {1}", ssid, */str + "\t");
                            }
                            else
                            {
                                if (IsDateTimeCell(workbookPart, c) == true)
                                {
                                    int ssid = int.Parse(c.CellValue.Text);
                                    DateTime date = DateTime.FromOADate(Double.Parse(c.CellValue.Text));
                                    Console.Write/*Line*/(/*"Shared string {0}: {1}", ssid, */date + "\t");
                                }
                                else if (c.CellValue != null)
                                {
                                    Console.Write/*Line*/(/*"Cell contents: {0}", */c.CellValue.Text + "\t");
                                }
                            }
                        }
                        Console.WriteLine("");
                    }
                }
            }
            Console.Read();
        }

        public static Dictionary<uint, NumberingFormat> GetDateTimeCellFormats(WorkbookPart wbPart)
        {

//Error on the following instruction: NumberingFormats seems to be always null
            var dateNumberFormats = wbPart.WorkbookStylesPart.Stylesheet.NumberingFormats
                .Descendants<NumberingFormat>()
                .Where(nf => dateTimeFormatRegex.Match(nf.FormatCode.Value).Success)
                .ToDictionary(nf => nf.NumberFormatId.Value);

            var cellFormats = wbPart.WorkbookStylesPart.Stylesheet.CellFormats
                .Descendants<CellFormat>();

            var dateCellFormats = new Dictionary<uint, NumberingFormat>();
            uint styleIndex = 0;
            foreach (var cellFormat in cellFormats)
            {
                if (cellFormat.ApplyNumberFormat != null && cellFormat.ApplyNumberFormat.Value)
                {
                    if (dateNumberFormats.ContainsKey(cellFormat.NumberFormatId.Value))
                    {
                        dateCellFormats.Add(styleIndex, dateNumberFormats[cellFormat.NumberFormatId.Value]);
                    }
                    else if (builtInDateTimeNumberFormats.ContainsKey(cellFormat.NumberFormatId.Value))
                    {
                        dateCellFormats.Add(styleIndex, builtInDateTimeNumberFormats[cellFormat.NumberFormatId.Value]);
                    }
                }

                styleIndex++;
            }

            return dateCellFormats;
        }

        //Usage Example
        public static bool IsDateTimeCell(WorkbookPart wbPart, Cell cell)
        {
            if (cell.StyleIndex == null)
                return false;

            var dateTimeCellFormats = GetDateTimeCellFormats(wbPart);

            return dateTimeCellFormats.ContainsKey(cell.StyleIndex);
        }

    }
}
</code>```

答:
OpenXML has 164 built-in formats that Excel uses for basic formats in spreadsheet cells. The default DateTime formats are part of these built-in types.

Only if you create new format with Excel (custom format), these will be included in the NumberingFormats section of the Stylesheet.

I suggest you wrap your code like below to check for NumberingFormats, to avoid the NullReferenceException

```<code>if (wbPart.WorkbookStylesPart.Stylesheet.NumberingFormats != null)
        {
</code>```

Then you will need to add some code to detect for a datetime format.

Sample code:

```<code>        if (cellFormat?.NumberFormatId == 14)
        {
            double d = double.Parse(cell.CellValue.InnerText);

            string val = DateTime.FromOADate(d).ToString();
            return val;
        }
</code>```

As per this link - NumberFormatId 14 is a datetime number format with

MM-DD-YY
format. We can use the above sample to convert it to datetime value.

This SO article tries to determine the possible datetime styles. See some of the comments and the first link above for references to the specification which provides more detail.

Referred and added to the answer given by @Taterhead

Title: NumberingFormats is always null, why?

Body:
I'm writing a program that use OpenXML to read an excel file. The file contains also dates, so i need a function that recognize them. Here on stackoverflow i've found this solution: How to distinguish inline numbers from OLE Automation date numbers in OpenXML SpreadSheet? .

I've tryed to apply it to my code, but every time I get the following error:

"An unhandled exception of type 'System.NullReferenceException' occurred in OpenXML_Prova.exe

Additional information: Object reference not set to an instance of an object."

on the first line of the GetDateTimeCellFormats, in which it seems that NumberingFormats is always null.

Here is the complete code:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace OpenXML_Prova
{
    class Program
    {

        DocumentFormat.OpenXml.Spreadsheet.NumberingFormats numb = new NumberingFormats();

        static uint[] builtInDateTimeNumberFormatIDs = new uint[] { 14, 15, 16, 17, 18, 19, 20, 21, 22, /*27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 45, 46, 47, 50, 51, 52, 53, 54, 55, 56, 57, 58 */};
        static Dictionary<uint, NumberingFormat> builtInDateTimeNumberFormats = builtInDateTimeNumberFormatIDs.ToDictionary(id => id, id => new NumberingFormat { NumberFormatId = id });
        static Regex dateTimeFormatRegex = new Regex(@"((?=([^[]*\[[^[\]]*\])*([^[]*[ymdhs]+[^\]]*))|.*\[(h|mm|ss)\].*)", RegexOptions.Compiled);

        static void Main(string[] args) {
            Program prova = new Program();
            prova.ReadFile();
        }

        void ReadFile()
        {

            var filePath = @"C:\\Users\\m.p\\Desktop\\report_fatturato_brevissimo.xlsx";
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, false))
                {
                    WorkbookPart workbookPart = doc.WorkbookPart;
                    SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
                    SharedStringTable sst = sstpart.SharedStringTable;

                    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                    Worksheet sheet = worksheetPart.Worksheet;

                    var cells = sheet.Descendants<Cell>();
                    var rows = sheet.Descendants<Row>();

                    Console.WriteLine("Row count = {0}", rows.LongCount());
                    Console.WriteLine("Cell count = {0}", cells.LongCount());

                    // Or... via each row
                    foreach (Row row in rows)
                    {
                        foreach (Cell c in row.Elements<Cell>())
                        {
                            if ((c.DataType != null) && (c.DataType == CellValues.SharedString))
                            {
                                int ssid = int.Parse(c.CellValue.Text);
                                string str = sst.ChildElements[ssid].InnerText;
                                Console.Write/*Line*/(/*"Shared string {0}: {1}", ssid, */str + "\t");
                            }
                            else
                            {
                                if (IsDateTimeCell(workbookPart, c) == true)
                                {
                                    int ssid = int.Parse(c.CellValue.Text);
                                    DateTime date = DateTime.FromOADate(Double.Parse(c.CellValue.Text));
                                    Console.Write/*Line*/(/*"Shared string {0}: {1}", ssid, */date + "\t");
                                }
                                else if (c.CellValue != null)
                                {
                                    Console.Write/*Line*/(/*"Cell contents: {0}", */c.CellValue.Text + "\t");
                                }
                            }
                        }
                        Console.WriteLine("");
                    }
                }
            }
            Console.Read();
        }

        public static Dictionary<uint, NumberingFormat> GetDateTimeCellFormats(WorkbookPart wbPart)
        {

//Error on the following instruction: NumberingFormats seems to be always null
            var dateNumberFormats = wbPart.WorkbookStylesPart.Stylesheet.NumberingFormats
                .Descendants<NumberingFormat>()
                .Where(nf => dateTimeFormatRegex.Match(nf.FormatCode.Value).Success)
                .ToDictionary(nf => nf.NumberFormatId.Value);

            var cellFormats = wbPart.WorkbookStylesPart.Stylesheet.CellFormats
                .Descendants<CellFormat>();

            var dateCellFormats = new Dictionary<uint, NumberingFormat>();
            uint styleIndex = 0;
            foreach (var cellFormat in cellFormats)
            {
                if (cellFormat.ApplyNumberFormat != null && cellFormat.ApplyNumberFormat.Value)
                {
                    if (dateNumberFormats.ContainsKey(cellFormat.NumberFormatId.Value))
                    {
                        dateCellFormats.Add(styleIndex, dateNumberFormats[cellFormat.NumberFormatId.Value]);
                    }
                    else if (builtInDateTimeNumberFormats.ContainsKey(cellFormat.NumberFormatId.Value))
                    {
                        dateCellFormats.Add(styleIndex, builtInDateTimeNumberFormats[cellFormat.NumberFormatId.Value]);
                    }
                }

                styleIndex++;
            }

            return dateCellFormats;
        }

        //Usage Example
        public static bool IsDateTimeCell(WorkbookPart wbPart, Cell cell)
        {
            if (cell.StyleIndex == null)
                return false;

            var dateTimeCellFormats = GetDateTimeCellFormats(wbPart);

            return dateTimeCellFormats.ContainsKey(cell.StyleIndex);
        }

    }
}

Body:
OpenXML has 164 built-in formats that Excel uses for basic formats in spreadsheet cells. The default DateTime formats are part of these built-in types.

Only if you create new format with Excel (custom format), these will be included in the NumberingFormats section of the Stylesheet.

I suggest you wrap your code like below to check for NumberingFormats, to avoid the NullReferenceException

if (wbPart.WorkbookStylesPart.Stylesheet.NumberingFormats != null)
        {

Then you will need to add some code to detect for a datetime format.

Sample code:

        if (cellFormat?.NumberFormatId == 14)
        {
            double d = double.Parse(cell.CellValue.InnerText);

            string val = DateTime.FromOADate(d).ToString();
            return val;
        }

As per this link - NumberFormatId 14 is a datetime number format with

MM-DD-YY
format. We can use the above sample to convert it to datetime value.

This SO article tries to determine the possible datetime styles. See some of the comments and the first link above for references to the specification which provides more detail.

Referred and added to the answer given by @Taterhead


问:
Converting Long to Date in Java returns 1970
I have list with long values (for example: 1220227200, 1220832000, 1221436800...) which I downloaded from web service. I must convert it to Dates. Unfortunately this way, for example:

```<code>Date d = new Date(1220227200);
</code>```

returns 1 Jan 1970. Anyone know another way to convert it correctly?

答:
Because 1220227200 ms = 338,952 hours.
java.util.Date has constructor new Date(Long milliseconds) - Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
So, in your case just remember 1 sec = 1000 millisec</p>

Body:
I have list with long values (for example: 1220227200, 1220832000, 1221436800...) which I downloaded from web service. I must convert it to Dates. Unfortunately this way, for example:

Date d = new Date(1220227200);

returns 1 Jan 1970. Anyone know another way to convert it correctly?


问:
Discord.js Slash command mention user
Ive been trying to figure out how to get my hug command to mention both the sender and the recipient of the command. As well as when you start the command it'll ask for the sender to select someone to mention before the command is sent off (or is that built in? I don't know yet)

I have read over the docs of the user class and as well as read this post here but have come to the conclusion that both aren't using slash commands though which is what ive been taught of how to do, not using embeds or text for the commands, just a slash command. If there is any help to this that would be greatly appreciated!
Here's my resulting code so far though

```<code>const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('hug')
        .setDescription('Hug Someone'),
    async execute(interaction) {
        return interaction.reply(`${user} hugs ${user}`)
    },
};
</code>```

答:
You can get the author of the Interaction using the Interaction#user property.

To specify a User to hug you'll have to add a SlashCommandUserOption.

You can then get the User by using CommandInteractionOptionResolver#getUser

module.exports = {
    data: new SlashCommandBuilder()
        .setName('hug')
        .setDescription('Hug Someone')
        .addUserOption(option =>
            option
                .setName('user')
                .setDescription('The user you want to hug')
                .setRequired(true)
        ),
    async execute(interaction) {
        return interaction.reply(`${interaction.user} hugs ${interaction.options.getUser('user')}`)
    },
};
```

Title: Discord.js Slash command mention user

Body:
Ive been trying to figure out how to get my hug command to mention both the sender and the recipient of the command. As well as when you start the command it'll ask for the sender to select someone to mention before the command is sent off (or is that built in? I don't know yet)

I have read over the docs of the user class and as well as read this post here but have come to the conclusion that both aren't using slash commands though which is what ive been taught of how to do, not using embeds or text for the commands, just a slash command. If there is any help to this that would be greatly appreciated!
Here's my resulting code so far though

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('hug')
        .setDescription('Hug Someone'),
    async execute(interaction) {
        return interaction.reply(`${user} hugs ${user}`)
    },
};


问:
Conditional jump or move depends on uninitialized value(s) - C valgrind
I got this error:
==4024== Conditional jump or move depends on uninitialised value(s)
==4024==    at 0x400D69: constructBoardSpaces (in /a/fr-01/vol/home/stud/roniy02/oop/Ex3/Play)

and the function is:

```<code>static void constructBoardSpaces(char** array,int rows,int cols)
{
    int i=0,j=0;
    for (i = 0; i < rows; ++i)
    {
        for (j = 0; j < cols; ++j)
        {
            if((array[i][j])!='X'&&(array[i][j]!='O'))
                {
                array[i][j]=' ';
                }
        }
    }
}
</code>```

can't figure out what is the problem.
Thanks

答:
are you sure you initialized the two dimensional array before you enter that loop? Otherwise I would say the problem is probably in the if statement where you read from the array:</p>

```<code>if((array[i][j])!='X'&&(array[i][j]!='O'))
</code>```

Body:
I got this error:
==4024== Conditional jump or move depends on uninitialised value(s)
==4024==    at 0x400D69: constructBoardSpaces (in /a/fr-01/vol/home/stud/roniy02/oop/Ex3/Play)

and the function is:

static void constructBoardSpaces(char** array,int rows,int cols)
{
    int i=0,j=0;
    for (i = 0; i < rows; ++i)
    {
        for (j = 0; j < cols; ++j)
        {
            if((array[i][j])!='X'&&(array[i][j]!='O'))
                {
                array[i][j]=' ';
                }
        }
    }
}

can't figure out what is the problem.
Thanks

Body:
are you sure you initialized the two dimensional array before you enter that loop? Otherwise I would say the problem is probably in the if statement where you read from the array:

if((array[i][j])!='X'&&(array[i][j]!='O'))


问:
importing rpy2.objects gives error: unable to initialize the JiT
I am trying to incorporate some R code in the python environment. I imported rpy2 package successfully. However, I get the error when I try to import rpy2.objects

```<code>from rpy2.robjects import pandas2ri
</code>```

I get the below error

```<code>Error in glue(.Internal(R.home()), "library", "base", "R", "base", sep =
.Platform$file.sep) :
  4 arguments passed to .Internal(paste) which requires 3
Error: could not find function "attach"
Error: object '.ArgsEnv' not found
Fatal error: unable to initialize the JIT
Restarting kernel...
</code>```

I found some of the related questions in SE here here and here. But, none of them seem to work.

答:
Form what I've gathered: if you have R installed on your machine it will avtomatically use the system's installation of R instead of the version rpy2 requires. To omit that I just added

```<code>import os
os.environ['R_HOME'] = '/Users/<your user>/anaconda3/envs/<env name>/lib/R'
</code>```

before I imported anything from rpy2. If it doesn't work, you may have to uninstall R from your machine completely.

Body:
I am trying to incorporate some R code in the python environment. I imported rpy2 package successfully. However, I get the error when I try to import rpy2.objects

from rpy2.robjects import pandas2ri

I get the below error

Error in glue(.Internal(R.home()), "library", "base", "R", "base", sep =
.Platform$file.sep) :
  4 arguments passed to .Internal(paste) which requires 3
Error: could not find function "attach"
Error: object '.ArgsEnv' not found
Fatal error: unable to initialize the JIT
Restarting kernel...

I found some of the related questions in SE here here and here. But, none of them seem to work.

Body:
Form what I've gathered: if you have R installed on your machine it will avtomatically use the system's installation of R instead of the version rpy2 requires. To omit that I just added

import os
os.environ['R_HOME'] = '/Users/<your user>/anaconda3/envs/<env name>/lib/R'

before I imported anything from rpy2. If it doesn't work, you may have to uninstall R from your machine completely.


问:
SwiftUI 2.0 Change DatePicker background
Is there anyway to change the background color of the DatePicker view? I have the following Picker:

```<code>DatePicker(selection: $form.start, in: Date()..., displayedComponents: .date) {}
            .padding(.vertical, 6)
            .labelsHidden()
            .accentColor(.black)
</code>```

But the picker has that grayish tint around the date (See image below). I just want the entire background to be white. I tried .background(Color.white) but that doesn't do anything. How can I make the entire background white?

答:
You can do this as follows:

```<code>dateTimePicker.setValue(UIColor.white, forKey: "backgroundColor")
</code>```

Body:
Is there anyway to change the background color of the DatePicker view? I have the following Picker:

DatePicker(selection: $form.start, in: Date()..., displayedComponents: .date) {}
            .padding(.vertical, 6)
            .labelsHidden()
            .accentColor(.black)

But the picker has that grayish tint around the date (See image below). I just want the entire background to be white. I tried .background(Color.white) but that doesn't do anything. How can I make the entire background white?

Body:
You can do this as follows:

dateTimePicker.setValue(UIColor.white, forKey: "backgroundColor")


问:
Getting the object using one of it's property's values
I have a json that, lets say it looks something like this:

```<code>[
  {
  "name":"Foo"
  "nickname":"Lorem Ipsum"
  },
  {
  "name":"Bar"
  "nickname":"Dolor Sit"
  }
]
</code>```

Now, i want to find the nickname of something using the value of nickname to find it. Is there a way to do this in JavaScript? If so, how?

答:
Given the input should be corrected in a way pointed out in my comment to be a proper and correct JSON, this function will serve the purpose.

function findByName(name) {
  const i = [{
      "name": "Foo",
      "nickname": "Lorem Ipsum"
    },
    {
      "name": "Bar",
      "nickname": "Dolor Sit"
    }
  ]

  return i.find(e => e.name === name).nickname;
}

const res = findByName("Foo"); // ==> "Lorem Ipsum"
console.log(res);```

Body:
I have a json that, lets say it looks something like this:

[
  {
  "name":"Foo"
  "nickname":"Lorem Ipsum"
  },
  {
  "name":"Bar"
  "nickname":"Dolor Sit"
  }
]

Now, i want to find the nickname of something using the value of nickname to find it. Is there a way to do this in JavaScript? If so, how?


问:
Select only records without future dates via join
There are 2 tables: events and dates. One event could have multiple dates.

I would like to select only those events which don't have corresponding dates in the future.

I tried the following query

```<code>SELECT e.id_event FROM events e RIGHT JOIN dates d ON e.id_event=d.id_event AND !(d.date > NOW())
</code>```

but it shows events which has both dates in past and in future.

Sample data

Events table

id_event

1

2

Dates table

id_event
date

1
2020-10-10

1
2030-10-10

2
2020-10-10

The query should return only one record, id_event =  2.

答:
NOW()is timestamp : you want CURDATE
try

```<code>SELECT e.id_event
FROM events e RIGHT
JOIN dates d
ON e.id_event=d.id_event AND d.date <= CURDATE();
</code>```

<= CURDATE() is before or including today which is the same thing as NOT IN THE FUTURE.

Body:
There are 2 tables: events and dates. One event could have multiple dates.

I would like to select only those events which don't have corresponding dates in the future.

I tried the following query

SELECT e.id_event FROM events e RIGHT JOIN dates d ON e.id_event=d.id_event AND !(d.date > NOW())

but it shows events which has both dates in past and in future.

Sample data

Events table

id_event

1

2

Dates table

id_event
date

1
2020-10-10

1
2030-10-10

2
2020-10-10

The query should return only one record, id_event =  2.

Body:
NOW()is timestamp : you want CURDATE
try

SELECT e.id_event
FROM events e RIGHT
JOIN dates d
ON e.id_event=d.id_event AND d.date <= CURDATE();

<= CURDATE() is before or including today which is the same thing as NOT IN THE FUTURE.