问:
Problem with reading last line of code algorithm - c++
I found this code on Stackoverflow:

```<code>    if (file.is_open())
    {
        file.seekg(-1, std::ios_base::end);
        if (file.peek() == '\n')
        {
            //Start searching for \n occurrences
            file.seekg(-1, std::ios_base::cur);
            int i = file.tellg();
            for (i;i > 0; i--)
            {
                if (file.peek() == '\n')
                {
                    //Found
                    file.get();
                    break;
                }
                //Move one character back
                file.seekg(i, std::ios_base::beg);
            }
                string line;
                getline(file,line);
        }
</code>```

It saves the last line of file in variable 'line', and it works ok, but if the last line is the first line it doesn't read the first character of line (the rest is read). When the last line is eg.the third line everything works. What's the problem?

答:
There are several conditions that you need to take into account when backing up looking for the last line in a text file.

you don't care what the last character in the file is. The file may (or may not) have a POSIX end-of-file (a '\n' as the final character of the last line),

what is relevant is that after seeking the end of file, you are not also at the beginning (empty-file); then you can

start looping looking for the '\n' before the last line in the file (keep a counter of the offset from the end and when the offset isn't one-before the end and file.peek() == '\n', then break the loop; and finally

check you are not at the beginning or if the 1st char is '\n', if so, advance the file position by one, and

read the last line.

You can code the logic several different ways, but if you are doing this in a function, you are either going to pass a reference to an open std::ifstream or pass the filename to open within the function. If you pass a reference to the open file-stream, you want your function return type to be the same reference to the open file-stream so the stream state can be validated to detect a stream error. (you will also check string.length() != 0 on return to ensure the file wasn't empty)

Putting that altogether, you could write a get last line file using your file operations similar to:

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

std::ifstream& getlastline (std::ifstream& f, std::string& last)
{
    long offsetend = 0;     /* initial offset from end */

    /* if file not empty */
    if (f.seekg(offsetend, std::ios_base::end) && f.tellg())
        /* loop continually seeking 1 before current offsetend */
        while (f.seekg(offsetend - 1, std::ios_base::end)) {
            /* if at beginning or offsetend and '\n' */
            if (!f.tellg() || (offsetend < 0 && f.peek() == '\n'))
                break;
            offsetend--;        /* decrement offsetend */
        }
    /* if not at beginning, or 1st char is '\n' advance by 1 */
    if (f.tellg() || f.peek() == '\n')
        f.seekg(offsetend, std::ios_base::end);

    if (!getline (f, last)) /* read last line */
        std::cerr << "error: getline() read of last line.\n";

    return f;       /* return stream state */
}
</code>```

Adding a short example that allows you to provide the filename to read as the first argument to the program, you could do:

```<code>int main (int argc, char **argv) {

    if (argc < 2) {
        std::cerr << "error: filename required as 1st argument.\n";
        return 1;
    }

    std::string last {};
    std::ifstream f (argv[1]);

    if (!getlastline (f, last) || last.length() == 0) {
        std::cerr << "error: stream error or file was empty.\n";
        return 1;
    }

    std::cout << last << '\n';
}
</code>```

By approaching it this way, you will get the last line regardless of whether there is a POSIX end-of-file contained in the file, and it will also handle the empty-file case as well.

Of course if all the files you are dealing with are a few hundred lines or less, you can do away with the offset from the end entirely and simply read all lines saving the last -- it makes a dramatic simplification, e.g.

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

int main (int argc, char **argv) {

    if (argc < 2) {
        std::cerr << "error: filename required as 1st argument.\n";
        return 1;
    }

    std::string current {}, last {};
    std::ifstream f (argv[1]);

    while (getline (f, current))
        last = current;

    /* (add any length validations here) */
    std::cout << last << '\n';
}
</code>```

Look things over and let me know if you have further questions.

Body:
I found this code on Stackoverflow:

    if (file.is_open())
    {
        file.seekg(-1, std::ios_base::end);
        if (file.peek() == '\n')
        {
            //Start searching for \n occurrences
            file.seekg(-1, std::ios_base::cur);
            int i = file.tellg();
            for (i;i > 0; i--)
            {
                if (file.peek() == '\n')
                {
                    //Found
                    file.get();
                    break;
                }
                //Move one character back
                file.seekg(i, std::ios_base::beg);
            }
                string line;
                getline(file,line);
        }

It saves the last line of file in variable 'line', and it works ok, but if the last line is the first line it doesn't read the first character of line (the rest is read). When the last line is eg.the third line everything works. What's the problem?

Body:
There are several conditions that you need to take into account when backing up looking for the last line in a text file.

you don't care what the last character in the file is. The file may (or may not) have a POSIX end-of-file (a '\n' as the final character of the last line),

what is relevant is that after seeking the end of file, you are not also at the beginning (empty-file); then you can

start looping looking for the '\n' before the last line in the file (keep a counter of the offset from the end and when the offset isn't one-before the end and file.peek() == '\n', then break the loop; and finally

check you are not at the beginning or if the 1st char is '\n', if so, advance the file position by one, and

read the last line.

You can code the logic several different ways, but if you are doing this in a function, you are either going to pass a reference to an open std::ifstream or pass the filename to open within the function. If you pass a reference to the open file-stream, you want your function return type to be the same reference to the open file-stream so the stream state can be validated to detect a stream error. (you will also check string.length() != 0 on return to ensure the file wasn't empty)

Putting that altogether, you could write a get last line file using your file operations similar to:

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

std::ifstream& getlastline (std::ifstream& f, std::string& last)
{
    long offsetend = 0;     /* initial offset from end */

    /* if file not empty */
    if (f.seekg(offsetend, std::ios_base::end) && f.tellg())
        /* loop continually seeking 1 before current offsetend */
        while (f.seekg(offsetend - 1, std::ios_base::end)) {
            /* if at beginning or offsetend and '\n' */
            if (!f.tellg() || (offsetend < 0 && f.peek() == '\n'))
                break;
            offsetend--;        /* decrement offsetend */
        }
    /* if not at beginning, or 1st char is '\n' advance by 1 */
    if (f.tellg() || f.peek() == '\n')
        f.seekg(offsetend, std::ios_base::end);

    if (!getline (f, last)) /* read last line */
        std::cerr << "error: getline() read of last line.\n";

    return f;       /* return stream state */
}

Adding a short example that allows you to provide the filename to read as the first argument to the program, you could do:

int main (int argc, char **argv) {

    if (argc < 2) {
        std::cerr << "error: filename required as 1st argument.\n";
        return 1;
    }

    std::string last {};
    std::ifstream f (argv[1]);

    if (!getlastline (f, last) || last.length() == 0) {
        std::cerr << "error: stream error or file was empty.\n";
        return 1;
    }

    std::cout << last << '\n';
}

By approaching it this way, you will get the last line regardless of whether there is a POSIX end-of-file contained in the file, and it will also handle the empty-file case as well.

Of course if all the files you are dealing with are a few hundred lines or less, you can do away with the offset from the end entirely and simply read all lines saving the last -- it makes a dramatic simplification, e.g.

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

int main (int argc, char **argv) {

    if (argc < 2) {
        std::cerr << "error: filename required as 1st argument.\n";
        return 1;
    }

    std::string current {}, last {};
    std::ifstream f (argv[1]);

    while (getline (f, current))
        last = current;

    /* (add any length validations here) */
    std::cout << last << '\n';
}

Look things over and let me know if you have further questions.


来源: stackexchange

问:
How to print rows where value == string in list in pandas
I have a dataframe like this:

```<code>                 words
1                 [me]
2               [they]
4         [it, we, it]
5                   []
6         [we, we, it]
</code>```

I want to print rows where df.words == a certain word, like 'me', 'it', or no word. Normally, I would do something like this:

df[df.words == 'me] or df[df.words == '', but when I do this, I get an empty data frame. What's going on here? How should I be treating the conditions I am searching on?

答:
You can make use of the pandas.DataFrame.apply method to achieve the result.

```<code>import pandas as pd
df = pd.Series(data=[["me"], ["they"], ["it", "we", "it"], [], ["we", "we", "it"]], name="words").to_frame()
filt = df["words"].apply(lambda x: "me" in x)
print(df.loc[filt])
</code>```

For the case of an empty string

```<code>empty_filt = df["words"].apply(lambda x: len(x)==0)
print(df.loc[empty_filt])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe like this:

                 words
1                 [me]
2               [they]
4         [it, we, it]
5                   []
6         [we, we, it]

I want to print rows where df.words == a certain word, like 'me', 'it', or no word. Normally, I would do something like this:

df[df.words == 'me] or df[df.words == '', but when I do this, I get an empty data frame. What's going on here? How should I be treating the conditions I am searching on?

Body:
You can make use of the pandas.DataFrame.apply method to achieve the result.

import pandas as pd
df = pd.Series(data=[["me"], ["they"], ["it", "we", "it"], [], ["we", "we", "it"]], name="words").to_frame()
filt = df["words"].apply(lambda x: "me" in x)
print(df.loc[filt])

For the case of an empty string

empty_filt = df["words"].apply(lambda x: len(x)==0)
print(df.loc[empty_filt])


问:
How can I print a modified asterisk triangle pattern using recursion?
I'm using C++ and I've been tasked with using recursion to print a triangle with a certain pattern:

For example, if the user enters the integer 4, the console should output the following:
https://i.stack.imgur.com/Gf46V.jpg

Edit: And if the user enters the integer 3, the console should output the following:
https://i.stack.imgur.com/7Sqxb.jpg
This is all the information I have on the pattern.

So, I recognize that the pattern of stars on each line is:
1, 2, 1, 3, 1, 2, 1, 4 (max), 1, 2, 1, 3, 1, 2, 1

But the furthest I've gotten using recursion is to print triangles of size n:

```<code>void starprint(int n) {
    for (int i = 1; i <= n; ++i)
    {
        if (i == 1) std::cout << "*" << std::endl;
        else
        {
            for (int j = 1; j <= i; j++)
            {
                std::cout << "*";
            }
            std::cout << std::endl;
        }
        if (i == n)
            starprint(n - 1);
    }
}
</code>```

So now I'm stuck, because the pattern is a bit strange and because my instinct for these things would be to use iteration instead of recursion and I'm a bit of a noob at recursion.

Any suggestions on how to approach this would be really helpful. Thanks guys!

答:
Here you have an elegant recursive solution for this sequence:

```<code>#include <iostream>
using namespace std;

void printstar(int n){
    if(n == 1) {cout<<"1 "; return;}
    printstar(n - 1);
    cout<<n<<" ";
    printstar(n - 1);
}

int main() {
  printstar(4);
}

//output: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
</code>```

As I said in the comments, the way is to think that n will act as a mirror for both sides. Each side will be another isolated sequence which its middle will be n - 1 (which will act as a mirror again), and so on.

```<code> 1   2  1  3  1 2 1 [4] 1 2 1 3 1 2 1

 1   2  1 [3] 1 2 1

 1  [2] 1

[1]
</code>```

Body:
I'm using C++ and I've been tasked with using recursion to print a triangle with a certain pattern:

For example, if the user enters the integer 4, the console should output the following:
https://i.stack.imgur.com/Gf46V.jpg

Edit: And if the user enters the integer 3, the console should output the following:
https://i.stack.imgur.com/7Sqxb.jpg
This is all the information I have on the pattern.

So, I recognize that the pattern of stars on each line is:
1, 2, 1, 3, 1, 2, 1, 4 (max), 1, 2, 1, 3, 1, 2, 1

But the furthest I've gotten using recursion is to print triangles of size n:

void starprint(int n) {
    for (int i = 1; i <= n; ++i)
    {
        if (i == 1) std::cout << "*" << std::endl;
        else
        {
            for (int j = 1; j <= i; j++)
            {
                std::cout << "*";
            }
            std::cout << std::endl;
        }
        if (i == n)
            starprint(n - 1);
    }
}

So now I'm stuck, because the pattern is a bit strange and because my instinct for these things would be to use iteration instead of recursion and I'm a bit of a noob at recursion.

Any suggestions on how to approach this would be really helpful. Thanks guys!

Body:
Here you have an elegant recursive solution for this sequence:

#include <iostream>
using namespace std;

void printstar(int n){
    if(n == 1) {cout<<"1 "; return;}
    printstar(n - 1);
    cout<<n<<" ";
    printstar(n - 1);
}

int main() {
  printstar(4);
}

//output: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1

As I said in the comments, the way is to think that n will act as a mirror for both sides. Each side will be another isolated sequence which its middle will be n - 1 (which will act as a mirror again), and so on.

 1   2  1  3  1 2 1 [4] 1 2 1 3 1 2 1

 1   2  1 [3] 1 2 1

 1  [2] 1

[1]


问:
h3 and anchor inline-block (on same line)
I want to have an edit icon on the same line as my product title. I thought I could use span or just set both elements to display: inline-block; But I'm having trouble getting this to work.

.model-title {
  display: inline-block;
}

.model-edit {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 class="model-title">Product Title</h3>
<i class="model-edit fa fa-pencil"></i></code>```

答:
For placing 2 elements on the same line just use display: inline-block; property and if you want to use edit icon then you can use bootstrap icon: source.

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Product Title

```

Body:
I want to have an edit icon on the same line as my product title. I thought I could use span or just set both elements to display: inline-block; But I'm having trouble getting this to work.

.model-title {
  display: inline-block;
}

.model-edit {
  display: inline-block;
}

Product Title

Body:
For placing 2 elements on the same line just use display: inline-block; property and if you want to use edit icon then you can use bootstrap icon: source.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style type="text/css">
        .model-title {
   display: inline-block;
        }
    </style>
  </head>
  <body>
    <div class="container">
       <h3 class="model-title">Product Title</h3>
        <a href="#">
          <span class="glyphicon glyphicon-pencil"></span>
        </a>
      </p>
    </div>
  </body>
</html>


问:
Desc Order in SubQueries
With this input, how do I use ORDER BY to get descending order for a subquery? It is not applying to the data in the column.

答:
Number of Sections in order by shouldn't be wrapped:</p>

```<code>Select name,
(select count(*)
from teaches
where instructor.ID = teachers.ID) as 'NumberOfSections'
from instructor
where NumberOfSections >= 2 ORDER BY NumberOfSections DESC;
</code>```

Title: Desc Order in SubQueries

Body:
Number of Sections in order by shouldn't be wrapped:

Select name,
(select count(*)
from teaches
where instructor.ID = teachers.ID) as 'NumberOfSections'
from instructor
where NumberOfSections >= 2 ORDER BY NumberOfSections DESC;


问:
How could I write an egrep command that will find all entries that have least 5 consecutive vowels (aeiou) in them upper or lower case?
I'm looking for an answer that doesnt include -i option to get both upper and lowercase. Specifically just how to make the regular expression itself output such a string.

I also do not want it to return any other strings outside of the consecutive "aeiou". For example I want to see:

aeiou
AEIOU
AeIou
daeiou
aeioud

etc.

I do not want to see:
AAAAA
aeiou
AEIOU
AeIou
daeiou
aeioud
AEODN
EEEEE
eaeee

when I do grep -E '[aeiou-AEIOU]{5,} it is still giving me additional strings like the ones above I do not want to see. Any ideas??

答:
If you can't use -i, things like [aA] will serve instead to match an upper or lower case version of a particular letter:

```<code>grep '[aA][eE][iI][oO][uU]' <<< '"AEIOU" "aEioU" "daeiou" "aeiouF"'
</code>```

Works fine with basic regular expressions, no need for extended (Which should be used via grep -E, not the obsolete egrep, by the way).

Body:
If you can't use -i, things like [aA] will serve instead to match an upper or lower case version of a particular letter:

grep '[aA][eE][iI][oO][uU]' <<< '"AEIOU" "aEioU" "daeiou" "aeiouF"'

Works fine with basic regular expressions, no need for extended (Which should be used via grep -E, not the obsolete egrep, by the way).


问:
eslint problem with firebase functions and idea
I reinstalled Intellij Idea and opened my vuejs/firebase project. I am able to see eslint notifications in IDE editor but inside functions directory in any js file I don't see any notifications. But when I try to deploy firebase --only functions I see lots of errors from prettier.

Running command: npm --prefix "$RESOURCE_DIR" run lint

functions@ lint /home/madcap/Projects/Alex/functions
  eslint .

```<code>/home/madcap/Projects/Alex/functions/index.js
  10:3   error  Delete `··`                                 prettier/prettier
  12:1   error  Delete `··`                                 prettier/prettier
  13:3   error  Delete `··`                                 prettier/prettier
  14:1   error  Replace `····` with `··`                    prettier/prettier
  15:1   error  Delete `··`                                 prettier/prettier
  16:1   error  Replace `····` with `··`                    prettier/prettier
  17:1   error  Delete `··`                                 prettier/prettier
  19:3   error  Delete `··`                                 prettier/prettier
  20:5   error  Delete `····`                               prettier/prettier
  21:1   error  Replace `············` with `······`        prettier/prettier
  22:1   error  Replace `········` with `····`              prettier/prettier
  23:1   error  Delete `····`                               prettier/prettier
  25:5   error  Delete `····`                               prettier/prettier
  26:1   error  Replace `············` with `······`        prettier/prettier
  27:1   error  Delete `········`                           prettier/prettier
  28:1   error  Replace `················` with `········`  prettier/prettier
  29:1   error  Replace `················` with `········`  prettier/prettier
  30:7   error  Delete `······`                             prettier/prettier
  31:5   error  Delete `····`                               prettier/prettier
  33:1   error  Replace `········` with `····`              prettier/prettier
  35:5   error  Delete `····`                               prettier/prettier
  36:1   error  Replace `········` with `····`              prettier/prettier
  37:1   error  Replace `············` with `······`        prettier/prettier
  38:7   error  Delete `······`                             prettier/prettier
  39:1   error  Replace `················` with `········`  prettier/prettier
  40:1   error  Delete `··········`                         prettier/prettier
  41:11  error  Delete `··········`                         prettier/prettier
  42:1   error  Replace `················` with `········`  prettier/prettier
  43:1   error  Replace `············` with `······`        prettier/prettier
  44:1   error  Replace `········` with `····`              prettier/prettier
  46:1   error  Delete `····`                               prettier/prettier
  48:5   error  Delete `····`                               prettier/prettier
  49:3   error  Delete `··`                                 prettier/prettier
  51:1   error  Replace `····` with `··`                    prettier/prettier
  52:1   error  Replace `········` with `····`              prettier/prettier
  53:1   error  Replace `············` with `······`        prettier/prettier
  54:1   error  Replace `············` with `······`        prettier/prettier
  55:7   error  Delete `······`                             prettier/prettier
  56:1   error  Delete `····`                               prettier/prettier
  57:5   error  Delete `····`                               prettier/prettier
  61:1   error  Delete `⏎··`                                prettier/prettier
  63:3   error  Delete `··`                                 prettier/prettier
  65:3   error  Delete `··`                                 prettier/prettier
  66:1   error  Delete `··`                                 prettier/prettier
  68:3   error  Delete `··`                                 prettier/prettier
  70:1   error  Delete `··`                                 prettier/prettier
  71:3   error  Delete `··`                                 prettier/prettier
  73:1   error  Replace `····` with `··`                    prettier/prettier
  74:1   error  Delete `··`                                 prettier/prettier
  76:3   error  Delete `··`                                 prettier/prettier
  77:2   error  Insert `⏎`                                  prettier/prettier

✖ 51 problems (51 errors, 0 warnings)
  51 errors and 0 warnings potentially fixable with the `--fix` option.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/madcap/.npm/_logs/2020-02-18T02_50_25_483Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1
</code>```

I've tried to reinstall firebase functions by deleting the folder and fully reinstall it with overwriting everything (firebase init functions).

I have .eslintrc.json file that has been created automatically

I have "eslint": "^5.12.0", in dev dependencies of package.json

I just don't know what happened

答:
The intellij eslint configuration is not properly configured to use the project's eslint file. So it is using the default one that has a different setting for indetation spaces.

Here you have the official guides to do it:

IntelliJ - How to configure prettier

IntelliJ - How to configure eslint

Body:
I reinstalled Intellij Idea and opened my vuejs/firebase project. I am able to see eslint notifications in IDE editor but inside functions directory in any js file I don't see any notifications. But when I try to deploy firebase --only functions I see lots of errors from prettier.

Running command: npm --prefix "$RESOURCE_DIR" run lint

functions@ lint /home/madcap/Projects/Alex/functions
  eslint .

/home/madcap/Projects/Alex/functions/index.js
  10:3   error  Delete `··`                                 prettier/prettier
  12:1   error  Delete `··`                                 prettier/prettier
  13:3   error  Delete `··`                                 prettier/prettier
  14:1   error  Replace `····` with `··`                    prettier/prettier
  15:1   error  Delete `··`                                 prettier/prettier
  16:1   error  Replace `····` with `··`                    prettier/prettier
  17:1   error  Delete `··`                                 prettier/prettier
  19:3   error  Delete `··`                                 prettier/prettier
  20:5   error  Delete `····`                               prettier/prettier
  21:1   error  Replace `············` with `······`        prettier/prettier
  22:1   error  Replace `········` with `····`              prettier/prettier
  23:1   error  Delete `····`                               prettier/prettier
  25:5   error  Delete `····`                               prettier/prettier
  26:1   error  Replace `············` with `······`        prettier/prettier
  27:1   error  Delete `········`                           prettier/prettier
  28:1   error  Replace `················` with `········`  prettier/prettier
  29:1   error  Replace `················` with `········`  prettier/prettier
  30:7   error  Delete `······`                             prettier/prettier
  31:5   error  Delete `····`                               prettier/prettier
  33:1   error  Replace `········` with `····`              prettier/prettier
  35:5   error  Delete `····`                               prettier/prettier
  36:1   error  Replace `········` with `····`              prettier/prettier
  37:1   error  Replace `············` with `······`        prettier/prettier
  38:7   error  Delete `······`                             prettier/prettier
  39:1   error  Replace `················` with `········`  prettier/prettier
  40:1   error  Delete `··········`                         prettier/prettier
  41:11  error  Delete `··········`                         prettier/prettier
  42:1   error  Replace `················` with `········`  prettier/prettier
  43:1   error  Replace `············` with `······`        prettier/prettier
  44:1   error  Replace `········` with `····`              prettier/prettier
  46:1   error  Delete `····`                               prettier/prettier
  48:5   error  Delete `····`                               prettier/prettier
  49:3   error  Delete `··`                                 prettier/prettier
  51:1   error  Replace `····` with `··`                    prettier/prettier
  52:1   error  Replace `········` with `····`              prettier/prettier
  53:1   error  Replace `············` with `······`        prettier/prettier
  54:1   error  Replace `············` with `······`        prettier/prettier
  55:7   error  Delete `······`                             prettier/prettier
  56:1   error  Delete `····`                               prettier/prettier
  57:5   error  Delete `····`                               prettier/prettier
  61:1   error  Delete `⏎··`                                prettier/prettier
  63:3   error  Delete `··`                                 prettier/prettier
  65:3   error  Delete `··`                                 prettier/prettier
  66:1   error  Delete `··`                                 prettier/prettier
  68:3   error  Delete `··`                                 prettier/prettier
  70:1   error  Delete `··`                                 prettier/prettier
  71:3   error  Delete `··`                                 prettier/prettier
  73:1   error  Replace `····` with `··`                    prettier/prettier
  74:1   error  Delete `··`                                 prettier/prettier
  76:3   error  Delete `··`                                 prettier/prettier
  77:2   error  Insert `⏎`                                  prettier/prettier

✖ 51 problems (51 errors, 0 warnings)
  51 errors and 0 warnings potentially fixable with the `--fix` option.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/madcap/.npm/_logs/2020-02-18T02_50_25_483Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

I've tried to reinstall firebase functions by deleting the folder and fully reinstall it with overwriting everything (firebase init functions).

I have .eslintrc.json file that has been created automatically

I have "eslint": "^5.12.0", in dev dependencies of package.json

I just don't know what happened


问:
NestJS - can't resolve ConfigService
I am using NestJS jwt passport to auth user. I follow the doc, here is my app module:

import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import configuration from '../config/configuration';

@Module({
  imports: [
      ConfigModule.forRoot({
          load: [configuration],
      }),
      TypeOrmModule.forRoot(),
      UserModule,
      AuthModule,
  ],
})
export class AppModule {}
```

<p>And here is my auth module:</p>

<pre class="lang-js prettyprint-override"><code>import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from '../user/user.module';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';

@Module({
    imports: [
        UserModule,
        PassportModule,
        JwtModule.registerAsync({
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
                secret:  configService.get('jwt.secret'),
                signOptions: {
                    expiresIn: configService.get('jwt.expiresIn'),
                },
            }),
            inject: [ConfigService],
        }),
    ],
    providers: [AuthService, LocalStrategy, JwtStrategy],
    exports: [AuthService],
    controllers: [AuthController],
})
export class AuthModule {}
</code>```

Every time I run npm run start, I got this error message:

```<code>Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.
</code>```

I have searched this problem, but still can't fix this. Someone can help me? Thanks.

答: I fought with this same issue for hours but according to Chau Tran, after making ConfigModule global with ConfigModule.forRoot({ isGlobal: true }) all my problems were gone.

Title: NestJS - can't resolve ConfigService

Body:
I am using NestJS jwt passport to auth user. I follow the doc, here is my app module:

import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import configuration from '../config/configuration';

@Module({
  imports: [
      ConfigModule.forRoot({
          load: [configuration],
      }),
      TypeOrmModule.forRoot(),
      UserModule,
      AuthModule,
  ],
})
export class AppModule {}

And here is my auth module:

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from '../user/user.module';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';

@Module({
    imports: [
        UserModule,
        PassportModule,
        JwtModule.registerAsync({
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
                secret:  configService.get('jwt.secret'),
                signOptions: {
                    expiresIn: configService.get('jwt.expiresIn'),
                },
            }),
            inject: [ConfigService],
        }),
    ],
    providers: [AuthService, LocalStrategy, JwtStrategy],
    exports: [AuthService],
    controllers: [AuthController],
})
export class AuthModule {}

Every time I run npm run start, I got this error message:

Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.

I have searched this problem, but still can't fix this. Someone can help me? Thanks.


问:
Does List.Insert have any performance penalty?
Given a list:

```<code>List<object> SomeList = new List<object>();
</code>```

Does doing:

```<code>SomeList.Insert(i, val);
</code>```

Vs.

```<code>SomeList.Add(val);
</code>```

Has any performance penalty? If it does, how it depends on:

 - i - insertion index

 - SomeList.Count - The size of the list

答:
I built off of Pattermiester's performance tests. When I think of insert, I think of an array, and in order to add to an array you have to specify the index you want to Insert at. Doing an Add(0, object) seems counter intuitive. Also, when you do performance tests in always create a throw away run in first. Sometimes it takes longer than it actually should.

Results

```<code>2.282 - Throw Away Run
2.6847 - List Insert By Index without Capacity
10544.9766 - List Insert At Index 0 without Capacity
1.8426 - List Add without Capacity
2.0835 - List Insert By Index with Capacity
1.4952 - List Add with Capacity
9323.699 - List Insert at Index 0 with Capacity
</code>```

Code

```<code>        var size = 200000;
        //First test sometimes has a bad count
        List<object> SomeList = new List<object>();
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(i, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds + " - Throw Away Run");
        sw.Reset();

        SomeList = new List<object>();
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size ; i++)
            SomeList.Insert(i, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Insert By Index without Capacity");
        sw.Reset();

        SomeList = new List<object>();
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(0, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds + " - List Insert At Index 0 without Capacity");
        sw.Reset();

        SomeList = new List<object>();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Add(String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Add without Capacity");
        sw.Reset();

        SomeList = new List<object>(size);
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(i, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Insert By Index with Capacity");
        sw.Reset();

        SomeList = new List<object>(size);
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Add(String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Add with Capacity");
        sw.Reset();

        SomeList = new List<object>(size);
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(0, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds + " - List Insert at Index 0 with Capacity");
</code>```

So it appears that the Add is a little more performant than than insert. However, if you are using an Insert(0, ""), you are going to be killing performance that is for sure. If you want best performance, than use capacity.

ContentLicense: CC BY-SA 3.0

Body:
Given a list:

List<object> SomeList = new List<object>();

Does doing:

SomeList.Insert(i, val);

Vs.

SomeList.Add(val);

Has any performance penalty? If it does, how it depends on:

 - i - insertion index

 - SomeList.Count - The size of the list

Body:
I built off of Pattermiester's performance tests. When I think of insert, I think of an array, and in order to add to an array you have to specify the index you want to Insert at. Doing an Add(0, object) seems counter intuitive. Also, when you do performance tests in always create a throw away run in first. Sometimes it takes longer than it actually should.

Results

2.282 - Throw Away Run
2.6847 - List Insert By Index without Capacity
10544.9766 - List Insert At Index 0 without Capacity
1.8426 - List Add without Capacity
2.0835 - List Insert By Index with Capacity
1.4952 - List Add with Capacity
9323.699 - List Insert at Index 0 with Capacity

Code

        var size = 200000;
        //First test sometimes has a bad count
        List<object> SomeList = new List<object>();
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(i, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds + " - Throw Away Run");
        sw.Reset();

        SomeList = new List<object>();
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size ; i++)
            SomeList.Insert(i, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Insert By Index without Capacity");
        sw.Reset();

        SomeList = new List<object>();
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(0, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds + " - List Insert At Index 0 without Capacity");
        sw.Reset();

        SomeList = new List<object>();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Add(String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Add without Capacity");
        sw.Reset();

        SomeList = new List<object>(size);
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(i, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Insert By Index with Capacity");
        sw.Reset();

        SomeList = new List<object>(size);
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Add(String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds+" - List Add with Capacity");
        sw.Reset();

        SomeList = new List<object>(size);
        sw = new Stopwatch();
        sw.Start();
        for (var i = 0; i < size; i++)
            SomeList.Insert(0, String.Empty);
        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalMilliseconds + " - List Insert at Index 0 with Capacity");

So it appears that the Add is a little more performant than than insert. However, if you are using an Insert(0, ""), you are going to be killing performance that is for sure. If you want best performance, than use capacity.


问:
Applying a function n times
I am trying to apply a function to a value n times.

Currently, I have

```<code>let rec n_times (f, n, v) =
 if n > 0 then
  n_times f n-1 (f v)
 else
  v
</code>```

For some reason I keep getting an error that says

```<code>This expression has type 'a but an expression was expected of type 'a * int * 'b
The type variable 'a occurs inside 'a * int * 'b
</code>```

I saw a few posts that address the same problem I am working on but none of them gets the same error.

答:
There are at least two problems, it would help to know what the purpose is other than recursion.

To get this to run you have to change your third line. n_times is defined with three inputs so it needs to be called with three. Also the function is defined to take a general, integer, and general input and output a general type.

You could remove (f v) and input just v every loop,

```<code># let rec n_times (f, n, v) =
    if n > 0 then
        n_times (f , n-1 , v)
    else
      v;;
val n_times : 'a * int * 'b -> 'b = <fun>
# n_times(2,3,4);;
- : int = 4
</code>```

This will however always return just v at the end.

You could also replace (f v) with a list and preapped it each loop,

```<code># let rec n_times (f, n, v) =
    if n > 0 then
        n_times (f , n-1 , f::v)
    else
      v;;
val n_times : 'a * int * 'a list -> 'a list = <fun>
# n_times(2,3,[4]);;
- : int list = [2; 2; 2; 4]
# n_times(2,5,[4]);;
- : int list = [2; 2; 2; 2; 2; 4]
</code>```

This allows the list to grow with each loop.

Title: Applying a function n times

Body:
I am trying to apply a function to a value n times.

Currently, I have

let rec n_times (f, n, v) =
 if n > 0 then
  n_times f n-1 (f v)
 else
  v

For some reason I keep getting an error that says

This expression has type 'a but an expression was expected of type 'a * int * 'b
The type variable 'a occurs inside 'a * int * 'b

I saw a few posts that address the same problem I am working on but none of them gets the same error.

Body:
There are at least two problems, it would help to know what the purpose is other than recursion.

To get this to run you have to change your third line. n_times is defined with three inputs so it needs to be called with three. Also the function is defined to take a general, integer, and general input and output a general type.

You could remove (f v) and input just v every loop,

# let rec n_times (f, n, v) =
    if n > 0 then
        n_times (f , n-1 , v)
    else
      v;;
val n_times : 'a * int * 'b -> 'b = <fun>
# n_times(2,3,4);;
- : int = 4

This will however always return just v at the end.

You could also replace (f v) with a list and preapped it each loop,

# let rec n_times (f, n, v) =
    if n > 0 then
        n_times (f , n-1 , f::v)
    else
      v;;
val n_times : 'a * int * 'a list -> 'a list = <fun>
# n_times(2,3,[4]);;
- : int list = [2; 2; 2; 4]
# n_times(2,5,[4]);;
- : int list = [2; 2; 2; 2; 2; 4]

This allows the list to grow with each loop.


问:
Determine number or character in textfile C
I have a textfile with these following numbers and characters inside of it.

```<code>36@xL!?\8
28?>\4
42<pX%7
37@#5
31kL%^?>\<#%5
</code>```

Now, i want to get the first integer which is 36 and subtract it on the last integer which is 8. I want to do this line by line.

答:
You want to read in the line, parse the numbers at the beginning and end, then convert them to integers. Here is a simple example:</p>

```<code>#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

main()
{
    FILE *file = fopen("input.txt", "r");
    char line[256];

    while (fgets(line, sizeof(line), file))
    {
    char num[15];
    int firstNumber = 0;
    int secondNumber = 0;

    line[strcspn(line, "\r\n")] = 0;

    for (int x = 0; x < 256; x++)
    {
        if (isdigit(line[x]))
        {
            num[x] = line[x];
        }
        else
        {
            num[x] = 0;
            break;
        }
    }
    firstNumber = atoi(num);

    int length = strlen(line);
    int ndx = 0;
    while (length >=0 && isdigit(line[length - 1]))
    {
        num[ndx] = line[length - 1];
        ndx++;
        length--;
    }
    num[ndx] = 0;
    secondNumber = atoi(num);

    printf("%d - %d = %d\n", firstNumber, secondNumber, firstNumber - secondNumber);
    }

    fclose(file);
}
</code>```

Body:
I have a textfile with these following numbers and characters inside of it.

36@xL!?\8
28?>\4
42<pX%7
37@#5
31kL%^?>\<#%5

Now, i want to get the first integer which is 36 and subtract it on the last integer which is 8. I want to do this line by line.

Body:
You want to read in the line, parse the numbers at the beginning and end, then convert them to integers. Here is a simple example:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

main()
{
    FILE *file = fopen("input.txt", "r");
    char line[256];

    while (fgets(line, sizeof(line), file))
    {
    char num[15];
    int firstNumber = 0;
    int secondNumber = 0;

    line[strcspn(line, "\r\n")] = 0;

    for (int x = 0; x < 256; x++)
    {
        if (isdigit(line[x]))
        {
            num[x] = line[x];
        }
        else
        {
            num[x] = 0;
            break;
        }
    }
    firstNumber = atoi(num);

    int length = strlen(line);
    int ndx = 0;
    while (length >=0 && isdigit(line[length - 1]))
    {
        num[ndx] = line[length - 1];
        ndx++;
        length--;
    }
    num[ndx] = 0;
    secondNumber = atoi(num);

    printf("%d - %d = %d\n", firstNumber, secondNumber, firstNumber - secondNumber);
    }

    fclose(file);
}


问:
ASP.NET application getting slower over time using Lucene.Net
A website I have using Lucene.Net for search is progressively getting slower over time. I have set IIS to recycle the app pool at 1.5GBs.

After a recycle the app is fast again.

What are the best steps in diagnosing which parts of the search is causing the issue?

Its worth noting, it is definitely the search that's causing the issues as its only this part of the application which gets slow. A normal page loads fine regardless of time.

答: Do you optimize your index after big updates ? This can really improve performance.</p>


问:
Two different projects with the same name and GitHub
I have two projects, one is in the Documents / Android Studio / Project folder, the other project is in the Documents / XCode / Project folder. That is, in both cases the folder is called "Project". I added the Android Studio project from the Android Studio to Github and successfully tested it. The versioning system works as it should. Next, I decided to add a project from Xcode to GitHub. I added a GitHub account in the Xcode settings. Xcode showed the projects available for my account. Next, I try to add a project to Github by clicking Source Control - Create Git Repositories. Xcode reports that all projects are already under the control of the versioning system. If I click Source Control - Commit, it looks like Xcode offers to commit for all project files to the same online repository called Project, which stores the project from Android Studio. I don’t understand what to do, because it is not recommended to rename the Xcode project. How to resolve this conflict?

答: Just create a new github repo at github (browser) by some other name. Then follow the instructions for pushing your project to it in the Terminal using the command line. Do not use Xcode for this or any other git related stuff. </p>


问:
What is the proper way to set the PROPS type?
I'm working with REDUX in REACT and am working on getting the mapStateToProps functionality to work correctly.

Here is my component:

```<code>interface NavProps{
    loggedIn: boolean,
    loggingIn: boolean
}

class Navigator extends Component {

public render(){
    const { loggedIn } = this.props as NavProps;
    return (
        ...removed irrelevant code
      );
    }
}

const mapStateToProps = (state: RootReducer): NavProps => {
    const { authentication } = state;
    const { loggedIn, loggingIn } = authentication;
    return{
        loggedIn,
        loggingIn
    };
}

export default connect(mapStateToProps, null)(Navigator);
</code>```

Here you can see I used:

```<code>const { loggedIn } = this.props as NavProps;
</code>```

If not, I get an error that 'loggedIn' is not in this.props.

In the tutorials I looked at, they all used something like this with no problem:

```<code>const { loggedIn } = this.props
</code>```

Am I doing it correctly or am I missing a step that will make the props correctly reflect what is assigned during mapStateToProps?

Update:
 I've gone back and reviewed a couple of the tutorials on REDUX. I see now they were using JSX, not TSX, so maybe I DO have to use type assertion to appease Typescript.

Update:

A couple of people suggested:

```<code>class Navigator extends Component <NavProps>
</code>```

However, that produces this error:

```<code>Type '{}' is missing the following properties from type 'Pick<NavProps, "loggedIn" | "loggingIn">': loggedIn, loggingIn  TS2739

<Router>
22 |       <div className="App">
> 23 |         <Navigator />
</code>```

Not sure if it makes any difference, but here is the component that is embedding NAVIGATOR:

```<code>const App = () => (
  <Provider store={store}>
    <Router>
      <div className="App">
        <Navigator />
            <Switch>
              <Route exact path="/libraries" component={Libraries} />
            </Switch>
      </div>
    </Router>
  </Provider>
);

export default App;
</code>```

Ok, I found a suggestion here:

TS2740 Type is missing the following properties from ReadOnly error in React Native with TypeScript app

As strange as it seems from the comments below, the answer is to do it like this:

```<code>class Navigator extends Component<any, any>
</code>```

Even though it doesn't seem right to just stick 'any' in there.

Here is one that is a little clearner:

TS2739 - Type missing in following properties

It suggests making the props optional:

```<code>interface NavProps{
    loggedIn?: boolean,
    loggingIn?: boolean
}

class Navigator extends Component<NavProps>
</code>```

答:
We can see that in the TypeScript docs here:

```<code>class Navigator extends Component<NavProps> {
</code>```

Here is how it looks on my machine:

Body:
I'm working with REDUX in REACT and am working on getting the mapStateToProps functionality to work correctly.

Here is my component:

interface NavProps{
    loggedIn: boolean,
    loggingIn: boolean
}

class Navigator extends Component {

public render(){
    const { loggedIn } = this.props as NavProps;
    return (
        ...removed irrelevant code
      );
    }
}

const mapStateToProps = (state: RootReducer): NavProps => {
    const { authentication } = state;
    const { loggedIn, loggingIn } = authentication;
    return{
        loggedIn,
        loggingIn
    };
}

export default connect(mapStateToProps, null)(Navigator);

Here you can see I used:

const { loggedIn } = this.props as NavProps;

If not, I get an error that 'loggedIn' is not in this.props.

In the tutorials I looked at, they all used something like this with no problem:

const { loggedIn } = this.props

Am I doing it correctly or am I missing a step that will make the props correctly reflect what is assigned during mapStateToProps?

Update:
 I've gone back and reviewed a couple of the tutorials on REDUX. I see now they were using JSX, not TSX, so maybe I DO have to use type assertion to appease Typescript.

Update:

A couple of people suggested:

class Navigator extends Component <NavProps>

However, that produces this error:

Type '{}' is missing the following properties from type 'Pick<NavProps, "loggedIn" | "loggingIn">': loggedIn, loggingIn  TS2739

<Router>
22 |

> 23 |         <Navigator />

Not sure if it makes any difference, but here is the component that is embedding NAVIGATOR:

const App = () => (
  <Provider store={store}>
    <Router>

        <Navigator />
            <Switch>
              <Route exact path="/libraries" component={Libraries} />
            </Switch>

    </Router>
  </Provider>
);

export default App;

Ok, I found a suggestion here:

TS2740 Type is missing the following properties from ReadOnly error in React Native with TypeScript app

As strange as it seems from the comments below, the answer is to do it like this:

class Navigator extends Component<any, any>

Even though it doesn't seem right to just stick 'any' in there.

Here is one that is a little clearner:

TS2739 - Type missing in following properties

It suggests making the props optional:

interface NavProps{
    loggedIn?: boolean,
    loggingIn?: boolean
}

class Navigator extends Component<NavProps>

Body:
We can see that in the TypeScript docs here:

class Navigator extends Component<NavProps> {

Here is how it looks on my machine:


问:
How to protect against direct access to images?
I would like to create a web site with many images. But I would like to protect against direct access to images, e.g. direct links to images without visiting the web site.

What is the preferred way to do this? And what are the alternatives with Pros and cons?

I have some ideas (I don't know if they are possible):

File permissions

PHP Sessions

Temporary file names or URLs

HTTP Redirection?

Maybe this isn't practiced on many web sites? E.g. I tried to access a private photo on Facebook without beeing logged in, but I could still visit the photo.

The platform will probably be a Ubuntu machine with NginX and PHP.

答:
There are perfomance issues on above answers.
My solution is to login system is follows.

You can rename the directory of images every hour / day etc.

images/2h4h4h4h4282hdj/182828.png
to something like
images/dhd777rhrje82883/182828.png

You can do this to complete system or to the specific user.

ContentLicense: CC BY-SA 2.5


问:
how do I do an authentication triage in Laravel 6.12?
I am using laravel 6.12 using the Authentication artisan command

php artisan ui vue --auth

I have been following https://laraveldaily.com/auth-login-how-to-check-more-than-just-emailpassword/ website .  I would like to know the steps needed to authenticate with a triage i.e company, email address and password.

I am receiving a duplicate when I add company name, it thinks this is the email address.  Where do you change this? And I am recieving the following error.

BadMethodCallException
Method App\Http\Controllers\Auth\LoginController::company does not exist.

$credentials = $request->only($this->username(), 'password');
 $credentials = array_add($credentials, 'company');

I need to Verify the Company name as part of the authentication process. with email, password & Company. Does anyone know how to authenticate using three authentication credentials?

```<code>use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = RouteServiceProvider::HOME;

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}
</code>```

}
'''

答:
Note: The tutorial you linked shows a bad way of logging in a User using a raw SQL query!. Please use a more standard way.

To login a user using multiple properties do something like this in your Controller method:

```<code>public function login(Request $request)
{
    //... request validation logic

    //take only what is needed to verify login
    $credentials = request(['company', 'email', 'password']);

    //verify login
    if (!Auth::attempt($credentials)) {
        return response()->json([
            'message' => 'Invalid password'
        ], 401);
    }

    //Login user, as you're using Vue I assume you use either JWT or Passport

    $user = $request->user();
    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;
    $token->save();

    return response()->json([
        'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
    ]);
}
</code>```

Body:
I am using laravel 6.12 using the Authentication artisan command

php artisan ui vue --auth

I have been following https://laraveldaily.com/auth-login-how-to-check-more-than-just-emailpassword/ website .  I would like to know the steps needed to authenticate with a triage i.e company, email address and password.

I am receiving a duplicate when I add company name, it thinks this is the email address.  Where do you change this? And I am recieving the following error.

BadMethodCallException
Method App\Http\Controllers\Auth\LoginController::company does not exist.

$credentials = $request->only($this->username(), 'password');
 $credentials = array_add($credentials, 'company');

I need to Verify the Company name as part of the authentication process. with email, password & Company. Does anyone know how to authenticate using three authentication credentials?

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = RouteServiceProvider::HOME;

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}

}
'''

Body:
Note: The tutorial you linked shows a bad way of logging in a User using a raw SQL query!. Please use a more standard way.

To login a user using multiple properties do something like this in your Controller method:

public function login(Request $request)
{
    //... request validation logic

    //take only what is needed to verify login
    $credentials = request(['company', 'email', 'password']);

    //verify login
    if (!Auth::attempt($credentials)) {
        return response()->json([
            'message' => 'Invalid password'
        ], 401);
    }

    //Login user, as you're using Vue I assume you use either JWT or Passport

    $user = $request->user();
    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;
    $token->save();

    return response()->json([
        'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
    ]);
}


问:
EF4.1 (Database First) Generic Repository: Problem with inconsistent data types
I am working on a new application which is using a legacy system's database.  Each table in the database (there are about 600) has a 'Deleted' column to flag whether or not the item should be displayed to users.  In my generic repository, I need to add LINQ expressions to filter out all items with Deleted == 1/True.

The problem I have ran into is that the "Deleted" column has different data types across tables.

It is a tinyint, smallint or bit in any given table.  Theoretically, this should not be much of an issue since the data will always be stored as a 1 or a 0 (well, should be, I suppose, but either way a number of some sort) which can be cast to any of the specific types mentioned above.  I'm just not sure how and/or where to go about casting this.

I created an interface which forces all of the entities to expose this property, but since the types are different, each entity with the different data types will cause issues.  I was hoping (although already knew it wouldn't work) I could change the interface to "object" or "dynamic" which still causes compile time errors, since the EDMX model is creating the data model classes.  I don't want to invest too much time in writing code in the T4 templates if that will not fix the issue.

When I change the EDMX model's entity properties to adhere to a specific datatype, I receive mapping errors ("Member Mapping specific is not valid. The type 'Edm.Byte[]' of member 'Deleted' in type 'MyEntity' is not compatible with 'SqlServer.bit[]' ....)

I doubt I'll be able to change the data types in the tables, since there are many different applications which use this database and I'm sure it will cause problems somewhere.

Has anyone else ran into a similar situation and come up with a working solution?

[EDIT]
I'm going with the solution recommended by Baldy and creating a view to wrap the table and create an additional column which will be used to cast the column to a bit.

答:
You may want to consider an ad-hoc task of converting the actual fields on the table with a T-SQL script.

Have you thought about that?  is there any reason why you couldnt do it?

it may prove to be a good move further down the line...


答:
The problem is caused by that you mistakenly quote NumberOfSections in ORDER BY clause.

You should use as an usual column name without quote.

```<code>Select name,
    (select count(*)
    from teaches
    where instructor.ID = teaches.ID)
    as 'NumberOfSections'
from instructor
where NumberOfSections >= 2 ORDER BY NumberOfSections DESC;
</code>```

Title: Desc Order in SubQueries

Body: With this input, how do I use ORDER BY to get descending order for a subquery? It is not applying to the data in the column.

Body:
The problem is caused by that you mistakenly quote NumberOfSections in ORDER BY clause.

You should use as an usual column name without quote.

Select name,
    (select count(*)
    from teaches
    where instructor.ID = teaches.ID)
    as 'NumberOfSections'
from instructor
where NumberOfSections >= 2 ORDER BY NumberOfSections DESC;


问:
using bash command in perl
i have short bash code

```<code>cat example.txt | grep mail | awk -F, '{print $1}' | awk -F= '{print $2}'
</code>```

I want to use it in perl script, and put its output to an array line by line.
I tried this but did not work

```<code>@array = system('cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}');
</code>```

Thanks for helping...

答:
Try:

```<code>@array = `cat /path/example.txt | grep mail | awk -F, {print \$1} | awk -F= {print \$2}')`;
</code>```

Noting that backticks are used and that the dollar signs need to be escaped as the qx operator will interpolate by default (i.e. it will think that $1 are Perl variables rather than arguments to awk).

Title: using bash command in perl

Body:
i have short bash code

cat example.txt | grep mail | awk -F, '{print $1}' | awk -F= '{print $2}'

I want to use it in perl script, and put its output to an array line by line.
I tried this but did not work

@array = system('cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}');

Thanks for helping...

Body:
Try:

@array = `cat /path/example.txt | grep mail | awk -F, {print \$1} | awk -F= {print \$2}')`;

Noting that backticks are used and that the dollar signs need to be escaped as the qx operator will interpolate by default (i.e. it will think that $1 are Perl variables rather than arguments to awk).


答:
According to my comments above, I have test this and there's no problem at all

```<code>interface NavProps {
  loggedIn: boolean
  loggingIn: boolean
}

class Navigator extends Component <NavProps> {
  public render() {
    const { loggedIn } = this.props
    console.log(loggedIn)
    return null
  }
}

const mapStateToProps = (state: RootReducer): NavProps => {
  const { authentication } = state
  const { loggedIn, loggingIn } = authentication
  return {
    loggedIn,
    loggingIn,
  }
}

export default connect(mapStateToProps, null)(Navigator)
</code>```

except that I don't have the RootReducer type from your question

update: try to write the connect like this, too

```<code>export default connect<NavProps>(mapStateToProps, null)(Navigator)
</code>```

Title: What is the proper way to set the PROPS type?

Body:
According to my comments above, I have test this and there's no problem at all

interface NavProps {
  loggedIn: boolean
  loggingIn: boolean
}

class Navigator extends Component <NavProps> {
  public render() {
    const { loggedIn } = this.props
    console.log(loggedIn)
    return null
  }
}

const mapStateToProps = (state: RootReducer): NavProps => {
  const { authentication } = state
  const { loggedIn, loggingIn } = authentication
  return {
    loggedIn,
    loggingIn,
  }
}

export default connect(mapStateToProps, null)(Navigator)

except that I don't have the RootReducer type from your question

update: try to write the connect like this, too

export default connect<NavProps>(mapStateToProps, null)(Navigator)


问:
How To Present a SKScene from a UIViewController
I am creating this game in SpriteKit.
At first launch, the GameViewController presents another ViewController called the MenuViewController linked with a storyboard.
And in the MenuViewController there is a play button that will present a SKScene called the GameScene.

I figured out how to present the MenuViewController from the GameViewController, but I can't find a way to present the GameScene when the play button is tapped.
In my code, when the button is tapped, nothing actually happens.

GameViewController:

```<code>import UIKit
import SpriteKit

class GameViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {

        let storyBoard: UIStoryboard = UIStoryboard(name: "MenuViewController", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
        self.present(vc, animated: true, completion: nil)

    }

}
</code>```

And in the MenuViewController:

```<code>import UIKit
import SpriteKit

class MenuViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func playButtonTapped(_ sender: Any) {

         if let view = self.view as! SKView? {
            let scene = GameScene(size: view.bounds.size)
            scene.scaleMode = .aspectFill
            view.presentScene(scene)
            view.ignoresSiblingOrder = true
            view.showsFPS = false
            view.showsNodeCount = false
            view.showsPhysics = false

         }
    }

}
</code>```

Also, I got this warning printed into the console:

SKView: ignoreRenderSyncInLayoutSubviews is NO. Call _renderSynchronouslyForTime without handler

I don't know if this is related...

I did set the view of the MenuViewController's storyboard to be equal SKView.
I can't find any way to make the GameScene appear. Nothing happens.

Thanks!

答:
I think I might have found a solution-I didn't present the GameScene directly from the MenuViewController, but instead, when the playButton is pressed I transitioned to the GameViewController and then presented the GameScene from there.

I don't know why it doesn't work in the MenuViewController, but this method works.

Body:
I am creating this game in SpriteKit.
At first launch, the GameViewController presents another ViewController called the MenuViewController linked with a storyboard.
And in the MenuViewController there is a play button that will present a SKScene called the GameScene.

I figured out how to present the MenuViewController from the GameViewController, but I can't find a way to present the GameScene when the play button is tapped.
In my code, when the button is tapped, nothing actually happens.

GameViewController:

import UIKit
import SpriteKit

class GameViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {

        let storyBoard: UIStoryboard = UIStoryboard(name: "MenuViewController", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
        self.present(vc, animated: true, completion: nil)

    }

}

And in the MenuViewController:

import UIKit
import SpriteKit

class MenuViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func playButtonTapped(_ sender: Any) {

         if let view = self.view as! SKView? {
            let scene = GameScene(size: view.bounds.size)
            scene.scaleMode = .aspectFill
            view.presentScene(scene)
            view.ignoresSiblingOrder = true
            view.showsFPS = false
            view.showsNodeCount = false
            view.showsPhysics = false

         }
    }

}

Also, I got this warning printed into the console:

SKView: ignoreRenderSyncInLayoutSubviews is NO. Call _renderSynchronouslyForTime without handler

I don't know if this is related...

I did set the view of the MenuViewController's storyboard to be equal SKView.
I can't find any way to make the GameScene appear. Nothing happens.

Thanks!


问:
App 'can’t be opened because its integrity cannot be verified' on macOS Catalina
Some users reported that my app cannot open in macOS Catalina, with the error message:

MyApp can’t be opened because its integrity cannot be verified.

Is this because of notarization? The app seems to be working on other macOS versions.

答:
This is because of recent changes in macOS Catalina.

```<code>sudo spctl --add "Path_to_flutter/bin/cache/artifacts/libimobiledevice/idevice_id"
</code>```

You might need to reboot the system in order to apply the changes.

You can run a GateKeeper script to fix the issue.

I have published an article with more information how to fix this.

Body:
This is because of recent changes in macOS Catalina.

sudo spctl --add "Path_to_flutter/bin/cache/artifacts/libimobiledevice/idevice_id"

You might need to reboot the system in order to apply the changes.

You can run a GateKeeper script to fix the issue.

I have published an article with more information how to fix this.


问:
Decoding assembly from MSVC 32-bit release (homework). What does no-op do?
Hi heads up this is a homework. I'm given an assembly generated by MSVC 32-bit Release with optimizations on, and I'm supposed to decode it back into C++. I've included the top of the function to the line I'm having problems with. The comments are mine, which I'm wrote while trying to understand this.

Note: Code is supposedly generated from C++. Not traditional ASM.
Note 2: There is one area of undefined behavior in the code.

Here are the lines I'm stuck with

```<code>TheFunction:                            ; TheFunction(int* a, int s);
0F2D4670  push  ebp                     ; Push/clear/save ebp
0F2D4671  mov   ebp,esp                 ; ebp now points to top of stack
0F2D4673  push  ecx                     ; Push/clear/save ecx
0F2D4674  push  ebx                     ; Push/clear/save ebs
0F2D4675  push  esi                     ; Push/clear/save esi

0F2D4676  mov   ebx,edx                         ; ebx = int s
0F2D4678  mov   esi,1                           ; esi = 1
0F2D467D  push  edi  ; calling convention       ; Push/clear/save edi
0F2D467E  mov   edi,dword ptr [a (0F2D95E8h)]   ; edi = a[0]
0F2D4684  cmp   ebx,esi                         ; if(s < 1)
0F2D4686  jl    SomeFunction+3Ch (0F2D46ACh)    ;   Jump to return
0F2D4688  nop   dword ptr [eax+eax]             ; !! <-- No op involving dereferencing?  What does this do?
0F2D4690  mov   eax,dword ptr [edi+esi*4-4]     ; !! <-- edi is *a, while esi is 1. There is no address
here!
..... More code but I've figured these out ....
</code>```

I've more or less got the gist of the function. Its a function that takes a pointer to an int, with an underlying array, and a size. It then goes through each element in the array from last to first, adding to each subsequent one and printing it out. However, I still haven't got the details down and need help

Two questions, both at the end of the code snippet. What does no op on a dereference pointer do, and am I reading the last line in that its attempting to dereference something not in memory?

答:
The nop dword ptr [eax+eax] instruciton does nothing.  It doesn't even access the memory location given by the operand.  It literally performs no operation.

It's just there so the next instruction is aligned to a 16-byte boundary. You'll notice that next instruction address is 0F2D4690 which ends with 0 which means it's 16-byte aligned. This can improve the performance of loops. Somewhere there will be an instruction that jumps back to 0F2D4690 as part of a loop. This particular form of a NOP instruction is used because it encodes a single NOP instruction in 8 bytes.

There is no corresponding C++ code for this instruction.  You shouldn't try to represent it in your C++ code, just ignore it.

Also note that your comment for mov edi,dword ptr [a (0F2D95E8h)] is incorrect.  Instead of being edi = a[0] it's simply edi = a.  The variable a isn't a parameter at all, instead it's a global (or file level static) variable located at memory location 0F2D95E8h. This instruction just loads the value from memory.

Body:
Hi heads up this is a homework. I'm given an assembly generated by MSVC 32-bit Release with optimizations on, and I'm supposed to decode it back into C++. I've included the top of the function to the line I'm having problems with. The comments are mine, which I'm wrote while trying to understand this.

Note: Code is supposedly generated from C++. Not traditional ASM.
Note 2: There is one area of undefined behavior in the code.

Here are the lines I'm stuck with

TheFunction:                            ; TheFunction(int* a, int s);
0F2D4670  push  ebp                     ; Push/clear/save ebp
0F2D4671  mov   ebp,esp                 ; ebp now points to top of stack
0F2D4673  push  ecx                     ; Push/clear/save ecx
0F2D4674  push  ebx                     ; Push/clear/save ebs
0F2D4675  push  esi                     ; Push/clear/save esi

0F2D4676  mov   ebx,edx                         ; ebx = int s
0F2D4678  mov   esi,1                           ; esi = 1
0F2D467D  push  edi  ; calling convention       ; Push/clear/save edi
0F2D467E  mov   edi,dword ptr [a (0F2D95E8h)]   ; edi = a[0]
0F2D4684  cmp   ebx,esi                         ; if(s < 1)
0F2D4686  jl    SomeFunction+3Ch (0F2D46ACh)    ;   Jump to return
0F2D4688  nop   dword ptr [eax+eax]             ; !! <-- No op involving dereferencing?  What does this do?
0F2D4690  mov   eax,dword ptr [edi+esi*4-4]     ; !! <-- edi is *a, while esi is 1. There is no address
here!
..... More code but I've figured these out ....

I've more or less got the gist of the function. Its a function that takes a pointer to an int, with an underlying array, and a size. It then goes through each element in the array from last to first, adding to each subsequent one and printing it out. However, I still haven't got the details down and need help

Two questions, both at the end of the code snippet. What does no op on a dereference pointer do, and am I reading the last line in that its attempting to dereference something not in memory?


问:
looking for an efficient way to add a column to a data frame using an apply function
I am new to Pandas and looking for some inputs on if there is a better way to achieve the following:

I have potentially millions of records of the form:

```<code>>>> s=pd.DataFrame({"col A": pd.Categorical(["typeA", "typeB", "typeC"]),
... "col B": pd.Series(["a.b/c/d/e", "a:b:c:d:e", "a.b.c.d.e"])})
>>> s
   col A      col B
0  typeA  a.b/c/d/e
1  typeB  a:b:c:d:e
2  typeC  a.b.c.d.e
</code>```

I need to add column C to the dataframe which will be a.b for typeA, a for typeB and a for type C. Here is what I have now:

```<code>>>> def parseColB(s):
...     col_split=re.split('[:,/,.]',s)
...     if len(col_split) < 2:
...             return ""
...     return col_split[0]
...
</code>```

I add the new column with the following apply call:

```<code>>>> s = s.assign(ColC = s["col B"].apply(parseColB))
>>> s
   col A      col B ColC
0  typeA  a.b/c/d/e    a
1  typeB  a:b:c:d:e    a
2  typeC  a.b.c.d.e    a
</code>```

Problem with this approach is I get "a" in ColC for typeA rather than "a.b". Is there a way to add the ColC efficiently based on "col A" value?

Tried the suggestion on this being a possible duplicate based on Henry's comment. I have it almost working:

```<code>>>> s=pd.DataFrame({"col A": pd.Categorical(["typeA", "typeB", "typeC"]),
...  "col B": pd.Series(["a.b/c/d/e", "a:b:c:d:e", "a.b.c.d.e"])})
>>> s
   col A      col B
0  typeA  a.b/c/d/e
1  typeB  a:b:c:d:e
2  typeC  a.b.c.d.e
>>> choices = [s['col B'].str.split("/"), s['col B'].str.split(":"), s['col B'].str.split(".")]
>>> conditions = [s['col A'] == 'typeA', s['col A'] == 'typeB', s['col A'] == 'typeC']
>>> s['col C'] = np.select(conditions, choices, default="")
>>> s
   col A      col B            col C
0  typeA  a.b/c/d/e   [a.b, c, d, e]
1  typeB  a:b:c:d:e  [a, b, c, d, e]
2  typeC  a.b.c.d.e  [a, b, c, d, e]
</code>```

Updated choices to use apply and that gives the desired results. Is this the right way or any other optimization is possible?

```<code>>>> choices = [s['col B'].str.split("/").apply(lambda x : x[0]), s['col B'].str.split(":").apply(lambda x : x[0]), s['col B'].str.split(".").apply(lambda x : x[0])]
>>> s['col C'] = np.select(conditions, choices, default="")
>>> s
   col A      col B col C
0  typeA  a.b/c/d/e   a.b
1  typeB  a:b:c:d:e     a
2  typeC  a.b.c.d.e     a
</code>```

答:
You can do it this way.

```<code>s["col C"] = s["col B"].str.split('/|:').apply(lambda x: x[0]).apply(lambda x: ''.join([x.split('\.')[0][0] if (len(x)>3) else x]))
</code>```

Output

```<code>     col A     col B    col C
0   typeA   a.b/c/d/e   a.b
1   typeB   a:b:c:d:e   a
2   typeC   a.b.c.d.e   a
</code>```

Body:
I am new to Pandas and looking for some inputs on if there is a better way to achieve the following:

I have potentially millions of records of the form:

>>> s=pd.DataFrame({"col A": pd.Categorical(["typeA", "typeB", "typeC"]),
... "col B": pd.Series(["a.b/c/d/e", "a:b:c:d:e", "a.b.c.d.e"])})
>>> s
   col A      col B
0  typeA  a.b/c/d/e
1  typeB  a:b:c:d:e
2  typeC  a.b.c.d.e

I need to add column C to the dataframe which will be a.b for typeA, a for typeB and a for type C. Here is what I have now:

>>> def parseColB(s):
...     col_split=re.split('[:,/,.]',s)
...     if len(col_split) < 2:
...             return ""
...     return col_split[0]
...

I add the new column with the following apply call:

>>> s = s.assign(ColC = s["col B"].apply(parseColB))
>>> s
   col A      col B ColC
0  typeA  a.b/c/d/e    a
1  typeB  a:b:c:d:e    a
2  typeC  a.b.c.d.e    a

Problem with this approach is I get "a" in ColC for typeA rather than "a.b". Is there a way to add the ColC efficiently based on "col A" value?

Tried the suggestion on this being a possible duplicate based on Henry's comment. I have it almost working:

>>> s=pd.DataFrame({"col A": pd.Categorical(["typeA", "typeB", "typeC"]),
...  "col B": pd.Series(["a.b/c/d/e", "a:b:c:d:e", "a.b.c.d.e"])})
>>> s
   col A      col B
0  typeA  a.b/c/d/e
1  typeB  a:b:c:d:e
2  typeC  a.b.c.d.e
>>> choices = [s['col B'].str.split("/"), s['col B'].str.split(":"), s['col B'].str.split(".")]
>>> conditions = [s['col A'] == 'typeA', s['col A'] == 'typeB', s['col A'] == 'typeC']
>>> s['col C'] = np.select(conditions, choices, default="")
>>> s
   col A      col B            col C
0  typeA  a.b/c/d/e   [a.b, c, d, e]
1  typeB  a:b:c:d:e  [a, b, c, d, e]
2  typeC  a.b.c.d.e  [a, b, c, d, e]

Updated choices to use apply and that gives the desired results. Is this the right way or any other optimization is possible?

>>> choices = [s['col B'].str.split("/").apply(lambda x : x[0]), s['col B'].str.split(":").apply(lambda x : x[0]), s['col B'].str.split(".").apply(lambda x : x[0])]
>>> s['col C'] = np.select(conditions, choices, default="")
>>> s
   col A      col B col C
0  typeA  a.b/c/d/e   a.b
1  typeB  a:b:c:d:e     a
2  typeC  a.b.c.d.e     a

Body:
You can do it this way.

s["col C"] = s["col B"].str.split('/|:').apply(lambda x: x[0]).apply(lambda x: ''.join([x.split('\.')[0][0] if (len(x)>3) else x]))

Output

     col A     col B    col C
0   typeA   a.b/c/d/e   a.b
1   typeB   a:b:c:d:e   a
2   typeC   a.b.c.d.e   a


问:
the byte string is same in python and c#,but md5 hashcode is different
I want to generate the hash code from a string,e.g."咖啡",but the hashcode I get from python and c# is different,the one from python is what I want

c#

```<code>String str = "咖啡";
MD5 m = MD5.Create();
byte[] data = m.ComputeHash(Encoding.Default.GetBytes(str));
StringBuilder sbuilder = new StringBuilder();
for(int i=0;i<data.Length;i++){
  sbuilder.Append(data[i].ToString("x2"));
}
byte[] hex = Encoding.Default.GetBytes(str);
StringBuilder hex_builder = new StringBuilder();
foreach(byte a in hex){
  hex_builder.Append("{0:x2}",a);
}
//md5 hash code
Response.Write(sbuilder.ToString());
//binary string
Response.Write(hex_builder.ToString());
</code>```

python

```<code>#coding:utf8
str = '咖啡'
m = hashlib.md5()
m.update(str)
#md5 hashcode
print m.hexdigest()
#binary string
print ' '.join(["%02x"%ord(x) for x in str])
</code>```

binary string is e5 92 96 e5 95 a1 both in c# and python

md5 hash code:

(c#)a761914f9760af3c112e24f08dea1b16

(python)3b7daa58a1fecdf5ba4d94d539fbb4d5

答: The string encoding might be different; therefore when you convert string to byte[] you probably get different values. Try printing those to see if they are the same.</p>

Body:
I want to generate the hash code from a string,e.g."咖啡",but the hashcode I get from python and c# is different,the one from python is what I want

c#

String str = "咖啡";
MD5 m = MD5.Create();
byte[] data = m.ComputeHash(Encoding.Default.GetBytes(str));
StringBuilder sbuilder = new StringBuilder();
for(int i=0;i<data.Length;i++){
  sbuilder.Append(data[i].ToString("x2"));
}
byte[] hex = Encoding.Default.GetBytes(str);
StringBuilder hex_builder = new StringBuilder();
foreach(byte a in hex){
  hex_builder.Append("{0:x2}",a);
}
//md5 hash code
Response.Write(sbuilder.ToString());
//binary string
Response.Write(hex_builder.ToString());

python

#coding:utf8
str = '咖啡'
m = hashlib.md5()
m.update(str)
#md5 hashcode
print m.hexdigest()
#binary string
print ' '.join(["%02x"%ord(x) for x in str])

binary string is e5 92 96 e5 95 a1 both in c# and python

md5 hash code:

(c#)a761914f9760af3c112e24f08dea1b16

(python)3b7daa58a1fecdf5ba4d94d539fbb4d5


问:
How to check if all items in a list are of the same type?
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Edit:

I've now tried combining a couple of the answers into a section of the code:

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

答:
The following section of your code always returns False, not True Why? follow the comments

def maxOfThree():
    #Ask users to input values
    # What do you think the data type fo Value1 to 3?
    Value1 = input('Enter the first value here:  \n')
    Value2 = input('Enter the second value here:  \n')
    Value3 = input('Enter the third value here:  \n')
    # When we read any data from user via input() it collect
    # the data in String data type

    #store values in a list
    # Now you stored all the String into list and applying
    # sort operation on Strings
    maxlist = [Value1, Value2, Value3]
    maxlist.sort()

    #Check for integer type across the list:
    # Now the maxlist contains sorted Strings, Now you are
    # comparing it's data type with Int which will always
    # fail and it returns **False**
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

maxOfThree()
```

<p>Example:</p>

<pre class="lang-py prettyprint-override"><code>Input:
Enter the first value here:
text
Enter the second value here:
abc
Enter the third value here:
1233
False -> your are comparing list of Strings to Int data type
         with isinstance(item, int)

Output:
The maximum of these values is:
 text
</code>```

Code:

def maxOfThree():
    #Ask users to input values
    Value1 = input('Enter the first value here:  \n')
    Value2 = input('Enter the second value here:  \n')
    Value3 = input('Enter the third value here:  \n')

    #store values in a list by converting to int
    maxlist = []
    # wrapped the conversion code in try block
    # if any text inputs are given
    try:
        maxlist = [int(each) for each in [Value1, Value2, Value3]]
    except Exception as e:
        print("Couldn't able to convert to integer")
        raise(e)
    maxlist.sort()

    #Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

maxOfThree()
```

Body:
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Edit:

I've now tried combining a couple of the answers into a section of the code:

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

Body:
The following section of your code always returns False, not True Why? follow the comments

def maxOfThree():
    #Ask users to input values
    # What do you think the data type fo Value1 to 3?
    Value1 = input('Enter the first value here:  \n')
    Value2 = input('Enter the second value here:  \n')
    Value3 = input('Enter the third value here:  \n')
    # When we read any data from user via input() it collect
    # the data in String data type

    #store values in a list
    # Now you stored all the String into list and applying
    # sort operation on Strings
    maxlist = [Value1, Value2, Value3]
    maxlist.sort()

    #Check for integer type across the list:
    # Now the maxlist contains sorted Strings, Now you are
    # comparing it's data type with Int which will always
    # fail and it returns **False**
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

maxOfThree()

Example:

Input:
Enter the first value here:
text
Enter the second value here:
abc
Enter the third value here:
1233
False -> your are comparing list of Strings to Int data type
         with isinstance(item, int)

Output:
The maximum of these values is:
 text

Code:

def maxOfThree():
    #Ask users to input values
    Value1 = input('Enter the first value here:  \n')
    Value2 = input('Enter the second value here:  \n')
    Value3 = input('Enter the third value here:  \n')

    #store values in a list by converting to int
    maxlist = []
    # wrapped the conversion code in try block
    # if any text inputs are given
    try:
        maxlist = [int(each) for each in [Value1, Value2, Value3]]
    except Exception as e:
        print("Couldn't able to convert to integer")
        raise(e)
    maxlist.sort()

    #Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

maxOfThree()


问:
Split list into lists by particular value
I have a list:

```<code>['S1', 'S2', 'S6', 'S1', 'S2', 'S3', 'S4', 'S5', 'S1', 'S2', 'S5', 'S1',
 'S2', 'S4', 'S5', 'S1', 'S2', 'S4', 'S5', 'S1', 'S2', 'S3', 'S6']
</code>```

and I want to split by next S1:

```<code>[['S1', 'S2', 'S6']['S1', 'S2', 'S3', 'S4', 'S5'],['S1', 'S2', 'S4', 'S5]...]
</code>```

My code is:

```<code>size = len(steps)
idx_list = [idx + 1 for idx, val in
            enumerate(steps) if val == 'S1']

res = [steps[i: j] for i, j in
        zip([0] + idx_list, idx_list +
        ([size] if idx_list[-1] != size else []))]

print("The list after splitting by a value : " + str(res))
</code>```

It splits the list as:

```<code>[['S1'], ['S2', 'S6', 'S1'], ['S2', 'S3', 'S4', 'S5', 'S1'],
 ['S2', 'S5', 'S1'], ['S2', 'S4', 'S5', 'S1'], ['S2', 'S4', 'S5', 'S1']..
</code>```

Can you please help to rectify it!

Body:
I have a list:

['S1', 'S2', 'S6', 'S1', 'S2', 'S3', 'S4', 'S5', 'S1', 'S2', 'S5', 'S1',
 'S2', 'S4', 'S5', 'S1', 'S2', 'S4', 'S5', 'S1', 'S2', 'S3', 'S6']

and I want to split by next S1:

[['S1', 'S2', 'S6']['S1', 'S2', 'S3', 'S4', 'S5'],['S1', 'S2', 'S4', 'S5]...]

My code is:

size = len(steps)
idx_list = [idx + 1 for idx, val in
            enumerate(steps) if val == 'S1']

res = [steps[i: j] for i, j in
        zip([0] + idx_list, idx_list +
        ([size] if idx_list[-1] != size else []))]

print("The list after splitting by a value : " + str(res))

It splits the list as:

[['S1'], ['S2', 'S6', 'S1'], ['S2', 'S3', 'S4', 'S5', 'S1'],
 ['S2', 'S5', 'S1'], ['S2', 'S4', 'S5', 'S1'], ['S2', 'S4', 'S5', 'S1']..

Can you please help to rectify it!

Body:
You can use itertools.groupby:

from itertools import groupby

lst = ['S1', 'S2', 'S6', 'S1', 'S2', 'S3', 'S4', 'S5', 'S1', 'S2', 'S5', 'S1', 'S2', 'S4', 'S5', 'S1', 'S2', 'S4', 'S5', 'S1', 'S2', 'S3', 'S6']

splitby = 'S1'
res = [[splitby] + list(g) for k, g in groupby(lst, key=lambda x: x != splitby) if k]

# [['S1', 'S2', 'S6'], ['S1', 'S2', 'S3', 'S4', 'S5'], ['S1', 'S2', 'S5'], ['S1', 'S2', 'S4', 'S5'], ['S1', 'S2', 'S4', 'S5'], ['S1', 'S2', 'S3', 'S6']]


答:
You have an off-by-one error. Change the following line:

```<code>idx_list = [idx + 1 for idx, val in
            enumerate(steps) if val == 'S1']
</code>```

to

```<code>idx_list = [idx for idx, val in
            enumerate(steps) if val == 'S1' and idx > 0]
</code>```

The result should then be:

```<code>[['S1', 'S2', 'S6'], ['S1', 'S2', 'S3', 'S4', 'S5'],
 ['S1', 'S2', 'S5'], ['S1', 'S2', 'S4', 'S5'],
 ['S1', 'S2', 'S4', 'S5'], ['S1', 'S2', 'S3', 'S6']]
</code>```

Title: Split list into lists by particular value

Body:
You have an off-by-one error. Change the following line:

idx_list = [idx + 1 for idx, val in
            enumerate(steps) if val == 'S1']

to

idx_list = [idx for idx, val in
            enumerate(steps) if val == 'S1' and idx > 0]

The result should then be:

[['S1', 'S2', 'S6'], ['S1', 'S2', 'S3', 'S4', 'S5'],
 ['S1', 'S2', 'S5'], ['S1', 'S2', 'S4', 'S5'],
 ['S1', 'S2', 'S4', 'S5'], ['S1', 'S2', 'S3', 'S6']]


问:
How to catch HTTP request of python selenium web driver?
I am making a web application with Django-Gunicorn-Nginx. It is a kind of closed community. Therefore at the start of sign-up, authentication by the third-party server is required. Because the third-party server does not provide official auth API, I'm trying to implement module by my self with python selenium.

I have built the module in a python file in Django accounts app directory. When I test the module with the terminal by python3 somemodulename.py, it works perfectly. However, when I import the module(which is a function) in view.py of the accounts app and test with browser, at some point, the third-party app throws an invalid session message. It never happened when I test exactly the same function with the terminal.

So, if there is any way to catch HTTP request that selenium chrome web driver sends, I would like to compare both cases for debugging. How could one get the full HTTP request of Chrome web driver with python selenium, without interfering the process of code?

I am sorry that I could not append the actual code because of the security issue.

答:
Unfortunately, this is not possible using Selenium APIs. A long and boring discussion on why can be found here.

However, there are few workarounds, for example, you can try capturing it using the browser logs. A good example of how to do it is discussed here:
How to get HTTP Response Code using Selenium WebDriver.