问:
Installing Appium via npm throw an error of "permission denied" type
Trying to install an appium package for node.js and have a problem referenced that permission been denied to mkdir

I tried to run this command in different ways and running as root user doesn't changed much. Have anybody had such an error before ?

```<code>Dmytros-MacBook-Pro:~ root# npm install -g appium
/usr/local/bin/appium ->
/usr/local/lib/node_modules/appium/build/lib/main.js

> appium-chromedriver@4.0.0 install
/usr/local/lib/node_modules/appium/node_modules/appium-chromedriver
> node install-npm.js

(node:8302) UnhandledPromiseRejectionWarning: Error: EACCES:
permission denied, mkdir
'/usr/local/lib/node_modules/appium/node_modules/appium-
chromedriver/201866-8302-85r6wr.u3tan'
(node:8302) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8302) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
info Chromedriver Install Installing Chromedriver version '2.38' for
platform 'mac' and architecture '64'
info Chromedriver Install Opening temp file to write
chromedriver_mac64 to...
Error: EACCES: permission denied, mkdir
'/usr/local/lib/node_modules/appium/node_modules/appium-
chromedriver/201866-8302-y2j8ui.tqs2'
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! appium-chromedriver@4.0.0 install: `node install-npm.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the appium-chromedriver@4.0.0 install script.
npm ERR! This is probably not a problem with npm. There is likely
additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /var/root/.npm/_logs/2018-07-07T02_06_56_333Z-debug.log
</code>```

答:
sudo npm install -g appium --unsafe-perm=true --allow-root

This command solved my issue as well

Body:
Trying to install an appium package for node.js and have a problem referenced that permission been denied to mkdir

I tried to run this command in different ways and running as root user doesn't changed much. Have anybody had such an error before ?

Dmytros-MacBook-Pro:~ root# npm install -g appium
/usr/local/bin/appium ->
/usr/local/lib/node_modules/appium/build/lib/main.js

> appium-chromedriver@4.0.0 install
/usr/local/lib/node_modules/appium/node_modules/appium-chromedriver
> node install-npm.js

(node:8302) UnhandledPromiseRejectionWarning: Error: EACCES:
permission denied, mkdir
'/usr/local/lib/node_modules/appium/node_modules/appium-
chromedriver/201866-8302-85r6wr.u3tan'
(node:8302) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8302) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
info Chromedriver Install Installing Chromedriver version '2.38' for
platform 'mac' and architecture '64'
info Chromedriver Install Opening temp file to write
chromedriver_mac64 to...
Error: EACCES: permission denied, mkdir
'/usr/local/lib/node_modules/appium/node_modules/appium-
chromedriver/201866-8302-y2j8ui.tqs2'
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! appium-chromedriver@4.0.0 install: `node install-npm.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the appium-chromedriver@4.0.0 install script.
npm ERR! This is probably not a problem with npm. There is likely
additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /var/root/.npm/_logs/2018-07-07T02_06_56_333Z-debug.log


来源: stackexchange

问:
Flutter Scrollable Stack with Height greater than Screen Height
I have a widget hierarchy where SingleChildScrollView is the parent with a Stack as the child, the Stack has two children, if the Second child goes beyond the screen height its height gets clipped. According to docs the stack occupies size according to a Non-Positioned child. So that means we have to explicitly give a height to the Stack, but this height is arbitrary and it won't wrap the contents inside. My main aim is to wrap the SingleChildScrollView height rather than having empty space at bottom.

```<code>SingleChildScrollView(
    child: Container(
      height: MediaQuery.of(context).size.height + 150,
      child: SafeArea(
        bottom: false,
        child: Stack(
           fit: StackFit.expand,
          children: <Widget>[
              Container(height:MediaQuery.of(context).size.height * .35,),
              Positioned(top: top: MediaQuery.of(context).size.height * .35 +
                  MediaQuery.of(context).viewInsets.top,..)
                 ...]))))
</code>```

[![image][1]][1]

[1]: https://i.stack.imgur.com/ZnoP0.png

答:
Solution #1

Do let me know if this isn't what you were looking for.

```<code>void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 44, left: 24, right: 24, bottom: 20),
            color: Colors.deepPurpleAccent,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.arrow_back),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                    Spacer(),
                    IconButton(
                      icon: Icon(Icons.more_vert),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(color: Colors.white, width: 100, height: 100),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          _myText("Your name", 16),
                          _myText("24 years old", 14),
                          SizedBox(height: 6),
                          _myText("Martial status", 16),
                          _myText("Unmarried", 14),
                          SizedBox(height: 6),
                          Container(padding: EdgeInsets.all(4), color: Colors.blue, child: _myText("PLUS PLAN - 1 DAY LEFT", 12)),
                          SizedBox(height: 12),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  width: double.maxFinite,
                  child: OutlineButton(
                    borderSide: BorderSide(color: Colors.white, width: 2),
                    onPressed: () {},
                    child: _myText("CHANGE PLAN", 16),
                  ),
                ),
                Text(
                  "Higher plans give you more connects",
                  style: TextStyle(fontSize: 10, color: Colors.white70),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView(
              children: <Widget>[
                _buildCard1(),
                _buildCard(size: 70, color: Colors.deepOrange),
                _buildCard(size: 80, color: Colors.purple),
                _buildCard(size: 90, color: Colors.pink),
                _buildCard(size: 100, color: Colors.grey),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _myText(String data, double size) => Text(data, style: TextStyle(fontSize: size, color: Colors.white));

  Widget _buildCard1() {
    return Card(
      elevation: 4,
      margin: EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text("PROFILE DETAILS"),
          ),
          Placeholder(fallbackHeight: 200),
          Divider(),
          SizedBox(
            width: double.maxFinite,
            child: FlatButton(
              onPressed: () {},
              child: Text("UPDATE MY PROFILE"),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCard({double size, Color color}) {
    return Card(
      margin: EdgeInsets.all(12),
      child: Container(height: size, color: color,),
    );
  }
}
</code>```

Solution # 2

Is this what you were looking for? (Here I only modified above build() method, rest of the method remains same.

```<code>@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.deepPurpleAccent,
    body: SafeArea(
      child: ListView(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 12, left: 24, right: 24, bottom: 20),
            color: Colors.deepPurpleAccent,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.arrow_back),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                    Spacer(),
                    IconButton(
                      icon: Icon(Icons.more_vert),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(color: Colors.white, width: 100, height: 100),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          _myText("Your name", 16),
                          _myText("24 years old", 14),
                          SizedBox(height: 6),
                          _myText("Martial status", 16),
                          _myText("Unmarried", 14),
                          SizedBox(height: 6),
                          Container(padding: EdgeInsets.all(4), color: Colors.blue, child: _myText("PLUS PLAN - 1 DAY LEFT", 12)),
                          SizedBox(height: 12),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  width: double.maxFinite,
                  child: OutlineButton(
                    borderSide: BorderSide(color: Colors.white, width: 2),
                    onPressed: () {},
                    child: _myText("CHANGE PLAN", 16),
                  ),
                ),
                Text(
                  "Higher plans give you more connects",
                  style: TextStyle(fontSize: 10, color: Colors.white70),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.horizontal(left: Radius.circular(30), right: Radius.circular(30))
            ),
            child: Column(
              children: <Widget>[
                _buildCard1(),
                _buildCard(size: 70, color: Colors.deepOrange),
                _buildCard(size: 80, color: Colors.purple),
                _buildCard(size: 90, color: Colors.pink),
                _buildCard(size: 100, color: Colors.grey),
              ],
            ),
          ),
        ],
      ),
    ),
  );
}
</code>```

Solution #3

```<code>@override
Widget build(BuildContext context) {
  return Scaffold(
    body: SafeArea(
      child: DecoratedBox(
        decoration: BoxDecoration(image: DecorationImage(image: AssetImage("your_image_here"), fit: BoxFit.cover)),
        child: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              expandedHeight: 300,
              flexibleSpace: FlexibleSpaceBar(
                collapseMode: CollapseMode.pin,
                background: Container(
                  decoration: BoxDecoration(image: DecorationImage(image: AssetImage("your_image_here"), fit: BoxFit.cover)),
                  padding: EdgeInsets.only(top: 12, left: 24, right: 24, bottom: 20),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          IconButton(
                            icon: Icon(Icons.arrow_back),
                            onPressed: () {},
                            color: Colors.white,
                          ),
                          Spacer(),
                          IconButton(
                            icon: Icon(Icons.more_vert),
                            onPressed: () {},
                            color: Colors.white,
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(color: Colors.white, width: 100, height: 100),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                _myText("Your name", 16),
                                _myText("24 years old", 14),
                                SizedBox(height: 6),
                                _myText("Martial status", 16),
                                _myText("Unmarried", 14),
                                SizedBox(height: 6),
                                Container(padding: EdgeInsets.all(4), color: Colors.blue, child: _myText("PLUS PLAN - 1 DAY LEFT", 12)),
                                SizedBox(height: 12),
                              ],
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        width: double.maxFinite,
                        child: OutlineButton(
                          borderSide: BorderSide(color: Colors.white, width: 2),
                          onPressed: () {},
                          child: _myText("CHANGE PLAN", 16),
                        ),
                      ),
                      Text(
                        "Higher plans give you more connects",
                        style: TextStyle(fontSize: 10, color: Colors.white70),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildListDelegate(
                [
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.orange,
                        borderRadius: BorderRadius.horizontal(
                          left: Radius.circular(30),
                          right: Radius.circular(30),
                        )),
                    child: Column(
                      children: <Widget>[
                        _buildCard1(),
                        _buildCard(size: 100, color: Colors.deepOrange),
                        _buildCard(size: 80, color: Colors.purple),
                        _buildCard(size: 100, color: Colors.pink),
                        _buildCard(size: 180, color: Colors.grey),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    ),
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a widget hierarchy where SingleChildScrollView is the parent with a Stack as the child, the Stack has two children, if the Second child goes beyond the screen height its height gets clipped. According to docs the stack occupies size according to a Non-Positioned child. So that means we have to explicitly give a height to the Stack, but this height is arbitrary and it won't wrap the contents inside. My main aim is to wrap the SingleChildScrollView height rather than having empty space at bottom.

SingleChildScrollView(
    child: Container(
      height: MediaQuery.of(context).size.height + 150,
      child: SafeArea(
        bottom: false,
        child: Stack(
           fit: StackFit.expand,
          children: <Widget>[
              Container(height:MediaQuery.of(context).size.height * .35,),
              Positioned(top: top: MediaQuery.of(context).size.height * .35 +
                  MediaQuery.of(context).viewInsets.top,..)
                 ...]))))

[![image][1]][1]

[1]: https://i.stack.imgur.com/ZnoP0.png

Body:
Solution #1

Do let me know if this isn't what you were looking for.

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 44, left: 24, right: 24, bottom: 20),
            color: Colors.deepPurpleAccent,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.arrow_back),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                    Spacer(),
                    IconButton(
                      icon: Icon(Icons.more_vert),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(color: Colors.white, width: 100, height: 100),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          _myText("Your name", 16),
                          _myText("24 years old", 14),
                          SizedBox(height: 6),
                          _myText("Martial status", 16),
                          _myText("Unmarried", 14),
                          SizedBox(height: 6),
                          Container(padding: EdgeInsets.all(4), color: Colors.blue, child: _myText("PLUS PLAN - 1 DAY LEFT", 12)),
                          SizedBox(height: 12),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  width: double.maxFinite,
                  child: OutlineButton(
                    borderSide: BorderSide(color: Colors.white, width: 2),
                    onPressed: () {},
                    child: _myText("CHANGE PLAN", 16),
                  ),
                ),
                Text(
                  "Higher plans give you more connects",
                  style: TextStyle(fontSize: 10, color: Colors.white70),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView(
              children: <Widget>[
                _buildCard1(),
                _buildCard(size: 70, color: Colors.deepOrange),
                _buildCard(size: 80, color: Colors.purple),
                _buildCard(size: 90, color: Colors.pink),
                _buildCard(size: 100, color: Colors.grey),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _myText(String data, double size) => Text(data, style: TextStyle(fontSize: size, color: Colors.white));

  Widget _buildCard1() {
    return Card(
      elevation: 4,
      margin: EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text("PROFILE DETAILS"),
          ),
          Placeholder(fallbackHeight: 200),
          Divider(),
          SizedBox(
            width: double.maxFinite,
            child: FlatButton(
              onPressed: () {},
              child: Text("UPDATE MY PROFILE"),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCard({double size, Color color}) {
    return Card(
      margin: EdgeInsets.all(12),
      child: Container(height: size, color: color,),
    );
  }
}

Solution # 2

Is this what you were looking for? (Here I only modified above build() method, rest of the method remains same.

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.deepPurpleAccent,
    body: SafeArea(
      child: ListView(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 12, left: 24, right: 24, bottom: 20),
            color: Colors.deepPurpleAccent,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.arrow_back),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                    Spacer(),
                    IconButton(
                      icon: Icon(Icons.more_vert),
                      onPressed: () {},
                      color: Colors.white,
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(color: Colors.white, width: 100, height: 100),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          _myText("Your name", 16),
                          _myText("24 years old", 14),
                          SizedBox(height: 6),
                          _myText("Martial status", 16),
                          _myText("Unmarried", 14),
                          SizedBox(height: 6),
                          Container(padding: EdgeInsets.all(4), color: Colors.blue, child: _myText("PLUS PLAN - 1 DAY LEFT", 12)),
                          SizedBox(height: 12),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  width: double.maxFinite,
                  child: OutlineButton(
                    borderSide: BorderSide(color: Colors.white, width: 2),
                    onPressed: () {},
                    child: _myText("CHANGE PLAN", 16),
                  ),
                ),
                Text(
                  "Higher plans give you more connects",
                  style: TextStyle(fontSize: 10, color: Colors.white70),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.horizontal(left: Radius.circular(30), right: Radius.circular(30))
            ),
            child: Column(
              children: <Widget>[
                _buildCard1(),
                _buildCard(size: 70, color: Colors.deepOrange),
                _buildCard(size: 80, color: Colors.purple),
                _buildCard(size: 90, color: Colors.pink),
                _buildCard(size: 100, color: Colors.grey),
              ],
            ),
          ),
        ],
      ),
    ),
  );
}

Solution #3

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: SafeArea(
      child: DecoratedBox(
        decoration: BoxDecoration(image: DecorationImage(image: AssetImage("your_image_here"), fit: BoxFit.cover)),
        child: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              expandedHeight: 300,
              flexibleSpace: FlexibleSpaceBar(
                collapseMode: CollapseMode.pin,
                background: Container(
                  decoration: BoxDecoration(image: DecorationImage(image: AssetImage("your_image_here"), fit: BoxFit.cover)),
                  padding: EdgeInsets.only(top: 12, left: 24, right: 24, bottom: 20),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          IconButton(
                            icon: Icon(Icons.arrow_back),
                            onPressed: () {},
                            color: Colors.white,
                          ),
                          Spacer(),
                          IconButton(
                            icon: Icon(Icons.more_vert),
                            onPressed: () {},
                            color: Colors.white,
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(color: Colors.white, width: 100, height: 100),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                _myText("Your name", 16),
                                _myText("24 years old", 14),
                                SizedBox(height: 6),
                                _myText("Martial status", 16),
                                _myText("Unmarried", 14),
                                SizedBox(height: 6),
                                Container(padding: EdgeInsets.all(4), color: Colors.blue, child: _myText("PLUS PLAN - 1 DAY LEFT", 12)),
                                SizedBox(height: 12),
                              ],
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        width: double.maxFinite,
                        child: OutlineButton(
                          borderSide: BorderSide(color: Colors.white, width: 2),
                          onPressed: () {},
                          child: _myText("CHANGE PLAN", 16),
                        ),
                      ),
                      Text(
                        "Higher plans give you more connects",
                        style: TextStyle(fontSize: 10, color: Colors.white70),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildListDelegate(
                [
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.orange,
                        borderRadius: BorderRadius.horizontal(
                          left: Radius.circular(30),
                          right: Radius.circular(30),
                        )),
                    child: Column(
                      children: <Widget>[
                        _buildCard1(),
                        _buildCard(size: 100, color: Colors.deepOrange),
                        _buildCard(size: 80, color: Colors.purple),
                        _buildCard(size: 100, color: Colors.pink),
                        _buildCard(size: 180, color: Colors.grey),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    ),
  );
}


问:
Using Background-Process to locate the User realtime in Flutter
I want to track the users live position using Flutter while the App is not running. I found a Tutorial on Medium explaining how to do this but I could not wrap my Head around it neither get the sample code to run. Are there any samples Apps I can use to see how it is done using Background-Process or are there any other Ressources I could use to make this happen?

I already tried to follow a Tutorial explaining how to implement this using a Background-Process but the Sample could would not run.

I would like to monitor the live location and call a callback when the position changes.

答:
I think that this is the biggest limitation in Flutter, yet.

I've implemented a background service, but, I have to write all my way down in native code, and it's painful, I mean, it's painful if you don't have any experience in it.

The only way I managed to make a background service (to send push notification), and I believe, in your case, to track user's location, it's to find examples written in native code.


问:
using exec to execute a system command in a new process
I am trying to spawn a process that executes a system command, while my own program still proceeds and two processes will run in parallel. I am working on linux.

I looked up online and sounds like I should use exec() family. But it doesn't work quite as what I expected. For example, in the following code, I only see "before" being printed, ,but not "done".

I am curious if I am issing anything?

```<code>#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
   cout << "done" << endl;
}
</code>```

[UPDATE]

Thank you for your guys comments. Now my program looks like this. Everything works fine except at the end, I have to press enter to finish the program. I am not sure why I have to press the last enter?

```<code>#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   int pid = fork();
   cout << pid << endl;
   if (pid==0) {
      execl("/bin/ls", "ls", "-r", "-t", "-l", (char *) 0);
   }
   cout << "done" << endl;
}
</code>```

答:
You're missing the part where execl() replaces your current program in memory with /bin/ls

I would suggest looking at popen() which will fork and exec a new process, then let you read or write to it via a pipe. (Or if you need read and write, fork() yourself, then exec())

ContentLicense: CC BY-SA 3.0

Body:
I am trying to spawn a process that executes a system command, while my own program still proceeds and two processes will run in parallel. I am working on linux.

I looked up online and sounds like I should use exec() family. But it doesn't work quite as what I expected. For example, in the following code, I only see "before" being printed, ,but not "done".

I am curious if I am issing anything?

#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
   cout << "done" << endl;
}

[UPDATE]

Thank you for your guys comments. Now my program looks like this. Everything works fine except at the end, I have to press enter to finish the program. I am not sure why I have to press the last enter?

#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   int pid = fork();
   cout << pid << endl;
   if (pid==0) {
      execl("/bin/ls", "ls", "-r", "-t", "-l", (char *) 0);
   }
   cout << "done" << endl;
}


问:
Will my application work if i don't give handlerMapping in configuration file?
This is my spring-servlet.xml file. I am new to spring MVC. Do we need to define bean for HelloWorld.Controller. If i don't define will it work?</p>

```<code> <bean id="viewResolver" class=" org.springframework.web.servlet.view. InternalResourceViewResolver" >
        <property name="prefix">
         <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean name="/welcome.htm" class="com.vaannila.HelloWorldController" >
        <property name="message" value="Hello World!" />
    </bean>

</beans>

If i don't give  this bean definition

 <bean name="/welcome.htm" class="com.vaannila.HelloWorldController" >
        <property name="message" value="Hello World!" />
    </bean>

MyApplication should work or not? I am new to spring MVC. In few tutorial this code is there and in few its not there. Please explain.
</code>```

答:
Yes, you will need to define the bean (way to create instance of class) for all the Controller/Service/Dao/Components class you want to use and set relevant properties.

I would recommend you to use Annotation based configuration (spring boot) as it eases all this process. You can find lot of tutorials on getting stated with spring boot. Here is one such good tutorial https://www.mkyong.com/spring-boot/spring-boot-hello-world-example-jsp/

Body:
This is my spring-servlet.xml file. I am new to spring MVC. Do we need to define bean for HelloWorld.Controller. If i don't define will it work?

 <bean id="viewResolver" class=" org.springframework.web.servlet.view. InternalResourceViewResolver" >
        <property name="prefix">
         <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean name="/welcome.htm" class="com.vaannila.HelloWorldController" >
        <property name="message" value="Hello World!" />
    </bean>

</beans>

If i don't give  this bean definition

 <bean name="/welcome.htm" class="com.vaannila.HelloWorldController" >
        <property name="message" value="Hello World!" />
    </bean>

MyApplication should work or not? I am new to spring MVC. In few tutorial this code is there and in few its not there. Please explain.


问:
Laravel date format and consoletv
I am trying to produce some charts for my laravel website but I am new to date formatting and I don't get this code, can someone help me to figure out how to tweak it to show graph per year ?

```<code>$project = Project::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"), date('Y'))->get();

$chart = Charts::database($project, 'bar', 'highcharts')
    ->title("Monthly new Logged-in Students")
    ->elementLabel("Total Students")
    ->dimensions(1000, 500)
    ->responsive(true)
    ->groupByYear(date('Y'), true);

return view('coordinator.Graph1', compact('chart'));
</code>```

I really don't get this part

```<code>(DB::raw("(DATE_FORMAT(created_at,'%Y'))"),date('Y'))
</code>```

if someone could explain it to me I would be able to group it by year successfully

答:
In Your Controller </p>

```<code>use Carbon;
</code>```

<p>then you can use carbon in your query </p>

```<code>$project = Project::where('created_at','=',Carbon\Carbon::now()->format('Y'))->get();
</code>```

Title: Laravel date format and consoletv

Body:
I am trying to produce some charts for my laravel website but I am new to date formatting and I don't get this code, can someone help me to figure out how to tweak it to show graph per year ?

$project = Project::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"), date('Y'))->get();

$chart = Charts::database($project, 'bar', 'highcharts')
    ->title("Monthly new Logged-in Students")
    ->elementLabel("Total Students")
    ->dimensions(1000, 500)
    ->responsive(true)
    ->groupByYear(date('Y'), true);

return view('coordinator.Graph1', compact('chart'));

I really don't get this part

(DB::raw("(DATE_FORMAT(created_at,'%Y'))"),date('Y'))

if someone could explain it to me I would be able to group it by year successfully

Body:
In Your Controller

use Carbon;

then you can use carbon in your query

$project = Project::where('created_at','=',Carbon\Carbon::now()->format('Y'))->get();


问:
How to concatenate two images side by side?
I have a folder which contains images named as 1_A.jpg,2_A.jpg....and so on. There exist another folder B which contains images named as 1_B.jpg, 2_B.jpg and so on. I want to concatenate the images 1_A and 1_B, 2_A 2_B and so on. i.e I want to concatenate the same name pair images. However, if I run the below code I am getting a concatenation of 1_B and 1_B and so on.

I also want to store the results in a folder named combined_canny. Here is my code.

```<code>import os
import numpy as np
import cv2
import argparse

parser = argparse.ArgumentParser('create image pairs')
parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='/home/vplab/pytorch-CycleGAN-and-pix2pix/datasets/canny/')
parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='/home/vplab/pytorch-CycleGAN-and-pix2pix/datasets/canny/')
parser.add_argument('--fold_AB', dest='fold_AB', help='output directory', type=str, default='/home/vplab/pytorch-CycleGAN-and-pix2pix/datasets/canny/combined_canny')
parser.add_argument('--num_imgs', dest='num_imgs', help='number of images', type=int, default=5000)
parser.add_argument('--use_AB', dest='use_AB', help='if true: (0001_A, 0001_B) to (0001_AB)', action='store_true')
args = parser.parse_args()

for arg in vars(args):
    print('[%s] = ' % arg, getattr(args, arg))

splits = os.listdir(args.fold_A)

for sp in splits:
    img_fold_A = os.path.join(args.fold_A, sp)
    img_fold_B = os.path.join(args.fold_B, sp)
    img_list = os.listdir(img_fold_A)
    if args.use_AB:
        img_list = [img_path for img_path in img_list if '_A.' in img_path]

    num_imgs = min(args.num_imgs, len(img_list))
    print('split = %s, use %d/%d images' % (sp, num_imgs, len(img_list)))
    img_fold_AB = os.path.join(args.fold_AB, sp)
    if not os.path.isdir(img_fold_AB):
        os.makedirs(img_fold_AB)
    print('split = %s, number of images = %d' % (sp, num_imgs))
    for n in range(num_imgs):
        name_A = img_list[n]
        path_A = os.path.join(img_fold_A, name_A)
        if args.use_AB:
            name_B = name_A.replace('_A.', '_B.')
        else:
            name_B = name_A
        path_B = os.path.join(img_fold_B, name_B)
        if os.path.isfile(path_A) and os.path.isfile(path_B):
            name_AB = name_A
            if args.use_AB:
                name_AB = name_AB.replace('_A.', '.')  # remove _A
            path_AB = os.path.join(img_fold_AB, name_AB)
            im_A = cv2.imread(path_A, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
            im_B = cv2.imread(path_B, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
            im_AB = np.concatenate([im_A, im_B], 1)
            cv2.imwrite(path_AB, im_AB)
</code>```

答:
```<code>import os
import numpy as np
import cv2
import argparse

parser = argparse.ArgumentParser('create image pairs')
parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='a')
parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='b')
parser.add_argument('--fold_AB', dest='fold_AB', help='output directory', type=str, default='./c')
parser.add_argument('--num_imgs', dest='num_imgs', help='number of images', type=int, default=1)
parser.add_argument('--use_AB', dest='use_AB', help='if true: (0001_A, 0001_B) to (0001_AB)', action='store_true')
args = parser.parse_args()

for arg in vars(args):
    print('[%s] = ' % arg, getattr(args, arg))

img_fold_A = args.fold_A
img_fold_B = args.fold_B

splits = os.listdir(args.fold_A)
img_list = os.listdir(img_fold_A)
if args.use_AB:
    img_list = [img_path for img_path in img_list if '_A.' in img_path]

num_imgs = min(args.num_imgs, len(img_list))
splits = splits[:num_imgs] # select sub array

for sp in splits:
    img_fold_AB = os.path.join(args.fold_AB, sp)
    if not os.path.isdir(img_fold_AB):
        os.makedirs(img_fold_AB)

    # print('split = %s, number of images = %d' % (sp, num_imgs))

    name_A = sp
    path_A = os.path.join(img_fold_A, name_A)
    if args.use_AB:
        name_B = name_A.replace('_A.', '_B.')
    else:
        name_B = name_A
    path_B = os.path.join(img_fold_B, name_B)
    print('path_A', path_A, path_B, os.path.isfile(path_A), os.path.isfile(path_B))
    if os.path.isfile(path_A) and os.path.isfile(path_B):
        name_AB = name_A
        if args.use_AB:
            name_AB = name_AB.replace('_A.', '.')  # remove _A
        path_AB = os.path.join(img_fold_AB, name_AB)
        im_A = cv2.imread(path_A, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
        im_B = cv2.imread(path_B, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
        im_AB = np.concatenate([im_A, im_B], 1)
        print('path_AB', path_AB)
        cv2.imwrite(path_AB, im_AB)
    else:
        print('Else')
</code>```

Updated:

```<code>`img_fold_A = os.path.join(args.fold_A, sp)`
`img_fold_B = os.path.join(args.fold_B, sp)`
</code>```

To

img_fold_A = args.fold_A

img_fold_B = args.fold_B

Remove for n in range(num_imgs):

and update algorython with one loop

Body:
I have a folder which contains images named as 1_A.jpg,2_A.jpg....and so on. There exist another folder B which contains images named as 1_B.jpg, 2_B.jpg and so on. I want to concatenate the images 1_A and 1_B, 2_A 2_B and so on. i.e I want to concatenate the same name pair images. However, if I run the below code I am getting a concatenation of 1_B and 1_B and so on.

I also want to store the results in a folder named combined_canny. Here is my code.

import os
import numpy as np
import cv2
import argparse

parser = argparse.ArgumentParser('create image pairs')
parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='/home/vplab/pytorch-CycleGAN-and-pix2pix/datasets/canny/')
parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='/home/vplab/pytorch-CycleGAN-and-pix2pix/datasets/canny/')
parser.add_argument('--fold_AB', dest='fold_AB', help='output directory', type=str, default='/home/vplab/pytorch-CycleGAN-and-pix2pix/datasets/canny/combined_canny')
parser.add_argument('--num_imgs', dest='num_imgs', help='number of images', type=int, default=5000)
parser.add_argument('--use_AB', dest='use_AB', help='if true: (0001_A, 0001_B) to (0001_AB)', action='store_true')
args = parser.parse_args()

for arg in vars(args):
    print('[%s] = ' % arg, getattr(args, arg))

splits = os.listdir(args.fold_A)

for sp in splits:
    img_fold_A = os.path.join(args.fold_A, sp)
    img_fold_B = os.path.join(args.fold_B, sp)
    img_list = os.listdir(img_fold_A)
    if args.use_AB:
        img_list = [img_path for img_path in img_list if '_A.' in img_path]

    num_imgs = min(args.num_imgs, len(img_list))
    print('split = %s, use %d/%d images' % (sp, num_imgs, len(img_list)))
    img_fold_AB = os.path.join(args.fold_AB, sp)
    if not os.path.isdir(img_fold_AB):
        os.makedirs(img_fold_AB)
    print('split = %s, number of images = %d' % (sp, num_imgs))
    for n in range(num_imgs):
        name_A = img_list[n]
        path_A = os.path.join(img_fold_A, name_A)
        if args.use_AB:
            name_B = name_A.replace('_A.', '_B.')
        else:
            name_B = name_A
        path_B = os.path.join(img_fold_B, name_B)
        if os.path.isfile(path_A) and os.path.isfile(path_B):
            name_AB = name_A
            if args.use_AB:
                name_AB = name_AB.replace('_A.', '.')  # remove _A
            path_AB = os.path.join(img_fold_AB, name_AB)
            im_A = cv2.imread(path_A, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
            im_B = cv2.imread(path_B, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
            im_AB = np.concatenate([im_A, im_B], 1)
            cv2.imwrite(path_AB, im_AB)

Body:
import os
import numpy as np
import cv2
import argparse

parser = argparse.ArgumentParser('create image pairs')
parser.add_argument('--fold_A', dest='fold_A', help='input directory for image A', type=str, default='a')
parser.add_argument('--fold_B', dest='fold_B', help='input directory for image B', type=str, default='b')
parser.add_argument('--fold_AB', dest='fold_AB', help='output directory', type=str, default='./c')
parser.add_argument('--num_imgs', dest='num_imgs', help='number of images', type=int, default=1)
parser.add_argument('--use_AB', dest='use_AB', help='if true: (0001_A, 0001_B) to (0001_AB)', action='store_true')
args = parser.parse_args()

for arg in vars(args):
    print('[%s] = ' % arg, getattr(args, arg))

img_fold_A = args.fold_A
img_fold_B = args.fold_B

splits = os.listdir(args.fold_A)
img_list = os.listdir(img_fold_A)
if args.use_AB:
    img_list = [img_path for img_path in img_list if '_A.' in img_path]

num_imgs = min(args.num_imgs, len(img_list))
splits = splits[:num_imgs] # select sub array

for sp in splits:
    img_fold_AB = os.path.join(args.fold_AB, sp)
    if not os.path.isdir(img_fold_AB):
        os.makedirs(img_fold_AB)

    # print('split = %s, number of images = %d' % (sp, num_imgs))

    name_A = sp
    path_A = os.path.join(img_fold_A, name_A)
    if args.use_AB:
        name_B = name_A.replace('_A.', '_B.')
    else:
        name_B = name_A
    path_B = os.path.join(img_fold_B, name_B)
    print('path_A', path_A, path_B, os.path.isfile(path_A), os.path.isfile(path_B))
    if os.path.isfile(path_A) and os.path.isfile(path_B):
        name_AB = name_A
        if args.use_AB:
            name_AB = name_AB.replace('_A.', '.')  # remove _A
        path_AB = os.path.join(img_fold_AB, name_AB)
        im_A = cv2.imread(path_A, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
        im_B = cv2.imread(path_B, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
        im_AB = np.concatenate([im_A, im_B], 1)
        print('path_AB', path_AB)
        cv2.imwrite(path_AB, im_AB)
    else:
        print('Else')

Updated:

`img_fold_A = os.path.join(args.fold_A, sp)`
`img_fold_B = os.path.join(args.fold_B, sp)`

To

img_fold_A = args.fold_A

img_fold_B = args.fold_B

Remove for n in range(num_imgs):

and update algorython with one loop


问:
C#: Querying a remote server to see which user has a lock on a file
** EDIT: The original question was not clear. I can't FIND IADsFileServiceOperations in any .Net assembly, and that's the problem - not that I don't know how to use it **

I've been digging around for hours and can't figure this out...

In C#, is there a way to query a remote file server (preferably using a ManagementObjectSearcher but not nessecarily) and ask it which user currently has a lock on a file?

The best I could come up with is

```<code>var en = new DirectoryEntry($@"\\{hostName}\root\cimv2");
var fso = sessQuery.NativeObject as IADsFileServiceOperations;
var resources = fso.Resources();
</code>```

but for the life of me, I cannot figure out how to use IADsFileServiceOperations in a .Net project.

Help...? Please...?

答:
IADsFileServiceOperations is an interface that exposes two methods:

IADsFileServiceOperations::Resources

IADsFileServiceOperations::Sessions

https://learn.microsoft.com/en-us/windows/desktop/api/iads/nn-iads-iadsfileserviceoperations#methods

The IADsFileServiceOperations::Resources method gets a pointer to a
  pointer to the IADsCollection interface on a collection of the
  resource objects representing the current open resources on this file
  service.

```<code>var en = new DirectoryEntry($@"\\{hostName}\root\cimv2");
var fso = sessQuery.NativeObject as IADsFileServiceOperations;
var resources = fso.Resources(); // returns resource objects representing the current open resources on the file

foreach(var res in resources)
{
   // res.User
   // res.Path
   // res.LockCount
   if(res.LockCount > 0)
   {
      // user has lock on file
   }
}
</code>```

Update 1:

To add active directory types to your .NET project, you need to add a COM reference to the project. Go to the add reference dialog, then COM tab and add Active DS Type Library.

By adding this COM reference you have all AD types, interfaces by using ActiveDS.

Hope it solves your problem.

Body:
** EDIT: The original question was not clear. I can't FIND IADsFileServiceOperations in any .Net assembly, and that's the problem - not that I don't know how to use it **

I've been digging around for hours and can't figure this out...

In C#, is there a way to query a remote file server (preferably using a ManagementObjectSearcher but not nessecarily) and ask it which user currently has a lock on a file?

The best I could come up with is

var en = new DirectoryEntry($@"\\{hostName}\root\cimv2");
var fso = sessQuery.NativeObject as IADsFileServiceOperations;
var resources = fso.Resources();

but for the life of me, I cannot figure out how to use IADsFileServiceOperations in a .Net project.

Help...? Please...?

Body:
IADsFileServiceOperations is an interface that exposes two methods:

IADsFileServiceOperations::Resources

IADsFileServiceOperations::Sessions

https://learn.microsoft.com/en-us/windows/desktop/api/iads/nn-iads-iadsfileserviceoperations#methods

The IADsFileServiceOperations::Resources method gets a pointer to a
  pointer to the IADsCollection interface on a collection of the
  resource objects representing the current open resources on this file
  service.

var en = new DirectoryEntry($@"\\{hostName}\root\cimv2");
var fso = sessQuery.NativeObject as IADsFileServiceOperations;
var resources = fso.Resources(); // returns resource objects representing the current open resources on the file

foreach(var res in resources)
{
   // res.User
   // res.Path
   // res.LockCount
   if(res.LockCount > 0)
   {
      // user has lock on file
   }
}

Update 1:

To add active directory types to your .NET project, you need to add a COM reference to the project. Go to the add reference dialog, then COM tab and add Active DS Type Library.

By adding this COM reference you have all AD types, interfaces by using ActiveDS.

Hope it solves your problem.


问:
Create function/procedure to return table to get the last rows
I have several tables, each with a different key.

For example: the key for the Customer could be 2 or more columns.

Input - dbo.customer:

```<code>Customer e_Date    Value
------------------------
1000     2019-05-26  200
1000     2019-05-25  100
2000     2019-04-23   50
2000     2019-04-21   20
</code>```

Output :

```<code>Customer  e_date       value
----------------------------
1000      2019-05-26    200
2000      2019-04-23     50
</code>```

The max dates and the values for them was return for each customer (key).

I want to build a function or procedure in SQL where I will enter the name of table and the key and will return me the output. A return table function.

```<code>exec procedure get_Last_Row_By_Key (@Table_Name, @Key)
</code>```

and it will show me the output.

In this example :

```<code>exec procedure get_Last_Row_By_Key ('dbo.customer', Customer)
</code>```

I guess that when the @key will be multiple value I can do concat of the other columns to make them a one column key.

答:
The function call would need to be something like this:

```<code>exec procedure get_Last_Row_By_Key ('dbo.customer', 'Customer', 'e_date')
</code>```

To support multiple keys, I would use row_number(), even though that adds an extra column to the result set.  So the dynamic SQL would look like:

```<code>declare @sql nvarchar(max);

set @sql = '
select t.*
from (select t.*,
             row_number() over (partition by [key] order by [datecol]) as seqnum
      from [table] t
     ) t
where seqnum = 1
';

set @sql = replace(@sql, '[table]', @table);
set @sql = replace(@sql, '[key]', @key);
set @sql = replace(@sql, '[datecol]', @datecol);

exec sp_executesql @sql;
</code>```

Note:  I am explicitly not using quotename() here, so the code will allow multiple columns for either the key order "datecol".

Also, as an exercise, this might be useful for learning about dynamic SQL and stored procedures.  In general though, such attempts at "generic" processing are not as useful as they seem.  People who know SQL know how to write the query to do what they want on a table; they do not know custom stored procedures that do the same thing.

Body:
I have several tables, each with a different key.

For example: the key for the Customer could be 2 or more columns.

Input - dbo.customer:

Customer e_Date    Value
------------------------
1000     2019-05-26  200
1000     2019-05-25  100
2000     2019-04-23   50
2000     2019-04-21   20

Output :

Customer  e_date       value
----------------------------
1000      2019-05-26    200
2000      2019-04-23     50

The max dates and the values for them was return for each customer (key).

I want to build a function or procedure in SQL where I will enter the name of table and the key and will return me the output. A return table function.

exec procedure get_Last_Row_By_Key (@Table_Name, @Key)

and it will show me the output.

In this example :

exec procedure get_Last_Row_By_Key ('dbo.customer', Customer)

I guess that when the @key will be multiple value I can do concat of the other columns to make them a one column key.

Body:
The function call would need to be something like this:

exec procedure get_Last_Row_By_Key ('dbo.customer', 'Customer', 'e_date')

To support multiple keys, I would use row_number(), even though that adds an extra column to the result set.  So the dynamic SQL would look like:

declare @sql nvarchar(max);

set @sql = '
select t.*
from (select t.*,
             row_number() over (partition by [key] order by [datecol]) as seqnum
      from [table] t
     ) t
where seqnum = 1
';

set @sql = replace(@sql, '[table]', @table);
set @sql = replace(@sql, '[key]', @key);
set @sql = replace(@sql, '[datecol]', @datecol);

exec sp_executesql @sql;

Note:  I am explicitly not using quotename() here, so the code will allow multiple columns for either the key order "datecol".

Also, as an exercise, this might be useful for learning about dynamic SQL and stored procedures.  In general though, such attempts at "generic" processing are not as useful as they seem.  People who know SQL know how to write the query to do what they want on a table; they do not know custom stored procedures that do the same thing.


问:
Hiding The excel logo when Application.ExecuteExcel4Macro "Show.ToolBar(""Ribbon"",False)" is run
When you hide the ribbon using VBA code
The Excel Logo is shown on the top left corner of the Window.
I want to suppress that and ideally load my own logo in its place

I have no clue where to begin with this

The code I use to hide the ribbon is:

```<code>Application.ExecuteExcel4Macro "Show.ToolBar(""Ribbon"",False)"
</code>```

答:
I've now tested the code from Chip Pearson. It changes the icon on top left of the  window and also in the taskbar.
http://www.cpearson.com/excel/SetIcon.aspx
I've tested it with the elephant icon from PostgreSQL db.

Body:
When you hide the ribbon using VBA code
The Excel Logo is shown on the top left corner of the Window.
I want to suppress that and ideally load my own logo in its place

I have no clue where to begin with this

The code I use to hide the ribbon is:

Application.ExecuteExcel4Macro "Show.ToolBar(""Ribbon"",False)"


问:
How to test Aspect in Spring MVC application
I have a Spring MVC application where I use an Aspect to catch exceptions in all controller methods

```<code>@Component
@Aspect
public class ControllerExceptionAspect {

    private Logger logger;

    public ControllerExceptionAspect() {
       logger = Logger.getLogger(ControllerExceptionAspect.class);
    }

    public ControllerExceptionAspect(Logger logger) {
       this.logger = logger;
    }

    // Catching all exceptions from all methods in all controllers classes

    @AfterThrowing(pointcut = "execution(* com.my.package..controller..*(..))", throwing = "exception")
    public void afterThrowingAdvice(Exception exception) {
       logger.error("CONTROLLER ASPECT: EXCEPTION IN METHOD -> " +
       exception.getClass());
    }
}
</code>```

Aspect works fine but unfortunatelly I can not test it. I tried many times but can not get how to catch whether an Aspect method was called after I simulate exception in Controller

```<code>@SuppressWarnings("ALL")
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
        @ContextConfiguration(classes = RootConfig.class),
        @ContextConfiguration(classes = WebConfig.class)
})
public class ControllerExceptionAspectTest {

    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void testControllerExceptionAspectGetsExecutedWhenExceptionOccures(){
        HomeController homeController = (HomeController)applicationContext.getAutowireCapableBeanFactory().getBean("homeController");
        try{homeController.callMethod("00000");}
        catch (Exception e){}
        ControllerExceptionAspect controllerExceptionAspect = (ControllerExceptionAspect)applicationContext.getAutowireCapableBeanFactory().getBean("controllerExceptionAspect");
        // HOW TO CATCH THAT ASPECT METHOD WAS CALLED???
    }
}
</code>```

答:
It is pretty easy to test an aspect (including its pointcut expressions) in isolation, without the whole web context (or any context at all).

I will first try to give a generalized example, not the one that was in the OP question.

Let's imagine that we have an aspect that must throw an exception if a method's first argument is null, otherwise allow the method invocation proceed.

It should only be applied to controllers annotated with our custom @ThrowOnNullFirstArg annotation.

```<code>@Aspect
public class ThrowOnNullFirstArgAspect {
    @Pointcut("" +
            "within(@org.springframework.stereotype.Controller *) || " +
            "within(@(@org.springframework.stereotype.Controller *) *)")
    private void isController() {}

    @Around("isController()")
    public Object executeAroundController(ProceedingJoinPoint point) throws Throwable {
        throwIfNullFirstArgIsPassed(point);
        return point.proceed();
    }

    private void throwIfNullFirstArgIsPassed(ProceedingJoinPoint point) {
        if (!(point.getSignature() instanceof MethodSignature)) {
            return;
        }

        if (point.getArgs().length > 0 && point.getArgs()[0] == null) {
            throw new IllegalStateException("The first argument is not allowed to be null");
        }
    }
}
</code>```

We could test it like this:

```<code>public class ThrowOnNullFirstArgAspectTest {
    private final ThrowOnNullFirstArgAspect aspect = new ThrowOnNullFirstArgAspect();
    private TestController controllerProxy;

    @Before
    public void setUp() {
        AspectJProxyFactory aspectJProxyFactory = new AspectJProxyFactory(new TestController());
        aspectJProxyFactory.addAspect(aspect);

        DefaultAopProxyFactory proxyFactory = new DefaultAopProxyFactory();
        AopProxy aopProxy = proxyFactory.createAopProxy(aspectJProxyFactory);

        controllerProxy = (TestController) aopProxy.getProxy();
    }

    @Test
    public void whenInvokingWithNullFirstArg_thenExceptionShouldBeThrown() {
        try {
            controllerProxy.someMethod(null);
            fail("An exception should be thrown");
        } catch (IllegalStateException e) {
            assertThat(e.getMessage(), is("The first argument is not allowed to be null"));
        }
    }

    @Test
    public void whenInvokingWithNonNullFirstArg_thenNothingShouldBeThrown() {
        String result = controllerProxy.someMethod(Descriptor.builder().externalId("id").build());
        assertThat(result, is("ok"));
    }

    @Controller
    @ThrowOnNullFirstArg
    private static class TestController {
        @SuppressWarnings("unused")
        String someMethod(Descriptor descriptor) {
            return "ok";
        }
    }
}
</code>```

The key part is inside the setUp() method. Please note that it also allows to verify the correctness of your pointcut expression.

How to test that the aspect method actually gets called?

If the aspect method only has some some effect that is difficult to verify in tests, you could use a mock library like Mockito and make a stub around your real aspect and then verify that the method was actually called.

```<code>private ControllerExceptionAspect aspect = Mockito.stub(new     ControllerExceptionAspect());
</code>```

Then in your test, after invoking the controller via proxy

```<code>Mockito.verify(aspect).afterThrowingAdvice(Matchers.any());
</code>```

How to test that the aspect method actually writes to log?

If you are using logback-classic, you could write an Appender implementation and add it to the Logger of interest, and then inspect whether a message that you expect gets logged or not.

```<code>public class TestAppender extends AppenderBase<ILoggingEvent> {
    public List<ILoggingEvent> events = new ArrayList<>();

    @Override
    protected void append(ILoggingEvent event) {
        events.add(event);
    }
}
</code>```

In the fixture setup:

```<code>appender = new TestAppender();
// logback Appender must be started to accept messages
appender.start();
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ControllerExceptionAspect.class.class);
logger.addAppender(appender);
</code>```

and in your test:

```<code>List<ILoggingEvent> errors = appender.events.stream()
        .filter(event -> event.getLevel() == Level.ERROR)
        .collect(Collectors.toList());
assertEquals("Exactly one ERROR is expected in log", 1, errors.size());
// any other assertions you need
</code>```

Probably you would also need to stop() the Appender in @After method, but I'm not sure.

Body:
I have a Spring MVC application where I use an Aspect to catch exceptions in all controller methods

@Component
@Aspect
public class ControllerExceptionAspect {

    private Logger logger;

    public ControllerExceptionAspect() {
       logger = Logger.getLogger(ControllerExceptionAspect.class);
    }

    public ControllerExceptionAspect(Logger logger) {
       this.logger = logger;
    }

    // Catching all exceptions from all methods in all controllers classes

    @AfterThrowing(pointcut = "execution(* com.my.package..controller..*(..))", throwing = "exception")
    public void afterThrowingAdvice(Exception exception) {
       logger.error("CONTROLLER ASPECT: EXCEPTION IN METHOD -> " +
       exception.getClass());
    }
}

Aspect works fine but unfortunatelly I can not test it. I tried many times but can not get how to catch whether an Aspect method was called after I simulate exception in Controller

@SuppressWarnings("ALL")
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
        @ContextConfiguration(classes = RootConfig.class),
        @ContextConfiguration(classes = WebConfig.class)
})
public class ControllerExceptionAspectTest {

    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void testControllerExceptionAspectGetsExecutedWhenExceptionOccures(){
        HomeController homeController = (HomeController)applicationContext.getAutowireCapableBeanFactory().getBean("homeController");
        try{homeController.callMethod("00000");}
        catch (Exception e){}
        ControllerExceptionAspect controllerExceptionAspect = (ControllerExceptionAspect)applicationContext.getAutowireCapableBeanFactory().getBean("controllerExceptionAspect");
        // HOW TO CATCH THAT ASPECT METHOD WAS CALLED???
    }
}

Body:
It is pretty easy to test an aspect (including its pointcut expressions) in isolation, without the whole web context (or any context at all).

I will first try to give a generalized example, not the one that was in the OP question.

Let's imagine that we have an aspect that must throw an exception if a method's first argument is null, otherwise allow the method invocation proceed.

It should only be applied to controllers annotated with our custom @ThrowOnNullFirstArg annotation.

@Aspect
public class ThrowOnNullFirstArgAspect {
    @Pointcut("" +
            "within(@org.springframework.stereotype.Controller *) || " +
            "within(@(@org.springframework.stereotype.Controller *) *)")
    private void isController() {}

    @Around("isController()")
    public Object executeAroundController(ProceedingJoinPoint point) throws Throwable {
        throwIfNullFirstArgIsPassed(point);
        return point.proceed();
    }

    private void throwIfNullFirstArgIsPassed(ProceedingJoinPoint point) {
        if (!(point.getSignature() instanceof MethodSignature)) {
            return;
        }

        if (point.getArgs().length > 0 && point.getArgs()[0] == null) {
            throw new IllegalStateException("The first argument is not allowed to be null");
        }
    }
}

We could test it like this:

public class ThrowOnNullFirstArgAspectTest {
    private final ThrowOnNullFirstArgAspect aspect = new ThrowOnNullFirstArgAspect();
    private TestController controllerProxy;

    @Before
    public void setUp() {
        AspectJProxyFactory aspectJProxyFactory = new AspectJProxyFactory(new TestController());
        aspectJProxyFactory.addAspect(aspect);

        DefaultAopProxyFactory proxyFactory = new DefaultAopProxyFactory();
        AopProxy aopProxy = proxyFactory.createAopProxy(aspectJProxyFactory);

        controllerProxy = (TestController) aopProxy.getProxy();
    }

    @Test
    public void whenInvokingWithNullFirstArg_thenExceptionShouldBeThrown() {
        try {
            controllerProxy.someMethod(null);
            fail("An exception should be thrown");
        } catch (IllegalStateException e) {
            assertThat(e.getMessage(), is("The first argument is not allowed to be null"));
        }
    }

    @Test
    public void whenInvokingWithNonNullFirstArg_thenNothingShouldBeThrown() {
        String result = controllerProxy.someMethod(Descriptor.builder().externalId("id").build());
        assertThat(result, is("ok"));
    }

    @Controller
    @ThrowOnNullFirstArg
    private static class TestController {
        @SuppressWarnings("unused")
        String someMethod(Descriptor descriptor) {
            return "ok";
        }
    }
}

The key part is inside the setUp() method. Please note that it also allows to verify the correctness of your pointcut expression.

How to test that the aspect method actually gets called?

If the aspect method only has some some effect that is difficult to verify in tests, you could use a mock library like Mockito and make a stub around your real aspect and then verify that the method was actually called.

private ControllerExceptionAspect aspect = Mockito.stub(new     ControllerExceptionAspect());

Then in your test, after invoking the controller via proxy

Mockito.verify(aspect).afterThrowingAdvice(Matchers.any());

How to test that the aspect method actually writes to log?

If you are using logback-classic, you could write an Appender implementation and add it to the Logger of interest, and then inspect whether a message that you expect gets logged or not.

public class TestAppender extends AppenderBase<ILoggingEvent> {
    public List<ILoggingEvent> events = new ArrayList<>();

    @Override
    protected void append(ILoggingEvent event) {
        events.add(event);
    }
}

In the fixture setup:

appender = new TestAppender();
// logback Appender must be started to accept messages
appender.start();
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ControllerExceptionAspect.class.class);
logger.addAppender(appender);

and in your test:

List<ILoggingEvent> errors = appender.events.stream()
        .filter(event -> event.getLevel() == Level.ERROR)
        .collect(Collectors.toList());
assertEquals("Exactly one ERROR is expected in log", 1, errors.size());
// any other assertions you need

Probably you would also need to stop() the Appender in @After method, but I'm not sure.


问:
Virtual functions for 2 derived classes (Hex + binary)
I have base class Array in which I have virtual function Add for addition

```<code>class Array
{
public:
    unsigned char arr[100] = { 0 };
    int size;
    Array();
    Array(int);
    char operator[](int);
    virtual Array& Add( Array);
};
</code>```

I have two derived classes Hex ( for storing hexidecimal numbers ) and BitString( for storing binary numbers ):

```<code>class BitString : public Array
{
public:
    BitString& operator&(BitString&);//and
    BitString& operator|(BitString&);//or
    BitString& operator^(BitString&);//xor
    BitString& operator~();//not
};

class Hex: public Array
{
public:
    Hex& operator+(Hex);
    Hex& operator-(Hex);
    Hex& operator*(Hex);
    Hex& operator/(Hex);
    bool operator==(const Hex);
    bool operator>(const Hex);
    bool operator<(const Hex);
    Hex DecToHex(int);
};
</code>```

My task, except make operators for Hex and BitString,  is to override virtual Add function for addition BitString and Hex objects.

I dont properly get :

1) Need I make 2 functions in both Hex and BitString

2) What these functions should return? Hex, BitString or Array.

3) What is the  fastest way to do this? Convert both Hex and BitString to decimals, make addition and then convert again?

Thank you.

答:
Since your classes are polymorphic, the Add() function should be taking a reference or pointer parameter:

```<code>class Array {
    // ...

    virtual Array& Add(Array&);
};
</code>```

You can now override Add() in your derived classes with a different return type:

```<code>class Hex: public Array {
    // ...

    Hex& Add(Array&) override;
};
</code>```

The return type must be a reference type of the class that does the override. This is the only case where an override can change the return type.

Body:
I have base class Array in which I have virtual function Add for addition

class Array
{
public:
    unsigned char arr[100] = { 0 };
    int size;
    Array();
    Array(int);
    char operator[](int);
    virtual Array& Add( Array);
};

I have two derived classes Hex ( for storing hexidecimal numbers ) and BitString( for storing binary numbers ):

class BitString : public Array
{
public:
    BitString& operator&(BitString&);//and
    BitString& operator|(BitString&);//or
    BitString& operator^(BitString&);//xor
    BitString& operator~();//not
};

class Hex: public Array
{
public:
    Hex& operator+(Hex);
    Hex& operator-(Hex);
    Hex& operator*(Hex);
    Hex& operator/(Hex);
    bool operator==(const Hex);
    bool operator>(const Hex);
    bool operator<(const Hex);
    Hex DecToHex(int);
};

My task, except make operators for Hex and BitString,  is to override virtual Add function for addition BitString and Hex objects.

I dont properly get :

1) Need I make 2 functions in both Hex and BitString

2) What these functions should return? Hex, BitString or Array.

3) What is the  fastest way to do this? Convert both Hex and BitString to decimals, make addition and then convert again?

Thank you.

Body:
Since your classes are polymorphic, the Add() function should be taking a reference or pointer parameter:

class Array {
    // ...

    virtual Array& Add(Array&);
};

You can now override Add() in your derived classes with a different return type:

class Hex: public Array {
    // ...

    Hex& Add(Array&) override;
};

The return type must be a reference type of the class that does the override. This is the only case where an override can change the return type.


问:
How to round (or perhaps cut) of a float based on some conditions
I am trying to make a cryptocurrency bot and I am stuck at a problem. I want to round of the balances based on the data from the exchange because otherwise the exchange doesn’t accept the order request. For example my account contains 0.0044859999999999995 btc and the exchange Stepsize(a fancy name for rounding factor) is 0.00000100, how do I get 0.004485 and not rounded up because then the exchange will give error.
I have tried to do it with the following code.but doesn’t work </p>

```<code>import sys, signal, json, time
import random
import math
num = 0.0044859999999999995
numCoins = num - math.fmod(num, 0.000001)
print (numCoins) # want to get 0.004485 `
</code>```

答:
```<code>from decimal import Decimal, ROUND_DOWN

num = Decimal('0.0044859999999999995')
numCoins = num.quantize(Decimal('0.000001'), rounding=ROUND_DOWN)
print(numCoins)  # Decimal('0.004485')
</code>```

This Should for you.

Body:
I am trying to make a cryptocurrency bot and I am stuck at a problem. I want to round of the balances based on the data from the exchange because otherwise the exchange doesn’t accept the order request. For example my account contains 0.0044859999999999995 btc and the exchange Stepsize(a fancy name for rounding factor) is 0.00000100, how do I get 0.004485 and not rounded up because then the exchange will give error.
I have tried to do it with the following code.but doesn’t work

import sys, signal, json, time
import random
import math
num = 0.0044859999999999995
numCoins = num - math.fmod(num, 0.000001)
print (numCoins) # want to get 0.004485 `

Body:
from decimal import Decimal, ROUND_DOWN

num = Decimal('0.0044859999999999995')
numCoins = num.quantize(Decimal('0.000001'), rounding=ROUND_DOWN)
print(numCoins)  # Decimal('0.004485')

This Should for you.


问:
ProgressBar between to activities in android?
when click the grid item, i want to show a progressbar between the time of next Activity shown. then the second activity has a custom listview. there also i want to show a progressbar. how to do that? </p>

答:
You should try this,

First Create the ProgressDilog in Activity. . .

```<code>private ProgressDialog progressDialog;
</code>```

Now, Set the ProgressDialog in the Any action where u want to Take Some time

```<code>progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");
</code>```

Now use Thread to Handle the Progressbar

```<code>new Thread()
   {
    public void run()
    {
    try
    {
     sleep(1500);
// Now Do some Task whatever u want to do
   }
   catch(Exception e)
   {
     Log.e("tag",e.getMessage());
   }
}.start();
</code>```

Thats it. Hope this will help you.

ContentLicense: CC BY-SA 2.5

Body:
You should try this,

First Create the ProgressDilog in Activity. . .

private ProgressDialog progressDialog;

Now, Set the ProgressDialog in the Any action where u want to Take Some time

progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");

Now use Thread to Handle the Progressbar

new Thread()
   {
    public void run()
    {
    try
    {
     sleep(1500);
// Now Do some Task whatever u want to do
   }
   catch(Exception e)
   {
     Log.e("tag",e.getMessage());
   }
}.start();

Thats it. Hope this will help you.


问:
Spring Data Couchbase - Connection problem with single server
I am getting started with Spring Boot and Spring Data Couchbase and I am having problems to connect to my couchbase server.

I using IntelliJ and I have used the Spring Initialzr to create my project.

Here's my configuration (I am using Kotlin):

```<code>@Configuration
class Config : AbstractCouchbaseConfiguration() {

override fun getBootstrapHosts(): List<String> = Collections.singletonList("10.0.0.10")

override fun getBucketName(): String = "cwp"

override fun getBucketPassword(): String = "password"
</code>```

}

But instead of "just connecting" to the given ip there seems to be some reverse dns and so on in place which resolves wrong ips (due to routers and vpn) and so I am getting the following errors:

[CWSRV.fritz.box:8091][ConfigEndpoint]: Socket connect took longer than specified timeout: connection timed out: CWSRV.fritz.box/10.0.0.112:8091

The name of my server is CWSRV and I am using a vpn between my routers (Fritzboxes)

To omit such problems I want to use just the ip without any mishmash.

Any help would be appreciated!

答:
I figured it out myself:

It seems that the Java SDK does a reverse DNS lookup if it gets an IP address. Since I had not reverse zone created in my DNS server it resolved to the router on the server side which return cwsrv.fritz.box. That resolved to 10.0.0.112 (instead of 10.0.0.10 - my server could have had this ip address assigned from the router any time in the past) and there no Couchbase server responded).
I created an entry of the server in my DNS and it works.

Resolution: Since the Couchbase (Java) SDK seems to rely on properly configured DNS make sure that Forward and Reverse lookups work as expected! :)

Body:
I am getting started with Spring Boot and Spring Data Couchbase and I am having problems to connect to my couchbase server.

I using IntelliJ and I have used the Spring Initialzr to create my project.

Here's my configuration (I am using Kotlin):

@Configuration
class Config : AbstractCouchbaseConfiguration() {

override fun getBootstrapHosts(): List<String> = Collections.singletonList("10.0.0.10")

override fun getBucketName(): String = "cwp"

override fun getBucketPassword(): String = "password"

}

But instead of "just connecting" to the given ip there seems to be some reverse dns and so on in place which resolves wrong ips (due to routers and vpn) and so I am getting the following errors:

[CWSRV.fritz.box:8091][ConfigEndpoint]: Socket connect took longer than specified timeout: connection timed out: CWSRV.fritz.box/10.0.0.112:8091

The name of my server is CWSRV and I am using a vpn between my routers (Fritzboxes)

To omit such problems I want to use just the ip without any mishmash.

Any help would be appreciated!


问:
How efficiently we can get the required output from the list in java?
```<code>CircuitID   Department  Hours

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

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70
</code>```

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

```<code>Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50
</code>```

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

```<code>for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours
</code>```

Circuit class is having pojo objects with getter setters of this three objects.

```<code> public class Circuit {

        String circuitID;
        int hours;
        String department;
}
</code>```

答:
```<code>public static Map<String, Circuit> getMaxHours(final List<Circuit> circuitsList) {
    final Map<String, Circuit> mappedCircuitsById = new HashMap<String, Circuit>();

    for (final Circuit circuit : circuitsList) {
        if (!mappedCircuitsById.containsKey(circuit.getCircuitID())) {
            mappedCircuitsById.put(circuit.getCircuitID(), circuit);
        } else {
            final Circuit existingMax = mappedCircuitsById.get(circuit.getCircuitID());
            if (circuit.getHours() > existingMax.getHours()) mappedCircuitsById.put(circuit.getCircuitID(), circuit);
            else if (circuit.getHours() == existingMax.getHours()) {
                if (circuit.getDepartment().equals("Electricity")) mappedCircuitsById.put(circuit.getCircuitID(), circuit);
                else if (existingMax.getDepartment().equals("Electricity")) mappedCircuitsById.put(circuit.getCircuitID(), existingMax);
            }
        }
    }

    return mappedCircuitsById;
}
</code>```

Create a map where the key of the map is the circuitID and the value is the Circuit object which meets the "max hours" requirements. Iterate over the elements of the list and and update the map accordingly to store the new "max hours" Circuit object

Body:
CircuitID   Department  Hours

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

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours

Circuit class is having pojo objects with getter setters of this three objects.

 public class Circuit {

        String circuitID;
        int hours;
        String department;
}

Body:
public static Map<String, Circuit> getMaxHours(final List<Circuit> circuitsList) {
    final Map<String, Circuit> mappedCircuitsById = new HashMap<String, Circuit>();

    for (final Circuit circuit : circuitsList) {
        if (!mappedCircuitsById.containsKey(circuit.getCircuitID())) {
            mappedCircuitsById.put(circuit.getCircuitID(), circuit);
        } else {
            final Circuit existingMax = mappedCircuitsById.get(circuit.getCircuitID());
            if (circuit.getHours() > existingMax.getHours()) mappedCircuitsById.put(circuit.getCircuitID(), circuit);
            else if (circuit.getHours() == existingMax.getHours()) {
                if (circuit.getDepartment().equals("Electricity")) mappedCircuitsById.put(circuit.getCircuitID(), circuit);
                else if (existingMax.getDepartment().equals("Electricity")) mappedCircuitsById.put(circuit.getCircuitID(), existingMax);
            }
        }
    }

    return mappedCircuitsById;
}

Create a map where the key of the map is the circuitID and the value is the Circuit object which meets the "max hours" requirements. Iterate over the elements of the list and and update the map accordingly to store the new "max hours" Circuit object


问:
Javascript: Sort object array by number properties which include undefined
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);```
</div>
</div>
</p>

<p>The output is <code>1, 2, null</code>.</p>

<p>I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);</code>```

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);```

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/

答:
You can return the difference between the existence of a number property on each object being compared, OR return the difference in their number properties (in the case that both objects have said properties):

var array = [
  { number: 2 },
  {},
  { number: 1 }
];

array.sort((a, b) => {
  const aHas = typeof a.number !== 'undefined';
  const bHas = typeof b.number !== 'undefined';
  return (bHas - aHas) || (aHas === true && a.number - b.number) || 0;
});
console.log(array);```

Body:
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);

The output is 1, 2, null.

I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:

var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/


问:
`html-loader` overwrite `HtmlWebpackPlugin` `<%= %>` expression
I am using HtmlWebpackPlugin in webpack and below is its configuration:

```<code>new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html',
        inject: 'body',
        sdk: '/mylib.js'
      })
</code>```

In my html I define the script tag as:

```<code><script src="<%= htmlWebpackPlugin.options.sdk %>"></script>
</code>```

webpack will replace the <%= htmlWebpackPlugin.options.sdk %> with /mylib.js. However it doesn't work once I add the html-loader plugin as below:

```<code>{
          test: /\.html$/,
          use: [
            {
              loader: 'html-loader',
              options: {
                attrs: 'img:src'
              }
            }
          ]
        }
</code>```

The reason I use html-loader is to parse the img src tag on html file. But it conflicts with HtmlWebpackPlugin <%= ... %> expression. How can I make both of them work?

答:
You need to combine three steps.

First, you need HtmlWebpackPlugin. as indicated by https://stackoverflow.com/a/56264384/9363857

Second, you activate html-loader. This leads to the strange result of having a line like

```<code>module.exports=.....
</code>```

in the middle of your html (replacing the require), which is not really what you want.

So, third, you need to translate this back to html, for which you need to add an extract-loader. As in:

```<code>test: /\.(html)$/, use:  [ 'extract-loader',  { loader: 'html-loader' } ]
</code>```

Body:
I am using HtmlWebpackPlugin in webpack and below is its configuration:

new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html',
        inject: 'body',
        sdk: '/mylib.js'
      })

In my html I define the script tag as:

webpack will replace the <%= htmlWebpackPlugin.options.sdk %> with /mylib.js. However it doesn't work once I add the html-loader plugin as below:

{
          test: /\.html$/,
          use: [
            {
              loader: 'html-loader',
              options: {
                attrs: 'img:src'
              }
            }
          ]
        }

The reason I use html-loader is to parse the img src tag on html file. But it conflicts with HtmlWebpackPlugin <%= ... %> expression. How can I make both of them work?

Body:
You need to combine three steps.

First, you need HtmlWebpackPlugin. as indicated by https://stackoverflow.com/a/56264384/9363857

Second, you activate html-loader. This leads to the strange result of having a line like

module.exports=.....

in the middle of your html (replacing the require), which is not really what you want.

So, third, you need to translate this back to html, for which you need to add an extract-loader. As in:

test: /\.(html)$/, use:  [ 'extract-loader',  { loader: 'html-loader' } ]


问:
Remote Access to Local ASP.NET Core Applications From IP Address?
I want to (call)debug my asp.net core application from remote computer or mobile device? please help me. In standard .net add this code in .vs\config\applicationhost.config when change <binding protocol="http" bindingInformation="*:21918:localhost" /> to <binding protocol="http" bindingInformation="*:21918:*" />  its worked.

```<code>           <site name="project" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="F:\users\Api" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:21918:*" />
                </bindings>
            </site>
</code>```

答:
You can use this method:

Open Program.cs in your project:

```<code>        var configuration = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();

        var hostUrl = configuration["hosturl"]; // add this line
        if (string.IsNullOrEmpty(hostUrl)) // add this line
            hostUrl = "http://0.0.0.0:5001"; // add this line

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseUrls(hostUrl)   // // add this line
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseConfiguration(configuration)
            .Build();

        host.Run();
</code>```

More Info

Body:
I want to (call)debug my asp.net core application from remote computer or mobile device? please help me. In standard .net add this code in .vs\config\applicationhost.config when change <binding protocol="http" bindingInformation="*:21918:localhost" /> to <binding protocol="http" bindingInformation="*:21918:*" />  its worked.

           <site name="project" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="F:\users\Api" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:21918:*" />
                </bindings>
            </site>

Body:
You can use this method:

Open Program.cs in your project:

        var configuration = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Build();

        var hostUrl = configuration["hosturl"]; // add this line
        if (string.IsNullOrEmpty(hostUrl)) // add this line
            hostUrl = "http://0.0.0.0:5001"; // add this line

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseUrls(hostUrl)   // // add this line
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseConfiguration(configuration)
            .Build();

        host.Run();

More Info


问:
Rename files based on their created time + date
I've just started learning Python and trying to understand what's wrong with the code below.

For the test purpose there are 50 images that I want to rename as Hour.Minute.Second_Year_Month_Day.jpg. The code below executes, but I'm getting the current time and date as file name, not the creation date of the images.

What am I missing? I was reading that getctime is for Windows and for Mac birthtime, or I'm talking nonsense (Bringing this up since I'm on a Mac) ?

```<code>
directory = './'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( file )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension;

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index;
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0;

        os.rename( file, newfile );
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )

print( 'All done. ' + str(count) + ' files are renamed. ')
</code>```

答:
Under MacOS, you should try st_birthtime:

```<code>os.stat(file).st_birthtime
</code>```

Note that your current code works as expected on Windows.

Body:
I've just started learning Python and trying to understand what's wrong with the code below.

For the test purpose there are 50 images that I want to rename as Hour.Minute.Second_Year_Month_Day.jpg. The code below executes, but I'm getting the current time and date as file name, not the creation date of the images.

What am I missing? I was reading that getctime is for Windows and for Mac birthtime, or I'm talking nonsense (Bringing this up since I'm on a Mac) ?

directory = './'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( file )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension;

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index;
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0;

        os.rename( file, newfile );
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )

print( 'All done. ' + str(count) + ' files are renamed. ')

Body:
Under MacOS, you should try st_birthtime:

os.stat(file).st_birthtime

Note that your current code works as expected on Windows.


问:
History management problem in ASP.net
I created a simple page with an UpdatePanel, inside that I have a couple of asp Panel controls, all with the Visible property set to false except for one. When the user clicks on some buttons on the side menu, the Visible property switches between the Panels being displayed, giving the user the cool & slick ajax feel.

On the scriptManager I have EnableHistory set to true.
I added history points to save which Panel is displayed each time.
I added the OnNavigate event that switches the Panel visible's property according to the previous history point.

For some reason this doesn't work, and I don't have any error/exceptions...?!?
When I try to change the Page.Title property for example in the OnNavigate event, this works perfectly, but for some reason, changing the visibility of other controls doesn't...

Any suggestions ???

答: If you are simply changing the visibility of the panels and not retrieving new data via an AJAX call (you didn't specify), remove the UpdatePanel, replace the Panel controls with standard DIVs (not running at server) and just use JavaScript to hide and show the DIVs. If you ARE retrieving data in the AJAX call, then we'll have to think of something else ;)</p>

OwnerDisplayName: Gilly Barr

Title: History management problem in ASP.net

OwnerDisplayName: HardCode