问:
Ruby on Rails: 'show' route of account
Currently I have two models, Account and User. Account has many users, and users belongs to account. I want to show account page but keep getting No route matches {:action=>"show", :controller=>"accounts"}, missing required keys: [:id] error.

Accounts controller

```<code>def show
   @account = Account.find_by(params[:id])
end
</code>```

Links to account page

```<code><%= link_to "Account Settings", account_path %>
</code>```

Routes

```<code>resources :accounts, only: [:new, :create, :show, :edit, :update]
</code>```

答:
Problem here:

```<code><%= link_to "Account Settings", account_path %>
</code>```

Rails said 'missing required keys: [:id]' that means that you must send id to show the method

```<code><%= link_to "Account Settings", account_path(123) %>
</code>```

after when somebody will click on your link, the controller will take this id here:

```<code>@account = Account.find_by(params[:id])
</code>```

will find your record into DB, and redirect you to :show page

Title: Ruby on Rails: 'show' route of account

Body:
Currently I have two models, Account and User. Account has many users, and users belongs to account. I want to show account page but keep getting No route matches {:action=>"show", :controller=>"accounts"}, missing required keys: [:id] error.

Accounts controller

def show
   @account = Account.find_by(params[:id])
end

Links to account page

<%= link_to "Account Settings", account_path %>

Routes

resources :accounts, only: [:new, :create, :show, :edit, :update]

Body:
Problem here:

<%= link_to "Account Settings", account_path %>

Rails said 'missing required keys: [:id]' that means that you must send id to show the method

<%= link_to "Account Settings", account_path(123) %>

after when somebody will click on your link, the controller will take this id here:

@account = Account.find_by(params[:id])

will find your record into DB, and redirect you to :show page


来源: stackexchange

问:
java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
So I'm getting the error java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) when I try to connect to MySQL Database from Java code. Everything I was able to find didn't solve the Problem at all and the code is very basic. I used it in projects before and found it like that in many tutorials. So first the relevant code:

```<code>//Inside class that manages SQLConnection
public SQLTransceiver(String url){
        this.connectionURL = url;
        this.reconnect();
}

public void reconnect(){
        try {
            Connection connection = DriverManager.getConnection(this.connectionURL); //Where the error occurs
            this.currentConnection = connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
}

//Inside main class I call this for testing purpose
String s = "jdbc:mysql://localhost:3306/tableName" +
                "?user=user" +
                "&password=thePassword" +
                "&serverTimezone=MET";

DataTransreciever transreciever = new SQLTransceiver(s);
</code>```

NOTE: I can perfectly log into the DB in MySQL workbench and do everything there from creating/altering tables to inserting and all that stuff.

The whole Stacktrace looks like this:

```<code>java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:20)
    at main.ui.toDoPane.ToDoPane.<init>(ToDoPane.java:208)
    at main.ui.Window.start(Window.java:40)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
</code>```

So what did I do to fix this:
It made me wonder why it doesn't state which user was denied note it statets "denied for user ''@'localhost'. So I did put in wrong password and this error came:

```<code>java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:29)
</code>```

So it looks like it at some point does check the user and password. It just gives the first error if user and password are correct.

So I did some lookup and got the solution that is stated for this question a few times (Although often it does state the "Using password: Yes" insted of "No"):

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

It states I should run following statement:

```<code>GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;
</code>```

The Problem is I can't run that. When I try to run it in MySQL Workbench I get the following error:

```<code>0   5   01:12:32    GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION    Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'password' WITH GRANT OPTION' at line 1  0.000 sec
</code>```

Additionally I tried to remove MySQL completely and reinstall it. This didn't help.

Disclaimer:
Password and user was changed for privacy reasons.
In terms of errors it doesn't make a difference calling the DriverManager with connection String and Properties class I did try that to.
Sorry for more basic and maybe bad englisch.
I am using MySQL Server 8.0.20 Community with InnoDB Engine. The J/Connector and MySQL Notifier are for the same Version. I installed all (including the workbench) with the Windows Installer downloaded from: https://dev.mysql.com/downloads/mysql/
I am using Windows 10.

When I remove the "serverTimezone" parameter I get the following error:

```<code>java.sql.SQLException: The server time zone value 'Mitteleurop�ische Sommerzeit' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:28)
</code>```

I don't know if that helps, but it's possible.

Thanks very much in advance :)

答:
Please use the following connection url:

```<code> String s = "jdbc:mysql://localhost:3306/databasename?user=user&password=password&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
</code>```

I hope it's help you, thanks.

ContentLicense: CC BY-SA 4.0

Body:
So I'm getting the error java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) when I try to connect to MySQL Database from Java code. Everything I was able to find didn't solve the Problem at all and the code is very basic. I used it in projects before and found it like that in many tutorials. So first the relevant code:

//Inside class that manages SQLConnection
public SQLTransceiver(String url){
        this.connectionURL = url;
        this.reconnect();
}

public void reconnect(){
        try {
            Connection connection = DriverManager.getConnection(this.connectionURL); //Where the error occurs
            this.currentConnection = connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
}

//Inside main class I call this for testing purpose
String s = "jdbc:mysql://localhost:3306/tableName" +
                "?user=user" +
                "&password=thePassword" +
                "&serverTimezone=MET";

DataTransreciever transreciever = new SQLTransceiver(s);

NOTE: I can perfectly log into the DB in MySQL workbench and do everything there from creating/altering tables to inserting and all that stuff.

The whole Stacktrace looks like this:

java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:20)
    at main.ui.toDoPane.ToDoPane.<init>(ToDoPane.java:208)
    at main.ui.Window.start(Window.java:40)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)

So what did I do to fix this:
It made me wonder why it doesn't state which user was denied note it statets "denied for user ''@'localhost'. So I did put in wrong password and this error came:

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:29)

So it looks like it at some point does check the user and password. It just gives the first error if user and password are correct.

So I did some lookup and got the solution that is stated for this question a few times (Although often it does state the "Using password: Yes" insted of "No"):

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

It states I should run following statement:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;

The Problem is I can't run that. When I try to run it in MySQL Workbench I get the following error:

0   5   01:12:32    GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION    Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'password' WITH GRANT OPTION' at line 1  0.000 sec

Additionally I tried to remove MySQL completely and reinstall it. This didn't help.

Disclaimer:
Password and user was changed for privacy reasons.
In terms of errors it doesn't make a difference calling the DriverManager with connection String and Properties class I did try that to.
Sorry for more basic and maybe bad englisch.
I am using MySQL Server 8.0.20 Community with InnoDB Engine. The J/Connector and MySQL Notifier are for the same Version. I installed all (including the workbench) with the Windows Installer downloaded from: https://dev.mysql.com/downloads/mysql/
I am using Windows 10.

When I remove the "serverTimezone" parameter I get the following error:

java.sql.SQLException: The server time zone value 'Mitteleurop�ische Sommerzeit' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at main.data.SQLTransceiver.reconnect(SQLTransceiver.java:31)
    at main.data.SQLTransceiver.<init>(SQLTransceiver.java:26)
    at main.Main.main(Main.java:28)

I don't know if that helps, but it's possible.

Thanks very much in advance :)

Body:
Please use the following connection url:

 String s = "jdbc:mysql://localhost:3306/databasename?user=user&password=password&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";

I hope it's help you, thanks.


问:
How and why JavaScript type coercion works?
var x = 5;

If I run console.log('The number is ' + x);

The output is The number is 5;

But my question is that why the number convert into string?

答:
It's simply because what you wrote in the console.log command outputs a string, therefore when you use 'The number is ' + x what you're doing is essentially string concatenation.

On the other hand if you use console.log(x) you'd get an int response.

You can check this here:

var x = 5;

console.log("The number is " + x);
console.log(typeof ("The number is " + x));

console.log(x);
console.log(typeof x);

console.log(x + x);
console.log(typeof (x + x));```

You can check more on this in MDN's Docs

Body:
It's simply because what you wrote in the console.log command outputs a string, therefore when you use 'The number is ' + x what you're doing is essentially string concatenation.

On the other hand if you use console.log(x) you'd get an int response.

You can check this here:

var x = 5;

console.log("The number is " + x);
console.log(typeof ("The number is " + x));

console.log(x);
console.log(typeof x);

console.log(x + x);
console.log(typeof (x + x));

You can check more on this in MDN's Docs


问:
How to put condition in Codeigniter 4 model
I have this model in Codeigniter 4.

```<code>class CommentsModel extends Model
{
    protected $table = 'comments';

    protected $allowedFields = ['com_user', 'com_email', 'com_phone', 'comment'];

}
</code>```

and this route

```<code>public function comments()
    {
        $model = new CommentsModel();

        $data = [
            'comments' => $model->paginate(50),
            'pager' => $model->pager
        ];

        echo view('templates/header');
        echo view('templates/aside');
        return view('comments', $data);
        echo view('templates/footer');
    }
</code>```

I want to put condition WHERE so that this will get only comments that meet with the condition....Please help!

答:
Use Where clause in active records to get what you want.

```<code>public function comments()
{
    $model = new CommentsModel();
    $model = $model->where('com_user','john');
    $data = [
        'comments' => $model->paginate(50),
        'pager' => $model->pager
    ];

    echo view('templates/header');
    echo view('templates/aside');
    return view('comments', $data);
    echo view('templates/footer');
}
</code>```

Body:
I have this model in Codeigniter 4.

class CommentsModel extends Model
{
    protected $table = 'comments';

    protected $allowedFields = ['com_user', 'com_email', 'com_phone', 'comment'];

}

and this route

public function comments()
    {
        $model = new CommentsModel();

        $data = [
            'comments' => $model->paginate(50),
            'pager' => $model->pager
        ];

        echo view('templates/header');
        echo view('templates/aside');
        return view('comments', $data);
        echo view('templates/footer');
    }

I want to put condition WHERE so that this will get only comments that meet with the condition....Please help!

Body:
Use Where clause in active records to get what you want.

public function comments()
{
    $model = new CommentsModel();
    $model = $model->where('com_user','john');
    $data = [
        'comments' => $model->paginate(50),
        'pager' => $model->pager
    ];

    echo view('templates/header');
    echo view('templates/aside');
    return view('comments', $data);
    echo view('templates/footer');
}


问:
NodeJS - Nested Promise inside a for loop
I am trying to do a call which retrieves a list of categories. Inside this call I want to loop through the categories and retrieve the items for each category and return them all together. My call retrieves the categories perfectly before I added the loop to retrieve the items.

To double check my call to another controller works, I added a proof of concept block of code which you can see below is commented out. So I know it isn't the call to an external class.

Here is my code:

```<code>'use strict';
var mongoose = require('mongoose'),
MenuCategory = mongoose.model('MenuCategory');

module.exports = function(menuItemController) {
  var mod = {
    listEntireMenu(req, res) {

      return new Promise(function(resolve, reject) {

        var entireMenu = [];

        MenuCategory.find({}, function(err, menuCategories) {
           if (err) {
             return reject(err)
           } else {

             //---------------------------
             // PROOF OF CONCEPT THAT CALL TO OTHER CONTROLLER WORKS
             //---------------------------
             //
             // var categoryWithItems = menuCategories[0].toObject();
             // req.body.menuCategoryID = categoryWithItems._id;
             // menuItemController.listAllMenuItemsByCategory(req, res).then((menuItems) => {
             //   if(menuItems)
             //   {
             //     return resolve(menuItems);
             //   }
             //   else
             //   {
             //     return { success: false }
             //   }
             // });
             //-----------------------------

            for (var i = 0; i < menuCategories.length; i++) {
                  var categoryWithItems = menuCategories[i].toObject();
                  var subItems = [];

                  req.body.menuCategoryID = categoryWithItems._id;
                  menuItemController.listAllMenuItemsByCategory(req, res).then((menuItems) => {
                  if(menuItems)
                  {
                    subItems = menuItems;
                  }
                  else
                  {
                    return { success: false }
                  }
                });

                categoryWithItems.tester = { "itemsList" : subItems };
                entireMenu.push(categoryWithItems);

             }
             return resolve(entireMenu)
           }
         });
       }).then((menuCategories) => {

         if(menuCategories)
         {
           return menuCategories
         }
         else
         {
           return { success: false }
         }
       });
    },
   }
   return mod;
};
</code>```

What I actually get returned is this :

```<code>[
    {
        "_id": "5ed16fxxxxxxxx95676e37",
        "locationID": "5ed16xxxxxxxx7295676e36",
        "menuCategoryName": "Category One",
        "Created_date": "2020-05-29T20:26:34.991Z",
        "__v": 0,
        "tester": {
            "itemsList": []
        }
    },
    {
        "_id": "5ed170xxxxxx95676e38",
        "locationID": "5ed16xxxxxxxx7295676e36",
        "menuCategoryName": "Category Two",
        "Created_date": "2020-05-29T20:26:48.799Z",
        "__v": 0,
        "tester": {
            "itemsList": []
        }
    }
]
</code>```

Here is the call from the route.js :

```<code>app.get('/api/listEntireMenu', (req, res) => {
    menuCategoryController.listEntireMenu(req, res).then(menuCategories => res.json(menuCategories));
})
</code>```

It never writes the subItems into the object. Is this an async issue or something else? I am not sure how to solve this.

Thanks in advance.

答:
i believe the reason the result of your call to resolve is being returned before the requests are able to complete...for this you need to wait until all the promises or requests have finished properly and returned.

There are two ways you can do this: you could either run them one by one and wait for each one to finish first or run them all concurrently until all of them are done.

Ofcourse the fastest way to do it would be to run them all concurrently so lets go for that way:

so to start, let us not use the for loop and instead remap the iterable array menuCategories to promises of the request, we will use your proof of concept code to make the array of promises

```<code>//...
Promise.all(
  menuCategories.map((category) => {
    let category_with_items = category.toObject();

    req.body.menuCategoryID = category_with_items._id;

    // here we need to return this since its the promise we are remapping to
    return menuItemController.listAllMenuItemsByCategory(req, res)
      .then((menuitems) => {
         if(menuItems) {
           return menuitems;
         }

         throw 'No menu items found'
      });
  });
)
// each promise will return menuitems so we have to wait for all the promises to complete
// then with the results of each promise we push the items into the entire menu
.then((itemslist) => {
  itemslist.forEach((items) => entireMenu.push(items));

  return entireMenu;
})
// lastly we need to handle any errors from the promises
.catch((error) => { success: false });
//...
</code>```

So now we have...

```<code>listEntireMenu(req, res) {
  return MenuCategory.find({}, function(err, menuCategories) {
    if (err) {
      throw err
    } else {
      entireMenu = [];

      return /* the promise all call from above will go right here */;
    }
}
</code>```

I hope it works out, thanks...

Body:
I am trying to do a call which retrieves a list of categories. Inside this call I want to loop through the categories and retrieve the items for each category and return them all together. My call retrieves the categories perfectly before I added the loop to retrieve the items.

To double check my call to another controller works, I added a proof of concept block of code which you can see below is commented out. So I know it isn't the call to an external class.

Here is my code:

'use strict';
var mongoose = require('mongoose'),
MenuCategory = mongoose.model('MenuCategory');

module.exports = function(menuItemController) {
  var mod = {
    listEntireMenu(req, res) {

      return new Promise(function(resolve, reject) {

        var entireMenu = [];

        MenuCategory.find({}, function(err, menuCategories) {
           if (err) {
             return reject(err)
           } else {

             //---------------------------
             // PROOF OF CONCEPT THAT CALL TO OTHER CONTROLLER WORKS
             //---------------------------
             //
             // var categoryWithItems = menuCategories[0].toObject();
             // req.body.menuCategoryID = categoryWithItems._id;
             // menuItemController.listAllMenuItemsByCategory(req, res).then((menuItems) => {
             //   if(menuItems)
             //   {
             //     return resolve(menuItems);
             //   }
             //   else
             //   {
             //     return { success: false }
             //   }
             // });
             //-----------------------------

            for (var i = 0; i < menuCategories.length; i++) {
                  var categoryWithItems = menuCategories[i].toObject();
                  var subItems = [];

                  req.body.menuCategoryID = categoryWithItems._id;
                  menuItemController.listAllMenuItemsByCategory(req, res).then((menuItems) => {
                  if(menuItems)
                  {
                    subItems = menuItems;
                  }
                  else
                  {
                    return { success: false }
                  }
                });

                categoryWithItems.tester = { "itemsList" : subItems };
                entireMenu.push(categoryWithItems);

             }
             return resolve(entireMenu)
           }
         });
       }).then((menuCategories) => {

         if(menuCategories)
         {
           return menuCategories
         }
         else
         {
           return { success: false }
         }
       });
    },
   }
   return mod;
};

What I actually get returned is this :

[
    {
        "_id": "5ed16fxxxxxxxx95676e37",
        "locationID": "5ed16xxxxxxxx7295676e36",
        "menuCategoryName": "Category One",
        "Created_date": "2020-05-29T20:26:34.991Z",
        "__v": 0,
        "tester": {
            "itemsList": []
        }
    },
    {
        "_id": "5ed170xxxxxx95676e38",
        "locationID": "5ed16xxxxxxxx7295676e36",
        "menuCategoryName": "Category Two",
        "Created_date": "2020-05-29T20:26:48.799Z",
        "__v": 0,
        "tester": {
            "itemsList": []
        }
    }
]

Here is the call from the route.js :

app.get('/api/listEntireMenu', (req, res) => {
    menuCategoryController.listEntireMenu(req, res).then(menuCategories => res.json(menuCategories));
})

It never writes the subItems into the object. Is this an async issue or something else? I am not sure how to solve this.

Thanks in advance.

Body:
i believe the reason the result of your call to resolve is being returned before the requests are able to complete...for this you need to wait until all the promises or requests have finished properly and returned.

There are two ways you can do this: you could either run them one by one and wait for each one to finish first or run them all concurrently until all of them are done.

Ofcourse the fastest way to do it would be to run them all concurrently so lets go for that way:

so to start, let us not use the for loop and instead remap the iterable array menuCategories to promises of the request, we will use your proof of concept code to make the array of promises

//...
Promise.all(
  menuCategories.map((category) => {
    let category_with_items = category.toObject();

    req.body.menuCategoryID = category_with_items._id;

    // here we need to return this since its the promise we are remapping to
    return menuItemController.listAllMenuItemsByCategory(req, res)
      .then((menuitems) => {
         if(menuItems) {
           return menuitems;
         }

         throw 'No menu items found'
      });
  });
)
// each promise will return menuitems so we have to wait for all the promises to complete
// then with the results of each promise we push the items into the entire menu
.then((itemslist) => {
  itemslist.forEach((items) => entireMenu.push(items));

  return entireMenu;
})
// lastly we need to handle any errors from the promises
.catch((error) => { success: false });
//...

So now we have...

listEntireMenu(req, res) {
  return MenuCategory.find({}, function(err, menuCategories) {
    if (err) {
      throw err
    } else {
      entireMenu = [];

      return /* the promise all call from above will go right here */;
    }
}

I hope it works out, thanks...


答: In type coercion, i.e comparing or calculating two operands of a different type, one of them will be converted to an equivalent type. The reason number is converted to string is because every number can be a string but the opposite can't always be true, so the type coercion always converts a number to a string

Title: How and why JavaScript type coercion works?

Body:
var x = 5;

If I run console.log('The number is ' + x);

The output is The number is 5;

But my question is that why the number convert into string?


问:
Need to grep file with specific extension and move to another folder
I want to write a bash command that greps all *.txt file with a pattern in current folder to another folder. Should I use find or for loop? I tried using find but it seems to complicate things.

Edit: I want to copy files with a specific pattern to a different folder. For example:

```<code>A.txt
B.txt
C.txt
</code>```

all have the word "foo" in them. I want grep to remove "foo" and send it to a different folder with the same name. I don't want to change the original file in any way.

答:
You could do this with find. (You need the sh -c to get the > redirection to work.)

```<code>find -name '*.txt' -exec sh -c 'grep -v foo {} > new/{}' \;
</code>```

Or with a for loop. This will be more robust when handling unusual file names, such as files with spaces.

```<code>for FILE in *.txt; do
    grep -v foo "$FILE" > "new/$FILE"
done
</code>```

If the files are in some other directory old rather than the current directory, use basename to strip out the directory:

```<code>for FILE in old/*.txt; do
    grep -v foo "$FILE" > "new/$(basename "$FILE")"
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to write a bash command that greps all *.txt file with a pattern in current folder to another folder. Should I use find or for loop? I tried using find but it seems to complicate things.

Edit: I want to copy files with a specific pattern to a different folder. For example:

A.txt
B.txt
C.txt

all have the word "foo" in them. I want grep to remove "foo" and send it to a different folder with the same name. I don't want to change the original file in any way.

Body:
You could do this with find. (You need the sh -c to get the > redirection to work.)

find -name '*.txt' -exec sh -c 'grep -v foo {} > new/{}' \;

Or with a for loop. This will be more robust when handling unusual file names, such as files with spaces.

for FILE in *.txt; do
    grep -v foo "$FILE" > "new/$FILE"
done

If the files are in some other directory old rather than the current directory, use basename to strip out the directory:

for FILE in old/*.txt; do
    grep -v foo "$FILE" > "new/$(basename "$FILE")"
done


问:
Maven won't run JUnit5 tests
(BTW: Yes, I am including the Maven surefire plugin in my pom.)

I can't persuade Maven to run my JUnit5 tests.

I am using the Maven surefire plugin version 2.22

I tried downgrading the surefire plugin to 2.19

I'm using the same dependencies and plugins as another project which runs fine

If I import the project into eclipse, eclipse finds and executes the tests

The class file for the test, app.AppTest.class, is in directory target\test-classes\app

I don't get any error messages from Maven; it just says "Tests run: 0, Failures: 0, Errors: 0, Skipped: 0"

I am including the contents of my pom, below. Can anyone tell me what I'm doing wrong? Thanks for the help.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>uw.syp.java</groupId>
  <artifactId>Temp1</artifactId>
  <packaging>jar</packaging>
  <version>01</version>
  <name>Temp1</name>
  <url>http://maven.apache.org</url>

    <properties>
       <developer>JesseJW</developer>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <arg>-Xlint:all</arg>
                        <arg>-Xlint:-serial</arg>
                    </compilerArgs>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

As requested: source code including imports:
    package app;

```<code>import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import java.net.URL;
import javax.swing.JOptionPane;

class AppTest
{
    void test()
    {
        System.out.println( "*************" );
        URL resURL  =  getClass().getClassLoader().getResource( "ResFile.txt" );
        System.out.println( resURL );
        assertNotNull( resURL );
        if ( resURL != null )
        {
            System.out.println( resURL.getPath() );
        }
    }
}
</code>```

答:
Maybe your code imports wrong Test annotation; org.junit.Test, org.testng.annotations.Test, ...

org.junit.jupiter.api.Test should be imported.

```<code>package app;

import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;

public class AppTest {
    @Test
    void test() {
        fail("Not yet implemented");
    }
}
</code>```

Title: Maven won't run JUnit5 tests

Body:
(BTW: Yes, I am including the Maven surefire plugin in my pom.)

I can't persuade Maven to run my JUnit5 tests.

I am using the Maven surefire plugin version 2.22

I tried downgrading the surefire plugin to 2.19

I'm using the same dependencies and plugins as another project which runs fine

If I import the project into eclipse, eclipse finds and executes the tests

The class file for the test, app.AppTest.class, is in directory target\test-classes\app

I don't get any error messages from Maven; it just says "Tests run: 0, Failures: 0, Errors: 0, Skipped: 0"

I am including the contents of my pom, below. Can anyone tell me what I'm doing wrong? Thanks for the help.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>uw.syp.java</groupId>
  <artifactId>Temp1</artifactId>
  <packaging>jar</packaging>
  <version>01</version>
  <name>Temp1</name>
  <url>http://maven.apache.org</url>

    <properties>
       <developer>JesseJW</developer>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <arg>-Xlint:all</arg>
                        <arg>-Xlint:-serial</arg>
                    </compilerArgs>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>

As requested: source code including imports:
    package app;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import java.net.URL;
import javax.swing.JOptionPane;

class AppTest
{
    void test()
    {
        System.out.println( "*************" );
        URL resURL  =  getClass().getClassLoader().getResource( "ResFile.txt" );
        System.out.println( resURL );
        assertNotNull( resURL );
        if ( resURL != null )
        {
            System.out.println( resURL.getPath() );
        }
    }
}

Body:
Maybe your code imports wrong Test annotation; org.junit.Test, org.testng.annotations.Test, ...

org.junit.jupiter.api.Test should be imported.

package app;

import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;

public class AppTest {
    @Test
    void test() {
        fail("Not yet implemented");
    }
}


问:
How can I make a piano sound with function beep?
I need help, my code doesn't output the piano sound.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

//Dó: 261 Hz
//Ré: 293 Hz
//Mi: 329 Hz
//Fá: 349 Hz
//Sol: 392 Hz
//Lá: 440 Hz
//Si: 493 Hz
//Dó(2): 522 Hz

int main(){
setlocale (LC_ALL,"Portuguese");
char nota = ' ';
int tempo = 150;
int som [8] = {261, 293, 329, 349, 392, 440,   493, 522};
puts("### PIANO VIRTUAL ###");
puts("\n m - Dó \n a - Ré \n r - Mi \n c - Fá \n    e - Sol \n l - Lá \n q - Si \n u - Dó*2");

nota = getchar();
switch (nota){
        case 'm': Beep(som[0]); tempo;
        case 'a': Beep(som[1]); tempo;
        case 'r': Beep(som[2]); tempo;
        case 'c': Beep(som[3]); tempo;
        case 'e': Beep(som[4]); tempo;
        case 'l': Beep(som[5]); tempo;
        case 'q': Beep(som[6]); tempo;
    case 'u': Beep(som[7]); tempo;
    }
}
</code>```

I need that return a piano beep with the function "Beep"

I don't know what more to say so pls help me,

答:
Standard C has no function for sounds.

Check by reading n1570 (the C11 standard) or this reference. There is no Beep there. Read also the Modern C book.

Some operating systems provide APIs and libraries to make sounds. But some computers (e.g. the web server providing you this content) don't even have any loudspeakers or devices capable of producing a nice sound (apart their fans). Any sound-related function is either operating system or computer specific. On an Arduino, your C code producing a sound would be very different than one for my Linux desktop.

On Linux, read about ALSA and consider using libsdl (which is an abstraction layer working on several OSes). On Windows, study the WinAPI.

You could code something interacting with your web browser and have your web browser produce a sound (if your computer can do that). Then learn more about the HTTP protocol and HTML5 and JavaScript.

You could find several libraries (for Linux at least) providing an API for HTTP services. For example libonion.

Read of course How to debug small programs

If you compile your  C code with GCC, be sure to enable all warnings and debug info, so compile with gcc -Wall -Wextra -g. Learn also to use some build automation tool such as GNU make or ninja, etc....

Body:
I need help, my code doesn't output the piano sound.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

//Dó: 261 Hz
//Ré: 293 Hz
//Mi: 329 Hz
//Fá: 349 Hz
//Sol: 392 Hz
//Lá: 440 Hz
//Si: 493 Hz
//Dó(2): 522 Hz

int main(){
setlocale (LC_ALL,"Portuguese");
char nota = ' ';
int tempo = 150;
int som [8] = {261, 293, 329, 349, 392, 440,   493, 522};
puts("### PIANO VIRTUAL ###");
puts("\n m - Dó \n a - Ré \n r - Mi \n c - Fá \n    e - Sol \n l - Lá \n q - Si \n u - Dó*2");

nota = getchar();
switch (nota){
        case 'm': Beep(som[0]); tempo;
        case 'a': Beep(som[1]); tempo;
        case 'r': Beep(som[2]); tempo;
        case 'c': Beep(som[3]); tempo;
        case 'e': Beep(som[4]); tempo;
        case 'l': Beep(som[5]); tempo;
        case 'q': Beep(som[6]); tempo;
    case 'u': Beep(som[7]); tempo;
    }
}

I need that return a piano beep with the function "Beep"

I don't know what more to say so pls help me,


问:
'instantiated view controller with identifier "" from storyboard "Main", but didn't get a UITableView' while trying to present view controller modally
I'm trying to display a table view inside a container view, which itself is a part of a view controller. Here's my HomeScreenViewController, which has a button that segues to the BroadcastSearchViewController.

Once I click the button, however, I'm getting the following runtime error. Why? What can I do to make this work? Do I need to switch up my design somehow?

```<code>Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: '-[UITableViewController loadView] instantiated view controller with identifier
"UIViewController-OSu-KC-K41" from storyboard "Main", but didn't get a UITableView.'
</code>```

Here's what my BroadcastSearchViewController looks like in Storyboard. It's presented modally from clicking the search button.

And here's what my table view controller, which is embedded in the container view, looks like:

BroadcastSearchViewController.swift

```<code>class BroadcastSearchViewController : UIViewController {

    @IBOutlet weak var broadcastSearchBar: UISearchBar!
    @IBOutlet weak var broadcastSearchSegmentedControl: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

}
</code>```

BroadcastSearchResultsTableViewController.swift

```<code>class BroadcastSearchResultsTableViewController : UITableViewController {

    let datasource = BroadcastSearchResultsTableViewDataSource()

    override func viewDidLoad() {
        datasource.broadcasts = [
            Broadcast(
                song: Song(id: "1", title: "November Rain", artist: "Guns N' Roses"),
                user: User(username: "sylphrenetic")
            ),
            Broadcast(
                song: Song(id: "2", title: "How To Disappear Completely", artist: "Radiohead"),
                user: User(username: "sylphrenetic")
            )
        ]
        self.tableView.dataSource = datasource
        self.tableView.reloadData()
    }

}
</code>```

答: I ended up figuring it out from this answer on a different question. Following those steps, I realized I needed to remove the default view controller and replace it with a new table view controller manually, instead of just setting the view controller to be my table view controller. This was confusing at first but it makes sense now that you can't have a UITableView inside of a UIView.</p>

Body:
I'm trying to display a table view inside a container view, which itself is a part of a view controller. Here's my HomeScreenViewController, which has a button that segues to the BroadcastSearchViewController.

Once I click the button, however, I'm getting the following runtime error. Why? What can I do to make this work? Do I need to switch up my design somehow?

Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: '-[UITableViewController loadView] instantiated view controller with identifier
"UIViewController-OSu-KC-K41" from storyboard "Main", but didn't get a UITableView.'

Here's what my BroadcastSearchViewController looks like in Storyboard. It's presented modally from clicking the search button.

And here's what my table view controller, which is embedded in the container view, looks like:

BroadcastSearchViewController.swift

class BroadcastSearchViewController : UIViewController {

    @IBOutlet weak var broadcastSearchBar: UISearchBar!
    @IBOutlet weak var broadcastSearchSegmentedControl: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

}

BroadcastSearchResultsTableViewController.swift

class BroadcastSearchResultsTableViewController : UITableViewController {

    let datasource = BroadcastSearchResultsTableViewDataSource()

    override func viewDidLoad() {
        datasource.broadcasts = [
            Broadcast(
                song: Song(id: "1", title: "November Rain", artist: "Guns N' Roses"),
                user: User(username: "sylphrenetic")
            ),
            Broadcast(
                song: Song(id: "2", title: "How To Disappear Completely", artist: "Radiohead"),
                user: User(username: "sylphrenetic")
            )
        ]
        self.tableView.dataSource = datasource
        self.tableView.reloadData()
    }

}


问:
How to get a column YYYY as procces_year and MM AS process_month from a date with YYYYMMDD and YYYYMM format? in Netezza sql
I have some dates like 20190101 (YYYYMMDD) and 201901 (YYYYMM) in a column called process_date and I need two columns, a column called process_year with the year (YYYY) and process_month with the month (MM), when I use

```<code>date_part('year',process_date::numeric(8,0)) as process_year
</code>```

the dates in format 201901 (YYYYMM) take the value '20' and same with

```<code>date_part('month',process_date::numeric(8,0)) as process_month
</code>```

take the value '19' to the same format 201901 (YYYYMM)

答:
I found one method:

```<code>substr(process_date,1,4) as process_year
</code>```

and

```<code>substr(process_date,5,2) as process_month
</code>```

Thanks for your help.

Body:
I have some dates like 20190101 (YYYYMMDD) and 201901 (YYYYMM) in a column called process_date and I need two columns, a column called process_year with the year (YYYY) and process_month with the month (MM), when I use

date_part('year',process_date::numeric(8,0)) as process_year

the dates in format 201901 (YYYYMM) take the value '20' and same with

date_part('month',process_date::numeric(8,0)) as process_month

take the value '19' to the same format 201901 (YYYYMM)

Body:
I found one method:

substr(process_date,1,4) as process_year

and

substr(process_date,5,2) as process_month

Thanks for your help.


问:
string value returning null value
In my code when i try to print the value of result inside the function str its showing null all the time. Could some pls give a input.
It showing correct value When i tried to display the value of result inside the for loop fir each iteration.</p>

```<code>string str(string s, int mid){

string result;
for(int j=0;j<=mid;j++){
    result[j]= s[j];
}
return result;
}

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
    int min= 0, max= 0,mid = 0;
    string temp2;
    max = strs[0].length()-1;
    mid = (min + max)/2;
    string temp = str(strs[0],mid);
    int flag1 = 0,flag2 = 1;

    cout<<temp<<endl;
    while(1){
        for(int i=1;i<strs.size(); i++){
            if(strs[i].compare(0,mid+1,temp,0,mid+1)!=0){
                if(flag1 == 1)
                    return temp2;
                if(mid == 0)
                    return " ";
                max = mid;
                temp2 = temp;
                mid = (min + max)/2;
                cout<<temp<<endl;
                temp = str(strs[0],mid);
                i = 1;
            }
            if(i+1 == strs.size()){
                if(mid == max)
                    return temp;
                min = mid;
                temp2 = temp;
                mid = (min + max)/2;
                temp = str(strs[0],mid);
                i = 1;
                flag1 = 1;
            }
        }
        return " ";
    }
}
</code>```

答:
You can't resize the string using operator[]. You are writing out of bounds and causing undefined behavior. Use

```<code>result += s[j];
</code>```

to add characters or initialize the string with the correct size

```<code>string result(mid, '\0');
</code>```

or simply copy the string;

```<code>auto result = s.substr(0, mid + 1);
</code>```

You could replace the function str by

```<code>string str(string s, int mid){
    return s.substr(0, mid + 1);
}
</code>```

or even remove the function and replace each call

```<code>str(strs[0],mid)
</code>```

by a call to

```<code>strs[0].substr(0, mid + 1)
</code>```

Title: string value returning null value

Body:
In my code when i try to print the value of result inside the function str its showing null all the time. Could some pls give a input.
It showing correct value When i tried to display the value of result inside the for loop fir each iteration.

string str(string s, int mid){

string result;
for(int j=0;j<=mid;j++){
    result[j]= s[j];
}
return result;
}

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
    int min= 0, max= 0,mid = 0;
    string temp2;
    max = strs[0].length()-1;
    mid = (min + max)/2;
    string temp = str(strs[0],mid);
    int flag1 = 0,flag2 = 1;

    cout<<temp<<endl;
    while(1){
        for(int i=1;i<strs.size(); i++){
            if(strs[i].compare(0,mid+1,temp,0,mid+1)!=0){
                if(flag1 == 1)
                    return temp2;
                if(mid == 0)
                    return " ";
                max = mid;
                temp2 = temp;
                mid = (min + max)/2;
                cout<<temp<<endl;
                temp = str(strs[0],mid);
                i = 1;
            }
            if(i+1 == strs.size()){
                if(mid == max)
                    return temp;
                min = mid;
                temp2 = temp;
                mid = (min + max)/2;
                temp = str(strs[0],mid);
                i = 1;
                flag1 = 1;
            }
        }
        return " ";
    }
}

Body:
You can't resize the string using operator[]. You are writing out of bounds and causing undefined behavior. Use

result += s[j];

to add characters or initialize the string with the correct size

string result(mid, '\0');

or simply copy the string;

auto result = s.substr(0, mid + 1);

You could replace the function str by

string str(string s, int mid){
    return s.substr(0, mid + 1);
}

or even remove the function and replace each call

str(strs[0],mid)

by a call to

strs[0].substr(0, mid + 1)


问:
"error: command 'gcc' failed with exit status 1" when trying to install python-language-server
I've below pip installed in my system

```<code>    $ pip --version
    pip 19.3.1 from /usr/lib/python3.8/site-packages/pip (python 3.8)
</code>```

python version installed in my system is -

```<code>    $ python --version
    Python 3.8.3
</code>```

I'm trying to install python-language-server and encountered below error -

Running setup.py install for ujson ... error
     ERROR: Command errored out with exit status 1:
      command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"'; file='"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-h4azsb93/install-record.txt --single-version-externally-managed --compile
          cwd: /tmp/pip-install-yoqmgayp/ujson/
     Complete output (16 lines):
     Warning: 'classifiers' should be a list, got type 'filter'
     running install

     running build

     running build_ext

     building 'ujson' extension

     creating build

     creating build/temp.linux-x86_64-3.8
     creating build/temp.linux-x86_64-3.8/python
     creating build/temp.linux-x86_64-3.8/lib
     gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I./python -I./lib -I/usr/include/python3.8 -c ./python/ujson.c -o build/temp.linux-x86_64-3.8/./python/ujson.o -D_GNU_SOURCE
     In file included from ./python/ujson.c:39:
     ./python/py_defines.h:39:10: fatal error: Python.h: No such file or directory
        39 | #include
           |          ^~~~~~~~~~
     compilation terminated.
     error: command 'gcc' failed with exit status 1

ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"'; file='"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-h4azsb93/install-record.txt --single-version-externally-managed --compile Check the logs for full command output.

Below is my OS details -

```<code>    $ lsb_release -a
    LSB Version:    :core-4.1-amd64:core-4.1-noarch
    Distributor ID: Fedora
    Description:    Fedora release 32 (Thirty Two)
    Release:        32
    Codename:       ThirtyTwo
</code>```

How can I fix this error?

答:
If you read the word message, it tells you what is wrong

```<code>./python/py_defines.h:39:10: fatal error: Python.h: No such file or directory
</code>```

It says it can't find the header file. Ask dnf about what provides it:

```<code>sudo dnf provides '*/Python.h'
</code>```

Then install that package (sudo dnf install ...) and retry your original command.

Body:
I've below pip installed in my system

    $ pip --version
    pip 19.3.1 from /usr/lib/python3.8/site-packages/pip (python 3.8)

python version installed in my system is -

    $ python --version
    Python 3.8.3

I'm trying to install python-language-server and encountered below error -

Running setup.py install for ujson ... error
     ERROR: Command errored out with exit status 1:
      command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"'; file='"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-h4azsb93/install-record.txt --single-version-externally-managed --compile
          cwd: /tmp/pip-install-yoqmgayp/ujson/
     Complete output (16 lines):
     Warning: 'classifiers' should be a list, got type 'filter'
     running install

     running build

     running build_ext

     building 'ujson' extension

     creating build

     creating build/temp.linux-x86_64-3.8
     creating build/temp.linux-x86_64-3.8/python
     creating build/temp.linux-x86_64-3.8/lib
     gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I./python -I./lib -I/usr/include/python3.8 -c ./python/ujson.c -o build/temp.linux-x86_64-3.8/./python/ujson.o -D_GNU_SOURCE
     In file included from ./python/ujson.c:39:
     ./python/py_defines.h:39:10: fatal error: Python.h: No such file or directory
        39 | #include
           |          ^~~~~~~~~~
     compilation terminated.
     error: command 'gcc' failed with exit status 1

ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"'; file='"'"'/tmp/pip-install-yoqmgayp/ujson/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-h4azsb93/install-record.txt --single-version-externally-managed --compile Check the logs for full command output.

Below is my OS details -

    $ lsb_release -a
    LSB Version:    :core-4.1-amd64:core-4.1-noarch
    Distributor ID: Fedora
    Description:    Fedora release 32 (Thirty Two)
    Release:        32
    Codename:       ThirtyTwo

How can I fix this error?

Body:
If you read the word message, it tells you what is wrong

./python/py_defines.h:39:10: fatal error: Python.h: No such file or directory

It says it can't find the header file. Ask dnf about what provides it:

sudo dnf provides '*/Python.h'

Then install that package (sudo dnf install ...) and retry your original command.


问:
Spring security - endpoint only for admin
I would like to make "users" with the role "Administrator" accessible to endpoint "/admin/**", unfortunately no one has access to this API at this time. What am I doing wrong</p>

```<code>@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/login/").permitAll()
                .antMatchers("/api/books/*").authenticated()
                .antMatchers("/api/admin/**").hasAuthority("Administrator")
                .and()
                .addFilter(new JwtFilter(authenticationManager()))
                .csrf().disable();

    }
}
</code>```

答:
While using hasAuthority() method you need to add prefix ROLE_ as used below. Also, make sure you are storing roles with prefix ROLE_ in the database.

```<code>@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/login/").permitAll()
            .antMatchers("/api/admin/**").hasAuthority("ROLE_Administrator")
            .antMatchers("/api/books/*").authenticated()
            .and()
            .addFilter(new JwtFilter(authenticationManager()));

    }
}
</code>```

Body:
I would like to make "users" with the role "Administrator" accessible to endpoint "/admin/**", unfortunately no one has access to this API at this time. What am I doing wrong

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/login/").permitAll()
                .antMatchers("/api/books/*").authenticated()
                .antMatchers("/api/admin/**").hasAuthority("Administrator")
                .and()
                .addFilter(new JwtFilter(authenticationManager()))
                .csrf().disable();

    }
}

Body:
While using hasAuthority() method you need to add prefix ROLE_ as used below. Also, make sure you are storing roles with prefix ROLE_ in the database.

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/login/").permitAll()
            .antMatchers("/api/admin/**").hasAuthority("ROLE_Administrator")
            .antMatchers("/api/books/*").authenticated()
            .and()
            .addFilter(new JwtFilter(authenticationManager()));

    }
}


问:
VB Entering a Non_Numeric value crashes the program
Please consider adding a description to this question to attract more helpful responses.

```<code>Public Class Form1
    Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
        Dim intvalue As Integer = CInt(TxtInputClassA.Text)
        Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
        Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
        Dim total As Double
        Try
            LblStatus.Text = String.Empty

            LblClassAResult.Text = (intvalue * 15).ToString("c")
            LblClassBResult.Text = (intvalue2 * 12).ToString("c")
            LblClassCResult.Text = (intvalue3 * 9).ToString("c")
            total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
            LblTotal.Text = total.ToString("c")
        Catch
            LblStatus.Text = "Please Enter a Number"
        End Try
    End Sub

    Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
        Me.Close()
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        TxtInputClassA.Clear()
        TxtInputClassB.Clear()
        TxtinputClassC.Clear()
        LblClassAResult.Text = String.Empty
        LblClassBResult.Text = String.Empty
        LblClassCResult.Text = String.Empty
        LblTotal.Text = String.Empty
    End Sub
End Class
</code>```

VB Entering a Non_Numeric value crashes the program

答:
Its bombing out on your cast "CInt(*value*)" so you can fix the code a couple ways.  You can move your try above the casts like...

```<code>Try
    Dim intvalue As Integer = CInt(TxtInputClassA.Text)
    Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
    Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
    Dim total As Double
    LblStatus.Text = String.Empty
</code>```

You can do a data validation on your inputs and exit if they aren't all numeric (put this above your Dim intvalue code)

```<code>    For Each value As String In {TxtInputClassA.Text, TxtInputClassA.Text, TxtInputClassA.Text}
        If Not IsNumeric(TxtInputClassA.Text) Then
            LblStatus.Text = "Please Enter a Number"
            Exit Sub
        End If
    Next
</code>```

Instead of casting as an int, use the tryparse method on Int32...

```<code>    Dim intvalue As Integer
    If Not Int32.TryParse(TxtInputClassA.Text, intvalue) Then
        Exit Sub
    End If
</code>```

Or you could intercept the keypresses on each text box so that only numbers can be entered

```<code>Private Sub TxtInputClassA_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress

    If Not Char.IsDigit(e.KeyChar) Then
        e.Handled = True
    End If

End Sub
</code>```

You can make that routine universal and append the event handler for all three text boxes like...

```<code>Private Sub EnforceOnlyNumericKeyPresses(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress, TxtInputClassB.KeyPress, TxtInputClassC.KeyPress

    If Not Char.IsDigit(e.KeyChar) Then
        e.Handled = True
    End If

End Sub
</code>```

Choose your favorite or do all of them, lots of choices.

Body:
Please consider adding a description to this question to attract more helpful responses.

Public Class Form1
    Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
        Dim intvalue As Integer = CInt(TxtInputClassA.Text)
        Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
        Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
        Dim total As Double
        Try
            LblStatus.Text = String.Empty

            LblClassAResult.Text = (intvalue * 15).ToString("c")
            LblClassBResult.Text = (intvalue2 * 12).ToString("c")
            LblClassCResult.Text = (intvalue3 * 9).ToString("c")
            total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
            LblTotal.Text = total.ToString("c")
        Catch
            LblStatus.Text = "Please Enter a Number"
        End Try
    End Sub

    Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
        Me.Close()
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        TxtInputClassA.Clear()
        TxtInputClassB.Clear()
        TxtinputClassC.Clear()
        LblClassAResult.Text = String.Empty
        LblClassBResult.Text = String.Empty
        LblClassCResult.Text = String.Empty
        LblTotal.Text = String.Empty
    End Sub
End Class

VB Entering a Non_Numeric value crashes the program

Body:
Its bombing out on your cast "CInt(*value*)" so you can fix the code a couple ways.  You can move your try above the casts like...

Try
    Dim intvalue As Integer = CInt(TxtInputClassA.Text)
    Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
    Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
    Dim total As Double
    LblStatus.Text = String.Empty

You can do a data validation on your inputs and exit if they aren't all numeric (put this above your Dim intvalue code)

    For Each value As String In {TxtInputClassA.Text, TxtInputClassA.Text, TxtInputClassA.Text}
        If Not IsNumeric(TxtInputClassA.Text) Then
            LblStatus.Text = "Please Enter a Number"
            Exit Sub
        End If
    Next

Instead of casting as an int, use the tryparse method on Int32...

    Dim intvalue As Integer
    If Not Int32.TryParse(TxtInputClassA.Text, intvalue) Then
        Exit Sub
    End If

Or you could intercept the keypresses on each text box so that only numbers can be entered

Private Sub TxtInputClassA_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress

    If Not Char.IsDigit(e.KeyChar) Then
        e.Handled = True
    End If

End Sub

You can make that routine universal and append the event handler for all three text boxes like...

Private Sub EnforceOnlyNumericKeyPresses(sender As Object, e As KeyPressEventArgs) Handles TxtInputClassA.KeyPress, TxtInputClassB.KeyPress, TxtInputClassC.KeyPress

    If Not Char.IsDigit(e.KeyChar) Then
        e.Handled = True
    End If

End Sub

Choose your favorite or do all of them, lots of choices.


问:
SVN having credential problems with Jenkins running as SYSTEM
I have Jenkins running a python script that makes some SVN calls, my problem is that Jenkins tries to run this script as SYSTEM user which doesn't seem to have permission to access the SVN. It prompts me for a password for 'SYSTEM' upon my svn call.

If I run the python script by itself, I have no problems accessing the repository. Is there a way to have Jenkins run its Windows batch command as a non-SYSTEM user? I would rather not hardcode the SVN username and password in my script.

Edit: I found a way to change the user Jenkins runs under, it is accessed through:
Start > Control Panel > Administrative Tools > Services > Right Click, Properties for jenkins > Log On.

答:
Create a new Jenkins job, and use Subversion as the revision control system. Put in the URL of the Subversion repository you want to manipulate in your Python script. Under the URL will appear a link to let you set the login. Click the link and log in.

Once you're done, you can delete the job. The whole purpose was to allow Jenkins to set up Subversion to allow that user to login in for that repository URL.


问:
How can I reject user registration with certain username in default laravel register form?
I'm trying to block users from using certain names like 'admin' or 'operator'.

I've tried fiddling with both Controllers/Auth/RegisterController and Controller/RegisterController but failed.

What I've tried was something like this:

```<code>in Controllers/Auth/RegisterController,

if ($data['name'] === 'admin' || $data['name'] === 'operator') {
             return redirect()->back()->withErrors(['Invalid username']);
        }
else {
    session()->flash('message', 'Welcome!');

    return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
            ]);
        }
</code>```

The code above gave me this error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an
  instance of Illuminate\Contracts\Auth\Authenticatable, string given,
  called in /var/www/vendor/laravel/ui/auth-backend/RegistersUsers.php
  on line 36

I've also searched whether validators can block specific words but failed.
I know I can work this around by using JS, but I think Laravel would have some function like this.

答:
Create RegisterControllerRequest using the following command:

```<code>php artisan make:request RegisterControllerRequest
</code>```

find out your recent created file in app/Http/Requests, then update rules() to be:

```<code>public function rules()
{
    return [
        'name' => 'required|notIn:admin,operator',
    ];
}
</code>```

Then update your controller to use the new validation:

After name space add:

```<code>use  App\Http\Requests\RegisterControllerRequest;
</code>```

And finally inject the validation as a parameter in your register method:

```<code>public function register (RegisterControllerRequest $request)
</code>```

For more information check documentation: https://laravel.com/docs/7.x/validation#form-request-validation

Body:
I'm trying to block users from using certain names like 'admin' or 'operator'.

I've tried fiddling with both Controllers/Auth/RegisterController and Controller/RegisterController but failed.

What I've tried was something like this:

in Controllers/Auth/RegisterController,

if ($data['name'] === 'admin' || $data['name'] === 'operator') {
             return redirect()->back()->withErrors(['Invalid username']);
        }
else {
    session()->flash('message', 'Welcome!');

    return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
            ]);
        }

The code above gave me this error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an
  instance of Illuminate\Contracts\Auth\Authenticatable, string given,
  called in /var/www/vendor/laravel/ui/auth-backend/RegistersUsers.php
  on line 36

I've also searched whether validators can block specific words but failed.
I know I can work this around by using JS, but I think Laravel would have some function like this.

Body:
Create RegisterControllerRequest using the following command:

php artisan make:request RegisterControllerRequest

find out your recent created file in app/Http/Requests, then update rules() to be:

public function rules()
{
    return [
        'name' => 'required|notIn:admin,operator',
    ];
}

Then update your controller to use the new validation:

After name space add:

use  App\Http\Requests\RegisterControllerRequest;

And finally inject the validation as a parameter in your register method:

public function register (RegisterControllerRequest $request)

For more information check documentation: https://laravel.com/docs/7.x/validation#form-request-validation


问:
Is there a simple way to condense if statements into a function to check arguments?
I have a switch statement for handling commands, and it works as intended. However, I also have tons of commands/cases. The error checking is to make sure that the program won't crash if they type something that isn't a number. Is there a way to condense those if statements into a function somehow?

```<code>case "test":
        if (typeof args[1] === 'string')
        {
            args[1] = parseInt(args[1])
            Functions.packs = args[1];
        }
        else if(Number.isNaN(+args[1]))
        {
            message.reply("The command was invalid.");
            break;
        }
        else
        {
            message.reply("The command was invalid.");
            break;
        }
</code>```

This is currently what the start of every command looks like, and it is becoming tedious to check commands. I have tried making a function for it, but nothing I tried has worked, so I doubt I'm on the right track.

答:
I would attempt to use .toString() to force everything to be string and then parseInt() the result.  Allows you to just test for NaN...</p>

```<code>var numberTest = function(testArg){
  var testString = testArg.toString();
  var testNumber = parseInt(testString);
  var returnObj = {
    number: testNumber,
    valid: Number.isNaN(testNumber)
  };
  return returnObj;
}

case "test":
  var argTest = numberTest(args[1]);
  if(argTest.valid){
    Functions.packs = argTest.number;
  }
  else{
    message.reply("The command was invalid.");
  }
  break;
</code>```

Body:
I have a switch statement for handling commands, and it works as intended. However, I also have tons of commands/cases. The error checking is to make sure that the program won't crash if they type something that isn't a number. Is there a way to condense those if statements into a function somehow?

case "test":
        if (typeof args[1] === 'string')
        {
            args[1] = parseInt(args[1])
            Functions.packs = args[1];
        }
        else if(Number.isNaN(+args[1]))
        {
            message.reply("The command was invalid.");
            break;
        }
        else
        {
            message.reply("The command was invalid.");
            break;
        }

This is currently what the start of every command looks like, and it is becoming tedious to check commands. I have tried making a function for it, but nothing I tried has worked, so I doubt I'm on the right track.

Body:
I would attempt to use .toString() to force everything to be string and then parseInt() the result.  Allows you to just test for NaN...

var numberTest = function(testArg){
  var testString = testArg.toString();
  var testNumber = parseInt(testString);
  var returnObj = {
    number: testNumber,
    valid: Number.isNaN(testNumber)
  };
  return returnObj;
}

case "test":
  var argTest = numberTest(args[1]);
  if(argTest.valid){
    Functions.packs = argTest.number;
  }
  else{
    message.reply("The command was invalid.");
  }
  break;


问:
How to use Redux to represent Material UI Drawer?
I am trying to implement Drawer, which will appear on the left with a saving state of the Drawer using Redux. But unfortunately, I did something wrong and my onClick events just don`t respond. Code:

Reducer:

import { NEW_DATA_LOADED, DRAWER_TOGGLED } from '../actions/types';
import { initialState } from '../store';

export default function rootReducer(state = initialState, action) {
    console.log(state);
    console.log(action);
    switch (action.type) {
        case DRAWER_TOGGLED: {
            return { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: action.value };
        }
        case NEW_DATA_LOADED: {
            const keyValue = action.keyValue;
            const content = action.content;
            console.log(action);
            let newState = { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: state.drawerToggled };;
            newState[keyValue] = content;
            return newState;
        }
        default:
            return state;
    }
}
```

<p><br/>creators.js:<br/></p>

<pre class="lang-js prettyprint-override"><code>import { NEW_DATA_LOADED, DRAWER_TOGGLED } from "./types";

const newDataLoaded = (key, content) => ({ type: NEW_DATA_LOADED, content: content, keyValue: key });
const drawerToggled = (open) => ({ type: DRAWER_TOGGLED, value:open });

export { newDataLoaded , drawerToggled };
</code>```

store.js:

import { createStore, compose, applyMiddleware } from "redux";
import rootReducer from './reducers/root';
import ReduxThunk from 'redux-thunk';

const initialState = { articles:[], authors:[],categories:[],  drawerToggled: false };

export default function configStore() {
  return createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(ReduxThunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    )
  );
}
export { initialState };
```

<p><br/>
And NavBar.js:<br/></p>

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import { AppBar, Toolbar } from '@material-ui/core';
import FaceIcon from '@material-ui/icons/Face';
import MenuIcon from '@material-ui/icons/Menu';
import IconButton from 'material-ui/IconButton';
import Drawer from "@material-ui/core/Drawer";
import ListItem from "@material-ui/core/ListItem";
import List from "@material-ui/core/List";
import makeStyles from "@material-ui/styles/makeStyles";
import { BrowserRouter as Router } from "react-router-dom";
import ListItemText from "@material-ui/core/ListItemText";
import BackToTopButton from "../BackToTopButton/BackToTopButton";
import { connect } from 'react-redux';
import { toggleDrawer } from '../../actions';
import './NavBar.css';

const useStyles = makeStyles(theme => ({
    list: {
        width: 250
    },
    fullList: {
        width: "auto"
    },
    paper: {
        background: "#485461"
    }
}));
function NavBar(props){
        const toolbar = React.createRef();
        let toolbarElement = props.article === true ? <Toolbar id="back-to-top-anchor" ref={toolbar} /> : <Toolbar />;
        let button = null;
        if (props.article === true) {
            button = <BackToTopButton anchor={toolbar} />;
        }
        const classes  = useStyles;
        const navbar_links = [["Home", "/"], ["Categories", "/categories"], ["Interesting Posts For You", "/interesting"], ["Your Inbox", "/inbox"], ["Register account","/registration"]];
        const sideList = (
            <div className={classes.list} role="presentation" onClick={props.toggleDrawer(false)}
                onKeyDown={props.toggleDrawer(false)}>
                <List>
                    {navbar_links.map((text) => (
                        <ListItem component="a" button key={text[0]} href={text[1]}>
                            <ListItemText>{text[0]}</ListItemText>
                        </ListItem>
                    ))}
                </List>
            </div>
        );
    const toggleDrawer = (open) => { props.toggleDrawer(open) };
    const drawerToggled = props.drawerToggled;
        return (
            <React.Fragment>
                <Router>
                    <AppBar position="sticky">
                        <Toolbar>
                            <IconButton className={"menu"} aria-label="Menu" color="white"
                                onClick={toggleDrawer(true)}>
                                <MenuIcon />
                            </IconButton>
                            <Drawer
                                classes={{ paper: classes.paper }}
                                open={drawerToggled}
                                onClose={toggleDrawer(false)}
                            >
                                <div
                                    tabIndex={0}
                                    role="button"
                                    onClick={toggleDrawer(false)}
                                    onKeyDown={toggleDrawer(false)}
                                    className={{ root: classes.root }}
                                >
                                    {sideList}
                                </div>
                            </Drawer>

                            <section className={"rightToolBar"}>
                                <IconButton className={"profile"} aria-label="My profile" color={"black"} href="/profile">
                                    <FaceIcon />
                                </IconButton>
                            </section>
                        </Toolbar>
                    </AppBar>
                    {toolbarElement}
                </Router>
                {button}
            </React.Fragment>
        );
    }

const mapStateToProps = (state) => ({
    drawerToggled:state.drawerToggled
});
const mapDispatchToProps = (dispatch) => ({
    toggleDrawer: (open) => dispatch(toggleDrawer(open)),
});

export default connect(mapStateToProps, mapDispatchToProps)(NavBar);
</code>```

P.S. Version of this navbar, implemented with react state worked good, so the problem is somewhere in redux usage.

Can anyone help me to make it work?
CodeSandbox:

https://codesandbox.io/s/github/LilJohny/BlogUI/tree/develop_4

答: onClick={()=>toggleDrawer(true)}</p>

Body:
I am trying to implement Drawer, which will appear on the left with a saving state of the Drawer using Redux. But unfortunately, I did something wrong and my onClick events just don`t respond. Code:

Reducer:

import { NEW_DATA_LOADED, DRAWER_TOGGLED } from '../actions/types';
import { initialState } from '../store';

export default function rootReducer(state = initialState, action) {
    console.log(state);
    console.log(action);
    switch (action.type) {
        case DRAWER_TOGGLED: {
            return { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: action.value };
        }
        case NEW_DATA_LOADED: {
            const keyValue = action.keyValue;
            const content = action.content;
            console.log(action);
            let newState = { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: state.drawerToggled };;
            newState[keyValue] = content;
            return newState;
        }
        default:
            return state;
    }
}

creators.js:

import { NEW_DATA_LOADED, DRAWER_TOGGLED } from "./types";

const newDataLoaded = (key, content) => ({ type: NEW_DATA_LOADED, content: content, keyValue: key });
const drawerToggled = (open) => ({ type: DRAWER_TOGGLED, value:open });

export { newDataLoaded , drawerToggled };

store.js:

import { createStore, compose, applyMiddleware } from "redux";
import rootReducer from './reducers/root';
import ReduxThunk from 'redux-thunk';

const initialState = { articles:[], authors:[],categories:[],  drawerToggled: false };

export default function configStore() {
  return createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(ReduxThunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    )
  );
}
export { initialState };

And NavBar.js:

import React from 'react';
import { AppBar, Toolbar } from '@material-ui/core';
import FaceIcon from '@material-ui/icons/Face';
import MenuIcon from '@material-ui/icons/Menu';
import IconButton from 'material-ui/IconButton';
import Drawer from "@material-ui/core/Drawer";
import ListItem from "@material-ui/core/ListItem";
import List from "@material-ui/core/List";
import makeStyles from "@material-ui/styles/makeStyles";
import { BrowserRouter as Router } from "react-router-dom";
import ListItemText from "@material-ui/core/ListItemText";
import BackToTopButton from "../BackToTopButton/BackToTopButton";
import { connect } from 'react-redux';
import { toggleDrawer } from '../../actions';
import './NavBar.css';

const useStyles = makeStyles(theme => ({
    list: {
        width: 250
    },
    fullList: {
        width: "auto"
    },
    paper: {
        background: "#485461"
    }
}));
function NavBar(props){
        const toolbar = React.createRef();
        let toolbarElement = props.article === true ? <Toolbar id="back-to-top-anchor" ref={toolbar} /> : <Toolbar />;
        let button = null;
        if (props.article === true) {
            button = <BackToTopButton anchor={toolbar} />;
        }
        const classes  = useStyles;
        const navbar_links = [["Home", "/"], ["Categories", "/categories"], ["Interesting Posts For You", "/interesting"], ["Your Inbox", "/inbox"], ["Register account","/registration"]];
        const sideList = (

                <List>
                    {navbar_links.map((text) => (
                        <ListItem component="a" button key={text[0]} href={text[1]}>
                            <ListItemText>{text[0]}</ListItemText>
                        </ListItem>
                    ))}
                </List>

        );
    const toggleDrawer = (open) => { props.toggleDrawer(open) };
    const drawerToggled = props.drawerToggled;
        return (
            <React.Fragment>
                <Router>
                    <AppBar position="sticky">
                        <Toolbar>
                            <IconButton className={"menu"} aria-label="Menu" color="white"
                                onClick={toggleDrawer(true)}>
                                <MenuIcon />
                            </IconButton>
                            <Drawer
                                classes={{ paper: classes.paper }}
                                open={drawerToggled}
                                onClose={toggleDrawer(false)}
                            >

                                    {sideList}

                            </Drawer>

                                <IconButton className={"profile"} aria-label="My profile" color={"black"} href="/profile">
                                    <FaceIcon />
                                </IconButton>

                        </Toolbar>
                    </AppBar>
                    {toolbarElement}
                </Router>
                {button}
            </React.Fragment>
        );
    }

const mapStateToProps = (state) => ({
    drawerToggled:state.drawerToggled
});
const mapDispatchToProps = (dispatch) => ({
    toggleDrawer: (open) => dispatch(toggleDrawer(open)),
});

export default connect(mapStateToProps, mapDispatchToProps)(NavBar);

P.S. Version of this navbar, implemented with react state worked good, so the problem is somewhere in redux usage.

Can anyone help me to make it work?
CodeSandbox:

https://codesandbox.io/s/github/LilJohny/BlogUI/tree/develop_4

Body: onClick={()=>toggleDrawer(true)}


问:
Does using a prototype + definition instead of just a definition speed up the program?
Im very new to C programing, but have limited experience with Python, Java, and Perl. I was just wondering what the advantage is of having the prototype of a function above main() and the definition of that function below main() rather than just having the definition of said function above main(). From what I have read, the definition can act as a prototype as well.

Thanks in advance,

答:
The use of a prototype above main() (within a single module) is mostly a matter of personal preference. Some people like to see main() at the bottom of the file; other people like to see it at the top. I had a professor in university who complained that I wrote my programs "upside-down" because I put main() at the bottom (and avoided having to write and maintain prototypes for everything).

There is one situation where a prototype may be required:

```<code>void b(); // prototype required here

void a()
{
    b();
}

void b()
{
    a();
}
</code>```

In this mutually recursive situation, you need at least one of the prototypes to appear prior to the definition of the other function.

Body:
The use of a prototype above main() (within a single module) is mostly a matter of personal preference. Some people like to see main() at the bottom of the file; other people like to see it at the top. I had a professor in university who complained that I wrote my programs "upside-down" because I put main() at the bottom (and avoided having to write and maintain prototypes for everything).

There is one situation where a prototype may be required:

void b(); // prototype required here

void a()
{
    b();
}

void b()
{
    a();
}

In this mutually recursive situation, you need at least one of the prototypes to appear prior to the definition of the other function.