问:
Query run as stored procedure (sp_sqlexec) delivers no results (T-SQL, SQL Server)
I want to run a query that shows me all columns from all tables in a database with the datatype varchar and a maximum length of 8000 characters.

This is my code so far.

```<code>DECLARE @tabs VARCHAR(MAX);

SET @tabs =
(
  SELECT STUFF(( SELECT DISTINCT ',' + [TABLE_NAME]
                 FROM [DB-Test].INFORMATION_SCHEMA.COLUMNS
                 WHERE DATA_TYPE = 'VARCHAR' AND
                       CHARACTER_MAXIMUM_LENGTH = 8000
                 FOR XML PATH('')), 1, 1, '')
);

DECLARE @cols VARCHAR(MAX)
SET @cols =
(
  SELECT STUFF(( SELECT DISTINCT ',' + [TABLE_NAME] + '.' + [COLUMN_NAME]
                 FROM [DB-Test].INFORMATION_SCHEMA.COLUMNS
                 WHERE DATA_TYPE = 'VARCHAR' AND
                       CHARACTER_MAXIMUM_LENGTH = 8000
                 FOR XML PATH('')), 1, 1, '')
);

DECLARE @query VARCHAR(MAX) = 'SELECT ' + @cols + ' FROM ' + @tabs

EXEC sp_sqlexec @query
</code>```

When I run the query I get all the column names, but not the values in the columns. It's empty. No 'NULL'-values. As if @cols is interpreted as simple string maybe.
Why?

(When I read out @cols and @tabs they are correct.)

答:
I guess there is one table available in your database which have column with VARCHAR datatype and 8000 length but that table don't have any records. Try by including only those column and table which have at least one record available.

You can try below. Check it and let me know if it works.

```<code>DECLARE @tabs VARCHAR(MAX) = ''

; WITH CTE AS
(
 SELECT DISTINCT TA.NAME TABLENAME
      , SUM(PA.ROWS) OVER (PARTITION BY TA.NAME ) NOOFROW
 FROM SYS.TABLES TA
 INNER JOIN SYS.PARTITIONS PA ON PA.OBJECT_ID = TA.OBJECT_ID
 INNER JOIN SYS.SCHEMAS SC ON TA.SCHEMA_ID = SC.SCHEMA_ID
 WHERE TA.IS_MS_SHIPPED = 0 AND PA.INDEX_ID IN (1,0)
), TABLENAME AS
(
    SELECT ITBL.[TABLE_NAME]
    FROM INFORMATION_SCHEMA.COLUMNS ITBL
    WHERE ITBL.DATA_TYPE = 'VARCHAR' AND
          ITBL.CHARACTER_MAXIMUM_LENGTH = 8000
          AND EXISTS(SELECT 1 FROM CTE WHERE CTE.TABLENAME = ITBL.TABLE_NAME AND CTE.NOOFROW > 0) -- To check no of record available in table
)
SELECT @tabs = @tabs+ISNULL(','+TABLE_NAME, '')
FROM TABLENAME

DECLARE @cols VARCHAR(MAX) = '';

; WITH CTE AS
(
 SELECT DISTINCT TA.NAME TABLENAME
      , SUM(PA.ROWS) OVER (PARTITION BY TA.NAME ) NOOFROW
 FROM SYS.TABLES TA
 INNER JOIN SYS.PARTITIONS PA ON PA.OBJECT_ID = TA.OBJECT_ID
 INNER JOIN SYS.SCHEMAS SC ON TA.SCHEMA_ID = SC.SCHEMA_ID
 WHERE TA.IS_MS_SHIPPED = 0 AND PA.INDEX_ID IN (1,0)
), TABLENAME AS
(
    SELECT ITBL.[TABLE_NAME], ITBL.[COLUMN_NAME]
    FROM INFORMATION_SCHEMA.COLUMNS ITBL
    WHERE ITBL.DATA_TYPE = 'VARCHAR' AND
          ITBL.CHARACTER_MAXIMUM_LENGTH = 8000
          AND EXISTS(SELECT 1 FROM CTE WHERE CTE.TABLENAME = ITBL.TABLE_NAME AND CTE.NOOFROW > 0) -- To check no of record available in table
)
SELECT @cols = @cols+ISNULL(','+[TABLE_NAME]+'.'+[COLUMN_NAME], '')
FROM TABLENAME

IF LEN(@cols) > 0 AND LEN(@tabs) > 0
BEGIN
    DECLARE @query VARCHAR(MAX) = 'SELECT ' + STUFF(@cols,1,1,'') + ' FROM ' + STUFF(@tabs,1,1, '')

    EXEC sp_sqlexec @query
END
ELSE
BEGIN
    PRINT 'No Column available with data where it''s datatype is VARCHAR and length is 8000'
END
</code>```

Body:
I want to run a query that shows me all columns from all tables in a database with the datatype varchar and a maximum length of 8000 characters.

This is my code so far.

DECLARE @tabs VARCHAR(MAX);

SET @tabs =
(
  SELECT STUFF(( SELECT DISTINCT ',' + [TABLE_NAME]
                 FROM [DB-Test].INFORMATION_SCHEMA.COLUMNS
                 WHERE DATA_TYPE = 'VARCHAR' AND
                       CHARACTER_MAXIMUM_LENGTH = 8000
                 FOR XML PATH('')), 1, 1, '')
);

DECLARE @cols VARCHAR(MAX)
SET @cols =
(
  SELECT STUFF(( SELECT DISTINCT ',' + [TABLE_NAME] + '.' + [COLUMN_NAME]
                 FROM [DB-Test].INFORMATION_SCHEMA.COLUMNS
                 WHERE DATA_TYPE = 'VARCHAR' AND
                       CHARACTER_MAXIMUM_LENGTH = 8000
                 FOR XML PATH('')), 1, 1, '')
);

DECLARE @query VARCHAR(MAX) = 'SELECT ' + @cols + ' FROM ' + @tabs

EXEC sp_sqlexec @query

When I run the query I get all the column names, but not the values in the columns. It's empty. No 'NULL'-values. As if @cols is interpreted as simple string maybe.
Why?

(When I read out @cols and @tabs they are correct.)

Body:
I guess there is one table available in your database which have column with VARCHAR datatype and 8000 length but that table don't have any records. Try by including only those column and table which have at least one record available.

You can try below. Check it and let me know if it works.

DECLARE @tabs VARCHAR(MAX) = ''

; WITH CTE AS
(
 SELECT DISTINCT TA.NAME TABLENAME
      , SUM(PA.ROWS) OVER (PARTITION BY TA.NAME ) NOOFROW
 FROM SYS.TABLES TA
 INNER JOIN SYS.PARTITIONS PA ON PA.OBJECT_ID = TA.OBJECT_ID
 INNER JOIN SYS.SCHEMAS SC ON TA.SCHEMA_ID = SC.SCHEMA_ID
 WHERE TA.IS_MS_SHIPPED = 0 AND PA.INDEX_ID IN (1,0)
), TABLENAME AS
(
    SELECT ITBL.[TABLE_NAME]
    FROM INFORMATION_SCHEMA.COLUMNS ITBL
    WHERE ITBL.DATA_TYPE = 'VARCHAR' AND
          ITBL.CHARACTER_MAXIMUM_LENGTH = 8000
          AND EXISTS(SELECT 1 FROM CTE WHERE CTE.TABLENAME = ITBL.TABLE_NAME AND CTE.NOOFROW > 0) -- To check no of record available in table
)
SELECT @tabs = @tabs+ISNULL(','+TABLE_NAME, '')
FROM TABLENAME

DECLARE @cols VARCHAR(MAX) = '';

; WITH CTE AS
(
 SELECT DISTINCT TA.NAME TABLENAME
      , SUM(PA.ROWS) OVER (PARTITION BY TA.NAME ) NOOFROW
 FROM SYS.TABLES TA
 INNER JOIN SYS.PARTITIONS PA ON PA.OBJECT_ID = TA.OBJECT_ID
 INNER JOIN SYS.SCHEMAS SC ON TA.SCHEMA_ID = SC.SCHEMA_ID
 WHERE TA.IS_MS_SHIPPED = 0 AND PA.INDEX_ID IN (1,0)
), TABLENAME AS
(
    SELECT ITBL.[TABLE_NAME], ITBL.[COLUMN_NAME]
    FROM INFORMATION_SCHEMA.COLUMNS ITBL
    WHERE ITBL.DATA_TYPE = 'VARCHAR' AND
          ITBL.CHARACTER_MAXIMUM_LENGTH = 8000
          AND EXISTS(SELECT 1 FROM CTE WHERE CTE.TABLENAME = ITBL.TABLE_NAME AND CTE.NOOFROW > 0) -- To check no of record available in table
)
SELECT @cols = @cols+ISNULL(','+[TABLE_NAME]+'.'+[COLUMN_NAME], '')
FROM TABLENAME

IF LEN(@cols) > 0 AND LEN(@tabs) > 0
BEGIN
    DECLARE @query VARCHAR(MAX) = 'SELECT ' + STUFF(@cols,1,1,'') + ' FROM ' + STUFF(@tabs,1,1, '')

    EXEC sp_sqlexec @query
END
ELSE
BEGIN
    PRINT 'No Column available with data where it''s datatype is VARCHAR and length is 8000'
END


来源: stackexchange

问:
Can I use MVVM without data binding?
I am trying to use MVVM. Upon reading some blogs on MVVM, I found them using data binding techniques like Rx, KVO, Boxing etc. Following are my classes for validating user using MVVM. I have not put any code for data binding. What I do is simply pass the username and password from viewcontroller to my view model class upon the submit button click. The view model consists all the logic for validation. And at the end, it returns the status to the viewcontroller, depending on which the view controller shows some message. I am wandering is this the way to go or should some data binding be used?

SignUpViewController.swift

```<code>import UIKit

class SignUpViewController: UIViewController {

    let signupviewmodel = SignUpViewModel()

    @IBOutlet weak var textFieldUsername: UITextField!
    @IBOutlet weak var textFieldPassword: UITextField!
    @IBOutlet weak var textFieldPasswordConfirm: UITextField!

    @IBAction func initialSignUp(_ sender: Any) {
        signupviewmodel.updateUsername(username: textFieldUsername.text!)
        signupviewmodel.updatePassword(password: textFieldPassword.text!)
        signupviewmodel.updateConfirmPassword(confirmpassword: textFieldPasswordConfirm.text!)

        switch signupviewmodel.validateUser() {
            case .Valid:
                showAlert(title: "Valid", message: "success")
            case .InValid(let error):
                showAlert(title: "Error Validation", message: error)
        }
    }

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

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

    func showAlert(title: String, message: String) -> Void {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}
</code>```

SignUpViewModel.swift

```<code>import Foundation

enum UserValidationState {
    case Valid
    case InValid(String)
}

class SignUpViewModel {
    private let minPasswordLength: Int = 6
    private var user = User()

    var username: String {
        return user.username!
    }

    var password: String {
        return user.password!
    }

    var confirmpassword: String {
        return user.confirmpassword!
    }
}

extension SignUpViewModel {

    func updateUsername(username: String) {
        user.username = username
    }

    func updatePassword(password: String) {
        user.password = password
    }

    func updateConfirmPassword(confirmpassword: String) {
        user.confirmpassword = confirmpassword
    }

    func validateUser() -> UserValidationState {
        if (username.isBlank || password.isBlank || confirmpassword.isBlank) {
            return .InValid("Please fill all the fields")
        } else {
            if isNumber(username: username) {
                if isValidPhone(phone: username) {
                    if isValidPasswordLength(password: password) {
                        if passwordsMatch(password: password, confirmpassword: confirmpassword) {
                            return .Valid
                        }
                        return .InValid("Passwords do not match")
                    }
                    return .InValid("Password length doesn't meet criteria")
                }
                return .InValid("InValid Phone")
            } else {
                if isValidEmail(email: username) {
                    if isValidPasswordLength(password: password) {
                        if passwordsMatch(password: password, confirmpassword: confirmpassword) {
                            return .Valid
                        }
                        return .InValid("Passwords do not match")
                    }
                    return .InValid("Password length doesn't meet criteria")
                }
                return .InValid("InValid Email")
           }
        }
    }

    func isValidEmail(email:String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
        return NSPredicate(format:"SELF MATCHES %@", emailRegEx).evaluate(with: email)
    }

    func isValidPhone(phone: String) -> Bool {
        return true
    }

    func isBlank(text: String) -> Bool {
        return text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }

    func isValidPasswordLength(password: String) -> Bool {
        guard password.count < minPasswordLength else {
            return true
        }
        return false
    }

    func passwordsMatch(password: String, confirmpassword: String) -> Bool {
        guard password == confirmpassword else {
            return false
        }
        return true
    }

    func isNumber(username: String) -> Bool {
        guard let _ = Int(username) else {
            return false
        }
        return true
    }
}
</code>```

User.swift

```<code>import Foundation

struct User {
    var username: String?
    var password: String?
    var confirmpassword: String?
}
</code>```

答:
Data binding is the foundation of MVVM. So data binding helps you to keep all the business logic out of Views and work asynchronously with sending and receiving data. It would seem ok that you're passing values to viewModel, but there are cases when you will need to pass values from ViewModels to ViewControllers. For example, you have asynchronous API request which responds some data. In MVVM you would store that data in your ViewModel, but your ViewController needs to be notified that some data was received. Data binding helps to solve those cases with less amount of code. Yes, you can work without data binding just by using callbacks, but that would mean that you have to write a lot of boilerplate code.

I understand that KVO, Rx and Reactive seem to be difficult. So, you can start with simple libraries which offer only binding functionality, without getting deep into complex stuff. Check out these libraries:

https://github.com/ReactiveKit/Bond

https://github.com/blendle/Hanson

And just for note, the way you coded is more like MVP(Model View Presenter). You can check that design architecture if you don't like reactive programming.

ContentLicense: CC BY-SA 3.0

Title: Can I use MVVM without data binding?

Body:
I am trying to use MVVM. Upon reading some blogs on MVVM, I found them using data binding techniques like Rx, KVO, Boxing etc. Following are my classes for validating user using MVVM. I have not put any code for data binding. What I do is simply pass the username and password from viewcontroller to my view model class upon the submit button click. The view model consists all the logic for validation. And at the end, it returns the status to the viewcontroller, depending on which the view controller shows some message. I am wandering is this the way to go or should some data binding be used?

SignUpViewController.swift

import UIKit

class SignUpViewController: UIViewController {

    let signupviewmodel = SignUpViewModel()

    @IBOutlet weak var textFieldUsername: UITextField!
    @IBOutlet weak var textFieldPassword: UITextField!
    @IBOutlet weak var textFieldPasswordConfirm: UITextField!

    @IBAction func initialSignUp(_ sender: Any) {
        signupviewmodel.updateUsername(username: textFieldUsername.text!)
        signupviewmodel.updatePassword(password: textFieldPassword.text!)
        signupviewmodel.updateConfirmPassword(confirmpassword: textFieldPasswordConfirm.text!)

        switch signupviewmodel.validateUser() {
            case .Valid:
                showAlert(title: "Valid", message: "success")
            case .InValid(let error):
                showAlert(title: "Error Validation", message: error)
        }
    }

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

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

    func showAlert(title: String, message: String) -> Void {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

SignUpViewModel.swift

import Foundation

enum UserValidationState {
    case Valid
    case InValid(String)
}

class SignUpViewModel {
    private let minPasswordLength: Int = 6
    private var user = User()

    var username: String {
        return user.username!
    }

    var password: String {
        return user.password!
    }

    var confirmpassword: String {
        return user.confirmpassword!
    }
}

extension SignUpViewModel {

    func updateUsername(username: String) {
        user.username = username
    }

    func updatePassword(password: String) {
        user.password = password
    }

    func updateConfirmPassword(confirmpassword: String) {
        user.confirmpassword = confirmpassword
    }

    func validateUser() -> UserValidationState {
        if (username.isBlank || password.isBlank || confirmpassword.isBlank) {
            return .InValid("Please fill all the fields")
        } else {
            if isNumber(username: username) {
                if isValidPhone(phone: username) {
                    if isValidPasswordLength(password: password) {
                        if passwordsMatch(password: password, confirmpassword: confirmpassword) {
                            return .Valid
                        }
                        return .InValid("Passwords do not match")
                    }
                    return .InValid("Password length doesn't meet criteria")
                }
                return .InValid("InValid Phone")
            } else {
                if isValidEmail(email: username) {
                    if isValidPasswordLength(password: password) {
                        if passwordsMatch(password: password, confirmpassword: confirmpassword) {
                            return .Valid
                        }
                        return .InValid("Passwords do not match")
                    }
                    return .InValid("Password length doesn't meet criteria")
                }
                return .InValid("InValid Email")
           }
        }
    }

    func isValidEmail(email:String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
        return NSPredicate(format:"SELF MATCHES %@", emailRegEx).evaluate(with: email)
    }

    func isValidPhone(phone: String) -> Bool {
        return true
    }

    func isBlank(text: String) -> Bool {
        return text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }

    func isValidPasswordLength(password: String) -> Bool {
        guard password.count < minPasswordLength else {
            return true
        }
        return false
    }

    func passwordsMatch(password: String, confirmpassword: String) -> Bool {
        guard password == confirmpassword else {
            return false
        }
        return true
    }

    func isNumber(username: String) -> Bool {
        guard let _ = Int(username) else {
            return false
        }
        return true
    }
}

User.swift

import Foundation

struct User {
    var username: String?
    var password: String?
    var confirmpassword: String?
}


问:
Get root object using JSONPath query
Is there any syntax for a json path query to return the root object?

To quote Goessner on the subject:

Since a JSON structure is usually anonymous and doesn't necessarily have a "root member object" JSONPath assumes the abstract name $ assigned to the outer level object.

So I'd really expect just "$" to return the root object... But it doesn't.  It returns false.

I need a way to get the root object in a query (seems silly I know but the application I am using only allows me to specify a jsonpath query to access items in JSON).

答:
$ does return the root object for Jayway, Gatling and Nebhale.

Looks like the equivalent in Goessner is $..

Title: Get root object using JSONPath query

ContentLicense: CC BY-SA 4.0


问:
Custom 404 Page with <httpErrors> element does not seem to function in IIS 7
I'm testing an IIS 7.5 site with Managed Pipeline Mode = 'Integrated'

My site targets mobile devices and leverages well formed URLs to pass parameters with a minimum of typing. For example 'mysite.com/bob1234' in this case 'bob1234' is actually parameter.

In the Application.BeginRequest, I process the Request.Url.AbsolutePath using a regular expression to determine if the URL is well formed.

I wanted to add a Custom 404 page, if a user mistypes the URL i.e. mysite.com/boob1234.

```<code><system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="~/MobileError.aspx">
      <error statusCode="404" redirect="404.htm"/>
    </customErrors>
</system.web>
</code>```

And while this catches errors when the extension is '.aspx', it does not catch 404(s) when no handler is mapped, for example '/mysite.com/boob1234'.

I followed the instructions and also added a  element to my system.webserver

```<code><system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <httpErrors defaultResponseMode="Redirect" errorMode="DetailedLocalOnly">
      <remove statusCode="404" subStatusCode="-1"/>
      <error statusCode="404" prefixLanguageFilePath=""
              path="/mobile/MobileError.aspx" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>
</code>```

But no iteration of this seems to work.  When I uncomment the block, I get a 500 error.  And no, there doesn't seem to be any problem with my code.  I get a 500 error, even when I just forward to an plain HTML Page.

I did implement failed request tracing to see what I could see.

I get the expected:  404 thrown by IIS Web Core.

Then a few steps later the CustomerErrorModule starts, but it fails with a 500 error.  The detailed message is

ConfigExceptionInfo:
  \?\C:.....\MyApp\web.config ( 89)
  :This configuration section cannot be
  used at this path. This happens when
  the section is locked at a parent
  level. Locking is either by default
  (overrideModeDefault="Deny"), or set
  explicitly by a location tag with
  overrideMode="Deny" or the legacy
  allowOverride="false".

I've tried walking up the '.config' stack, and haven't found any references to overrideMode="Deny"

Any help would be awesome.  Totally stuck now.

Thanks:
Dylan

答:
Just a stab in the dark, try adding this attribute to the httpErrors element:

```<code>existingResponse="PassThrough"
</code>```

For example:

```<code><httpErrors existingResponse="PassThrough"
        defaultResponseMode="Redirect"
        errorMode="DetailedLocalOnly">
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm testing an IIS 7.5 site with Managed Pipeline Mode = 'Integrated'

My site targets mobile devices and leverages well formed URLs to pass parameters with a minimum of typing. For example 'mysite.com/bob1234' in this case 'bob1234' is actually parameter.

In the Application.BeginRequest, I process the Request.Url.AbsolutePath using a regular expression to determine if the URL is well formed.

I wanted to add a Custom 404 page, if a user mistypes the URL i.e. mysite.com/boob1234.

<system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="~/MobileError.aspx">
      <error statusCode="404" redirect="404.htm"/>
    </customErrors>
</system.web>

And while this catches errors when the extension is '.aspx', it does not catch 404(s) when no handler is mapped, for example '/mysite.com/boob1234'.

I followed the instructions and also added a  element to my system.webserver

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <httpErrors defaultResponseMode="Redirect" errorMode="DetailedLocalOnly">
      <remove statusCode="404" subStatusCode="-1"/>
      <error statusCode="404" prefixLanguageFilePath=""
              path="/mobile/MobileError.aspx" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>

But no iteration of this seems to work.  When I uncomment the block, I get a 500 error.  And no, there doesn't seem to be any problem with my code.  I get a 500 error, even when I just forward to an plain HTML Page.

I did implement failed request tracing to see what I could see.

I get the expected:  404 thrown by IIS Web Core.

Then a few steps later the CustomerErrorModule starts, but it fails with a 500 error.  The detailed message is

ConfigExceptionInfo:
  \?\C:.....\MyApp\web.config ( 89)
  :This configuration section cannot be
  used at this path. This happens when
  the section is locked at a parent
  level. Locking is either by default
  (overrideModeDefault="Deny"), or set
  explicitly by a location tag with
  overrideMode="Deny" or the legacy
  allowOverride="false".

I've tried walking up the '.config' stack, and haven't found any references to overrideMode="Deny"

Any help would be awesome.  Totally stuck now.

Thanks:
Dylan

Body:
Just a stab in the dark, try adding this attribute to the httpErrors element:

existingResponse="PassThrough"

For example:

<httpErrors existingResponse="PassThrough"
        defaultResponseMode="Redirect"
        errorMode="DetailedLocalOnly">


问:
django template white page
Help me
after add my {% extends "menu.html" %>

the rest of my page is white I can not see my content anymore
resultat

答:
Please change

```<code>{% extends "menu.html" %
</code>```

TO

```<code>{% extends "menu.html" %}
</code>```

Title: django template white page

Body:
Please change

{% extends "menu.html" %

TO

{% extends "menu.html" %}


问:
Node.JS Request Module Callback Not Firing
I'm running this code using the request module for node.js

```<code>var hsKey    = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
var hsForm   = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
var hsHost   = "https://docs.google.com/"
var url = hsHost + "forms/d/" + hsForm + "/formResponse"

var form = {
    "entry.129401737": pointsAvg,
    "entry.2000749128": hiddenNeurons,
    "submit": "Submit",
    "formkey": hsKey
};

request.post({
    url: url,
    form: form
}, function (err, res, body) {
    console.log("Sent data");
});
</code>```

I have tried running the above code just using standard Node.JS libraries, to no avail. The callback function is never fired and the request doesn't go through. I don't know why.

答:
I ran into this as well. I ended up creating a separate js file containing only the request, without the describe and it methods, and running it with 'mocha mynewbarebonesreq.js'. suddenly I could see that there was an exception being thrown and swallowed by mocha (with the standard reporter, spec).

I finally installed and enabled mocha_reporter which shows the exceptions

now it looks like this:

```<code>describe('CMSLogin', function () {
    it('should log in as user ' + JSON.stringify(USER_PASS), function (done) {
        request({
            url: "http://cms.lund.multiq.com:3000/api/CMSUsers/login",
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            json: false,
            body: JSON.stringify(USER_PASS)
        }, (err, res, body) => {
            var parsedBody = JSON.parse(body);
            this.token = parsedBody.id;
            console.log(this.token)
            assert.equal(USER_PASS.userId, parsedBody.userId);
            assert.doesNotThrow(() => Date.parse(parsedBody.created));
            if (err) { done.fail(err); }

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

Body:
I'm running this code using the request module for node.js

var hsKey    = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
var hsForm   = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
var hsHost   = "https://docs.google.com/"
var url = hsHost + "forms/d/" + hsForm + "/formResponse"

var form = {
    "entry.129401737": pointsAvg,
    "entry.2000749128": hiddenNeurons,
    "submit": "Submit",
    "formkey": hsKey
};

request.post({
    url: url,
    form: form
}, function (err, res, body) {
    console.log("Sent data");
});

I have tried running the above code just using standard Node.JS libraries, to no avail. The callback function is never fired and the request doesn't go through. I don't know why.

Body:
I ran into this as well. I ended up creating a separate js file containing only the request, without the describe and it methods, and running it with 'mocha mynewbarebonesreq.js'. suddenly I could see that there was an exception being thrown and swallowed by mocha (with the standard reporter, spec).

I finally installed and enabled mocha_reporter which shows the exceptions

now it looks like this:

describe('CMSLogin', function () {
    it('should log in as user ' + JSON.stringify(USER_PASS), function (done) {
        request({
            url: "http://cms.lund.multiq.com:3000/api/CMSUsers/login",
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            json: false,
            body: JSON.stringify(USER_PASS)
        }, (err, res, body) => {
            var parsedBody = JSON.parse(body);
            this.token = parsedBody.id;
            console.log(this.token)
            assert.equal(USER_PASS.userId, parsedBody.userId);
            assert.doesNotThrow(() => Date.parse(parsedBody.created));
            if (err) { done.fail(err); }

            done();
        });
    });
}


问:
Html.Dropdownlist values when using repository classes
Until now I have used the Model class to embed list of related values to render as DropDownList in the view. For example, suppose I have a Contact model class that has a ContactType property in it

```<code>public class Contact {
    ...
    public int ContactTypeID { get; set; }
    ...
}
</code>```

ContactTypeID reference a row in a database table that contains all the contact types like Customer, Supplier, etc. I have used successfully until now a property of the Contact class called, for example, ContactTypeList as in the following sample

```<code>public IEnumerable<SelectListItem> ContactTypeList {
    get {
        return GetContactTypeList().Select(
            t => new SelectListItem { Text = t.Description,
                 Value = t.ContactTypeID.ToString() });
    }
}
</code>```

This way when using strong typed views I can do the following way

```<code><%: Html.DropDownListFor( model => model.ContactTypeID, Model.ContactTypeList, new {} )%>
</code>```

This method works wothout any problem but is not completely clean from the SoC point of view.

In a new project I am starting I am using the repository pattern and StructureMap as the DI/IoC tool and so the model class, does not have anymore a reference to the repository class that is getting the data from the underlying data store.

I know that I can always use the controller and the ViewData/ViewBag to get these lists to pass in the views but I was wondering if this is a good way to achieve the scope.

How are you doing in your projects? What is the best way to achieve the result and having the code remain clean?

Thanks for helping

答: In our project we also use ViewData to store the list and use them  in the view, there's nothing wrong in it.</p>

Body:
Until now I have used the Model class to embed list of related values to render as DropDownList in the view. For example, suppose I have a Contact model class that has a ContactType property in it

public class Contact {
    ...
    public int ContactTypeID { get; set; }
    ...
}

ContactTypeID reference a row in a database table that contains all the contact types like Customer, Supplier, etc. I have used successfully until now a property of the Contact class called, for example, ContactTypeList as in the following sample

public IEnumerable<SelectListItem> ContactTypeList {
    get {
        return GetContactTypeList().Select(
            t => new SelectListItem { Text = t.Description,
                 Value = t.ContactTypeID.ToString() });
    }
}

This way when using strong typed views I can do the following way

<%: Html.DropDownListFor( model => model.ContactTypeID, Model.ContactTypeList, new {} )%>

This method works wothout any problem but is not completely clean from the SoC point of view.

In a new project I am starting I am using the repository pattern and StructureMap as the DI/IoC tool and so the model class, does not have anymore a reference to the repository class that is getting the data from the underlying data store.

I know that I can always use the controller and the ViewData/ViewBag to get these lists to pass in the views but I was wondering if this is a good way to achieve the scope.

How are you doing in your projects? What is the best way to achieve the result and having the code remain clean?

Thanks for helping


问:
Increasing image margin based on a label value html
I have an image that is at the bottom of the screen and I would like to increase its margins (move it towards the top) based on the value of a label.

```<code><img src="flag.png"
style=" margin-left:50%;
        position:absolute;
        margin-top:50%;
        bottom:0px;
        ">
<label id="countdown" > countdown: </label>
</code>```

Label id="countdown" is updated frequently.

Essentially, is it possible to move the image up (increase the value of "bottom:0;") based on the value of the id="countdown"?

答:
Since you indicated that you MUST get the value from the label, here's a way to do it:

$(function(){
  $('label').bind('DOMSubtreeModified', function() {
   var labelText = $('label').html();
    // use regex to get the number from the label string
    var matches = labelText.match(/\d+$/);
    // event fires with empty text and new contents
    // only update the flag when we have labelText and a valid number
    if(labelText && matches[0]){
       var countDownNumber = parseInt(matches[0]);
        // I use 100 - countdown here, but
        // you would propably have some calculation to determine the height of your flag here.
        $('.flag').css('bottom', 100-countDownNumber)
    }
  });

  // separate code to update the label
  var i = 100;
  setInterval(function(){
   $('label').html('countdown: '+i);
    i--;
    if(i === 0){
     i= 100;
    }
  }, 100);

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flag{
  width: 30px;
  margin-left:50%;
  position:absolute;
  margin-top:50%;
  bottom:0px;
}</code>```

 countdown: ```

Body:
I have an image that is at the bottom of the screen and I would like to increase its margins (move it towards the top) based on the value of a label.

 countdown:

Label id="countdown" is updated frequently.

Essentially, is it possible to move the image up (increase the value of "bottom:0;") based on the value of the id="countdown"?

Body:
Since you indicated that you MUST get the value from the label, here's a way to do it:

$(function(){
  $('label').bind('DOMSubtreeModified', function() {
   var labelText = $('label').html();
    // use regex to get the number from the label string
    var matches = labelText.match(/\d+$/);
    // event fires with empty text and new contents
    // only update the flag when we have labelText and a valid number
    if(labelText && matches[0]){
       var countDownNumber = parseInt(matches[0]);
        // I use 100 - countdown here, but
        // you would propably have some calculation to determine the height of your flag here.
        $('.flag').css('bottom', 100-countDownNumber)
    }
  });

  // separate code to update the label
  var i = 100;
  setInterval(function(){
   $('label').html('countdown: '+i);
    i--;
    if(i === 0){
     i= 100;
    }
  }, 100);

})

.flag{
  width: 30px;
  margin-left:50%;
  position:absolute;
  margin-top:50%;
  bottom:0px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img class="flag" src="http://www.thedayibecameapirate.com/wp-content/uploads/2012/05/Flag3.png">

<label id="countdown" > countdown: <span id="counter"></span></label>


问:
REF! error with copyTo
I need only part of the spreadsheet to be copied. If I use copying by values, hyperlinks don't work in other cells(and in this one too).</p>

答:
When copying a range from one sheet to another, the REF! commonly occurs because the copied range include formulas that use relative references and the resulting references on the destination range aren't valid.

Let say that o B2 you have =A1, which means get the value from the cell positioned one cell up, one cell left. If you copy B2 to C3, the resulting formula will be =B2 but if you copy B2 to A1 the result will be REF! because A1 there isn't on the referred position, one cell up, one cell left.

The fix will depend on what your formulas are intended to do. Some times making the references absolute ($A$1) will work.

Title: REF! error with copyTo


问:
angularjs how can pass multipul parameter to api
How can I pass mutipul parameters from angularjs -to WebAPi My Api as its Required two parameters

```<code>public IHttpActionResult GetData(int pagesize,int Totalpages){---}
</code>```

angularctrls.js

```<code>function GetData() {
        var PageDetails={
            'currentpage': $scope.currentPage,
            'pagesize':$scope.pagesize
        }
        HomeFactory.GetDat(PageDetails).then(function () {
        })
    }
</code>```

Factory.js

```<code> EmployeeServiceFactory.GetDat = function (PageDetails) {
        return $http({
            url:WebAPi+'Home/GetData/',
            method: 'GET',
            data: PageDetails,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
}
</code>```

Getting Error as

```<code>Failed to load http://localhost:3084/Home/GetData/%7B%22currentpage%22:1,%22pagesize%22:5%7D: No 'Access-Control-Allow-Origin' header is present on the requested resource
</code>```

答:
I think you can put data as an object. </p>

```<code>EmployeeServiceFactory.GetDat = function (PageDetails) {
  return $http({
    url:WebAPi+'Home/GetData/'+PageDetails,
    method: 'GET',
    data: {page_details:
      PageDetails, foo: 'bar'}, headers: { 'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}
</code>```

Body:
How can I pass mutipul parameters from angularjs -to WebAPi My Api as its Required two parameters

public IHttpActionResult GetData(int pagesize,int Totalpages){---}

angularctrls.js

function GetData() {
        var PageDetails={
            'currentpage': $scope.currentPage,
            'pagesize':$scope.pagesize
        }
        HomeFactory.GetDat(PageDetails).then(function () {
        })
    }

Factory.js

 EmployeeServiceFactory.GetDat = function (PageDetails) {
        return $http({
            url:WebAPi+'Home/GetData/',
            method: 'GET',
            data: PageDetails,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
}

Getting Error as

Failed to load http://localhost:3084/Home/GetData/%7B%22currentpage%22:1,%22pagesize%22:5%7D: No 'Access-Control-Allow-Origin' header is present on the requested resource

Body:
I think you can put data as an object.

EmployeeServiceFactory.GetDat = function (PageDetails) {
  return $http({
    url:WebAPi+'Home/GetData/'+PageDetails,
    method: 'GET',
    data: {page_details:
      PageDetails, foo: 'bar'}, headers: { 'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}


问:
Type parameter inference in pattern matching
I am trying to create some kind of heterogeneous map and came up with the following code

```<code>sealed trait Key[V]
case object LongKey extends Key[Long]

case class KeyValue[V](key: Key[V], value: V)

object KeyValue {
  def values(key: Key[Long], kvs: List[KeyValue[_]]): List[Long] =
    kvs.collect {
      case KeyValue(LongKey, v) ⇒ v: Long // this compiles
      case KeyValue(`key`, v)   ⇒ v: Long // this doesn't
    }
}
</code>```

As Key is sealed and invariant I would have expected the 2 lines to be interchangeable.
Why does the second case not compile?

```<code>...: type mismatch;
  found   : _$1 where type _$1
  required: Long
       case KeyValue(`key`, v) ⇒ v: Long
</code>```

答:
Well, this is the way type system guaranty that your function is correct.

When you make your function signature,

```<code>def values(key: Key[Long], kvs: List[KeyValue[_]]): List[Long]
</code>```

KeyValue[_] means KeyValue[Z] forSome { type Z }

When compiler does type inference, there is no way to make sure that the return would be List[Long], without constraining the case match to only KeyValue(LongKey, v).

If you need a generic function to collect the values, you could rewrite it as below.

```<code>def values[V](key: Key[V], kvs: List[KeyValue[V]]): List[V] =
  kvs.collect {
    case KeyValue(keyType, v) ⇒ v
  }
</code>```

On the other hand, if you want constrain them to only Long types, you need to change the function signature to,

```<code>def values(key: Key[Long], kvs: List[KeyValue[Long]]): List[Long]
</code>```

That would allow you to pattern match on case KeyValue(key, v). Because compiler could verify that only Long type is to be expected.

Body:
I am trying to create some kind of heterogeneous map and came up with the following code

sealed trait Key[V]
case object LongKey extends Key[Long]

case class KeyValue[V](key: Key[V], value: V)

object KeyValue {
  def values(key: Key[Long], kvs: List[KeyValue[_]]): List[Long] =
    kvs.collect {
      case KeyValue(LongKey, v) ⇒ v: Long // this compiles
      case KeyValue(`key`, v)   ⇒ v: Long // this doesn't
    }
}

As Key is sealed and invariant I would have expected the 2 lines to be interchangeable.
Why does the second case not compile?

...: type mismatch;
  found   : _$1 where type _$1
  required: Long
       case KeyValue(`key`, v) ⇒ v: Long

Body:
Well, this is the way type system guaranty that your function is correct.

When you make your function signature,

def values(key: Key[Long], kvs: List[KeyValue[_]]): List[Long]

KeyValue[_] means KeyValue[Z] forSome { type Z }

When compiler does type inference, there is no way to make sure that the return would be List[Long], without constraining the case match to only KeyValue(LongKey, v).

If you need a generic function to collect the values, you could rewrite it as below.

def values[V](key: Key[V], kvs: List[KeyValue[V]]): List[V] =
  kvs.collect {
    case KeyValue(keyType, v) ⇒ v
  }

On the other hand, if you want constrain them to only Long types, you need to change the function signature to,

def values(key: Key[Long], kvs: List[KeyValue[Long]]): List[Long]

That would allow you to pattern match on case KeyValue(key, v). Because compiler could verify that only Long type is to be expected.


问:
Exception Thread in java
I have an "Exception in thread" error.  I create a public class student and give it three classes: NAME of student, ID of student and GPA of student. When I run the code and enter information for student1 it's good. But when I enter student2, the code skips the name for student2, and gives me the student id and GPA. How can I remedy this?

Here is the code:

```<code>import java.util.Scanner;
class Student {

    public String name;
    public int id;
    public float gpa;
}
public class learning {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        Student s1 = new Student();
        System.out.print("Enter your name: ");
        s1.name = input.nextLine();
        System.out.print("Enter your id: ");
        s1.id = input.nextInt();
        System.out.print("Enter your gpa: ");
        s1.gpa = input.nextFloat();

        Student s2 = new Student();
        System.out.print("Enter your name: ");
        s2.name = input.nextLine();
        System.out.print("Enter your id: ");
        s2.id = input.nextInt();
        System.out.print("Enter your gpa: ");
        s2.gpa = input.nextFloat();

        Student s3 = new Student();
        System.out.print("Enter your name: ");
        s3.name = input.nextLine();
        System.out.print("Enter your id: ");
        s3.id = input.nextInt();
        System.out.print("Enter your gpa: ");
        s3.gpa = input.nextFloat();

        System.out.println("your name: " + s1.name + "\n"
                + "your id: " + s1.id + "\n"
                + "your GPA: " + s1.gpa);

    }

}
</code>```

答:
Your scanner is getting screwed up if you both use nextLine and next/nextInt/nextDouble refer to this for more Information.

I changed your main method accordingly, it now works like you wanted it to.

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

    Scanner input = new Scanner(System.in);

    Student s1 = new Student();
    System.out.print("Enter your name: ");
    s1.name = input.nextLine();
    System.out.print("Enter your id: ");
    s1.id = Integer.parseInt(input.nextLine());
    System.out.print("Enter your gpa: ");
    s1.gpa = Float.parseFloat(input.nextLine());

    Student s2 = new Student();
    System.out.print("Enter your name: ");
    s2.name = input.nextLine();
    System.out.print("Enter your id: ");
    s2.id = Integer.parseInt(input.nextLine());
    System.out.print("Enter your gpa: ");
    s2.gpa = Float.parseFloat(input.nextLine());

    Student s3 = new Student();
    System.out.print("Enter your name: ");
    s3.name = input.nextLine();
    System.out.print("Enter your id: ");
    s3.id = Integer.parseInt(input.nextLine());
    System.out.print("Enter your gpa: ");
    s3.gpa = Float.parseFloat(input.nextLine());

    System.out.println("your name: " + s1.name + "\n" + "your id: " + s1.id + "\n" + "your GPA: " + s1.gpa);

}
</code>```

Title: Exception Thread in java

Body:
I have an "Exception in thread" error.  I create a public class student and give it three classes: NAME of student, ID of student and GPA of student. When I run the code and enter information for student1 it's good. But when I enter student2, the code skips the name for student2, and gives me the student id and GPA. How can I remedy this?

Here is the code:

import java.util.Scanner;
class Student {

    public String name;
    public int id;
    public float gpa;
}
public class learning {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        Student s1 = new Student();
        System.out.print("Enter your name: ");
        s1.name = input.nextLine();
        System.out.print("Enter your id: ");
        s1.id = input.nextInt();
        System.out.print("Enter your gpa: ");
        s1.gpa = input.nextFloat();

        Student s2 = new Student();
        System.out.print("Enter your name: ");
        s2.name = input.nextLine();
        System.out.print("Enter your id: ");
        s2.id = input.nextInt();
        System.out.print("Enter your gpa: ");
        s2.gpa = input.nextFloat();

        Student s3 = new Student();
        System.out.print("Enter your name: ");
        s3.name = input.nextLine();
        System.out.print("Enter your id: ");
        s3.id = input.nextInt();
        System.out.print("Enter your gpa: ");
        s3.gpa = input.nextFloat();

        System.out.println("your name: " + s1.name + "\n"
                + "your id: " + s1.id + "\n"
                + "your GPA: " + s1.gpa);

    }

}

Body:
Your scanner is getting screwed up if you both use nextLine and next/nextInt/nextDouble refer to this for more Information.

I changed your main method accordingly, it now works like you wanted it to.

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    Student s1 = new Student();
    System.out.print("Enter your name: ");
    s1.name = input.nextLine();
    System.out.print("Enter your id: ");
    s1.id = Integer.parseInt(input.nextLine());
    System.out.print("Enter your gpa: ");
    s1.gpa = Float.parseFloat(input.nextLine());

    Student s2 = new Student();
    System.out.print("Enter your name: ");
    s2.name = input.nextLine();
    System.out.print("Enter your id: ");
    s2.id = Integer.parseInt(input.nextLine());
    System.out.print("Enter your gpa: ");
    s2.gpa = Float.parseFloat(input.nextLine());

    Student s3 = new Student();
    System.out.print("Enter your name: ");
    s3.name = input.nextLine();
    System.out.print("Enter your id: ");
    s3.id = Integer.parseInt(input.nextLine());
    System.out.print("Enter your gpa: ");
    s3.gpa = Float.parseFloat(input.nextLine());

    System.out.println("your name: " + s1.name + "\n" + "your id: " + s1.id + "\n" + "your GPA: " + s1.gpa);

}


问:
Android studio how to play background music automatically when activity started
Can anyone help me with my problem, i am trying to play a background music automatically without a button when activity started.

I dont have any idea how.

答:
Add music file in the raw folder then call R.raw.[musincname] then call function in your onCreate or onStart,....</p>

```<code>public static void PlayVoice(final Context context, int rawVoice) {
    voice = MediaPlayer.create(context, rawVoice);
    voice.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            if (voice != null) {
                voice.release();
            }
        }
    });
    voice.start();
}
</code>```

Body:
Add music file in the raw folder then call R.raw.[musincname] then call function in your onCreate or onStart,....

public static void PlayVoice(final Context context, int rawVoice) {
    voice = MediaPlayer.create(context, rawVoice);
    voice.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            if (voice != null) {
                voice.release();
            }
        }
    });
    voice.start();
}


问:
Trying to write to a mysql database but it keeps coming up empty set
For a school project I am trying to write to a table called enrolment where the student number and the course they have selected are added after they have been tested to make sure the student name and number exists in another database. No errors are coming up, however when I check my database afterward enrolment says its an empty set. Does anyone have suggestions?

```<code><?php

require 'connect.php';

//making a variable from the user data
$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];

//linking up the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());

// select all from table student which show student name and number
$squery = "SELECT * FROM student";
$sresult = mysqli_query($link, $squery);

$found = 0;

while ($srow = mysqli_fetch_array($sresult)) {

    // testing if the student name and number match the users data
    if ($name == $srow['family'] && $number == $srow['uid']) {

        $enrol = "INSERT INTO enrolment (uid course) VALUES('$number' '$course')";
        $found = 1;
        break;
    }
}
mysqli_close($link);

?>

<html>
    <body>
        <form action="index.php" method="post">
            <br>
            <input type = "submit" value="back" name="back">
        </form>
    </body>
</html>
</code>```

index.php (form)

```<code><!DOCTYPE html>
<html>
  <body>
    <h1>Course Selection</h1><br>

    <form action="next.php" method="post">

              Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">
              <br><br>

              Student Number: <input type="text" name= "snumber" required="required" maxlength="9">
              <br><br>

        <?php
        //form
      require 'connect.php';

       echo "Select a course: <select name = \"pcourse\">\n";

      $link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());

      $query = "SELECT * FROM course";
      $result = mysqli_query($link, $query);

      while ($row = mysqli_fetch_array($result)) {
        echo "<option> $row[code] $row[name] $row[maxenroll]</option><br>";
      }

      mysqli_free_result($results);

      mysqli_close ($link);

      echo " </select>\n";

      ?>

      <br><br>
      <input type = "submit" value="submit" name= "submit">

    </form>

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

答:
Your insert code just a string. You should send to mysql your insert code. Try this</p>

```<code>$enrol = "INSERT INTO enrolment (uid, course) VALUES($number, $course)";
$link->query($enrol);
</code>```

Body:
For a school project I am trying to write to a table called enrolment where the student number and the course they have selected are added after they have been tested to make sure the student name and number exists in another database. No errors are coming up, however when I check my database afterward enrolment says its an empty set. Does anyone have suggestions?

<?php

require 'connect.php';

//making a variable from the user data
$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];

//linking up the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());

// select all from table student which show student name and number
$squery = "SELECT * FROM student";
$sresult = mysqli_query($link, $squery);

$found = 0;

while ($srow = mysqli_fetch_array($sresult)) {

    // testing if the student name and number match the users data
    if ($name == $srow['family'] && $number == $srow['uid']) {

        $enrol = "INSERT INTO enrolment (uid course) VALUES('$number' '$course')";
        $found = 1;
        break;
    }
}
mysqli_close($link);

?>

        <form action="index.php" method="post">

            <input type = "submit" value="back" name="back">
        </form>

index.php (form)

<!DOCTYPE html>

Course Selection

    <form action="next.php" method="post">

              Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">

              Student Number: <input type="text" name= "snumber" required="required" maxlength="9">

        <?php
        //form
      require 'connect.php';

       echo "Select a course: <select name = \"pcourse\">\n";

      $link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());

      $query = "SELECT * FROM course";
      $result = mysqli_query($link, $query);

      while ($row = mysqli_fetch_array($result)) {
        echo "<option> $row[code] $row[name] $row[maxenroll]</option>
";
      }

      mysqli_free_result($results);

      mysqli_close ($link);

      echo " </select>\n";

      ?>

      <input type = "submit" value="submit" name= "submit">

    </form>

Body:
Your insert code just a string. You should send to mysql your insert code. Try this

$enrol = "INSERT INTO enrolment (uid, course) VALUES($number, $course)";
$link->query($enrol);


问:
Change the domains of SSL certificate - like Charles Proxy
When generating an SSL paid or self signed you assign a set of specific domains (wildcard or not), known as canonical names. If you use this SSL to open domains which are not on the list Chrome gives warning - NET::ERR_CERT_COMMON_NAME_INVALID - you know, click advanced  > Proceed Unsafe.

I use the same certificate on Charles Proxy which opens all urls fine on chrome, without warning. Viewing on dev options > security > view certificate, I can see that it's my certificate, my domain etc. However Charles changes the domains on the cert automatically for any website you visit, which pass all Chrome validations / warnings.

  -- >

How can I achieve this?

Preferably using Nginx or NodeJS via https.createServer(...)

Not worried about how to bypass chrome but how can a .cer be modified so instantly for each http request and be served to the browser.

答:
Solved!

There are several options which include mitmproxy, sslsniff and my favorite SSLSPLIT

It is available for all distros, prepackaged, install via apt-get or yum install sslsplit and that's all.
You simply need to run 1 command, simply package your certificate with key and bundle into 1 pem file and run this:

Forward the port though NAT via iptables and then run sslsplit

```<code>iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8888

sslsplit -p /path/anywhere.pid -c certbundle.pem -l connections.log ssl 0.0.0.0 8888 sni 443
</code>```

It reissues new certificates on the fly with modified subject names as well as log all traffic if you wish. Bypasses all chrome validations and it is quite fast. It doesn't proxy through Nginx though as I was hoping.
.

--- Edit 1/6/2018
Also found a node solution which is beyond what I need https://www.npmjs.com/package/node-forge

Body:
Solved!

There are several options which include mitmproxy, sslsniff and my favorite SSLSPLIT

It is available for all distros, prepackaged, install via apt-get or yum install sslsplit and that's all.
You simply need to run 1 command, simply package your certificate with key and bundle into 1 pem file and run this:

Forward the port though NAT via iptables and then run sslsplit

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8888

sslsplit -p /path/anywhere.pid -c certbundle.pem -l connections.log ssl 0.0.0.0 8888 sni 443

It reissues new certificates on the fly with modified subject names as well as log all traffic if you wish. Bypasses all chrome validations and it is quite fast. It doesn't proxy through Nginx though as I was hoping.
.

--- Edit 1/6/2018
Also found a node solution which is beyond what I need https://www.npmjs.com/package/node-forge


问:
ASP.NET Core return JSON with status code
I'm looking for the correct way to return JSON with a HTTP status code in my .NET Core Web API controller. I use to use it like this:

```<code>public IHttpActionResult GetResourceData()
{
    return this.Content(HttpStatusCode.OK, new { response = "Hello"});
}
</code>```

This was in a 4.6 MVC application but now with .NET Core I don't seem to have this IHttpActionResult I have ActionResult and using like this:

```<code>public ActionResult IsAuthenticated()
{
    return Ok(Json("123"));
}
</code>```

But the response from the server is weird, as in the image below:

I just want the Web API controller to return JSON with a HTTP status code like I did in Web API 2.

答:
The easiest way I came up with is :</p>

```<code>var result = new Item { Id = 123, Name = "Hero" };

return new JsonResult(result)
{
    StatusCode = StatusCodes.Status201Created // Status code here
};
</code>```

Body:
I'm looking for the correct way to return JSON with a HTTP status code in my .NET Core Web API controller. I use to use it like this:

public IHttpActionResult GetResourceData()
{
    return this.Content(HttpStatusCode.OK, new { response = "Hello"});
}

This was in a 4.6 MVC application but now with .NET Core I don't seem to have this IHttpActionResult I have ActionResult and using like this:

public ActionResult IsAuthenticated()
{
    return Ok(Json("123"));
}

But the response from the server is weird, as in the image below:

I just want the Web API controller to return JSON with a HTTP status code like I did in Web API 2.

Body:
The easiest way I came up with is :

var result = new Item { Id = 123, Name = "Hero" };

return new JsonResult(result)
{
    StatusCode = StatusCodes.Status201Created // Status code here
};


问:
Change packaging to war causes 404
I've got a Maven project with Java Enterprise 7, Java 8 and I use IntelliJ.
When I add the  attribut with war in the pom.xml, I get 404 in my browser trying to get the index page. I didn't get this error before the changing packaging to war.

My project structure can be seen in the picture.

I noticed that my index.xhtml is missing in the out Directory after chanaging to war. Why? Thanks for your help :)

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <display-name>JSF Hibernate</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.xhtml</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

I changed my project structure after the war-plugin-specification as mentioned in the answer.

Problem still exists.

```<code><?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>MyGroupID</groupId>
    <artifactId>Application</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <webXml>src\main\web\WEB-INF\web.xml</webXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
        <repository>
            <uniqueVersion>false</uniqueVersion>
            <id>corp1</id>
            <name>Corporate Repository</name>
            <url>file:///home/myfolder/.m2</url>
            <layout>default</layout>
        </repository>
    </distributionManagement>

    <dependencies>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.8-dmr</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.12.Final</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml</groupId>
            <artifactId>classmate</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>5.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jandex</artifactId>
            <version>2.0.3.Final</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.spec.javax.transaction</groupId>
            <artifactId>jboss-transaction-api_1.2_spec</artifactId>
            <version>1.0.1.Final</version>
        </dependency>

    </dependencies>
</project>
</code>```

It is a glassfish 5.0.0 Server.

答:
normally in a maven war project the structure looks something like this:

```<code>.
├── README.md
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   ├── resources
│   │   └── webapp
│   │       ├── WEB-INF
│   │       └── index.html
│   └── test
│       ├── java
│       └── resources
└── target
</code>```

I see you have: /src/main/java but the web app is in /web
this will not work in a maven web project...

Also it looks like you have the pom.xml in the /web project and not in the root of the project.

It also looks like you have a /lib folder in the root of your project. All the dependencies there should be added to the pom.xml file as dependencies and the lib folder will then be generated by maven in the webapp folder in the resulting war

So think about reorganising your code to conform to the maven structure. As Maven works with convention over configuration this is always a good idea :-)

The target folder is only used for the build.

Title: Change packaging to war causes 404

Body:
I've got a Maven project with Java Enterprise 7, Java 8 and I use IntelliJ.
When I add the  attribut with war in the pom.xml, I get 404 in my browser trying to get the index page. I didn't get this error before the changing packaging to war.

My project structure can be seen in the picture.

I noticed that my index.xhtml is missing in the out Directory after chanaging to war. Why? Thanks for your help :)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <display-name>JSF Hibernate</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.xhtml</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
</web-app>

I changed my project structure after the war-plugin-specification as mentioned in the answer.

Problem still exists.

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>MyGroupID</groupId>
    <artifactId>Application</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <webXml>src\main\web\WEB-INF\web.xml</webXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
        <repository>
            <uniqueVersion>false</uniqueVersion>
            <id>corp1</id>
            <name>Corporate Repository</name>
            <url>file:///home/myfolder/.m2</url>
            <layout>default</layout>
        </repository>
    </distributionManagement>

    <dependencies>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.8-dmr</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.12.Final</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml</groupId>
            <artifactId>classmate</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>5.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>

        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jandex</artifactId>
            <version>2.0.3.Final</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.spec.javax.transaction</groupId>
            <artifactId>jboss-transaction-api_1.2_spec</artifactId>
            <version>1.0.1.Final</version>
        </dependency>

    </dependencies>
</project>

It is a glassfish 5.0.0 Server.

Body:
normally in a maven war project the structure looks something like this:

.
├── README.md
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   ├── resources
│   │   └── webapp
│   │       ├── WEB-INF
│   │       └── index.html
│   └── test
│       ├── java
│       └── resources
└── target

I see you have: /src/main/java but the web app is in /web
this will not work in a maven web project...

Also it looks like you have the pom.xml in the /web project and not in the root of the project.

It also looks like you have a /lib folder in the root of your project. All the dependencies there should be added to the pom.xml file as dependencies and the lib folder will then be generated by maven in the webapp folder in the resulting war

So think about reorganising your code to conform to the maven structure. As Maven works with convention over configuration this is always a good idea :-)

The target folder is only used for the build.


问:
Handling promise.reject to try-catch or promise.catch
My understanding for promise is not perfect.

So I'm not sure which code is right way for handling error and exception cases.

Pleas help me to write code correctly.

1st.  try - catch for sequelizer's promise.reject

```<code>async function doGetAdminList(adminName) {

      let adminList;
      try {
        adminList = await sequelize.query(
          sqls.GET_ADMIN_LIST,
          { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT }
        );
      } catch (e) {
        return Promise.reject({status:500, message: "SQL Error" });
      }

      if (!adminList || !Object.keys(adminList).length) {
        log.info('\nadminList not found :\n');
        return Promise.reject({status:400, message: 'adminList not found.' })
      }

      return adminList;
    }
</code>```

For this, I wonder if try-catch can catch sequelizer's promise.catch().

2nd. do not handle sequelizer's promise.reject

```<code>async function doGetAdminList(adminName) {
          let adminList;
          adminList = await sequelize.query(
              sqls.GET_ADMIN_LIST,
              { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT }
          );

          if (!adminList || !Object.keys(adminList).length) {
            log.info('\nadminList not found :\n');
            return Promise.reject({status:400, message: 'adminList not found.' })
          }

          return adminList;
        }
</code>```

For this, I wonder if sequelizer's promise.reject() can be passed caller function and catched caller's at promise.catch().

Above sequelize-using function will be used below express function.

adminController.js

```<code>const jwtAuth = require('../common/jwtAuth.js');

exports.getAdminList = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");

  if (!req.body.adminName) {
    return res.status(400).json({ message: 'adminName is empty.' });
  }

  jwtAuth(req.headers.accesstoken)
  .then((decoded) => {
    worker = decoded.loginName;
    return doGetAdminList(adminName);
  })
  .then((adminList) => {
    log.info("getAdminList() finish");
    res.status(200).json(adminList);
  })
  .catch(e => {
    log.error(e);
    return res.status(e.status).json(e);
  });
};
</code>```

jwtAuth.js  is also promise function.

```<code>const jwt = require('jsonwebtoken');
module.exports = async function verifyJwt(token) {
  return await new Promise((resolve, reject) => {
    if (!token) {
      reject({status:401, message:'Empty token'});
      return;
    }

    jwt.verify(token,"dipa",function(err, decoded){
      if(err) {
        reject({status:401, message:'TokenExpiredError'});
      } else {
        resolve(decoded);
      }
    });
  });
}
</code>```

答:
There is no need to use 'async' if your function returns a promise, because async function returns a Promise.

What I mean is that the result of var somethink = await doSomethink() its not a promise its an object and because you return it from an async function its returned as Promise.resolve(somethink ).

So your 'jwtAuth.js' its better without

```<code>const jwt = require('jsonwebtoken');
module.exports = function verifyJwt(token) {
  return new Promise((resolve, reject) => {
    if (!token) {
      reject({status:401, message:'Empty token'});
      return;
    }

    jwt.verify(token,"dipa",function(err, decoded){
      if(err) {
        reject({status:401, message:'TokenExpiredError'});
      } else {
        resolve(decoded);
      }
    });
  });
}
</code>```

Same goes for

```<code>function doGetAdminList(adminName) {

  let adminList;

  return sequelize.query(
    sqls.GET_ADMIN_LIST, {
      replacements: {
        adminName: adminName
      },
      type: sequelize.QueryTypes.SELECT
    }
  ).catch((e)=> {
    //here you catch you sequelize error which can be anything
    //you can either catch and throw a new Error
    log.info('\nadminList not found :\n');
    throw Error({
      status: 500,
      message: "SQL Error"
    })
  })

}
</code>```

About getAdminList and the catch at the end.

If jwtAuth or doGetAdminList throws an error .catch will receive the error.

If in doGetAdminList you dont do .catch on sequelize.query then the sequelize error will travel to your catch in here. But if you wanna handle the error and rethrow you error is possible.

```<code>const jwtAuth = require('../common/jwtAuth.js');

exports.getAdminList = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");

  if (!req.body.adminName) {
    res.status(400).json({ message: 'adminName is empty.' });
  }

  jwtAuth(req.headers.accesstoken)
  .then((decoded) => {
    worker = decoded.loginName;
    return doGetAdminList(adminName);
  })
  .then((adminList) => {
    log.info("getAdminList() finish");
    res.status(200).json(adminList);
  })
  .catch(e => {
    //the message with mess "SQL Error" will travel here.
    log.error(e);
    res.status(e.status).json(e);
  });
};
</code>```

Adding, If you dont wanna change the error but you wanna log and passthroud the error you can rethrow it

```<code>.catch(function(e) {
    log.info('\nadminList not found :\n');
    throw e;
  })
</code>```

Also if you wanna do getAdminList with async/await

```<code>exports.getAdminList = async function(req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");

  if (!req.body.adminName)
    res.status(400).json({message: 'adminName is empty.'});

  try {

    let decoded = await jwtAuth(req.headers.accesstoken)
    worker = decoded.loginName;

    let adminList = await doGetAdminList(req.body.adminName);
    log.info("getAdminList() finish");

    res.status(200).json(adminList);

  } catch (e) {
     //the message with mess "SQL Error" will travel here.
    log.error(e);
    res.status(e.status).json(e);
  }

};
</code>```

Body:
My understanding for promise is not perfect.

So I'm not sure which code is right way for handling error and exception cases.

Pleas help me to write code correctly.

1st.  try - catch for sequelizer's promise.reject

async function doGetAdminList(adminName) {

      let adminList;
      try {
        adminList = await sequelize.query(
          sqls.GET_ADMIN_LIST,
          { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT }
        );
      } catch (e) {
        return Promise.reject({status:500, message: "SQL Error" });
      }

      if (!adminList || !Object.keys(adminList).length) {
        log.info('\nadminList not found :\n');
        return Promise.reject({status:400, message: 'adminList not found.' })
      }

      return adminList;
    }

For this, I wonder if try-catch can catch sequelizer's promise.catch().

2nd. do not handle sequelizer's promise.reject

async function doGetAdminList(adminName) {
          let adminList;
          adminList = await sequelize.query(
              sqls.GET_ADMIN_LIST,
              { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT }
          );

          if (!adminList || !Object.keys(adminList).length) {
            log.info('\nadminList not found :\n');
            return Promise.reject({status:400, message: 'adminList not found.' })
          }

          return adminList;
        }

For this, I wonder if sequelizer's promise.reject() can be passed caller function and catched caller's at promise.catch().

Above sequelize-using function will be used below express function.

adminController.js

const jwtAuth = require('../common/jwtAuth.js');

exports.getAdminList = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");

  if (!req.body.adminName) {
    return res.status(400).json({ message: 'adminName is empty.' });
  }

  jwtAuth(req.headers.accesstoken)
  .then((decoded) => {
    worker = decoded.loginName;
    return doGetAdminList(adminName);
  })
  .then((adminList) => {
    log.info("getAdminList() finish");
    res.status(200).json(adminList);
  })
  .catch(e => {
    log.error(e);
    return res.status(e.status).json(e);
  });
};

jwtAuth.js  is also promise function.

const jwt = require('jsonwebtoken');
module.exports = async function verifyJwt(token) {
  return await new Promise((resolve, reject) => {
    if (!token) {
      reject({status:401, message:'Empty token'});
      return;
    }

    jwt.verify(token,"dipa",function(err, decoded){
      if(err) {
        reject({status:401, message:'TokenExpiredError'});
      } else {
        resolve(decoded);
      }
    });
  });
}

Body:
There is no need to use 'async' if your function returns a promise, because async function returns a Promise.

What I mean is that the result of var somethink = await doSomethink() its not a promise its an object and because you return it from an async function its returned as Promise.resolve(somethink ).

So your 'jwtAuth.js' its better without

const jwt = require('jsonwebtoken');
module.exports = function verifyJwt(token) {
  return new Promise((resolve, reject) => {
    if (!token) {
      reject({status:401, message:'Empty token'});
      return;
    }

    jwt.verify(token,"dipa",function(err, decoded){
      if(err) {
        reject({status:401, message:'TokenExpiredError'});
      } else {
        resolve(decoded);
      }
    });
  });
}

Same goes for

function doGetAdminList(adminName) {

  let adminList;

  return sequelize.query(
    sqls.GET_ADMIN_LIST, {
      replacements: {
        adminName: adminName
      },
      type: sequelize.QueryTypes.SELECT
    }
  ).catch((e)=> {
    //here you catch you sequelize error which can be anything
    //you can either catch and throw a new Error
    log.info('\nadminList not found :\n');
    throw Error({
      status: 500,
      message: "SQL Error"
    })
  })

}

About getAdminList and the catch at the end.

If jwtAuth or doGetAdminList throws an error .catch will receive the error.

If in doGetAdminList you dont do .catch on sequelize.query then the sequelize error will travel to your catch in here. But if you wanna handle the error and rethrow you error is possible.

const jwtAuth = require('../common/jwtAuth.js');

exports.getAdminList = function (req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");

  if (!req.body.adminName) {
    res.status(400).json({ message: 'adminName is empty.' });
  }

  jwtAuth(req.headers.accesstoken)
  .then((decoded) => {
    worker = decoded.loginName;
    return doGetAdminList(adminName);
  })
  .then((adminList) => {
    log.info("getAdminList() finish");
    res.status(200).json(adminList);
  })
  .catch(e => {
    //the message with mess "SQL Error" will travel here.
    log.error(e);
    res.status(e.status).json(e);
  });
};

Adding, If you dont wanna change the error but you wanna log and passthroud the error you can rethrow it

.catch(function(e) {
    log.info('\nadminList not found :\n');
    throw e;
  })

Also if you wanna do getAdminList with async/await

exports.getAdminList = async function(req, res) {
  res.setHeader("Content-Type", "application/json; charset=utf-8");

  if (!req.body.adminName)
    res.status(400).json({message: 'adminName is empty.'});

  try {

    let decoded = await jwtAuth(req.headers.accesstoken)
    worker = decoded.loginName;

    let adminList = await doGetAdminList(req.body.adminName);
    log.info("getAdminList() finish");

    res.status(200).json(adminList);

  } catch (e) {
     //the message with mess "SQL Error" will travel here.
    log.error(e);
    res.status(e.status).json(e);
  }

};


问:
How do I get all invoices for a customer using the Linq extensions in QuickBooks Online API v3?
I would like to query for all invoices in a customer. The SDK has some LinqExtender extensions so one would think you could do (for example customer id '1' which maps to an existing customer):

```<code>CreateQueryService<IppData.Invoice>().Where(x => x.CustomerRef.Value = "1")
</code>```

But, this produces the following SQL:

```<code>Select * FROM Invoice  WHERE CustomerRef.Value = '1'
</code>```

which is a no-go:

```<code><IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2014-08-24T13:41:04.367-07:00">
  <Fault type="ValidationFault">
    <Error code="4001">
      <Message>Invalid query</Message>
      <Detail>QueryValidationError: Property CustomerRef.Value not found for Entity Invoice</Detail>
    </Error>
  </Fault>
</IntuitResponse>
</code>```

The correct SQL would read:

```<code>Select * FROM Invoice WHERE CustomerRef = '1'
</code>```

Of course using SQL directly and creating dynamic queries (eww) works, but I was hoping there was a better way. I like the readability and (hopefully) type-safe-goodness of the Linq extensions, and you'd think this would be such a common thing to do. Unfortunately the documentation is a huge maze and severely lacks any kind of useful examples, so: does anyone know how to do this, or are we stuck with string SQL?

答:
I'm using a different library but using CustomerRef as the field and the ID as a string ended up working.  Documentation wasn't very clear on this</p>

```<code>{
    field: 'CustomerRef',
    value: '2083',
    operator: '='
}
</code>```

Body:
I would like to query for all invoices in a customer. The SDK has some LinqExtender extensions so one would think you could do (for example customer id '1' which maps to an existing customer):

CreateQueryService<IppData.Invoice>().Where(x => x.CustomerRef.Value = "1")

But, this produces the following SQL:

Select * FROM Invoice  WHERE CustomerRef.Value = '1'

which is a no-go:

<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2014-08-24T13:41:04.367-07:00">
  <Fault type="ValidationFault">
    <Error code="4001">
      <Message>Invalid query</Message>
      <Detail>QueryValidationError: Property CustomerRef.Value not found for Entity Invoice</Detail>
    </Error>
  </Fault>
</IntuitResponse>

The correct SQL would read:

Select * FROM Invoice WHERE CustomerRef = '1'

Of course using SQL directly and creating dynamic queries (eww) works, but I was hoping there was a better way. I like the readability and (hopefully) type-safe-goodness of the Linq extensions, and you'd think this would be such a common thing to do. Unfortunately the documentation is a huge maze and severely lacks any kind of useful examples, so: does anyone know how to do this, or are we stuck with string SQL?

Body:
I'm using a different library but using CustomerRef as the field and the ID as a string ended up working.  Documentation wasn't very clear on this

{
    field: 'CustomerRef',
    value: '2083',
    operator: '='
}


问:
C# - Restart timer when the event handler gets called again
I have a C# WinForms application that has a panel. The panel loads a UserControl and the UserControl contains a DataGridView.

In my UserControl, I have an event handler for the MouseDown event on the DataGrid

```<code>private void palletsGrid_MouseDown(object sender, MouseEventArgs e)
{
    try
    {
        EventHandler handler = onScrolling;
        if (handler != null)
        {
            handler(this, new EventArgs());
        }
    }
    Catch (Exception ex)
    {
        Logging.LogWarn("Mouse down error: ", ex);
    }
}
</code>```

Where onScrolling is a publicly declared EventHandler property.

I deal with this EventHandler in the main form because, I have a timer that auto refreshes every 5 seconds. So I need the main form to know to stop refreshing when this event (scrolling through the DataGridView) happens.

In my main form, this is what I am doing:

```<code>private void userControl_ScrollEvent(object sender, EventArgs e)
{
    try
    {
        timer1.Stop();
        Timer pauseTimer = new Timer();
        pauseTimer.Interval = 60000;
        pauseTimer.Start();
        pauseTimer.Tick += new System.EventHandler(pauseTimer_Tick);
    }
    catch (Exception ex)
    {
        Logging.LogFatal("Scroll event capture error: ", ex);
    }
}
</code>```

What this does is, when the user is scrolling through the DataGridView, the main form stops the auto refresh for 60 seconds. Once the 60 second pauseTimer ticks, the refreshTimer resumes like normal.

Problem:

I need my form to know when I touch the screen twice. As in, if I touch the screen now, the timer starts. Does not refresh for 60 seconds. If I touch it again, the 60 seconds needs to start from the second touch. Not the first. So every time I touch the screen, the pauseTimer needs to restart.

答:
Like @FrankM points out, you should not create a new timer everytime you scroll. You should always be careful when creating timers (System.Windows.Forms.Timer) in code, if you do, you have to make sure they are disposed properly. The easiest way is to add timers from the designer, this way proper cleanup is taken care of for you. More on disposal of System.Windows.Forms.Timers

Solution 1: Add a pausetimer in the designer and restart it in the scroll event. How to restart a timer may not be obvious, but you do it by first disabling the timer, then enable it:

```<code>try
{
    timer1.Enabled = false;
    //Set interval and tick-handler from designer
    pauseTimer.Enabled = false;
    pauseTimer.Enabled = true;
}
catch (Exception ex)
{
    Logging.LogFatal("Scroll event capture error: ", ex);
}
</code>```

Solution 2: Get rid of the pause timer and just change the interval of your refresh-timer.

```<code>try
{
    //Assume that this is the refreshtimer. In the Tick-eventhandler
    //you reset interval to default refresh intervals
    timer1.Interval = 60000;
    timer1.Enabled = false;
    timer1.Enabled = true;

}
catch (Exception ex)
{
    Logging.LogFatal("Scroll event capture error: ", ex);
}
</code>```

Body:
I have a C# WinForms application that has a panel. The panel loads a UserControl and the UserControl contains a DataGridView.

In my UserControl, I have an event handler for the MouseDown event on the DataGrid

private void palletsGrid_MouseDown(object sender, MouseEventArgs e)
{
    try
    {
        EventHandler handler = onScrolling;
        if (handler != null)
        {
            handler(this, new EventArgs());
        }
    }
    Catch (Exception ex)
    {
        Logging.LogWarn("Mouse down error: ", ex);
    }
}

Where onScrolling is a publicly declared EventHandler property.

I deal with this EventHandler in the main form because, I have a timer that auto refreshes every 5 seconds. So I need the main form to know to stop refreshing when this event (scrolling through the DataGridView) happens.

In my main form, this is what I am doing:

private void userControl_ScrollEvent(object sender, EventArgs e)
{
    try
    {
        timer1.Stop();
        Timer pauseTimer = new Timer();
        pauseTimer.Interval = 60000;
        pauseTimer.Start();
        pauseTimer.Tick += new System.EventHandler(pauseTimer_Tick);
    }
    catch (Exception ex)
    {
        Logging.LogFatal("Scroll event capture error: ", ex);
    }
}

What this does is, when the user is scrolling through the DataGridView, the main form stops the auto refresh for 60 seconds. Once the 60 second pauseTimer ticks, the refreshTimer resumes like normal.

Problem:

I need my form to know when I touch the screen twice. As in, if I touch the screen now, the timer starts. Does not refresh for 60 seconds. If I touch it again, the 60 seconds needs to start from the second touch. Not the first. So every time I touch the screen, the pauseTimer needs to restart.

Body:
Like @FrankM points out, you should not create a new timer everytime you scroll. You should always be careful when creating timers (System.Windows.Forms.Timer) in code, if you do, you have to make sure they are disposed properly. The easiest way is to add timers from the designer, this way proper cleanup is taken care of for you. More on disposal of System.Windows.Forms.Timers

Solution 1: Add a pausetimer in the designer and restart it in the scroll event. How to restart a timer may not be obvious, but you do it by first disabling the timer, then enable it:

try
{
    timer1.Enabled = false;
    //Set interval and tick-handler from designer
    pauseTimer.Enabled = false;
    pauseTimer.Enabled = true;
}
catch (Exception ex)
{
    Logging.LogFatal("Scroll event capture error: ", ex);
}

Solution 2: Get rid of the pause timer and just change the interval of your refresh-timer.

try
{
    //Assume that this is the refreshtimer. In the Tick-eventhandler
    //you reset interval to default refresh intervals
    timer1.Interval = 60000;
    timer1.Enabled = false;
    timer1.Enabled = true;

}
catch (Exception ex)
{
    Logging.LogFatal("Scroll event capture error: ", ex);
}


问:
English texts lexicon comparison
Let's imagine, we can build a statistics table, how much each word is used in some English text or book. We can gather statistics for each text/book in library.
What is the simplest way to compare these statistics with each other? How can we find group/cluster of texts with very statistically similar lexicon?</p>

答: I would start by seeing what Lucene (http://lucene.apache.org/java/docs/index.html ) had to offer. After that you will need to use a machine learning method and look at http://en.wikipedia.org/wiki/Information_retrieval.</p>

Title: English texts lexicon comparison


问:
What would be a good approach to construct docker containers for nginx, uwsgi, django
I have an approach that use a base OS image to construct nginx, uwsgi, django all inside a container for the purpose to fast deploy a website on a cloud service. And I also successfully building a reverse proxy to point to different django apps, but still inside one container. This approach has the drawback that, when I update one of the services or apps, I need to completely destroy the whole container and create a new container with all services. Therefore, I want to construct for nginx, uwsgi each with one container, for each django app a container. In short, I want to separate apps and services each with a container. Most of the tutorials online deploy such combinations inside one container.  </p>

<p>So my question is what would be the best approach to do so? For services such as nginx, uwsgi, should I construct them without a base OS image but simply just the service image, or I should construct them each with a base OS image and then add the service on top? Also, for my Django apps, should I construct for each app with a base OS image or just start base with python image?    </p>

答:
Yes, you need to deploy each service separately and NGINX server will listen on 80(http) or 443(https) port to act as a reverser poxy for all other containers.

You can use docker-compose to run all containers with a file, also you need to create docker network which helps you to achieve zero downtime for any service upgrade.

There are many more examples available on the internet.

have a look at blog:
https://devopsdevelopment.wordpress.com/2017/08/02/how-to-configure-docker-with-nginx-and-php-application/

Body:
I have an approach that use a base OS image to construct nginx, uwsgi, django all inside a container for the purpose to fast deploy a website on a cloud service. And I also successfully building a reverse proxy to point to different django apps, but still inside one container. This approach has the drawback that, when I update one of the services or apps, I need to completely destroy the whole container and create a new container with all services. Therefore, I want to construct for nginx, uwsgi each with one container, for each django app a container. In short, I want to separate apps and services each with a container. Most of the tutorials online deploy such combinations inside one container.

So my question is what would be the best approach to do so? For services such as nginx, uwsgi, should I construct them without a base OS image but simply just the service image, or I should construct them each with a base OS image and then add the service on top? Also, for my Django apps, should I construct for each app with a base OS image or just start base with python image?


问:
What is the difference between Unit.type and Unit
I have the method below:

```<code>override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] = {
  val f = Future.sequence(notifications.map(insert)).map(_ => Unit)
  f.onFailure { case ex => sys.error(s"Got exception whilst saving PushNotification: $ex") }
  f
}
</code>```

It gives the following compiler error:

```<code>  type mismatch;
  found   : scala.concurrent.Future[Unit.type]
  required: scala.concurrent.Future[Unit]
     f
     ^
</code>```

I thought Unit was a type with a single element, thus there shouldn't be any confusion when it comes to Unit. I tried googling this but I couldn't find any more information about what "Unit.type" is.

If I simplify the method like this, then it works fine:

```<code>override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] =
  Future.sequence(notifications.map(insert)).map(_ => Unit)
</code>```

What is going on here?

答:
Types in scala are objects too, and, as any object, have their own types.
() is an instance of type Unit. Unit is an instance of Unit.type.
(I don't think there is a way to go even higher - no such thing as Unit.type.type though).

For most non-esoteric purposes, you don't need to worry about it, just use () whenever you need to reference an instance of type Unit, you shouldn't really need the other one anywhere.

Body:
I have the method below:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] = {
  val f = Future.sequence(notifications.map(insert)).map(_ => Unit)
  f.onFailure { case ex => sys.error(s"Got exception whilst saving PushNotification: $ex") }
  f
}

It gives the following compiler error:

  type mismatch;
  found   : scala.concurrent.Future[Unit.type]
  required: scala.concurrent.Future[Unit]
     f
     ^

I thought Unit was a type with a single element, thus there shouldn't be any confusion when it comes to Unit. I tried googling this but I couldn't find any more information about what "Unit.type" is.

If I simplify the method like this, then it works fine:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] =
  Future.sequence(notifications.map(insert)).map(_ => Unit)

What is going on here?