问:
php pdo for Postgres: "could not find driver"
I installed php on a new Ubuntu 18.04 server for Postgres, and I have a problem with php.  Here are my php 7.3 installation steps:

```<code>sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php]
sudo systemctl restart apache2
</code>```

After installing PHP 7.3, I installed pgsql.

```<code>sudo apt install php-pgsql
sudo service apache2 reload
</code>```

Next I edited the php.ini file in /etc/php/7.3/apache2 and removed the semi-colons from the following lines:

```<code>extension=pdo_pgsql
extension=pgsql
</code>```

I saved the file and did sudo systemctl restart apache2.

Finally I enabled the modules:

```<code>sudo phpenmod -v 7.3 pgsql
sudo phpenmod -v 7.3 pdo_pgsql
sudo systemctl restart apache2
</code>```

Then I created a script to use pdo to log on to my Postgres database (the logon credentials are replaced with placeholder values here.)

```<code><?php

$params = [
    'host' => '[IP Address]',
    'user' => '[username]',
    'pwd' => '[password]',
    'db' => '[dbname]'
];

$dsn = sprintf('pgsql:host=%s;dbname=%s;user=%s;password=%s',
    $params['host'],
    $params['db'],
    $params['user'],
    $params['pwd']);

try {
    $dsn = sprintf('pgsql:host=%s;dbname=%s;unix_socket=%s',
        $params['host'], $params['db'], $params['sock']);
    $opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
    $pdo = new PDO($dsn, $params['user'], $params['pwd'], $opts);
} catch (PDOException $e) {
    echo $e->getMessage();
} catch (Throwable $e) {
    echo $e->getMessage();
}

?>
</code>```

But the Firefox dev console echoes back:  "could not find driver."

One clue is that php 7.3 is in /etc/apache2/mods-available, but it's not in /etc/apache2/mods-enabled, which suggests that it's not enabled.  But when I try phpenmod -v 7.3 php7.3.conf, I get: WARNING: Module php7.3.conf ini file doesn't exist under /etc/php/7.3/mods-available.

I've done a lot of research on this, and those are the steps to follow.  Much of that research was specific to MySQL, but that shouldn't matter for PDO.

Thanks for any ideas on why I am getting the message "could not find driver."

UPDATE:

I created a script to run phpinfo():

```<code><?php
ob_start();
phpinfo();
$info = ob_get_clean();
echo $info;
?>
</code>```

but it returns only html code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<style type="text/css">
body {background-color: #fff; color: #222; font-family: sans-serif;}
pre {margin: 0; font-family: monospace;}
a:link {color: #009; text-decoration: none; background-color: #fff;}
a:hover {text-decoration: underline;}
table {border-collapse: collapse; border: 0; width: 934px; box-shadow: 1px 2px 3px #ccc;}
.center {text-align: center;}
.center table {margin: 1em auto; text-align: left;}
.center th {text-align: center !important;}
td, th {border: 1px solid #666; font-size: 75%; vertical-align: baseline; padding: 4px 5px;}
h1 {font-size: 150%;}
h2 {font-size: 125%;}
.p {text-align: left;}
.e {background-color: #ccf; width: 300px; font-weight: bold;}
.h {background-color: #99c; font-weight: bold;}
.v {background-color: #ddd; max-width: 300px; overflow-x: auto; word-wrap:  break-word;}
.v i {color: #999;}
img {float: right; bo…
jquery.min.js line 2 > eval:12:21
?
</code>```

But that's not what I expected.

答:
As from our conversation, the issue was caused by having multiple versions of PHP installed and Apache was loading a different version of PHP (7.2) than the expected PHP 7.3.

To resolve the issue run the following commands:

```<code>sudo a2dismod php7.2
sudo a2enmod php7.3
</code>```

This will disable php7.2 from being loaded by Apache and load php7.3 instead.

For your DSN (data source name), your current configuration is using a unix_socket which does not appear to be a valid option for the postgresql DSN. Additionally the $params['socket'] to be used for the unix_socket parameter is missing.

For more details see: https://www.php.net/manual/en/ref.pdo-pgsql.connection.php

If the database server is listening on the default port (5432) you can use:

```<code>try {
    $dsn = vsprintf('pgsql:host=%s;port=%s;dbname=%s;user=%s;password=%s', [
        'host' => '[IP Address]',
        'port' => '5432',
        'dbname' => '[dbname]',
        'user' => '[username]',
        'password' => '[password]',
    ]);
    $pdo = new PDO($dsn);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMessage();
} catch (Throwable $e) {
    echo $e->getMessage();
}
</code>```

The DSN should result in: https://3v4l.org/aFKAW

```<code>pgsql:host=[IP Address];port=5432;dbname=[dbname];user=[username];password=[password]
</code>```

Body:
I installed php on a new Ubuntu 18.04 server for Postgres, and I have a problem with php.  Here are my php 7.3 installation steps:

sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php]
sudo systemctl restart apache2

After installing PHP 7.3, I installed pgsql.

sudo apt install php-pgsql
sudo service apache2 reload

Next I edited the php.ini file in /etc/php/7.3/apache2 and removed the semi-colons from the following lines:

extension=pdo_pgsql
extension=pgsql

I saved the file and did sudo systemctl restart apache2.

Finally I enabled the modules:

sudo phpenmod -v 7.3 pgsql
sudo phpenmod -v 7.3 pdo_pgsql
sudo systemctl restart apache2

Then I created a script to use pdo to log on to my Postgres database (the logon credentials are replaced with placeholder values here.)

<?php

$params = [
    'host' => '[IP Address]',
    'user' => '[username]',
    'pwd' => '[password]',
    'db' => '[dbname]'
];

$dsn = sprintf('pgsql:host=%s;dbname=%s;user=%s;password=%s',
    $params['host'],
    $params['db'],
    $params['user'],
    $params['pwd']);

try {
    $dsn = sprintf('pgsql:host=%s;dbname=%s;unix_socket=%s',
        $params['host'], $params['db'], $params['sock']);
    $opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
    $pdo = new PDO($dsn, $params['user'], $params['pwd'], $opts);
} catch (PDOException $e) {
    echo $e->getMessage();
} catch (Throwable $e) {
    echo $e->getMessage();
}

?>

But the Firefox dev console echoes back:  "could not find driver."

One clue is that php 7.3 is in /etc/apache2/mods-available, but it's not in /etc/apache2/mods-enabled, which suggests that it's not enabled.  But when I try phpenmod -v 7.3 php7.3.conf, I get: WARNING: Module php7.3.conf ini file doesn't exist under /etc/php/7.3/mods-available.

I've done a lot of research on this, and those are the steps to follow.  Much of that research was specific to MySQL, but that shouldn't matter for PDO.

Thanks for any ideas on why I am getting the message "could not find driver."

UPDATE:

I created a script to run phpinfo():

<?php
ob_start();
phpinfo();
$info = ob_get_clean();
echo $info;
?>

but it returns only html code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

Body:
As from our conversation, the issue was caused by having multiple versions of PHP installed and Apache was loading a different version of PHP (7.2) than the expected PHP 7.3.

To resolve the issue run the following commands:

sudo a2dismod php7.2
sudo a2enmod php7.3

This will disable php7.2 from being loaded by Apache and load php7.3 instead.

For your DSN (data source name), your current configuration is using a unix_socket which does not appear to be a valid option for the postgresql DSN. Additionally the $params['socket'] to be used for the unix_socket parameter is missing.

For more details see: https://www.php.net/manual/en/ref.pdo-pgsql.connection.php

If the database server is listening on the default port (5432) you can use:

try {
    $dsn = vsprintf('pgsql:host=%s;port=%s;dbname=%s;user=%s;password=%s', [
        'host' => '[IP Address]',
        'port' => '5432',
        'dbname' => '[dbname]',
        'user' => '[username]',
        'password' => '[password]',
    ]);
    $pdo = new PDO($dsn);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMessage();
} catch (Throwable $e) {
    echo $e->getMessage();
}

The DSN should result in: https://3v4l.org/aFKAW

pgsql:host=[IP Address];port=5432;dbname=[dbname];user=[username];password=[password]


来源: stackexchange

问:
bootstrap navbar is not working properly for Laravel, only a part is working
I created a navbar from bootstrap inside resources/views/inc -> navbar.blade.php

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">Project</a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
        <li><a href="/contact">Contact</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div>
</nav>
</code>```

The first div tag is working fine but the second div tag is not visible in the output

And I properly include the navbar in a separate file inside resources/views/layouts -> app.blade.php

```<code><body>
    @include('inc.navbar')
    <div class="container">
        @yield('content')
    </div>
</body>
</code>```

Please help me with this

edit

I removed class="collapse navbar-collapse", then the navigation links are appearing, what is the issue with the compatibility on the collapse?

答:
If you are referring to wanting this div to be visible immediately (without clicking):

```<code><div id="navbar" class="collapse navbar-collapse">...</div>
</code>```

As it is, it is not meant to be visible upon load.  If you want it to load, you've got an extra collapse class in there, which is effectively hiding the div, remove it, and it should be visible for you:

```<code><div id="navbar" class="navbar-collapse"> <-- No collapse
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a navbar from bootstrap inside resources/views/inc -> navbar.blade.php

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      Project

Home

About

Contact

The first div tag is working fine but the second div tag is not visible in the output

And I properly include the navbar in a separate file inside resources/views/layouts -> app.blade.php

    @include('inc.navbar')

        @yield('content')

Please help me with this

edit

I removed class="collapse navbar-collapse", then the navigation links are appearing, what is the issue with the compatibility on the collapse?

Body:
If you are referring to wanting this div to be visible immediately (without clicking):

<div id="navbar" class="collapse navbar-collapse">...</div>

As it is, it is not meant to be visible upon load.  If you want it to load, you've got an extra collapse class in there, which is effectively hiding the div, remove it, and it should be visible for you:

<div id="navbar" class="navbar-collapse"> <-- No collapse


问:
How do I receive messages from an Artemis multicast queue in C#?
I'm up to send and receive messages over ActiveMQ Artemis with C# applications. In Anycast-mode, everything is working.

When i tried to send and receive in multicast-mode, i can send, but i don't receive any of the messages from the queue.

I tried the trick from java, set the "multicast" flag before the tcp uri, but an error message shows up that there isn't an implementation for "multicast"

private void Receiver()
{
    IConnectionFactory factory = new NMSConnectionFactory("multicast:tcp://172.29.213.150:61616");
    IConnection connection = factory.CreateConnection("artemis", "simetraehcapa");
    connection.Start();
    ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
    IDestination destination = SessionUtil.GetDestination(session, "hund");
    IMessageConsumer receiver = session.CreateConsumer(destination);
    receiver.Listener += new MessageListener(Message_Listener);
}
```

Normally I would receive the messages, because I only switched from anycast to multicast, but actually I receive nothing.

答:
If using the AcitveMQ OpenWire NMS client you don't apply that odd multicast thing you've done to the URI, that will give you an error.  The client should just work if you use the Session API and not that confusing SessionUtil API that has resulted in many people running into issues.  </p>

<p>I'd use Session.CreateTopic to get an ITopic instance and then create a consumer using that which should map over into Artemis Multicast addresses without you needing to do anything.  You do of course need to be subscribed before any messages are sent as Topics don't retain messages if no consumers are around when the are sent. </p>

Body:
I'm up to send and receive messages over ActiveMQ Artemis with C# applications. In Anycast-mode, everything is working.

When i tried to send and receive in multicast-mode, i can send, but i don't receive any of the messages from the queue.

I tried the trick from java, set the "multicast" flag before the tcp uri, but an error message shows up that there isn't an implementation for "multicast"

private void Receiver()
{
    IConnectionFactory factory = new NMSConnectionFactory("multicast:tcp://172.29.213.150:61616");
    IConnection connection = factory.CreateConnection("artemis", "simetraehcapa");
    connection.Start();
    ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
    IDestination destination = SessionUtil.GetDestination(session, "hund");
    IMessageConsumer receiver = session.CreateConsumer(destination);
    receiver.Listener += new MessageListener(Message_Listener);
}

Normally I would receive the messages, because I only switched from anycast to multicast, but actually I receive nothing.

Body:
If using the AcitveMQ OpenWire NMS client you don't apply that odd multicast thing you've done to the URI, that will give you an error.  The client should just work if you use the Session API and not that confusing SessionUtil API that has resulted in many people running into issues.

I'd use Session.CreateTopic to get an ITopic instance and then create a consumer using that which should map over into Artemis Multicast addresses without you needing to do anything.  You do of course need to be subscribed before any messages are sent as Topics don't retain messages if no consumers are around when the are sent.


问:
Checking if button is held for a duration or if it is just clicked ANDROID
I'm trying to do something pretty simple, but for some reason I can't get it to work.
I have two circular buttons.

-When I simply click the top (green) button, I want the buttons to switch colors and remain that way.

-If I HOLD a button for 2 seconds, I want the colors to swap for as long as I hold the button, but then revert back to their original colors as soon as I let go.

I am trying to use an OnClickListener. I am using a switch with 2 cases: MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP. (see code below)

To get the duration the button is being held, I use System.currentTimeMillis() within a while loop (while button is being held) --> (if timeElapsed > 2000){switch the colors}

full code below:

```<code>    greenbutton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    startTime = System.currentTimeMillis();
                    while (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        currentTime = System.currentTimeMillis();
                        elapsedTime = currentTime - startTime;
                        if (elapsedTime > 500) {
                            if (switched) {
                                revertButtons();
                                return true;
                            } else {
                                switchButtons();
                                return true;
                            }
                        }
                    }

                case MotionEvent.ACTION_UP:

                    if (switched) {
                        revertButtons();
                        elapsedTime = 0;
                        currentTime = 0;
                        startTime = 0;
                        return true;
                    } else {
                        switchButtons();
                        elapsedTime = 0;
                        currentTime = 0;
                        startTime = 0;
                        return true;
                    }

            }
            return false;
        }
    });
</code>```

答:
Try use the predefined methods -

onClickListener( () => {} ) for single clicks

onLongClickListener( () => {} ) for long clicks

This way you don't need to calculate the time the user clicked and by running a loop or thread you may keep changing colours on long clicks.

UPDATED

As mentioned in comment its needed only a particular timing use the following algorithm-

Start a timer on long click of button

As soon as 2 seconds pass you apply your result

** UPDATED**

As the time of click is required follow :

Create a timer before button definition

Start timer with the long click lister

On action up stop timer and you get your result

Body:
I'm trying to do something pretty simple, but for some reason I can't get it to work.
I have two circular buttons.

-When I simply click the top (green) button, I want the buttons to switch colors and remain that way.

-If I HOLD a button for 2 seconds, I want the colors to swap for as long as I hold the button, but then revert back to their original colors as soon as I let go.

I am trying to use an OnClickListener. I am using a switch with 2 cases: MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP. (see code below)

To get the duration the button is being held, I use System.currentTimeMillis() within a while loop (while button is being held) --> (if timeElapsed > 2000){switch the colors}

full code below:

    greenbutton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    startTime = System.currentTimeMillis();
                    while (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        currentTime = System.currentTimeMillis();
                        elapsedTime = currentTime - startTime;
                        if (elapsedTime > 500) {
                            if (switched) {
                                revertButtons();
                                return true;
                            } else {
                                switchButtons();
                                return true;
                            }
                        }
                    }

                case MotionEvent.ACTION_UP:

                    if (switched) {
                        revertButtons();
                        elapsedTime = 0;
                        currentTime = 0;
                        startTime = 0;
                        return true;
                    } else {
                        switchButtons();
                        elapsedTime = 0;
                        currentTime = 0;
                        startTime = 0;
                        return true;
                    }

            }
            return false;
        }
    });


问:
How to get an AWS EC2 instance ID from within that EC2 instance?
How can I find out the instance id of an ec2 instance from within the ec2 instance?

答: For AWS elastic beanstalk eb cli run eb tags --list

OwnerDisplayName: andy


问:
C++ alloc array of objects
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

```<code>ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}
</code>```

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)

答:
Here's the simplest solution to your problem.</p>

```<code>out[i].open(fileName);
</code>```

ContentLicense: CC BY-SA 3.0

Title: C++ alloc array of objects

Body:
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)

Body:
Here's the simplest solution to your problem.

out[i].open(fileName);


问:
How to save a text file in external storage in ios using flutter?
I have created an app in which user can create and save a text file in the local storage of Android. I have used path_provider package which gives getExternalStorageDirectory() to save the data in the external storage. But I can not find the same for ios. getExternalStorageDirectory() is not supported for ios.

I want to save the file so that user can later on access the file from Files app in ios.

```<code>Future<String> get _localPath async{
var dir = await getExternalStorageDirectory();

  return dir.path;
}

Future<File> get _localFile async{
  final path = await _localPath;

  return File('$path/test.txt');
}

Future<File> writeData(String msg) async{
  final file = await _localFile;

  return file.writeAsString(msg);
}
</code>```

The above code works for Android(if storage permissions are provided). Can anyone help me for achieving the same in ios.

答:
You can save the file in the NSDocumentsDirectory (getApplicationDocumentsDirectory()) and then make it available to the user.

From: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

Use this directory to store user-generated content. The contents of this directory can be made available to the user through file sharing; therefore, his directory should only contain files that you may wish to expose to the user.

To make the directory available to the user you need to open the Xcode project under 'your_app/ios/Runner.xcworkspace'. Then open the Info.plist file in the Runner directory and add two rows with the key UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace. Set the value of both keys to YES.

If you now open the Files app and click on 'On My iPhone' you should see a folder with the name of your application.

Body:
I have created an app in which user can create and save a text file in the local storage of Android. I have used path_provider package which gives getExternalStorageDirectory() to save the data in the external storage. But I can not find the same for ios. getExternalStorageDirectory() is not supported for ios.

I want to save the file so that user can later on access the file from Files app in ios.

Future<String> get _localPath async{
var dir = await getExternalStorageDirectory();

  return dir.path;
}

Future<File> get _localFile async{
  final path = await _localPath;

  return File('$path/test.txt');
}

Future<File> writeData(String msg) async{
  final file = await _localFile;

  return file.writeAsString(msg);
}

The above code works for Android(if storage permissions are provided). Can anyone help me for achieving the same in ios.


问:
Laravel CRUD delete route parameters
Id' like to use a CRUD Controller to handle the admin profile. I created the Controller and edited my routes/web.php like this.

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.', 'middleware' => ['auth:admin']], function(){
    Route::resource('profile', 'ProfileController')->only(['index', 'edit', 'update', 'destroy']);
});
```

<p>This creates the following routes.</p>

```admin/profile -> admin.profile.index
admin/profile/{profile} -> admin.profile.destroy
admin/profile/{profile} -> admin.profile.update
admin/profile/{profile}/edit -> admin.profile.edit
```

Since I get the admin_id through the session I don't need to get it through the URL via the profile parameter. I know that I could just ignore the parameter, but it makes the URL unnecessary long.
Is there a chance to delete the {profile} parameter from the routes, so that my routes are like teacher/profile/edit and not like teacher/profile/12345678/edit?

答:
Yes you can remove that perticular parameters from route.

but instead on this you have to send profile data through post variable

This is not possible to send post data in every redirection.

I will suggest you to use 'Slugs' instead of profile id

Title: Laravel CRUD delete route parameters

Body:
Id' like to use a CRUD Controller to handle the admin profile. I created the Controller and edited my routes/web.php like this.

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.', 'middleware' => ['auth:admin']], function(){
    Route::resource('profile', 'ProfileController')->only(['index', 'edit', 'update', 'destroy']);
});

This creates the following routes.

admin/profile -> admin.profile.index
admin/profile/{profile} -> admin.profile.destroy
admin/profile/{profile} -> admin.profile.update
admin/profile/{profile}/edit -> admin.profile.edit

Since I get the admin_id through the session I don't need to get it through the URL via the profile parameter. I know that I could just ignore the parameter, but it makes the URL unnecessary long.
Is there a chance to delete the {profile} parameter from the routes, so that my routes are like teacher/profile/edit and not like teacher/profile/12345678/edit?


问:
Passing a 2D array to a C++ function
I have a function which I want to take, as a parameter, a 2D array of variable size.

So far I have this:

```<code>void myFunction(double** myArray){
     myArray[x][y] = 5;
     etc...
}
</code>```

And I have declared an array elsewhere in my code:

```<code>double anArray[10][10];
</code>```

However, calling myFunction(anArray) gives me an error.

I do not want to copy the array when I pass it in. Any changes made in myFunction should alter the state of anArray. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10] and [5][5]. How can I do this?

答:
If you want to pass int a[2][3] to void func(int** pp) you need auxiliary steps as follows.

```<code>int a[2][3];
int* p[2] = {a[0],a[1]};
int** pp = p;

func(pp);
</code>```

As the first [2] can be implicitly specified,  it can be simplified further as.

```<code>int a[][3];
int* p[] = {a[0],a[1]};
int** pp = p;

func(pp);
</code>```

Title: Passing a 2D array to a C++ function

Body:
I have a function which I want to take, as a parameter, a 2D array of variable size.

So far I have this:

void myFunction(double** myArray){
     myArray[x][y] = 5;
     etc...
}

And I have declared an array elsewhere in my code:

double anArray[10][10];

However, calling myFunction(anArray) gives me an error.

I do not want to copy the array when I pass it in. Any changes made in myFunction should alter the state of anArray. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10] and [5][5]. How can I do this?

Body:
If you want to pass int a[2][3] to void func(int** pp) you need auxiliary steps as follows.

int a[2][3];
int* p[2] = {a[0],a[1]};
int** pp = p;

func(pp);

As the first [2] can be implicitly specified,  it can be simplified further as.

int a[][3];
int* p[] = {a[0],a[1]};
int** pp = p;

func(pp);


问:
I have some questions about the way to assign values to the std::array
I'm learning C++ on codesdope.com and I have read a document on another website, learncpp.com. But these two websites have different ways to assign values to the array.

```<code>//codesdope.com

std::array<int,5> n  {{1,2,3,4,5}};
</code>```

```<code>//learncpp.com

std::array<int,5> n = {1,2,3,4,5};
</code>```

Which way is more accurate? Which way should I choose? What is the difference between them?

答:
Double-braces required in C++11 prior to the CWG 1270 (not needed in C++11 after the revision and in C++14 and beyond):

```<code>// construction uses aggregate initialization
std::array<int, 5> a{ {1, 2, 3, 4, 5} }; // double-braces required in C++11 prior to the CWG 1270 revision
std::array<int, 5> a{1, 2, 3, 4, 5}; // not needed in C++11 after the revision and in C++14 and beyond
std::array<int, 5> a = {1, 2, 3, 4, 5};  // never required after =
</code>```

std::array reference

Body:
I'm learning C++ on codesdope.com and I have read a document on another website, learncpp.com. But these two websites have different ways to assign values to the array.

//codesdope.com

std::array<int,5> n  {{1,2,3,4,5}};

//learncpp.com

std::array<int,5> n = {1,2,3,4,5};

Which way is more accurate? Which way should I choose? What is the difference between them?

Body:
Double-braces required in C++11 prior to the CWG 1270 (not needed in C++11 after the revision and in C++14 and beyond):

// construction uses aggregate initialization
std::array<int, 5> a{ {1, 2, 3, 4, 5} }; // double-braces required in C++11 prior to the CWG 1270 revision
std::array<int, 5> a{1, 2, 3, 4, 5}; // not needed in C++11 after the revision and in C++14 and beyond
std::array<int, 5> a = {1, 2, 3, 4, 5};  // never required after =

std::array reference


问:
Appinventor - finding the launch icon / starting appinventor
Could someone explain how to start Appinventor after installing?

I downloaded the file and placed in folder as indicated in the provided instructions but am unable to find the launching icon for the Appinventor editor.

http://appinventor.googlelabs.com/about/

答:
Just sign up for a google ID (if you don't already have one) and google it (or go to the more selection under the "More>>" menu) </p>

<p>I believe that the apps made by the AppInventor cannot be places on the Android Market, I know this from personal experience   </p>

Body:
Just sign up for a google ID (if you don't already have one) and google it (or go to the more selection under the "More>>" menu)

I believe that the apps made by the AppInventor cannot be places on the Android Market, I know this from personal experience


答:
If dat is as shown reproducibly in the Note at the end then as.data.frame(dat) creates a data frame with one column called dat and then when there is an attempt to take the 3rd column an error results since there is only one column.

Instead, use read.table and get the third column like this.  Omit the comma if you want a data frame result.

```<code>read.table(text = dat)[, 3]
## [1]  5.0  6.7 10.4 13.2 15.4 17.3
</code>```

Note

```<code>dat <- c("   1931   1    5.0     0.6      11    78.4    43.4",
  "   1931   2    6.7     0.7       7    48.9    63.6",
  "   1931   4   10.4     3.1       3    44.6   110.1",
  "   1931   5   13.2     6.1       1    63.7   167.4",
  "   1931   6   15.4     8.0       0    87.8   150.3",
  "   1931   7   17.3    10.6       0   121.4   111.2")
</code>```

Title: How to convert a character array to data frame

Body:
I have a character array dat which I want to convert to a data frame df but it is not working

 head(dat)
[1] "   1931   1    5.0     0.6      11    78.4    43.4"
[2] "   1931   2    6.7     0.7       7    48.9    63.6"
[3] "   1931   4   10.4     3.1       3    44.6   110.1"
[4] "   1931   5   13.2     6.1       1    63.7   167.4"
[5] "   1931   6   15.4     8.0       0    87.8   150.3"
[6] "   1931   7   17.3    10.6       0   121.4   111.2"

> df<-as.data.frame(dat)
> head(df)
                                                 dat
1    1931   1    5.0     0.6      11    78.4    43.4
2    1931   2    6.7     0.7       7    48.9    63.6
3    1931   4   10.4     3.1       3    44.6   110.1
4    1931   5   13.2     6.1       1    63.7   167.4
5    1931   6   15.4     8.0       0    87.8   150.3
6    1931   7   17.3    10.6       0   121.4   111.2

df[,c(3)]

Error in [.data.frame(df, , c(3)) : undefined columns selected

Body:
If dat is as shown reproducibly in the Note at the end then as.data.frame(dat) creates a data frame with one column called dat and then when there is an attempt to take the 3rd column an error results since there is only one column.

Instead, use read.table and get the third column like this.  Omit the comma if you want a data frame result.

read.table(text = dat)[, 3]
## [1]  5.0  6.7 10.4 13.2 15.4 17.3

Note

dat <- c("   1931   1    5.0     0.6      11    78.4    43.4",
  "   1931   2    6.7     0.7       7    48.9    63.6",
  "   1931   4   10.4     3.1       3    44.6   110.1",
  "   1931   5   13.2     6.1       1    63.7   167.4",
  "   1931   6   15.4     8.0       0    87.8   150.3",
  "   1931   7   17.3    10.6       0   121.4   111.2")


问:
How to enable external file linking in CefPython?
I am working on a CEFPython application that requires me to include some external files like JS or CSS libraries.However any external path (Referring to external libraries present in the same folder and the online resource URL both) mentioned in the HTML file seems to be unacceptable, I am sure am missing a flag to enable external files liking but am unable to figure out which. below is the code to my main function:</p>

```<code>def main():
sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error
# To change user agent use either "product_version"
# or "user_agent" options. Explained in Tutorial in
# "Change user agent string" section.
settings = {
    # "web_security_disabled": True,
    # "user_agent": "MyAgent/20.00 MyProduct/10.00",

}
cef.Initialize(settings=settings)
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),
                                window_title="Demo Program")
set_javascript_bindings(browser)
cef.MessageLoop()
cef.Shutdown()
</code>```

答:
You cannot mix scripts from different origins, see:
https://en.wikipedia.org/wiki/Same-origin_policy

There is --disable-web-security switch that you can try.

If that doesn't work then use "http" url instead of data uri. You can run an internal web server using Python. You can also implement ResourceHandler and serve http content without the need to run a web server, however implementing ResourceHandler correctly is a complex task.

Body:
I am working on a CEFPython application that requires me to include some external files like JS or CSS libraries.However any external path (Referring to external libraries present in the same folder and the online resource URL both) mentioned in the HTML file seems to be unacceptable, I am sure am missing a flag to enable external files liking but am unable to figure out which. below is the code to my main function:

def main():
sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error
# To change user agent use either "product_version"
# or "user_agent" options. Explained in Tutorial in
# "Change user agent string" section.
settings = {
    # "web_security_disabled": True,
    # "user_agent": "MyAgent/20.00 MyProduct/10.00",

}
cef.Initialize(settings=settings)
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),
                                window_title="Demo Program")
set_javascript_bindings(browser)
cef.MessageLoop()
cef.Shutdown()


问:
How to define empty variable in python or pass value from a function to global variable?
I am making some kind of basic image filter app. I have a function to open and initialize image but variables stay just in function and I can't get them from another function, so I need to define variables global?

I tried to define variables globally and initialize them with example image, then in function I assigned new data to that variables (or not?) But it seems function that opens the file does not rewrite global variable, so my filter functions applies to my example image, not target image I opened.

image = Image.open("test.jpg")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pix = image.load()

class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.load_file.triggered.connect(self.load_image) #Can I here call load_image with arguments? How?
        self.grayscale.triggered.connect(self.Grayscale)
    def browse_file(self):
        file_name = QtWidgets.QFileDialog.getOpenFileName(self, 'Pick a picture',"","JPEG (*.jpg;*.jpeg);;PNG (*.png);;All Files (*)")[0]
        if file_name:
            print (file_name)
            return file_name
        else:
            print("File couldn't be open")
            return 0
    def load_image(self):
        file_name = self.browse_file()
        pixmap = QPixmap(file_name)
        self.pic_box.setPixmap(pixmap)
        self.pic_box.resize(pixmap.width(), pixmap.height())
        print(pixmap.width(), pixmap.height())
        self.resize(pixmap.width(), pixmap.height())
        image = Image.open(file_name) #Here I'm trying assign new image and it's properties to variables I defined on the first lines
        draw = ImageDraw.Draw(image)
        width = image.size[0]
        height = image.size[1]
        pix = image.load()
        self.show()
    def Grayscale(self): #Function works with test.jpg, not with file I'm trying to load
        for i in range(width):
            for j in range(height):
                a = pix[i, j][0]
                b = pix[i, j][1]
                c = pix[i, j][2]
                S = (a + b + c) // 3
                draw.point((i, j), (S, S, S))
        image.save("Grayscale.jpg", "JPEG")
```

My goal is to somehow pass string with file name to the global variable, so every function could access it.
There is other design.py file, I made from .ui file of QtDesigner but I think problem does not depends on it

答:
If you really want to use a global variable, than can't you just do

```<code>filename = "test.jpg"
image = Image.Open(filename)
...
</code>```

at the top?

Body:
I am making some kind of basic image filter app. I have a function to open and initialize image but variables stay just in function and I can't get them from another function, so I need to define variables global?

I tried to define variables globally and initialize them with example image, then in function I assigned new data to that variables (or not?) But it seems function that opens the file does not rewrite global variable, so my filter functions applies to my example image, not target image I opened.

image = Image.open("test.jpg")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pix = image.load()

class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.load_file.triggered.connect(self.load_image) #Can I here call load_image with arguments? How?
        self.grayscale.triggered.connect(self.Grayscale)
    def browse_file(self):
        file_name = QtWidgets.QFileDialog.getOpenFileName(self, 'Pick a picture',"","JPEG (*.jpg;*.jpeg);;PNG (*.png);;All Files (*)")[0]
        if file_name:
            print (file_name)
            return file_name
        else:
            print("File couldn't be open")
            return 0
    def load_image(self):
        file_name = self.browse_file()
        pixmap = QPixmap(file_name)
        self.pic_box.setPixmap(pixmap)
        self.pic_box.resize(pixmap.width(), pixmap.height())
        print(pixmap.width(), pixmap.height())
        self.resize(pixmap.width(), pixmap.height())
        image = Image.open(file_name) #Here I'm trying assign new image and it's properties to variables I defined on the first lines
        draw = ImageDraw.Draw(image)
        width = image.size[0]
        height = image.size[1]
        pix = image.load()
        self.show()
    def Grayscale(self): #Function works with test.jpg, not with file I'm trying to load
        for i in range(width):
            for j in range(height):
                a = pix[i, j][0]
                b = pix[i, j][1]
                c = pix[i, j][2]
                S = (a + b + c) // 3
                draw.point((i, j), (S, S, S))
        image.save("Grayscale.jpg", "JPEG")

My goal is to somehow pass string with file name to the global variable, so every function could access it.
There is other design.py file, I made from .ui file of QtDesigner but I think problem does not depends on it

Body:
If you really want to use a global variable, than can't you just do

filename = "test.jpg"
image = Image.Open(filename)
...

at the top?


答:
I found a simple solution studying how the long press event works.
Each time a view is clicked, a Runnable of type CheckForLongPress is added to a queue with a delay. If the delay ends, the OnLongClickListener is called. If there is a different event before the delay ends, then, the CheckForLongPress Runnable is removed from de queue.

I just override the public method postDelayed(Runnable action, long delayMillis) of the view to change the OS delay

```<code>@Override public boolean postDelayed(Runnable action, long delayMillis) {
    boolean isLongPress = action.getClass().getSimpleName().equals("CheckForLongPress");
    return super.postDelayed(action, isLongPress ? LONG_PRESS_MILLIS : delayMillis);
}
</code>```

I set LONG_PRESS_MILLIS to 100 and it's working!

Hope it helps!!! ;)

Credit: MArtinCR

Title: Checking if button is held for a duration or if it is just clicked ANDROID

Body:
I found a simple solution studying how the long press event works.
Each time a view is clicked, a Runnable of type CheckForLongPress is added to a queue with a delay. If the delay ends, the OnLongClickListener is called. If there is a different event before the delay ends, then, the CheckForLongPress Runnable is removed from de queue.

I just override the public method postDelayed(Runnable action, long delayMillis) of the view to change the OS delay

@Override public boolean postDelayed(Runnable action, long delayMillis) {
    boolean isLongPress = action.getClass().getSimpleName().equals("CheckForLongPress");
    return super.postDelayed(action, isLongPress ? LONG_PRESS_MILLIS : delayMillis);
}

I set LONG_PRESS_MILLIS to 100 and it's working!

Hope it helps!!! ;)

Credit: MArtinCR


问:
Python in terminal: how to signify end of for loop?
Say I want to print 0 through 9.

I type in for i in range(10): print(i), press enter, and terminal shows ..., waiting for further statements.

So I have to press enter again to have the numbers printed.

```<code>>>> for i in range(10): print(i)
...
</code>```

How can I have the number printed without having to press enter twice?

答:
"alt+enter"
I was working in ipython and facing the same problem as yours. upon trying various combinations from keyboard, this one finally worked</p>

Body:
Say I want to print 0 through 9.

I type in for i in range(10): print(i), press enter, and terminal shows ..., waiting for further statements.

So I have to press enter again to have the numbers printed.

>>> for i in range(10): print(i)
...

How can I have the number printed without having to press enter twice?


问:
How to make a simple JavaScript call from a PHP function?
I have a simple PHP function that is being called when a form is submitted:

```<code>function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}
</code>```

What I need is to be able to do a simple Google Analytics call like this:

```<code>_gaq.push(['_trackPageview', 'virtual/formSubmit']);
</code>```

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?

答:
You just have to call your javascript code from the onSubmit argument of the form.</p>

```<code><form name="..." action="..." onSubmit="_gaq.push(['_trackPageview', 'virtual/formSubmit']);">
</code>```

Body:
I have a simple PHP function that is being called when a form is submitted:

function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}

What I need is to be able to do a simple Google Analytics call like this:

_gaq.push(['_trackPageview', 'virtual/formSubmit']);

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?

Body:
You just have to call your javascript code from the onSubmit argument of the form.

<form name="..." action="..." onSubmit="_gaq.push(['_trackPageview', 'virtual/formSubmit']);">


问:
How do I use bitwise shifts with cout?
I'm trying to do something similar to this:

```<code>#include <iostream>

int main()
{
    std::cout << 1 << 5 << std::endl;
}
</code>```

I expect 32 (1 shifted left by 5), but I get 15.

I am trying to use a macro like this:

```<code>#define BIT_SHIFT(x,y) x << y
...
cout << BIT_SHIFT(1, 5) << std::endl;
</code>```

and this happens.

Why? How do I fix this?

答:
Just use parentheses:

#include <iostream>

int main()
{
    std::cout << (1 << 5) << std::endl;
}
```

std::cout << 1 << 5 means "push to output stream first integer literal 1, followed by integer 5". However, adding parantheses changes the order of evaluation, and 1 << 5 is evaluated first, resulting in std::cout << 32 << std::endl; expression.

Title: How do I use bitwise shifts with cout?

Body:
I'm trying to do something similar to this:

#include <iostream>

int main()
{
    std::cout << 1 << 5 << std::endl;
}

I expect 32 (1 shifted left by 5), but I get 15.

I am trying to use a macro like this:

#define BIT_SHIFT(x,y) x << y
...
cout << BIT_SHIFT(1, 5) << std::endl;

and this happens.

Why? How do I fix this?

Body:
Just use parentheses:

#include <iostream>

int main()
{
    std::cout << (1 << 5) << std::endl;
}

std::cout << 1 << 5 means "push to output stream first integer literal 1, followed by integer 5". However, adding parantheses changes the order of evaluation, and 1 << 5 is evaluated first, resulting in std::cout << 32 << std::endl; expression.


答:
Use parenthesis:

```<code>    std::cout << (1 << 5) << std::endl;
</code>```

The reason is that the output ostream& operator<<(ostream&, const T&) overload chains the return values to call the function once more.

If you use parenthesis, the bitshift value is calculated first, and then passed to the overloaded output operator.

I am trying to use this in a macro: ...

Thus the above said your macro definition should look like:

```<code>#define BIT_SHIFT(x,y) ((x) << (y))
</code>```

You may wonder why the extra parenthesis now. This is just safer writing macros. Think about someone tries to use your macro like:

```<code> cout << BIT_SHIFT(1, 5*2) << std::endl;
</code>```

Title: How do I use bitwise shifts with cout?

Body:
Use parenthesis:

    std::cout << (1 << 5) << std::endl;

The reason is that the output ostream& operator<<(ostream&, const T&) overload chains the return values to call the function once more.

If you use parenthesis, the bitshift value is calculated first, and then passed to the overloaded output operator.

I am trying to use this in a macro: ...

Thus the above said your macro definition should look like:

#define BIT_SHIFT(x,y) ((x) << (y))

You may wonder why the extra parenthesis now. This is just safer writing macros. Think about someone tries to use your macro like:

 cout << BIT_SHIFT(1, 5*2) << std::endl;


问:
Displaying a large image next to 3 smaller images
I'm setting up a layout in PyQT5, and I want one large image on the left side to be displayed next to 3 images that are 1/3 the height of the big image (so that the combined heights of the smaller images adds up to the height of the large image)

Here's the code in the class Layout, which starts and displays the gui. All images are loaded in the createGridLayout method:

class Layout(QDialog):

    def __init__(self):
        super().__init__()
        self.title = 'Imaging'
        self.left = 10
        self.top = 10
        self.width = 800
        self.height = 500
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.createGridLayout()

        windowLayout = QVBoxLayout()
        windowLayout.setSpacing(0)
        windowLayout.addWidget(self.horizontalGroupBox)
        self.setLayout(windowLayout)

        self.show()

    def createGridLayout(self):
        self.horizontalGroupBox = QGroupBox()
        layout = QGridLayout()

        # label is the large image in the grid
        label = QLabel(self)
        pixmap = QPixmap('snap_1,1.tif') # USE RELATIVE PATH TO IMAGE!
        pixmap = pixmap.scaledToHeight(450)
        label.setPixmap(pixmap)

        # simplified version of the above for small images
        label1 = QLabel(self)
        label1.setPixmap(QPixmap('snap_1,1.tif').scaledToHeight(150))

        label2 = QLabel(self)
        label2.setPixmap(QPixmap('snap_1,2.tif').scaledToHeight(150))

        label3 = QLabel(self)
        label3.setPixmap(QPixmap('snap_1,3.tif').scaledToHeight(150))

        # adding images to grid
        layout.addWidget(label,1,0)
        layout.addWidget(label1,0,1)
        layout.addWidget(label2,1,1)
        layout.addWidget(label3,2,1)

        self.horizontalGroupBox.setLayout(layout)
```

All the imaging stuff is hardcoded for testing, which is to be accounted to later, yet not part of this issue.

So what I want is something like in the following image (Black boxes representing an image):

But what I'm currently getting is something like this:

答:
If you want to obtain the following structure:

```<code>┌---------┬---------┐
|         |         |
|         ├---------┤
|         |         |
|         ├---------┤
|         |         |
└---------┴---------┘
</code>```

Then you must analyze the structure, the item on the left starts at (0, 0) and has 3 rows and 1 column so the addWidget() method must pass (0, 0, 3, 1)

```<code># ...
# adding images to grid
layout.addWidget(label, 0, 0, 3, 1)
layout.addWidget(label1, 0, 1)
layout.addWidget(label2, 1, 1)
layout.addWidget(label3, 2, 1)
# ...
</code>```

Body:
I'm setting up a layout in PyQT5, and I want one large image on the left side to be displayed next to 3 images that are 1/3 the height of the big image (so that the combined heights of the smaller images adds up to the height of the large image)

Here's the code in the class Layout, which starts and displays the gui. All images are loaded in the createGridLayout method:

class Layout(QDialog):

    def __init__(self):
        super().__init__()
        self.title = 'Imaging'
        self.left = 10
        self.top = 10
        self.width = 800
        self.height = 500
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.createGridLayout()

        windowLayout = QVBoxLayout()
        windowLayout.setSpacing(0)
        windowLayout.addWidget(self.horizontalGroupBox)
        self.setLayout(windowLayout)

        self.show()

    def createGridLayout(self):
        self.horizontalGroupBox = QGroupBox()
        layout = QGridLayout()

        # label is the large image in the grid
        label = QLabel(self)
        pixmap = QPixmap('snap_1,1.tif') # USE RELATIVE PATH TO IMAGE!
        pixmap = pixmap.scaledToHeight(450)
        label.setPixmap(pixmap)

        # simplified version of the above for small images
        label1 = QLabel(self)
        label1.setPixmap(QPixmap('snap_1,1.tif').scaledToHeight(150))

        label2 = QLabel(self)
        label2.setPixmap(QPixmap('snap_1,2.tif').scaledToHeight(150))

        label3 = QLabel(self)
        label3.setPixmap(QPixmap('snap_1,3.tif').scaledToHeight(150))

        # adding images to grid
        layout.addWidget(label,1,0)
        layout.addWidget(label1,0,1)
        layout.addWidget(label2,1,1)
        layout.addWidget(label3,2,1)

        self.horizontalGroupBox.setLayout(layout)

All the imaging stuff is hardcoded for testing, which is to be accounted to later, yet not part of this issue.

So what I want is something like in the following image (Black boxes representing an image):

But what I'm currently getting is something like this:

Body:
If you want to obtain the following structure:

┌---------┬---------┐
|         |         |
|         ├---------┤
|         |         |
|         ├---------┤
|         |         |
└---------┴---------┘

Then you must analyze the structure, the item on the left starts at (0, 0) and has 3 rows and 1 column so the addWidget() method must pass (0, 0, 3, 1)

# ...
# adding images to grid
layout.addWidget(label, 0, 0, 3, 1)
layout.addWidget(label1, 0, 1)
layout.addWidget(label2, 1, 1)
layout.addWidget(label3, 2, 1)
# ...


问:
How to change CPU ID
How do I change my cpu id I know how to get it yet I have no clue how to change it I really need help. Im using this code:</p>

```<code>private string getCPUID()
{
    string cpuInfo = "";
    ManagementClass managClass = new ManagementClass("win32_processor");
    ManagementObjectCollection managCollec = managClass.GetInstances();

    foreach (ManagementObject managObj in managCollec)
    {
        if (cpuInfo == "")
        {
            //Get only the first CPU's ID
            cpuInfo = managObj.Properties["processorID"].Value.ToString();
            break;
        }
    }

    return cpuInfo;
}
</code>```

答:
I can't tell you how to change CPU Id's because I don't think that's possible but I can tell you how to write concise code,</p>

```<code>private string getFirstCPUID() =>
    new ManagementClass("win32_processor")
      .GetInstances()
      .FirstOrDefault()?
      .Properties["processorID"]?
      .Value?.ToString();

</code>```

Title: How to change CPU ID

Body:
How do I change my cpu id I know how to get it yet I have no clue how to change it I really need help. Im using this code:

private string getCPUID()
{
    string cpuInfo = "";
    ManagementClass managClass = new ManagementClass("win32_processor");
    ManagementObjectCollection managCollec = managClass.GetInstances();

    foreach (ManagementObject managObj in managCollec)
    {
        if (cpuInfo == "")
        {
            //Get only the first CPU's ID
            cpuInfo = managObj.Properties["processorID"].Value.ToString();
            break;
        }
    }

    return cpuInfo;
}

Body:
I can't tell you how to change CPU Id's because I don't think that's possible but I can tell you how to write concise code,

private string getFirstCPUID() =>
    new ManagementClass("win32_processor")
      .GetInstances()
      .FirstOrDefault()?
      .Properties["processorID"]?
      .Value?.ToString();


答:
You can't. JavaScript is client side, and PHP is server side.

You can make the browser call a JavaScript function:

```<code><?='<script type="text/javascript">jsfunc();<;/script>';?>;
</code>```

Title: How to make a simple JavaScript call from a PHP function?

Body:
You can't. JavaScript is client side, and PHP is server side.

You can make the browser call a JavaScript function:

<?='<script type="text/javascript">jsfunc();<;/script>';?>;


问:
Getting 'Invalid envelope status' resending documents through Docusign API
I am re-sending documents via the API.  This has worked for a long time, and suddenly started getting these errors?  I can't figure out what is going on?  Does anyone have any ideas?

The actual envelope status is 'Waiting on Others', which of course is not in the list below, but we need to resend the envelope, because the user never got the email.  So how do I deal with this?

```<code>{ "errorCode": "ENVELOPE_INVALID_STATUS",
  "message": "Invalid envelope status. Envelope status is not one of: Created, Sent, Delivered, Correct." }

EnvelopesApi envelopesApi = new
    EnvelopesApi(GetBasePath(myAccount.BaseUrl));
envelopesApi.Configuration.AddDefaultHeader(
    "X-DocuSign-Authentication", JsonConvert.SerializeObject(myHeader));
EnvelopesApi.UpdateRecipientsOptions options = new
    EnvelopesApi.UpdateRecipientsOptions();
options.resendEnvelope = "true";
envelopesApi.UpdateRecipients(myAccount.AccountId,
    EnvelopeId, docuSignRecipients, options);
</code>```

答:
You're not showing what the docusignRecipients value is.

I suggest you first obtain the recipients object via EnvelopeRecipients::list and then use it in the call.

Also, at the API level, there is no envelope status of Waiting on Others. I suggest you also obtain the envelope status so you can see what is going on.

I'm sorry to hear that your code was working and then stopped. That would indicate a regression test problem. Does your code still work on demo?

Body:
I am re-sending documents via the API.  This has worked for a long time, and suddenly started getting these errors?  I can't figure out what is going on?  Does anyone have any ideas?

The actual envelope status is 'Waiting on Others', which of course is not in the list below, but we need to resend the envelope, because the user never got the email.  So how do I deal with this?

{ "errorCode": "ENVELOPE_INVALID_STATUS",
  "message": "Invalid envelope status. Envelope status is not one of: Created, Sent, Delivered, Correct." }

EnvelopesApi envelopesApi = new
    EnvelopesApi(GetBasePath(myAccount.BaseUrl));
envelopesApi.Configuration.AddDefaultHeader(
    "X-DocuSign-Authentication", JsonConvert.SerializeObject(myHeader));
EnvelopesApi.UpdateRecipientsOptions options = new
    EnvelopesApi.UpdateRecipientsOptions();
options.resendEnvelope = "true";
envelopesApi.UpdateRecipients(myAccount.AccountId,
    EnvelopeId, docuSignRecipients, options);


问:
Compiling HTML, CSS, and JS, into a single JS file
Is there any decent procedure to compile html, css, and js files into one js file? I've been looking on methods how to load css and html files to js, and they all require requireJS. Is there any webpack plugin, or just a module for this?

I know this is not a decent question, but I've been thinking on not always fetching an external source file (html, css).

Example:

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Blah blah blah</title>
    <script src="something.js"></script>
    <script>
        // 'load' will load everthing to #something
        something.load(
            // options
        )
    </script>
</head>

<body>
    <div id="something"></div>
</body>

</html>
</code>```

答: Finally, thanks to this article, all I need is html-loader. Then I can just add import html from 'some.html'.

Body:
Is there any decent procedure to compile html, css, and js files into one js file? I've been looking on methods how to load css and html files to js, and they all require requireJS. Is there any webpack plugin, or just a module for this?

I know this is not a decent question, but I've been thinking on not always fetching an external source file (html, css).

Example:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Blah blah blah</title>


问:
How can I transfer data between a Jupyter Notebook and a windows forms application?
I have a neural network in a jupyter notebook which I am usting as a black box for my program. The network takes an image in, makes some changes and returns an image back. I am trying to find a way to send the image and an int value from the winform into the jupyternotebook (probably as a path to it) and then return the result back to the windows forms with the ability to save it on the computer.
If it would help, the neural network is based on Keras.

I tried some guides that i have found on the internet, i will link them below, and asked a couple of teachers for help but I didn't have any results.

Here are the things I have found:

https://ndres.me/post/jupyter-notebook-rest-api/

How do you put an image file in a json object?

Call and consume Web API in winform using C#.net

https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb412179(v=vs.100)

答:
You can choose an alternative way:

Using your jupyter notebook, save the Keras model, and then build a python server that listens for calls from your WinForms program.

You can start off with a few more relevant tutorials:

Training and serving ML models with tf keras

Deploying Keras models using TensorFlow Serving and Flask

Basically, what you want to do is:

Save your model's weights and graph.

Serve as server that listens for incoming requests via some protocol(HTTPRequests or RPC for instance)

Make you WinForms program call it and get the answer.

Depending on your application, you can:

Return the image as lists of lists (for instance as in RBG, you can specify the exact value of each pixel and channel)

Return a binary stream of the image (encode it and decode it)

Encode to Base64 string.

You can also explore for more options.
Eventually, now you have a service that runs in background and awaits from WinForms to call it with an image.
You can also serve it over the internet if you choose web-based protocol (Flask for instance).


问:
VB.NET reading XML file troubles
I am using the following code to parse a XML file of mine:

```<code>Dim xml As String = "<?xml version=""1.0"" encoding=""Windows-1252""?>" & _
                        "<theref:theref-msg xmlns:csr=""http://www.xxxxx.com/Schema/csr"" xmlns:theref=""http://www.xxxxx.com/Schema/theref"">" & _
                          "<theref:header>" & _
                            "<theref:eid />" & _
                            "<theref:reference_id>429</theref:reference_id>" & _
                            "<theref:sr_type_code>US1</theref:sr_type_code>" & _
                            "<theref:event_type_code>REQUEST</theref:event_type_code>" & _
                            "<theref:eai_event_code>DSR</theref:eai_event_code>" & _
                            "<theref:source_code>WORKS</theref:source_code>" & _
                            "<theref:target_code>APP</theref:target_code>" & _
                            "<theref:status_code />" & _
                            "<theref:details />" & _
                          "</theref:header>" & _
                        "</theref:theref-msg>"

    Dim document As XDocument = XDocument.Parse(xml)

    Dim pupils = From pupil In document.Descendants("theref:theref-msg") _
                 Select New With _
                 { _
                    .Name = pupil.Element("theref:reference_id").Value, _
                    .TagID = pupil.Element("theref:sr_type_code").Value _
                 }

    For Each pupil In pupils
        Debug.Print("{0}: {1}", pupil.Name, pupil.TagID)
    Next
</code>```

The problem being is that it doesn't seem to work at all. It crashes on the line:

```<code>Dim pupils = From pupil In document.Descendants("csreai:csreai-msg") _
                 Select New With _
                 { _
                    .Name = pupil.Element("csreai:reference_id").Value, _
                    .TagID = pupil.Element("csreai:sr_type_code").Value _
                 }
</code>```

ERROR is: A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
The ':' character, hexadecimal value 0x3A, cannot be included in a name. 5

UPDATED CODE:

```<code>Dim xml As String = "<?xml version=""1.0"" encoding=""Windows-1252""?>" & _
                    "<theref:theref-msg xmlns:csr=""http://www.xxxxx.com/Schema/csr"" xmlns:theref=""http://www.xxxxx.com/Schema/theref"">" & _
                      "<theref:header>" & _
                        "<theref:eid />" & _
                        "<theref:reference_id>429</theref:reference_id>" & _
                        "<theref:sr_type_code>US1</theref:sr_type_code>" & _
                        "<theref:event_type_code>REQUEST</theref:event_type_code>" & _
                        "<theref:eai_event_code>DSR</theref:eai_event_code>" & _
                        "<theref:source_code>WORKS</theref:source_code>" & _
                        "<theref:target_code>APP</theref:target_code>" & _
                        "<theref:status_code />" & _
                        "<theref:details />" & _
                      "</theref:header>" & _
                      "<theref:body>" & _
                        "<csr:document>" & _
                          "<csr:header>" & _
                            "<csr:system>CSR</csr:system>" & _
                            "<csr:doc_name>FULLSR</csr:doc_name>" & _
                            "<csr:version>3.1</csr:version>" & _
                            "<csr:dml_event>UPDATE</csr:dml_event>" & _
                          "</csr:header>" & _
                    "</csr:document></theref:body></theref:theref-msg>"

Dim xmlb = From getXMLData In document.<theref:theref-msg>.<theref:header>.<theref:body>.<csr:document>.<csr:header>
</code>```

Newest UPDATE

What if i have this:

```<code>   <csr:custom_attributes>
      <csr:custom_attribute>
        <csr:type_code>
          <csr:value>data1</csr:value>
        </csr:type_code>
        <csr:group_code>
          <csr:value>wide1</csr:value>
        </csr:group_code>
      </csr:custom_attribute>
      <csr:custom_attribute>
        <csr:type_code>
          <csr:value>data2</csr:value>
        </csr:type_code>
        <csr:group_code>
          <csr:value>wide2</csr:value>
        </csr:group_code>
      </csr:custom_attribute>
   </csr:custom_attributes>
</code>```

I can only seem to get the first set of data (data1, wide1) but not the second?

```<code>   xmlDATA = (From getXMLData In document.<theref:csreai-msg>.<theref:body>.<csr:document>.<csr:service_request>.<csr:custom_attributes>.<csr:custom_attribute>).ToList()
</code>```

答:
1.Try with this,

```<code>       document.Descendants("{http://www.xxxxx.com/Schema/theref}theref-msg").FirstOrDefault
</code>```

2.Another solution with traditional looping approach,

```<code>     Imports <xmlns:ns='http://www.xxxxx.com/Schema/theref'>
</code>```

import namespace on top of the class. than use follwoing code to get the values,

```<code>         For Each header As XElement In document.<ns:theref-msg>.<ns:header>.<ns:reference_id>
             dim something = header.Value
         Next
</code>```

Title: VB.NET reading XML file troubles

Body:
I am using the following code to parse a XML file of mine:

Dim xml As String = "<?xml version=""1.0"" encoding=""Windows-1252""?>" & _
                        "<theref:theref-msg xmlns:csr=""http://www.xxxxx.com/Schema/csr"" xmlns:theref=""http://www.xxxxx.com/Schema/theref"">" & _
                          "<theref:header>" & _
                            "<theref:eid />" & _
                            "<theref:reference_id>429</theref:reference_id>" & _
                            "<theref:sr_type_code>US1</theref:sr_type_code>" & _
                            "<theref:event_type_code>REQUEST</theref:event_type_code>" & _
                            "<theref:eai_event_code>DSR</theref:eai_event_code>" & _
                            "<theref:source_code>WORKS</theref:source_code>" & _
                            "<theref:target_code>APP</theref:target_code>" & _
                            "<theref:status_code />" & _
                            "<theref:details />" & _
                          "</theref:header>" & _
                        "</theref:theref-msg>"

    Dim document As XDocument = XDocument.Parse(xml)

    Dim pupils = From pupil In document.Descendants("theref:theref-msg") _
                 Select New With _
                 { _
                    .Name = pupil.Element("theref:reference_id").Value, _
                    .TagID = pupil.Element("theref:sr_type_code").Value _
                 }

    For Each pupil In pupils
        Debug.Print("{0}: {1}", pupil.Name, pupil.TagID)
    Next

The problem being is that it doesn't seem to work at all. It crashes on the line:

Dim pupils = From pupil In document.Descendants("csreai:csreai-msg") _
                 Select New With _
                 { _
                    .Name = pupil.Element("csreai:reference_id").Value, _
                    .TagID = pupil.Element("csreai:sr_type_code").Value _
                 }

ERROR is: A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
The ':' character, hexadecimal value 0x3A, cannot be included in a name. 5

UPDATED CODE:

Dim xml As String = "<?xml version=""1.0"" encoding=""Windows-1252""?>" & _
                    "<theref:theref-msg xmlns:csr=""http://www.xxxxx.com/Schema/csr"" xmlns:theref=""http://www.xxxxx.com/Schema/theref"">" & _
                      "<theref:header>" & _
                        "<theref:eid />" & _
                        "<theref:reference_id>429</theref:reference_id>" & _
                        "<theref:sr_type_code>US1</theref:sr_type_code>" & _
                        "<theref:event_type_code>REQUEST</theref:event_type_code>" & _
                        "<theref:eai_event_code>DSR</theref:eai_event_code>" & _
                        "<theref:source_code>WORKS</theref:source_code>" & _
                        "<theref:target_code>APP</theref:target_code>" & _
                        "<theref:status_code />" & _
                        "<theref:details />" & _
                      "</theref:header>" & _
                      "<theref:body>" & _
                        "<csr:document>" & _
                          "<csr:header>" & _
                            "<csr:system>CSR</csr:system>" & _
                            "<csr:doc_name>FULLSR</csr:doc_name>" & _
                            "<csr:version>3.1</csr:version>" & _
                            "<csr:dml_event>UPDATE</csr:dml_event>" & _
                          "</csr:header>" & _
                    "</csr:document></theref:body></theref:theref-msg>"

Dim xmlb = From getXMLData In document.<theref:theref-msg>.<theref:header>.<theref:body>.<csr:document>.<csr:header>

Newest UPDATE

What if i have this:

   <csr:custom_attributes>
      <csr:custom_attribute>
        <csr:type_code>
          <csr:value>data1</csr:value>
        </csr:type_code>
        <csr:group_code>
          <csr:value>wide1</csr:value>
        </csr:group_code>
      </csr:custom_attribute>
      <csr:custom_attribute>
        <csr:type_code>
          <csr:value>data2</csr:value>
        </csr:type_code>
        <csr:group_code>
          <csr:value>wide2</csr:value>
        </csr:group_code>
      </csr:custom_attribute>
   </csr:custom_attributes>

I can only seem to get the first set of data (data1, wide1) but not the second?

   xmlDATA = (From getXMLData In document.<theref:csreai-msg>.<theref:body>.<csr:document>.<csr:service_request>.<csr:custom_attributes>.<csr:custom_attribute>).ToList()

Body:
1.Try with this,

       document.Descendants("{http://www.xxxxx.com/Schema/theref}theref-msg").FirstOrDefault

2.Another solution with traditional looping approach,

     Imports <xmlns:ns='http://www.xxxxx.com/Schema/theref'>

import namespace on top of the class. than use follwoing code to get the values,

         For Each header As XElement In document.<ns:theref-msg>.<ns:header>.<ns:reference_id>
             dim something = header.Value
         Next


问:
Why is this a non-constant condition for g++8?
I have this code. This is an array (which is a bit like std :: array) that I could work with at compile time. Also for-loop at compile time.

#include <utility>
#include <memory>
#include <type_traits>

template<class F,
         std::size_t ... Is>
constexpr void __loop(F&& func, std::index_sequence<Is ...>) noexcept
{
    (func(std::integral_constant<std::size_t, Is>{}), ...);
}

template<std::size_t N,
         typename F>
constexpr void CONSTEXPR_LOOP(F&& func) noexcept
{
    __loop(std::forward<F>(func), std::make_index_sequence<N>());
}

template<typename T, std::size_t Size>
class StaticArray
{
    static_assert(std::disjunction_v<
                        std::is_default_constructible<T>,
                        std::is_nothrow_default_constructible<T>
                    >,
                  "Type must have a trivial constructor.");
public:
    constexpr StaticArray() noexcept;
    template<typename ... Args,
             std::enable_if_t<
                 std::conjunction_v<
                     std::is_same<T, Args>...
                     >
                 > * = nullptr
             >
    constexpr StaticArray(Args && ... list) noexcept;
    constexpr StaticArray(const StaticArray& a) = delete;
    constexpr StaticArray(StaticArray&& a) = delete;
    ~StaticArray() noexcept = default;

    constexpr StaticArray& operator=(const StaticArray& a) = delete;
    constexpr StaticArray& operator=(StaticArray&& a) = delete;

    constexpr const T& operator[](std::size_t i) const noexcept;
private:
    T _data[Size];
    std::size_t _capacity;
    std::size_t _count;

    template<typename Arg>
    constexpr void set_data(std::size_t i, Arg&& arg) noexcept;
    template<typename ... Args, std::size_t ... Indices>
    constexpr void unpack(std::index_sequence<Indices ...>, Args&& ... args) noexcept;
    template<typename ... Args>
    constexpr void create_indexes(Args&& ... args) noexcept;
};

template<typename T, std::size_t Size>
constexpr StaticArray<T, Size>::StaticArray() noexcept :
    _data{T{}},
    _capacity{Size},
    _count{0}
{
}

template<typename T, std::size_t Size>
template<typename ... Args,
         std::enable_if_t<
             std::conjunction_v<
                 std::is_same<T, Args>...
                 >
             > *
         >
constexpr StaticArray<T, Size>::StaticArray(Args&& ... list) noexcept :
    _data{T{}},
    _capacity{Size},
    _count{Size}
{
    static_assert(Size == sizeof ... (list), "Size of array not equal number of elements in the list");
    static_assert(std::conjunction_v<std::is_same<T, Args>... >, "Parameter must be the same type as StaticArray<T>.");
    create_indexes(std::forward<Args>(list) ...);
}

template<typename T, std::size_t Size>
template<typename Arg>
constexpr void StaticArray<T, Size>::set_data(std::size_t i, Arg&& arg) noexcept
{
    _data[i] = arg;
}

template<typename T, std::size_t Size>
template<typename ... Args, std::size_t ... Indices>
constexpr void StaticArray<T, Size>::unpack(std::index_sequence<Indices ...>, Args&& ... args) noexcept
{
    (set_data(Indices, args), ...);
}

template<typename T, std::size_t Size>
template<typename ... Args>
constexpr void StaticArray<T, Size>::create_indexes(Args&& ... args) noexcept
{
    unpack(std::make_index_sequence<Size>{}, std::forward<Args>(args)...);
}

template<typename T, std::size_t Size>
constexpr const T& StaticArray<T, Size>::operator[](std::size_t i) const noexcept
{
    return _data[i];
}

int main()
{
    constexpr StaticArray<unsigned, 10> array = {9u, 8u, 7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};

    static_assert(array[0] == 9);
    static_assert(array[1] == 8);
    static_assert(array[2] == 7);
    static_assert(array[3] == 6);
    static_assert(array[4] == 5);
    static_assert(array[5] == 4);
    static_assert(array[6] == 3);
    static_assert(array[7] == 2);
    static_assert(array[8] == 1);
    static_assert(array[9] == 0);

    constexpr std::array<unsigned, 10> checker = {9u, 8u, 7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};

    CONSTEXPR_LOOP<10>([&](auto i) constexpr {
        static_assert(array[i] == checker[i]);
    });

    return 0;
}
```
<p>And when I compile this using <code>g++-8.3</code>, I get this error:</p>
```.../main.cpp: In instantiation of ‘main()::<lambda(auto:1)> [with auto:1 = std::integral_constant<long unsigned int, 0>]’:
.../main.cpp:9:10:   required from ‘constexpr void __loop(F&&, std::index_sequence<Is ...>) [with F = main()::<lambda(auto:1)>; long unsigned int ...Is = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::index_sequence<Is ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9>]’
.../main.cpp:16:11:   required from ‘constexpr void CONSTEXPR_LOOP(F&&) [with long unsigned int N = 10; F = main()::<lambda(auto:1)>]’
.../main.cpp:149:6:   required from here
.../main.cpp:148:32: error: non-constant condition for static assertion
         static_assert(array[i] == checker[i]);
                       ~~~~~~~~~^~~~~~~~~~~
.../main.cpp:148:32: error: ‘__closure’ is not a constant expression

```
<p>After I spent some time to understand what the problem was, I decided to compile this code using <code>g++-7.4</code>. It compiles successfully without any errors. Clang-6 and <code>g++-9</code> give me the same result, but as soon as I use g++-8, I get the errors described above. Any idea why this is happening?</p>
<p>Thanks!</p>
<p><strong>[Note]</strong> Online example: https://godbolt.org/z/Ig4CCW</p>
<p><strong>[UPDATE]</strong> I compiled this code in <code>g++-8</code> when I added a static specifier to the constexpr variable. It works because:</p>
<p>enter link description here</p>
<blockquote>
<p>A lambda expression can use a variable without capturing it if the variable</p>
<ul>
<li>is a non-local variable or has static or thread local storage duration >(in which case the variable cannot be captured)</li>
</ul>
</blockquote>
<p>But if you look at the code below, you will notice that the lambda, which is called from another function, for some reason does not capture the constexpr variable by reference and value in <code>g++-8</code>. Other compilers do not report any errors.</p>
<pre class="lang-cpp prettyprint-override"><code>template<typename F>
constexpr void call(F&& f)
{
    f();
}

int main()
{
    constexpr std::array<unsigned, 1> checker = {1u};
    call([&]() constexpr { static_assert(checker[0] == checker[0]); });
    static constexpr std::array<unsigned, 1> checker2 = {1u};
    call([]() constexpr { static_assert(checker2[0] == checker2[0]); });
    constexpr std::array<unsigned, 1> checker3 = {1u};
    call([=]() constexpr { static_assert(checker3[0] == checker3[0]); });

    return 0;
}
</code>```

Try it

答:
AFAIK parameter, even in a constexpr function aren't constexpr

```<code>constexpr void f(std::size_t n) {
  static_assert(n == 42, "");  // not allowed.
}
</code>```

Source : https://mpark.github.io/programming/2017/05/26/constexpr-function-parameters/

UPDATE : from comments

I got fooled by the auto. Indeed, since the call is here :

```<code>func(std::integral_constant<std::size_t, Is>{}), ...);
</code>```

auto is an std::integral_constant and it should work

Body:
I have this code. This is an array (which is a bit like std :: array) that I could work with at compile time. Also for-loop at compile time.

#include <utility>
#include <memory>
#include <type_traits>

template<class F,
         std::size_t ... Is>
constexpr void __loop(F&& func, std::index_sequence<Is ...>) noexcept
{
    (func(std::integral_constant<std::size_t, Is>{}), ...);
}

template<std::size_t N,
         typename F>
constexpr void CONSTEXPR_LOOP(F&& func) noexcept
{
    __loop(std::forward<F>(func), std::make_index_sequence<N>());
}

template<typename T, std::size_t Size>
class StaticArray
{
    static_assert(std::disjunction_v<
                        std::is_default_constructible<T>,
                        std::is_nothrow_default_constructible<T>
                    >,
                  "Type must have a trivial constructor.");
public:
    constexpr StaticArray() noexcept;
    template<typename ... Args,
             std::enable_if_t<
                 std::conjunction_v<
                     std::is_same<T, Args>...
                     >
                 > * = nullptr
             >
    constexpr StaticArray(Args && ... list) noexcept;
    constexpr StaticArray(const StaticArray& a) = delete;
    constexpr StaticArray(StaticArray&& a) = delete;
    ~StaticArray() noexcept = default;

    constexpr StaticArray& operator=(const StaticArray& a) = delete;
    constexpr StaticArray& operator=(StaticArray&& a) = delete;

    constexpr const T& operator[](std::size_t i) const noexcept;
private:
    T _data[Size];
    std::size_t _capacity;
    std::size_t _count;

    template<typename Arg>
    constexpr void set_data(std::size_t i, Arg&& arg) noexcept;
    template<typename ... Args, std::size_t ... Indices>
    constexpr void unpack(std::index_sequence<Indices ...>, Args&& ... args) noexcept;
    template<typename ... Args>
    constexpr void create_indexes(Args&& ... args) noexcept;
};

template<typename T, std::size_t Size>
constexpr StaticArray<T, Size>::StaticArray() noexcept :
    _data{T{}},
    _capacity{Size},
    _count{0}
{
}

template<typename T, std::size_t Size>
template<typename ... Args,
         std::enable_if_t<
             std::conjunction_v<
                 std::is_same<T, Args>...
                 >
             > *
         >
constexpr StaticArray<T, Size>::StaticArray(Args&& ... list) noexcept :
    _data{T{}},
    _capacity{Size},
    _count{Size}
{
    static_assert(Size == sizeof ... (list), "Size of array not equal number of elements in the list");
    static_assert(std::conjunction_v<std::is_same<T, Args>... >, "Parameter must be the same type as StaticArray<T>.");
    create_indexes(std::forward<Args>(list) ...);
}

template<typename T, std::size_t Size>
template<typename Arg>
constexpr void StaticArray<T, Size>::set_data(std::size_t i, Arg&& arg) noexcept
{
    _data[i] = arg;
}

template<typename T, std::size_t Size>
template<typename ... Args, std::size_t ... Indices>
constexpr void StaticArray<T, Size>::unpack(std::index_sequence<Indices ...>, Args&& ... args) noexcept
{
    (set_data(Indices, args), ...);
}

template<typename T, std::size_t Size>
template<typename ... Args>
constexpr void StaticArray<T, Size>::create_indexes(Args&& ... args) noexcept
{
    unpack(std::make_index_sequence<Size>{}, std::forward<Args>(args)...);
}

template<typename T, std::size_t Size>
constexpr const T& StaticArray<T, Size>::operator[](std::size_t i) const noexcept
{
    return _data[i];
}

int main()
{
    constexpr StaticArray<unsigned, 10> array = {9u, 8u, 7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};

    static_assert(array[0] == 9);
    static_assert(array[1] == 8);
    static_assert(array[2] == 7);
    static_assert(array[3] == 6);
    static_assert(array[4] == 5);
    static_assert(array[5] == 4);
    static_assert(array[6] == 3);
    static_assert(array[7] == 2);
    static_assert(array[8] == 1);
    static_assert(array[9] == 0);

    constexpr std::array<unsigned, 10> checker = {9u, 8u, 7u, 6u, 5u, 4u, 3u, 2u, 1u, 0u};

    CONSTEXPR_LOOP<10>([&](auto i) constexpr {
        static_assert(array[i] == checker[i]);
    });

    return 0;
}

And when I compile this using g++-8.3, I get this error:

.../main.cpp: In instantiation of ‘main()::<lambda(auto:1)> [with auto:1 = std::integral_constant<long unsigned int, 0>]’:
.../main.cpp:9:10:   required from ‘constexpr void __loop(F&&, std::index_sequence<Is ...>) [with F = main()::<lambda(auto:1)>; long unsigned int ...Is = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::index_sequence<Is ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9>]’
.../main.cpp:16:11:   required from ‘constexpr void CONSTEXPR_LOOP(F&&) [with long unsigned int N = 10; F = main()::<lambda(auto:1)>]’
.../main.cpp:149:6:   required from here
.../main.cpp:148:32: error: non-constant condition for static assertion
         static_assert(array[i] == checker[i]);
                       ~~~~~~~~~^~~~~~~~~~~
.../main.cpp:148:32: error: ‘__closure’ is not a constant expression

After I spent some time to understand what the problem was, I decided to compile this code using g++-7.4. It compiles successfully without any errors. Clang-6 and g++-9 give me the same result, but as soon as I use g++-8, I get the errors described above. Any idea why this is happening?

Thanks!

[Note] Online example: https://godbolt.org/z/Ig4CCW

[UPDATE] I compiled this code in g++-8 when I added a static specifier to the constexpr variable. It works because:

enter link description here

A lambda expression can use a variable without capturing it if the variable

is a non-local variable or has static or thread local storage duration >(in which case the variable cannot be captured)

But if you look at the code below, you will notice that the lambda, which is called from another function, for some reason does not capture the constexpr variable by reference and value in g++-8. Other compilers do not report any errors.

template<typename F>
constexpr void call(F&& f)
{
    f();
}

int main()
{
    constexpr std::array<unsigned, 1> checker = {1u};
    call([&]() constexpr { static_assert(checker[0] == checker[0]); });
    static constexpr std::array<unsigned, 1> checker2 = {1u};
    call([]() constexpr { static_assert(checker2[0] == checker2[0]); });
    constexpr std::array<unsigned, 1> checker3 = {1u};
    call([=]() constexpr { static_assert(checker3[0] == checker3[0]); });

    return 0;
}

Try it

Body:
AFAIK parameter, even in a constexpr function aren't constexpr

constexpr void f(std::size_t n) {
  static_assert(n == 42, "");  // not allowed.
}

Source : https://mpark.github.io/programming/2017/05/26/constexpr-function-parameters/

UPDATE : from comments

I got fooled by the auto. Indeed, since the call is here :

func(std::integral_constant<std::size_t, Is>{}), ...);

auto is an std::integral_constant and it should work


问:
How to make a string from separate int values
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

```<code>    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

</code>```

But when I printf I get nothing.

```<code>    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);
</code>```

This is what is working but seems very inefficient.

答:
If your integers are more than 1 digit long then maybe you should consider using something like sprintf()

char string[20];
int start = 13;
int finish = 21;

sprintf(string, "%d/%d", start, finish);
```

It works exactly like printf() but instead of printing to the console it prints to a string you supply to it.

Body:
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

But when I printf I get nothing.

    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);

This is what is working but seems very inefficient.

Body:
If your integers are more than 1 digit long then maybe you should consider using something like sprintf()

char string[20];
int start = 13;
int finish = 21;

sprintf(string, "%d/%d", start, finish);

It works exactly like printf() but instead of printing to the console it prints to a string you supply to it.


问:
How to process tables in parallel with Microsoft.AnalysisServices.Tabular
I need to create a program that parallelizes the process of a list of tables contained in a Tabular model.

Here the code i'm using:

Server[] svrList = new Server[tables.getTables.Count];
Parallel.For(0, tables.getTables.Count, i =>
            {
                svrList[i] = ServerConnect(connectionString);
                Model m = svrList[i].Databases[database].Model;
                log.Info("process table " + tables.getTables.ElementAt(i).Name);
                Table t = m.Tables[tables.getTables.ElementAt(i).Name];
                t.RequestRefresh(Microsoft.AnalysisServices.Tabular.RefreshType.Full);
                m.SaveChanges();
                log.Info("Finish " + tables.getTables.ElementAt(i).Name);
                svrList[i].Disconnect();
            }
            );
```

<p>if one table fail, the others must load correctly.</p>

<p>In this code the tables are process correctly but they are processed in sequence.</p>

<p>I'm using different connection to the server for each table because if i use the same connection i've this error:</p>

```the connection cannot be used while an xmlreader object is open
```

How can i resolve this problem?

Thanks

答:
Just change the Parallel.For to a regular for loop and move the SaveChanges outside the loop. SaveChanges executes all the commands you have queued up. It does this in parallel inside a transaction by default.

```<code>var conn = ServerConnect(connectionString);
Model m = conn.Databases[database].Model;
for (int i=0; i<tables.getTables.Count; i++)
{
     log.Info("process table " + tables.getTables.ElementAt(i).Name);
     Table t = m.Tables[tables.getTables.ElementAt(i).Name];
     t.RequestRefresh(Microsoft.AnalysisServices.Tabular.RefreshType.Full);
}
m.SaveChanges();
conn.Disconnect();
</code>```

Body:
I need to create a program that parallelizes the process of a list of tables contained in a Tabular model.

Here the code i'm using:

Server[] svrList = new Server[tables.getTables.Count];
Parallel.For(0, tables.getTables.Count, i =>
            {
                svrList[i] = ServerConnect(connectionString);
                Model m = svrList[i].Databases[database].Model;
                log.Info("process table " + tables.getTables.ElementAt(i).Name);
                Table t = m.Tables[tables.getTables.ElementAt(i).Name];
                t.RequestRefresh(Microsoft.AnalysisServices.Tabular.RefreshType.Full);
                m.SaveChanges();
                log.Info("Finish " + tables.getTables.ElementAt(i).Name);
                svrList[i].Disconnect();
            }
            );

if one table fail, the others must load correctly.

In this code the tables are process correctly but they are processed in sequence.

I'm using different connection to the server for each table because if i use the same connection i've this error:

the connection cannot be used while an xmlreader object is open

How can i resolve this problem?

Thanks

Body:
Just change the Parallel.For to a regular for loop and move the SaveChanges outside the loop. SaveChanges executes all the commands you have queued up. It does this in parallel inside a transaction by default.

var conn = ServerConnect(connectionString);
Model m = conn.Databases[database].Model;
for (int i=0; i<tables.getTables.Count; i++)
{
     log.Info("process table " + tables.getTables.ElementAt(i).Name);
     Table t = m.Tables[tables.getTables.ElementAt(i).Name];
     t.RequestRefresh(Microsoft.AnalysisServices.Tabular.RefreshType.Full);
}
m.SaveChanges();
conn.Disconnect();


问:
Using Maven for multiple deployment environment (production/development)
I have a web app in Maven, with the default directory structure. No problem there.
The default directory structure has some property files that point to my localhost database.

Currently I create an Ant script to create different war files -
one for production and one for development, using these commands:

```<code>ant deploy-dev
ant deploy-prod
ant deploy-sit
ant deploy-uat
</code>```

So basically they create a war file and then update the war file by plugging in the properties file

Is there something like that in maven (different war created depending on the configuration)?

if so, how do i do that?

i tried mvn warbut it just creates a war

答:
There is a plugin that helps simplifies some of this madness now.

https://environments-maven-plugin.sourceforge.io/index.html

Disclosure. I have authored the plugin.

Body:
I have a web app in Maven, with the default directory structure. No problem there.
The default directory structure has some property files that point to my localhost database.

Currently I create an Ant script to create different war files -
one for production and one for development, using these commands:

ant deploy-dev
ant deploy-prod
ant deploy-sit
ant deploy-uat

So basically they create a war file and then update the war file by plugging in the properties file

Is there something like that in maven (different war created depending on the configuration)?

if so, how do i do that?

i tried mvn warbut it just creates a war


答:
The short and easy answer is you can't execute JavaScript code server-side. The long and hard answer is you can, but it's long and hard and involves some server-side scripts/libraries and is kind of messy at best.

Basically, what you want to do is either output that code on the confirmation/thank you page the user lands on after (optimal) or else use cURL to make a hit (it is a little trickier... Basically you have to simulate the img request, appending the relevant information, including cookie information... Note, this is not the "long and hard" method mentioned above.).

Body:
I have a simple PHP function that is being called when a form is submitted:

function uc_paypal_ec_submit_form($form, &$form_state) {
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit order'),
  );
  return $form;
}

What I need is to be able to do a simple Google Analytics call like this:

_gaq.push(['_trackPageview', 'virtual/formSubmit']);

I've tried a few options, but nothing works. I don't see the call being made to Google Analytics...

How can I fix this problem?