问:
What is the use case of @Import annotation?
According to official doc:

Annotation Type Configuration

Indicates that a class declares one or more @Bean methods and may be
processed by the Spring container to generate bean definitions...

@Configuration classes may be composed using the @Import annotation,
not unlike the way that  works in Spring XML. Because
@Configuration objects are managed as Spring beans within the
container..

But i can also use @Configuration annotation without @Import. I have tested the code listed below and it works as expected. So what is the purpose to use @Import?

DispatcherServletInitializer

```<code>public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

 }
</code>```

WebMvcConfigurerAdapter

```<code>@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "package.name" })
// @Import(OptionalConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
    // ...
}
</code>```

OptionalConfig

```<code>@Configuration
public class OptionalConfig {

    @Bean(name = "myClass")
    public MyClass myClass() {
        return new MyClass();
    }
}
</code>```

Service

```<code>@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private MyClass myClass;    // yes, it works

    // ...
}
</code>```

答:
@Import works great when for some reasons you need to register not all but some of the components from a package. In such case @ComponentScan would be too complicated.

See details in the Spring boot component scan include a single class question.

Body:
According to official doc:

Annotation Type Configuration

Indicates that a class declares one or more @Bean methods and may be
processed by the Spring container to generate bean definitions...

@Configuration classes may be composed using the @Import annotation,
not unlike the way that  works in Spring XML. Because
@Configuration objects are managed as Spring beans within the
container..

But i can also use @Configuration annotation without @Import. I have tested the code listed below and it works as expected. So what is the purpose to use @Import?

DispatcherServletInitializer

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

 }

WebMvcConfigurerAdapter

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "package.name" })
// @Import(OptionalConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
    // ...
}

OptionalConfig

@Configuration
public class OptionalConfig {

    @Bean(name = "myClass")
    public MyClass myClass() {
        return new MyClass();
    }
}

Service

@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private MyClass myClass;    // yes, it works

    // ...
}


来源: stackexchange

问:
No TabController for TabBarView flutter
I am trying add TabBar by using the below code:

```<code>TabBarView(
                        children: [
                          Icon(Icons.directions_car),
                          Icon(Icons.directions_transit),
                          Icon(Icons.directions_bike),
                        ],
                      ),
</code>```

but I found the below error:

```<code>No TabController for TabBarView.
</code>```

and this is whole code:

```<code>import '../providers/properties.dart';
import '../providers/cities.dart';
import '../providers/property.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/properties_grid.dart';
import '../app_theme.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  int currentTab = 0;
  final PageStorageBucket bucket = PageStorageBucket();
  var _showOnlyFavorites = false;
  // List<HomeList> homeList = HomeList.homeList;
  AnimationController animationController;
  bool multiple = true;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    super.initState();
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 0));
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // final properties = Provider.of<Properties>(context, listen: false);
    return Scaffold(
      extendBody: true,
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {},
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: BottomAppBar(
        elevation: 0,
        shape: CircularNotchedRectangle(),
        notchMargin: 10,
        child: Container(
          height: 60,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  MaterialButton(
                    padding: EdgeInsets.all(0),
                    minWidth: 155,
                    onPressed: () {
                      setState(() {
                        // currentScreen =
                        //     Chat(); // if user taps on this dashboard tab will be active
                        currentTab = 1;
                      });
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(
                          Icons.home,
                          color: currentTab == 1 ? Colors.blue : Colors.grey,
                        ),
                        Text(
                          'Home',
                          style: TextStyle(
                            color: currentTab == 1 ? Colors.blue : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),

              // Right Tab bar icons

              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  MaterialButton(
                    padding: EdgeInsets.all(0),
                    minWidth: 60,
                    onPressed: () {
                      setState(() {
                        // currentScreen =
                        //     Settings(); // if user taps on this dashboard tab will be active
                        currentTab = 3;
                      });
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(
                          Icons.view_list,
                          color: currentTab == 3 ? Colors.blue : Colors.grey,
                        ),
                        Text(
                          'Property List',
                          style: TextStyle(
                            color: currentTab == 3 ? Colors.blue : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                  MaterialButton(
                    padding: EdgeInsets.all(0),
                    minWidth: 77,
                    onPressed: () {
                      setState(() {
                        // currentScreen =
                        //     Settings(); // if user taps on this dashboard tab will be active
                        currentTab = 4;
                      });
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(
                          Icons.location_searching,
                          color: currentTab == 4 ? Colors.blue : Colors.grey,
                        ),
                        Text(
                          'Map',
                          style: TextStyle(
                            color: currentTab == 4 ? Colors.blue : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
      backgroundColor: AppTheme.white,
      body: Stack(
        children: <Widget>[
          FutureBuilder<bool>(
            future: getData(),
            builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
              if (!snapshot.hasData) {
                return const SizedBox();
              } else {
                return Padding(
                  padding:
                      EdgeInsets.only(top: MediaQuery.of(context).padding.top),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      appBar(),
                      TabBarView(
                        children: [
                          Icon(Icons.directions_car),
                          Icon(Icons.directions_transit),
                          Icon(Icons.directions_bike),
                        ],
                      ),
                      Expanded(
                        child: FutureBuilder<bool>(
                          future: getData(),
                          builder: (BuildContext context,
                              AsyncSnapshot<bool> snapshot) {
                            if (!snapshot.hasData) {
                              return const SizedBox();
                            } else {
                              return ChangeNotifierProvider(
                                create: (context) => Properties(),
                                child: PropertiesGrid(_showOnlyFavorites),
                              );
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                );
              }
            },
          ),
        ],
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    Icons.location_on,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
</code>```

So How Can I solve this problem...

答:
How can TabBar get to know about the TabBarView? There should be a connection between them to change when tab press or if swap from view right?

So, to connect both two, you have to either wrap your parent widget using DefaultTabController or providing a TabController for TabBar and TabBarView to controll and configure Tabs.

Flutter cookbook example for DefaultTabController:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Using TabController(Example from doc):

```<code>class MyTabbedPage extends StatefulWidget {
  const MyTabbedPage({ Key key }) : super(key: key);
  @override
  _MyTabbedPageState createState() => _MyTabbedPageState();
}

class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {
  final List<Tab> myTabs = <Tab>[
    Tab(text: 'LEFT'),
    Tab(text: 'RIGHT'),
  ];

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: myTabs.length);
  }

 @override
 void dispose() {
   _tabController.dispose();
   super.dispose();
 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        bottom: TabBar(
          controller: _tabController,
          tabs: myTabs,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: myTabs.map((Tab tab) {
          final String label = tab.text.toLowerCase();
          return Center(
            child: Text(
              'This is the $label tab',
              style: const TextStyle(fontSize: 36),
            ),
          );
        }).toList(),
      ),
    );
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: No TabController for TabBarView flutter

Body:
I am trying add TabBar by using the below code:

TabBarView(
                        children: [
                          Icon(Icons.directions_car),
                          Icon(Icons.directions_transit),
                          Icon(Icons.directions_bike),
                        ],
                      ),

but I found the below error:

No TabController for TabBarView.

and this is whole code:

import '../providers/properties.dart';
import '../providers/cities.dart';
import '../providers/property.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/properties_grid.dart';
import '../app_theme.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  int currentTab = 0;
  final PageStorageBucket bucket = PageStorageBucket();
  var _showOnlyFavorites = false;
  // List<HomeList> homeList = HomeList.homeList;
  AnimationController animationController;
  bool multiple = true;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    super.initState();
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 0));
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // final properties = Provider.of<Properties>(context, listen: false);
    return Scaffold(
      extendBody: true,
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {},
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: BottomAppBar(
        elevation: 0,
        shape: CircularNotchedRectangle(),
        notchMargin: 10,
        child: Container(
          height: 60,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  MaterialButton(
                    padding: EdgeInsets.all(0),
                    minWidth: 155,
                    onPressed: () {
                      setState(() {
                        // currentScreen =
                        //     Chat(); // if user taps on this dashboard tab will be active
                        currentTab = 1;
                      });
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(
                          Icons.home,
                          color: currentTab == 1 ? Colors.blue : Colors.grey,
                        ),
                        Text(
                          'Home',
                          style: TextStyle(
                            color: currentTab == 1 ? Colors.blue : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),

              // Right Tab bar icons

              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  MaterialButton(
                    padding: EdgeInsets.all(0),
                    minWidth: 60,
                    onPressed: () {
                      setState(() {
                        // currentScreen =
                        //     Settings(); // if user taps on this dashboard tab will be active
                        currentTab = 3;
                      });
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(
                          Icons.view_list,
                          color: currentTab == 3 ? Colors.blue : Colors.grey,
                        ),
                        Text(
                          'Property List',
                          style: TextStyle(
                            color: currentTab == 3 ? Colors.blue : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                  MaterialButton(
                    padding: EdgeInsets.all(0),
                    minWidth: 77,
                    onPressed: () {
                      setState(() {
                        // currentScreen =
                        //     Settings(); // if user taps on this dashboard tab will be active
                        currentTab = 4;
                      });
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(
                          Icons.location_searching,
                          color: currentTab == 4 ? Colors.blue : Colors.grey,
                        ),
                        Text(
                          'Map',
                          style: TextStyle(
                            color: currentTab == 4 ? Colors.blue : Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
      backgroundColor: AppTheme.white,
      body: Stack(
        children: <Widget>[
          FutureBuilder<bool>(
            future: getData(),
            builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
              if (!snapshot.hasData) {
                return const SizedBox();
              } else {
                return Padding(
                  padding:
                      EdgeInsets.only(top: MediaQuery.of(context).padding.top),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      appBar(),
                      TabBarView(
                        children: [
                          Icon(Icons.directions_car),
                          Icon(Icons.directions_transit),
                          Icon(Icons.directions_bike),
                        ],
                      ),
                      Expanded(
                        child: FutureBuilder<bool>(
                          future: getData(),
                          builder: (BuildContext context,
                              AsyncSnapshot<bool> snapshot) {
                            if (!snapshot.hasData) {
                              return const SizedBox();
                            } else {
                              return ChangeNotifierProvider(
                                create: (context) => Properties(),
                                child: PropertiesGrid(_showOnlyFavorites),
                              );
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                );
              }
            },
          ),
        ],
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    Icons.location_on,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

So How Can I solve this problem...

Body:
How can TabBar get to know about the TabBarView? There should be a connection between them to change when tab press or if swap from view right?

So, to connect both two, you have to either wrap your parent widget using DefaultTabController or providing a TabController for TabBar and TabBarView to controll and configure Tabs.

Flutter cookbook example for DefaultTabController:

import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

Using TabController(Example from doc):

class MyTabbedPage extends StatefulWidget {
  const MyTabbedPage({ Key key }) : super(key: key);
  @override
  _MyTabbedPageState createState() => _MyTabbedPageState();
}

class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {
  final List<Tab> myTabs = <Tab>[
    Tab(text: 'LEFT'),
    Tab(text: 'RIGHT'),
  ];

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: myTabs.length);
  }

 @override
 void dispose() {
   _tabController.dispose();
   super.dispose();
 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        bottom: TabBar(
          controller: _tabController,
          tabs: myTabs,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: myTabs.map((Tab tab) {
          final String label = tab.text.toLowerCase();
          return Center(
            child: Text(
              'This is the $label tab',
              style: const TextStyle(fontSize: 36),
            ),
          );
        }).toList(),
      ),
    );
  }
}


问:
Kafka Streams Retry PAPI and dead letter
I am trying to implement a retry logic within kafka streams processor topology in the event there was an exception producing to a sink topic.

I am using a custom ProductionExceptionHandler to be able to catch exception that happen on "producer.send" to the sink topic upon context.forward

What criteria should I use to be able resend the message to an alternate sink topic if there was an exception sending to original sink topic. Could this be deduced from type of exception in producer exception handler without compromising the transactional nature of the internal producer in Kafka streams.

If we decide to produce to a dead letter queue from production exception handler in some unrecoverable errors, could this be done within the context of "EOS" guarantee or it has to be a custom producer not known to the topology.

答:
Kafka Streams has not built-in support for dead-letter-queue. Hence, you are "on your own" to implement it.

What criteria should I use to be able resend the message to an alternate sink topic if there was an exception sending to original sink topic.

Not sure what you mean by this? Can you elaborate?

Could this be deduced from type of exception in producer exception handler

Also not sure about this part.

without compromising the transactional nature of the internal producer in Kafka streams.

That is not possible. You have no access to the internal producer.

If we decide to produce to a dead letter queue from production exception handler in some unrecoverable errors, could this be done within the context of "EOS" guarantee or it has to be a custom producer not known to the topology.

You would need to maintain your own producer and thus it's out-of-scope for EOS.


问:
Apache POI Excel shows only data label and cut chart
Question 1. I just show only data labels on the bar chart.

Question 2. The chart is cut the bar. The first category and the last category.

You can see mixed labels, 'right axis' + 'bottom axis' + 'data value'.

I want to see only the data labels.

I want to display three of bottom of category '1'. And also three of bottom of category '64'.

How can I do this?

Language - Java

Dependency

```<code><dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>
</code>```

I referenced here.
(https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/BarChart.java)

```<code>private void createChart(XSSFSheet sheet,
                         String chartTitle,
                         String leftTitle,
                         String bottomAxisTitle,
                         List<Map<String, Object>> reportData,
                         Map<String, String> capMap,
                         String rwRatio,
                         String resultType,
                         String name,
                         Integer startRownum,
                         Integer startCellIndex,
                         Integer lastRownum,
                         Integer lastCellIndex) {

    XSSFDrawing drawing = (XSSFDrawing)sheet.createDrawingPatriarch();

    XSSFClientAnchor anchor = drawing.createAnchor(
        10, 10, 110, 110, startCellIndex,
        startRownum, lastCellIndex, lastRownum); //int dx1, int dy1, int dx2,
                                                 //int dy2, int col1, int row1,
                                                 //int col2, int row2

    XSSFChart chart = drawing.createChart(anchor);

    chart.setTitleText(chartTitle);
    chart.setTitleOverlay(false);
    XDDFChartLegend legend = chart.getOrAddLegend();
    legend.setPosition(LegendPosition.TOP_RIGHT);

    // Use a category axis for the bottom axis.
    XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
    bottomAxis.setTitle(bottomAxisTitle);

    XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
    leftAxis.setTitle(leftTitle);
    leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

    XDDFChartData data = chart.createData(ChartTypes.BAR, bottomAxis, leftAxis); // Chart type

    XDDFDataSource<String> xs = XDDFDataSourcesFactory.fromArray(qdList);
    String title = "";

    for(Map<String, Object> report : reportData) {
        List <Double>iops = new ArrayList<>();

        List<Map<String, Object>> fios = (List<Map<String, Object>>) report.get("myData");
        TestMain tm =  (TestMain) report.get("testMain");
        title = capMap.get(tm.getId().toString());
        for(String qd : qdList) {
            for(Map<String, Object> fio : fios) {
                iops.add(Double.parseDouble(fio.get(name).toString()));
            }
        }

        Double [] values = new Double[iops.size()];
        for(int i = 0 ; i < iops.size(); i++) {
            values[i] = iops.get(i);
        }

        XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromArray(values);
        XDDFChartData.Series series1 = data.addSeries(xs, ys1);

        series1.setTitle(title, null);
        series1.setShowLeaderLines(true);

    }

    chart.plot(data);
    chart.displayBlanksAs(DisplayBlanks.SPAN);

    XDDFBarChartData bar = (XDDFBarChartData) data;
    bar.setBarDirection(BarDirection.COL);

    List<PresetColor> color = colors();
    for(int idx = 0 ; idx < reportData.size() ; idx++) {
        solidFillSeries(data, idx, color.get(idx));
    }

private static void solidFillSeries(XDDFChartData data, int index, PresetColor color) {

    XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color));
    XDDFChartData.Series series = data.getSeries().get(index);
    XDDFShapeProperties properties = series.getShapeProperties();
    if (properties == null) {
        properties = new XDDFShapeProperties();
    }
    properties.setFillProperties(fill);
    series.setShapeProperties(properties);
    series.setShowLeaderLines(true);
}
</code>```

答:
I found the first answer!!!

I added a dependency:

```<code><dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
    <version>1.3</version>
</dependency>
</code>```

I added some code.

```<code>int seriesNr = 0;

chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.CTR);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowVal().setVal(true);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowLegendKey().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowCatName().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowSerName().setVal(false);

chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.CTR);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowVal().setVal(true);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowLegendKey().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowCatName().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowSerName().setVal(false);
</code>```

Here is the changed chart image.

seriesNr is data of index getSerArray(seriesNr).

Body:
Question 1. I just show only data labels on the bar chart.

Question 2. The chart is cut the bar. The first category and the last category.

You can see mixed labels, 'right axis' + 'bottom axis' + 'data value'.

I want to see only the data labels.

I want to display three of bottom of category '1'. And also three of bottom of category '64'.

How can I do this?

Language - Java

Dependency

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>

I referenced here.
(https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/BarChart.java)

private void createChart(XSSFSheet sheet,
                         String chartTitle,
                         String leftTitle,
                         String bottomAxisTitle,
                         List<Map<String, Object>> reportData,
                         Map<String, String> capMap,
                         String rwRatio,
                         String resultType,
                         String name,
                         Integer startRownum,
                         Integer startCellIndex,
                         Integer lastRownum,
                         Integer lastCellIndex) {

    XSSFDrawing drawing = (XSSFDrawing)sheet.createDrawingPatriarch();

    XSSFClientAnchor anchor = drawing.createAnchor(
        10, 10, 110, 110, startCellIndex,
        startRownum, lastCellIndex, lastRownum); //int dx1, int dy1, int dx2,
                                                 //int dy2, int col1, int row1,
                                                 //int col2, int row2

    XSSFChart chart = drawing.createChart(anchor);

    chart.setTitleText(chartTitle);
    chart.setTitleOverlay(false);
    XDDFChartLegend legend = chart.getOrAddLegend();
    legend.setPosition(LegendPosition.TOP_RIGHT);

    // Use a category axis for the bottom axis.
    XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
    bottomAxis.setTitle(bottomAxisTitle);

    XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
    leftAxis.setTitle(leftTitle);
    leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

    XDDFChartData data = chart.createData(ChartTypes.BAR, bottomAxis, leftAxis); // Chart type

    XDDFDataSource<String> xs = XDDFDataSourcesFactory.fromArray(qdList);
    String title = "";

    for(Map<String, Object> report : reportData) {
        List <Double>iops = new ArrayList<>();

        List<Map<String, Object>> fios = (List<Map<String, Object>>) report.get("myData");
        TestMain tm =  (TestMain) report.get("testMain");
        title = capMap.get(tm.getId().toString());
        for(String qd : qdList) {
            for(Map<String, Object> fio : fios) {
                iops.add(Double.parseDouble(fio.get(name).toString()));
            }
        }

        Double [] values = new Double[iops.size()];
        for(int i = 0 ; i < iops.size(); i++) {
            values[i] = iops.get(i);
        }

        XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromArray(values);
        XDDFChartData.Series series1 = data.addSeries(xs, ys1);

        series1.setTitle(title, null);
        series1.setShowLeaderLines(true);

    }

    chart.plot(data);
    chart.displayBlanksAs(DisplayBlanks.SPAN);

    XDDFBarChartData bar = (XDDFBarChartData) data;
    bar.setBarDirection(BarDirection.COL);

    List<PresetColor> color = colors();
    for(int idx = 0 ; idx < reportData.size() ; idx++) {
        solidFillSeries(data, idx, color.get(idx));
    }

private static void solidFillSeries(XDDFChartData data, int index, PresetColor color) {

    XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color));
    XDDFChartData.Series series = data.getSeries().get(index);
    XDDFShapeProperties properties = series.getShapeProperties();
    if (properties == null) {
        properties = new XDDFShapeProperties();
    }
    properties.setFillProperties(fill);
    series.setShapeProperties(properties);
    series.setShowLeaderLines(true);
}

Body:
I found the first answer!!!

I added a dependency:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
    <version>1.3</version>
</dependency>

I added some code.

int seriesNr = 0;

chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.CTR);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowVal().setVal(true);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowLegendKey().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowCatName().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowSerName().setVal(false);

chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.CTR);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowVal().setVal(true);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowLegendKey().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowCatName().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(1).getDLbls().addNewShowSerName().setVal(false);

Here is the changed chart image.

seriesNr is data of index getSerArray(seriesNr).


问:
Native screeshot
After looking for a long time on how to take a Webview screenshot, I found this package - native_screenshot.

The issue is, it works in debug mode, but not in production mode - even when using the example posted in pub.dev.

I've added the required permission to the android manifest and still can't get it working.

I've reported the issue to the dev, still waiting for an answer. I was wondering if anyone here can help.

I need help to make this works. All help is appreciated. Thanks

答:
The webview_flutter plugin doesn't offer a way or a method to take the screenshot of the WebView.
So, you can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

To take a screenshot, you can use InAppWebViewController.takeScreenshot method, that takes a screenshot (in PNG format) of the WebView's visible viewport and returns a Uint8List.

Here is an example that takes a screenshot of the WebView when the page stops loading and shows an alert dialog with the corresponding screenshot image:

import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(initialRoute: '/', routes: {
      '/': (context) => InAppWebViewExampleScreen(),
    });
  }
}

class InAppWebViewExampleScreen extends StatefulWidget {
  @override
  _InAppWebViewExampleScreenState createState() =>
      new _InAppWebViewExampleScreenState();
}

class _InAppWebViewExampleScreenState extends State<InAppWebViewExampleScreen> {
  InAppWebViewController webView;
  Uint8List screenshotBytes;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("InAppWebView")),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "https://github.com/flutter",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {},
            onLoadStop: (InAppWebViewController controller, String url) async {
              screenshotBytes = await controller.takeScreenshot();
              showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    content: Image.memory(screenshotBytes),
                  );
                },
              );
            },
          ))
        ])));
  }
}
```

Title: Native screeshot


问:
Overflow-x:hidden; on mobile device not working
I hope you guys can help me cause I cant seem to wrap my head arroud this. I build a one-page site which works fine, except for one thing, which is the overflow-x:hidden on the tablet viewport (and probably smartphone too, havent tested that yet)

Despite the body having body {overflow-x:hidden;} which works fine within normal browsers on the pc, i am able to move to the side for about 25 pixels or so, cause thats the overflow of my rotated div, that sticks out of the screen, which i wanted to hide.

Is there a way to fix this? I supplied below part of the head and html / css

The viewport meta tag.

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

The CSS applied to the media queries and they respective elements that overflow

```<code>@media only screen and (max-width: 992px){
    #skills, #experience    {overflow-x:hidden;}
}
@media (max-width: 479px){
    body                    {overflow-x:hidden;}
}
</code>```

And the regular CSS applied to the html / body tags

```<code>body, html  {height: 100%;width: 100%;font-family: 'Source Sans Pro',Helvetica,Arial,sans-serif;color: #757575; overflow-x:hidden;}
</code>```

The id's #skills and #experience have a class called .hoek  which is defined as followed and causes the overflow.

```<code>    .hoek    {margin: 0 -50px;
              -webkit-transform-origin:left center;
              -moz-transform-origin:left center;
              -o-transform-origin:left center;
              -ms-transform-origin:left center;
              margin-top: -175px;
              -webkit-transform:rotate(5deg);
              -moz-transform:rotate(5deg);
              -o-transform:rotate(5deg);
              -ms-transform:rotate(5deg);
              z-index: 20;
    }
</code>```

I must point out, I think, that the #skills and #experience are sections and not divs. I am not sure if that might be a problem within the code, but I thought not. If there is anymore information that is needed, please let me know, but I thought I had covered the bases here.

I dont know where to begin with a fiddle, so I supply you just the test link of the site: http://www.jellyfishwebdesign.nl/Joost/index.php

答:
if you applied overflow-x:hidden to the body, you might wanna apply to html too.

body,html {
  overflow-x:hidden;
}
```

ContentLicense: CC BY-SA 3.0

Body:
I hope you guys can help me cause I cant seem to wrap my head arroud this. I build a one-page site which works fine, except for one thing, which is the overflow-x:hidden on the tablet viewport (and probably smartphone too, havent tested that yet)

Despite the body having body {overflow-x:hidden;} which works fine within normal browsers on the pc, i am able to move to the side for about 25 pixels or so, cause thats the overflow of my rotated div, that sticks out of the screen, which i wanted to hide.

Is there a way to fix this? I supplied below part of the head and html / css

The viewport meta tag.

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

The CSS applied to the media queries and they respective elements that overflow

@media only screen and (max-width: 992px){
    #skills, #experience    {overflow-x:hidden;}
}
@media (max-width: 479px){
    body                    {overflow-x:hidden;}
}

And the regular CSS applied to the html / body tags

body, html  {height: 100%;width: 100%;font-family: 'Source Sans Pro',Helvetica,Arial,sans-serif;color: #757575; overflow-x:hidden;}

The id's #skills and #experience have a class called .hoek  which is defined as followed and causes the overflow.

    .hoek    {margin: 0 -50px;
              -webkit-transform-origin:left center;
              -moz-transform-origin:left center;
              -o-transform-origin:left center;
              -ms-transform-origin:left center;
              margin-top: -175px;
              -webkit-transform:rotate(5deg);
              -moz-transform:rotate(5deg);
              -o-transform:rotate(5deg);
              -ms-transform:rotate(5deg);
              z-index: 20;
    }

I must point out, I think, that the #skills and #experience are sections and not divs. I am not sure if that might be a problem within the code, but I thought not. If there is anymore information that is needed, please let me know, but I thought I had covered the bases here.

I dont know where to begin with a fiddle, so I supply you just the test link of the site: http://www.jellyfishwebdesign.nl/Joost/index.php


问:
Intellij Maven Test Failed
I"m running selenium automation code on intellij but it shows test failed but my code is empty test only. The test result shows passed but this warning bothering me

Error log:
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test (default-test) on project dsf-automation: There are test failures.

```<code>Please refer to C:\Users\peter.wong\IdeaProjects\dsf-automation\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
There was an error in the forked process
null
org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
null
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:657)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:283)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:246)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1161)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1002)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:848)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>dsf-automation</groupId>
    <artifactId>dsf-automation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                    <!--  <configuration>
                          <release>12</release>
                          <compilerArgs>enable-preview</compilerArgs>
                    </configuration>-->
                    <configuration>
                        <source>1.9</source>
                        <target>1.9</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M3</version>
                    <configuration>
                        <includes>
                            <include>RestWebServiceTestManager.java</include>
                            <include>FirefoxTestManager.java</include>
                        </includes>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>

    <dependencies>

        <!--=========================== Selenium ========================== -->
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>6.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-support</artifactId>
            <version>3.14.0</version>
        </dependency>

        <!--=============================Spring Framework ===================== -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-test</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <!--============================Rest Assured========================== -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.scribejava</groupId>
            <artifactId>scribejava-apis</artifactId>
            <version>2.5.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <!--=========================== Java Mail ==============================-->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.6.2</version>
        </dependency>

        <dependency>
            <groupId>com.github.bbottema</groupId>
            <artifactId>emailaddress-rfc2822</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.5</version>
        </dependency>

        <dependency>
            <groupId>io.codearte.jfairy</groupId>
            <artifactId>jfairy</artifactId>
            <version>0.5.9</version>
        </dependency>

        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>0.16</version>
        </dependency>

        <!-- ========================= Extent Report =======================-->
        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.1.5</version>
        </dependency>

        <!-- ======================= Log4j 2 =========================================== -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.1</version>
        </dependency>

        <!--============================ MySQL Driver ====================-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!--============================= Mongo DB Driver ====================-->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.2</version>
        </dependency>
        <!--============================= POI ============================-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

        <dependency>
            <groupId>com.deque</groupId>
            <artifactId>axe-selenium</artifactId>
            <version>2.1</version>
        </dependency>

    </dependencies>

</project>
</code>```

Please help me. Thanks.

答:
Added

```<code><testFailureIgnore>true</testFailureIgnore>
<shutdown>kill</shutdown>
</code>```

to surefire plugin configuration.

Title: Intellij Maven Test Failed

Body:
I"m running selenium automation code on intellij but it shows test failed but my code is empty test only. The test result shows passed but this warning bothering me

Error log:
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test (default-test) on project dsf-automation: There are test failures.

Please refer to C:\Users\peter.wong\IdeaProjects\dsf-automation\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
There was an error in the forked process
null
org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
null
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:657)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:283)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:246)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1161)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1002)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:848)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>dsf-automation</groupId>
    <artifactId>dsf-automation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>

                    <configuration>
                        <source>1.9</source>
                        <target>1.9</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M3</version>
                    <configuration>
                        <includes>
                            <include>RestWebServiceTestManager.java</include>
                            <include>FirefoxTestManager.java</include>
                        </includes>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>

    <dependencies>

        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>6.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-support</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-test</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.scribejava</groupId>
            <artifactId>scribejava-apis</artifactId>
            <version>2.5.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.6.2</version>
        </dependency>

        <dependency>
            <groupId>com.github.bbottema</groupId>
            <artifactId>emailaddress-rfc2822</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.5</version>
        </dependency>

        <dependency>
            <groupId>io.codearte.jfairy</groupId>
            <artifactId>jfairy</artifactId>
            <version>0.5.9</version>
        </dependency>

        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>0.16</version>
        </dependency>

        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.1.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

        <dependency>
            <groupId>com.deque</groupId>
            <artifactId>axe-selenium</artifactId>
            <version>2.1</version>
        </dependency>

    </dependencies>

</project>

Please help me. Thanks.

Body:
Added

<testFailureIgnore>true</testFailureIgnore>
<shutdown>kill</shutdown>

to surefire plugin configuration.


问:
Flex string recognition "unrecognised rule" error
Im trying to create a string recognition rule to run in flex,the string can consist of escape characters(\n , \t , \r , \ , " , '), symbols( -, +, *, /, :, _, $, !, #, @, &, ~, ^, (, ) ) and a-zA-Z0-9 characters,i have tried many variations of the code below,but i keep getting the same error mentioned above.</p>

```<code>ESCAPECHAR  [\n] | [\t] | [\r] | [\] | ['] | ["]
SYMBOLS [-+*/:_$!#@&~^()]
CHARACTERS [0-9a-zA-Z]
STRING  ("({ESCAPECHAR} | {SYMBOLS} | {CHARACTERS})*") | ('({ESCAPECHAR} | {SYMBOLS} | {CHARACTERS})*')
</code>```

答:
You would do well to read the Flex manual chapter on patterns syntax. It is not very long, and it gives a complete description of the syntax of Flex patterns.

Here are a few of the errors you have made:

Flex patterns cannot include unquoted whitespace (unless you put them inside of a subexpression marked with the x flag). So

```<code>[\n] | [\t] | [\r] | [\] | ['] | ["]
</code>```

is invalid.

Also, the \ is used to indicate that:

the following letter is a code for a control character (so that \n is a newline character), or

the following punctuation symbol should not be given special significance.
So in [\], the \ indicates that the following ] should be treated as an ordinary character, instead of being the end of a character class, which means that the character class will continue up to the next ]. Space characters inside a character class are considered to be quoted, so the character class consists of the characters ], space, |, [ and '. (Flex lets you repeat characters inside a character class, so it won't complain about the fact that there are two space characters.) You probably meant [\\].

Anyway, you should write character classes in the same way you wrote the other character classes, as a series of characters or escaped codes inside [ and ]:

```<code>[\n\t\r\\ '"]
</code>```

Flex lets you quote characters by surrounding them with quotation marks, so that `"({ESCAPECHAR} | {SYMBOLS} | {CHARACTERS})*" is treated as a single literal string, which must be matched literally in the text. You probably intended the quotation marks to be ordinary characters, so you should have escaped them or put them into a single-character character class:

```<code>["]({ESCAPECHAR}|{SYMBOLS}|{CHARACTERS})*["]
</code>```

Again, it is necessary to remove the whitespace from the pattern.

I assume that your intention was to allow "escape characters" to appear in a string only if they are actually escaped. Your {ESCAPECHAR} macro expands to a collection of actual characters, so that it includes newline, tab and carriage return characters. It also includes quote and apostrophe, which really should be reserved for terminating the string literal. Probably, what you meant was to allow escape codes if they are preceded with a \ (as with C or, as mentioned above, flex itself). In that case, what you really need to write is

```<code>ESCAPECHAR    \\[ntr'"]
</code>```

(That is, a \\, followed by exactly on of the characters n, t, r, ', ".) Even that is not precise, though: It does not allow the use of \\ to indicate a single \, and it forces the user to write "Don\'t just copy code." and '\"', both of which would normally be written without the backslash escapes.

Body:
Im trying to create a string recognition rule to run in flex,the string can consist of escape characters(\n , \t , \r , \ , " , '), symbols( -, +, *, /, :, _, $, !, #, @, &, ~, ^, (, ) ) and a-zA-Z0-9 characters,i have tried many variations of the code below,but i keep getting the same error mentioned above.

ESCAPECHAR  [\n] | [\t] | [\r] | [\] | ['] | ["]
SYMBOLS [-+*/:_$!#@&~^()]
CHARACTERS [0-9a-zA-Z]
STRING  ("({ESCAPECHAR} | {SYMBOLS} | {CHARACTERS})*") | ('({ESCAPECHAR} | {SYMBOLS} | {CHARACTERS})*')

Body:
You would do well to read the Flex manual chapter on patterns syntax. It is not very long, and it gives a complete description of the syntax of Flex patterns.

Here are a few of the errors you have made:

Flex patterns cannot include unquoted whitespace (unless you put them inside of a subexpression marked with the x flag). So

[\n] | [\t] | [\r] | [\] | ['] | ["]

is invalid.

Also, the \ is used to indicate that:

the following letter is a code for a control character (so that \n is a newline character), or

the following punctuation symbol should not be given special significance.
So in [\], the \ indicates that the following ] should be treated as an ordinary character, instead of being the end of a character class, which means that the character class will continue up to the next ]. Space characters inside a character class are considered to be quoted, so the character class consists of the characters ], space, |, [ and '. (Flex lets you repeat characters inside a character class, so it won't complain about the fact that there are two space characters.) You probably meant [\\].

Anyway, you should write character classes in the same way you wrote the other character classes, as a series of characters or escaped codes inside [ and ]:

[\n\t\r\\ '"]

Flex lets you quote characters by surrounding them with quotation marks, so that `"({ESCAPECHAR} | {SYMBOLS} | {CHARACTERS})*" is treated as a single literal string, which must be matched literally in the text. You probably intended the quotation marks to be ordinary characters, so you should have escaped them or put them into a single-character character class:

["]({ESCAPECHAR}|{SYMBOLS}|{CHARACTERS})*["]

Again, it is necessary to remove the whitespace from the pattern.

I assume that your intention was to allow "escape characters" to appear in a string only if they are actually escaped. Your {ESCAPECHAR} macro expands to a collection of actual characters, so that it includes newline, tab and carriage return characters. It also includes quote and apostrophe, which really should be reserved for terminating the string literal. Probably, what you meant was to allow escape codes if they are preceded with a \ (as with C or, as mentioned above, flex itself). In that case, what you really need to write is

ESCAPECHAR    \\[ntr'"]

(That is, a \\, followed by exactly on of the characters n, t, r, ', ".) Even that is not precise, though: It does not allow the use of \\ to indicate a single \, and it forces the user to write "Don\'t just copy code." and '\"', both of which would normally be written without the backslash escapes.


问:
F# best way to swap letters in a string
Im currently trying to figure out the best way possible to take a string (fairly long string in my case) and replace all occurrences of let's say "A" with "B", and all occurrences of "B" with "A".

I've come up with two ways of doing it but there are probably a bette, faster and nicer way to implement this.

The first one is

```<code>    let stringFun letter1 letter2 = fun letter ->
                                      match letter with
                                      | letter when letter = letter1 -> letter2
                                      | letter when letter = letter2 -> letter1
                                      | letter                       -> letter

    let replaceLetter letter1 letter2 text = String.map (stringFun letter1 letter2) text
</code>```

With the second one being

```<code>    let remapInput (cipher: string) l1 l2 = cipher.Replace(l1, '&').Replace(l2, l1).Replace('&', l2)
</code>```

This one of course only works when there are no '&' in the given string.

答:
There are certainly a million ways to do what you want to do, and I'd assume at some point you may want more flexibility than just swapping two letters. The functionality that does this is called "string translation" in some programming languages, where a translation is done by "mapping" a search-list to a target-list for each character that you want modified.

Here's a generic way to do it and it is faster than your original approach (by about 3x):

```<code>/// Replaces each char in str that matches a char in search for the corresponding
/// char in repl. Array of search and repl must be equal in size.
let translate search repl (str: string) =
    // you can just as well use String.map, but it's slower, see comments
    str.ToCharArray()
    |> Array.map (fun c ->
        match search |> Array.tryFindIndex ((=) c) with
        | Some i -> Array.item i repl
        | None -> c
    ) |> String
</code>```

You call it like as follows (and you can use it with any number of characters to replace, not just swapping):

```<code>> translate [|'A';'B'|] [|'B';'A'|] "ABracadaBRA";;
val it : String = "BAracadaARB"
</code>```

In terms of timings compared to your approach, there's a clear difference (also notice the much smaller GC pressure):

```<code>> for i=1 to 1_000_000 do translate [|'A';'B'|] [|'B';'A'|] "ABracadaBRA" |> ignore;;
Real: 00:00:00.306, CPU: 00:00:00.312, GC gen0: 91, gen1: 0, gen2: 0

> for i=1 to 1_000_000 do replaceLetter 'A' 'B' "ABracadaBRA" |> ignore;;
Real: 00:00:01.053, CPU: 00:00:01.076, GC gen0: 185, gen1: 0, gen2: 0
</code>```

If the "generic" solution is a bit too much and you want raw speed plus simple code for just swapping the chars, this works just as well:

```<code>/// Swaps each search char for repl char in str in vice versa
let swap search repl (str: string) =
    str.ToCharArray()
    |> Array.map (fun c -> if c = search then repl elif c = repl then search else c)
    |> String
</code>```

And it performs another 3.5x faster, beating the original by 10x and even less GC pressure ;)

```<code>> for i=1 to 1_000_000 do swap 'A' 'B' "ABracadaBRA" |> ignore;;
Real: 00:00:00.101, CPU: 00:00:00.109, GC gen0: 23, gen1: 1, gen2: 0
</code>```

EDIT: I didn't check your remapInput version for timings earlier (mainly because you cannot rely on the & for not being present), but it is pretty fast already, it clocks in at 00:00.183 on my machine, with same GC pressure as my last solution. It can do that by using a modifiable array internally. We can do that too with my first and second solution if you want even more raw speed at expense of more complex code.

If we take my last solution and use a mutable array internally, we can squeeze out even better performance and even less GC pressure yet:

```<code>/// Swaps each search char for repl char in str in vice versa
let fastSwap search repl (str: string) =
    let x = str.ToCharArray()
    let mutable i = -1
    for c in x do
        i <- i + 1
        if c = search then x.[i] <- repl
        elif c = repl then x.[i] <- search
    String x
</code>```

Performance is pretty amazing:

```<code>> for i=1 to 1_000_000 do fastSwap 'A' 'B' "ABracadaBRA" |> ignore;;
Real: 00:00:00.067, CPU: 00:00:00.062, GC gen0: 16, gen1: 0, gen2: 0
</code>```

Title: F# best way to swap letters in a string

Body:
Im currently trying to figure out the best way possible to take a string (fairly long string in my case) and replace all occurrences of let's say "A" with "B", and all occurrences of "B" with "A".

I've come up with two ways of doing it but there are probably a bette, faster and nicer way to implement this.

The first one is

    let stringFun letter1 letter2 = fun letter ->
                                      match letter with
                                      | letter when letter = letter1 -> letter2
                                      | letter when letter = letter2 -> letter1
                                      | letter                       -> letter

    let replaceLetter letter1 letter2 text = String.map (stringFun letter1 letter2) text

With the second one being

    let remapInput (cipher: string) l1 l2 = cipher.Replace(l1, '&').Replace(l2, l1).Replace('&', l2)

This one of course only works when there are no '&' in the given string.

Body:
There are certainly a million ways to do what you want to do, and I'd assume at some point you may want more flexibility than just swapping two letters. The functionality that does this is called "string translation" in some programming languages, where a translation is done by "mapping" a search-list to a target-list for each character that you want modified.

Here's a generic way to do it and it is faster than your original approach (by about 3x):

/// Replaces each char in str that matches a char in search for the corresponding
/// char in repl. Array of search and repl must be equal in size.
let translate search repl (str: string) =
    // you can just as well use String.map, but it's slower, see comments
    str.ToCharArray()
    |> Array.map (fun c ->
        match search |> Array.tryFindIndex ((=) c) with
        | Some i -> Array.item i repl
        | None -> c
    ) |> String

You call it like as follows (and you can use it with any number of characters to replace, not just swapping):

> translate [|'A';'B'|] [|'B';'A'|] "ABracadaBRA";;
val it : String = "BAracadaARB"

In terms of timings compared to your approach, there's a clear difference (also notice the much smaller GC pressure):

> for i=1 to 1_000_000 do translate [|'A';'B'|] [|'B';'A'|] "ABracadaBRA" |> ignore;;
Real: 00:00:00.306, CPU: 00:00:00.312, GC gen0: 91, gen1: 0, gen2: 0

> for i=1 to 1_000_000 do replaceLetter 'A' 'B' "ABracadaBRA" |> ignore;;
Real: 00:00:01.053, CPU: 00:00:01.076, GC gen0: 185, gen1: 0, gen2: 0

If the "generic" solution is a bit too much and you want raw speed plus simple code for just swapping the chars, this works just as well:

/// Swaps each search char for repl char in str in vice versa
let swap search repl (str: string) =
    str.ToCharArray()
    |> Array.map (fun c -> if c = search then repl elif c = repl then search else c)
    |> String

And it performs another 3.5x faster, beating the original by 10x and even less GC pressure ;)

> for i=1 to 1_000_000 do swap 'A' 'B' "ABracadaBRA" |> ignore;;
Real: 00:00:00.101, CPU: 00:00:00.109, GC gen0: 23, gen1: 1, gen2: 0

EDIT: I didn't check your remapInput version for timings earlier (mainly because you cannot rely on the & for not being present), but it is pretty fast already, it clocks in at 00:00.183 on my machine, with same GC pressure as my last solution. It can do that by using a modifiable array internally. We can do that too with my first and second solution if you want even more raw speed at expense of more complex code.

If we take my last solution and use a mutable array internally, we can squeeze out even better performance and even less GC pressure yet:

/// Swaps each search char for repl char in str in vice versa
let fastSwap search repl (str: string) =
    let x = str.ToCharArray()
    let mutable i = -1
    for c in x do
        i <- i + 1
        if c = search then x.[i] <- repl
        elif c = repl then x.[i] <- search
    String x

Performance is pretty amazing:

> for i=1 to 1_000_000 do fastSwap 'A' 'B' "ABracadaBRA" |> ignore;;
Real: 00:00:00.067, CPU: 00:00:00.062, GC gen0: 16, gen1: 0, gen2: 0


问:
Angular 9: how to re-render component
I have one parent and one child component. If the child component updates its value internally I am unable to update value back from Parent.

See the example in this Stackblitz: https://stackblitz.com/edit/angular-ivy-tynepp. When the child component loses focus I fire an event and the parent resets value of the child component. But I think that because the parent's "this.value" didn't change that the update doesn't trigger detection changes in the child.

How can I solve this dilemma?

答:
Another simpler approach to get this can be to use the template variables as you can see in the example below:

parent.component.html

<app-my-child
  #child
  (lostFocus)="child.value = ''"></app-my-child>
```

Solution available here.

Title: Angular 9: how to re-render component

Body:
Another simpler approach to get this can be to use the template variables as you can see in the example below:

parent.component.html

<app-my-child
  #child
  (lostFocus)="child.value = ''"></app-my-child>

Solution available here.


问:
Wait for useLazyQuery response
I need to call a query when submit button is pressed and then handle the response.

I need something like this:

```<code>const [checkEmail] = useLazyQuery(CHECK_EMAIL)
const handleSubmit = async () => {
  const res = await checkEmail({ variables: { email: values.email }})
  console.log(res) // handle response
}
</code>```

Try #1:

```<code>const [checkEmail, { data }] = useLazyQuery(CHECK_EMAIL)
const handleSubmit = async () => {
  const res = await checkEmail({ variables: { email: values.email }})
  console.log(data) // undefined the first time
}
</code>```

Thanks in advance!

答:
After all, this is my solution.</p>

```<code>export function useLazyQuery<TData = any, TVariables = OperationVariables>(query: DocumentNode) {
  const client = useApolloClient()
  return React.useCallback(
    (variables: TVariables) =>
      client.query<TData, TVariables>({
        query: query,
        variables: variables,
      }),
    [client]
  )
}
</code>```

Title: Wait for useLazyQuery response

Body:
I need to call a query when submit button is pressed and then handle the response.

I need something like this:

const [checkEmail] = useLazyQuery(CHECK_EMAIL)
const handleSubmit = async () => {
  const res = await checkEmail({ variables: { email: values.email }})
  console.log(res) // handle response
}

Try #1:

const [checkEmail, { data }] = useLazyQuery(CHECK_EMAIL)
const handleSubmit = async () => {
  const res = await checkEmail({ variables: { email: values.email }})
  console.log(data) // undefined the first time
}

Thanks in advance!

Body:
After all, this is my solution.

export function useLazyQuery<TData = any, TVariables = OperationVariables>(query: DocumentNode) {
  const client = useApolloClient()
  return React.useCallback(
    (variables: TVariables) =>
      client.query<TData, TVariables>({
        query: query,
        variables: variables,
      }),
    [client]
  )
}


问:
material ui styling not applying
For some reason my material ui styles are not applying to my html element? Any idea why? I have no other styles applied to this page</p>

```<code>import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '@material-ui/core';

const classes = makeStyles( (theme) => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "white"
  },
}) )

class Login extends Component {
  render() {
    return(
      <div className = {classes.root}>
        <LoginForm/>
      </div>
    );
  }
}
export default Login;
</code>```

答:
makeStyles returns a react hook to use in the component. Hooks also only work in functional components, so you'll need to convert Login to a functional component.

```<code>import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '@material-ui/core';

const useStyles = makeStyles(theme => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "lightblue"
  }
}));

const Login = props => {
  const classes = useStyles();

  return(
    <div className={classes.root}>
      <LoginForm/>
    </div>
  );
}
export default Login;
</code>```

Title: material ui styling not applying

Body:
For some reason my material ui styles are not applying to my html element? Any idea why? I have no other styles applied to this page

import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '@material-ui/core';

const classes = makeStyles( (theme) => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "white"
  },
}) )

class Login extends Component {
  render() {
    return(

        <LoginForm/>

    );
  }
}
export default Login;

Body:
makeStyles returns a react hook to use in the component. Hooks also only work in functional components, so you'll need to convert Login to a functional component.

import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '@material-ui/core';

const useStyles = makeStyles(theme => ({
  root: {
    paddingTop: theme.spacing(8),
    backgroundColor: "lightblue"
  }
}));

const Login = props => {
  const classes = useStyles();

  return(
    <div className={classes.root}>
      <LoginForm/>
    </div>
  );
}
export default Login;


问:
Android sharedpreferences
I've been following this tutorial and i am stuck.

```<code>public class Main extends Activity {

    SharedPreferences mPrefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        firstRunPreferences();

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();
        }
        else
        {
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
     }

}`
</code>```

Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".

Thanks

答:
I am assuming you are using the Emulator to run your app. Are you closing the emulator between runs?

Check if you have the "Wipe User Data" checkbox ticked in the Target tab of your Debug run configuration in Eclipse.

Title: Android sharedpreferences

Body:
I've been following this tutorial and i am stuck.

public class Main extends Activity {

    SharedPreferences mPrefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        firstRunPreferences();

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();
        }
        else
        {
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
     }

}`

Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".

Thanks


问:
Matching a pattern in cat/zcat?
How can I match a more complex pattern when using cat or zcat? For example, I know I can do this:

```<code>zcat /var/log/nginx/access.log.*.gz
</code>```

Which will output all the gzipped access logs to stdin.

What if I want a more complex pattern? Say, all the log files that are between 1-15, e.g. something like this pattern:

```<code>zcat /var/log/nginx/access.log.([1-9]|1[0-5]).gz
</code>```

This results in an unexpected token which is obvious, but I'm not sure how I'd escape the regex in this situation? Maybe I need to pipe ls output to zcat instead?

答:
It depends of course on specifically what pattern you want to match. For the example you have given of log files 1-15, you could use something like

```<code>cat /var/log/nginx/access.log.{1..15}.gz
</code>```

which will complain to stderr if any of those numbers don't exist, but it will still concatenate the rest to stdout.

This technique is a "sequence expression" if you want to look it up - it's a part of brace expansion.

Title: Matching a pattern in cat/zcat?

Body:
How can I match a more complex pattern when using cat or zcat? For example, I know I can do this:

zcat /var/log/nginx/access.log.*.gz

Which will output all the gzipped access logs to stdin.

What if I want a more complex pattern? Say, all the log files that are between 1-15, e.g. something like this pattern:

zcat /var/log/nginx/access.log.([1-9]|1[0-5]).gz

This results in an unexpected token which is obvious, but I'm not sure how I'd escape the regex in this situation? Maybe I need to pipe ls output to zcat instead?

Body:
It depends of course on specifically what pattern you want to match. For the example you have given of log files 1-15, you could use something like

cat /var/log/nginx/access.log.{1..15}.gz

which will complain to stderr if any of those numbers don't exist, but it will still concatenate the rest to stdout.

This technique is a "sequence expression" if you want to look it up - it's a part of brace expansion.


问:
How do you run a half float ONNX model using ONNXRuntime C API?
Since the C language doesn't have a half float implementation, how do you send data to the ONNXRuntime C API?</p>

答:
There's possibly an example you can follow linked from here: https://github.com/microsoft/onnxruntime/issues/1173#issuecomment-501088662

You can create a buffer to write the input data to using CreateTensorAsOrtValue, and access the buffer within the OrtValue using GetTensorMutableData.

ONNXRuntime is using Eigen to convert a float into the 16 bit value that you could write to that buffer.

```<code>uint16_t floatToHalf(float f) {
  return Eigen::half_impl::float_to_half_rtne(f).x;
}
</code>```

Alternatively you could edit the model to add a Cast node from float32 to float16 so that the model takes float32 as input.

Body:
There's possibly an example you can follow linked from here: https://github.com/microsoft/onnxruntime/issues/1173#issuecomment-501088662

You can create a buffer to write the input data to using CreateTensorAsOrtValue, and access the buffer within the OrtValue using GetTensorMutableData.

ONNXRuntime is using Eigen to convert a float into the 16 bit value that you could write to that buffer.

uint16_t floatToHalf(float f) {
  return Eigen::half_impl::float_to_half_rtne(f).x;
}

Alternatively you could edit the model to add a Cast node from float32 to float16 so that the model takes float32 as input.