问:
Prepare(), Execute() working but FETCH_ASSOC not working
I am trying to create a simple login API which allows login to a database on entering matching email and password and throws the id of that row in result.

Note: 1) I am using var_dump at places only for test purpose.

2) discalimer: I am not using password encryption just for simplicity of understanding the flow.

3) I am using PDO but no framework.
Here is a part of the login.php code. 'user' is a class declared in user.php and table name is 'users' containing columns as id, email, password and username.

```<code>//prepare user object
$user= new user($db);

$user->email=isset($_GET['email'])?$_GET['email']:die();
$user->password=isset($_GET['password']) ? $_GET['password'] : die();

$stmt=$user->login();
var_dump($stmt);
if ($stmt->rowCount()>0) {
  $row=$stmt->fetch(PDO::FETCH_ASSOC);
  var_dump($row);
  $user_arr=array(
    "status" => true,
    "message" => "succesfully logged in",
    "id" => $row['id']
  );
} else {
  $user_arr=array(
    "status" => false,
    "message" => "login attempt failed due to invalid email or password"
  );
}
print_r(json_encode($user_arr));
</code>```

Below is the snippet of the login function from user.php

```<code> function login(){
 //select all query

 $query="SELECT
              'id','email','password','username'
          FROM ".$this->table_name."
           WHERE
              email='".$this->email."'
                AND password='".$this->password."'";

//prepare query statement
$stmt=$this->conn->prepare($query);
if ($stmt->execute()) {
  return $stmt;
} else {
  return null;
}
</code>```

The output is

object(PDOStatement)#4 (1) {
  ["queryString"]=>
  string(194) "SELECT
  'id','email','password','username'
  FROM users
  WHERE
  email='upasana@api.com'
  AND password='def456'"
  }
  array(4) {
  ["id"]=>
  string(2) "id"
  ["email"]=>
  string(5) "email"
  ["password"]=>
  string(8) "password"
  ["username"]=>
  string(8) "username"
  }
  {"status":true,"message":"succesfully logged in","id":"id"}

So, basically, FETCH_ASSOC is not working? Why is it treating the id as id and throwing as a string rather than finding the associated value?

答:
FETCH_ASSOC is working fine, the problem is in your sql, if you write the fields between single quotes you are getting strings and not the fields content.

Just write the fields without quotes:

```<code>$query = "SELECT id, email, password, username ...";
</code>```

And you should use prepared statements to prevent from SQL injection attacks.

Body:
I am trying to create a simple login API which allows login to a database on entering matching email and password and throws the id of that row in result.

Note: 1) I am using var_dump at places only for test purpose.

2) discalimer: I am not using password encryption just for simplicity of understanding the flow.

3) I am using PDO but no framework.
Here is a part of the login.php code. 'user' is a class declared in user.php and table name is 'users' containing columns as id, email, password and username.

//prepare user object
$user= new user($db);

$user->email=isset($_GET['email'])?$_GET['email']:die();
$user->password=isset($_GET['password']) ? $_GET['password'] : die();

$stmt=$user->login();
var_dump($stmt);
if ($stmt->rowCount()>0) {
  $row=$stmt->fetch(PDO::FETCH_ASSOC);
  var_dump($row);
  $user_arr=array(
    "status" => true,
    "message" => "succesfully logged in",
    "id" => $row['id']
  );
} else {
  $user_arr=array(
    "status" => false,
    "message" => "login attempt failed due to invalid email or password"
  );
}
print_r(json_encode($user_arr));

Below is the snippet of the login function from user.php

 function login(){
 //select all query

 $query="SELECT
              'id','email','password','username'
          FROM ".$this->table_name."
           WHERE
              email='".$this->email."'
                AND password='".$this->password."'";

//prepare query statement
$stmt=$this->conn->prepare($query);
if ($stmt->execute()) {
  return $stmt;
} else {
  return null;
}

The output is

object(PDOStatement)#4 (1) {
  ["queryString"]=>
  string(194) "SELECT
  'id','email','password','username'
  FROM users
  WHERE
  email='upasana@api.com'
  AND password='def456'"
  }
  array(4) {
  ["id"]=>
  string(2) "id"
  ["email"]=>
  string(5) "email"
  ["password"]=>
  string(8) "password"
  ["username"]=>
  string(8) "username"
  }
  {"status":true,"message":"succesfully logged in","id":"id"}

So, basically, FETCH_ASSOC is not working? Why is it treating the id as id and throwing as a string rather than finding the associated value?

Body:
FETCH_ASSOC is working fine, the problem is in your sql, if you write the fields between single quotes you are getting strings and not the fields content.

Just write the fields without quotes:

$query = "SELECT id, email, password, username ...";

And you should use prepared statements to prevent from SQL injection attacks.


来源: stackexchange

问:
Making join condition more exclusive causes query to hang
Sorry for the wall of SQL, but I am having some problems with the query below. It seems to never finish executing (it runs for a few minutes, then I kill it). The weird thing is that if I change the join condition for the StudentTestsPre table from TestInstances.fkSchoolYearID = (TestInstancesPre.fkSchoolYearID + 1) to TestInstances.fkSchoolYearID > TestInstancesPre.fkSchoolYearID, then the query returns instantly. How could using a more exclusive join condition cause my query to hang? Seems like that should make the query faster, if anything.

Any ideas?

```<code>            SELECT *
        FROM TestInstances
        INNER JOIN StudentTests on StudentTests.fkTestInstanceID = TestInstances.pkTestInstanceID
                                    AND StudentTests.pkStudentTestID IN (SELECT * FROM @tempTests)
        INNER JOIN TestInstances TestInstancesPre ON TestInstances.fkSchoolYearID = (TestInstancesPre.fkSchoolYearID + 1)
                                        AND TestInstancesPre.fkTestTypeID = 1 AND TestInstances.fkTestTypeID = 1
        INNER JOIN StudentTests StudentTestsPre on StudentTestsPre.fkTestInstanceID = TestInstancesPre.pkTestInstanceID
                                        AND StudentTests.fkStudentID = StudentTestsPre.fkStudentID
        INNER JOIN StudentScores_Subject s ON s.fkStudentTestID = StudentTests.pkStudentTestID
                                        AND s.fkTest_SubjectID IN (SELECT pkTestSubjectID FROM MM_Test_Subjects WHERE fkCSTStrandID IN (SELECT number FROM itot(@strAcceptableStrands, N','))  AND fkTestTypeID = 1)
                                        AND s.fkScoreTypeID = 3
        INNER JOIN StudentScores_Subject sPre ON sPre.fkStudentTestID = StudentTestsPre.pkStudentTestID
                                        AND sPre.fkTest_SubjectID IN (SELECT pkTestSubjectID FROM MM_Test_Subjects WHERE fkCSTStrandID IN (SELECT number FROM itot(@strAcceptableStrands, N','))  AND fkTestTypeID = 1)
                                        AND sPre.fkScoreTypeID = 3
        INNER JOIN MM_Test_PL_SS_Ranges r ON r.fkTest_SubjectID = s.fkTest_SubjectID
                                        AND r.fkSchoolYearID = TestInstances.fkSchoolYearID
                                        AND r.fkTestTypeID = TestInstances.fkTestTypeID
                                        AND (r.fkGradeID = StudentTests.fkGradeID OR r.fkGradeID = 99)
        INNER JOIN MM_Test_PL_SS_Ranges rPre ON rPre.fkTest_SubjectID = sPre.fkTest_SubjectID
                                        AND rPre.fkSchoolYearID = TestInstancesPre.fkSchoolYearID
                                        AND rPre.fkTestTypeID = TestInstancesPre.fkTestTypeID
                                        AND (rPre.fkGradeID = StudentTestsPre.fkGradeID OR rPre.fkGradeID = 99)
        INNER JOIN StudentScores_Subject s2 ON s2.fkStudentTestID = StudentTests.pkStudentTestID
                                        AND s2.fkTest_SubjectID = s.fkTest_SubjectID
                                        AND s2.fkScoreTypeID = 2
        INNER JOIN StudentScores_Subject sPre2 ON sPre2.fkStudentTestID = StudentTestsPre.pkStudentTestID
                                        AND sPre2.fkTest_SubjectID = sPre.fkTest_SubjectID
                                        AND sPre2.fkScoreTypeID = 2
        INNER JOIN Students on Students.pkStudentID = StudentTests.fkStudentID
</code>```

thanks for the help!

For SO, here's the above script with alternative formatting & short aliases:

```<code>SELECT *
FROM TestInstances

  INNER JOIN StudentTests st
     ON st.fkTestInstanceID = ti.pkTestInstanceID
    AND st.pkStudentTestID IN (SELECT * FROM @tempTests)

  INNER JOIN TestInstances tiPre
     ON ti.fkSchoolYearID = (tiPre.fkSchoolYearID + 1)
    AND tiPre.fkTestTypeID = 1 AND ti.fkTestTypeID = 1

  INNER JOIN StudentTests stPre
     ON stPre.fkTestInstanceID = tiPre.pkTestInstanceID
    AND st.fkStudentID = stPre.fkStudentID

  INNER JOIN StudentScores_Subject s
     ON s.fkStudentTestID = st.pkStudentTestID
    AND s.fkTest_SubjectID IN (
          SELECT pkTestSubjectID
          FROM MM_Test_Subjects
          WHERE fkCSTStrandID IN (
                  SELECT number FROM itot(@strAcceptableStrands, N','))
            AND fkTestTypeID = 1)
    AND s.fkScoreTypeID = 3

  INNER JOIN StudentScores_Subject sPre
     ON sPre.fkStudentTestID = stPre.pkStudentTestID
    AND sPre.fkTest_SubjectID IN (
          SELECT pkTestSubjectID
          FROM MM_Test_Subjects
          WHERE fkCSTStrandID IN (
                  SELECT number FROM itot(@strAcceptableStrands, N','))
            AND fkTestTypeID = 1)
    AND sPre.fkScoreTypeID = 3

  INNER JOIN MM_Test_PL_SS_Ranges r
     ON r.fkTest_SubjectID = s.fkTest_SubjectID
    AND r.fkSchoolYearID = ti.fkSchoolYearID
    AND r.fkTestTypeID = ti.fkTestTypeID
    AND (r.fkGradeID = st.fkGradeID OR r.fkGradeID = 99)

  INNER JOIN MM_Test_PL_SS_Ranges rPre
     ON rPre.fkTest_SubjectID = sPre.fkTest_SubjectID
    AND rPre.fkSchoolYearID = tiPre.fkSchoolYearID
    AND rPre.fkTestTypeID = tiPre.fkTestTypeID
    AND (rPre.fkGradeID = stPre.fkGradeID OR rPre.fkGradeID = 99)

  INNER JOIN StudentScores_Subject s2
     ON s2.fkStudentTestID = st.pkStudentTestID
    AND s2.fkTest_SubjectID = s.fkTest_SubjectID
    AND s2.fkScoreTypeID = 2

  INNER JOIN StudentScores_Subject sPre2
     ON sPre2.fkStudentTestID = stPre.pkStudentTestID
    AND sPre2.fkTest_SubjectID = sPre.fkTest_SubjectID
    AND sPre2.fkScoreTypeID = 2

  INNER JOIN Students
     ON Students.pkStudentID = st.fkStudentID
</code>```

答:
By having a calculation in your comparison, it can invalidate the use of an index. This usually happens when the datatype of the calculation result is different from the datatype of the column being indexed. Sometimes the cost of calculation is large if it has to be repeated enough times (eg from lots of joins). One solution is to store the calculated value in a special column, eg:

```<code>CREATE TABLE TestInstances (
...
nextSchoolYearID int);
</code>```

And use a trigger or logic to maintain nextSchoolYearID = fkSchoolYearID + 1, then use

```<code>ON TestInstances.fkSchoolYearID = TestInstancesPre.nextSchoolYearID)
</code>```

Also, you have AND StudentTests.pkStudentTestID IN (SELECT * FROM @tempTests) in the first join's on clause, but the values in @tempTests are not related to either table.

Try moving that predicate to a where clause at the end, ie:

```<code>SELECT
     ...
WHERE StudentTests.pkStudentTestID IN (SELECT * FROM @tempTests)
</code>```

Doing this means SELECT * FROM @tempTests will only get executed once, instead of being executed for every row combination of TestInstances and StudentTests.

ContentLicense: CC BY-SA 3.0

Body:
Sorry for the wall of SQL, but I am having some problems with the query below. It seems to never finish executing (it runs for a few minutes, then I kill it). The weird thing is that if I change the join condition for the StudentTestsPre table from TestInstances.fkSchoolYearID = (TestInstancesPre.fkSchoolYearID + 1) to TestInstances.fkSchoolYearID > TestInstancesPre.fkSchoolYearID, then the query returns instantly. How could using a more exclusive join condition cause my query to hang? Seems like that should make the query faster, if anything.

Any ideas?

            SELECT *
        FROM TestInstances
        INNER JOIN StudentTests on StudentTests.fkTestInstanceID = TestInstances.pkTestInstanceID
                                    AND StudentTests.pkStudentTestID IN (SELECT * FROM @tempTests)
        INNER JOIN TestInstances TestInstancesPre ON TestInstances.fkSchoolYearID = (TestInstancesPre.fkSchoolYearID + 1)
                                        AND TestInstancesPre.fkTestTypeID = 1 AND TestInstances.fkTestTypeID = 1
        INNER JOIN StudentTests StudentTestsPre on StudentTestsPre.fkTestInstanceID = TestInstancesPre.pkTestInstanceID
                                        AND StudentTests.fkStudentID = StudentTestsPre.fkStudentID
        INNER JOIN StudentScores_Subject s ON s.fkStudentTestID = StudentTests.pkStudentTestID
                                        AND s.fkTest_SubjectID IN (SELECT pkTestSubjectID FROM MM_Test_Subjects WHERE fkCSTStrandID IN (SELECT number FROM itot(@strAcceptableStrands, N','))  AND fkTestTypeID = 1)
                                        AND s.fkScoreTypeID = 3
        INNER JOIN StudentScores_Subject sPre ON sPre.fkStudentTestID = StudentTestsPre.pkStudentTestID
                                        AND sPre.fkTest_SubjectID IN (SELECT pkTestSubjectID FROM MM_Test_Subjects WHERE fkCSTStrandID IN (SELECT number FROM itot(@strAcceptableStrands, N','))  AND fkTestTypeID = 1)
                                        AND sPre.fkScoreTypeID = 3
        INNER JOIN MM_Test_PL_SS_Ranges r ON r.fkTest_SubjectID = s.fkTest_SubjectID
                                        AND r.fkSchoolYearID = TestInstances.fkSchoolYearID
                                        AND r.fkTestTypeID = TestInstances.fkTestTypeID
                                        AND (r.fkGradeID = StudentTests.fkGradeID OR r.fkGradeID = 99)
        INNER JOIN MM_Test_PL_SS_Ranges rPre ON rPre.fkTest_SubjectID = sPre.fkTest_SubjectID
                                        AND rPre.fkSchoolYearID = TestInstancesPre.fkSchoolYearID
                                        AND rPre.fkTestTypeID = TestInstancesPre.fkTestTypeID
                                        AND (rPre.fkGradeID = StudentTestsPre.fkGradeID OR rPre.fkGradeID = 99)
        INNER JOIN StudentScores_Subject s2 ON s2.fkStudentTestID = StudentTests.pkStudentTestID
                                        AND s2.fkTest_SubjectID = s.fkTest_SubjectID
                                        AND s2.fkScoreTypeID = 2
        INNER JOIN StudentScores_Subject sPre2 ON sPre2.fkStudentTestID = StudentTestsPre.pkStudentTestID
                                        AND sPre2.fkTest_SubjectID = sPre.fkTest_SubjectID
                                        AND sPre2.fkScoreTypeID = 2
        INNER JOIN Students on Students.pkStudentID = StudentTests.fkStudentID

thanks for the help!

For SO, here's the above script with alternative formatting & short aliases:

SELECT *
FROM TestInstances

  INNER JOIN StudentTests st
     ON st.fkTestInstanceID = ti.pkTestInstanceID
    AND st.pkStudentTestID IN (SELECT * FROM @tempTests)

  INNER JOIN TestInstances tiPre
     ON ti.fkSchoolYearID = (tiPre.fkSchoolYearID + 1)
    AND tiPre.fkTestTypeID = 1 AND ti.fkTestTypeID = 1

  INNER JOIN StudentTests stPre
     ON stPre.fkTestInstanceID = tiPre.pkTestInstanceID
    AND st.fkStudentID = stPre.fkStudentID

  INNER JOIN StudentScores_Subject s
     ON s.fkStudentTestID = st.pkStudentTestID
    AND s.fkTest_SubjectID IN (
          SELECT pkTestSubjectID
          FROM MM_Test_Subjects
          WHERE fkCSTStrandID IN (
                  SELECT number FROM itot(@strAcceptableStrands, N','))
            AND fkTestTypeID = 1)
    AND s.fkScoreTypeID = 3

  INNER JOIN StudentScores_Subject sPre
     ON sPre.fkStudentTestID = stPre.pkStudentTestID
    AND sPre.fkTest_SubjectID IN (
          SELECT pkTestSubjectID
          FROM MM_Test_Subjects
          WHERE fkCSTStrandID IN (
                  SELECT number FROM itot(@strAcceptableStrands, N','))
            AND fkTestTypeID = 1)
    AND sPre.fkScoreTypeID = 3

  INNER JOIN MM_Test_PL_SS_Ranges r
     ON r.fkTest_SubjectID = s.fkTest_SubjectID
    AND r.fkSchoolYearID = ti.fkSchoolYearID
    AND r.fkTestTypeID = ti.fkTestTypeID
    AND (r.fkGradeID = st.fkGradeID OR r.fkGradeID = 99)

  INNER JOIN MM_Test_PL_SS_Ranges rPre
     ON rPre.fkTest_SubjectID = sPre.fkTest_SubjectID
    AND rPre.fkSchoolYearID = tiPre.fkSchoolYearID
    AND rPre.fkTestTypeID = tiPre.fkTestTypeID
    AND (rPre.fkGradeID = stPre.fkGradeID OR rPre.fkGradeID = 99)

  INNER JOIN StudentScores_Subject s2
     ON s2.fkStudentTestID = st.pkStudentTestID
    AND s2.fkTest_SubjectID = s.fkTest_SubjectID
    AND s2.fkScoreTypeID = 2

  INNER JOIN StudentScores_Subject sPre2
     ON sPre2.fkStudentTestID = stPre.pkStudentTestID
    AND sPre2.fkTest_SubjectID = sPre.fkTest_SubjectID
    AND sPre2.fkScoreTypeID = 2

  INNER JOIN Students
     ON Students.pkStudentID = st.fkStudentID

Body:
By having a calculation in your comparison, it can invalidate the use of an index. This usually happens when the datatype of the calculation result is different from the datatype of the column being indexed. Sometimes the cost of calculation is large if it has to be repeated enough times (eg from lots of joins). One solution is to store the calculated value in a special column, eg:

CREATE TABLE TestInstances (
...
nextSchoolYearID int);

And use a trigger or logic to maintain nextSchoolYearID = fkSchoolYearID + 1, then use

ON TestInstances.fkSchoolYearID = TestInstancesPre.nextSchoolYearID)

Also, you have AND StudentTests.pkStudentTestID IN (SELECT * FROM @tempTests) in the first join's on clause, but the values in @tempTests are not related to either table.

Try moving that predicate to a where clause at the end, ie:

SELECT
     ...
WHERE StudentTests.pkStudentTestID IN (SELECT * FROM @tempTests)

Doing this means SELECT * FROM @tempTests will only get executed once, instead of being executed for every row combination of TestInstances and StudentTests.


问:
How do i make something random in a function?
I have a function with some images in it here:

```<code>function rain() {
    ctx.drawImage (image1, x, y, 100, 50);
    ctx.drawImage (image2, x, y, 100, 50);
    ctx.drawImage (image3, x, y, 100, 50);
    ctx.drawImage (image4, x, y, 100, 50);
}
</code>```

How do I make this function randomly choose one of these images when I call it?

答:
You should put your images in an array, then pick a random index of the array.

function randomImage() {
  const images = [
    image1,
    image2,
    image3,
    image4,
  ];
  // Pick an index at random from the images array. Math.rand returns
  // a random number between 0 and 1, multiplying that by the length
  // of the images array, gets a number between 0 and the length of the
  // array, and flooring it makes it into an integer.
  const randomIndex = Math.floor(Math.rand() * images.length);
  return images[randomIndex];
}
```

ContentLicense: CC BY-SA 4.0

Body:
I have a function with some images in it here:

function rain() {
    ctx.drawImage (image1, x, y, 100, 50);
    ctx.drawImage (image2, x, y, 100, 50);
    ctx.drawImage (image3, x, y, 100, 50);
    ctx.drawImage (image4, x, y, 100, 50);
}

How do I make this function randomly choose one of these images when I call it?


问:
How I can solve AttributeError: 'dict' object has no attribute 'nemitx' error and Keyerror?
How I can solve

AttributeError: 'dict' object has no attribute 'nemitx' error and Keyerror?

```<code>class TwissGaussBeam(GaussBeam):
    '''__init__(self, twiss, N=1000, pos=np.array([0, 0, 0, 0, 0, 1]),
    Q=1e-9, chargesign=-1, restmass=ele_mass)
    Create a multi-particle beam with a Gaussian spread in each of the
    6 dimensions.  The statistics of the beam distribution are calculated
    from the Twiss parameters in twiss.'''

def __init__(self, twiss, N=100000, pos=np.array([0, 0, 0, 0, 0, 1]),
    Q=1e-12, chargesign=-1, restmass=ele_mass):
    P = pos[5]
    gammasquared = ( (P*1e6)**2 + restmass**2 ) / restmass**2
    betagamma = np.sqrt(gammasquared - 1)
    sig = np.zeros(6)
    sig[0] = np.sqrt((twiss.nemitx/betagamma) * twiss.betax)
    sig[1] = np.sqrt((twiss.nemitx/betagamma) / twiss.betax)
    sig[2] = np.sqrt((twiss.nemity/betagamma) * twiss.betay)
    sig[3] = np.sqrt((twiss.nemity/betagamma) / twiss.betay)
    sig[4] = twiss.sigz
    sig[5] = twiss.sigP
</code>```

答:
I am posting this since the user confirmed via right answer that he wanted to access  the key 'nemitx' of his dictionary 'twiss'.

The error has occurred because probably you were trying to access your dictionary key with an expression like twiss.nemitx, instead of the right one twiss['nemitx'].

Actually twiss.nemitx in Python would indicate that you are trying to access the attribute nemitx of the object twiss, and that would explain why you are getting an AttributeError:

If this attribute is not available, the exception AttributeError is
  raised.

Body:
How I can solve

AttributeError: 'dict' object has no attribute 'nemitx' error and Keyerror?

class TwissGaussBeam(GaussBeam):
    '''__init__(self, twiss, N=1000, pos=np.array([0, 0, 0, 0, 0, 1]),
    Q=1e-9, chargesign=-1, restmass=ele_mass)
    Create a multi-particle beam with a Gaussian spread in each of the
    6 dimensions.  The statistics of the beam distribution are calculated
    from the Twiss parameters in twiss.'''

def __init__(self, twiss, N=100000, pos=np.array([0, 0, 0, 0, 0, 1]),
    Q=1e-12, chargesign=-1, restmass=ele_mass):
    P = pos[5]
    gammasquared = ( (P*1e6)**2 + restmass**2 ) / restmass**2
    betagamma = np.sqrt(gammasquared - 1)
    sig = np.zeros(6)
    sig[0] = np.sqrt((twiss.nemitx/betagamma) * twiss.betax)
    sig[1] = np.sqrt((twiss.nemitx/betagamma) / twiss.betax)
    sig[2] = np.sqrt((twiss.nemity/betagamma) * twiss.betay)
    sig[3] = np.sqrt((twiss.nemity/betagamma) / twiss.betay)
    sig[4] = twiss.sigz
    sig[5] = twiss.sigP


问:
C++: Stroustrup iterator_traits example not compiling?
I'm trying to compile the code from Stroustrups C++ 4th Ed Page 124 and 125, section Iterator Traits.  Unfortunately, the compilation results in numerous errors which look like they are in the template system.  Does anyone know whats wrong with this code?

Thanks

```<code>#include <iostream>
#include <iterator>
#include <algorithm>
#include <forward_list>
#include <vector>
using namespace std;

template<typename Ran>
void sort_helper(Ran beg, Ran end, random_access_iterator_tag)
{
    sort(beg, end);
}

template<typename For>
void sort_helper(For beg, For end, forward_iterator_tag)
{
    vector<decltype(*beg)> v {beg, end};
    sort(v.begin(), v.end());
    copy(v.begin(), v.end(), beg);
}

template<typename C>
using Iterator_type = typename C::iterator;

template<typename Iter>
using Iterator_category = typename std::iterator_traits<Iter>::iterator_category;

template<typename C> void sort(C& c)
{
    using Iter = Iterator_type<C>; // ex. vector<int>::iterator
    sort_helper(c.begin(), c.end(), Iterator_category<Iter>{});
}

int main(int argc, char *argv[])
{
    forward_list<int> fl = {2, 1, 0};
    vector<int> v = {2, 1, 0};

    sort(fl); // this line causes compilation error
    sort(v);

    return 0;
}
</code>```

Errors:

```<code>In file included from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/x86_64-linux-gnu/bits/c++allocator.h:33,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:46,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/string:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/locale_classes.h:40,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/ios_base.h:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ios:42,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ostream:38,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/iostream:39,
                 from <source>:1:
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h: In instantiation of 'class __gnu_cxx::new_allocator<int&>':
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:116:11:   required from 'class std::allocator<int&>'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:87:21:   required from 'struct std::_Vector_base<int&, std::allocator<int&> >'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:389:11:   required from 'class std::vector<int&, std::allocator<int&> >'
<source>:17:28:   required from 'void sort_helper(For, For, std::forward_iterator_tag) [with For = std::_Fwd_list_iterator<int>]'
<source>:31:16:   required from 'void sort(C&) [with C = std::forward_list<int>]'
<source>:39:12:   required from here
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h:62:26: error: forming pointer to reference type 'int&'
   62 |       typedef _Tp*       pointer;
      |                          ^~~~~~~
... and more ...
</code>```

答:
You need to instantiate a vector<int>, but doing

```<code>std::vector<decltype(*beg)>
</code>```

gives a std::vector<int&>.

Instead you should use the value_type of the iterator:

```<code>std::vector<typename For::value_type> v {beg, end};
</code>```

Here's a demo.

Body:
I'm trying to compile the code from Stroustrups C++ 4th Ed Page 124 and 125, section Iterator Traits.  Unfortunately, the compilation results in numerous errors which look like they are in the template system.  Does anyone know whats wrong with this code?

Thanks

#include <iostream>
#include <iterator>
#include <algorithm>
#include <forward_list>
#include <vector>
using namespace std;

template<typename Ran>
void sort_helper(Ran beg, Ran end, random_access_iterator_tag)
{
    sort(beg, end);
}

template<typename For>
void sort_helper(For beg, For end, forward_iterator_tag)
{
    vector<decltype(*beg)> v {beg, end};
    sort(v.begin(), v.end());
    copy(v.begin(), v.end(), beg);
}

template<typename C>
using Iterator_type = typename C::iterator;

template<typename Iter>
using Iterator_category = typename std::iterator_traits<Iter>::iterator_category;

template<typename C> void sort(C& c)
{
    using Iter = Iterator_type<C>; // ex. vector<int>::iterator
    sort_helper(c.begin(), c.end(), Iterator_category<Iter>{});
}

int main(int argc, char *argv[])
{
    forward_list<int> fl = {2, 1, 0};
    vector<int> v = {2, 1, 0};

    sort(fl); // this line causes compilation error
    sort(v);

    return 0;
}

Errors:

In file included from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/x86_64-linux-gnu/bits/c++allocator.h:33,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:46,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/string:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/locale_classes.h:40,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/ios_base.h:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ios:42,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ostream:38,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/iostream:39,
                 from <source>:1:
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h: In instantiation of 'class __gnu_cxx::new_allocator<int&>':
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:116:11:   required from 'class std::allocator<int&>'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:87:21:   required from 'struct std::_Vector_base<int&, std::allocator<int&> >'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:389:11:   required from 'class std::vector<int&, std::allocator<int&> >'
<source>:17:28:   required from 'void sort_helper(For, For, std::forward_iterator_tag) [with For = std::_Fwd_list_iterator<int>]'
<source>:31:16:   required from 'void sort(C&) [with C = std::forward_list<int>]'
<source>:39:12:   required from here
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h:62:26: error: forming pointer to reference type 'int&'
   62 |       typedef _Tp*       pointer;
      |                          ^~~~~~~
... and more ...

Body:
You need to instantiate a vector<int>, but doing

std::vector<decltype(*beg)>

gives a std::vector<int&>.

Instead you should use the value_type of the iterator:

std::vector<typename For::value_type> v {beg, end};

Here's a demo.


问:
How to use X509Certificate2 as the credentials for a SharePointService request
I have a MOSS 2007 farm that requires a client certificate to access. I have written several methods that use the built in SharePoint services to retrieve data from the site. However, outside of my local test environment everything requires a client cert to access the services.

My method for retrieving the cert is:

```<code>private static X509Certificate2 GetCertCreds()
{
     X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
     try
     {
         store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, "SiteIdentityCertificateSerialNumber", true);

         Assert.IsNotNull(certs);

         return certs[0];
     }
     finally
     {
          store.Close();
     }
}
</code>```

Then in use I have to have something LIKE:

```<code>using (ListsServiceProxy.Lists service = new ListsServiceProxy.Lists())
{
    service.Crendentials = GetCredentials();
    XmlNode idResultsNode = service.GetListItems(documentLibraryName, null, queryNode, viewNode, "1", optionNode, null);
}
</code>```

This is not compiling because of the type mismatch. Am I going about this the wrong way? If not is there a way to use the certificate as the services credentials? I think in end what I'm trying to do is convert an X509Certificate2 to ICredentials. Any help or advice would be greatly appreciated.

答:
It turns out I had it all wrong. To correctly do this I replaced:

service.Credentials = GetCertCreds()

with

service.ClientCertificates.Add(GetCretCreds());

Adding the certificate into the service's client certificates collection is all that needed to happen.

Body:
I have a MOSS 2007 farm that requires a client certificate to access. I have written several methods that use the built in SharePoint services to retrieve data from the site. However, outside of my local test environment everything requires a client cert to access the services.

My method for retrieving the cert is:

private static X509Certificate2 GetCertCreds()
{
     X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
     try
     {
         store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, "SiteIdentityCertificateSerialNumber", true);

         Assert.IsNotNull(certs);

         return certs[0];
     }
     finally
     {
          store.Close();
     }
}

Then in use I have to have something LIKE:

using (ListsServiceProxy.Lists service = new ListsServiceProxy.Lists())
{
    service.Crendentials = GetCredentials();
    XmlNode idResultsNode = service.GetListItems(documentLibraryName, null, queryNode, viewNode, "1", optionNode, null);
}

This is not compiling because of the type mismatch. Am I going about this the wrong way? If not is there a way to use the certificate as the services credentials? I think in end what I'm trying to do is convert an X509Certificate2 to ICredentials. Any help or advice would be greatly appreciated.


问:
Swift, CoreData, FetchRequest, 2 Entities, ManyToMany, with GroupBy, Having Count and Sort, How?
I have a hard time with CoreData requests. Using some SQL derivate I'd get along. But here I need some help.

I have two entities with manyToMany relationships. It looks like this:

Repeatable (name: String, type: Int16, entries: [Entry])
Entry      (id: UUID, createdAt: Date, repeatables: [Repeatable])
```

<p>I want to get a list of repeatables belonging to more than 1 entry, ordered by the count of associations</p>

<p>In SQL it would look like this:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT rep.Z_PK, COUNT(rep.Z_PK) as count FROM ZREPEATABLE AS rep
INNER JOIN Z_1REPEATABLES as link
ON rep.Z_PK = link.Z_2REPEATABLES
INNER JOIN ZENTRY AS entry
ON entry.Z_PK = link.Z_1ENTRIES
GROUP BY rep.Z_PK
HAVING count > 1
ORDER BY count DESC
</code>```

Can I do this with Core Data in swift ? How does the code look like ?

Edit:

I came up with this (part of solution):

let somethingED = NSExpressionDescription()
somethingED.expression = NSExpression(forKeyPath: "entries.@count.id")
somethingED.name = "countSth"
somethingED.expressionResultType = .integer64AttributeType

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Repeatable")
fetchRequest.propertiesToFetch = ["name", somethingED]
fetchRequest.relationshipKeyPathsForPrefetching = ["entries"]
fetchRequest.resultType = .dictionaryResultType
fetchRequest.predicate = NSPredicate(format: "$countSth > 1")

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

do {
    let result = try context.fetch(fetchRequest)
    print(result)
} catch{
    print("error fetching: \(error)")
}
```

<p>The problem with this solution... I don't know how to sort this. I always end up with an error. Also this is no group-by + having construct. So, I think, well, ok, if this works, I don't need no group-by. BUT still I'd like to know how or if this is possible with group-by + having predicate ?!</p>

<hr>

<p>Edit 2:</p>

<p>So in the comments @pbasdf linked this from wwdc 2019 (+1 for that). It describes exactly my use case and provides a perfect solution... BUT... it's for iOS 13, but I want to support iOS 12 as well (iPhone 6 for example). And so I finally came up with this solution: have an <code>entriesCount</code> property + on each save update that value.
Now saving is a little bit slower but reading will be ultra fast because there's no table join, group by or count needed in the query.</p>

```    public override func willSave() {
        let newValue =  Int16(self.entries?.count ?? 0)
        if countEntries != newValue, changedValues()[#keyPath(Repeatable.countEntries)] == nil, !isDeleted {
            countEntries = newValue
        }
        super.willSave()
    }
```

答:
Yes you can do this. You would create an NSFetchRequest and customize its sortDescriptors and predicate properties to get the result you want.

If you set up your core data relationships properly, there's no need to manually specify things like an "inner join". You simply set up the many-to-many relationship in the data model and then you can access those relationships directly in your predicate.

I don't know if your entire query is entirely translatable into a single fetch, but there's no need to restrict yourself to that. Once you've finished your fetch you can do further refinement/processing in a managed object context. That's the whole point of the CoreData ORM, you just work on the objects directly and don't worry about the underlying DB.

Body:
I have a hard time with CoreData requests. Using some SQL derivate I'd get along. But here I need some help.

I have two entities with manyToMany relationships. It looks like this:

Repeatable (name: String, type: Int16, entries: [Entry])
Entry      (id: UUID, createdAt: Date, repeatables: [Repeatable])

I want to get a list of repeatables belonging to more than 1 entry, ordered by the count of associations

In SQL it would look like this:

SELECT rep.Z_PK, COUNT(rep.Z_PK) as count FROM ZREPEATABLE AS rep
INNER JOIN Z_1REPEATABLES as link
ON rep.Z_PK = link.Z_2REPEATABLES
INNER JOIN ZENTRY AS entry
ON entry.Z_PK = link.Z_1ENTRIES
GROUP BY rep.Z_PK
HAVING count > 1
ORDER BY count DESC

Can I do this with Core Data in swift ? How does the code look like ?

Edit:

I came up with this (part of solution):

let somethingED = NSExpressionDescription()
somethingED.expression = NSExpression(forKeyPath: "entries.@count.id")
somethingED.name = "countSth"
somethingED.expressionResultType = .integer64AttributeType

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Repeatable")
fetchRequest.propertiesToFetch = ["name", somethingED]
fetchRequest.relationshipKeyPathsForPrefetching = ["entries"]
fetchRequest.resultType = .dictionaryResultType
fetchRequest.predicate = NSPredicate(format: "$countSth > 1")

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext

do {
    let result = try context.fetch(fetchRequest)
    print(result)
} catch{
    print("error fetching: \(error)")
}

The problem with this solution... I don't know how to sort this. I always end up with an error. Also this is no group-by + having construct. So, I think, well, ok, if this works, I don't need no group-by. BUT still I'd like to know how or if this is possible with group-by + having predicate ?!

Edit 2:

So in the comments @pbasdf linked this from wwdc 2019 (+1 for that). It describes exactly my use case and provides a perfect solution... BUT... it's for iOS 13, but I want to support iOS 12 as well (iPhone 6 for example). And so I finally came up with this solution: have an entriesCount property + on each save update that value.
Now saving is a little bit slower but reading will be ultra fast because there's no table join, group by or count needed in the query.

    public override func willSave() {
        let newValue =  Int16(self.entries?.count ?? 0)
        if countEntries != newValue, changedValues()[#keyPath(Repeatable.countEntries)] == nil, !isDeleted {
            countEntries = newValue
        }
        super.willSave()
    }


问:
In Java, how would I code a pyramid of asterisks by using nested for loops?
I am working on an assignment where I have to use nested loops to program a pyramid of asterisks that is on its side.
The output of this program should look like this:

```<code>*
**
***
****
***
**
*
</code>```

When I run my program, it only displays the final four lines of the code. I don't know why the first three don't show up.
Here is my code:

```<code>public class Main
{
    public static void main(String[] args) {

        for(int a = 0; a < 8; a++) //1
        {
            if(a < 4){
                for(int b = a; b < 4; b++)
                {
                    System.out.print("*");
                }

            }
            if(a >= 4)
                for(int c = a; c < 4; c++)
                {
                    System.out.print("*");
                }

            System.out.println();
        } //loop 1

    }
}
</code>```

And here is my output:

```<code>****
***
**
*
</code>```

(There is some empty space after the output that I did not include. This is caused by the outer for loop iterating eight times.) How would I make my program correctly display all of the code, instead of just the last four lines?

Any help would be greatly appreciated.

答:
There are several mistakes in your logic:

Since you only need 7 rows, the first loop should iterate until a < 7

In the first 3 rows, your nested loop should iterate from 0 to a

After that, the other nested loop should go from a to 7

It is better to use if-else instead of two if statements

Here is the complete solution that I tested:

```<code>for(int a = 0; a < 7; a++) {
     if(a < 4){
          for(int b = 0; b <= a; b++)
               System.out.print("*");
     }else {
          for(int c = a; c < 7; c++)
               System.out.print("*");
     }
     System.out.println();
}
</code>```

Output:

```<code>*
**
***
****
***
**
*
</code>```

EDIT:

As mentioned in the comments, you can also split the outer loop into two parts in order to remove the conditions as follows:

```<code>for(int a = 0; a < 4; a++) {
     for(int b = 0; b <= a; b++)
          System.out.print("*");
     System.out.println();
}
for(int a = 4; a <= 7; a++) {
     for(int b = a; b < 7; b++)
          System.out.print("*");
     System.out.println();
}
</code>```

Body:
I am working on an assignment where I have to use nested loops to program a pyramid of asterisks that is on its side.
The output of this program should look like this:

*
**
***
****
***
**
*

When I run my program, it only displays the final four lines of the code. I don't know why the first three don't show up.
Here is my code:

public class Main
{
    public static void main(String[] args) {

        for(int a = 0; a < 8; a++) //1
        {
            if(a < 4){
                for(int b = a; b < 4; b++)
                {
                    System.out.print("*");
                }

            }
            if(a >= 4)
                for(int c = a; c < 4; c++)
                {
                    System.out.print("*");
                }

            System.out.println();
        } //loop 1

    }
}

And here is my output:

****
***
**
*

(There is some empty space after the output that I did not include. This is caused by the outer for loop iterating eight times.) How would I make my program correctly display all of the code, instead of just the last four lines?

Any help would be greatly appreciated.

Body:
There are several mistakes in your logic:

Since you only need 7 rows, the first loop should iterate until a < 7

In the first 3 rows, your nested loop should iterate from 0 to a

After that, the other nested loop should go from a to 7

It is better to use if-else instead of two if statements

Here is the complete solution that I tested:

for(int a = 0; a < 7; a++) {
     if(a < 4){
          for(int b = 0; b <= a; b++)
               System.out.print("*");
     }else {
          for(int c = a; c < 7; c++)
               System.out.print("*");
     }
     System.out.println();
}

Output:

*
**
***
****
***
**
*

EDIT:

As mentioned in the comments, you can also split the outer loop into two parts in order to remove the conditions as follows:

for(int a = 0; a < 4; a++) {
     for(int b = 0; b <= a; b++)
          System.out.print("*");
     System.out.println();
}
for(int a = 4; a <= 7; a++) {
     for(int b = a; b < 7; b++)
          System.out.print("*");
     System.out.println();
}


问:
Date created doesn't work but the hard coded does
I´m trying to consume an api with two dates: startDate and endDate, when I use harcoded endDate the program works, but when I try to use a date that I create it doesn´t

```<code>$date = Get-Date
$year = $date.year
$month = $date.Month
$startDate2 = $year.ToString() + "-" + $month.ToString() +  "-" + 01 + "T00:00:00.000-00:00"
$startDate = "2020-5-1T00:00:00.000-00:00"
$endDate2 = Get-Date -Format "yyyy-MM-ddTHH:mm:ss"
$toAdd = ".205-07:00"
$endDate2 = $endDate2 + $toAdd
#2019-06-23T09:07:21.205-07:00
Write-Host $endDate2

#Armar el url con las dos fechas
$url_api2 = "https://api.mypurecloud.com/api/v2/billing/reports/billableusage?startDate=" + $startDate2 +"&endDate=" + `
$endDate2
</code>```

Both look the same in structure:
Hardcoded:
2019-06-23T09:07:21.205-07:00
Created
2020-05-29T15:23:48.000-00:00

The api documentation says that this must be the format
"yyyy-MM-ddTHH:mm:ss.SSSZ"

It comes like this
2020-05-29T16:58:37.SSSZ

So I manipulate de final part to remove the letters

答:
Looks like ISO 8601. Try this.

Get-Date -Format o
```

Round-trip specifier

You shouldn't need the $toAdd variable then.

Body:
I´m trying to consume an api with two dates: startDate and endDate, when I use harcoded endDate the program works, but when I try to use a date that I create it doesn´t

$date = Get-Date
$year = $date.year
$month = $date.Month
$startDate2 = $year.ToString() + "-" + $month.ToString() +  "-" + 01 + "T00:00:00.000-00:00"
$startDate = "2020-5-1T00:00:00.000-00:00"
$endDate2 = Get-Date -Format "yyyy-MM-ddTHH:mm:ss"
$toAdd = ".205-07:00"
$endDate2 = $endDate2 + $toAdd
#2019-06-23T09:07:21.205-07:00
Write-Host $endDate2

#Armar el url con las dos fechas
$url_api2 = "https://api.mypurecloud.com/api/v2/billing/reports/billableusage?startDate=" + $startDate2 +"&endDate=" + `
$endDate2

Both look the same in structure:
Hardcoded:
2019-06-23T09:07:21.205-07:00
Created
2020-05-29T15:23:48.000-00:00

The api documentation says that this must be the format
"yyyy-MM-ddTHH:mm:ss.SSSZ"

It comes like this
2020-05-29T16:58:37.SSSZ

So I manipulate de final part to remove the letters

Body:
Looks like ISO 8601. Try this.

Get-Date -Format o

Round-trip specifier

You shouldn't need the $toAdd variable then.


问:
Can Orca be used to operate on a DolphinDB stream table?
I was trying to append data to a stream table through the Orca API (pandas project of DolphinDB).

It seems that it doesn't work. Will Orca support operations on streams tables?

e.g.

```<code>orca.load_table(THE_STREAM_TABLE)
</code>```

is not working.

答:
I believe read_share_table is for reading stream table:</p>

```<code>orca.read_shared_table(THE_STREAM_TABLE)
</code>```

Body:
I was trying to append data to a stream table through the Orca API (pandas project of DolphinDB).

It seems that it doesn't work. Will Orca support operations on streams tables?

e.g.

orca.load_table(THE_STREAM_TABLE)

is not working.

Body:
I believe read_share_table is for reading stream table:

orca.read_shared_table(THE_STREAM_TABLE)


问:
HTML5 Web Audio API, porting from javax.sound and getting distortion
I have a requirement to generate audio on the fly (generating from wav or mp3 files is not an option). Luckily the new WebAudio API (FF4 and Chrome 13) provides this functionality.

I have some Java code i'm porting to Javascript that looks like this:

```<code>byte[] buffer = new byte[]{ 56, -27, 88, -29, 88, -29, 88, -29 ............ };
AudioFormat af = new AudioFormat(44100, 16, 1, true, false);
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af, 1470 * 4); //create 4 frame audio buffer
sdl.start();
sdl.write(buffer, 0, buffer.length);
</code>```

I'm trying to get this working with the Web Audio API, but it is extremely distorted. Here is the code i'm using in JS:

```<code>var buffer = [ 56, -27, 88, -29, 88, -29, 88, -29 ............ ];
var ctx = new webkitAudioContext();
var src = ctx.createBufferSource();
src.buffer = ctx.createBuffer(1, buffer.length, 44100);
src.buffer.getChannelData(0).set(buffer);
src.connect(ctx.destination);
src.looping = false;
src.noteOn(0);
</code>```

Here is a .java file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.java

And here is the .js file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.js

Any tips on the differences between how javax.sound and Web Audio work, and what is causing the distortion in my JS code?

答:
You can do this without the Web Audio API since you have the sample data.
Generate a .wav file on the fly and use type arrays.

Slide 23: http://davidflanagan.com/Talks/jsconf11/BytesAndBlobs.html

Body:
I have a requirement to generate audio on the fly (generating from wav or mp3 files is not an option). Luckily the new WebAudio API (FF4 and Chrome 13) provides this functionality.

I have some Java code i'm porting to Javascript that looks like this:

byte[] buffer = new byte[]{ 56, -27, 88, -29, 88, -29, 88, -29 ............ };
AudioFormat af = new AudioFormat(44100, 16, 1, true, false);
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af, 1470 * 4); //create 4 frame audio buffer
sdl.start();
sdl.write(buffer, 0, buffer.length);

I'm trying to get this working with the Web Audio API, but it is extremely distorted. Here is the code i'm using in JS:

var buffer = [ 56, -27, 88, -29, 88, -29, 88, -29 ............ ];
var ctx = new webkitAudioContext();
var src = ctx.createBufferSource();
src.buffer = ctx.createBuffer(1, buffer.length, 44100);
src.buffer.getChannelData(0).set(buffer);
src.connect(ctx.destination);
src.looping = false;
src.noteOn(0);

Here is a .java file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.java

And here is the .js file that i'm testing with:
http://gwt-nes-port.googlecode.com/svn/wiki/webAudioTests/Main.js

Any tips on the differences between how javax.sound and Web Audio work, and what is causing the distortion in my JS code?


问:
Authorization: How to handle mutiple (dozen or more) requirements
I have a set of tables in our database with users, permissions, and a join that maps which users have what permissions.

Looking at the docs, the following is an example of how policies and the requirement(s) are set up on Startup:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddRazorPages();
    services.AddAuthorization(options =>
    {
        options.AddPolicy("AtLeast21", policy =>
            policy.Requirements.Add(new MinimumAgeRequirement(21)));
    });
}
</code>```

And here is an example of a handler for multiple requirements:

```<code>using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using PoliciesAuthApp1.Services.Requirements;

public class PermissionHandler : IAuthorizationHandler
{
    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        var pendingRequirements = context.PendingRequirements.ToList();

        foreach (var requirement in pendingRequirements)
        {
            if (requirement is ReadPermission)
            {
                if (IsOwner(context.User, context.Resource) ||
                    IsSponsor(context.User, context.Resource))
                {
                    context.Succeed(requirement);
                }
            }
            else if (requirement is EditPermission ||
                     requirement is DeletePermission)
            {
                if (IsOwner(context.User, context.Resource))
                {
                    context.Succeed(requirement);
                }
            }
        }

        //TODO: Use the following if targeting a version of
        //.NET Framework older than 4.6:
        //      return Task.FromResult(0);
        return Task.CompletedTask;
    }

    private bool IsOwner(ClaimsPrincipal user, object resource)
    {
        // Code omitted for brevity

        return true;
    }

    private bool IsSponsor(ClaimsPrincipal user, object resource)
    {
        // Code omitted for brevity

        return true;
    }
}
</code>```

My intention is to check my database tables within the handler to validate that the user has a setting that corresponds to the policy. To check if a user can upload files, the policy might look like this:

```<code>    services.AddAuthorization(config =>
    {
        config.AddPolicy("CanUploadFiles", policy => policy.Requirements.Add(new CanDoRequirement("CanUploadFiles")));
    });
</code>```

Using an [Authorize] attribute for a given policy, I can check that within the handler. I have that much working.

Question: Given that I might have 10-20 separate "CanDo…" permissions in our table, is there a better way to set these up rather than have separate lines in AddAuthorization()?

答:
Well, I'm not aware of any shortcuts when configuring the 20-ish requirements and policies that would remove the separate lines in startup, but you could consider implementing a sort of custom resource based authorization rather than a policy based one, policy-based being a declarative one. Declarative meaning the policy is pre-configured. Like so: [Authorize("policy")].

By using imperative authorization, rather than declarative, you would remove the need for x amount of policies to be configured. Instead of saying "Authorize this method", you let the framework take care of the authorization itself.

Consider the following requirements

A user must be authenticated.
That user can only upload a file if they satisfy the CanUploadFiles which is a boolean on the user's record in the database.

Now consider the following example

You have created your own ICustomAuthorizationHandler, somewhat similar to the the ASP.NET Core's IAuthorizationHandler, with the exception that you won't be satisfying a policy, but instead you will feed it a 'CanDoPermission' and it will return true or false if that user has that specific 'flag'.

public class FileController : Controller
{
    private ICustomAuthorizationService _authService
    public FileController(ICustomAuthorizationService authService)
    {
        _authService = authService;
    }

    [Authorize]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        var authResult = await _authService.AuthorizeAsync(User, "CanDoUpload");
        if (!authResult.Succeeded)
        {
            return new ForbidResult();
        }
        // Process upload
        return View();
    }
}
```

This way, there wouldn't have to be policies nor requirements configured for checking if the user can upload a file. But, you would need to take care of a lot of the stuff that you get for 'free' by simply going for policies and configuring them in AddAuthorization.

Body:
I have a set of tables in our database with users, permissions, and a join that maps which users have what permissions.

Looking at the docs, the following is an example of how policies and the requirement(s) are set up on Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddRazorPages();
    services.AddAuthorization(options =>
    {
        options.AddPolicy("AtLeast21", policy =>
            policy.Requirements.Add(new MinimumAgeRequirement(21)));
    });
}

And here is an example of a handler for multiple requirements:

using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using PoliciesAuthApp1.Services.Requirements;

public class PermissionHandler : IAuthorizationHandler
{
    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        var pendingRequirements = context.PendingRequirements.ToList();

        foreach (var requirement in pendingRequirements)
        {
            if (requirement is ReadPermission)
            {
                if (IsOwner(context.User, context.Resource) ||
                    IsSponsor(context.User, context.Resource))
                {
                    context.Succeed(requirement);
                }
            }
            else if (requirement is EditPermission ||
                     requirement is DeletePermission)
            {
                if (IsOwner(context.User, context.Resource))
                {
                    context.Succeed(requirement);
                }
            }
        }

        //TODO: Use the following if targeting a version of
        //.NET Framework older than 4.6:
        //      return Task.FromResult(0);
        return Task.CompletedTask;
    }

    private bool IsOwner(ClaimsPrincipal user, object resource)
    {
        // Code omitted for brevity

        return true;
    }

    private bool IsSponsor(ClaimsPrincipal user, object resource)
    {
        // Code omitted for brevity

        return true;
    }
}

My intention is to check my database tables within the handler to validate that the user has a setting that corresponds to the policy. To check if a user can upload files, the policy might look like this:

    services.AddAuthorization(config =>
    {
        config.AddPolicy("CanUploadFiles", policy => policy.Requirements.Add(new CanDoRequirement("CanUploadFiles")));
    });

Using an [Authorize] attribute for a given policy, I can check that within the handler. I have that much working.

Question: Given that I might have 10-20 separate "CanDo…" permissions in our table, is there a better way to set these up rather than have separate lines in AddAuthorization()?

Body:
Well, I'm not aware of any shortcuts when configuring the 20-ish requirements and policies that would remove the separate lines in startup, but you could consider implementing a sort of custom resource based authorization rather than a policy based one, policy-based being a declarative one. Declarative meaning the policy is pre-configured. Like so: [Authorize("policy")].

By using imperative authorization, rather than declarative, you would remove the need for x amount of policies to be configured. Instead of saying "Authorize this method", you let the framework take care of the authorization itself.

Consider the following requirements

A user must be authenticated.
That user can only upload a file if they satisfy the CanUploadFiles which is a boolean on the user's record in the database.

Now consider the following example

You have created your own ICustomAuthorizationHandler, somewhat similar to the the ASP.NET Core's IAuthorizationHandler, with the exception that you won't be satisfying a policy, but instead you will feed it a 'CanDoPermission' and it will return true or false if that user has that specific 'flag'.

public class FileController : Controller
{
    private ICustomAuthorizationService _authService
    public FileController(ICustomAuthorizationService authService)
    {
        _authService = authService;
    }

    [Authorize]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        var authResult = await _authService.AuthorizeAsync(User, "CanDoUpload");
        if (!authResult.Succeeded)
        {
            return new ForbidResult();
        }
        // Process upload
        return View();
    }
}

This way, there wouldn't have to be policies nor requirements configured for checking if the user can upload a file. But, you would need to take care of a lot of the stuff that you get for 'free' by simply going for policies and configuring them in AddAuthorization.


问:
Powershell ps1 script runs bat file but CMD screen closes after execution
This is my code:

```<code>set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait

set-location C:\
</code>```

When executed in powershell, the system opens a Command prompt window and executes the bat file without issue. The problem is that the window closes and I cannot see if there was an error if it succeeds.

I want to keep the CMD window open.

I also tried at the end of the bat file:

```<code>:END
cmd /k

</code>```

but no luck.

答:
First, unless you specifically need to run the batch file in a new window, do not use Start-Process - use direct invocation instead, which is implicitly synchronous and allows you to capture or redirect output:

```<code># Invoke the batch file synchronously (wait for it to exit)
# and capture its (standard) output in variable $A
# To print the batch file's output to the console instead, just use:
#    .\refresh.bat
$A = .\refresh.bat
</code>```

See this answer for more information.

Also note Start-Process never allows you to capture the invoked program's output directly (you can only redirect it to files with -RedirectStandardOutput and -RedirectStandardOutput); your specific command captures nothing[1] in $A; adding -PassThru does return something, but not the program's output, but a process-information object (System.Diagnostics.Process).

If you do need to run the batch file in a new window and want to keep that window open:

```<code>Start-Process -Wait -FilePath cmd -ArgumentList '/k .\refresh.bat'
</code>```

Relying on positional parameter binding, the above can be simplified to:

 Start-Process -Wait cmd '/k .\refresh.bat'

[1] Strictly speaking, $A is assigned the [System.Management.Automation.Internal.AutomationNull]::Value singleton, which in most contexts behaves like $null.

Body:
This is my code:

set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait

set-location C:\

When executed in powershell, the system opens a Command prompt window and executes the bat file without issue. The problem is that the window closes and I cannot see if there was an error if it succeeds.

I want to keep the CMD window open.

I also tried at the end of the bat file:

:END
cmd /k

but no luck.

Body:
First, unless you specifically need to run the batch file in a new window, do not use Start-Process - use direct invocation instead, which is implicitly synchronous and allows you to capture or redirect output:

# Invoke the batch file synchronously (wait for it to exit)
# and capture its (standard) output in variable $A
# To print the batch file's output to the console instead, just use:
#    .\refresh.bat
$A = .\refresh.bat

See this answer for more information.

Also note Start-Process never allows you to capture the invoked program's output directly (you can only redirect it to files with -RedirectStandardOutput and -RedirectStandardOutput); your specific command captures nothing[1] in $A; adding -PassThru does return something, but not the program's output, but a process-information object (System.Diagnostics.Process).

If you do need to run the batch file in a new window and want to keep that window open:

Start-Process -Wait -FilePath cmd -ArgumentList '/k .\refresh.bat'

Relying on positional parameter binding, the above can be simplified to:

 Start-Process -Wait cmd '/k .\refresh.bat'

[1] Strictly speaking, $A is assigned the [System.Management.Automation.Internal.AutomationNull]::Value singleton, which in most contexts behaves like $null.


问:
Renaming a column that R recognizes as a function
I have a large data set with set column names, I need to rename the columns. Here are the columns:

```<code>class(spec_sub_act_feat_all)
[1] "data.frame"
names(spec_sub_act_feat_all[,82:86])
[1] "angle(tBodyAccMean,gravity)"          "angle(tBodyAccJerkMean),gravityMean)"
[3] "angle(tBodyGyroMean,gravityMean)"     "angle(tBodyGyroJerkMean,gravityMean)"
[5] "angle(X,gravityMean)"
class(names(spec_sub_act_feat_all[,82:88]))
[1] "character"
</code>```

However, when I try to rename the columns using

```<code>names(spec_sub_act_feat_all) <- gsub(`angle(tBodyAccMean,gravity)`,
'Vector of mean body accelerometer signal',names(spec_sub_act_feat_all))
Error in gsub(`angle(tBodyAccMean,gravity)`, "Vector of mean body accelerometer signal",  :
  object 'angle(tBodyAccMean,gravity)' not found
</code>```

or simply

```<code>names(spec_sub_act_feat_all[,82])<-"Vector of mean body accelerometer signal"
</code>```

Neither one works. I believe my problem is that R is recognizing the column name as an actual function and won't let me select the character string to change it. The first renaming I tried with gsub(), I used `` to try to select the column name as not a function, which was recommended in another post, but did not work for me. I did notice that I could substitute out what was in the () but not the whole 'angle(...)' part.

答:
As the ( and ) are metacharacters to capture the group in regex mode, if we use this in gsub, the default option is fixed = FALSE i.e. regex mode, either we need to escape (\\() or place it in square brackets ([(]) to literally evaluate it in regex mode or we can specify fixed = TRUE

```<code>gsub("angle(tBodyAccMean,gravity)",
    'Vector of mean body accelerometer signal',
                     names(spec_sub_act_feat_all), fixed = TRUE)
</code>```

Body:
I have a large data set with set column names, I need to rename the columns. Here are the columns:

class(spec_sub_act_feat_all)
[1] "data.frame"
names(spec_sub_act_feat_all[,82:86])
[1] "angle(tBodyAccMean,gravity)"          "angle(tBodyAccJerkMean),gravityMean)"
[3] "angle(tBodyGyroMean,gravityMean)"     "angle(tBodyGyroJerkMean,gravityMean)"
[5] "angle(X,gravityMean)"
class(names(spec_sub_act_feat_all[,82:88]))
[1] "character"

However, when I try to rename the columns using

names(spec_sub_act_feat_all) <- gsub(`angle(tBodyAccMean,gravity)`,
'Vector of mean body accelerometer signal',names(spec_sub_act_feat_all))
Error in gsub(`angle(tBodyAccMean,gravity)`, "Vector of mean body accelerometer signal",  :
  object 'angle(tBodyAccMean,gravity)' not found

or simply

names(spec_sub_act_feat_all[,82])<-"Vector of mean body accelerometer signal"

Neither one works. I believe my problem is that R is recognizing the column name as an actual function and won't let me select the character string to change it. The first renaming I tried with gsub(), I used `` to try to select the column name as not a function, which was recommended in another post, but did not work for me. I did notice that I could substitute out what was in the () but not the whole 'angle(...)' part.

Body:
As the ( and ) are metacharacters to capture the group in regex mode, if we use this in gsub, the default option is fixed = FALSE i.e. regex mode, either we need to escape (\\() or place it in square brackets ([(]) to literally evaluate it in regex mode or we can specify fixed = TRUE

gsub("angle(tBodyAccMean,gravity)",
    'Vector of mean body accelerometer signal',
                     names(spec_sub_act_feat_all), fixed = TRUE)


问:
How to take the 5th power python
I want to find the 5th power of a number given by the user. Can i do this without typing:

```<code>ans = n * n * n * n * n
</code>```

and can it be used for higher powers?

答:
Use the ** operator for exponents:

```<code>print(5**12)
>>> 224832
</code>```

We can use this more generally using variables.

```<code>exponent = 5
n = 12
ans = n ** exponent
print(ans)
>>> 248832
</code>```

Other Methods
Since the ** operator caps at an exponent of 256, we can use the built-in pow() function for larger exponents. However, these numbers can be very large.

```<code>power = pow(base, exponent)
</code>```

The math and numpy libraries also can do this using the math.pow() and numpy.power() functions.

Title: How to take the 5th power python

Body:
I want to find the 5th power of a number given by the user. Can i do this without typing:

ans = n * n * n * n * n

and can it be used for higher powers?

Body:
Use the ** operator for exponents:

print(5**12)
>>> 224832

We can use this more generally using variables.

exponent = 5
n = 12
ans = n ** exponent
print(ans)
>>> 248832

Other Methods
Since the ** operator caps at an exponent of 256, we can use the built-in pow() function for larger exponents. However, these numbers can be very large.

power = pow(base, exponent)

The math and numpy libraries also can do this using the math.pow() and numpy.power() functions.


问:
How to find duration of a webm (opus) audio file in seconds (in a js program)?
On a javascript web page I generate an audio message, using HTML5 Media API, and I send it through socketio to a nodejs server that save the file on disk. It all works.

Javascript chunk, client side:

```<code>navigator.mediaDevices
  .getUserMedia({ audio: true })
    .then(stream => {

      const mediaRecorder = new MediaRecorder(stream)
      ...
      }
</code>```

Server side I succesfully save the webm/opus file:

```<code>$ ll audiofiles/audiofile.webm
-rw-rw-r-- 1 username 180K May 29 21:04 audiofiles/audiofile.webm
</code>```

Using vlc player, I see that the duration in seconds is almost 28 seconds.

let's check with mediainfo / ffmpeg:

Using mediainfo:

```<code>$ mediainfo audiofiles/audiofile.webm
General
Complete name                            : audiofiles/audiofile.webm
Format                                   : WebM
Format version                           : Version 4 / Version 2
File size                                : 180 KiB
Writing application                      : Chrome
Writing library                          : Chrome
IsTruncated                              : Yes

Audio
ID                                       : 1
Format                                   : Opus
Codec ID                                 : A_OPUS
Channel(s)                               : 1 channel
Channel positions                        : Front: C
Sampling rate                            : 48.0 kHz
Bit depth                                : 32 bits
Compression mode                         : Lossy
Language                                 : English
Default                                  : Yes
Forced                                   : No
</code>```

Using ffmpeg:

```<code>$ ffmpeg -hide_banner -i audiofiles/audiofile.webm
Input #0, matroska,webm, from 'audiofiles/audiofile.webm':
  Metadata:
    encoder         : Chrome
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0(eng): Audio: opus, 48000 Hz, mono, fltp (default)
At least one output file must be specified
</code>```

My question is:

How can I trace, server side, on the node server log file, the length in seconds of the webm audio file?

I need to have the approssimative time duration (in seconds) of the file. Possibly using a nodejs function.

A bad/rough solution in runtime could be to empirically map the length in bytes of the file with the length in seconds...By example for the specific encoding/format: 1000 bytes ~= 1 sec.

Any better idea to measure the duration of the audio file, possibly in the nodejs code?

答:
Node.js isn't famous for its audio possibilities.

I like your empirical approach of mapping the length of file to determine the duration, and I'm sure you could get some results if you can extract the sample rate or infos like that to make your calculation, but if you have access to ffmpeg in your environment, I would personally use a subprocess to obtain that information:

```<code>const { exec } = require('child_process');

let your_webm_file = 'audiofiles/audiofile.webm';

// https://trac.ffmpeg.org/wiki/FFprobeTips#Duration
let cmd_ffprobe_duration = `ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 ${your_webm_file}`;

exec(cmd_ffprobe_duration, (error, duration, stderr) => {
  if (error || stderr)
    return console.error('Can\'t determine webm file duration');
  console.log(duration);  // 30.543000
});
</code>```

And for those like me that doesn't know what is ll.

Body:
On a javascript web page I generate an audio message, using HTML5 Media API, and I send it through socketio to a nodejs server that save the file on disk. It all works.

Javascript chunk, client side:

navigator.mediaDevices
  .getUserMedia({ audio: true })
    .then(stream => {

      const mediaRecorder = new MediaRecorder(stream)
      ...
      }

Server side I succesfully save the webm/opus file:

$ ll audiofiles/audiofile.webm
-rw-rw-r-- 1 username 180K May 29 21:04 audiofiles/audiofile.webm

Using vlc player, I see that the duration in seconds is almost 28 seconds.

let's check with mediainfo / ffmpeg:

Using mediainfo:

$ mediainfo audiofiles/audiofile.webm
General
Complete name                            : audiofiles/audiofile.webm
Format                                   : WebM
Format version                           : Version 4 / Version 2
File size                                : 180 KiB
Writing application                      : Chrome
Writing library                          : Chrome
IsTruncated                              : Yes

Audio
ID                                       : 1
Format                                   : Opus
Codec ID                                 : A_OPUS
Channel(s)                               : 1 channel
Channel positions                        : Front: C
Sampling rate                            : 48.0 kHz
Bit depth                                : 32 bits
Compression mode                         : Lossy
Language                                 : English
Default                                  : Yes
Forced                                   : No

Using ffmpeg:

$ ffmpeg -hide_banner -i audiofiles/audiofile.webm
Input #0, matroska,webm, from 'audiofiles/audiofile.webm':
  Metadata:
    encoder         : Chrome
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0(eng): Audio: opus, 48000 Hz, mono, fltp (default)
At least one output file must be specified

My question is:

How can I trace, server side, on the node server log file, the length in seconds of the webm audio file?

I need to have the approssimative time duration (in seconds) of the file. Possibly using a nodejs function.

A bad/rough solution in runtime could be to empirically map the length in bytes of the file with the length in seconds...By example for the specific encoding/format: 1000 bytes ~= 1 sec.

Any better idea to measure the duration of the audio file, possibly in the nodejs code?

Body:
Node.js isn't famous for its audio possibilities.

I like your empirical approach of mapping the length of file to determine the duration, and I'm sure you could get some results if you can extract the sample rate or infos like that to make your calculation, but if you have access to ffmpeg in your environment, I would personally use a subprocess to obtain that information:

const { exec } = require('child_process');

let your_webm_file = 'audiofiles/audiofile.webm';

// https://trac.ffmpeg.org/wiki/FFprobeTips#Duration
let cmd_ffprobe_duration = `ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 ${your_webm_file}`;

exec(cmd_ffprobe_duration, (error, duration, stderr) => {
  if (error || stderr)
    return console.error('Can\'t determine webm file duration');
  console.log(duration);  // 30.543000
});

And for those like me that doesn't know what is ll.


问:
Concept for a function returning a templated entity
I've been experimenting with adding concepts to a constexpr json parser and am struggling to define the proper Parser concept. My first attempt:

using parse_input_t = std::string_view;
template <typename T>
using parse_result_t = std::optional<std::pair<T, std::string_view>>;

// A parser for type `T` is a function: parse_input_t -> parse_result_t<T>
template <typename F, typename T>
concept Parser = std::is_invocable_r_v<parse_result_t<T>, F, parse_input_t>;
```

<p>The problem with this is that I want to write functions with the signature:</p>

<pre class="lang-cpp prettyprint-override"><code>template <Parser P>
auto func(P p);
</code>```

That is, I don't want T in the interface.

I can accomplish what I want with something kind of ugly:

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    requires requires(typename decltype(f(i))::value_type result)
    {
        { f(i) } -> std::same_as<parse_result_t<decltype(result.first)>>;
    };
};
```

<p>Is there a cleaner way to do this?  I was hoping for something like:</p>

<pre class="lang-cpp prettyprint-override"><code>template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    { f(i) } -> std::same_as<parse_result_t<auto>>;
};
</code>```

答:
Introduce a helper trait that verifies if a given type is parse_result_t, then use it in the concept on decltype(f(i)):

```<code>template <typename T>
constexpr bool is_parse_result_v = false;

template <typename T>
constexpr bool is_parse_result_v<parse_result_t<T>> = true;

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    f(i);
    requires is_parse_result_v<decltype(f(i))>;
};
</code>```

DEMO

Alternatively, use the helper trait in a separate concept definition, so as to avoid decltype:

```<code>template <typename T>
concept is_parse_result = is_parse_result_v<T>;

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    { f(i) } -> is_parse_result;
};
</code>```

DEMO 2

Body:
I've been experimenting with adding concepts to a constexpr json parser and am struggling to define the proper Parser concept. My first attempt:

using parse_input_t = std::string_view;
template <typename T>
using parse_result_t = std::optional<std::pair<T, std::string_view>>;

// A parser for type `T` is a function: parse_input_t -> parse_result_t<T>
template <typename F, typename T>
concept Parser = std::is_invocable_r_v<parse_result_t<T>, F, parse_input_t>;

The problem with this is that I want to write functions with the signature:

template <Parser P>
auto func(P p);

That is, I don't want T in the interface.

I can accomplish what I want with something kind of ugly:

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    requires requires(typename decltype(f(i))::value_type result)
    {
        { f(i) } -> std::same_as<parse_result_t<decltype(result.first)>>;
    };
};

Is there a cleaner way to do this?  I was hoping for something like:

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    { f(i) } -> std::same_as<parse_result_t<auto>>;
};

Body:
Introduce a helper trait that verifies if a given type is parse_result_t, then use it in the concept on decltype(f(i)):

template <typename T>
constexpr bool is_parse_result_v = false;

template <typename T>
constexpr bool is_parse_result_v<parse_result_t<T>> = true;

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    f(i);
    requires is_parse_result_v<decltype(f(i))>;
};

DEMO

Alternatively, use the helper trait in a separate concept definition, so as to avoid decltype:

template <typename T>
concept is_parse_result = is_parse_result_v<T>;

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    { f(i) } -> is_parse_result;
};

DEMO 2


问:
How to code a user input textbox in HTML and use javascript to show an explanation if the answer is correct otherwise say incorrect
I want to code this for my website so I can show the explanation for a problem only if a user input is correct otherwise, it should say that I am incorrect. I want to know what functions I need for this and how to code the HTML5 part of it.</p>

答:
Do you want something like this ?

let answer = "washington";

const input = document.getElementById("input");
const button = document.getElementById("checkAnswer")

button.addEventListener("click", () => {
  if (input.value.toLowerCase() === answer) {
    alert("you are right")
  } else {
    alert("you are incorrect")
    input.value = ""

  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>where is the capital of america?</p>
<label for="input">Your answer</label>
<input type="text" id="input">
<button type="button" id="checkAnswer">Check</button></code>```

Body:
Do you want something like this ?

let answer = "washington";

const input = document.getElementById("input");
const button = document.getElementById("checkAnswer")

button.addEventListener("click", () => {
  if (input.value.toLowerCase() === answer) {
    alert("you are right")
  } else {
    alert("you are incorrect")
    input.value = ""

  }
})

<p>where is the capital of america?</p>
<label for="input">Your answer</label>
<input type="text" id="input">
<button type="button" id="checkAnswer">Check</button>


问:
T-SQL Multiple duplicates check
I'm facing this problem - I have this kind of select result:

```<code>col1 col2           col3
5    95.91.232.198  1
8    95.91.232.198  1
9    95.91.222.206  5
152  95.91.222.206  1
25   95.91.204.108  5
5    95.91.204.108  5
</code>```

column3 can have only 2 values: 1 or 5

I want to select only those rows which have different numbers in column3 with duplicated ip - example (what should be selected):

this should be selected

```<code>127.0.0.1   1
127.0.0.1   5
</code>```

and this not

```<code>127.0.0.1   1
127.0.0.1   1
</code>```

Appreciate any help.

答:
With EXISTS:

```<code>select t.* from tablename t
where exists (
  select 1 from tablename
  where col2 = t.col2 and col3 <> t.col3
)
</code>```

Or if you want only the ips:

```<code>select col2
from tablename
group by col2
having count(distinct col3) = 2
</code>```

Title: T-SQL Multiple duplicates check

Body:
I'm facing this problem - I have this kind of select result:

col1 col2           col3
5    95.91.232.198  1
8    95.91.232.198  1
9    95.91.222.206  5
152  95.91.222.206  1
25   95.91.204.108  5
5    95.91.204.108  5

column3 can have only 2 values: 1 or 5

I want to select only those rows which have different numbers in column3 with duplicated ip - example (what should be selected):

this should be selected

127.0.0.1   1
127.0.0.1   5

and this not

127.0.0.1   1
127.0.0.1   1

Appreciate any help.

Body:
With EXISTS:

select t.* from tablename t
where exists (
  select 1 from tablename
  where col2 = t.col2 and col3 <> t.col3
)

Or if you want only the ips:

select col2
from tablename
group by col2
having count(distinct col3) = 2


问:
How to "flatten" in Inkscape?
I know that Inkscape has no flatten function. But. I have three objects in an svg file, which I want to all merge into one. It's a contribution to the Material Design Icon catalog, so this has to be a single path SVG.

However, when I "Union" the objects, two of the inner objects become thinner. If I "Combine" them, the outer object becomes fatter. Think it may have something to do with stroke and fill, but tinkering with these doesn't change anything.

Isn't there a function that just converts whatever is visible into one shape?

Juancho suggested doing "Stroke to Path", this works in the sense that the dimensions are now kept the same. But I fail to get the background (fill?) back on the outer ring afterwards:

This is the raw SVG:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   version="1.1"
   width="24"
   height="24"
   viewBox="0 0 24 24"
   id="svg4"
   sodipodi:docname="pentagram-circle-outline.svg"
   inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
  <metadata
     id="metadata10">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title />
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <defs
     id="defs8" />
  <sodipodi:namedview
     pagecolor="#ffffff"
     bordercolor="#666666"
     borderopacity="1"
     objecttolerance="10"
     gridtolerance="10"
     guidetolerance="10"
     inkscape:pageopacity="0"
     inkscape:pageshadow="2"
     inkscape:window-width="1722"
     inkscape:window-height="999"
     id="namedview6"
     showgrid="false"
     inkscape:zoom="27.812867"
     inkscape:cx="12.701976"
     inkscape:cy="11.744741"
     inkscape:window-x="0"
     inkscape:window-y="0"
     inkscape:window-maximized="0"
     inkscape:current-layer="svg4" />
  <path
     d="M 12 2 C 6.47 2 2 6.5 2 12 A 10 10 0 0 0 12 22 A 10 10 0 0 0 22 12 A 10 10 0 0 0 12 2 z M 12 4 A 8 8 0 0 1 19.722656 9.9179688 A 7.5696538 7.4413764 5.2319768 0 1 19.722656 9.9199219 A 7.5696538 7.4413764 5.2319768 0 1 20.044922 11.904297 A 7.5696538 7.4413764 5.2319768 0 1 19.140625 15.587891 A 8 8 0 0 1 12 20 A 8 8 0 0 1 4 12 A 8 8 0 0 1 12 4 z "
     id="path2"
     style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-opacity:1;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none" />
  <path
     inkscape:connector-curvature="0"
     style="display:inline;fill:#030000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:0.40000001;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
     d="M 12.091785,4.6840407 7.6392526,17.907485 12.129207,14.886198 16.54432,17.867474 Z m -0.03789,2.140559 3.126247,9.3421803 -3.107775,-2.180816 -3.1262453,2.180816 z"
     id="path4048"
     sodipodi:nodetypes="cccccccccc" />
  <path
     inkscape:connector-curvature="0"
     style="display:inline;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:0.40000001;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
     d="m 4.8751298,9.9191537 6.5719872,4.4869193 h 1.36418 l 6.33373,-4.4296539 z M 7.2977352,10.665597 H 16.96068 l -4.906786,3.380383 z"
     id="path3166"
     sodipodi:nodetypes="ccccccccc" />
</svg>
</code>```

答:
The paths have different stroke styles.

Therefore you must first get rid of strokes by turning them into paths as well.

Select everything, Path -> Stroke to path, then Path -> Combine.

Title: How to "flatten" in Inkscape?

Body:
I know that Inkscape has no flatten function. But. I have three objects in an svg file, which I want to all merge into one. It's a contribution to the Material Design Icon catalog, so this has to be a single path SVG.

However, when I "Union" the objects, two of the inner objects become thinner. If I "Combine" them, the outer object becomes fatter. Think it may have something to do with stroke and fill, but tinkering with these doesn't change anything.

Isn't there a function that just converts whatever is visible into one shape?

Juancho suggested doing "Stroke to Path", this works in the sense that the dimensions are now kept the same. But I fail to get the background (fill?) back on the outer ring afterwards:

This is the raw SVG:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   version="1.1"
   width="24"
   height="24"
   viewBox="0 0 24 24"
   id="svg4"
   sodipodi:docname="pentagram-circle-outline.svg"
   inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
  <metadata
     id="metadata10">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title />
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <defs
     id="defs8" />
  <sodipodi:namedview
     pagecolor="#ffffff"
     bordercolor="#666666"
     borderopacity="1"
     objecttolerance="10"
     gridtolerance="10"
     guidetolerance="10"
     inkscape:pageopacity="0"
     inkscape:pageshadow="2"
     inkscape:window-width="1722"
     inkscape:window-height="999"
     id="namedview6"
     showgrid="false"
     inkscape:zoom="27.812867"
     inkscape:cx="12.701976"
     inkscape:cy="11.744741"
     inkscape:window-x="0"
     inkscape:window-y="0"
     inkscape:window-maximized="0"
     inkscape:current-layer="svg4" />
  <path
     d="M 12 2 C 6.47 2 2 6.5 2 12 A 10 10 0 0 0 12 22 A 10 10 0 0 0 22 12 A 10 10 0 0 0 12 2 z M 12 4 A 8 8 0 0 1 19.722656 9.9179688 A 7.5696538 7.4413764 5.2319768 0 1 19.722656 9.9199219 A 7.5696538 7.4413764 5.2319768 0 1 20.044922 11.904297 A 7.5696538 7.4413764 5.2319768 0 1 19.140625 15.587891 A 8 8 0 0 1 12 20 A 8 8 0 0 1 4 12 A 8 8 0 0 1 12 4 z "
     id="path2"
     style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-opacity:1;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none" />
  <path
     inkscape:connector-curvature="0"
     style="display:inline;fill:#030000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:0.40000001;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
     d="M 12.091785,4.6840407 7.6392526,17.907485 12.129207,14.886198 16.54432,17.867474 Z m -0.03789,2.140559 3.126247,9.3421803 -3.107775,-2.180816 -3.1262453,2.180816 z"
     id="path4048"
     sodipodi:nodetypes="cccccccccc" />
  <path
     inkscape:connector-curvature="0"
     style="display:inline;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:0.40000001;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
     d="m 4.8751298,9.9191537 6.5719872,4.4869193 h 1.36418 l 6.33373,-4.4296539 z M 7.2977352,10.665597 H 16.96068 l -4.906786,3.380383 z"
     id="path3166"
     sodipodi:nodetypes="ccccccccc" />
</svg>


问:
In xcode 11.4.1 I get this error "Use of unresolved identifier" for an image which is in assets folder, why is that?
```<code>import UIKit

class ViewController: UIViewController {

    let canoaimageview: UIImageView = {
        let imageview = UIImageView(image: canoa) //ERROR Use of unresolved identifier 'canoa'

        imageview.translatesAutoresizingMaskIntoConstraints = false
       return imageview
}()

  override func viewDidLoad() {
          super.viewDidLoad()

    view.addSubview(canoaimageview)
    setupLayout()
    }

    private func setupLayout() {
    canoaimageview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    canoaimageview.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
    canoaimageview.widthAnchor.constraint(equalToConstant: 150).isActive = true
    canoaimageview.heightAnchor.constraint(equalToConstant: 150).isActive = true
    }

}
</code>```

//an attached image is included showing the error and assets folder

答:
You need to make an UIImage first to assign it to imageView like this</p>

```<code>    let canoaimageview: UIImageView = {
        let imageview = UIImageView(image: UIImage(named: "canoa")) //ERROR Use of unresolved identifier 'canoa'
        imageview.contentMode = .scaleAspectFit
        imageview.translatesAutoresizingMaskIntoConstraints = false
       return imageview
}()
</code>```

Body:
import UIKit

class ViewController: UIViewController {

    let canoaimageview: UIImageView = {
        let imageview = UIImageView(image: canoa) //ERROR Use of unresolved identifier 'canoa'

        imageview.translatesAutoresizingMaskIntoConstraints = false
       return imageview
}()

  override func viewDidLoad() {
          super.viewDidLoad()

    view.addSubview(canoaimageview)
    setupLayout()
    }

    private func setupLayout() {
    canoaimageview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    canoaimageview.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
    canoaimageview.widthAnchor.constraint(equalToConstant: 150).isActive = true
    canoaimageview.heightAnchor.constraint(equalToConstant: 150).isActive = true
    }

}

//an attached image is included showing the error and assets folder

Body:
You need to make an UIImage first to assign it to imageView like this

    let canoaimageview: UIImageView = {
        let imageview = UIImageView(image: UIImage(named: "canoa")) //ERROR Use of unresolved identifier 'canoa'
        imageview.contentMode = .scaleAspectFit
        imageview.translatesAutoresizingMaskIntoConstraints = false
       return imageview
}()


问:
what is the alternate for depreciation for XMLHttpRequest for file-saver?
I am using File Saver for my react application to download files.

```<code>var FileSaver = require('file-saver');
..
..
..
FileSaver.saveAs(files['file_path'], files['file_title']);
</code>```

It was working fine but few days back it showing an error now.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

答:
This is showing because FileSaver.js sets async parameter to false of XMLHttpRequest.open() when it uses the corsEnabled method for the request and in your case it does because you are fetching data from a different origin source.

Note: Synchronous requests on the main thread can be easily disruptive
  to the user experience and should be avoided; in fact, many browsers
  have deprecated synchronous XHR support on the main thread entirely.
  Synchronous requests are permitted in Workers.

If we look at the source, we'll see a comment that is being set to false to avoid popup blocker:

function corsEnabled (url) {
  var xhr = new XMLHttpRequest()
  // use sync to avoid popup blocker
  xhr.open('HEAD', url, false)
  ...
}
```

There is also an opened issue regarding this warning Chrome gives me a warning in Angular app with no responses at all.

I suggest that you just ignore this warning message until it is fixed. You can always fork the repo and remove that async false parameter from xhr.open call.

Body:
I am using File Saver for my react application to download files.

var FileSaver = require('file-saver');
..
..
..
FileSaver.saveAs(files['file_path'], files['file_title']);

It was working fine but few days back it showing an error now.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Body:
This is showing because FileSaver.js sets async parameter to false of XMLHttpRequest.open() when it uses the corsEnabled method for the request and in your case it does because you are fetching data from a different origin source.

Note: Synchronous requests on the main thread can be easily disruptive
  to the user experience and should be avoided; in fact, many browsers
  have deprecated synchronous XHR support on the main thread entirely.
  Synchronous requests are permitted in Workers.

If we look at the source, we'll see a comment that is being set to false to avoid popup blocker:

function corsEnabled (url) {
  var xhr = new XMLHttpRequest()
  // use sync to avoid popup blocker
  xhr.open('HEAD', url, false)
  ...
}

There is also an opened issue regarding this warning Chrome gives me a warning in Angular app with no responses at all.

I suggest that you just ignore this warning message until it is fixed. You can always fork the repo and remove that async false parameter from xhr.open call.


问:
Filter array of objects by nested array of object value
Suppose I have an array of objects, each of which contains a nested array of objects likes:

```<code>[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]
</code>```

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?

答:
You could filter by looking into the nested array.

var data = [{ id: 1, title: 'Lorem', private: false, likes: [{ id: 01, username: 'mike' }, { id: 02, username: 'john' }] }, { id: 2, title: 'Ipsum', private: true, likes: [{ id: 03, username: 'steve' }, { id: 04, username: 'mike' }, { id: 05, username: 'sara' }] }, { id: 3, title: 'Dolor', private: false, likes: [{ id: 06, username: 'brad' }, { id: 07, username: 'cameron' }, { id: 08, username: 'liam' }] }],
    result = data.filter(({ likes }) => likes.some(({ username }) => username === 'mike'));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Suppose I have an array of objects, each of which contains a nested array of objects likes:

[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?

Body:
You could filter by looking into the nested array.

var data = [{ id: 1, title: 'Lorem', private: false, likes: [{ id: 01, username: 'mike' }, { id: 02, username: 'john' }] }, { id: 2, title: 'Ipsum', private: true, likes: [{ id: 03, username: 'steve' }, { id: 04, username: 'mike' }, { id: 05, username: 'sara' }] }, { id: 3, title: 'Dolor', private: false, likes: [{ id: 06, username: 'brad' }, { id: 07, username: 'cameron' }, { id: 08, username: 'liam' }] }],
    result = data.filter(({ likes }) => likes.some(({ username }) => username === 'mike'));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }