问:
Accessing an uploaded file's url
My application for sends and receives data from/to my phone - basically a 2-way communication through the pushbullet API.

I am trying to take a file from my phone and when it's uploaded do something with it, (play it for example if it's an audiofile).

But when I upload the file on my phone and then I list the pushes on my computer and get that exact push, the file-URLL is restricted.

I got following XML error-response showing "Access Denied" as message:

403: Forbidden

How would I approach this?

Here is the code for the application:

def play_sound(url):
    #open the url and then write the contents into a local file
    open("play.mp3", 'wb').write(urlopen(url))

    #playsound through the playsound library
    playsound("play.mp3", False)

pb = pushbullet.Pushbullet(API_KEY, ENCRYPTION_PASSWORD)

pushes = pb.get_pushes()
past_pushes = len(pushes)
while True:
    time.sleep(3)

    # checks for new pushes on the phone and then scans them for commands
    pushes = pb.get_pushes()
    number_pushes = len(pushes) - past_pushes

    if number_pushes != 0:
        past_pushes = (len(pushes) - number_pushes)

        try:
            for i in range(number_pushes):
                push = pushes[i]

                push_body = push.get("body")

                if push_body is not None:
                    play = False

                    if push_body == "play":
                        play = True
                elif play:
                    #only runs if the user has asked to play something
                    #beforehand

                    play = False
                    url = push.get('file_url')

                    #play sound from url
                    #this is where I get my 403: forbidden error
                    if url is not None and ".mp3" in url:
                        play_sound(url)

        except Exception as e:
            print(e)
```

答:
From the docs...

To authenticate for the API, use your access token in a header like Access-Token: <your_access_token_here>.

You're using urlopen(url) without any header information, so the request is denied.

So, try something like the following

```<code>from urllib.request import Request, urlopen

req = Request('https://dl.pushbulletusercontent.com/...')
req.add_header('Access-Token', '<your token here>')
content = urlopen(req).read()

with open('sound.mp3', 'wb') as f:
  f.write(content)
</code>```

Reference: How do I set headers using python's urllib?

Title: Accessing an uploaded file's url

Body:
From the docs...

To authenticate for the API, use your access token in a header like Access-Token: <your_access_token_here>.

You're using urlopen(url) without any header information, so the request is denied.

So, try something like the following

from urllib.request import Request, urlopen

req = Request('https://dl.pushbulletusercontent.com/...')
req.add_header('Access-Token', '<your token here>')
content = urlopen(req).read()

with open('sound.mp3', 'wb') as f:
  f.write(content)

Reference: How do I set headers using python's urllib?


来源: stackexchange

问:
Hebrew send to google spreadsheet from PowerShell Hebrew correctly
Please help.
In console look hebrew correct but in spreadsheet is not correctenter image description here

```<code>    $import = New-Object System.Collections.ArrayList($null)
$import.Add( @("route_id"))
$import.Add( @( 'אבא אבן 1 הרצליה' ))  | Out-NULL

try {

   $Response = Set-GSheetData -accessToken $accessToken -rangeA1 "A1:X$($import.Count)" -sheetName "23-07-21" -spreadSheetID $SpreadsheetID -values $import -Verbose
   $Response | ConvertTo-Json

} catch {
    $err = $_.Exception
    $err | Select-Object -Property *
    "Response: "
    $err.Response
    }
</code>```

答:
Hebrew might not be supported in Sheets, you would need to install a font. You can try with this one

https://fonts.google.com/noto/specimen/Noto+Sans+Hebrew?query=hebrew

Update

After testing using the Rest API, it works, so the issue might be related on how the PowerShell process hebrew characters.

I've found some information on how to process hebrew characters in the Windows Powershell

```<code>[Console]::OutputEncoding = [Text.Encoding]::GetEncoding(1255)
</code>```

Make sure the console is outputting the right characters and the POST a request to Google Sheets

ContentLicense: CC BY-SA 4.0

Body:
Please help.
In console look hebrew correct but in spreadsheet is not correctenter image description here

    $import = New-Object System.Collections.ArrayList($null)
$import.Add( @("route_id"))
$import.Add( @( 'אבא אבן 1 הרצליה' ))  | Out-NULL

try {

   $Response = Set-GSheetData -accessToken $accessToken -rangeA1 "A1:X$($import.Count)" -sheetName "23-07-21" -spreadSheetID $SpreadsheetID -values $import -Verbose
   $Response | ConvertTo-Json

} catch {
    $err = $_.Exception
    $err | Select-Object -Property *
    "Response: "
    $err.Response
    }

Body:
Hebrew might not be supported in Sheets, you would need to install a font. You can try with this one

https://fonts.google.com/noto/specimen/Noto+Sans+Hebrew?query=hebrew

Update

After testing using the Rest API, it works, so the issue might be related on how the PowerShell process hebrew characters.

I've found some information on how to process hebrew characters in the Windows Powershell

[Console]::OutputEncoding = [Text.Encoding]::GetEncoding(1255)

Make sure the console is outputting the right characters and the POST a request to Google Sheets


问:
Undefined reference for TicTacToe
I've got this file where it seems to be an undefined reference but I don't know why, everything it seems correct to me. Someone can help me?

This is the error:

```<code>g++ -c driver.cpp -std=c++11 -pedantic -Wall
g++ -o driver driver.o
/usr/bin/ld: driver.o: in function `main':
driver.cpp:(.text+0x23): undefined reference to `TicTacToe::TicTacToe()'
/usr/bin/ld: driver.cpp:(.text+0x2f): undefined reference to `TicTacToe::makeMove()'
collect2: error: ld returned 1 exit status
make: *** [makefile:2: driver] Error 1
</code>```

And these are the files I'm using:

The driver program:

```<code>// driver.cpp: use of TicTacToe class
#include "TicTacToe.h" // include definition of class TicTacToe

int main() {
    TicTacToe g; // creates object g of class TicTacToe
    g.makeMove(); // invokes function makeMove
}
</code>```

This is the class:

```<code>// TicTacToe.h
#ifndef TICTACTOE_H
#define TICTACTOE_H
#include <array>

class TicTacToe {
    private:
        enum Status {WIN, DRAW, CONTINUE}; // enumeration constants
        std::array<std::array<int, 3>, 3> board;
    public:
        TicTacToe(); // default constructor
        void makeMove(); // make move
        void printBoard() const; // print board
        bool validMove(int, int) const; // validate move
        bool xoMove(int); // x o move
        Status gameStatus() const; // game status
};

#endif
</code>```

These are the class function members:

```<code>// TicTacToe.cpp
// Member-function defnitions for class TicTacToe.
#include <iostream>
#include <iomanip>
#include "TicTacToe.h" // include definition of class TicTacToe
using std::cout;
using std::cin;
using std::setw;

TicTacToe::TicTacToe() {
    for (int j{0}; j < 3; ++j) { // initialize board
        for (int k{0}; k < 3; ++k) {
            board[j][k] = ' ';
        }
    }
}

void TicTacToe::makeMove() {
    printBoard();

    while (true) {
        if (xoMove('X')) {
            break;
        }
        else if (xoMove('O')) {
            break;
        }
    }
}

void TicTacToe::printBoard() const {
    cout << "   0    1    2\n\n";

    for (int r{0}; r < 3; ++r) {
        cout << r;

        for (int c = 0; c < 3; ++r) {
            cout << setw(3) << static_cast< char > (board[r][c]);

            if (c != 2) {
                cout << " |";
            }
        }

        if (r != 2) {
            cout << "\n ____|____|____\n     |    |    \n";
        }
    }

    cout << "\n\n";
}

bool TicTacToe::xoMove(int symbol) {
    int x;
    int y;

    do {
        cout << "Player " << static_cast<char>(symbol) << " enter move: ";
        cin >> x >> y;
        cout << '\n';
    } while (!validMove(x, y));

    board[x][y] = symbol;
    printBoard();
    Status xoStatus = gameStatus();

    if (xoStatus == WIN) {
        cout << "Player " << static_cast<char>(symbol) << " wins!\n";
        return true;
    }
    else if (xoStatus == DRAW) {
        cout << "Game is draw.\n";
        return true;
    }
    else { // CONTINUE
        return false;
    }
}

bool TicTacToe::validMove(int r, int c) const {
    return r >= 0 && r < 3 && c >= 0 && c < 3 && board[r][c] == ' ';
}

// must specify that type Status is part of the TicTacToe class.
TicTacToe::Status TicTacToe::gameStatus() const {
    // check for a win on diagonals
    if (board[0][0] != ' ' && board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
        return WIN;
    }
    else if (board[2][0] != ' ' && board[2][0] == board[1][1] && board[2][0] == board[0][2]) {
        return WIN;
    }

    // check for win in rows
    for (int a{0}; a < 3; ++a) {
        if (board[a][0] != ' ' && board[a][0] == board[a][1] && board[a][0] == board[a][2]) {
            return WIN;
        }
    }

    // check for win in columns
    for (int a{0}; a < 3; ++a) {
        if (board[0][a] != ' ' && board[0][a] == board[1][a] && board[0][a] == board[2][a]) {
            return WIN;
        }
    }

    // check for a completed game
    for (int r{0}; r < 3; ++r) {
        for (int c{0}; c < 3; ++c) {
            if (board[r][c] == ' ') {
                return CONTINUE; // game is not finished
            }
        }
    }

    return DRAW; // game is a draw
}
</code>```

It's probably something stupid but I don't know what I have to look for.

答:
step by step:

g++ -c driver.cpp TicTacToe.cpp -std=c++11 -pedantic -Wall

g++ -o driver driver.o TicTacToe.o

./driver

Title: Undefined reference for TicTacToe

Body:
I've got this file where it seems to be an undefined reference but I don't know why, everything it seems correct to me. Someone can help me?

This is the error:

g++ -c driver.cpp -std=c++11 -pedantic -Wall
g++ -o driver driver.o
/usr/bin/ld: driver.o: in function `main':
driver.cpp:(.text+0x23): undefined reference to `TicTacToe::TicTacToe()'
/usr/bin/ld: driver.cpp:(.text+0x2f): undefined reference to `TicTacToe::makeMove()'
collect2: error: ld returned 1 exit status
make: *** [makefile:2: driver] Error 1

And these are the files I'm using:

The driver program:

// driver.cpp: use of TicTacToe class
#include "TicTacToe.h" // include definition of class TicTacToe

int main() {
    TicTacToe g; // creates object g of class TicTacToe
    g.makeMove(); // invokes function makeMove
}

This is the class:

// TicTacToe.h
#ifndef TICTACTOE_H
#define TICTACTOE_H
#include <array>

class TicTacToe {
    private:
        enum Status {WIN, DRAW, CONTINUE}; // enumeration constants
        std::array<std::array<int, 3>, 3> board;
    public:
        TicTacToe(); // default constructor
        void makeMove(); // make move
        void printBoard() const; // print board
        bool validMove(int, int) const; // validate move
        bool xoMove(int); // x o move
        Status gameStatus() const; // game status
};

#endif

These are the class function members:

// TicTacToe.cpp
// Member-function defnitions for class TicTacToe.
#include <iostream>
#include <iomanip>
#include "TicTacToe.h" // include definition of class TicTacToe
using std::cout;
using std::cin;
using std::setw;

TicTacToe::TicTacToe() {
    for (int j{0}; j < 3; ++j) { // initialize board
        for (int k{0}; k < 3; ++k) {
            board[j][k] = ' ';
        }
    }
}

void TicTacToe::makeMove() {
    printBoard();

    while (true) {
        if (xoMove('X')) {
            break;
        }
        else if (xoMove('O')) {
            break;
        }
    }
}

void TicTacToe::printBoard() const {
    cout << "   0    1    2\n\n";

    for (int r{0}; r < 3; ++r) {
        cout << r;

        for (int c = 0; c < 3; ++r) {
            cout << setw(3) << static_cast< char > (board[r][c]);

            if (c != 2) {
                cout << " |";
            }
        }

        if (r != 2) {
            cout << "\n ____|____|____\n     |    |    \n";
        }
    }

    cout << "\n\n";
}

bool TicTacToe::xoMove(int symbol) {
    int x;
    int y;

    do {
        cout << "Player " << static_cast<char>(symbol) << " enter move: ";
        cin >> x >> y;
        cout << '\n';
    } while (!validMove(x, y));

    board[x][y] = symbol;
    printBoard();
    Status xoStatus = gameStatus();

    if (xoStatus == WIN) {
        cout << "Player " << static_cast<char>(symbol) << " wins!\n";
        return true;
    }
    else if (xoStatus == DRAW) {
        cout << "Game is draw.\n";
        return true;
    }
    else { // CONTINUE
        return false;
    }
}

bool TicTacToe::validMove(int r, int c) const {
    return r >= 0 && r < 3 && c >= 0 && c < 3 && board[r][c] == ' ';
}

// must specify that type Status is part of the TicTacToe class.
TicTacToe::Status TicTacToe::gameStatus() const {
    // check for a win on diagonals
    if (board[0][0] != ' ' && board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
        return WIN;
    }
    else if (board[2][0] != ' ' && board[2][0] == board[1][1] && board[2][0] == board[0][2]) {
        return WIN;
    }

    // check for win in rows
    for (int a{0}; a < 3; ++a) {
        if (board[a][0] != ' ' && board[a][0] == board[a][1] && board[a][0] == board[a][2]) {
            return WIN;
        }
    }

    // check for win in columns
    for (int a{0}; a < 3; ++a) {
        if (board[0][a] != ' ' && board[0][a] == board[1][a] && board[0][a] == board[2][a]) {
            return WIN;
        }
    }

    // check for a completed game
    for (int r{0}; r < 3; ++r) {
        for (int c{0}; c < 3; ++c) {
            if (board[r][c] == ' ') {
                return CONTINUE; // game is not finished
            }
        }
    }

    return DRAW; // game is a draw
}

It's probably something stupid but I don't know what I have to look for.


问:
setup letsencrypt ClusterIssuer with terraform
i have a terraform config that create a kubernetes(GKE) on GCP, install ingress and cert-manager using Helm.
the only part missing is the letsencrypt ClusterIssuer (when i deploy the letsencrypt.yaml manually all works fine).

my Terraform config:

```<code># provider
provider "kubernetes" {
  host                   = google_container_cluster.runners.endpoint
  cluster_ca_certificate = base64decode(google_container_cluster.runners.master_auth.0.cluster_ca_certificate)
  token                  = data.google_client_config.current.access_token
}

provider "helm" {
  kubernetes {
      host                   = google_container_cluster.runners.endpoint
      cluster_ca_certificate = base64decode(google_container_cluster.runners.master_auth.0.cluster_ca_certificate)
      token                  = data.google_client_config.current.access_token
  }
}

# create namespace for ingress controller
resource "kubernetes_namespace" "ingress" {
  metadata {
    name = "ingress"
  }
}
# deploy ingress controller
resource "helm_release" "ingress" {
  name       = "ingress"
  namespace = kubernetes_namespace.ingress.metadata[0].name

  repository = "https://kubernetes.github.io/ingress-nginx"
  chart      = "ingress-nginx"

  values = [
    "${file("./helm_values/ingress.yaml")}"
  ]
  set {
    name  = "controller.service.loadBalancerIP"
    value = google_compute_address.net_runner.address
  }
}

#create namespace for cert mananger
resource "kubernetes_namespace" "cert" {
  metadata {
    name = "cert-manager"
  }
}

#deploy cert maanger
resource "helm_release" "cert" {
  name       = "cert-manager"
  namespace = kubernetes_namespace.cert.metadata[0].name
  repository = "https://charts.jetstack.io"
  chart      = "cert-manager"
  depends_on = ["helm_release.ingress"]
  set {
    name  = "version"
    value = "v1.4.0"
  }
  set {
    name  = "installCRDs"
    value = "true"
  }
}

</code>```

my letsencrypt.yaml:

```<code>apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    email: example@example.com
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - http01:
        ingress:
          class: nginx
</code>```

any idea how to deploy the ClusterIssuer using terraform?

答:
I recently did this most successfully using the Terraform tool tfk8s to migrate yaml files. You can also use Terraform yamldecode.

Test your yaml files and make sure they are working exactly like you want before using the tool.

Using tfk8s, run tfk8s cluster-issuer.yaml -o cluster-issuer.tf This will create a working kubernetes_manifest resource.

Here is an example of my entire terraform script that installs it along with CRDs and ClusterIssuer.

```<code>resource "helm_release" "cert-manager" {
  name       = "cert-manager"
  repository = "https://charts.jetstack.io"
  chart      = "cert-manager"
  version    = "1.7.1"

  namespace        = "cert-manager"
  create_namespace = true

  #values = [file("cert-manager-values.yaml")]

  set {
    name  = "installCRDs"
    value = "true"
  }

}

resource "kubernetes_manifest" "clusterissuer_letsencrypt_prod" {
  manifest = {
    "apiVersion" = "cert-manager.io/v1"
    "kind" = "ClusterIssuer"
    "metadata" = {
      "name" = "letsencrypt-prod"
    }
    "spec" = {
      "acme" = {
        "email" = "myemail@email.com"
        "privateKeySecretRef" = {
          "name" = "letsencrypt-prod"
        }
        "server" = "https://acme-v02.api.letsencrypt.org/directory"
        "solvers" = [
          {
            "http01" = {
              "ingress" = {
                "class" = "nginx"
              }
            }
          },
        ]
      }
    }
  }
}
</code>```

NOTE This tool creates a resource type kubernetes_manifest, and Terraform docs state that it's not a stable resource to use with an initial apply command. In other words, create the cluster, etc first, then add the files and apply again. Otherwise, you need to manually migrate each kubernetes_manifest into its own dedicated resource type (deployment, service, etc).

Body:
i have a terraform config that create a kubernetes(GKE) on GCP, install ingress and cert-manager using Helm.
the only part missing is the letsencrypt ClusterIssuer (when i deploy the letsencrypt.yaml manually all works fine).

my Terraform config:

# provider
provider "kubernetes" {
  host                   = google_container_cluster.runners.endpoint
  cluster_ca_certificate = base64decode(google_container_cluster.runners.master_auth.0.cluster_ca_certificate)
  token                  = data.google_client_config.current.access_token
}

provider "helm" {
  kubernetes {
      host                   = google_container_cluster.runners.endpoint
      cluster_ca_certificate = base64decode(google_container_cluster.runners.master_auth.0.cluster_ca_certificate)
      token                  = data.google_client_config.current.access_token
  }
}

# create namespace for ingress controller
resource "kubernetes_namespace" "ingress" {
  metadata {
    name = "ingress"
  }
}
# deploy ingress controller
resource "helm_release" "ingress" {
  name       = "ingress"
  namespace = kubernetes_namespace.ingress.metadata[0].name

  repository = "https://kubernetes.github.io/ingress-nginx"
  chart      = "ingress-nginx"

  values = [
    "${file("./helm_values/ingress.yaml")}"
  ]
  set {
    name  = "controller.service.loadBalancerIP"
    value = google_compute_address.net_runner.address
  }
}

#create namespace for cert mananger
resource "kubernetes_namespace" "cert" {
  metadata {
    name = "cert-manager"
  }
}

#deploy cert maanger
resource "helm_release" "cert" {
  name       = "cert-manager"
  namespace = kubernetes_namespace.cert.metadata[0].name
  repository = "https://charts.jetstack.io"
  chart      = "cert-manager"
  depends_on = ["helm_release.ingress"]
  set {
    name  = "version"
    value = "v1.4.0"
  }
  set {
    name  = "installCRDs"
    value = "true"
  }
}

my letsencrypt.yaml:

apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    email: example@example.com
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - http01:
        ingress:
          class: nginx

any idea how to deploy the ClusterIssuer using terraform?

Body:
I recently did this most successfully using the Terraform tool tfk8s to migrate yaml files. You can also use Terraform yamldecode.

Test your yaml files and make sure they are working exactly like you want before using the tool.

Using tfk8s, run tfk8s cluster-issuer.yaml -o cluster-issuer.tf This will create a working kubernetes_manifest resource.

Here is an example of my entire terraform script that installs it along with CRDs and ClusterIssuer.

resource "helm_release" "cert-manager" {
  name       = "cert-manager"
  repository = "https://charts.jetstack.io"
  chart      = "cert-manager"
  version    = "1.7.1"

  namespace        = "cert-manager"
  create_namespace = true

  #values = [file("cert-manager-values.yaml")]

  set {
    name  = "installCRDs"
    value = "true"
  }

}

resource "kubernetes_manifest" "clusterissuer_letsencrypt_prod" {
  manifest = {
    "apiVersion" = "cert-manager.io/v1"
    "kind" = "ClusterIssuer"
    "metadata" = {
      "name" = "letsencrypt-prod"
    }
    "spec" = {
      "acme" = {
        "email" = "myemail@email.com"
        "privateKeySecretRef" = {
          "name" = "letsencrypt-prod"
        }
        "server" = "https://acme-v02.api.letsencrypt.org/directory"
        "solvers" = [
          {
            "http01" = {
              "ingress" = {
                "class" = "nginx"
              }
            }
          },
        ]
      }
    }
  }
}

NOTE This tool creates a resource type kubernetes_manifest, and Terraform docs state that it's not a stable resource to use with an initial apply command. In other words, create the cluster, etc first, then add the files and apply again. Otherwise, you need to manually migrate each kubernetes_manifest into its own dedicated resource type (deployment, service, etc).


问:
truffle migrate only migrating first contract, not the second
the command "truffle migrate" works properly (no errors) but only migrates "Migrations.sol". It does not even attempt to migrate with 2_deploy_contracts.js

1_initial_migration.js :

```<code>var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};
</code>```

Migrations.sol:

```<code>enter code herepragma solidity ^0.4.25;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  function Migration() public {
    owner = msg.sender;
  }

  function setCompleted(uint completed) restricted public{
    last_completed_migration = completed;
  }

  function upgrade(address new_address) restricted public{
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}
</code>```

2_deploy_contracts.js:

```<code>var Election = artifacts.require("./Election.sol");

module.exports = function(deployer) {
  deployer.deploy(Election);
};
</code>```

Election.sol:

```<code>pragma solidity ^0.4.25;

contract Election {
  // Store candidate
  // Read candidate
  string public candidate;

  // Constructor
  // Our constructor will be run when the contract gets deployed, so must be public
  constructor() public{
      candidate = "Candidate 1";
  }
}
</code>```

答: Solution: I deleted my project folder and rebuilt it. This fixed it. Not sure exactly what the issue was.</p>

Body:
the command "truffle migrate" works properly (no errors) but only migrates "Migrations.sol". It does not even attempt to migrate with 2_deploy_contracts.js

1_initial_migration.js :

var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

Migrations.sol:

enter code herepragma solidity ^0.4.25;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  function Migration() public {
    owner = msg.sender;
  }

  function setCompleted(uint completed) restricted public{
    last_completed_migration = completed;
  }

  function upgrade(address new_address) restricted public{
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}

2_deploy_contracts.js:

var Election = artifacts.require("./Election.sol");

module.exports = function(deployer) {
  deployer.deploy(Election);
};

Election.sol:

pragma solidity ^0.4.25;

contract Election {
  // Store candidate
  // Read candidate
  string public candidate;

  // Constructor
  // Our constructor will be run when the contract gets deployed, so must be public
  constructor() public{
      candidate = "Candidate 1";
  }
}


问:
Hashing and salting a password field
I have been tossing around the question of how to store the passwords in my DB for some time now. This is my first time at making a secure application with a web login, so i wanted to set up some good practices.

First, i read up on hashing and salting. It seems that the idea is...

Get hashing algorithm

Get password from user

Add 'salt' to plain text password from user

hash the entire password (including salt)

Store the salt in the db so that you can retrieve it later (for verification of PSWD)

And that got me thinking... If a hacker knows your salt (because it is stored in the DB somewhere, maybe a column called this_is_not_the_salt_ur_looking_for or something equally ambiguous) they can re-generate the password dictionary and gain access.

Then i had an idea. What if you stored your salt inside the hashed password field. So follow steps 1-4 (randomly generating the salt), then in step 5, insert the salt in the password somewhere known by the password interpreting class or service:

xxxxxsaltvaluexxxxxxxxxxxxxxxx

where x is the hashed string values. Can anyone see any issues with this? is it just completely unnecessary?

Answer:

There is no reason why this couldnt be done. As Yahia states, other methods of securing a password include double (or n) hashing. On another note, BCrypt looks like a good method of stopping brute force attacks almost entirely, but I couldnt find a trusted library for C#

Thanks!

TTD

答:
Just hash the Password and save the Hash value in your Database, once the User logs in again you calculate the Hash value of the passwort he enteres and compare it with the one saved in your Database, you dont need to know the password. a Hacker wouldnt be able to get the password if he gets the Hashvalue.

If you Use Salting you will increase security by saving the Salt and the Hash value it belongs to, the end value is calculated using the generated salt combined with the password from which the hash value was calculated, the password is not saved in your database but only the calculated Hash value, it means an evtl. Hacker cant do anything having only the Hash value and Salt.

Read this

ContentLicense: CC BY-SA 3.0

Title: Hashing and salting a password field


问:
AWS Lambda + API integration returning as plain text instead of a downloadable .csv
Im working on a basic API lambda function written in Node.js with Api gateway integration where my goal is to get a file from S3 as a downloadable object (in this case its a .csv file). The API works but it returns as a plain text inside the browser and the data does not look like the data inside the csv.

I don't get any errors so I don't understand where my problem lies. Any thoughts? Thanks!

This is the node.js code:

```<code>console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = async (event, context) => {
const params = {
    Bucket: 'testing-api-lambda-s3-jfr',
    Key: 'sample-file-testing.csv',
};

return new Promise((resolve, reject) => {
  s3.getObject(params, function (err, data) {
    if (err) {
      reject({
        statusCode: 500,
        error: JSON.stringify(err)
      });
    }
  resolve({
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "text/csv"
    },
    body: data
  });

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

Api gatewayflow:

API call returns like this instead of a downloadable .csv file:

答:
Convert the S3 Buffer data to a string, which the API Gateway proxy response expects.  Return body: dataString in the response.

const dataString = data.Body.toString('utf-8'); // set encoding as necessary
```
<p>Add a Content-Disposition header to your response to get the desired file download behaviour:</p>
<pre class="lang-js prettyprint-override"><code>'Content-Disposition': 'attachment; filename=download.csv'
</code>```

Body:
Im working on a basic API lambda function written in Node.js with Api gateway integration where my goal is to get a file from S3 as a downloadable object (in this case its a .csv file). The API works but it returns as a plain text inside the browser and the data does not look like the data inside the csv.

I don't get any errors so I don't understand where my problem lies. Any thoughts? Thanks!

This is the node.js code:

console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = async (event, context) => {
const params = {
    Bucket: 'testing-api-lambda-s3-jfr',
    Key: 'sample-file-testing.csv',
};

return new Promise((resolve, reject) => {
  s3.getObject(params, function (err, data) {
    if (err) {
      reject({
        statusCode: 500,
        error: JSON.stringify(err)
      });
    }
  resolve({
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "text/csv"
    },
    body: data
  });

  });
});
 };

Api gatewayflow:

API call returns like this instead of a downloadable .csv file:

Body:
Convert the S3 Buffer data to a string, which the API Gateway proxy response expects.  Return body: dataString in the response.

const dataString = data.Body.toString('utf-8'); // set encoding as necessary

Add a Content-Disposition header to your response to get the desired file download behaviour:

'Content-Disposition': 'attachment; filename=download.csv'


问:
I am able to click on WebElement from List of QAFWebElements in DEBUG mode but unable to do the same in runtime mode
I am trying to select departure airport from list of airports that are appeared in a search result.

Stored all airports from the search results in QAFWebElement List Variable
Iterated through the List of Airport WebElements and Click on the Airport that matches the airport code given
my method setup appears to be correct. Not Sure why It is not selecting the airport. check the below method and also attached screenshot.

```<code>    @QAFTestStep(description = "User enters departure airport {dAirPort}")
    public void enterDepartureAirport(String dAirPort) {

            QAFExtendedWebDriver objDriver = getDriver();
            BookingPage bookingpage = new BookingPage();
            bookingpage.getAirPortSearchTextBox().sendKeys(dAirPort);

             List<QAFWebElement> depAirportList = objDriver.getElements(By.xpath("//*[@id=\"airport-serach-panel\"]/div/div[2]/div/ul/li/a/span[2]"));

             for(QAFWebElement airPort:depAirportList) {
                     if(airPort.getText().contains(dAirPort)) {
                             System.out.println(airPort.getText().contains(dAirPort));
                             System.out.println(airPort.getText());
                             airPort.click();
                     }
             }
             Assert.assertTrue("Script failed to Select Departure Airport",bookingpage.getAirPortSearchTextBox().verifyNotPresent());
    }
</code>```

Lets me know if anyone see an issue with the method

答:
possibly in normal execution it goes fast didn't wait for list to load. You can add wait for visible  or instead of list use element like this:

```<code>bookingpage.getAirPortSearchTextBox().sendKeys(dAirPort);

objDriver.findElement("xpath=//*[@id=\"airport-serach-panel\"]//a[contains(.,'"+dAirPort+"')]").click();
</code>```

The best efficient way in such case is creating custom component.

Body:
I am trying to select departure airport from list of airports that are appeared in a search result.

Stored all airports from the search results in QAFWebElement List Variable
Iterated through the List of Airport WebElements and Click on the Airport that matches the airport code given
my method setup appears to be correct. Not Sure why It is not selecting the airport. check the below method and also attached screenshot.

    @QAFTestStep(description = "User enters departure airport {dAirPort}")
    public void enterDepartureAirport(String dAirPort) {

            QAFExtendedWebDriver objDriver = getDriver();
            BookingPage bookingpage = new BookingPage();
            bookingpage.getAirPortSearchTextBox().sendKeys(dAirPort);

             List<QAFWebElement> depAirportList = objDriver.getElements(By.xpath("//*[@id=\"airport-serach-panel\"]/div/div[2]/div/ul/li/a/span[2]"));

             for(QAFWebElement airPort:depAirportList) {
                     if(airPort.getText().contains(dAirPort)) {
                             System.out.println(airPort.getText().contains(dAirPort));
                             System.out.println(airPort.getText());
                             airPort.click();
                     }
             }
             Assert.assertTrue("Script failed to Select Departure Airport",bookingpage.getAirPortSearchTextBox().verifyNotPresent());
    }

Lets me know if anyone see an issue with the method

Body:
possibly in normal execution it goes fast didn't wait for list to load. You can add wait for visible  or instead of list use element like this:

bookingpage.getAirPortSearchTextBox().sendKeys(dAirPort);

objDriver.findElement("xpath=//*[@id=\"airport-serach-panel\"]//a[contains(.,'"+dAirPort+"')]").click();

The best efficient way in such case is creating custom component.


问:
in Powershell, how to pass $args of type string[] to a "function param()" (I dont want to pass a @{} of type Hashtable to the function)
In Powershell, how to pass $args of type string[] to a "function param()"... see code below, it doesn't work...

(Note: I dont want to  pass a hash @{} of type Hashtable to the function as required by splatting.  I want to pass a string[] type as arguments to function param)...

```<code># FILE: run1.ps1
function run1{
   param(
       [switch]$go,
       [string]$sim,
       [switch]$rec
   )

   write-host "go:  $go"
   write-host "sim: $sim"
   write-host "rec: $rec"
}

write-host ""
foreach ($a in $args) {
    write-host "a: $a"
}
write-host ""

run1 $args

</code>```
```<code>
PS> ./run1.ps1

a: -go
a: -rec:
a: dfsdf
a: -rec

go:  False
sim: -go -rec: dfsdf -rec
rec: False
</code>```

答:
```<code>function run1{
   param(
       [switch]$go,
       [string]$sim,
       [switch]$rec
   )

   write-host "go:  $go"
   write-host "sim: $sim"
   write-host "rec: $rec"
}

$cmd = "run1 $args"
write-host "cmd: $cmd"
invoke-expression "$cmd"
</code>```
```<code>PS> run1.ps1 -go -sim:asdfasdf +rec

PS> run1.ps1 -go -sim:asdfasdf -rec
</code>```
```<code></code>```

Body:
In Powershell, how to pass $args of type string[] to a "function param()"... see code below, it doesn't work...

(Note: I dont want to  pass a hash @{} of type Hashtable to the function as required by splatting.  I want to pass a string[] type as arguments to function param)...

# FILE: run1.ps1
function run1{
   param(
       [switch]$go,
       [string]$sim,
       [switch]$rec
   )

   write-host "go:  $go"
   write-host "sim: $sim"
   write-host "rec: $rec"
}

write-host ""
foreach ($a in $args) {
    write-host "a: $a"
}
write-host ""

run1 $args

PS> ./run1.ps1

a: -go
a: -rec:
a: dfsdf
a: -rec

go:  False
sim: -go -rec: dfsdf -rec
rec: False

Body:
function run1{
   param(
       [switch]$go,
       [string]$sim,
       [switch]$rec
   )

   write-host "go:  $go"
   write-host "sim: $sim"
   write-host "rec: $rec"
}

$cmd = "run1 $args"
write-host "cmd: $cmd"
invoke-expression "$cmd"

PS> run1.ps1 -go -sim:asdfasdf +rec

PS> run1.ps1 -go -sim:asdfasdf -rec


问:
Carbon.php The separation symbol could not be found Data missing
First, I retrieve all the records,

```<code>//get inventory items
$inv = inventory::all();
</code>```

and then I loop on the retrieved records and modify the created_at and updated_at data to make it more human readable date.

```<code>foreach($inv as $i){
    $i->created_at = date("M d, Y",strtotime($i->created_at));
    $i->updated_at = date("M d, Y",strtotime($i->updated_at));
}
</code>```

but it returns me this error,

InvalidArgumentException in Carbon.php line 425: Unexpected data
  found. Unexpected data found. The separation symbol could not be found
  Data missing

any ideas, help, clues, suggestions, recommendations please?

here's my model

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class inventory extends Model
{
    protected $table = "inventory";
    protected $primaryKey = "item_id";
    public $incrementing = false;

    public function profile(){
        return $this->belongsTo('App\profile','username');
    }
    public function inventory_images(){
        return $this->hasMany('App\inventory_images','item_id');
    }
}
</code>```

and in blade, I can just use

```<code>{{ date("M d, Y",strtotime($i->created_at)) }}

{{ date("M d, Y",strtotime($i->updated_at)) }}
</code>```

and it work just fine.

答:
So simple error please do  like this

check your date format (d-m-Y)  then use the same format

```<code>$shipDate = Carbon::createFromFormat('d-m-Y H:i',Carbon::parse($request->date)->format('d-m-Y') . " " . $request->time);
</code>```

Body:
First, I retrieve all the records,

//get inventory items
$inv = inventory::all();

and then I loop on the retrieved records and modify the created_at and updated_at data to make it more human readable date.

foreach($inv as $i){
    $i->created_at = date("M d, Y",strtotime($i->created_at));
    $i->updated_at = date("M d, Y",strtotime($i->updated_at));
}

but it returns me this error,

InvalidArgumentException in Carbon.php line 425: Unexpected data
  found. Unexpected data found. The separation symbol could not be found
  Data missing

any ideas, help, clues, suggestions, recommendations please?

here's my model

namespace App;

use Illuminate\Database\Eloquent\Model;

class inventory extends Model
{
    protected $table = "inventory";
    protected $primaryKey = "item_id";
    public $incrementing = false;

    public function profile(){
        return $this->belongsTo('App\profile','username');
    }
    public function inventory_images(){
        return $this->hasMany('App\inventory_images','item_id');
    }
}

and in blade, I can just use

{{ date("M d, Y",strtotime($i->created_at)) }}

{{ date("M d, Y",strtotime($i->updated_at)) }}

and it work just fine.

Body:
So simple error please do  like this

check your date format (d-m-Y)  then use the same format

$shipDate = Carbon::createFromFormat('d-m-Y H:i',Carbon::parse($request->date)->format('d-m-Y') . " " . $request->time);


问:
Django-registration Admin
I've tried Django-registration, see this tutorial to create a full Login-system.

In the tutorials (see STEP 4), I need to update the file urls.py to:

```<code>from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'^accounts/', include('registration.urls')),
    (r'^$', direct_to_template,
            { 'template': 'index.html' }, 'index'),
)
</code>```

But when I do this, the Admin page is not available. When I chance

```<code>(r'^admin/(.*)', admin.site.root)
</code>```

in

```<code>(r'^admin/(.*)', admin.site.urls)
</code>```

The adminpage works; I could login, but I couldn't click on anything... So I couldn't see the registered users.

What am I doing wrong?

答:
You have to use:

```<code>(r'^admin/', include(admin.site.urls))
</code>```

See the documentation.

Title: Django-registration Admin

Body:
I've tried Django-registration, see this tutorial to create a full Login-system.

In the tutorials (see STEP 4), I need to update the file urls.py to:

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'^accounts/', include('registration.urls')),
    (r'^$', direct_to_template,
            { 'template': 'index.html' }, 'index'),
)

But when I do this, the Admin page is not available. When I chance

(r'^admin/(.*)', admin.site.root)

in

(r'^admin/(.*)', admin.site.urls)

The adminpage works; I could login, but I couldn't click on anything... So I couldn't see the registered users.

What am I doing wrong?

Body:
You have to use:

(r'^admin/', include(admin.site.urls))

See the documentation.


问:
Get URL from Open dialog of standard Swift document-based application
I am trying to extract the URL of the document a user has selected in the default "Open" dialogue of my document based macOS application. I understand, a fileWrapper is passed to the init method but is there a way of extracting the path/URL from said wrapper?

Thanks,

Lars

答: The FileWrapper has a filename field, so you'd presumably use that.


问:
PySpark Add Months to Date Field Based on vlaue of column
I have a dataframe with a date column and an integer column and I'd like to add months based on the integer column to the date column.  I tried the following, but I'm getting an error:

```<code>from pyspark.sql import functions as f
withColumn('future', f.add_months('cohort', col('period')))
</code>```

Where 'cohort' is my date column and period is an integer.  I'm getting the following error:

TypeError: Column is not iterable

答:
Use expr to pass a column as second parameter for add_months function:

df.withColumn('future', F.expr("add_months(cohort, period)"))
```

Body:
I have a dataframe with a date column and an integer column and I'd like to add months based on the integer column to the date column.  I tried the following, but I'm getting an error:

from pyspark.sql import functions as f
withColumn('future', f.add_months('cohort', col('period')))

Where 'cohort' is my date column and period is an integer.  I'm getting the following error:

TypeError: Column is not iterable


问:
Debug window toolbar console missing arrows
I am trying to debug a simple program in Python with PyCharm debugger but when I put a break point and run debugger the arrows such as "Step Into" or "Step Over" doesn't show so I can't move on with debugging. The last time I used PyCharm I didn't have this problem and I don't believe I did anything that can change the debugger.

答:
The part of the toolbar you're refering to with the "Step Over" F8, "Step Into" F7 icons is called the "Debug Tool Window Top Toolbar" or the Stepping Toolbar. It can be enabled/disabled cliking on the cog on the right side of the toolbar and choosing Show Toolbar.

You can also configure the icons individually by going to Settings > Apperance and Behavior > Menus and Toolbars > Debug Tool Window Top Toolbar > Add Action and using Choose Actions to Add.


问:
How do I get mobile status for discord bot by directly modifying IDENTIFY packet?
Apparently, discord bots can have mobile status as opposed to the desktop (online) status that one gets by default.

After a bit of digging I found out that such a status is achieved by modifying the IDENTIFY packet in discord.gateway.DiscordWebSocket.identify modifying the value of $browser to Discord Android or Discord iOS should theoretically get us the mobile status.

After modifying code snippets I found online which does this, I end up with this :

def get_mobile():
    """
    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
    from there they send the extended presence object.
    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
    the mobile indicator is not triggered by the mobile client.
    The specific values for the $os, $browser, and $device fields are can change from time to time.
    """
    import ast
    import inspect
    import re
    import discord

    def source(o):
        s = inspect.getsource(o).split("\n")
        indent = len(s[0]) - len(s[0].lstrip())

        return "\n".join(i[indent:] for i in s)

    source_ = source(discord.gateway.DiscordWebSocket.identify)
    patched = re.sub(
        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
        r"\1Discord Android\2",
        source_,
    )

    loc = {}
    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
    return loc["identify"]
```
<p>Now all there is left to do is overwrite the <code>discord.gateway.DiscordWebSocket.identify</code> during runtime in the main file, something like this :</p>
<pre class="lang-py prettyprint-override"><code>import discord
import os
from discord.ext import commands
import mobile_status

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))
</code>```

And we do get the mobile status successfully

But here's the problem, I wanted to directly modify the file (which held the function) rather than monkey-patching it during runtime. So I cloned the dpy lib locally and edited the file on my machine, it ended up looking like this :

    async def identify(self):
        """Sends the IDENTIFY packet."""
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'Discord Android',
                    '$device': 'Discord Android',
                    '$referrer': '',
                    '$referring_domain': ''
                },
                'compress': True,
                'large_threshold': 250,
                'v': 3
            }
        }
     # ...
```
<p>(edited both <code>$browser</code> and <code>$device</code> to <code>Discord Android</code> just to be safe)</p>
<p>But this does not work and just gives me the regular desktop online icon.<br />
So the next thing I did is to inspect the <code>identify</code> function <em>after</em> it has been monkey-patched, so I could just look at the source code and see what went wrong earlier, but due to hard luck I got this error :</p>
```Traceback (most recent call last):
  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
    raise OSError('could not get source code')
OSError: could not get source code
```
<p>Code :</p>
<pre class="lang-py prettyprint-override"><code>import discord
import os
from discord.ext import commands
import mobile_status
import inspect

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))
</code>```

Since this same behavior was exhibited for every patched function (aforementioned one and the loc["identify"]) I could no longer use inspect.getsource(...) and then relied upon dis.dis which lead to much more disappointing results

The disassembled data looks exactly identical to the monkey-patched working version, so the directly modified version simply does not work despite function content being the exact same. (In regards to disassembled data)

Notes: Doing Discord iOS directly does not work either, changing the $device to some other value but keeping $browser does not work, I have tried all combinations, none of them work.

TL;DR: How to get mobile status for discord bot without monkey-patching it during runtime?

答:
DiscordWebSocket.identify is non-trivial and there is no supported way to override those fields.

A more maintainable alternative to copy-pasting 35* lines of code to modify 2 lines, is to subclass and then override DiscordWebSocket.send_as_json (4 lines of custom code), and patch the classmethod DiscordWebSocket.from_client to instantiate the subclass:

import os

from discord.ext import commands
from discord.gateway import DiscordWebSocket

class MyDiscordWebSocket(DiscordWebSocket):

    async def send_as_json(self, data):
        if data.get('op') == self.IDENTIFY:
            if data.get('d', {}).get('properties', {}).get('$browser') is not None:
                data['d']['properties']['$browser'] = 'Discord Android'
                data['d']['properties']['$device'] = 'Discord Android'
        await super().send_as_json(data)

DiscordWebSocket.from_client = MyDiscordWebSocket.from_client
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))
```

*39 lines in Pycord 1.7.3. By overriding, you get future updates usually without additional effort.

Body:
Apparently, discord bots can have mobile status as opposed to the desktop (online) status that one gets by default.

After a bit of digging I found out that such a status is achieved by modifying the IDENTIFY packet in discord.gateway.DiscordWebSocket.identify modifying the value of $browser to Discord Android or Discord iOS should theoretically get us the mobile status.

After modifying code snippets I found online which does this, I end up with this :

def get_mobile():
    """
    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
    from there they send the extended presence object.
    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
    the mobile indicator is not triggered by the mobile client.
    The specific values for the $os, $browser, and $device fields are can change from time to time.
    """
    import ast
    import inspect
    import re
    import discord

    def source(o):
        s = inspect.getsource(o).split("\n")
        indent = len(s[0]) - len(s[0].lstrip())

        return "\n".join(i[indent:] for i in s)

    source_ = source(discord.gateway.DiscordWebSocket.identify)
    patched = re.sub(
        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
        r"\1Discord Android\2",
        source_,
    )

    loc = {}
    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
    return loc["identify"]

Now all there is left to do is overwrite the discord.gateway.DiscordWebSocket.identify during runtime in the main file, something like this :

import discord
import os
from discord.ext import commands
import mobile_status

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))

And we do get the mobile status successfully

But here's the problem, I wanted to directly modify the file (which held the function) rather than monkey-patching it during runtime. So I cloned the dpy lib locally and edited the file on my machine, it ended up looking like this :

    async def identify(self):
        """Sends the IDENTIFY packet."""
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'Discord Android',
                    '$device': 'Discord Android',
                    '$referrer': '',
                    '$referring_domain': ''
                },
                'compress': True,
                'large_threshold': 250,
                'v': 3
            }
        }
     # ...

(edited both $browser and $device to Discord Android just to be safe)

But this does not work and just gives me the regular desktop online icon.

So the next thing I did is to inspect the identify function after it has been monkey-patched, so I could just look at the source code and see what went wrong earlier, but due to hard luck I got this error :

Traceback (most recent call last):
  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
    raise OSError('could not get source code')
OSError: could not get source code

Code :

import discord
import os
from discord.ext import commands
import mobile_status
import inspect

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))

Since this same behavior was exhibited for every patched function (aforementioned one and the loc["identify"]) I could no longer use inspect.getsource(...) and then relied upon dis.dis which lead to much more disappointing results

The disassembled data looks exactly identical to the monkey-patched working version, so the directly modified version simply does not work despite function content being the exact same. (In regards to disassembled data)

Notes: Doing Discord iOS directly does not work either, changing the $device to some other value but keeping $browser does not work, I have tried all combinations, none of them work.

TL;DR: How to get mobile status for discord bot without monkey-patching it during runtime?

Body:
DiscordWebSocket.identify is non-trivial and there is no supported way to override those fields.

A more maintainable alternative to copy-pasting 35* lines of code to modify 2 lines, is to subclass and then override DiscordWebSocket.send_as_json (4 lines of custom code), and patch the classmethod DiscordWebSocket.from_client to instantiate the subclass:

import os

from discord.ext import commands
from discord.gateway import DiscordWebSocket

class MyDiscordWebSocket(DiscordWebSocket):

    async def send_as_json(self, data):
        if data.get('op') == self.IDENTIFY:
            if data.get('d', {}).get('properties', {}).get('$browser') is not None:
                data['d']['properties']['$browser'] = 'Discord Android'
                data['d']['properties']['$device'] = 'Discord Android'
        await super().send_as_json(data)

DiscordWebSocket.from_client = MyDiscordWebSocket.from_client
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))

*39 lines in Pycord 1.7.3. By overriding, you get future updates usually without additional effort.


问:
IS there a rails war file equivalent?
I am learning rails and have what seems to be a fairly easy question - except I don't know the answer. Going through the rails tutorials, I can get my apps to run on my dev machine. I can also copy the folders to a server and the app works there also.
Question: Is there some way to deploy a war/jar type of file instead of the 'exploded' folder structure on the server?</p>

答: The most common way to deploy Rails applications is to use a tool like Capistrano, which will copy all the files across, and also provide you with a way of rolling back to a previous release in case of issues in production.</p>

Title: IS there a rails war file equivalent?


问:
Using multiprocessing doesn't speed-up code
I was trying to speed up the following code, using multiprocessing . So I used this code, after getting some help here :

```<code>from multiprocessing import Pool, Manager, cpu_count
from functools import partial
import re

def process_value(data_set_N, i_1):
    print(i_1)
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10))+list("+-*/")+["=="]:
                        for i_7 in list(range(10))+list("+-*/")+["=="]:
                            for i_8 in list(range(10)):
                                try:
                                    value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)+str(i_7)+str(i_8)
                                    if '//' in value:
                                        continue
                                    valuev = re.sub(r'\b0+(?!\b)', '', value)
                                    evaluation = eval(valuev)
                                    if type(evaluation) == type(True) and evaluation:
                                        data_set_N.append(value)
                                except:
                                    continue

if __name__ == '__main__':
    with Manager() as manager:
        data_set_N = manager.list()
        # The iterable is the i_1 list:
        i_1_list = list(range(10))+list("+-")
        POOL_SIZE = min(cpu_count(), len(i_1_list))
        pool = Pool(POOL_SIZE)
        pool.map(partial(process_value, data_set_N), i_1_list)
        pool.close()
        pool.join()
        data_set_N=list(data_set_N)
        print(len(data_set_N))
</code>```

Which is working, but it is supposed to take less time (divide the time by the number of cpus).
After waiting for around 24 hours, the code was still executing.

So, I tested the code to compare it (before multiprocessing and after), with less nested loops (6 instead of 8).

```<code>from multiprocessing import Pool, Manager, cpu_count
from functools import partial
import re

def process_value(data_set_N, i_1):
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10)):
                        try:
                            value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)
                            if '//' in value:
                                continue
                            valuev = re.sub(r'\b0+(?!\b)', '', value)
                            evaluation = eval(valuev)
                            if type(evaluation) == type(True) and evaluation:
                                data_set_N.append(value)
                        except:
                            continue

import time
start_time = time.time()
if __name__ == '__main__':
    with Manager() as manager:
        data_set_N = manager.list()
        # The iterable is the i_1 list:
        i_1_list = list(range(10))+list("+-")
        POOL_SIZE = min(cpu_count(), len(i_1_list))
        pool = Pool(POOL_SIZE)
        pool.map(partial(process_value, data_set_N), i_1_list)
        pool.close()
        pool.join()
        data_set_N=list(data_set_N)
        print(len(data_set_N))

    print("--- %s seconds ---" % (time.time() - start_time))
</code>```

This one gives 4687 --- 46.11929202079773 seconds ---

While without multiprocessing  :

```<code>import time
start_time = time.time()

data_set_N =[]
for i_1 in list(range(10))+list("+-"):
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10)):
                        try:
                            value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)
                            if '//' in value:
                                continue
                            valuev = re.sub(r'\b0+(?!\b)', '', value)
                            evaluation = eval(valuev)
                            if type(evaluation) == type(True) and evaluation:
                                data_set_N.append(value)
                        except:
                            continue
data_set_N=list(data_set_N)
print(len(data_set_N))

print("--- %s seconds ---" % (time.time() - start_time))
</code>```

Which gives 4687 --- 48.32949733734131 seconds ---.  Which is almost the same.

I have 12 cpus cpu_count() >>> 12, still there is almost no difference. I dont know why using multiprocesses doesn't make it run faster.

答:
In every loop you access the managed memory:

```<code>data_set_N.append(value)
</code>```

Every time a process comes to this line it has to wait for the Manager to update underlying memory for all the processes. Given that the rest of the loop is rather trivial (or fast), most of the time is spent in waiting for the Manager to update it. Note that the manager has to provide the "correct" content for all the processes, so you cannot have two processes adding a value to the array at the same time. So this part of the code essentially runs in a single process. Given that the rest of the code is pretty quick, and add some non-trivial management that Manager has to do in each append and you arrive at the same speed as without using multiprocessing at all.

Nevertheless, if you don't need anything special, you can use much quicker methods, just by... not using the manager:

```<code>def process_value(data_set_N, i_1):  # <- instead of this
def process_value(i_1):  # <- use this
...
                                data_set_N.append(value)   # <- instead of this
                                return value  # <- use this
...
        pool.map(partial(process_value, data_set_N), i_1_list)  # <- instead of this
        data_set_N = pool.map(process_value, i_1_list)  # <- use this
</code>```

Body:
I was trying to speed up the following code, using multiprocessing . So I used this code, after getting some help here :

from multiprocessing import Pool, Manager, cpu_count
from functools import partial
import re

def process_value(data_set_N, i_1):
    print(i_1)
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10))+list("+-*/")+["=="]:
                        for i_7 in list(range(10))+list("+-*/")+["=="]:
                            for i_8 in list(range(10)):
                                try:
                                    value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)+str(i_7)+str(i_8)
                                    if '//' in value:
                                        continue
                                    valuev = re.sub(r'\b0+(?!\b)', '', value)
                                    evaluation = eval(valuev)
                                    if type(evaluation) == type(True) and evaluation:
                                        data_set_N.append(value)
                                except:
                                    continue

if __name__ == '__main__':
    with Manager() as manager:
        data_set_N = manager.list()
        # The iterable is the i_1 list:
        i_1_list = list(range(10))+list("+-")
        POOL_SIZE = min(cpu_count(), len(i_1_list))
        pool = Pool(POOL_SIZE)
        pool.map(partial(process_value, data_set_N), i_1_list)
        pool.close()
        pool.join()
        data_set_N=list(data_set_N)
        print(len(data_set_N))

Which is working, but it is supposed to take less time (divide the time by the number of cpus).
After waiting for around 24 hours, the code was still executing.

So, I tested the code to compare it (before multiprocessing and after), with less nested loops (6 instead of 8).

from multiprocessing import Pool, Manager, cpu_count
from functools import partial
import re

def process_value(data_set_N, i_1):
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10)):
                        try:
                            value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)
                            if '//' in value:
                                continue
                            valuev = re.sub(r'\b0+(?!\b)', '', value)
                            evaluation = eval(valuev)
                            if type(evaluation) == type(True) and evaluation:
                                data_set_N.append(value)
                        except:
                            continue

import time
start_time = time.time()
if __name__ == '__main__':
    with Manager() as manager:
        data_set_N = manager.list()
        # The iterable is the i_1 list:
        i_1_list = list(range(10))+list("+-")
        POOL_SIZE = min(cpu_count(), len(i_1_list))
        pool = Pool(POOL_SIZE)
        pool.map(partial(process_value, data_set_N), i_1_list)
        pool.close()
        pool.join()
        data_set_N=list(data_set_N)
        print(len(data_set_N))

    print("--- %s seconds ---" % (time.time() - start_time))

This one gives 4687 --- 46.11929202079773 seconds ---

While without multiprocessing  :

import time
start_time = time.time()

data_set_N =[]
for i_1 in list(range(10))+list("+-"):
    for i_2 in list(range(10))+list("+-*/")+["=="]:
        for i_3 in list(range(10))+list("+-*/")+["=="]:
            for i_4 in list(range(10))+list("+-*/")+["=="]:
                for i_5 in list(range(10))+list("+-*/")+["=="]:
                    for i_6 in list(range(10)):
                        try:
                            value = str(i_1)+str(i_2)+str(i_3)+str(i_4)+str(i_5)+str(i_6)
                            if '//' in value:
                                continue
                            valuev = re.sub(r'\b0+(?!\b)', '', value)
                            evaluation = eval(valuev)
                            if type(evaluation) == type(True) and evaluation:
                                data_set_N.append(value)
                        except:
                            continue
data_set_N=list(data_set_N)
print(len(data_set_N))

print("--- %s seconds ---" % (time.time() - start_time))

Which gives 4687 --- 48.32949733734131 seconds ---.  Which is almost the same.

I have 12 cpus cpu_count() >>> 12, still there is almost no difference. I dont know why using multiprocesses doesn't make it run faster.

Body:
In every loop you access the managed memory:

data_set_N.append(value)

Every time a process comes to this line it has to wait for the Manager to update underlying memory for all the processes. Given that the rest of the loop is rather trivial (or fast), most of the time is spent in waiting for the Manager to update it. Note that the manager has to provide the "correct" content for all the processes, so you cannot have two processes adding a value to the array at the same time. So this part of the code essentially runs in a single process. Given that the rest of the code is pretty quick, and add some non-trivial management that Manager has to do in each append and you arrive at the same speed as without using multiprocessing at all.

Nevertheless, if you don't need anything special, you can use much quicker methods, just by... not using the manager:

def process_value(data_set_N, i_1):  # <- instead of this
def process_value(i_1):  # <- use this
...
                                data_set_N.append(value)   # <- instead of this
                                return value  # <- use this
...
        pool.map(partial(process_value, data_set_N), i_1_list)  # <- instead of this
        data_set_N = pool.map(process_value, i_1_list)  # <- use this


问:
Error while running nestjs in production mode, cannot find module
I have implemented a generic class as below which might be causing the problem,

```<code>    import { Logger } from '@nestjs/common';
    import { PaginationOptionsInterface, Pagination } from './paginate';
    import { Repository } from 'typeorm';

    export class EntityService<T> {
      private repository: Repository<T>;
      constructor(repository) {
        this.repository = repository;
      }

      async getEntityWithPagination(
        options: PaginationOptionsInterface,
      ): Promise<Pagination<T>> {
        const [results, total] = await this.repository.findAndCount({
          take: options.limit,
          skip: (options.page - 1) * options.limit,
        });
        return new Pagination<T>({ results, total });
      }
    }
</code>```

and using with other entity services, such as

```<code>    @Injectable()
    export class CarService extends EntityService<CarEntity> {
      constructor(
        @InjectRepository(CarEntity)
        private carRepository: Repository<CarEntity>,
      ) {
        super(carRepository);
      }
</code>```

the code is working perfectly fine with npm run start:dev but throwing below error when trying to run with production npm run start:prod

```<code>        internal/modules/cjs/loader.js:582
            throw err;
            ^

        Error: Cannot find module 'src/shared/entity.service'
            at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
            at Function.Module._load (internal/modules/cjs/loader.js:506:25)
            at Module.require (internal/modules/cjs/loader.js:636:17)
            at require (internal/modules/cjs/helpers.js:20:18)
            at Object.<anonymous> (/home/tejas/Code/web/project/dist/car/car.service.js:27:26)
            at Module._compile (internal/modules/cjs/loader.js:688:30)
            at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
            at Module.load (internal/modules/cjs/loader.js:598:32)
            at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
            at Function.Module._load (internal/modules/cjs/loader.js:529:3)
        npm ERR! code ELIFECYCLE
        npm ERR! errno 1
        npm ERR! project@0.0.0 start:prod: `node dist/main.js`
        npm ERR! Exit status 1
</code>```

I have tried deleting dist folder, but still no luck. I have tried updating packages also, package.json is as follows. I have no clue how to debug this.

```<code>        dependencies": {
            "@nestjs/common": "^5.5.0",
            "@nestjs/core": "^5.5.0",
            "@nestjs/jwt": "^0.2.1",
            "@nestjs/passport": "^5.1.0",
            "@nestjs/typeorm": "^5.2.2",
            "bcryptjs": "^2.4.3",
            "glob": "^7.1.3",
            "passport": "^0.4.0",
            "passport-http-bearer": "^1.0.1",
            "passport-jwt": "^4.0.0",
            "pg": "^7.7.1",
            "reflect-metadata": "^0.1.12",
            "rimraf": "^2.6.2",
            "rxjs": "^6.2.2",
            "typeorm": "^0.2.9",
            "typescript": "^3.2.2"
        },
        "devDependencies": {
            "@nestjs/testing": "^5.5.0",
            "@types/express": "^4.16.0",
            "@types/jest": "^23.3.1",
            "@types/node": "^10.12.18",
            "@types/supertest": "^2.0.7",
            "jest": "^23.5.0",
            "nodemon": "^1.18.9",
            "prettier": "^1.14.2",
            "supertest": "^3.1.0",
            "ts-jest": "^23.1.3",
            "ts-loader": "^4.4.2",
            "ts-node": "^7.0.1",
            "tsconfig-paths": "^3.5.0",
            "tslint": "5.11.0",
            "webpack": "^4.28.2",
            "webpack-cli": "^3.1.2",
            "webpack-node-externals": "^1.7.2"
        },
</code>```

答:
I forgot to install these two packages that were required by mikro-orm. Installing solved my issue:</p>
```<code>yarn add @mikro-orm/core @mikro-orm/nestjs
</code>```

Body:
I have implemented a generic class as below which might be causing the problem,

    import { Logger } from '@nestjs/common';
    import { PaginationOptionsInterface, Pagination } from './paginate';
    import { Repository } from 'typeorm';

    export class EntityService<T> {
      private repository: Repository<T>;
      constructor(repository) {
        this.repository = repository;
      }

      async getEntityWithPagination(
        options: PaginationOptionsInterface,
      ): Promise<Pagination<T>> {
        const [results, total] = await this.repository.findAndCount({
          take: options.limit,
          skip: (options.page - 1) * options.limit,
        });
        return new Pagination<T>({ results, total });
      }
    }

and using with other entity services, such as

    @Injectable()
    export class CarService extends EntityService<CarEntity> {
      constructor(
        @InjectRepository(CarEntity)
        private carRepository: Repository<CarEntity>,
      ) {
        super(carRepository);
      }

the code is working perfectly fine with npm run start:dev but throwing below error when trying to run with production npm run start:prod

        internal/modules/cjs/loader.js:582
            throw err;
            ^

        Error: Cannot find module 'src/shared/entity.service'
            at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
            at Function.Module._load (internal/modules/cjs/loader.js:506:25)
            at Module.require (internal/modules/cjs/loader.js:636:17)
            at require (internal/modules/cjs/helpers.js:20:18)
            at Object.<anonymous> (/home/tejas/Code/web/project/dist/car/car.service.js:27:26)
            at Module._compile (internal/modules/cjs/loader.js:688:30)
            at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
            at Module.load (internal/modules/cjs/loader.js:598:32)
            at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
            at Function.Module._load (internal/modules/cjs/loader.js:529:3)
        npm ERR! code ELIFECYCLE
        npm ERR! errno 1
        npm ERR! project@0.0.0 start:prod: `node dist/main.js`
        npm ERR! Exit status 1

I have tried deleting dist folder, but still no luck. I have tried updating packages also, package.json is as follows. I have no clue how to debug this.

        dependencies": {
            "@nestjs/common": "^5.5.0",
            "@nestjs/core": "^5.5.0",
            "@nestjs/jwt": "^0.2.1",
            "@nestjs/passport": "^5.1.0",
            "@nestjs/typeorm": "^5.2.2",
            "bcryptjs": "^2.4.3",
            "glob": "^7.1.3",
            "passport": "^0.4.0",
            "passport-http-bearer": "^1.0.1",
            "passport-jwt": "^4.0.0",
            "pg": "^7.7.1",
            "reflect-metadata": "^0.1.12",
            "rimraf": "^2.6.2",
            "rxjs": "^6.2.2",
            "typeorm": "^0.2.9",
            "typescript": "^3.2.2"
        },
        "devDependencies": {
            "@nestjs/testing": "^5.5.0",
            "@types/express": "^4.16.0",
            "@types/jest": "^23.3.1",
            "@types/node": "^10.12.18",
            "@types/supertest": "^2.0.7",
            "jest": "^23.5.0",
            "nodemon": "^1.18.9",
            "prettier": "^1.14.2",
            "supertest": "^3.1.0",
            "ts-jest": "^23.1.3",
            "ts-loader": "^4.4.2",
            "ts-node": "^7.0.1",
            "tsconfig-paths": "^3.5.0",
            "tslint": "5.11.0",
            "webpack": "^4.28.2",
            "webpack-cli": "^3.1.2",
            "webpack-node-externals": "^1.7.2"
        },

Body:
I forgot to install these two packages that were required by mikro-orm. Installing solved my issue:

yarn add @mikro-orm/core @mikro-orm/nestjs


问:
Flutter webview set cookies as URL parameters
I would like to know if it's possible to set a cookie in a webview to pass a query parameter to a webview URL in the following way.
My URL would be mydomain.com?isMobile=true And would like to set the parameter isMobile=true as a fixed cookie to include And force the parameter.

The reason I need to do It with cookies is because I was told it's the correct way to do It, asswell because forcing the parameter directly into the URL is making some functions in my webview to not work as It would on a browser.

I'd appreciate any feedback even without using cookies about how to work webview to make some realtime web functions update as It would on a browser.

This issue is driving me absolutely crazy, thank you very much un advance.

答:
In the end They're were problems related to a firewall on the webpage that made the cookies not work as intended in the end the solution was as simple as declarion the initialCookies as follows in the WebView Widget.</p>
```<code>WebView(
 initialCookies: [
      WebViewCookie(
         name: cookieName,
         value: cookieVal,
         domain: cookieDomain,
         path: cookiePath,
     ),
   ],
),
</code>```

Body:
In the end They're were problems related to a firewall on the webpage that made the cookies not work as intended in the end the solution was as simple as declarion the initialCookies as follows in the WebView Widget.

WebView(
 initialCookies: [
      WebViewCookie(
         name: cookieName,
         value: cookieVal,
         domain: cookieDomain,
         path: cookiePath,
     ),
   ],
),


问:
Adding New Input Field using button in ReactJs
I am working on a project so I  am trying to add a new input field after clicking the add(+) button in the form using react-Hooks. It would be very helpful if someone can figure this out so I can learn a new thing. Thankyou in advance.[React events handling link is added][1]
Here is the code of the form and css file

```<code>import Navbar from "./Navbar/Navbar";
import "./UserDetails.css";

function UserDetails() {
  const [Info, setInfo] = useState({
    username: "",
    email: "",
    bio: "",
    positions: "",
  });
  const { username, email, bio, positions } = Info;
  const onChange = (e) => setInfo({ ...Info, [e.target.name]: e.target.value });

  const onSubmit = (e) => {
    e.preventDefault();

    console.log(Info);
  };

  return (
    <div>
      <Navbar />
      <div className="full">
        <h1 className="top">Edit Profile</h1>
        <img
          className="pic"
          src="https://www.pngitem.com/pimgs/m/146-1468479_my-profile-icon-blank-profile-picture-circle-hd.png"
          alt=""
        ></img>
        <div className="inputs">
          <form className="frms" onSubmit={(e) => onSubmit(e)}>
            <input
              className="insides"
              type="text"
              placeholder="Username"
              name="username"
              value={username}
              onChange={(e) => onChange(e)}
            ></input>
            <input
              className="insides"
              type="email"
              placeholder="email"
              name="email"
              value={email}
              onChange={(e) => onChange(e)}
            ></input>

            <textarea
              placeholder="Add Bio here..."
              name="bio"
              value={bio}
              onChange={(e) => onChange(e)}
            ></textarea>
          </form>
        </div>
        <div className="addbtn">
          <input
            className="insidesp"
            type="text"
            placeholder="positions held..."
            name="positions"
            value={positions}
            onChange={(e) => onChange(e)}
          ></input>
          <button>+</button>
          <br></br>
          <button className="savebtn">Save Changes</button>
        </div>
      </div>
    </div>
  );
}
export default UserDetails;

.full {
  text-align: center;
  border: 2px solid white;
  margin: 0 auto;
  padding-top: 1%;
  width: 50%;
  padding-bottom: 1%;
  margin-top: 2%;
  border-radius: 30px;
  box-shadow: 5px 6px 5px 6px rgb(158, 170, 238);
}
.top {
  color: rgb(88 99 161);
}
.pic {
  height: 40%;
  width: 30%;
}
.inputs input {
  display: block;
  width: 70%;
  margin: 0 auto;
  margin-top: 2%;
  border: 2px solid rgb(88 99 161);
  border-radius: 7px;
}
.inputs textarea {
  display: block;
  width: 70%;
  margin: 0 auto;
  margin-top: 2%;
  border: 2px solid rgb(88 99 161);
  border-radius: 7px;
}
.pic {
  margin: 2%;
}
.savebtn {
  margin-top: 2%;
  background-color: rgb(88 99 161);
  border: 2px solid rgb(158, 170, 238);
  border-radius: 6px;
}
.addbtn {
  display: inline;
}
.addbtn input {
  margin-right: 1%;
  width: 65%;
  margin-top: 2%;
  border: 2px solid rgb(88 99 161);
  border-radius: 7px;
}
.addbtn button {
  background-color: rgb(88 99 161);
  border-radius: 6px;
  border: 2px solid rgb(158, 170, 238);
}```

  [1]: https://reactjs.org/docs/handling-events.html
```

答:
Here is a great article that explains solution for your question step by step:
https://www.cluemediator.com/add-or-remove-input-fields-dynamically-with-reactjs</p>

Body:
I am working on a project so I  am trying to add a new input field after clicking the add(+) button in the form using react-Hooks. It would be very helpful if someone can figure this out so I can learn a new thing. Thankyou in advance.[React events handling link is added][1]
Here is the code of the form and css file

import Navbar from "./Navbar/Navbar";
import "./UserDetails.css";

function UserDetails() {
  const [Info, setInfo] = useState({
    username: "",
    email: "",
    bio: "",
    positions: "",
  });
  const { username, email, bio, positions } = Info;
  const onChange = (e) => setInfo({ ...Info, [e.target.name]: e.target.value });

  const onSubmit = (e) => {
    e.preventDefault();

    console.log(Info);
  };

  return (

      <Navbar />

Edit Profile

          <form className="frms" onSubmit={(e) => onSubmit(e)}>
            <input
              className="insides"
              type="text"
              placeholder="Username"
              name="username"
              value={username}
              onChange={(e) => onChange(e)}
            ></input>
            <input
              className="insides"
              type="email"
              placeholder="email"
              name="email"
              value={email}
              onChange={(e) => onChange(e)}
            ></input>

            <textarea
              placeholder="Add Bio here..."
              name="bio"
              value={bio}
              onChange={(e) => onChange(e)}
            ></textarea>
          </form>

          <input
            className="insidesp"
            type="text"
            placeholder="positions held..."
            name="positions"
            value={positions}
            onChange={(e) => onChange(e)}
          ></input>
          <button>+</button>

          <button className="savebtn">Save Changes</button>

  );
}
export default UserDetails;

.full {
  text-align: center;
  border: 2px solid white;
  margin: 0 auto;
  padding-top: 1%;
  width: 50%;
  padding-bottom: 1%;
  margin-top: 2%;
  border-radius: 30px;
  box-shadow: 5px 6px 5px 6px rgb(158, 170, 238);
}
.top {
  color: rgb(88 99 161);
}
.pic {
  height: 40%;
  width: 30%;
}
.inputs input {
  display: block;
  width: 70%;
  margin: 0 auto;
  margin-top: 2%;
  border: 2px solid rgb(88 99 161);
  border-radius: 7px;
}
.inputs textarea {
  display: block;
  width: 70%;
  margin: 0 auto;
  margin-top: 2%;
  border: 2px solid rgb(88 99 161);
  border-radius: 7px;
}
.pic {
  margin: 2%;
}
.savebtn {
  margin-top: 2%;
  background-color: rgb(88 99 161);
  border: 2px solid rgb(158, 170, 238);
  border-radius: 6px;
}
.addbtn {
  display: inline;
}
.addbtn input {
  margin-right: 1%;
  width: 65%;
  margin-top: 2%;
  border: 2px solid rgb(88 99 161);
  border-radius: 7px;
}
.addbtn button {
  background-color: rgb(88 99 161);
  border-radius: 6px;
  border: 2px solid rgb(158, 170, 238);
}```

  [1]: https://reactjs.org/docs/handling-events.html


问:
Power BI Rest API Requests Not Authorizing as expected
I have built a python application to access read only Power BI Rest API’s.  I am automating the collection of tenant activity.  However despite configuring my Azure App and using the service principal to generate an access token, the response I receive from the API request is one of an unauthorised response:

```<code>{"error": {"code": "PowerBINotAuthorizedException", "pbi.error": {"code":
"PowerBINotAuthorizedException", "parameters": {}, "details": [], "exceptionCulprit": 1}}}
</code>```

I have found a number of similar issues posted online, however feel that I have done everything that is suggested but am still not able to get it working.  I would appreciate any guidance.

The steps that I have taken are:

Configured an Azure App, adding the Application Permission for Power Bi Service-Tenant.Read.All

Screenshot of App Settings in Azure Portal

Requested my access token based upon the Client Credentials Flow using my app's client_ID and client_Secret as documented in the below link:

https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow

I successfully receive a token using the script below:

```<code>import requests

azureTenantID = "xxxxxxxxxxxxxxxxx"
azureClientId = "xxxxxxxxxxxxxxxxx"
azureClientSecret = "xxxxxxxxxxxxxxxxxx"

url = f"https://login.microsoftonline.com/{azureTenantID}/oauth2/v2.0/token"

payload = {
        "grant_type": "client_credentials",
        "client_id": azureClientId,
        "client_secret": azureClientSecret,
        "scope": "https://analysis.windows.net/powerbi/api/.default"
}
# Header HAS to be x-www-form-urlencoded for MS to accept it.
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

# Return POST content as JSON.
r = requests.post(url, data=payload, headers=headers).json()

# Grab the access token.
response = r.get("access_token")

# Concatenate with Bearer string
access_token = "Bearer {r['access_token']}"
</code>```

Configured my Power BI Tenant Settings to enable Service Principals to use API's.

Screenshot of Admin API Setting

Screenshot of Developer API Setting

Note that I added the Service Principal as a member of the Security Group for which both of these settings are enabled

Execute my Get request to the API

The followings script returns a good response when I take an access token from the Power BI REST API Documentation's 'Try it out' feature, but not when I generate the token as above.

```<code>import requests

# Initialise parameters.
url = "https://api.powerbi.com/v1.0/myorg/admin/groups?$top=1000&$expand=datasets,dataflows,reports,users,dashboards"
headers = {'Authorization': get_access_token2()}

# Get response.
response = requests.get(url, headers=headers)
response = response.json()
</code>```

Any assistance would be appreciated !

答:
I just went through this exact scenario that you described, and in the end we had to engage Microsoft support to solve it.

Although extremely counter intuitive, if the app that you create for your service principal authentication has any Power BI permissions assigned to it then the access token that is generated (when passed to Power BI REST Admin API) will return an error response that reports PowerBINotAuthorizedException.

To be even more specific, if the access token that you pass to the Power BI API has a roles key/value pair, then you will get a PowerBINotAuthorizedException.

In your case, the issue is easier because you have listed out what permissions you granted. You mentioned that you Configured an Azure App, adding the Application Permission for Power Bi Service-Tenant.Read.All. In order to resolve this issue, you will need to remove that permission.

For future readers, you can troubleshoot this by decoding your access token using a JWT token decoder like one found at jstoolset.com. If your app has permissions allocated to the scope that you have requested (https://analysis.windows.net/powerbi/api/.default is the typical Power BI scope that you request in your authorization) and you decode your JWT token then you will see a roles key/value pair. The presence of this roles is essentially the issue. It does not matter that the values there might match up to the Required Scope in the Power BI REST Admin API documentation. It was described to us as if there is a roles value in your access token then when the token is presented to the Power BI API the roles that are granted are attempted to be used, which ultimately results in a PowerBINotAuthorizedException because service principals are not allowed to use a certain role.

If you have an app that you have removed all permissions from, but still has a value coming through in your access token for the roles key/value pair, then I would suggest starting with a new app with no permissions allocated to it, and simply add the new app to the existing security group that you originally created. This is how we realized that this truly was the issue, and were then able to reconcile from there.

EDIT: Microsoft has now updated their API documentation on the relevant endpoints to reflect this information. For example, in Admin - Groups GetGroupUsersAsAdmin the Required Scope now reads:

Tenant.Read.All or Tenant.ReadWrite.All

Relevant only when authenticating via a standard delegated admin access token. Must not be present when authentication via a service principal is used.

Body:
I have built a python application to access read only Power BI Rest API’s.  I am automating the collection of tenant activity.  However despite configuring my Azure App and using the service principal to generate an access token, the response I receive from the API request is one of an unauthorised response:

{"error": {"code": "PowerBINotAuthorizedException", "pbi.error": {"code":
"PowerBINotAuthorizedException", "parameters": {}, "details": [], "exceptionCulprit": 1}}}

I have found a number of similar issues posted online, however feel that I have done everything that is suggested but am still not able to get it working.  I would appreciate any guidance.

The steps that I have taken are:

Configured an Azure App, adding the Application Permission for Power Bi Service-Tenant.Read.All

Screenshot of App Settings in Azure Portal

Requested my access token based upon the Client Credentials Flow using my app's client_ID and client_Secret as documented in the below link:

https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow

I successfully receive a token using the script below:

import requests

azureTenantID = "xxxxxxxxxxxxxxxxx"
azureClientId = "xxxxxxxxxxxxxxxxx"
azureClientSecret = "xxxxxxxxxxxxxxxxxx"

url = f"https://login.microsoftonline.com/{azureTenantID}/oauth2/v2.0/token"

payload = {
        "grant_type": "client_credentials",
        "client_id": azureClientId,
        "client_secret": azureClientSecret,
        "scope": "https://analysis.windows.net/powerbi/api/.default"
}
# Header HAS to be x-www-form-urlencoded for MS to accept it.
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

# Return POST content as JSON.
r = requests.post(url, data=payload, headers=headers).json()

# Grab the access token.
response = r.get("access_token")

# Concatenate with Bearer string
access_token = "Bearer {r['access_token']}"

Configured my Power BI Tenant Settings to enable Service Principals to use API's.

Screenshot of Admin API Setting

Screenshot of Developer API Setting

Note that I added the Service Principal as a member of the Security Group for which both of these settings are enabled

Execute my Get request to the API

The followings script returns a good response when I take an access token from the Power BI REST API Documentation's 'Try it out' feature, but not when I generate the token as above.

import requests

# Initialise parameters.
url = "https://api.powerbi.com/v1.0/myorg/admin/groups?$top=1000&$expand=datasets,dataflows,reports,users,dashboards"
headers = {'Authorization': get_access_token2()}

# Get response.
response = requests.get(url, headers=headers)
response = response.json()

Any assistance would be appreciated !


问:
How to get the next auto-increment id in mysql
How to get the next id in mysql to insert it in the table</p>

```<code>INSERT INTO payments (date, item, method, payment_code)
VALUES (NOW(), '1 Month', 'paypal', CONCAT("sahf4d2fdd45", id))
</code>```

答: SELECT AUTO_INCREMENT AS next_id FROM information_schema.tables WHERE table_name = 'table name' AND table_schema = 'database name of table name'

Body:
How to get the next id in mysql to insert it in the table

INSERT INTO payments (date, item, method, payment_code)
VALUES (NOW(), '1 Month', 'paypal', CONCAT("sahf4d2fdd45", id))


问:
How to find similar text values within the same column in excel?
Trying to find a way to highlight in the same column values which start with the same 3 characters:

A

Lorem Ipsum

Lorim

Esset

John

Johnathan

On this example it would highlight all but Esset. I've done some research and found a Fuzzy match add-on but it does not work on Mac. https://www.microsoft.com/en-us/download/details.aspx?id=15011

Also tried

Match and Look up formulas without luck

=IF(ISNA(MATCH(LEFT(E8,3),LEFT(E:E,3),0)),"No Match",E8)

Thanks!

答:
Use a rule based on COUNTIFS, LEFT, and a wildcard:

```<code>=COUNTIFS(A:A,LEFT(A2,3)&"*")>1
</code>```

Body:
Use a rule based on COUNTIFS, LEFT, and a wildcard:

=COUNTIFS(A:A,LEFT(A2,3)&"*")>1


问:
Circular dependency error in Google Sheets
I have two formulas:

CELL W21:

```<code>=IF(AND(TODAY() >= DATE(2022,2,1), TODAY() <= DATE(2022,2,28)), SUM('Master Report'!$B$20:$B$24,'Master report'!$B$31:$B$32), W21)
</code>```

CELL X21:

```<code>=IF(AND(TODAY() >= DATE(2022,3,1), TODAY() <= DATE(2022,3,31)), SUM('Master report'!$B$20:$B$24,'Master report'!$B$31:$B$32), X21)
</code>```

The first formula works ok, while the second gives a circular dependency error. I want the value in X21 to be populated only between those dates but I want to set up the spreadsheet now for the entire year.

The values in "Master Report" gets updated automatically via API on 1st of every month and I am referencing those value in a table where each month is present. Example as follows:

Master Report (updated automatically every 1st of the month)
| Page | Visits |
| -------- | -------------- |
| Page 1| 20012|

This spreadsheet
| January 2022| March 2022| April 2022|
|:---- |:------:| -----:|
| Visits| Visits| Visits|

答:
I managed to do this in Google App Script as suggested by @TheWizEd.

It's a very primitive script, but I hope it can help people with this problem in future:

```<code>function checkDateAndWrite(dateStart,dateEnd,cellFrom,cellTo) {
  var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var reportSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Master Report')
  var today = new Date();
  var dateOne = new Date(dateStart);
  var dateTwo = new Date(dateEnd);

  if(today.valueOf() >= dateOne.valueOf() && today.valueOf() <= dateTwo.valueOf()) {
    activeSheet.getRange(cellTo).setValue(reportSheet.getRange(cellFrom).getValue());
  }

  return;
}
</code>```

Body:
I have two formulas:

CELL W21:

=IF(AND(TODAY() >= DATE(2022,2,1), TODAY() <= DATE(2022,2,28)), SUM('Master Report'!$B$20:$B$24,'Master report'!$B$31:$B$32), W21)

CELL X21:

=IF(AND(TODAY() >= DATE(2022,3,1), TODAY() <= DATE(2022,3,31)), SUM('Master report'!$B$20:$B$24,'Master report'!$B$31:$B$32), X21)

The first formula works ok, while the second gives a circular dependency error. I want the value in X21 to be populated only between those dates but I want to set up the spreadsheet now for the entire year.

The values in "Master Report" gets updated automatically via API on 1st of every month and I am referencing those value in a table where each month is present. Example as follows:

Master Report (updated automatically every 1st of the month)
| Page | Visits |
| -------- | -------------- |
| Page 1| 20012|

This spreadsheet
| January 2022| March 2022| April 2022|
|:---- |:------:| -----:|
| Visits| Visits| Visits|

Body:
I managed to do this in Google App Script as suggested by @TheWizEd.

It's a very primitive script, but I hope it can help people with this problem in future:

function checkDateAndWrite(dateStart,dateEnd,cellFrom,cellTo) {
  var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var reportSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Master Report')
  var today = new Date();
  var dateOne = new Date(dateStart);
  var dateTwo = new Date(dateEnd);

  if(today.valueOf() >= dateOne.valueOf() && today.valueOf() <= dateTwo.valueOf()) {
    activeSheet.getRange(cellTo).setValue(reportSheet.getRange(cellFrom).getValue());
  }

  return;
}