问:
How to write in the same file C++
I need to delete all the occurencies of a string in a file.
I receive the text as a string and erase every occurencies.
After I deleted all the occurencies i don't know how to save the string back to the file.

I've tried to close the file and wit ofstream to write in it but it didn't work.

```<code>#include <iostream>
#include <fstream>
#include <string>

int main () {
    std::string file_contents = "";
    std::ifstream myfile ("text.txt");

    char ch;

    if (myfile.is_open())
    {
        // READ FILE CONTENTS AS STRING
        while ( myfile >> std::noskipws >> ch)
        {
            file_contents += ch;
        }

        // DISPLAY STRING
        std::cout << file_contents << '\n';

        // GET WORD TO BE DELETED
        std::string word;
        std::cout << "Please enter word to be deleted: ";
        std::cin >> word;

        std::string::size_type found;

        std::string new_text;
        //DELETE WORD FROM STRING
        bool ok=0;
        do{
        found = file_contents.find(word);
        ok=1;
        if (found!=std::string::npos)
        {
            std::cout << word << " found at: " << found << '\n';
            file_contents.erase(found, word.length());
            std::cout << file_contents << '\n';

        }
        else
            ok==0;
            new_text=file_contents;
        }while(ok==1);

        myfile.close();
    }

    else std::cout << "Unable to open file";

    return 0;
}

</code>```

答:
Okay so you must close ifstream instance before proceeding to write to the file again.

After closing the file, modify the content and then open the same file for write using ofstream and simply write the content.

```<code>#include <iostream>
#include <fstream>
#include <string>

int main() {
  std::string file_contents = "";
  std::ifstream myfile("text.txt");

  char ch;

  if (myfile.is_open())
  {
    // READ FILE CONTENTS AS STRING
    while (myfile >> std::noskipws >> ch)
    {
      file_contents += ch;
    }
    myfile.close();
  }
  else {
    std::cout << "Unable to open file";
    return -1; // no need to continue if can't read it
  }

  // DISPLAY STRING
  std::cout << file_contents << '\n';

  // GET WORD TO BE DELETED
  std::string word;
  std::cout << "Please enter word to be deleted: ";
  std::cin >> word;

  //DELETE WORD FROM STRING
  size_t found;
  while ((found = file_contents.find(word)) != file_contents.npos)
  {
    std::cout << word << " found at: " << found << '\n';
    file_contents.erase(found, word.length());
    std::cout << file_contents << '\n';
  }

  // this will open in text mode and will replace all existing content
  std::ofstream out("text.txt");
  if (out.is_open()) {
    out << file_contents;
    out.close();
  }
  else {
    std::cout << "Unable to open file for writing.\n";
    return -2; // for failure to open for write
  }
  return 0;
}
</code>```

Note: the loop you had went infinitely when I tried to execute it, I had to change it to the code shown above. Also, new_text is completely unnecessary, why have it?

Title: How to write in the same file C++

Body:
I need to delete all the occurencies of a string in a file.
I receive the text as a string and erase every occurencies.
After I deleted all the occurencies i don't know how to save the string back to the file.

I've tried to close the file and wit ofstream to write in it but it didn't work.

#include <iostream>
#include <fstream>
#include <string>

int main () {
    std::string file_contents = "";
    std::ifstream myfile ("text.txt");

    char ch;

    if (myfile.is_open())
    {
        // READ FILE CONTENTS AS STRING
        while ( myfile >> std::noskipws >> ch)
        {
            file_contents += ch;
        }

        // DISPLAY STRING
        std::cout << file_contents << '\n';

        // GET WORD TO BE DELETED
        std::string word;
        std::cout << "Please enter word to be deleted: ";
        std::cin >> word;

        std::string::size_type found;

        std::string new_text;
        //DELETE WORD FROM STRING
        bool ok=0;
        do{
        found = file_contents.find(word);
        ok=1;
        if (found!=std::string::npos)
        {
            std::cout << word << " found at: " << found << '\n';
            file_contents.erase(found, word.length());
            std::cout << file_contents << '\n';

        }
        else
            ok==0;
            new_text=file_contents;
        }while(ok==1);

        myfile.close();
    }

    else std::cout << "Unable to open file";

    return 0;
}

Body:
Okay so you must close ifstream instance before proceeding to write to the file again.

After closing the file, modify the content and then open the same file for write using ofstream and simply write the content.

#include <iostream>
#include <fstream>
#include <string>

int main() {
  std::string file_contents = "";
  std::ifstream myfile("text.txt");

  char ch;

  if (myfile.is_open())
  {
    // READ FILE CONTENTS AS STRING
    while (myfile >> std::noskipws >> ch)
    {
      file_contents += ch;
    }
    myfile.close();
  }
  else {
    std::cout << "Unable to open file";
    return -1; // no need to continue if can't read it
  }

  // DISPLAY STRING
  std::cout << file_contents << '\n';

  // GET WORD TO BE DELETED
  std::string word;
  std::cout << "Please enter word to be deleted: ";
  std::cin >> word;

  //DELETE WORD FROM STRING
  size_t found;
  while ((found = file_contents.find(word)) != file_contents.npos)
  {
    std::cout << word << " found at: " << found << '\n';
    file_contents.erase(found, word.length());
    std::cout << file_contents << '\n';
  }

  // this will open in text mode and will replace all existing content
  std::ofstream out("text.txt");
  if (out.is_open()) {
    out << file_contents;
    out.close();
  }
  else {
    std::cout << "Unable to open file for writing.\n";
    return -2; // for failure to open for write
  }
  return 0;
}

Note: the loop you had went infinitely when I tried to execute it, I had to change it to the code shown above. Also, new_text is completely unnecessary, why have it?


来源: stackexchange

问:
Return stored procedure result from a second stored procedure?
This is a question about some stored procedures running on MSSQL 8 (I think that's SQL Server 2000).

I have two stored procedures left by my predecessor at the company.

The "Modify" window for the first procedure looks something like this:

```<code>ALTER PROCEDURE [dbo].[Proc1]
    @ID,
    @someBool

AS
BEGIN

SELECT colA, colB, colC
FROM   myTable
WHERE  colA = @ID AND colB = @someBool

END
</code>```

The second procedure is very similar, being something along the lines of:

```<code>ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

SELECT colA, colB
FROM   myTable
WHERE  colA = @ID AND colB = FALSE

END
</code>```

Obviously, the real procedures are more complicated than this and require a lot more maintenance when changes are made.

Rather than maintaining these two queries separately, which pretty much sucks, I was wondering if there was any way to simply have Proc2 do something along the lines of:

```<code>ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

EXEC Proc1(@ID, FALSE)
"drop colC"
"return modified result"

END
</code>```

Any ideas on the best way to go about this?

答:
Maybe something like this?</p>

```<code>CREATE TABLE #Proc1TempResults
(
    ColA INT, --OR WHATEVER DATA TYPE
    ColB INT,
    ColC INT
)

INSERT INTO #Proc1TempResults (ColA, ColB, ColC)
EXEC Proc1 @ID, 0

SELECT ColA, ColB
FROM #Proc1TempResults
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is a question about some stored procedures running on MSSQL 8 (I think that's SQL Server 2000).

I have two stored procedures left by my predecessor at the company.

The "Modify" window for the first procedure looks something like this:

ALTER PROCEDURE [dbo].[Proc1]
    @ID,
    @someBool

AS
BEGIN

SELECT colA, colB, colC
FROM   myTable
WHERE  colA = @ID AND colB = @someBool

END

The second procedure is very similar, being something along the lines of:

ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

SELECT colA, colB
FROM   myTable
WHERE  colA = @ID AND colB = FALSE

END

Obviously, the real procedures are more complicated than this and require a lot more maintenance when changes are made.

Rather than maintaining these two queries separately, which pretty much sucks, I was wondering if there was any way to simply have Proc2 do something along the lines of:

ALTER PROCEDURE [dbo].[Proc2]
    @ID

AS
BEGIN

EXEC Proc1(@ID, FALSE)
"drop colC"
"return modified result"

END

Any ideas on the best way to go about this?

Body:
Maybe something like this?

CREATE TABLE #Proc1TempResults
(
    ColA INT, --OR WHATEVER DATA TYPE
    ColB INT,
    ColC INT
)

INSERT INTO #Proc1TempResults (ColA, ColB, ColC)
EXEC Proc1 @ID, 0

SELECT ColA, ColB
FROM #Proc1TempResults


问:
How to update data in table if data is match other then insert in mysql
Insert a row in sql if any match then update it.

I tried it

```<code>INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@s.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+
</code>```

This is only work for checking duplicate entry. but i want if no enrty found then insert it or other than update it.

```<code>INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@somewhere.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+
</code>```

答:
First of all you need to RUN this query

```<code>ALTER TABLE test ADD CONSTRAINT email UNIQUE (email);
</code>```

After Then use this it will update your record if exist

```<code>INSERT INTO test (name,email) VALUES ('Gorilla','Somewhere@s.com') ON DUPLICATE KEY UPDATE email = "Somewhere@somewhere.com"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Insert a row in sql if any match then update it.

I tried it

INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@s.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+

This is only work for checking duplicate entry. but i want if no enrty found then insert it or other than update it.

INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@somewhere.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+

Body:
First of all you need to RUN this query

ALTER TABLE test ADD CONSTRAINT email UNIQUE (email);

After Then use this it will update your record if exist

INSERT INTO test (name,email) VALUES ('Gorilla','Somewhere@s.com') ON DUPLICATE KEY UPDATE email = "Somewhere@somewhere.com"


问:
What is the difference between application server and web server?
What is the difference between application server and web server?</p>

答:
Basic understanding :

In client server architecture

Server :> Which serves the requests.

Client :> Which consumes service.

Web server & Application server are both software applications which act as servers to their clients.

They got their names based on their place of utilization.

```<code>Web server :> serve web content
           :> Like Html components
           :> Like Javascript components
           :> Other web components like images,resource files
           :> Supports mainly web protocols like http,https.
           :> Supports web Request & Response formats.
</code>```

Usage --

```<code>      we require low processing rates,

      regular processing practices involves.
</code>```

Eg: All flat servers generally available ready-made  which serves only web
   based content.

```<code>Application server :> Serve application content/component data(Business data).
                   :> These are special kind which are custom written
                      designed/engineered for specific
                      purpose.some times fully unique in
                      their way and stands out of the crowd.

                   :> As these serves different types of data/response contents
                   :> So we can utilize these services for mobile client,web
                      clients,intranet clients.
                   :> Usually application servers are services offered on different
                      protocols.
                   :> Supports different Request& Response formats.
</code>```

Usage --

```<code>      we require multi point processing,

      specialized processing techniques involves like for AI.
</code>```

Eg: Google maps servers, Google search servers,Google docs servers,Microsoft 365
  servers,Microsoft computer vision servers for AI.

We can assume them as tiers/Hierarchies in 4-tier/n-tier architecture.

```<code> So they can provide
                    load balancing,
                    multiple security levels,
                    multiple active points,
                    even they can provide different request processing environments.
</code>```

Please follow this link for standard architecture analogies:

https://learn.microsoft.com/en-us/previous-versions/msp-n-p/ee658120(v%3dpandp.10)

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Roger Pate

Body:
Basic understanding :

In client server architecture

Server :> Which serves the requests.

Client :> Which consumes service.

Web server & Application server are both software applications which act as servers to their clients.

They got their names based on their place of utilization.

Web server :> serve web content
           :> Like Html components
           :> Like Javascript components
           :> Other web components like images,resource files
           :> Supports mainly web protocols like http,https.
           :> Supports web Request & Response formats.

Usage --

      we require low processing rates,

      regular processing practices involves.

Eg: All flat servers generally available ready-made  which serves only web
   based content.

Application server :> Serve application content/component data(Business data).
                   :> These are special kind which are custom written
                      designed/engineered for specific
                      purpose.some times fully unique in
                      their way and stands out of the crowd.

                   :> As these serves different types of data/response contents
                   :> So we can utilize these services for mobile client,web
                      clients,intranet clients.
                   :> Usually application servers are services offered on different
                      protocols.
                   :> Supports different Request& Response formats.

Usage --

      we require multi point processing,

      specialized processing techniques involves like for AI.

Eg: Google maps servers, Google search servers,Google docs servers,Microsoft 365
  servers,Microsoft computer vision servers for AI.

We can assume them as tiers/Hierarchies in 4-tier/n-tier architecture.

 So they can provide
                    load balancing,
                    multiple security levels,
                    multiple active points,
                    even they can provide different request processing environments.

Please follow this link for standard architecture analogies:

https://learn.microsoft.com/en-us/previous-versions/msp-n-p/ee658120(v%3dpandp.10)


问:
Input mp3 file returns 0
When I try to input an mp3 file the $_FILES returns null.

Controller:

```<code>$audio = $_FILES['muziek']['tmp_name'];

if ($audio != ''){
     $audioContent = file_get_contents($audio);
     $this->load->model('muziek_model');
     $this->muziek_model->insertMuziek($audioContent);
}
var_dump($audio);
var_dump($audioContent);
</code>```

View:

```<code><?php echo form_open_multipart('Muziek/uploadMuziek');?>
<table>
    <tr>
        <td><?php echo form_label('MP3 Bestand:', 'muziek'); ?></td>
        <td><input type="file" name="muziek" id="muziek" accept=".mp3" style="margin-left: 10px; padding-bottom: 35px; color: black" class="btn btn-login form-control login-formcontrol bg-white"/></td>
    </tr>
    <tr>
        <td></td>
        <td>
            <?php echo form_submit('knop', 'Uploaden', 'class = "btn btn-login login-formcontrol"'); ?>
        </td>
    </tr>
</table>
<?php echo form_close();?>
</code>```

When I select an mp3 file audio should not be null

答:
File uploads can fail for a variety of reasons. https://www.php.net/manual/en/features.file-upload.errors.php

Your's is failing because it is too big:

Value: 1; The uploaded file exceeds the upload_max_filesize directive
  in php.ini.

If you have access to php.ini you can change this variable to make it accept larger files.

Even if you do this with success, I would suggest checking for upload errors if(!isset($_FILES['muziek']['tmp_name']) || $_FILES['muziek']['error'] !== 0) { echo 'error'; } before trying to perform actions on a file that may or may not exist.

I personally use: https://github.com/verot/class.upload.php

but Codeigniter has an in-built upload library.

Title: Input mp3 file returns 0

Body:
When I try to input an mp3 file the $_FILES returns null.

Controller:

$audio = $_FILES['muziek']['tmp_name'];

if ($audio != ''){
     $audioContent = file_get_contents($audio);
     $this->load->model('muziek_model');
     $this->muziek_model->insertMuziek($audioContent);
}
var_dump($audio);
var_dump($audioContent);

View:

<?php echo form_open_multipart('Muziek/uploadMuziek');?>

        <?php echo form_label('MP3 Bestand:', 'muziek'); ?>
        <input type="file" name="muziek" id="muziek" accept=".mp3" style="margin-left: 10px; padding-bottom: 35px; color: black" class="btn btn-login form-control login-formcontrol bg-white"/>

            <?php echo form_submit('knop', 'Uploaden', 'class = "btn btn-login login-formcontrol"'); ?>

<?php echo form_close();?>

When I select an mp3 file audio should not be null


问:
How to check whether a zip file is successfully downloaded or not using java-selenium webdriver?
I am downloading multiple zip files from an application and each file has different size. Obviously, the downloading time depends upon the file size. I have the below java code to check the download based on the file size .But it is not working as expected.It is just waiting for 10 seconds and terminating the loop by continuing to the next set of lines. Could someone please help me solve this issue?

```<code>public void isFileDownloaded(String downloadPath, String folderName) {

        String source = "downloadPath" + folderName + ".zip";

        long fileSize1;
        long fileSize2;
        do {
            System.out.println("Entered do-while loop to check if file is downloaded successfully");

            String tempFile = source + "crdownload";
            fileSize1 = tempFile.length(); // check file size
            System.out.println("file size before wait time: " + fileSize1 + " Bytes");
            Thread.sleep(10); // wait for 10 seconds
            fileSize2 = tempFile.length(); // check file size again
            System.out.println("file size after wait time: " + fileSize2 + " Bytes");

        } while (fileSize2 != fileSize1);

        }
</code>```

The fileSize before and after wait time is always returning 43 bytes.

答:
Take two list of Strings :

```<code>List<String> expectedFileName ;
</code>```

in this list add every file name which you must have in String Format.[Your expected File names]

then after downloading all the files, go to download directory :

Check how many files are present by using code like this :

```<code>new File(<directory path>).list().length
</code>```

Now compare the length of expected and actual :

expectedFileName.size() and new File(<directory path>).list().length , If there is any mismatch then return false and print Files are missing.If there's not any mismatch then get all the file names from directory like this :

```<code>List<String> actualFileName;
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
   actualFileName.add(listOfFiles[i].getName());
}
}
</code>```

Now you have two list of String , you can easily compare it. Though It won't check the file size.

Body:
I am downloading multiple zip files from an application and each file has different size. Obviously, the downloading time depends upon the file size. I have the below java code to check the download based on the file size .But it is not working as expected.It is just waiting for 10 seconds and terminating the loop by continuing to the next set of lines. Could someone please help me solve this issue?

public void isFileDownloaded(String downloadPath, String folderName) {

        String source = "downloadPath" + folderName + ".zip";

        long fileSize1;
        long fileSize2;
        do {
            System.out.println("Entered do-while loop to check if file is downloaded successfully");

            String tempFile = source + "crdownload";
            fileSize1 = tempFile.length(); // check file size
            System.out.println("file size before wait time: " + fileSize1 + " Bytes");
            Thread.sleep(10); // wait for 10 seconds
            fileSize2 = tempFile.length(); // check file size again
            System.out.println("file size after wait time: " + fileSize2 + " Bytes");

        } while (fileSize2 != fileSize1);

        }

The fileSize before and after wait time is always returning 43 bytes.

Body:
Take two list of Strings :

List<String> expectedFileName ;

in this list add every file name which you must have in String Format.[Your expected File names]

then after downloading all the files, go to download directory :

Check how many files are present by using code like this :

new File(<directory path>).list().length

Now compare the length of expected and actual :

expectedFileName.size() and new File(<directory path>).list().length , If there is any mismatch then return false and print Files are missing.If there's not any mismatch then get all the file names from directory like this :

List<String> actualFileName;
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
   actualFileName.add(listOfFiles[i].getName());
}
}

Now you have two list of String , you can easily compare it. Though It won't check the file size.


答:
This is how I manage downloading files:</p>

```<code>public class Rahul {

    String downloadDir = "C:\\Users\\pburgr\\Downloads\\";

    public WebDriverWait waitSec(WebDriver driver, int sec) {
        return new WebDriverWait(driver, sec);
    }

    public File waitToDownloadFile(WebDriver driver, int sec, String fileName) {
        String filePath = downloadDir + fileName;
        waitSec(driver, 30).until(new Function<WebDriver, Boolean>() {
          public Boolean apply(WebDriver driver) {
            if (Files.exists(Paths.get(filePath))) {
              System.out.println("Downloading " + filePath + " finished.");
              return true;
            } else {
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                 System.out.println("Downloading " + filePath + " not finished yet.");
              }
            }
            return false;
          }
        });
        File downloadedFile = new File(filePath);
        return downloadedFile;
      }
}
</code>```

Title: How to check whether a zip file is successfully downloaded or not using java-selenium webdriver?

Body:
This is how I manage downloading files:

public class Rahul {

    String downloadDir = "C:\\Users\\pburgr\\Downloads\\";

    public WebDriverWait waitSec(WebDriver driver, int sec) {
        return new WebDriverWait(driver, sec);
    }

    public File waitToDownloadFile(WebDriver driver, int sec, String fileName) {
        String filePath = downloadDir + fileName;
        waitSec(driver, 30).until(new Function<WebDriver, Boolean>() {
          public Boolean apply(WebDriver driver) {
            if (Files.exists(Paths.get(filePath))) {
              System.out.println("Downloading " + filePath + " finished.");
              return true;
            } else {
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                 System.out.println("Downloading " + filePath + " not finished yet.");
              }
            }
            return false;
          }
        });
        File downloadedFile = new File(filePath);
        return downloadedFile;
      }
}


问:
MySQL workbench does not display the tables
I installed mysql workbench in Windows7 32 bit machine. I imported a dump tables from another machine, the import process completes successfully as mysql shows. But, I can not see the tables, even after refresh all. Not only the tables that I import, even the tables in the test database (that comes by default) or any previously created tables in another database. Simply, it just shows the database name without the plus sign that display the tables. I removed mysql, installed it again, but no hope. I installed the requirements for mysql. What can be the reasons for such problem ?</p>

答: I had faced the same issue, Decrease the window size of workbench, table will be visible.</p>


问:
Creating secret keys with same shared secret leads to different results
i'm working on Android application which requires to create secure channel between the app and the server(.NET), the first step is we creating shared secret, the app generates key pair (EC) and sends the public key to the server, then the server creates its own key pair and send the public key to the app and save the shared secret created based on app's public and server private keys and the server send back to the app its own public, salt and iv, then the app perform key agreement, the result is that both the android app and the server have string created based on public-private keys.

Later when the android app want to send some encrypted message to the server, i take the generated secret, salt and iv and creates secret key to be able use Cipher to encrypt the message.

The problem is even though the app and the server have exact the same shred secret, salt and iv for some reason android generates different SecretKey than the server (we checked in debug mode to see that the shared secret salt and iv are same).

Here is the code i use to create secret key:

```<code>byte[] sharedSecretBytes = Base64.decode(sharedSecretBase64, Base64.DEFAULT);
byte[] ivBytes = Base64.decode(ivBase64, Base64.DEFAULT);
byte[] saltBytes = Base64.decode(saltBase64, Base64.DEFAULT);

String sharedSecret = new String(sharedSecretBytes, "UTF-8");
//i tried to use different encoding, no luck.
//String sharedSecretAscii = new String(sharedSecretBytes, "ASCII");
char[] charArray  = sharedSecret .toCharArray();

PBEKeySpec keySpec = new PBEKeySpec(charArray, saltBytes, 1000, 256);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey key = secretKeyFactory.generateSecret(keySpec);

//here the keyBytes are not the same as generated in the server.
byte[] keyBytes = key.getEncoded();

//i saw in some tutorial somene do this, not sure why because we can provide the key as is to the cipher,
//the problem is that both not working.
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getEncoded(), "AES");

IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

byte[] encrypted = cipher.doFinal(logNumber.getBytes("UTF-8"));
String asString = Base64.encodeToString(encrypted, Base64.NO_WRAP);
</code>```

I also made try to pub hard-coded shared secret as "123abc" in both android and server side and actually it worked so my only guess is that the problem coming from converting the sharedSecrte.toCharArray(), if the sharedSecret contains weird characters can lead java generating bad secret key?

Also we working on iOS app that make exactly same process and have no issue to generate correct keys.

答:
In the end the only thing that worked as expected was to use Bouncy Castle library
What i done is :

```<code>PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
      generator.init(sharedSecretBytes, saltBytes, 1000);
      byte[] dk = ((KeyParameter) generator.generateDerivedParameters(256)).getKey();
      SecretKeySpec secretKeySpec = new SecretKeySpec(dk, "AES");

      IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

      byte[] encrypted = cipher.doFinal(logNumber.getBytes("UTF-8"));
</code>```

Still don't understand why native java.security makes trouble .

Body:
i'm working on Android application which requires to create secure channel between the app and the server(.NET), the first step is we creating shared secret, the app generates key pair (EC) and sends the public key to the server, then the server creates its own key pair and send the public key to the app and save the shared secret created based on app's public and server private keys and the server send back to the app its own public, salt and iv, then the app perform key agreement, the result is that both the android app and the server have string created based on public-private keys.

Later when the android app want to send some encrypted message to the server, i take the generated secret, salt and iv and creates secret key to be able use Cipher to encrypt the message.

The problem is even though the app and the server have exact the same shred secret, salt and iv for some reason android generates different SecretKey than the server (we checked in debug mode to see that the shared secret salt and iv are same).

Here is the code i use to create secret key:

byte[] sharedSecretBytes = Base64.decode(sharedSecretBase64, Base64.DEFAULT);
byte[] ivBytes = Base64.decode(ivBase64, Base64.DEFAULT);
byte[] saltBytes = Base64.decode(saltBase64, Base64.DEFAULT);

String sharedSecret = new String(sharedSecretBytes, "UTF-8");
//i tried to use different encoding, no luck.
//String sharedSecretAscii = new String(sharedSecretBytes, "ASCII");
char[] charArray  = sharedSecret .toCharArray();

PBEKeySpec keySpec = new PBEKeySpec(charArray, saltBytes, 1000, 256);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey key = secretKeyFactory.generateSecret(keySpec);

//here the keyBytes are not the same as generated in the server.
byte[] keyBytes = key.getEncoded();

//i saw in some tutorial somene do this, not sure why because we can provide the key as is to the cipher,
//the problem is that both not working.
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getEncoded(), "AES");

IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

byte[] encrypted = cipher.doFinal(logNumber.getBytes("UTF-8"));
String asString = Base64.encodeToString(encrypted, Base64.NO_WRAP);

I also made try to pub hard-coded shared secret as "123abc" in both android and server side and actually it worked so my only guess is that the problem coming from converting the sharedSecrte.toCharArray(), if the sharedSecret contains weird characters can lead java generating bad secret key?

Also we working on iOS app that make exactly same process and have no issue to generate correct keys.

Body:
In the end the only thing that worked as expected was to use Bouncy Castle library
What i done is :

PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
      generator.init(sharedSecretBytes, saltBytes, 1000);
      byte[] dk = ((KeyParameter) generator.generateDerivedParameters(256)).getKey();
      SecretKeySpec secretKeySpec = new SecretKeySpec(dk, "AES");

      IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

      byte[] encrypted = cipher.doFinal(logNumber.getBytes("UTF-8"));

Still don't understand why native java.security makes trouble .


问:
Php, problem with increasing key value by 1
I have spent now 2 days figuring out this problem. I'm trying to create voting script which reads .txt file and modifies values inside it. I have problem with foreach part where I try to add +1 in votes of person. 1-5 is id of person, number after | is amount of votes. First output is:

```<code>Array
(
[0] => 1|2

[1] => 2|6

[2] => 3|8

[3] => 4|3

[4] => 5|10
</code>```

and I want it to add just +1 in last number. But if I try to use increment, I get error: "PHP Fatal error:  Cannot increment/decrement overloaded objects nor string offsets in..."

```<code>foreach ($file_contents as &$id) {
  if ($id == 2) {
    $id[2]++;
  }
}

print_r($file_contents);
</code>```

I'm still learning PHP and this is weird to me, because just giving "$id[2] = 8" actually modifies that value. Why ++ can't be used? What's way around this?

```<code>Array
(
[0] => 1|2

[1] => 2|8

[2] => 3|8

[3] => 4|3

[4] => 5|10
)
</code>```

答:
Use json instead. It will make your life much easier.

Json is a text string that can be decode in to an array.

Either a indexed array or an associative array. Associative is preferred in this case in my opinion.

```<code>$votes = ["1" => 2, "2" => 6, "3" => 8, "4" => 3, "5" => 10];
// Above is an associative array with the same data as your example.
// The key is the id and the value is the votes.
// To read it from the file use:
// $votes = json_decode(file_get_contents("file.txt"));

$inputVote = 2; // someone voted on person 2.

if(!isset($votes[$inputVote])) $votes[$inputVote] = 0; // if someone voted on a person not already in the array, add the person to the array.

$votes[$inputVote]++; // increments the votes on person 2.

file_put_contents("file.txt", json_encode($votes));
</code>```

Body:
I have spent now 2 days figuring out this problem. I'm trying to create voting script which reads .txt file and modifies values inside it. I have problem with foreach part where I try to add +1 in votes of person. 1-5 is id of person, number after | is amount of votes. First output is:

Array
(
[0] => 1|2

[1] => 2|6

[2] => 3|8

[3] => 4|3

[4] => 5|10

and I want it to add just +1 in last number. But if I try to use increment, I get error: "PHP Fatal error:  Cannot increment/decrement overloaded objects nor string offsets in..."

foreach ($file_contents as &$id) {
  if ($id == 2) {
    $id[2]++;
  }
}

print_r($file_contents);

I'm still learning PHP and this is weird to me, because just giving "$id[2] = 8" actually modifies that value. Why ++ can't be used? What's way around this?

Array
(
[0] => 1|2

[1] => 2|8

[2] => 3|8

[3] => 4|3

[4] => 5|10
)

Body:
Use json instead. It will make your life much easier.

Json is a text string that can be decode in to an array.

Either a indexed array or an associative array. Associative is preferred in this case in my opinion.

$votes = ["1" => 2, "2" => 6, "3" => 8, "4" => 3, "5" => 10];
// Above is an associative array with the same data as your example.
// The key is the id and the value is the votes.
// To read it from the file use:
// $votes = json_decode(file_get_contents("file.txt"));

$inputVote = 2; // someone voted on person 2.

if(!isset($votes[$inputVote])) $votes[$inputVote] = 0; // if someone voted on a person not already in the array, add the person to the array.

$votes[$inputVote]++; // increments the votes on person 2.

file_put_contents("file.txt", json_encode($votes));


问:
Center alignment for both vertical and horizontal
I want to show an image in the center of a page with original size.

I tried the code below

.container
    {

      margin-left: auto;
      margin-right: auto;
        vertical-align: middle;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>

    <div class="container"><img src="1.png" alt="No Internet Connection" ></div>

    </body>
    </html></code>```

答:
.container
    {
      display: flex;
    align-items: center;
    justify-content: center;
       height: 90vh;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>

    <div class="container"><img src="1.png" alt="No Internet Connection" ></div>

    </body>
    </html></code>```

You can use display: flex;. It's responsive and works great. After that I used justify-content: center; because of this it is horizontal in the center. And because of align-items: center; and height: 90vh; it is vertical centered

Body:
I want to show an image in the center of a page with original size.

I tried the code below

.container
    {

      margin-left: auto;
      margin-right: auto;
        vertical-align: middle;
     }

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

Body:
.container
    {
      display: flex;
    align-items: center;
    justify-content: center;
       height: 90vh;
     }

<html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>

    <div class="container"><img src="1.png" alt="No Internet Connection" ></div>

    </body>
    </html>

You can use display: flex;. It's responsive and works great. After that I used justify-content: center; because of this it is horizontal in the center. And because of align-items: center; and height: 90vh; it is vertical centered


问:
Regex.Replace - skip strings which are part of a longer string
I need to replace a list of numeric strings in a text file. However, if the string is part of another numeric string it should not be replaced:
String to be replaced: 111111
Replacement string: MASKED

```<code>Text file:
111111
 111111.text text
text text111111 text text
a111111
2111111
111111a
1111112
a111111a

Expected result:
MASKED
 MASKED.text text
text textMASKED text text
aMASKED
2111111 -> Character 2 prevents masking
MASKEDa
1111112 -> Character 2 prevents masking
aMASKEDa
</code>```

This is my code:

```<code>inputText = Regex.Replace(inputText, "(?<![0-9])" + stringToMask + "(?<![0-9])", "####MASKED####");
</code>```

This code just skips everything and doesn't perform any masking.

答: You can use MatchEvaluator http://www.dotnetperls.com/regex-replace to perform replace by condition. To decide preform replace or not you can add first and last letter to match pattern, split string by this pattern and analyze first and last symbols.</p>

Body:
I need to replace a list of numeric strings in a text file. However, if the string is part of another numeric string it should not be replaced:
String to be replaced: 111111
Replacement string: MASKED

Text file:
111111
 111111.text text
text text111111 text text
a111111
2111111
111111a
1111112
a111111a

Expected result:
MASKED
 MASKED.text text
text textMASKED text text
aMASKED
2111111 -> Character 2 prevents masking
MASKEDa
1111112 -> Character 2 prevents masking
aMASKEDa

This is my code:

inputText = Regex.Replace(inputText, "(?<![0-9])" + stringToMask + "(?<![0-9])", "####MASKED####");

This code just skips everything and doesn't perform any masking.


问:
Grant Cloudformation permissions to only resources that are part of the stack
At my company, our CI/CD pipleline can only connect to AWS via an assumed IAM role. I'm trying to lock down this role so that it can only update resources that are part of the stack, to avoid mistakenly changing a resource that is managed by another team.

I am running into a bit of a chicken or the egg scenario here. It seems that in order to create a role that restricts access to just the resources created by my stack, I need the IDs of those resources, which means the stack needs to have been created. I could run the stack with admin permissions once, then extract the resource IDs, and then put it into CI/CD, but that seems to defeat the purpose.

My ideal solution would be to be able to create a set of permissions that allow CloudFormation to create a fixed set of Resource Types, and then grant additional permissions to only those resources that were created as part of the stack. Is this possible? Or is there a different philosophy for how to manage the permissions for CI/CD?

答:
What has me confused is how you want to "lock down" the resource to a particular stack. Anyway, try this:

Have a role that only have Create* permissions (You prob need Describe* too). This role is used to create new stacks and so it's not possible for it to meddle with resources already created.

In your CloudFormation template, create an IAM role that has Update* / Delete* permission to your resource. Call into this role when you want to modify the stack. Maybe give it a name of !Sub ${AWS::StackName}-CfnRole.

You'll also need to give it a deletion policy of retain and delete it manually after the stack is cleaned up.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html. Otherwise, when you call that role to delete a stack, you'll run into permission denied error as the role will almost certainly be the first resource to be deleted.

?? Does that work for you


问:
How to find occurence of objects in an array
I need to know if an array of objects contains at least two same objects in it, in JavaScript.

I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.

```<code>// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]
</code>```

I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.

答:
You can use lodash.js to compare two objects.
Please see the sample below.

```<code>let array = [{ value: "a" }, { value: "b" }, { value: "c" }, { value: "a" }];

const object = { value: "a" };

countObjOccurrences = object => {
  let occurances = 0;
  array.map(item => {
    if (_.isEqual(item, object)) {
      occurances += 1;
    }
  });
  return occurances;
};
</code>```

This function will return 2.

Body:
I need to know if an array of objects contains at least two same objects in it, in JavaScript.

I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.

// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]

I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.

Body:
You can use lodash.js to compare two objects.
Please see the sample below.

let array = [{ value: "a" }, { value: "b" }, { value: "c" }, { value: "a" }];

const object = { value: "a" };

countObjOccurrences = object => {
  let occurances = 0;
  array.map(item => {
    if (_.isEqual(item, object)) {
      occurances += 1;
    }
  });
  return occurances;
};

This function will return 2.


问:
How to avoid grouping images (bars) while selecting contours in an image?
I am extracting the length of individual bars from a chart image. It works fine in most of the cases but in some cases the contour groups 2 bars as 1 which is detrimental to my cause. I tried different combinations of canny,dilate, erode, and color scheme. It improved the result only slightly. How can avoid the grouping? Here is the complete code and one image. You can run using this image too see the problem.

```<code>from scipy.spatial import distance as dist
from imutils import perspective
from imutils import contours
import numpy as np
import argparse
import imutils
import cv2

def midpoint(ptA, ptB):
    return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)

image = cv2.imread("somefile.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)

#edged=cv2.Laplacian(gray, cv2.CV_8U, gray, ksize=7)

edged = cv2.Canny(gray, 30, 50)
cv2.imwrite("test00.png", edged)
edged = cv2.dilate(edged, None, iterations=1)
cv2.imwrite("test01.png", edged)
edged = cv2.erode(edged, None, iterations=1)
cv2.imwrite("test02.png", edged)

cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

pixelsPerMetric = 100

for c in cnts:
    orig = image.copy()
    box = cv2.minAreaRect(c)
    box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
    box = np.array(box, dtype="int")
    print(box)

    box = perspective.order_points(box)
    cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)

    for (x, y) in box:
        cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)

    (tl, tr, br, bl) = box
    (tltrX, tltrY) = midpoint(tl, tr)
    (blbrX, blbrY) = midpoint(bl, br)

    (tlblX, tlblY) = midpoint(tl, bl)
    (trbrX, trbrY) = midpoint(tr, br)

    cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)

    cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),
             (255, 0, 255), 2)
    cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),
             (255, 0, 255), 2)

    dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
    dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))

    dimA = dA / pixelsPerMetric
    dimB = dB / pixelsPerMetric

    cv2.putText(orig, "{:.1f}in".format(dimA),
                (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,
                0.65, (255, 255, 255), 2)
    cv2.putText(orig, "{:.1f}in".format(dimB),
                (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,
                0.65, (255, 255, 255), 2)

    cv2.imshow("Image", orig)
    cv2.waitKey(0)
</code>```

答:
This image is trivial to segment. The color of the bars is exactly RGB=(245,222,179). You can use OpenCV's function inRange to find pixels of this color. In this function, we need to give the color in BGR order, because that is how OpenCV reads in images by default. Here I'm picking a slightly larger range in case the image used JPEG compression (which is lossy and therefore changes pixel values slightly):

```<code>image = cv2.imread("somefile.png")
mask = cv2.inRange(image, (177, 220, 243), (181, 224, 247))
</code>```

This image mask now has perfectly separated bars:

Body:
I am extracting the length of individual bars from a chart image. It works fine in most of the cases but in some cases the contour groups 2 bars as 1 which is detrimental to my cause. I tried different combinations of canny,dilate, erode, and color scheme. It improved the result only slightly. How can avoid the grouping? Here is the complete code and one image. You can run using this image too see the problem.

from scipy.spatial import distance as dist
from imutils import perspective
from imutils import contours
import numpy as np
import argparse
import imutils
import cv2

def midpoint(ptA, ptB):
    return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)

image = cv2.imread("somefile.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)

#edged=cv2.Laplacian(gray, cv2.CV_8U, gray, ksize=7)

edged = cv2.Canny(gray, 30, 50)
cv2.imwrite("test00.png", edged)
edged = cv2.dilate(edged, None, iterations=1)
cv2.imwrite("test01.png", edged)
edged = cv2.erode(edged, None, iterations=1)
cv2.imwrite("test02.png", edged)

cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

pixelsPerMetric = 100

for c in cnts:
    orig = image.copy()
    box = cv2.minAreaRect(c)
    box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
    box = np.array(box, dtype="int")
    print(box)

    box = perspective.order_points(box)
    cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)

    for (x, y) in box:
        cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)

    (tl, tr, br, bl) = box
    (tltrX, tltrY) = midpoint(tl, tr)
    (blbrX, blbrY) = midpoint(bl, br)

    (tlblX, tlblY) = midpoint(tl, bl)
    (trbrX, trbrY) = midpoint(tr, br)

    cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)

    cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),
             (255, 0, 255), 2)
    cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),
             (255, 0, 255), 2)

    dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
    dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))

    dimA = dA / pixelsPerMetric
    dimB = dB / pixelsPerMetric

    cv2.putText(orig, "{:.1f}in".format(dimA),
                (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,
                0.65, (255, 255, 255), 2)
    cv2.putText(orig, "{:.1f}in".format(dimB),
                (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,
                0.65, (255, 255, 255), 2)

    cv2.imshow("Image", orig)
    cv2.waitKey(0)

Body:
This image is trivial to segment. The color of the bars is exactly RGB=(245,222,179). You can use OpenCV's function inRange to find pixels of this color. In this function, we need to give the color in BGR order, because that is how OpenCV reads in images by default. Here I'm picking a slightly larger range in case the image used JPEG compression (which is lossy and therefore changes pixel values slightly):

image = cv2.imread("somefile.png")
mask = cv2.inRange(image, (177, 220, 243), (181, 224, 247))

This image mask now has perfectly separated bars:


问:
Find next greater number with zeros in sql number
I'm looking for a way to find next greater number starting by 1 and followed by zeros in Microsoft SQL. Numbers could vary in digits. ie:

Query: 9856, Result after procedure: 10000
Query: 98999, Result after procedure: 100000

Thanks.

EDIT: There is no chance of having negative numbers. This is a calculation for a energy meter. For example, numbers can go up to 99999 or 999999 or 9999999. When energy overcome that number, it will start again at 0. So I can't read what energy has been used in that period. To know it, I need to calculate the number as asked, then perform some basic maths.

There is no need for knowing what is going on on 10, 100, etc, because of the nature of the operation. It will only be used when the above escenario happend.

答:
This works for positive numbers (numbers greater than zero):

```<code>select power(10, ceiling( log10(the_number) )) from mytable;
</code>```

In case the number is already a power of ten (1, 10, 100, ...) , the number itself is returned.

Body:
This works for positive numbers (numbers greater than zero):

select power(10, ceiling( log10(the_number) )) from mytable;

In case the number is already a power of ten (1, 10, 100, ...) , the number itself is returned.


问:
map of map get outer map based on inner map value
How do I write below code using Java8?

```<code>for (Entry<Integer, Map<String, Object>> entry : data.entrySet()) {
  Map<String, Object> value = entry.getValue();
  if (value.get(Constants.USER_TRAN_ID).equals(stsTxn.getSeedTrade().getTransactionId())) {
    closedTaxLotByTxnId = value;
    break;
  }
}
</code>```

I am clueless after this

```<code>data.values().stream().map(e -> e.get(Constants.USER_TRAN_ID)).filter(txnId -> txnId.equals(stsTxn.getSeedTrade().getTransactionId()));
</code>```

答:
You don't need map. Just use filter with your criteria, and findFirst as terminal operation:

```<code>Optional<Map<String, Object>>
    value = data.values()
                .stream()
                .filter(m -> m.get(Constants.USER_TRAN_ID).equals(stsTxn.getSeedTrade().getTransactionId()))
                .findFirst();
</code>```

If you want a default value (such as null) when no match is found, use:

```<code>Map<String, Object> closedTaxLotByTxnId =
           data.values()
               .stream()
               .filter(m -> m.get(Constants.USER_TRAN_ID).equals(stsTxn.getSeedTrade().getTransactionId()))
               .findFirst()
               .orElse(null);
</code>```

Body:
How do I write below code using Java8?

for (Entry<Integer, Map<String, Object>> entry : data.entrySet()) {
  Map<String, Object> value = entry.getValue();
  if (value.get(Constants.USER_TRAN_ID).equals(stsTxn.getSeedTrade().getTransactionId())) {
    closedTaxLotByTxnId = value;
    break;
  }
}

I am clueless after this

data.values().stream().map(e -> e.get(Constants.USER_TRAN_ID)).filter(txnId -> txnId.equals(stsTxn.getSeedTrade().getTransactionId()));

Body:
You don't need map. Just use filter with your criteria, and findFirst as terminal operation:

Optional<Map<String, Object>>
    value = data.values()
                .stream()
                .filter(m -> m.get(Constants.USER_TRAN_ID).equals(stsTxn.getSeedTrade().getTransactionId()))
                .findFirst();

If you want a default value (such as null) when no match is found, use:

Map<String, Object> closedTaxLotByTxnId =
           data.values()
               .stream()
               .filter(m -> m.get(Constants.USER_TRAN_ID).equals(stsTxn.getSeedTrade().getTransactionId()))
               .findFirst()
               .orElse(null);


问:
How do I make an alphabetized list of all distinct words in a file with the number of times each word was used?
I am writing a program using Microsoft Visual C++. In the program I must read in a text file and print out an alphabetized list of all distinct words in that file with the number of times each word was used.

I have looked up different ways to alphabetize a string but they do not work with the way I have my string initialized.

```<code>// What is inside my text file
Any experienced programmer engaged in writing programs for use by others knows
that, once his program is working correctly, good output is a must. Few people
really care how much time and trouble a programmer has spent in designing and
debugging a program. Most people see only the results. Often, by the time a
programmer has finished tackling a difficult problem, any output may look
great. The programmer knows what it means and how to interpret it. However,
the same cannot be said for others, or even for the programmer himself six
months hence.
</code>```

```<code>string lines;
getline(input, lines);      // Stores what is in file into the string
</code>```

I expect an alphabetized list of words with the number of times each word was used. So far, I do not know how to begin this process.

答:
As others have already noted, an std::map handles the counting you care about quite easily.

Iostreams already have a tokenize to break an input stream up into words. In this case, we want to to only "think" of letters as characters that can make up words though. A stream uses a locale to make that sort of decision, so to change how it's done, we need to define a locale that classifies characters as we see fit.

```<code>struct alpha_only: std::ctype<char> {
    alpha_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table() {
        // everything is white space
        static std::vector<std::ctype_base::mask>
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        // except lower- and upper-case letters, which are classified accordingly:
        std::fill(&rc['a'], &rc['z'], std::ctype_base::lower);
        std::fill(&rc['A'], &rc['Z'], std::ctype_base::upper);
        return &rc[0];
    }
};
</code>```

With that in place, we tell the stream to use our ctype facet, then simply read words from the file and count them in the map:

```<code>std::cin.imbue(std::locale(std::locale(), new alpha_only));
std::map<std::string, std::size_t> counts;

std::string word;
while (std::cin >> word)
    ++counts[to_lower(word)];
</code>```

...and when we're done with that, we can print out the results:

```<code>for (auto w : counts)
    std::cout << w.first << ": " << w.second << "\n";
</code>```

Body:
I am writing a program using Microsoft Visual C++. In the program I must read in a text file and print out an alphabetized list of all distinct words in that file with the number of times each word was used.

I have looked up different ways to alphabetize a string but they do not work with the way I have my string initialized.

// What is inside my text file
Any experienced programmer engaged in writing programs for use by others knows
that, once his program is working correctly, good output is a must. Few people
really care how much time and trouble a programmer has spent in designing and
debugging a program. Most people see only the results. Often, by the time a
programmer has finished tackling a difficult problem, any output may look
great. The programmer knows what it means and how to interpret it. However,
the same cannot be said for others, or even for the programmer himself six
months hence.

string lines;
getline(input, lines);      // Stores what is in file into the string

I expect an alphabetized list of words with the number of times each word was used. So far, I do not know how to begin this process.

Body:
As others have already noted, an std::map handles the counting you care about quite easily.

Iostreams already have a tokenize to break an input stream up into words. In this case, we want to to only "think" of letters as characters that can make up words though. A stream uses a locale to make that sort of decision, so to change how it's done, we need to define a locale that classifies characters as we see fit.

struct alpha_only: std::ctype<char> {
    alpha_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table() {
        // everything is white space
        static std::vector<std::ctype_base::mask>
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        // except lower- and upper-case letters, which are classified accordingly:
        std::fill(&rc['a'], &rc['z'], std::ctype_base::lower);
        std::fill(&rc['A'], &rc['Z'], std::ctype_base::upper);
        return &rc[0];
    }
};

With that in place, we tell the stream to use our ctype facet, then simply read words from the file and count them in the map:

std::cin.imbue(std::locale(std::locale(), new alpha_only));
std::map<std::string, std::size_t> counts;

std::string word;
while (std::cin >> word)
    ++counts[to_lower(word)];

...and when we're done with that, we can print out the results:

for (auto w : counts)
    std::cout << w.first << ": " << w.second << "\n";


问:
How to find task user is currently working upon?
I have following usecase:

A user is working on a user task, and meanwhile other tasks are assigned to her.
So now multiple tasks are assigned  to the user.

User logs out of the system, and logs in. System needs to determine which of the assigned task user was working upon last time.

How can it be done?

There are date fields in act_ru_task table, like claim time, create time etc which can be used to make this decision.

But is there any other facility within Activiti API to do it?

答:
No, Activiti cannot (and should not) maintain recent activities for user.\

These sort of customization can be maintained in user sessions/ browser caches without loading the engine.


问:
How to prevent pytest from printing local variables during a test
I'm executing a simple testing script with pytest. I'm testing if the creation of a database connection succeeded.
The function that creates the database connection requires a username and a password. During the testing, pytest prints out the username and password. Obviously, I don't want passwords to be printed out to the console! How can I prevent this from happening?

I've tried multiple solutions, including using contextlib and custom created NullWriters that suppress stderr and/or stdout (for example here https://stackoverflow.com/a/1810086). However, none of it seems to have any effect.

This is the test function:

```<code>def test_make_db2_connection():

    # get username and password from the environmental variables
    username = os.environ['username']
    password = 'my_password' # would be: os.environ['pwd']

    # create a connection with the database
    connection = make_db2_connection(username, password)

    # assert if the connection exists
    assert connection, "Connection wasn't created."
</code>```

See pytest's output below. As you can see, my username and (testing) password are printed. This is what I want to prevent.

```<code>============================================================================================================ FAILURES ============================================================================================================
____________________________________________________________________________________________________ test_make_db2_connection ____________________________________________________________________________________________________

    def test_make_db2_connection():

        # get username and password from the environmental variables
        username = os.environ['username']
        password = 'my_password' # would be: os.environ['pwd']

        # create a connection with the database
>       connection = make_db2_connection(username, password)

test_file.py:16:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

username = 'E001703', password = 'my_password'

    def make_db2_connection(username, password):
        """Creates a connection with the database"""

        dbalias = os.environ['dbalias']
>       connection = connect(dbalias, username, password)
 SQLCODE=-30082on: [IBM][CLI Driver] SQL30082N  Security processing failed with reason "24" ("USERNAME AND/OR PASSWORD INVALID").  SQLSTATE=08001

=================================================================================================== 1 failed in 14.19 seconds ====================================================================================================
</code>```

答:
Solved by @hoefling! See the comments below the original question.

Solution was to use __tracebackhide__ = True. Downside of this solution is that you need to modify the original function that is being tested, instead of the testing script itself.

Body:
I'm executing a simple testing script with pytest. I'm testing if the creation of a database connection succeeded.
The function that creates the database connection requires a username and a password. During the testing, pytest prints out the username and password. Obviously, I don't want passwords to be printed out to the console! How can I prevent this from happening?

I've tried multiple solutions, including using contextlib and custom created NullWriters that suppress stderr and/or stdout (for example here https://stackoverflow.com/a/1810086). However, none of it seems to have any effect.

This is the test function:

def test_make_db2_connection():

    # get username and password from the environmental variables
    username = os.environ['username']
    password = 'my_password' # would be: os.environ['pwd']

    # create a connection with the database
    connection = make_db2_connection(username, password)

    # assert if the connection exists
    assert connection, "Connection wasn't created."

See pytest's output below. As you can see, my username and (testing) password are printed. This is what I want to prevent.

============================================================================================================ FAILURES ============================================================================================================
____________________________________________________________________________________________________ test_make_db2_connection ____________________________________________________________________________________________________

    def test_make_db2_connection():

        # get username and password from the environmental variables
        username = os.environ['username']
        password = 'my_password' # would be: os.environ['pwd']

        # create a connection with the database
>       connection = make_db2_connection(username, password)

test_file.py:16:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

username = 'E001703', password = 'my_password'

    def make_db2_connection(username, password):
        """Creates a connection with the database"""

        dbalias = os.environ['dbalias']
>       connection = connect(dbalias, username, password)
 SQLCODE=-30082on: [IBM][CLI Driver] SQL30082N  Security processing failed with reason "24" ("USERNAME AND/OR PASSWORD INVALID").  SQLSTATE=08001

=================================================================================================== 1 failed in 14.19 seconds ====================================================================================================


问:
How to ignore children count in my SOAP response
I am using Citrus Framework 2.8.0 for some integration tests on a SOAP webservice.

For a specific operation, the number of children elements may vary and I currently get this error on some calls:

```<code>com.consol.citrus.exceptions.TestCaseFailedException: Validation failed: Number of child elements not equal for element 'myResponse', expected '25' but was '21'
</code>```

How should I write my receive() SoapActionBuilder to ignore this count? Or how can I annotate my response template?

```<code>soap()
    .client(debolClient)
    .receive()
    .payload(new ClassPathResource("templates/responses/myResponse.xml"))
    .schemaValidation(false);
</code>```

Seems that @ignore@ and receive().ignore("/parent/node) won't help.

答:
Template based validation might not be the best way to validate the message in your scenario as it always tries to compare alle elements with all children.

So you might need to switch to something like XPath based validation instead.

You could also use a combination of template based and XPath where you ignore the parent node (where the number of children is of dynamic nature) with @ignore@ in your template. With additional XPath expressions you could try to validate the dynamic amount of children with XPath.

Also you could switch to a script validation using Groovy or validation callback. This is the most powerful way to validate a message in Citrus where you can code whatever you want to meet the dynamic nature of the messages.

Body:
I am using Citrus Framework 2.8.0 for some integration tests on a SOAP webservice.

For a specific operation, the number of children elements may vary and I currently get this error on some calls:

com.consol.citrus.exceptions.TestCaseFailedException: Validation failed: Number of child elements not equal for element 'myResponse', expected '25' but was '21'

How should I write my receive() SoapActionBuilder to ignore this count? Or how can I annotate my response template?

soap()
    .client(debolClient)
    .receive()
    .payload(new ClassPathResource("templates/responses/myResponse.xml"))
    .schemaValidation(false);

Seems that @ignore@ and receive().ignore("/parent/node) won't help.


问:
How to clean up v-bind directives from html code in Vue?
Ok, I've got some Vue code and HTML.

For example:

```<code>Vue.component('area-selectors-box', {
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});
</code>```

And in my page:

```<code><div is="area-selectors-box" v-bind:selects="selects"></div>
</code>```

It all works, but if I read the page source, I see the v-bind:selects="selects" portion, which is not standard compliant, I guess.

Similarly, other components have other object properties like:

```<code>Vue.component('area-option', {
  template: `<option :area="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});
</code>```

which on the page source evaluates to something like:

```<code><option area="[object Object]" value="82">Europa</option>
</code>```

which is obviously not desirable.

How do I bind these properties without them appearing in the DOM as attributes?

答:
My own answer is: pass props when you call the component, not in the component itself. This code will work and produce clean html:

In-page HTML:

```<code><!-- pass selects to area-selectors-box -->
<div is="area-selectors-box" :selects="selects"></div>
</code>```

JS:

```<code>Vue.component('area-selectors-box', { // pass select to area-selector
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', { // pass area to area-option
  template: `
    <select @change="selected" >
      <option disabled selected value="">Seleziona continente</option>
      <area-option v-for="area in select.areas" :area="area" :key="area.term_id"></area-option>
    </select>
  `
  ,props:['select']
});

Vue.component('area-option', { // pass nothing
  template: `<option :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});
</code>```

Body:
Ok, I've got some Vue code and HTML.

For example:

Vue.component('area-selectors-box', {
  template: `

      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>

  `,
  props:['selects']
});

And in my page:

It all works, but if I read the page source, I see the v-bind:selects="selects" portion, which is not standard compliant, I guess.

Similarly, other components have other object properties like:

Vue.component('area-option', {
  template: `<option :area="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});

which on the page source evaluates to something like:

<option area="[object Object]" value="82">Europa</option>

which is obviously not desirable.

How do I bind these properties without them appearing in the DOM as attributes?

Body:
My own answer is: pass props when you call the component, not in the component itself. This code will work and produce clean html:

In-page HTML:

<!-- pass selects to area-selectors-box -->
<div is="area-selectors-box" :selects="selects"></div>

JS:

Vue.component('area-selectors-box', { // pass select to area-selector
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', { // pass area to area-option
  template: `
    <select @change="selected" >
      <option disabled selected value="">Seleziona continente</option>
      <area-option v-for="area in select.areas" :area="area" :key="area.term_id"></area-option>
    </select>
  `
  ,props:['select']
});

Vue.component('area-option', { // pass nothing
  template: `<option :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});


问:
How to obtain a nested average with Dax in Power BI?
I am trying to calculate the average of a column in a measure in DAX, but I have the problem that the values are duplicated on multiple rows.

The data looks like this:

```<code>Line  ID  Value
1     1   10
2     1   10
3     1   10
4     1   10
5     1   10
6     2   40
7     2   40
8     3   90
9     3   90
10    3   90
</code>```

When I do

sum(data[Value]) / countrows(data)

the answer will be (50 + 80 + 270) / 10 = 40.

However, I want the answer to be (10 + 40 + 90) / 3 = 46.7

I know I have to divide by 3 and can achieve the 3 by

distinctcount(data[ID])

But I find it difficult to extract the 10, 40 and 90.

Can you help me?

答:
There are many ways to achieve that. For example:

```<code>Average Value =
  VAR Summarized_Table = SUMMARIZE ( Data, Data[ID], Data[Value] )
  VAR Total_Value = SUMX ( Summarized_Table, Data[Value] )
  VAR Total_Count = COUNTROWS ( Summarized_Table )
  RETURN
    DIVIDE ( Total_Value, Total_Count )
</code>```

Result:

Explanation:

First, we create a summarized version of the data, by grouping it on ID and Value columns. Grouping eliminates duplication, so the summary table contains only 3 records. We save the table in a variable;

Second, we sum up values in the summary table (140);

Third, we count number of records in the summary table (3)

Finally, we return the result by dividing sum and count

Alternatively, you can do this:

```<code>Average Value =
  AVERAGEX ( VALUES ( Data[ID] ), CALCULATE ( AVERAGE ( Data[Value] ) ) )
</code>```

Result is the same, but the logic is different:

First, using VALUES we create a list of distinct IDs;

Second, we use AVERAGEX to iterate the list, and for each ID calculate its average value. For example, for ID=1, result will be Average of (50)/5= 10;

Finally, we average the averages as (10 + 40 + 90) / 3

Body:
I am trying to calculate the average of a column in a measure in DAX, but I have the problem that the values are duplicated on multiple rows.

The data looks like this:

Line  ID  Value
1     1   10
2     1   10
3     1   10
4     1   10
5     1   10
6     2   40
7     2   40
8     3   90
9     3   90
10    3   90

When I do

sum(data[Value]) / countrows(data)

the answer will be (50 + 80 + 270) / 10 = 40.

However, I want the answer to be (10 + 40 + 90) / 3 = 46.7

I know I have to divide by 3 and can achieve the 3 by

distinctcount(data[ID])

But I find it difficult to extract the 10, 40 and 90.

Can you help me?

Body:
There are many ways to achieve that. For example:

Average Value =
  VAR Summarized_Table = SUMMARIZE ( Data, Data[ID], Data[Value] )
  VAR Total_Value = SUMX ( Summarized_Table, Data[Value] )
  VAR Total_Count = COUNTROWS ( Summarized_Table )
  RETURN
    DIVIDE ( Total_Value, Total_Count )

Result:

Explanation:

First, we create a summarized version of the data, by grouping it on ID and Value columns. Grouping eliminates duplication, so the summary table contains only 3 records. We save the table in a variable;

Second, we sum up values in the summary table (140);

Third, we count number of records in the summary table (3)

Finally, we return the result by dividing sum and count

Alternatively, you can do this:

Average Value =
  AVERAGEX ( VALUES ( Data[ID] ), CALCULATE ( AVERAGE ( Data[Value] ) ) )

Result is the same, but the logic is different:

First, using VALUES we create a list of distinct IDs;

Second, we use AVERAGEX to iterate the list, and for each ID calculate its average value. For example, for ID=1, result will be Average of (50)/5= 10;

Finally, we average the averages as (10 + 40 + 90) / 3


问:
Exact number of nested ranked data exact in SQL procedure
I have a procedure like this:

```<code>SELECT Name, Date, Par3, Date_rank
FROM
   (SELECT Name, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC)
   AS Date_rank
   FROM Table
   WHERE (..conditions..)) ranked
WHERE Par2_rank <= 3
ORDER BY Par2 ASC, Par3 ASC
</code>```

The result gives me if number of rows is less or equal 3 is:

```<code>Name,    Date,     Par3,    Date_rank
AB   2010-01-01    1.5          1
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3
</code>```

But I need only results, where we have exact number of rows for date, equal 3.
So the result should be:

```<code>Name,    Date,     Par3,    Date_rank
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3
</code>```

I tried to put WHERE Par2_rank = 3.

Then I get only one row:

```<code>Name,    Date,     Par3,    Date_rank
GH   2010-02-16    1.7          3
</code>```

Also I tried to use HAVING COUNT, but it gives me no rows.

Thanks in advance.

UPDATE:
Thanks to all you guys for quick answers. COUNT (*) OVER PARTITION did the trick. It's so simple.. I hope, I will code better in SQL thanks to you in the future.

答:
If I understand your question correctly, try the following approach using SUM() with OVER clause, but without ORDER BY:

Input:

```<code>CREATE TABLE #Table (
    Name varchar(2),
    [Date] date,
    Par3 numeric(5, 1)
)
INSERT INTO #Table
    (Name, [Date], Par3)
VALUES
    ('AB', '20100101', 1.5),
    ('AB', '20100101', 1.6),
    ('AB', '20100102', 1.5),
    ('AC', '20100102', 1.6),
    ('AD', '20100102', 1.7),
    ('AE', '20100102', 1.8),
    ('CD', '20100216', 0.9),
    ('EF', '20100216', 1.1),
    ('GH', '20100216', 1.7)
</code>```

T-SQL:

```<code>SELECT Name, [Date], Par3, Rn
FROM (
    SELECT
        Name,
        [Date],
        Par3,
        ROW_NUMBER() OVER (PARTITION BY [Date] ORDER BY Par3 ASC) AS Rn,
        COUNT(*) OVER (PARTITION BY [Date]) As Cnt
    FROM #Table
    ) ranked
WHERE Cnt = 3
</code>```

Output:

```<code>------------------------------
Name    Date        Par3    Rn
------------------------------
CD      2010-02-16  0.9     1
EF      2010-02-16  1.1     2
GH      2010-02-16  1.7     3
</code>```

Body:
I have a procedure like this:

SELECT Name, Date, Par3, Date_rank
FROM
   (SELECT Name, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC)
   AS Date_rank
   FROM Table
   WHERE (..conditions..)) ranked
WHERE Par2_rank <= 3
ORDER BY Par2 ASC, Par3 ASC

The result gives me if number of rows is less or equal 3 is:

Name,    Date,     Par3,    Date_rank
AB   2010-01-01    1.5          1
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3

But I need only results, where we have exact number of rows for date, equal 3.
So the result should be:

Name,    Date,     Par3,    Date_rank
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3

I tried to put WHERE Par2_rank = 3.

Then I get only one row:

Name,    Date,     Par3,    Date_rank
GH   2010-02-16    1.7          3

Also I tried to use HAVING COUNT, but it gives me no rows.

Thanks in advance.

UPDATE:
Thanks to all you guys for quick answers. COUNT (*) OVER PARTITION did the trick. It's so simple.. I hope, I will code better in SQL thanks to you in the future.

Body:
If I understand your question correctly, try the following approach using SUM() with OVER clause, but without ORDER BY:

Input:

CREATE TABLE #Table (
    Name varchar(2),
    [Date] date,
    Par3 numeric(5, 1)
)
INSERT INTO #Table
    (Name, [Date], Par3)
VALUES
    ('AB', '20100101', 1.5),
    ('AB', '20100101', 1.6),
    ('AB', '20100102', 1.5),
    ('AC', '20100102', 1.6),
    ('AD', '20100102', 1.7),
    ('AE', '20100102', 1.8),
    ('CD', '20100216', 0.9),
    ('EF', '20100216', 1.1),
    ('GH', '20100216', 1.7)

T-SQL:

SELECT Name, [Date], Par3, Rn
FROM (
    SELECT
        Name,
        [Date],
        Par3,
        ROW_NUMBER() OVER (PARTITION BY [Date] ORDER BY Par3 ASC) AS Rn,
        COUNT(*) OVER (PARTITION BY [Date]) As Cnt
    FROM #Table
    ) ranked
WHERE Cnt = 3

Output:

------------------------------
Name    Date        Par3    Rn
------------------------------
CD      2010-02-16  0.9     1
EF      2010-02-16  1.1     2
GH      2010-02-16  1.7     3


问:
How to send data from Adapter to ViewModel to Fragment
My structure is like this, in the Fragment I call the ViewModel which instantiate the Adapter

For each item of my RecyclerView, I have a button which I listen

```<code>binding.addItem.setOnClickListener(onAddItemClicked(product))

private fun onAddToQuoteClicked(product: Product): View.OnClickListener {
    return View.OnClickListener {
        // TODO add item
    }
}
</code>```

I don't know how to send this item data to the fragment, is there a way to do that?

Should I use interface between Adapter and ViewModel and between ViewModel and Fragment ?

Or Can I use RxEvent & RxBus ?

答: You can directly add item through ViewModel reference and subscribe to RxJava EventBus or LiveData change in your Fragment or Activity</p>

Body:
My structure is like this, in the Fragment I call the ViewModel which instantiate the Adapter

For each item of my RecyclerView, I have a button which I listen

binding.addItem.setOnClickListener(onAddItemClicked(product))

private fun onAddToQuoteClicked(product: Product): View.OnClickListener {
    return View.OnClickListener {
        // TODO add item
    }
}

I don't know how to send this item data to the fragment, is there a way to do that?

Should I use interface between Adapter and ViewModel and between ViewModel and Fragment ?

Or Can I use RxEvent & RxBus ?


问:
Cannot turn off short_open_tag with ini_set
I'm embedding a javascript syntax highlighter to a PHP script that reads source file and echos it back. The js highlighter has this string on one line:

... [z,/^[^<?]+/], ...

The short_open_tag is on on this server and the <? in the string confuses the script and causes errors. I cannot turn off in php.ini or elsewhere.

I have used ini_set('short_open_tag', '0'); in the same script, but it does not take effect. What could be the problem?

Edit

In the end, I used what Col Shrapnel suggested in a comment:

I changed [z,/^[^<?]+/], to [z,/^[^<?php echo '<' .'?'; ?>]+/],

答:
I see no connection between your highlighter and turning short open tags off.

If some of your code gets confused with short tags, you have to rewrite your code manually, replacing short tags with long ones. Or at least run some code to do it.

But no configuration setting will do it for you.

Also, I see no way for JavaScript code to read PHP file source with all these whatever short or long tags.

It seems your problem is somewhere else.


问:
Why does typescript show an error for my Array.filter parameters
I am using Array.prototype.filter to return specific entries from within an object, however typescript is giving me an error that "Argument of type '(current: currentInterface) => boolean' is not assignable to parameter of type '(value: [string, {}], index: number, array: [string, {}][]) => any'.
  Types of parameters 'current' and 'value' are incompatible."

current is an object that contains entries that I want to filter.

How can I get this to work, and why does it not work currently?

It seems that it expects current to be a string, however in normal JS this is not required.

```<code>    interface currentInterface {
        firstName: string,
        lastName: string,
        [key: number]: any
    }

    //filter matching customers from list of customers by search term
    const matchingCustomers = Object.entries(state.customers).filter((current: currentInterface) => {
        let firstname = current[1].firstName.toLowerCase();
        let lastname = current[1].lastName.toLowerCase();
        let searchTerm = action.payload.searchTerm.toLowerCase();
        return firstname === searchTerm || lastname === searchTerm;
    });

Argument of type '(current: currentInterface) => boolean' is not assignable to parameter of type '(value: [string, {}], index: number, array: [string, {}][]) => any'.
  Types of parameters 'current' and 'value' are incompatible.
    Type '[string, {}]' is missing the following properties from type 'currentInterface': firstName, lastNamets(2345)
</code>```

答:
Because Object.entries returns an array of arrays, you are assigning a single interface though.

From your code, it seems like you where looking for Object.values instead

Body:
I am using Array.prototype.filter to return specific entries from within an object, however typescript is giving me an error that "Argument of type '(current: currentInterface) => boolean' is not assignable to parameter of type '(value: [string, {}], index: number, array: [string, {}][]) => any'.
  Types of parameters 'current' and 'value' are incompatible."

current is an object that contains entries that I want to filter.

How can I get this to work, and why does it not work currently?

It seems that it expects current to be a string, however in normal JS this is not required.

    interface currentInterface {
        firstName: string,
        lastName: string,
        [key: number]: any
    }

    //filter matching customers from list of customers by search term
    const matchingCustomers = Object.entries(state.customers).filter((current: currentInterface) => {
        let firstname = current[1].firstName.toLowerCase();
        let lastname = current[1].lastName.toLowerCase();
        let searchTerm = action.payload.searchTerm.toLowerCase();
        return firstname === searchTerm || lastname === searchTerm;
    });

Argument of type '(current: currentInterface) => boolean' is not assignable to parameter of type '(value: [string, {}], index: number, array: [string, {}][]) => any'.
  Types of parameters 'current' and 'value' are incompatible.
    Type '[string, {}]' is missing the following properties from type 'currentInterface': firstName, lastNamets(2345)


问:
Axon MongoDB - message='E11000 duplicate key error collection uniqueAggregateIndex dup key: { : "101", : 0 }
In my application, we are using axon 3.3.3 and mongo db as event store

we have situation to save all events whenever user updated his profile information.

below is use case

user has created his profile (aggregate id : 101)
In mongodb(CreateEvent) has been saved with 101 aggregate id.

user has updated his profile info,
so we would like to store UpdateEvent in mongo db(event store)

But getting below exception

13:52:49.643 [http-nio-7030-exec-3] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.axonframework.commandhandling.model.ConcurrencyException: An event for aggregate [101] at sequence [0] was already inserted] with root cause
com.mongodb.MongoBulkWriteException: Bulk write operation error on server 127.0.0.1:27017. Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection: mytest.domainevents index: uniqueAggregateIndex dup key: { : "101", : 0 }', details={ }}].
    at com.mongodb.connection.BulkWriteBatchCombiner.getError(BulkWriteBatchCombiner.java:176)
    at com.mongodb.connection.BulkWriteBatchCombiner.throwOnError(BulkWriteBatchCombiner.java:205)
    at com.mongodb.connection.BulkWriteBatchCombiner.getResult(BulkWriteBatchCombiner.java:146)
    at com.mongodb.operation.BulkWriteBatch.getResult(BulkWriteBatch.java:227)
    at com.mongodb.operation.MixedBulkWriteOperation.executeBulkWriteBatch(MixedBulkWriteOperation.java:276)

so how can i save the updated event ?

Below is the uniqueAggregateIndex in mongo db

{
    "aggregateIdentifier" : 1,
    "sequenceNumber" : 1
}

```<code>@Value("${mongo.host:127.0.0.1}")
private String mongoHost;

@Value("${mongo.port:27017}")
private int mongoPort;

@Value("${mongo.db:mytest}")
private String mongoDB;

@Bean
public MongoSagaStore sagaStore() {
    return new MongoSagaStore(axonMongoTemplate());
}

@Bean
public TokenStore tokenStore(Serializer serializer) {
    return new MongoTokenStore(axonMongoTemplate(), serializer);
}

@Bean
public EventStorageEngine eventStorageEngine(Serializer serializer) {
    return new MongoEventStorageEngine(serializer, null, axonMongoTemplate(), new DocumentPerEventStorageStrategy());
}

@Bean
public MongoTemplate axonMongoTemplate() {
    return new DefaultMongoTemplate(mongo(), mongoDB);
}

@Bean
public MongoClient mongo() {
    MongoFactory mongoFactory = new MongoFactory();
    mongoFactory.setMongoAddresses(Collections.singletonList(new ServerAddress(mongoHost, mongoPort)));
    return mongoFactory.createMongo();
}
</code>```

答:
Axon uses that index to guarantee that there are no concurrent actions on Aggregates. After all, an Aggregate is a consistency boundary, and all state changes on it should be atomic and highly consistent.

Changing the index to be non-unique is a bad idea. It would only allow for insertion of events that conflict with other events already in the events store.

Given that the problem seems to be at sequence #0, it may be that you accidentally modelled your @CommandHandler method as a constructor. Axon treats these command handlers specially, by creating a new instance, rather than attempt to load an existing one. In your case, an aggregate already exists, as some events were already stored.

Body:
In my application, we are using axon 3.3.3 and mongo db as event store

we have situation to save all events whenever user updated his profile information.

below is use case

user has created his profile (aggregate id : 101)
In mongodb(CreateEvent) has been saved with 101 aggregate id.

user has updated his profile info,
so we would like to store UpdateEvent in mongo db(event store)

But getting below exception

13:52:49.643 [http-nio-7030-exec-3] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.axonframework.commandhandling.model.ConcurrencyException: An event for aggregate [101] at sequence [0] was already inserted] with root cause
com.mongodb.MongoBulkWriteException: Bulk write operation error on server 127.0.0.1:27017. Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection: mytest.domainevents index: uniqueAggregateIndex dup key: { : "101", : 0 }', details={ }}].
    at com.mongodb.connection.BulkWriteBatchCombiner.getError(BulkWriteBatchCombiner.java:176)
    at com.mongodb.connection.BulkWriteBatchCombiner.throwOnError(BulkWriteBatchCombiner.java:205)
    at com.mongodb.connection.BulkWriteBatchCombiner.getResult(BulkWriteBatchCombiner.java:146)
    at com.mongodb.operation.BulkWriteBatch.getResult(BulkWriteBatch.java:227)
    at com.mongodb.operation.MixedBulkWriteOperation.executeBulkWriteBatch(MixedBulkWriteOperation.java:276)

so how can i save the updated event ?

Below is the uniqueAggregateIndex in mongo db

{
    "aggregateIdentifier" : 1,
    "sequenceNumber" : 1
}

@Value("${mongo.host:127.0.0.1}")
private String mongoHost;

@Value("${mongo.port:27017}")
private int mongoPort;

@Value("${mongo.db:mytest}")
private String mongoDB;

@Bean
public MongoSagaStore sagaStore() {
    return new MongoSagaStore(axonMongoTemplate());
}

@Bean
public TokenStore tokenStore(Serializer serializer) {
    return new MongoTokenStore(axonMongoTemplate(), serializer);
}

@Bean
public EventStorageEngine eventStorageEngine(Serializer serializer) {
    return new MongoEventStorageEngine(serializer, null, axonMongoTemplate(), new DocumentPerEventStorageStrategy());
}

@Bean
public MongoTemplate axonMongoTemplate() {
    return new DefaultMongoTemplate(mongo(), mongoDB);
}

@Bean
public MongoClient mongo() {
    MongoFactory mongoFactory = new MongoFactory();
    mongoFactory.setMongoAddresses(Collections.singletonList(new ServerAddress(mongoHost, mongoPort)));
    return mongoFactory.createMongo();
}


问:
is there an explicit interface declaration for abstract methods?
i have a (quite easy) problem and it seems I can't find out how to do it. I would appreciate some help.

I have two classes which are something like this:

```<code>public class FileParameters { ... }

public abstract class File {
    ...
    public abstract FileParameters Params { get; }
}
</code>```

From both classes I have a derived special version:

```<code>public class SpecialFileParameters { ... }

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    public override FileParameters Params { get { return params; } }
}
</code>```

When I want to use the SpecialFileParameters I have to cast them first, e.g:

```<code>((SpecialFileParameters)SpecialFileObject.Parameters).DoSomething();
</code>```

which is quite obnoxious. What I would like to have is basically the same syntax as with interfaces

```<code>public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    private override FileParameters File.Params { get { return params; } }
    public new SpecialFileParameters Params { get { return params; } }
}
</code>```

But like this i get an compiler error: 'File' in explicit interface declaration is not an interface. Is there some other way to do this?

Some further information:

I cannot change the base classes, only my special classes

I actually need 2 special derived classes, one is written in C#, the other in C++/CLI. If the "trick" to makes it work is different between C# and C++ CLI please let me know.

Thanks for your help (and patience I guess ^^),

答:
You can use generics to solve this:

```<code>    public class FileParameters   {    }

    public class SpecialFileParameters : FileParameters{}

    public abstract class File<T>
        where T : FileParameters
    {
        private T _params;

        public T Params   { get { return _params;}        }
    }

    public class SpecialFileParams : FileParameters<SpecialFileParameters> { }
</code>```

and you will get the concrete "Special" when you access Params.

Body:
i have a (quite easy) problem and it seems I can't find out how to do it. I would appreciate some help.

I have two classes which are something like this:

public class FileParameters { ... }

public abstract class File {
    ...
    public abstract FileParameters Params { get; }
}

From both classes I have a derived special version:

public class SpecialFileParameters { ... }

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    public override FileParameters Params { get { return params; } }
}

When I want to use the SpecialFileParameters I have to cast them first, e.g:

((SpecialFileParameters)SpecialFileObject.Parameters).DoSomething();

which is quite obnoxious. What I would like to have is basically the same syntax as with interfaces

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    private override FileParameters File.Params { get { return params; } }
    public new SpecialFileParameters Params { get { return params; } }
}

But like this i get an compiler error: 'File' in explicit interface declaration is not an interface. Is there some other way to do this?

Some further information:

I cannot change the base classes, only my special classes

I actually need 2 special derived classes, one is written in C#, the other in C++/CLI. If the "trick" to makes it work is different between C# and C++ CLI please let me know.

Thanks for your help (and patience I guess ^^),

Body:
You can use generics to solve this:

    public class FileParameters   {    }

    public class SpecialFileParameters : FileParameters{}

    public abstract class File<T>
        where T : FileParameters
    {
        private T _params;

        public T Params   { get { return _params;}        }
    }

    public class SpecialFileParams : FileParameters<SpecialFileParameters> { }

and you will get the concrete "Special" when you access Params.


答:
```<code>WITH cte_ranked
AS
(
 SELECT Name, [Date], Par3
       ,COUNT(*) OVER (PARTITION BY [Date]) As DateCount
 FROM Table
 )

SELECT Name, [Date], Par3
FROM cte_ranked
WHERE DateCount = 3
ORDER BY [Date], Par3
</code>```

Title: Exact number of nested ranked data exact in SQL procedure