问:
How do I transform my SQL query to a MongoDB query?
I migrated timeseries data from SQL to MongoDB. I'll give you an example:

Let's say we have a measurement device with an ID, where once per minute a value gets read. So per day, we have 24 hours * 60 minutes = 1440 values for that device.

In SQL, we have 1440 single rows for this device per day:

```<code>ID          Timestamp                Value
400001       01.01.2017 00:00:00      ...
""           01.01.2017 00:01:00      ...
""                  ...               ...
""           01.01.2017 23:59:00      ...
</code>```

I migrated the data to MongoDB where I now have one document per day, with the values distributed to 24 hour array that respectively contain 60 minute fields containing the values (and only one Timestamp with the date XX-XX-XXXX 00:00:00):

{ ID: 400001,
  Timestamp: 01.01.2017 00:00:00,
  Hours:
       [ 0: [0: ..., 1: ..., 2: ..., ....... 59: ... ],
         1: [0: ..., 1: ..., 2: ..., ....... 59: ... ],
          .
          .
        23: [0: ..., 1: ..., 2: ..., ....... 59: ... ]
       ]
}

My Problem is:
I want to transform the following SQL statement to mongoDB:

```<code>SELECT (Val) AS Val, (UNIX_TIMESTAMP(DATE_FORMAT(ArrivalTime, '%Y-%m-%d %H:%i:00'))) * 1000 AS timestmp FROM database WHERE ID = 400001 AND ArrivalTime BETWEEN FROM_UNIXTIME(1470002400) AND FROM_UNIXTIME(1475272800) ORDER BY ArrivalTime ASC
</code>```

Output

Since in MongoDB I only save the day Timestamp and then split the values in arrays, I don't have a Timestamp for each Value like in SQL. So if I want to for example, get the values between 01.01.2017 02:14:00 and 01.01.2017 18:38:00, how would I do that?

I made a MongoDB query that can give me the Values between two whole days:

```<code>db.getCollection('test').aggregate([{$match: {ID: '400001', $and: [ {Timestamp_day: {$gte: new ISODate("2016-08-01 00:00:00.000Z")}}, {Timestamp_day: {$lte: new ISODate("2016-10-01 00:00:00.000Z")}}]}},{$unwind:"$Hours"}, {$unwind:"$Hours"}, {$group: {_id: '$Timestamp_day', Value: {$push: "$Hours"}}}, {$sort: {_id: 1}}]);
</code>```

Output

But I need it like in SQL that I can also just give out the Values for a few hours, and with the correct Timestamp given per each Values.

I hope you can help me.

答:
This should get you going:

```<code>db.collection.aggregate([{
    $match: {
        "ID": '400001',
        "Timestamp_day": {
            $gte: new ISODate("2017-01-01T00:00:00.000Z"),
            $lte: new ISODate("2017-01-01T00:00:00.000Z")
        }
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Hour"
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Minute"
    }
}, {
    $project: {
        "_id": 0, // remove the "_id" field
        "Val": "$Hours", // rename "Hours" to "Val"
        "Timestamp": { // "resolve" our timestamp...
            $add: // ...by adding
            [
                { $multiply: [ "$Hour", 60 * 60 * 1000 ] }, // ...the number of hours in milliseconds
                { $multiply: [ "$Minute", 60 * 1000 ] }, // ...plus the number of minutes in milliseconds
                "$Timestamp_day", // to the "Timestamp_day" value
            ]
        }
    }
}, {
    $sort: {
        "Timestamp": 1 // oh well, sort by timestamp ascending
    }
}]);
</code>```

With an input document of

```<code>{
    "_id" : ObjectId("5a0e7d096216d24dd605cdec"),
    "ID" : "400001",
    "Timestamp_day" : ISODate("2017-01-01T00:00:00.000Z"),
    "Hours" : [
        [
            0.0,
            0.1,
            2.0
        ],
        [
            1.0,
            1.1,
            2.1
        ],
        [
            2.0,
            2.1,
            2.2
        ]
    ]
}
</code>```

the results look like this:

```<code>/* 1 */
{
    "Val" : 0.0,
    "Timestamp" : ISODate("2017-01-01T00:00:00.000Z")
}

/* 2 */
{
    "Val" : 0.1,
    "Timestamp" : ISODate("2017-01-01T00:01:00.000Z")
}

/* 3 */
{
    "Val" : 2.0,
    "Timestamp" : ISODate("2017-01-01T00:02:00.000Z")
}

/* 4 */
{
    "Val" : 1.0,
    "Timestamp" : ISODate("2017-01-01T01:00:00.000Z")
}

/* 5 */
{
    "Val" : 1.1,
    "Timestamp" : ISODate("2017-01-01T01:01:00.000Z")
}

/* 6 */
{
    "Val" : 2.1,
    "Timestamp" : ISODate("2017-01-01T01:02:00.000Z")
}

/* 7 */
{
    "Val" : 2.0,
    "Timestamp" : ISODate("2017-01-01T02:00:00.000Z")
}

/* 8 */
{
    "Val" : 2.1,
    "Timestamp" : ISODate("2017-01-01T02:01:00.000Z")
}

/* 9 */
{
    "Val" : 2.2,
    "Timestamp" : ISODate("2017-01-01T02:02:00.000Z")
}
</code>```

UPDATE:

Based on your comment you need to calculate the difference between any value and its respective preceding value. This can be done the following way - there might be nicer ways of achieving the same thing, though... The first part is almost identical to the solution above except it has an added $match stage to remove null values as per your specification.

```<code>db.collection.aggregate([{
    $match: {
        "ID": '400001',
        "Timestamp_day": {
            $gte: new ISODate("2017-01-01T00:00:00.000Z"),
            $lte: new ISODate("2017-01-01T00:00:00.000Z")
        }
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Hour"
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Minute"
    }
}, {
    $match: {
        "Hours": { $ne: null } // get rid of all null values
    }
}, {
    $project: {
        "_id": 0, // remove the "_id" field
        "Val": "$Hours", // rename "Hours" to "Val"
        "Timestamp": { // "resolve" our timestamp...
            $add: // ...by adding
            [
                { $multiply: [ "$Hour", 60 * 60 * 1000 ] }, // ...the number of hours in milliseconds
                { $multiply: [ "$Minute", 60 * 1000 ] }, // ...plus the number of minutes in milliseconds
                "$Timestamp_day", // to the "Timestamp_day" value
            ]
        }
    }
}, {
    $sort: {
        "Timestamp": 1 // oh well, sort by timestamp ascending
    }
}, {
    $group: {
        "_id": null, // throw all documents in the same aggregated document
        "Docs": {
            $push: "$$ROOT" // and store our documents in an array
        }
    }
}, {
    $unwind: {
        path: "$Docs", // we flatten the "values" array
        includeArrayIndex: "Docs.Index", // this will give us the index of every element - there might be more elegant solutions using $map and $let...
    }
}, {
    $group: { // YES, unfortunately a second time... but this time we have the array index for each element
        "_id": null, // throw all documents in the same aggregated document
        "Docs": {
            $push: "$Docs" // and store our documents in an array
        }
    }
}, {
    $addFields: {
        "Docs": {
            $let: {
                vars: { "shiftedArray": { $concatArrays: [ [ null ], "$Docs.Val" ] } }, // shift value array by one to the right and put a null object at the start
                in: {
                    $map: {
                        input: "$Docs",
                        as: "d",
                        in: {
                            "Timestamp" : "$$d.Timestamp",
                            "Val": { $ifNull: [ { $abs: { $subtract: [ "$$d.Val", { $arrayElemAt: [ "$$shiftedArray", "$$d.Index" ] } ] } }, 0 ] }
                        }
                    }
                }
            }
        }
    }
}, {
    $unwind: "$Docs"
}, {
    $replaceRoot: {
        newRoot: "$Docs"
    }
}]);
</code>```

The results using your sample data set look like this:

```<code>/* 1 */
{
    "Timestamp" : ISODate("2017-01-01T00:00:00.000Z"),
    "Val" : 0.0
}

/* 2 */
{
    "Timestamp" : ISODate("2017-01-01T00:01:00.000Z"),
    "Val" : 0.0
}

/* 3 */
{
    "Timestamp" : ISODate("2017-01-01T00:02:00.000Z"),
    "Val" : 2.0
}

/* 4 */
{
    "Timestamp" : ISODate("2017-01-01T00:04:00.000Z"),
    "Val" : 3.0
}

/* 5 */
{
    "Timestamp" : ISODate("2017-01-01T00:05:00.000Z"),
    "Val" : 0.0
}

/* 6 */
{
    "Timestamp" : ISODate("2017-01-01T00:06:00.000Z"),
    "Val" : 1.0
}
</code>```

Body:
I migrated timeseries data from SQL to MongoDB. I'll give you an example:

Let's say we have a measurement device with an ID, where once per minute a value gets read. So per day, we have 24 hours * 60 minutes = 1440 values for that device.

In SQL, we have 1440 single rows for this device per day:

ID          Timestamp                Value
400001       01.01.2017 00:00:00      ...
""           01.01.2017 00:01:00      ...
""                  ...               ...
""           01.01.2017 23:59:00      ...

I migrated the data to MongoDB where I now have one document per day, with the values distributed to 24 hour array that respectively contain 60 minute fields containing the values (and only one Timestamp with the date XX-XX-XXXX 00:00:00):

{ ID: 400001,
  Timestamp: 01.01.2017 00:00:00,
  Hours:
       [ 0: [0: ..., 1: ..., 2: ..., ....... 59: ... ],
         1: [0: ..., 1: ..., 2: ..., ....... 59: ... ],
          .
          .
        23: [0: ..., 1: ..., 2: ..., ....... 59: ... ]
       ]
}

My Problem is:
I want to transform the following SQL statement to mongoDB:

SELECT (Val) AS Val, (UNIX_TIMESTAMP(DATE_FORMAT(ArrivalTime, '%Y-%m-%d %H:%i:00'))) * 1000 AS timestmp FROM database WHERE ID = 400001 AND ArrivalTime BETWEEN FROM_UNIXTIME(1470002400) AND FROM_UNIXTIME(1475272800) ORDER BY ArrivalTime ASC

Output

Since in MongoDB I only save the day Timestamp and then split the values in arrays, I don't have a Timestamp for each Value like in SQL. So if I want to for example, get the values between 01.01.2017 02:14:00 and 01.01.2017 18:38:00, how would I do that?

I made a MongoDB query that can give me the Values between two whole days:

db.getCollection('test').aggregate([{$match: {ID: '400001', $and: [ {Timestamp_day: {$gte: new ISODate("2016-08-01 00:00:00.000Z")}}, {Timestamp_day: {$lte: new ISODate("2016-10-01 00:00:00.000Z")}}]}},{$unwind:"$Hours"}, {$unwind:"$Hours"}, {$group: {_id: '$Timestamp_day', Value: {$push: "$Hours"}}}, {$sort: {_id: 1}}]);

Output

But I need it like in SQL that I can also just give out the Values for a few hours, and with the correct Timestamp given per each Values.

I hope you can help me.

Body:
This should get you going:

db.collection.aggregate([{
    $match: {
        "ID": '400001',
        "Timestamp_day": {
            $gte: new ISODate("2017-01-01T00:00:00.000Z"),
            $lte: new ISODate("2017-01-01T00:00:00.000Z")
        }
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Hour"
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Minute"
    }
}, {
    $project: {
        "_id": 0, // remove the "_id" field
        "Val": "$Hours", // rename "Hours" to "Val"
        "Timestamp": { // "resolve" our timestamp...
            $add: // ...by adding
            [
                { $multiply: [ "$Hour", 60 * 60 * 1000 ] }, // ...the number of hours in milliseconds
                { $multiply: [ "$Minute", 60 * 1000 ] }, // ...plus the number of minutes in milliseconds
                "$Timestamp_day", // to the "Timestamp_day" value
            ]
        }
    }
}, {
    $sort: {
        "Timestamp": 1 // oh well, sort by timestamp ascending
    }
}]);

With an input document of

{
    "_id" : ObjectId("5a0e7d096216d24dd605cdec"),
    "ID" : "400001",
    "Timestamp_day" : ISODate("2017-01-01T00:00:00.000Z"),
    "Hours" : [
        [
            0.0,
            0.1,
            2.0
        ],
        [
            1.0,
            1.1,
            2.1
        ],
        [
            2.0,
            2.1,
            2.2
        ]
    ]
}

the results look like this:

/* 1 */
{
    "Val" : 0.0,
    "Timestamp" : ISODate("2017-01-01T00:00:00.000Z")
}

/* 2 */
{
    "Val" : 0.1,
    "Timestamp" : ISODate("2017-01-01T00:01:00.000Z")
}

/* 3 */
{
    "Val" : 2.0,
    "Timestamp" : ISODate("2017-01-01T00:02:00.000Z")
}

/* 4 */
{
    "Val" : 1.0,
    "Timestamp" : ISODate("2017-01-01T01:00:00.000Z")
}

/* 5 */
{
    "Val" : 1.1,
    "Timestamp" : ISODate("2017-01-01T01:01:00.000Z")
}

/* 6 */
{
    "Val" : 2.1,
    "Timestamp" : ISODate("2017-01-01T01:02:00.000Z")
}

/* 7 */
{
    "Val" : 2.0,
    "Timestamp" : ISODate("2017-01-01T02:00:00.000Z")
}

/* 8 */
{
    "Val" : 2.1,
    "Timestamp" : ISODate("2017-01-01T02:01:00.000Z")
}

/* 9 */
{
    "Val" : 2.2,
    "Timestamp" : ISODate("2017-01-01T02:02:00.000Z")
}

UPDATE:

Based on your comment you need to calculate the difference between any value and its respective preceding value. This can be done the following way - there might be nicer ways of achieving the same thing, though... The first part is almost identical to the solution above except it has an added $match stage to remove null values as per your specification.

db.collection.aggregate([{
    $match: {
        "ID": '400001',
        "Timestamp_day": {
            $gte: new ISODate("2017-01-01T00:00:00.000Z"),
            $lte: new ISODate("2017-01-01T00:00:00.000Z")
        }
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Hour"
    }
}, {
    $unwind: {
      path: "$Hours",
      includeArrayIndex: "Minute"
    }
}, {
    $match: {
        "Hours": { $ne: null } // get rid of all null values
    }
}, {
    $project: {
        "_id": 0, // remove the "_id" field
        "Val": "$Hours", // rename "Hours" to "Val"
        "Timestamp": { // "resolve" our timestamp...
            $add: // ...by adding
            [
                { $multiply: [ "$Hour", 60 * 60 * 1000 ] }, // ...the number of hours in milliseconds
                { $multiply: [ "$Minute", 60 * 1000 ] }, // ...plus the number of minutes in milliseconds
                "$Timestamp_day", // to the "Timestamp_day" value
            ]
        }
    }
}, {
    $sort: {
        "Timestamp": 1 // oh well, sort by timestamp ascending
    }
}, {
    $group: {
        "_id": null, // throw all documents in the same aggregated document
        "Docs": {
            $push: "$$ROOT" // and store our documents in an array
        }
    }
}, {
    $unwind: {
        path: "$Docs", // we flatten the "values" array
        includeArrayIndex: "Docs.Index", // this will give us the index of every element - there might be more elegant solutions using $map and $let...
    }
}, {
    $group: { // YES, unfortunately a second time... but this time we have the array index for each element
        "_id": null, // throw all documents in the same aggregated document
        "Docs": {
            $push: "$Docs" // and store our documents in an array
        }
    }
}, {
    $addFields: {
        "Docs": {
            $let: {
                vars: { "shiftedArray": { $concatArrays: [ [ null ], "$Docs.Val" ] } }, // shift value array by one to the right and put a null object at the start
                in: {
                    $map: {
                        input: "$Docs",
                        as: "d",
                        in: {
                            "Timestamp" : "$$d.Timestamp",
                            "Val": { $ifNull: [ { $abs: { $subtract: [ "$$d.Val", { $arrayElemAt: [ "$$shiftedArray", "$$d.Index" ] } ] } }, 0 ] }
                        }
                    }
                }
            }
        }
    }
}, {
    $unwind: "$Docs"
}, {
    $replaceRoot: {
        newRoot: "$Docs"
    }
}]);

The results using your sample data set look like this:

/* 1 */
{
    "Timestamp" : ISODate("2017-01-01T00:00:00.000Z"),
    "Val" : 0.0
}

/* 2 */
{
    "Timestamp" : ISODate("2017-01-01T00:01:00.000Z"),
    "Val" : 0.0
}

/* 3 */
{
    "Timestamp" : ISODate("2017-01-01T00:02:00.000Z"),
    "Val" : 2.0
}

/* 4 */
{
    "Timestamp" : ISODate("2017-01-01T00:04:00.000Z"),
    "Val" : 3.0
}

/* 5 */
{
    "Timestamp" : ISODate("2017-01-01T00:05:00.000Z"),
    "Val" : 0.0
}

/* 6 */
{
    "Timestamp" : ISODate("2017-01-01T00:06:00.000Z"),
    "Val" : 1.0
}


来源: stackexchange

问:
Set object properties if truthy in Javascript
I want to transfer properties from objA to objB while changing their names and overriding only if they are truthy. Using lodash but an ES6 solution would be even better.

This is what I have so far:

```<code>// My initial objects
const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};

// Extracting and renaming
let {x: a, y: b, z: c} = obj1;

// Sanitizing
const temp = _.pickBy({x, y, z}, _.identity);

// Merging A and B
return {...objB, ...objA}; // {x: 1, y: 8, z: 9}
</code>```

Is there a less contrived way of doing this?

答:
Both solution use a Map to rename array keys, and Object#assign to merge objects (the snippets don't support object rest/spread).

ES2017

Use Object#entries (ES2017) to get the keys and values of objA, rename and add them only if the value is not falsy.

const a2x = new Map([['a', 'x'], ['b', 'y'], ['c', 'z']]);

const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};

const result = Object.assign({}, objB,
  Object.entries(objA).reduce((r, [k, v]) => v ?
    Object.assign(r, { [a2x.get(k)]: v }) : r, {}));

console.log(result);```
</div>
</div>
</p>

<p><strong>lodash:</strong></p>

<p>Use <code>_.mapKeys()</code> to change the names of the keys, then <code>_.pickBy()</code> with <code>_.identity()</code> to remove falsy values.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a2x = new Map([['a', 'x'], ['b', 'y'], ['c', 'z']]);

const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};

const result = Object.assign({}, objB,
  _.pickBy(_.mapKeys(objA, (v, k) => a2x.get(k)), _.identity));

console.log(result);</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
I want to transfer properties from objA to objB while changing their names and overriding only if they are truthy. Using lodash but an ES6 solution would be even better.

This is what I have so far:

// My initial objects
const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};

// Extracting and renaming
let {x: a, y: b, z: c} = obj1;

// Sanitizing
const temp = _.pickBy({x, y, z}, _.identity);

// Merging A and B
return {...objB, ...objA}; // {x: 1, y: 8, z: 9}

Is there a less contrived way of doing this?

Body:
Both solution use a Map to rename array keys, and Object#assign to merge objects (the snippets don't support object rest/spread).

ES2017

Use Object#entries (ES2017) to get the keys and values of objA, rename and add them only if the value is not falsy.

const a2x = new Map([['a', 'x'], ['b', 'y'], ['c', 'z']]);

const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};

const result = Object.assign({}, objB,
  Object.entries(objA).reduce((r, [k, v]) => v ?
    Object.assign(r, { [a2x.get(k)]: v }) : r, {}));

console.log(result);

lodash:

Use _.mapKeys() to change the names of the keys, then _.pickBy() with _.identity() to remove falsy values.

const a2x = new Map([['a', 'x'], ['b', 'y'], ['c', 'z']]);

const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};

const result = Object.assign({}, objB,
  _.pickBy(_.mapKeys(objA, (v, k) => a2x.get(k)), _.identity));

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
WPF MVVM Login Credentials
I am new to WPF and MVVM and I am making headway in understanding. There is one issue that has me a bit confused. I have a Login Page with associated ViewModel to log into the application. But, every time I use credentials I know are correct, it comes back with the "Username Incorrect" MessageBox. It should open to the WindowMain window. Perhaps an issue with Textbox binding?  Any help would be greatly appreciated. Thank you!

ObservableObject

```<code>public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propName)
    {
        Debug.Assert(GetType().GetProperty(propName) != null);

        var pc = PropertyChanged;
        if (pc != null)
        {
            pc(this, new PropertyChangedEventArgs(propName));
        }
    }

    protected bool SetProperty<T>(ref T field, T value, string propName)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(propName);
            return true;
        }

        return false;
    }

    protected bool SetProperty<T>(ref T field, T value, Expression<Func<T>> expr)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            var lambda = (LambdaExpression)expr;
            MemberExpression memberExpr;

            if (lambda.Body is UnaryExpression)
            {
                var unaryExpr = (UnaryExpression)lambda.Body;
                memberExpr = (MemberExpression)unaryExpr.Operand;
            }
            else
            {
                memberExpr = (MemberExpression)lambda.Body;
            }

            OnPropertyChanged(memberExpr.Member.Name);
            return true;
        }

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

LoginRelayCommand

```<code>public class LoginRelayCommand : ICommand
{
    private Action<object> execute;
    private Func<object, bool> canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public LoginRelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return this.canExecute == null || this.canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        this.execute(parameter);
    }
}
</code>```

ViewModel

```<code>public class LoginWindowVM : ObservableObject
{
    private ICommand _submitLoginButton;

    private Textbox1 _textbox1Input;
    private Textbox2 _textbox2Input;

    public ICommand SubmitLoginButton
    {
        get
        {
            if(_submitLoginButton == null)
            {
                _submitLoginButton = new LoginRelayCommand(param => this.SubmitButton(), null);
            }

            return _submitLoginButton;
        }
    }

    public Textbox1 Textbox1Input
    {
        get { return _textbox1Input; }
        set { SetProperty(ref _textbox1Input, value, () => Textbox1Input); }
    }

    public Textbox2 Textbox2Input
    {
        get { return _textbox2Input; }
        set { SetProperty(ref _textbox2Input, value, () => Textbox2Input); }
    }

    public LoginWindowVM() : base()
    {
        _textbox1Input = new Textbox1();
        _textbox2Input = new Textbox2();
    }

    private void SubmitButton()
    {
        MySqlConnection dbConnectionString = new MySqlConnection(@"datasource=localhost;port=3306;Initial Catalog='optest1a1';username=root;password=");
        try
        {
            if (dbConnectionString.State == System.Data.ConnectionState.Closed)
                dbConnectionString.Open();
            String query = "SELECT COUNT(1) FROM users_sw WHERE Username=@Username AND Password=@Password";
            MySqlCommand cmd = new MySqlCommand(query, dbConnectionString);
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Parameters.AddWithValue("@Username", Textbox1Input);
            cmd.Parameters.AddWithValue("@Password", Textbox2Input);
            int count = Convert.ToInt32(cmd.ExecuteScalar());
            if (count == 1)
            {
                WindowMain dashboard = new WindowMain();
                dashboard.Show();
                dbConnectionString.Close();
            }
            else
            {
                MessageBox.Show("Username or Password Is Incorrect");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            dbConnectionString.Close();
        }
    }
}
</code>```

View

```<code>    <Grid>
    <Label x:Name="lblUsername" Content="Username" HorizontalAlignment="Left" Margin="45,57,0,0" VerticalAlignment="Top"/>
    <Label x:Name="lblPassword" Content="Password" HorizontalAlignment="Left" Margin="48,104,0,0" VerticalAlignment="Top"/>
    <TextBox x:Name="txtUsername" Text="{Binding Textbox1Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,60,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="txtPassword" Text="{Binding Textbox2Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,108,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Button x:Name="btnSubmit" Content="Submit" HorizontalAlignment="Left" Margin="118,175,0,0" VerticalAlignment="Top" Width="75"
            Command="{Binding SubmitLoginButton}"
            />
</Grid>
</code>```

View.cs

```<code>    public partial class LoginWindow : Window
{
    private LoginWindowVM _viewModel;

    public LoginWindow()
    {
        InitializeComponent();

        _viewModel = new LoginWindowVM();
        this.DataContext = _viewModel;
    }
}
</code>```

答:
You are Binding to TextBox Text property which expect string as a source and you are binding to Textbox itself.
just change it to String property:

```<code>private String_textbox1Input;

public String Textbox1Input
{
    get { return _textbox1Input; }
    set { SetProperty(ref _textbox1Input, value, () => Textbox1Input); }
}
</code>```

Note: Textbox default binding mode is TwoWay setting it explicitly is of no use

Title: WPF MVVM Login Credentials

Body:
I am new to WPF and MVVM and I am making headway in understanding. There is one issue that has me a bit confused. I have a Login Page with associated ViewModel to log into the application. But, every time I use credentials I know are correct, it comes back with the "Username Incorrect" MessageBox. It should open to the WindowMain window. Perhaps an issue with Textbox binding?  Any help would be greatly appreciated. Thank you!

ObservableObject

public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propName)
    {
        Debug.Assert(GetType().GetProperty(propName) != null);

        var pc = PropertyChanged;
        if (pc != null)
        {
            pc(this, new PropertyChangedEventArgs(propName));
        }
    }

    protected bool SetProperty<T>(ref T field, T value, string propName)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(propName);
            return true;
        }

        return false;
    }

    protected bool SetProperty<T>(ref T field, T value, Expression<Func<T>> expr)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            var lambda = (LambdaExpression)expr;
            MemberExpression memberExpr;

            if (lambda.Body is UnaryExpression)
            {
                var unaryExpr = (UnaryExpression)lambda.Body;
                memberExpr = (MemberExpression)unaryExpr.Operand;
            }
            else
            {
                memberExpr = (MemberExpression)lambda.Body;
            }

            OnPropertyChanged(memberExpr.Member.Name);
            return true;
        }

        return false;
    }
}

LoginRelayCommand

public class LoginRelayCommand : ICommand
{
    private Action<object> execute;
    private Func<object, bool> canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public LoginRelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return this.canExecute == null || this.canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        this.execute(parameter);
    }
}

ViewModel

public class LoginWindowVM : ObservableObject
{
    private ICommand _submitLoginButton;

    private Textbox1 _textbox1Input;
    private Textbox2 _textbox2Input;

    public ICommand SubmitLoginButton
    {
        get
        {
            if(_submitLoginButton == null)
            {
                _submitLoginButton = new LoginRelayCommand(param => this.SubmitButton(), null);
            }

            return _submitLoginButton;
        }
    }

    public Textbox1 Textbox1Input
    {
        get { return _textbox1Input; }
        set { SetProperty(ref _textbox1Input, value, () => Textbox1Input); }
    }

    public Textbox2 Textbox2Input
    {
        get { return _textbox2Input; }
        set { SetProperty(ref _textbox2Input, value, () => Textbox2Input); }
    }

    public LoginWindowVM() : base()
    {
        _textbox1Input = new Textbox1();
        _textbox2Input = new Textbox2();
    }

    private void SubmitButton()
    {
        MySqlConnection dbConnectionString = new MySqlConnection(@"datasource=localhost;port=3306;Initial Catalog='optest1a1';username=root;password=");
        try
        {
            if (dbConnectionString.State == System.Data.ConnectionState.Closed)
                dbConnectionString.Open();
            String query = "SELECT COUNT(1) FROM users_sw WHERE Username=@Username AND Password=@Password";
            MySqlCommand cmd = new MySqlCommand(query, dbConnectionString);
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Parameters.AddWithValue("@Username", Textbox1Input);
            cmd.Parameters.AddWithValue("@Password", Textbox2Input);
            int count = Convert.ToInt32(cmd.ExecuteScalar());
            if (count == 1)
            {
                WindowMain dashboard = new WindowMain();
                dashboard.Show();
                dbConnectionString.Close();
            }
            else
            {
                MessageBox.Show("Username or Password Is Incorrect");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            dbConnectionString.Close();
        }
    }
}

View

    <Grid>

    <TextBox x:Name="txtUsername" Text="{Binding Textbox1Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,60,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="txtPassword" Text="{Binding Textbox2Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,108,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Button x:Name="btnSubmit" Content="Submit" HorizontalAlignment="Left" Margin="118,175,0,0" VerticalAlignment="Top" Width="75"
            Command="{Binding SubmitLoginButton}"
            />
</Grid>

View.cs

    public partial class LoginWindow : Window
{
    private LoginWindowVM _viewModel;

    public LoginWindow()
    {
        InitializeComponent();

        _viewModel = new LoginWindowVM();
        this.DataContext = _viewModel;
    }
}

Body:
You are Binding to TextBox Text property which expect string as a source and you are binding to Textbox itself.
just change it to String property:

private String_textbox1Input;

public String Textbox1Input
{
    get { return _textbox1Input; }
    set { SetProperty(ref _textbox1Input, value, () => Textbox1Input); }
}

Note: Textbox default binding mode is TwoWay setting it explicitly is of no use


问:
Need a regular expression to match letter followed by number or capital
I need a regular expression that can replace the lowercase letter n with a newline, but only when it is followed by a digit 0-9 or a capital letter.

For example, the string:

Company Buildingn100 Prospect Way

Should convert into:

Company Building

 100 Prospect Way

I'm trying to sanitize this data in PHP, so the resulting expression needs to be compatible.

答:
Try this:

```<code>n(?=[\dA-Z])
</code>```

In PHP (working example):

```<code>$str = preg_replace("/n(?=[\dA-Z])/", "\n", $str);
</code>```

(?=...) is a positive lookahead - it checks what's after the n we matched, but doesn't match it, so the next character isn't replaced.

ContentLicense: CC BY-SA 2.5

Body:
Try this:

n(?=[\dA-Z])

In PHP (working example):

$str = preg_replace("/n(?=[\dA-Z])/", "\n", $str);

(?=...) is a positive lookahead - it checks what's after the n we matched, but doesn't match it, so the next character isn't replaced.


问:
Cannot remove the progress bar after the ajax call is completed
What am I doing wrong?

```<code>progressbar : function() {
    var $progress = $('<div>', {'class' : 'progress-bar', height : '2px'});
    var width = 0,
        load  = 0;
    $(document).on({
        ajaxSend : function(event, req, set) {
            $('body').append($progress);
            load = setInterval(function(e) {
                if (width > 100) {
                    clearInterval(load);
                }
                width++;
                $('.progress-bar').width(width + '%');
            }, 10);
        },
        ajaxComplete : function(){
            width = 0;
            clearInterval(load);
            $('body').remove('.progress-bar');
            //$('.progress-bar').fadeOut();
        }
    });
}
</code>```

The fadeOut function works but I cannot remove the .progress-bar from the DOM. I call the above function on window - load & click.

答:
```<code>$('body').remove('.progress-bar');
</code>```

<p>replace this with </p>

```<code>$('.progress-bar').remove();
</code>```

Body:
What am I doing wrong?

progressbar : function() {
    var $progress = $('
', {'class' : 'progress-bar', height : '2px'});
    var width = 0,
        load  = 0;
    $(document).on({
        ajaxSend : function(event, req, set) {
            $('body').append($progress);
            load = setInterval(function(e) {
                if (width > 100) {
                    clearInterval(load);
                }
                width++;
                $('.progress-bar').width(width + '%');
            }, 10);
        },
        ajaxComplete : function(){
            width = 0;
            clearInterval(load);
            $('body').remove('.progress-bar');
            //$('.progress-bar').fadeOut();
        }
    });
}

The fadeOut function works but I cannot remove the .progress-bar from the DOM. I call the above function on window - load & click.

Body:
$('body').remove('.progress-bar');

replace this with

$('.progress-bar').remove();


问:
How prevent user to change form input value from browser debug tools?
I would like to create a HTML form ,the user can input his name and submit, but the user does not fill in the name input, the system will not submit and show the error message in alert box.

Here is my code about form.php

```<code><form name="myForm" action="b.php" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit" onclick="return validateForm()">
</form>

<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
}
</script>
</code>```

and submit successful,the information will go to this page b.php
b.php

```<code>    <?php
echo $_POST[fname];
?>
</code>```

But When the user use browser debug tools(like chrome),They can change form input "name" "id" "class" .etc value, In this case, when the user change the form name value, the form can submit without fill in the name.

any idea to solve this problem.....or use javascript to Validation is not a good choice????? Thanks

enter image description here

答: Server side validation will handle this. Return the page back to the form if the input values is empty or anything. </p>

Body:
I would like to create a HTML form ,the user can input his name and submit, but the user does not fill in the name input, the system will not submit and show the error message in alert box.

Here is my code about form.php

<form name="myForm" action="b.php" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit" onclick="return validateForm()">
</form>

and submit successful,the information will go to this page b.php
b.php

    <?php
echo $_POST[fname];
?>

But When the user use browser debug tools(like chrome),They can change form input "name" "id" "class" .etc value, In this case, when the user change the form name value, the form can submit without fill in the name.

any idea to solve this problem.....or use javascript to Validation is not a good choice????? Thanks

enter image description here


问:
Sql Server: Creating a table with multiple foreign keys
I have to create a set of tables in SQL Server.

Those are:

BusCity: Traveling Cities

BusType: AC/Non AC

BusInformation: Information about Name, Traveling City, Bus Fare,etc (Add by the Admin)

BookingDetails: Storing Booking details after customer booked the travel.

BookedStatus:  Availability of Bus.

I have a problem in creating these tables.

Following is my DDL code:

Create Table Customer
(
CustomerId int primary key identity(100,1),
CustomerName varchar(100) not null,
CustomerEmail varchar(100) not null,
CustomerPassword varchar(50) not null,
CustomerPhone int not null,
)

Create Table BusCity
(
BusCityId varchar(10) primary key,
BusCityName varchar(100) not null unique
)

Create Table BusType
(
BusTypeId int identity(10,1) primary key,
BusTypes varchar(100) not null unique
)

Create Table BusInformation
(
BusInformationId varchar(10) primary key,
BusName varchar(100) not null unique,
BusNumOfSeats int not null,
BusFromCity varchar(10) not null,
BusToCity varchar(10) not null,
BusTravelPrice int not null,
BusTypeId int,
constraint Fk_BusInfo_BusType Foreign key(BusTypeId) references BusType(BusTypeId),
constraint Fk_BusInfo_BusFromCity Foreign key(BusFromCity) references BusCity(BusCityId),
constraint Fk_BusInfo_BusToCity Foreign key(BusToCity) references BusCity(BusCityId)
)

Create Table BookingDetails
(
BookingDetailsId int identity(2000,1) primary key,
CustomerId int,
BusInformationId varchar(10),
BookingDateofTravel Date,
BookingFromCity varchar(10) not null,
BookingToCity varchar(10) not null,
BookingNumOfSeats int not null,
BookingTravelPrice int not null,
constraint Fk_BookingDetails_BusInformation Foreign key(BusInformationId)references BusInformation(BusInformationId),
constraint Fk_BookingDetails_Customer Foreign key(CustomerId)references Customer(CustomerId),
constraint Fk_BusDetails_BusFromCity Foreign key(BookingFromCity) references BusCity(BusCityId),
constraint Fk_BusDetails_BusToCity Foreign key(BookingToCity) references BusCity(BusCityId)
)

Create Table BookedStatus
(
BookedStatusId int identity(3000,1) primary key,
AvailableSeats int not null,
BookedDate Date,
IsAvailable bit,
BusInformationId varchar(10),
constraint Fk_BookedStatus_BusInfo Foreign key(BusInformationId)references BusInformation(BusInformationId)
)
```

My issue is,

1.whether I mapped the table relationship properly between the tables.

2.Included multiple foreign key columns in a table(BusInformation, BookingDetails).

Please help me on the same.

Online Bus Ticket Booking

This project has two user roles - First is Admin and second are Customers. The project allows customers to book their travel tickets online.

Administrator

Administrator user of the website can add city information, bus information, bus routes (From City to To City), Bus details(bus information/Bus ticket price per city to city details), No of Seats per bus, Available seats per bus on booking date, Bus Available and Booked status.

Customer

Customers can search available buses for booking tickets by Bus Name/ Traveling City From and To / Date of traveling with one way or return and by price.

There needs to be a search feature that will list all available buses
and bus details.

For search and details, customers don't need to be logged in. Any
user can search and check for available bus and their routes.

But for booking, Customer needs to be logged in, Customer can
register to the web application for booking tickets .

After a customer is logged in, he or she can book a Bus Ticket by
entering number of seats they need, date of travel, and From City

and    To City.

No need for payment details for now.

Customer can register and book tickets. Admin can view all booked
information.

答:
I'm not sure you've given enough info to answer 1) - we don't know enough about the inter dependencies between your data from the statements given to comment on all the possible relationships

Foreign keys can be created when the column is specified in the create table:

```<code>CREATE TABLE BusBlah (
  BusID int PRIMARY KEY,
  StatusID int not null REFERENCES StatusesTable(StatusIDColumnInStatusesTable)
  ...
)
</code>```

Or they can be added after with an ALTER (this is the way SQL Management Studio does it)

```<code>ALTER TABLE BusBlah
ADD CONSTRAINT SomeConstraintName FOREIGN KEY (StatusID)
REFERENCES StatusesTable (StatusIDColumnToReference) ;
</code>```

Ultimately, if you want a perfect set of scripts, you can always design your tables visually, including relationships, in SQLServer management studio, and then ask it to script them and take a look at the results. If your query is in relation to an academic exercise, maybe don't hand in the scripts that SSMS made, as it'll be obvious they were machine prepped, - but you can use them as a base to check what you're doing

If it's not an academic exercise, I generally think that designing these things visually in SSMS is a better and guided way to do it. You can always script them as above if you're putting them into a database migration or other mechanism that sets up a new db from scratch programmatically

Body:
I have to create a set of tables in SQL Server.

Those are:

BusCity: Traveling Cities

BusType: AC/Non AC

BusInformation: Information about Name, Traveling City, Bus Fare,etc (Add by the Admin)

BookingDetails: Storing Booking details after customer booked the travel.

BookedStatus:  Availability of Bus.

I have a problem in creating these tables.

Following is my DDL code:

Create Table Customer
(
CustomerId int primary key identity(100,1),
CustomerName varchar(100) not null,
CustomerEmail varchar(100) not null,
CustomerPassword varchar(50) not null,
CustomerPhone int not null,
)

Create Table BusCity
(
BusCityId varchar(10) primary key,
BusCityName varchar(100) not null unique
)

Create Table BusType
(
BusTypeId int identity(10,1) primary key,
BusTypes varchar(100) not null unique
)

Create Table BusInformation
(
BusInformationId varchar(10) primary key,
BusName varchar(100) not null unique,
BusNumOfSeats int not null,
BusFromCity varchar(10) not null,
BusToCity varchar(10) not null,
BusTravelPrice int not null,
BusTypeId int,
constraint Fk_BusInfo_BusType Foreign key(BusTypeId) references BusType(BusTypeId),
constraint Fk_BusInfo_BusFromCity Foreign key(BusFromCity) references BusCity(BusCityId),
constraint Fk_BusInfo_BusToCity Foreign key(BusToCity) references BusCity(BusCityId)
)

Create Table BookingDetails
(
BookingDetailsId int identity(2000,1) primary key,
CustomerId int,
BusInformationId varchar(10),
BookingDateofTravel Date,
BookingFromCity varchar(10) not null,
BookingToCity varchar(10) not null,
BookingNumOfSeats int not null,
BookingTravelPrice int not null,
constraint Fk_BookingDetails_BusInformation Foreign key(BusInformationId)references BusInformation(BusInformationId),
constraint Fk_BookingDetails_Customer Foreign key(CustomerId)references Customer(CustomerId),
constraint Fk_BusDetails_BusFromCity Foreign key(BookingFromCity) references BusCity(BusCityId),
constraint Fk_BusDetails_BusToCity Foreign key(BookingToCity) references BusCity(BusCityId)
)

Create Table BookedStatus
(
BookedStatusId int identity(3000,1) primary key,
AvailableSeats int not null,
BookedDate Date,
IsAvailable bit,
BusInformationId varchar(10),
constraint Fk_BookedStatus_BusInfo Foreign key(BusInformationId)references BusInformation(BusInformationId)
)

My issue is,

1.whether I mapped the table relationship properly between the tables.

2.Included multiple foreign key columns in a table(BusInformation, BookingDetails).

Please help me on the same.

Online Bus Ticket Booking

This project has two user roles - First is Admin and second are Customers. The project allows customers to book their travel tickets online.

Administrator

Administrator user of the website can add city information, bus information, bus routes (From City to To City), Bus details(bus information/Bus ticket price per city to city details), No of Seats per bus, Available seats per bus on booking date, Bus Available and Booked status.

Customer

Customers can search available buses for booking tickets by Bus Name/ Traveling City From and To / Date of traveling with one way or return and by price.

There needs to be a search feature that will list all available buses
and bus details.

For search and details, customers don't need to be logged in. Any
user can search and check for available bus and their routes.

But for booking, Customer needs to be logged in, Customer can
register to the web application for booking tickets .

After a customer is logged in, he or she can book a Bus Ticket by
entering number of seats they need, date of travel, and From City

and    To City.

No need for payment details for now.

Customer can register and book tickets. Admin can view all booked
information.

Body:
I'm not sure you've given enough info to answer 1) - we don't know enough about the inter dependencies between your data from the statements given to comment on all the possible relationships

Foreign keys can be created when the column is specified in the create table:

CREATE TABLE BusBlah (
  BusID int PRIMARY KEY,
  StatusID int not null REFERENCES StatusesTable(StatusIDColumnInStatusesTable)
  ...
)

Or they can be added after with an ALTER (this is the way SQL Management Studio does it)

ALTER TABLE BusBlah
ADD CONSTRAINT SomeConstraintName FOREIGN KEY (StatusID)
REFERENCES StatusesTable (StatusIDColumnToReference) ;

Ultimately, if you want a perfect set of scripts, you can always design your tables visually, including relationships, in SQLServer management studio, and then ask it to script them and take a look at the results. If your query is in relation to an academic exercise, maybe don't hand in the scripts that SSMS made, as it'll be obvious they were machine prepped, - but you can use them as a base to check what you're doing

If it's not an academic exercise, I generally think that designing these things visually in SSMS is a better and guided way to do it. You can always script them as above if you're putting them into a database migration or other mechanism that sets up a new db from scratch programmatically


问:
How can I fill gaps in a binary image in OpenCV?
I have some thresholded images of hand-drawn figures (circuits) but there are some parts where I need to have gaps closed between two points, as I show in the following image:

Binary image

I tried closing (dilation followed by erosion), but it is not working. It doesn't fill the gaps and makes the resistors and other components unrecognizable. I couldn't find a proper value for the morph size and number of iterations that give me a good result without affecting the rest of the picture. It's important not to affect too much the components.
I can't use hough lines because the gaps are not always in lines.

Result after closing:

Result after closing

```<code>int morph_size1 = 2;
Mat element1 = getStructuringElement(MORPH_RECT, Size(2 * morph_size1 + 1, 2 * morph_size1 + 1), Point(morph_size1, morph_size1));
Mat dst1; // result matrix
for (int i = 1; i<3; i++)
{
    morphologyEx(binary, dst1, CV_MOP_CLOSE, element1, Point(-1, -1), i);

}

imshow("closing ", dst1);
</code>```

Any idea?
Thanks in advance.

答:
My suggestion is to use a custom convolution filter (cv::filter2D) like the one below (can be larger):

```<code>0 0 1/12 0 0
0 0 2/12 0 0
1/12 2/12 0 2/12 1/12
0 0 2/12 0 0
0 0 1/12 0 0
</code>```

The idea is to fill gaps when there are two line segments near each other. You can also use custom structuring elements to obtain the same effect.

Body:
I have some thresholded images of hand-drawn figures (circuits) but there are some parts where I need to have gaps closed between two points, as I show in the following image:

Binary image

I tried closing (dilation followed by erosion), but it is not working. It doesn't fill the gaps and makes the resistors and other components unrecognizable. I couldn't find a proper value for the morph size and number of iterations that give me a good result without affecting the rest of the picture. It's important not to affect too much the components.
I can't use hough lines because the gaps are not always in lines.

Result after closing:

Result after closing

int morph_size1 = 2;
Mat element1 = getStructuringElement(MORPH_RECT, Size(2 * morph_size1 + 1, 2 * morph_size1 + 1), Point(morph_size1, morph_size1));
Mat dst1; // result matrix
for (int i = 1; i<3; i++)
{
    morphologyEx(binary, dst1, CV_MOP_CLOSE, element1, Point(-1, -1), i);

}

imshow("closing ", dst1);

Any idea?
Thanks in advance.

Body:
My suggestion is to use a custom convolution filter (cv::filter2D) like the one below (can be larger):

0 0 1/12 0 0
0 0 2/12 0 0
1/12 2/12 0 2/12 1/12
0 0 2/12 0 0
0 0 1/12 0 0

The idea is to fill gaps when there are two line segments near each other. You can also use custom structuring elements to obtain the same effect.


问:
Where does Gradle store downloaded jars on the local file system
How does Gradle store downloaded jar files on the local file system? Maven stores them in the .m2 directory under USER_HOME, but where does Gradle store them? I checked the .gradle folder there, but saw only compiled scripts.

答:
In Windows 10 PC, it is saved at:</p>
```<code>C:\Users\%USERNAME%\.gradle\caches\modules-2\files-2.1\
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Windows 10 PC, it is saved at:

C:\Users\%USERNAME%\.gradle\caches\modules-2\files-2.1\


问:
Firefox Bug?: Getting more content generated & list items
It seems like with html like

```<code><ul id="projectsList" class="list-style-1">
  <li>
    <a href="/projects/view/1">
      <p class="heading">New Project 1</p>
      <p class="desc">by <strong>jiewmeng</strong></p>
      <ul class="meta">
        <li>Your progress <strong>0%</strong></li>
        <li>Project's Progress <strong>0%</strong></li>
        <li>Your tasks due today <strong>0</strong></li>
      </ul>
    </a>
  </li>
</ul>
</code>```

firefox adds markup to make it

```<code><ul class="list-style-1" id="projectsList">
  <li>
    <a href="/projects/view/1"></a>
    <p class="heading"><a href="/projects/view/1">New Project 1</a></p>
    <a href="/projects/view/1"></a>
    <p class="desc"><a href="/projects/view/1">by <strong>jiewmeng</strong></a></p>
    <a href="/projects/view/1"></a>
    <ul class="meta">
      <a href="/projects/view/1"></a>
      <li><a href="/projects/view/1">Your progress <strong>0%</strong></a></li>
      <a href="/projects/view/1"></a>
      <li><a href="/projects/view/1">Project's Progress <strong>0%</strong></a></li>
      <a href="/projects/view/1"></a>
      <li><a href="/projects/view/1">Your tasks due today <strong>0</strong></a></li>
      <a href="/projects/view/1"></a>
    </ul>
    <a href="/projects/view/1"></a>
  </li>
</ul>
</code>```

I narrowed the problem to the meta list items if I comment out the meta list, it works http://jsfiddle.net/MSegC/2/

I want to use the  as a block level element as I want the user to be able to click the whole box to enter the link

答:
A is not a block level element in html (at least in html 4) so the short story is you can't use it like this :). That's why FF breaks' it for you.

http://htmlhelp.com/reference/html40/block.html

You should do what you want with an onclick event on the containing block.

Another option seems to be to force the doctype of the page to be html5 since in html5 it is possible for a to be a block level element.

http://davidwalsh.name/html5-elements-links

Body:
It seems like with html like

New Project 1

by jiewmeng

Your progress 0%

Project's Progress 0%

Your tasks due today 0

firefox adds markup to make it

New Project 1

by jiewmeng

Your progress 0%

Project's Progress 0%

Your tasks due today 0

I narrowed the problem to the meta list items if I comment out the meta list, it works http://jsfiddle.net/MSegC/2/

I want to use the  as a block level element as I want the user to be able to click the whole box to enter the link


答: You have to use $('.progress-bar').remove()

Title: Cannot remove the progress bar after the ajax call is completed


问:
pyldap AD authentication bind_s vs simple_bind_s
I am using pyldap to connect to AD server
pyldap is providing two functions bind_s() and simple_bind_s()
can any one explain me when to use bind_s() and simple_bind_s() and which one is best.</p>

答:
simple_bind_s() can do simple LDAP authentication or Kerberos authentication. However, bind_s() can only do LDAP authentication to form connection with Active Directory server.

I mostly prefer simple_bind_s() because we need both authentication support for applications but if you're sure you will never need to implement/use kerberos authentication in your application then feel free to pick bind_s().

Following is the implementations of respective bind definitions (Reference):

simple_bind_s():

```<code>  def simple_bind_s(self,who='',cred='',serverctrls=None,clientctrls=None):
    """
    simple_bind_s([who='' [,cred='']]) -> 4-tuple
    """
    msgid = self.simple_bind(who,cred,serverctrls,clientctrls)
    resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all=1,timeout=self.timeout)
    return resp_type, resp_data, resp_msgid, resp_ctrls
</code>```

bind_s():

```<code>  def bind_s(self,who,cred,method=ldap.AUTH_SIMPLE):
    """
    bind_s(who, cred, method) -> None
    """
    msgid = self.bind(who,cred,method)
    return self.result(msgid,all=1,timeout=self.timeout)
</code>```

Body:
simple_bind_s() can do simple LDAP authentication or Kerberos authentication. However, bind_s() can only do LDAP authentication to form connection with Active Directory server.

I mostly prefer simple_bind_s() because we need both authentication support for applications but if you're sure you will never need to implement/use kerberos authentication in your application then feel free to pick bind_s().

Following is the implementations of respective bind definitions (Reference):

simple_bind_s():

  def simple_bind_s(self,who='',cred='',serverctrls=None,clientctrls=None):
    """
    simple_bind_s([who='' [,cred='']]) -> 4-tuple
    """
    msgid = self.simple_bind(who,cred,serverctrls,clientctrls)
    resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all=1,timeout=self.timeout)
    return resp_type, resp_data, resp_msgid, resp_ctrls

bind_s():

  def bind_s(self,who,cred,method=ldap.AUTH_SIMPLE):
    """
    bind_s(who, cred, method) -> None
    """
    msgid = self.bind(who,cred,method)
    return self.result(msgid,all=1,timeout=self.timeout)


问:
Input set of string from user in c#
I am new in c#.So please help.

The first line of input has a unique integer N that indicates the number of sets of strings, each set may contain between 1 and 50 inclusive elements, and each of the strings of the set may contain between 1 and 50 inclusive characters.

How i take input from user above this condition??

example:

enter integer number:3

My dream is big

I want to go school

You are so sweet

答:
Here's what you need to do.

Split the string into array.

Sort the array using an IComparer that compares the length of each string in the array

Join the string array into a single string

See this function below:

```<code>public static string SortStringByLength(string input, Order order) {
    string[] words = input.Split(' ');
    if (order == Order.ASC)
        Array.Sort(words, (x, y) => x.Length.CompareTo(y.Length));
    else
        Array.Sort(words, (x, y) => y.Length.CompareTo(x.Length));

    return string.Join(" ", words);
}
</code>```

And here's a demo to see it in action.

Title: Input set of string from user in c#

Body:
Here's what you need to do.

Split the string into array.

Sort the array using an IComparer that compares the length of each string in the array

Join the string array into a single string

See this function below:

public static string SortStringByLength(string input, Order order) {
    string[] words = input.Split(' ');
    if (order == Order.ASC)
        Array.Sort(words, (x, y) => x.Length.CompareTo(y.Length));
    else
        Array.Sort(words, (x, y) => y.Length.CompareTo(x.Length));

    return string.Join(" ", words);
}

And here's a demo to see it in action.


问:
PL SQL how to select all columns
How do i make the following wrapper select all columns "*" instead of just if_type, and number_infected?

```<code>--spec
create or replace package WrapperSample is

  type TResultRow is record(
     if_type         codes.cd%type
    ,number_infected Integer);

  type TResultRowList is table of TResultRow;

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined;

end WrapperSample;
/

--body
create or replace package body WrapperSample is

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined is
    v_refcur   eOdatatypes_package.eOrefcur;
    currentRow TResultRow;
  begin
    v_refcur := YourSchema.getADedIcWarningsProv(p_hos_id, p_date);

    loop
      fetch v_refcur
        INTO currentRow;
      exit when v_refcur%NotFound;
      pipe row(currentRow);
    end loop;

    close v_refcur;

    return;
  end;

end WrapperSample;
/
</code>```

答:
I am not sure if I do understand your question and requirement.

But if you're looking for a way to get a table's content, or a portion thereof, this is probably how you would approach it:

```<code>create table tq84_test_table (
  col_1 number,
  col_2 varchar2(10),
  col_3 date
);

insert into tq84_test_table values (1, 'one'  , sysdate);
insert into tq84_test_table values (2, 'two'  , sysdate+1);
insert into tq84_test_table values (3, 'three', sysdate-1);

create or replace package tq84_sss as

  type record_t is table of tq84_test_table%rowtype;

  function GetADedIcWarningsProv return record_t;

end;
/

create or replace package body tq84_sss as

  function GetADedIcWarningsProv return record_t
  is
      ret record_t;
  begin

      select * bulk collect into ret
      from tq84_test_table;

      return ret;

  end GetADedIcWarningsProv;

end;
/
</code>```

You would then later use this function like so:

```<code>declare

  table_content tq84_sss.record_t;

begin

  table_content := tq84_sss.GetADedIcWarningsProv;

  for i in 1 .. table_content.count loop

      dbms_output.put_line(table_content(i).col_1 || ' ' ||
                           table_content(i).col_2 || ' ' ||
                           table_content(i).col_3
                          );

  end loop;

end;
/
</code>```

Title: PL SQL how to select all columns

Body:
How do i make the following wrapper select all columns "*" instead of just if_type, and number_infected?

--spec
create or replace package WrapperSample is

  type TResultRow is record(
     if_type         codes.cd%type
    ,number_infected Integer);

  type TResultRowList is table of TResultRow;

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined;

end WrapperSample;
/

--body
create or replace package body WrapperSample is

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined is
    v_refcur   eOdatatypes_package.eOrefcur;
    currentRow TResultRow;
  begin
    v_refcur := YourSchema.getADedIcWarningsProv(p_hos_id, p_date);

    loop
      fetch v_refcur
        INTO currentRow;
      exit when v_refcur%NotFound;
      pipe row(currentRow);
    end loop;

    close v_refcur;

    return;
  end;

end WrapperSample;
/

Body:
I am not sure if I do understand your question and requirement.

But if you're looking for a way to get a table's content, or a portion thereof, this is probably how you would approach it:

create table tq84_test_table (
  col_1 number,
  col_2 varchar2(10),
  col_3 date
);

insert into tq84_test_table values (1, 'one'  , sysdate);
insert into tq84_test_table values (2, 'two'  , sysdate+1);
insert into tq84_test_table values (3, 'three', sysdate-1);

create or replace package tq84_sss as

  type record_t is table of tq84_test_table%rowtype;

  function GetADedIcWarningsProv return record_t;

end;
/

create or replace package body tq84_sss as

  function GetADedIcWarningsProv return record_t
  is
      ret record_t;
  begin

      select * bulk collect into ret
      from tq84_test_table;

      return ret;

  end GetADedIcWarningsProv;

end;
/

You would then later use this function like so:

declare

  table_content tq84_sss.record_t;

begin

  table_content := tq84_sss.GetADedIcWarningsProv;

  for i in 1 .. table_content.count loop

      dbms_output.put_line(table_content(i).col_1 || ' ' ||
                           table_content(i).col_2 || ' ' ||
                           table_content(i).col_3
                          );

  end loop;

end;
/


问:
Node JS request blocking other requests
I have created Node JS app, i am explicitly downloading more than 100000 records from database. While the request is in proceeding, i try to login in the same application from another browser it wont respond unless the previous request is completed. Any idea ? Anything to do with event loop or threads ??
So here is my logic.
I make a get request to my API in Step 1, API calls database layer in Step 2. Database is returning only 21 records, i am explicitly looping 100000*21 to make heavy rendering just to test the load on json2csv. While doing so, the other requests to server will not respond until the last processing completes.</p>

```<code>Step 1:

router.get('/report/downloadOverdueTrainings/:criteria', function (req, res, next) {
        var overDueTrainings = [];
        var reportManager = new ReportManager();
        var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
        result.then(function (result) {
            var fields = ['Over Due Trainings'];
            for (var i = 0; i < 100000; i++) { //Testing purpose
                for (var training of result) {
                    overDueTrainings.push({
                        'Over Due Trainings': training.OverDueTrainings
                    })
                }
            }
            json2csv({
                data: overDueTrainings,
                fields: fields
            }, function (err, csv) {
                if (err)
                    throw err;
                res.setHeader('Content-disposition', 'attachment; filename=OverdueTrainings.csv');
                res.set('Content-Type', 'text/csv');
                res.send(csv);
            });
        }).catch(function (err) {
            next(err);
        });
    });

Step 2: Database Logic
var xtrDatabaseConnection =require('./xtrDatabaseConnection').XTRDatabaseConnection;
       ReportData.prototype.getOverdueTrainings = async function (params) {
        var connection = new xtrDatabaseConnection();
        var sequelize = connection.getSequelize();
        try {
            var query = "CALL report_getOverdueTrainings(:p_CourseCode,:p_Revision,:p_RevisionNo,:p_UserGroup,:p_Username,:p_Status,:p_SortColoumnNo,:p_SortColoumnDirection,:p_callType,:p_StartIndex,:p_PageSize)";
            var replacements = {
                p_CourseCode: params.CourseCode,
                p_Revision: params.Revision,
                p_RevisionNo: (params.RevisionNo == '' || params.RevisionNo == null) ? 0 : params.RevisionNo,
                p_UserGroup: params.UserGroup,
                p_Username: params.Username,
                p_Status: params.Status,
                p_SortColoumnNo: params.SortColoumnNo,
                p_SortColoumnDirection: params.SortColoumnDirection,
                p_callType: params.callType,
                p_StartIndex: params.startIndex,
                p_PageSize: params.pageSize
            };
            //console.log(replacements);
            return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);
        } catch (e) {
            throw (e);
        } finally {
            //To close connections
            sequelize.connectionManager.close().then(() => console.log('Connection Closed'));
        }
    }

XTRDatabaseConnection.prototype.executeQuerySequelize = function (sequelize, query, queryType, replacements) {
    return sequelize.authenticate()
        .then(() => {
            return sequelize.query(query, {
                replacements: replacements,
                type: queryType
            }).
            then(result => result)
                .catch(err => {
                    throw (err);
                });
        })
        .catch(err => {
            xtrUtility.logErrorsToWinstonTransports('Unable to connect to the database or some error occurred while executing your query. ', err);
            throw new AppError(err, "dbError", "Unable to connect to the database or some error occurred while executing your query.");
        });
}
</code>```

答: NodeJS is single-thread, single process. As long as a javascript function is running, nothing else can run. This is by design. The event loop will only kick in again once your functions have stopped executing.</p>

Title: Node JS request blocking other requests

Body:
I have created Node JS app, i am explicitly downloading more than 100000 records from database. While the request is in proceeding, i try to login in the same application from another browser it wont respond unless the previous request is completed. Any idea ? Anything to do with event loop or threads ??
So here is my logic.
I make a get request to my API in Step 1, API calls database layer in Step 2. Database is returning only 21 records, i am explicitly looping 100000*21 to make heavy rendering just to test the load on json2csv. While doing so, the other requests to server will not respond until the last processing completes.

Step 1:

router.get('/report/downloadOverdueTrainings/:criteria', function (req, res, next) {
        var overDueTrainings = [];
        var reportManager = new ReportManager();
        var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
        result.then(function (result) {
            var fields = ['Over Due Trainings'];
            for (var i = 0; i < 100000; i++) { //Testing purpose
                for (var training of result) {
                    overDueTrainings.push({
                        'Over Due Trainings': training.OverDueTrainings
                    })
                }
            }
            json2csv({
                data: overDueTrainings,
                fields: fields
            }, function (err, csv) {
                if (err)
                    throw err;
                res.setHeader('Content-disposition', 'attachment; filename=OverdueTrainings.csv');
                res.set('Content-Type', 'text/csv');
                res.send(csv);
            });
        }).catch(function (err) {
            next(err);
        });
    });

Step 2: Database Logic
var xtrDatabaseConnection =require('./xtrDatabaseConnection').XTRDatabaseConnection;
       ReportData.prototype.getOverdueTrainings = async function (params) {
        var connection = new xtrDatabaseConnection();
        var sequelize = connection.getSequelize();
        try {
            var query = "CALL report_getOverdueTrainings(:p_CourseCode,:p_Revision,:p_RevisionNo,:p_UserGroup,:p_Username,:p_Status,:p_SortColoumnNo,:p_SortColoumnDirection,:p_callType,:p_StartIndex,:p_PageSize)";
            var replacements = {
                p_CourseCode: params.CourseCode,
                p_Revision: params.Revision,
                p_RevisionNo: (params.RevisionNo == '' || params.RevisionNo == null) ? 0 : params.RevisionNo,
                p_UserGroup: params.UserGroup,
                p_Username: params.Username,
                p_Status: params.Status,
                p_SortColoumnNo: params.SortColoumnNo,
                p_SortColoumnDirection: params.SortColoumnDirection,
                p_callType: params.callType,
                p_StartIndex: params.startIndex,
                p_PageSize: params.pageSize
            };
            //console.log(replacements);
            return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);
        } catch (e) {
            throw (e);
        } finally {
            //To close connections
            sequelize.connectionManager.close().then(() => console.log('Connection Closed'));
        }
    }

XTRDatabaseConnection.prototype.executeQuerySequelize = function (sequelize, query, queryType, replacements) {
    return sequelize.authenticate()
        .then(() => {
            return sequelize.query(query, {
                replacements: replacements,
                type: queryType
            }).
            then(result => result)
                .catch(err => {
                    throw (err);
                });
        })
        .catch(err => {
            xtrUtility.logErrorsToWinstonTransports('Unable to connect to the database or some error occurred while executing your query. ', err);
            throw new AppError(err, "dbError", "Unable to connect to the database or some error occurred while executing your query.");
        });
}


问:
Changing the curser into a custom one
I have found about the coreccursor.custom property but I could not figure out how to set a value to it</p>

答:
To start with the simplest (maybe it's enough), you can set up one of the predefined cursors, by picking one of the available options:

```<code>Window.Current.CoreWindow.PointerCursor =
     new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Hand, 0);
</code>```

.Hand is one of the several available.

For a very own custom cursor, you'd have to do a little more.
Check these references:
one and two.

Title: Changing the curser into a custom one

Body:
To start with the simplest (maybe it's enough), you can set up one of the predefined cursors, by picking one of the available options:

Window.Current.CoreWindow.PointerCursor =
     new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Hand, 0);

.Hand is one of the several available.

For a very own custom cursor, you'd have to do a little more.
Check these references:
one and two.


问:
Nextjs global api calls
I am developing react based web application using NEXT.js,. As specified in NEXT.js, documentation to fetch the data before page loads, i am putting required action dispatch code in getInitialProps of the specific page. but some data fetching calls(action dispatch) like fetching authenticated user's data will be common to all the pages, so is there any way to dispatch such actions from single place before page load.

Thanks!

答:
update, now you can use getServerSideProps and nextjs provides an easy way to get user cookie : How to use cookie inside `getServerSideProps` method in Next.js?

--------- old answer ---------

simple answer: use cookie, code refer https://github.com/nextjs-boilerplate/next.js-boilerplate https://github.com/nextjs-boilerplate/next-fetch

-- details --

I had the same question when I first adopt next.js, as it worked in react, people prefer use a token to tag authed user and fetch always run in front-end. But as next.js made ssr a build in feature, I tried and find auth by cookie is possible, and I start https://github.com/nextjs-boilerplate/next.js-boilerplate and split out a fetch based on cookie https://github.com/nextjs-boilerplate/next-fetch

-- how it works --

1.client side fetch:  use fetch option option.credentials = 'include' and option.headers.Cookie=document.cookie will patch cookie into your request. Bnd when fetch back result, this become wired, you cannot access cookie header, so you have to use another header and additional logic needed in backend logic like res.header('custom-set-cookie', res.getHeader('set-cookie'))

2.server side fetch: first you need the express request object, and get cookie like req.headers.cookie, then pack it into fetch request option. when fetch back, get cookie like r.headers._headers[cookieHeaderName] and pack into response res.header('set-cookie', setCookie)

then after you pack this transfer up, you can simply call a json api and cookie will automatically transfered. And if you don't need to change cookie through header (you can through js), you can ommit the extra handle like res.header('custom-set-cookie', res.getHeader('set-cookie')) in api

you can try my ssr login here http://nextjs.i18ntech.com/login

Title: Nextjs global api calls


问:
Searchkick: counting records in index
I can open a Rails console on the production server and do a search * and then count on my ElasticSearch db.

```<code>s = Sentence.search '*'
s.count

...5, 381587, 381590, 381597, 381600, 381602, 381604, 381618, 381632, 381637, 381640, 381642, 381645, 381648, 381670, 381678, 381679, 381686, 381693, 381698, 381712, 387518, 387519, 387535, 387541)
=> 1000
</code>```

There are two problems here

(1) It is paging at 1000. Where is this set and how can I ignore it for a total count of entries in the index?

(2) The search is bringing back a Rails ID not an ElasticSearch ID. Does this mean I am then doing a db call?

How can I get a count of entries directly from ElasticSearch via the Rails console with Searchkick?

答:
You can use the method total_count to get the full count regardless of pagination.

```<code>s = Sentence.search '*'
s.total_count
</code>```

(2) The search is bringing back a Rails ID not an ElasticSearch ID. Does this mean I am then doing a db call?

According to my understanding searchkick would create a elasticsearchid for each of your row in the table. Then, when you search it would search elasticsearch and bring the list of ids that match the search keyword and then, pull out all the records from the database based on the elasticsearchids returned.

Title: Searchkick: counting records in index

Body:
I can open a Rails console on the production server and do a search * and then count on my ElasticSearch db.

s = Sentence.search '*'
s.count

...5, 381587, 381590, 381597, 381600, 381602, 381604, 381618, 381632, 381637, 381640, 381642, 381645, 381648, 381670, 381678, 381679, 381686, 381693, 381698, 381712, 387518, 387519, 387535, 387541)
=> 1000

There are two problems here

(1) It is paging at 1000. Where is this set and how can I ignore it for a total count of entries in the index?

(2) The search is bringing back a Rails ID not an ElasticSearch ID. Does this mean I am then doing a db call?

How can I get a count of entries directly from ElasticSearch via the Rails console with Searchkick?

Body:
You can use the method total_count to get the full count regardless of pagination.

s = Sentence.search '*'
s.total_count

(2) The search is bringing back a Rails ID not an ElasticSearch ID. Does this mean I am then doing a db call?

According to my understanding searchkick would create a elasticsearchid for each of your row in the table. Then, when you search it would search elasticsearch and bring the list of ids that match the search keyword and then, pull out all the records from the database based on the elasticsearchids returned.


问:
Getting weights of features using scikit-learn Logistic Regression
I am a little new to this.
I am using a simple Logistic Regression Classifier in python scikit-learn. I have 4 features.
My code is

```<code>X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 42)
classifier = LogisticRegression(random_state = 0, C=100)
classifier.fit(X_train, y_train)
coef = classifier.coef_[0]
print (coef)

[-1.07091645 -0.07848958  0.66913624  0.43500273]
</code>```

I want to know what does the coef array signifies?

can we use these coef * features to rank?

Does this mean that the last two features are most important in classifying results?

答:
When you're doing simple logistic regression, you are trying to decide it Y is true/false, 1/0, yes/no … etc. Right?

You have these features X that presumable help you decide. The math behind basic logistic regression uses a sigmoid function (aka logistic function), which in Numpy/Python looks like:

```<code>y = 1/(1 + np.exp(-x) )
</code>```

The x in this case is the linear combination of your features and coef:

```<code>coeaf[0] + coef[1] * feature[0] + coef[2] * coef[1] # etc.
</code>```

As this increases the logistic function approaches 1 and as it decreases it approaches 0 asymptotically.

When you plug your coefficients and features into the logistic function it will spit out a number which is the probability that your sample will be true. How accurate it is depends on how well you modeled and fit the data. The goal of logistic regression is to find these coefficients that fit your data correctly and minimize error. Because the logistic function outputs probability, you can use it to rank least likely to most likely.

If you are using Numpy you can take a sample Xand your coefficients and plug them into the logistic equation with:

```<code>import numpy as np
X = np.array([1, .2 , .1, 1.5]) # one element from your data set
c = np.array([.5, .1, -.7, .2]) # the coefficients that (hopefully) minimize error
z = X @ c.T                     # matrix multiply - linear combination

y = 1/(1 + np.exp(-z)           # logistic function
</code>```

y will be the probability that your model thinks this sample X is true.

Body:
I am a little new to this.
I am using a simple Logistic Regression Classifier in python scikit-learn. I have 4 features.
My code is

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 42)
classifier = LogisticRegression(random_state = 0, C=100)
classifier.fit(X_train, y_train)
coef = classifier.coef_[0]
print (coef)

[-1.07091645 -0.07848958  0.66913624  0.43500273]

I want to know what does the coef array signifies?

can we use these coef * features to rank?

Does this mean that the last two features are most important in classifying results?

Body:
When you're doing simple logistic regression, you are trying to decide it Y is true/false, 1/0, yes/no … etc. Right?

You have these features X that presumable help you decide. The math behind basic logistic regression uses a sigmoid function (aka logistic function), which in Numpy/Python looks like:

y = 1/(1 + np.exp(-x) )

The x in this case is the linear combination of your features and coef:

coeaf[0] + coef[1] * feature[0] + coef[2] * coef[1] # etc.

As this increases the logistic function approaches 1 and as it decreases it approaches 0 asymptotically.

When you plug your coefficients and features into the logistic function it will spit out a number which is the probability that your sample will be true. How accurate it is depends on how well you modeled and fit the data. The goal of logistic regression is to find these coefficients that fit your data correctly and minimize error. Because the logistic function outputs probability, you can use it to rank least likely to most likely.

If you are using Numpy you can take a sample Xand your coefficients and plug them into the logistic equation with:

import numpy as np
X = np.array([1, .2 , .1, 1.5]) # one element from your data set
c = np.array([.5, .1, -.7, .2]) # the coefficients that (hopefully) minimize error
z = X @ c.T                     # matrix multiply - linear combination

y = 1/(1 + np.exp(-z)           # logistic function

y will be the probability that your model thinks this sample X is true.


问:
Failed to initialize TLS context
I have installed stunnel version stunnel-5.43.tar.gz on linux server. after assign certification path and stunnel.conf file, my stunnel is not able to start due to tlsversion .
see this is my stunnel.conf:

```<code>[abc]
client = yes cert = /usr/local/etc/stunnel/cert.pem key = /usr/local/etc/stunnel/key.pem CAfile = /usr/local/etc/stunnel/Cert.pem sslVersion = TLSv1.2 accept = 127.0.0.1:5001 connect = x.x.x.x:port
</code>```

I am getting this error while starting stunnel:

```<code>[root@test stunnel]# stunnel #Certification loaded here  >Loading certificate from file: /usr/local/etc/stunnel/cert.pem >Certificate loaded from file: /usr/local/etc/stunnel/cert.pem >Loading private key from file: /usr/local/etc/stunnel/key.pem >Insecure file permissions on /usr/local/etc/stunnel/key.pem >#Getting here >SSL_CTX_use_PrivateKey_file: B080074: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch >Service [abc]: Failed to initialize TLS context
</code>```

Service [abc]: Failed to initialize TLS context

答:
Make sure your private key file (/usr/local/etc/stunnel/key.pem) has permissions set to 600 with:

```<code>chmod 600 /usr/local/etc/stunnel/key.pem
</code>```

From the stunnel manual:

The stunnel.pem file contains your key (private data) and certificate (public data). In order for stunnel to start automatically without requiring a password, the key is created without a password. This means that anyone who can read this file can compromise your SSL security. This file must be readable only by root, or the user who runs stunnel.

Title: Failed to initialize TLS context

Body:
I have installed stunnel version stunnel-5.43.tar.gz on linux server. after assign certification path and stunnel.conf file, my stunnel is not able to start due to tlsversion .
see this is my stunnel.conf:

[abc]
client = yes cert = /usr/local/etc/stunnel/cert.pem key = /usr/local/etc/stunnel/key.pem CAfile = /usr/local/etc/stunnel/Cert.pem sslVersion = TLSv1.2 accept = 127.0.0.1:5001 connect = x.x.x.x:port

I am getting this error while starting stunnel:

[root@test stunnel]# stunnel #Certification loaded here  >Loading certificate from file: /usr/local/etc/stunnel/cert.pem >Certificate loaded from file: /usr/local/etc/stunnel/cert.pem >Loading private key from file: /usr/local/etc/stunnel/key.pem >Insecure file permissions on /usr/local/etc/stunnel/key.pem >#Getting here >SSL_CTX_use_PrivateKey_file: B080074: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch >Service [abc]: Failed to initialize TLS context

Service [abc]: Failed to initialize TLS context

Body:
Make sure your private key file (/usr/local/etc/stunnel/key.pem) has permissions set to 600 with:

chmod 600 /usr/local/etc/stunnel/key.pem

From the stunnel manual:

The stunnel.pem file contains your key (private data) and certificate (public data). In order for stunnel to start automatically without requiring a password, the key is created without a password. This means that anyone who can read this file can compromise your SSL security. This file must be readable only by root, or the user who runs stunnel.


答:
You are looking for the points that mark any location where the slope changes to or from zero or infinity. We do not not actually need to compute slopes anywhere: either yn - yn-1 == 0 and yn+1 - yn != 0, or vice versa, or the same for x.

We can take the diff of x. If one of two successive elements is zero, then the diff of the diff will be the diff or the negative diff at that point. So we just want to find and label all points where diff(x) == diff(diff(x)) and diff(x) != 0, properly adjusted for differences in size between the arrays of course. We also want all the points where the same is true for y.

In numpy terms, this is can be written as follows

```<code>def masks(vec):
    d = np.diff(vec)
    dd = np.diff(d)

    # Mask of locations where graph goes to vertical or horizontal, depending on vec
    to_mask = ((d[:-1] != 0) & (d[:-1] == -dd))
    # Mask of locations where graph comes from vertical or horizontal, depending on vec
    from_mask = ((d[1:] != 0) & (d[1:] == dd))
    return to_mask, from_mask

to_vert_mask, from_vert_mask = masks(time)
to_horiz_mask, from_horiz_mask = masks(volts)
</code>```

Keep in mind that the masks are computed on second order differences, so they are two elements shorter than the inputs. Elements in the masks correspond to elements in the input arrays with a one-element border on the leading and trailing edge (hence the index [1:-1] below). You can convert the mask to indices using np.nonzero or you can get the x- and y-values directly using the masks as indices:

```<code>def apply_mask(mask, x, y):
    return x[1:-1][mask], y[1:-1][mask]

to_vert_t, to_vert_v = apply_mask(to_vert_mask, time, volts)
from_vert_t, from_vert_v = apply_mask(from_vert_mask, time, volts)
to_horiz_t, to_horiz_v = apply_mask(to_horiz_mask, time, volts)
from_horiz_t, from_horiz_v = apply_mask(from_horiz_mask, time, volts)

plt.plot(time, volts, 'b-')
plt.plot(to_vert_t, to_vert_v, 'r^', label='Plot goes vertical')
plt.plot(from_vert_t, from_vert_v, 'kv', label='Plot stops being vertical')
plt.plot(to_horiz_t, to_horiz_v, 'r>', label='Plot goes horizontal')
plt.plot(from_horiz_t, from_horiz_v, 'k<', label='Plot stops being horizontal')
plt.legend()
plt.show()
</code>```

Here is the resulting plot:

Notice that because the classification is done separately, "Point A" is correctly identified as being both a spot where verticalness starts and horizontalness ends. The problem is that "Point E" does not appear to be resolvable as such according to these criteria. Zooming in shows that all of the proliferated points correctly identify horizontal line segments:

You could choose a "correct" version of "Point E" by discarding from_horiz completely, and only the last value from to_horiz:

```<code>to_horiz_t, to_horiz_v = apply_mask(to_horiz_mask, time, volts)
to_horiz_t, to_horiz_v = to_horiz_t[-1], to_horiz_v[-1]

plt.plot(time, volts, 'b-')
plt.plot(*apply_mask(to_vert_mask, time, volts), 'r^', label='Plot goes vertical')
plt.plot(*apply_mask(from_vert_mask, time, volts), 'kv', label='Plot stops being vertical')
plt.plot(to_horiz_t, to_horiz_v, 'r>', label='Plot goes horizontal')
plt.legend()
plt.show()
</code>```

I am using this as a showcase for the star expansion of the results of apply_mask. The resulting plot is:

This is pretty much exactly the plot you were looking for. Discarding from_horiz also makes "Point A" be identified only as a drop to vertical, which is nice.

As multiple values in to_horiz show, this method is very sensitive to noise within the data. Your data is quite smooth, but this approach is unlikely to ever work with raw unfiltered measurements.

Title: Find locations on a curve where the slope changes

Body:
I have data points of time and voltage that create the curve shown below.

The time data is

array([  0.10810811,   0.75675676,   1.62162162,   2.59459459,
         3.56756757,   4.21621622,   4.97297297,   4.97297297,
         4.97297297,   4.97297297,   4.97297297,   4.97297297,
         4.97297297,   4.97297297,   5.08108108,   5.18918919,
         5.2972973 ,   5.51351351,   5.72972973,   5.94594595,
         6.27027027,   6.59459459,   7.13513514,   7.67567568,
         8.32432432,   9.18918919,  10.05405405,  10.91891892,
        11.78378378,  12.64864865,  13.51351351,  14.37837838,
        15.35135135,  16.32432432,  17.08108108,  18.16216216,
        19.02702703,  20.        ,  20.        ,  20.        ,
        20.        ,  20.        ,  20.        ,  20.        ,
        20.10810811,  20.21621622,  20.43243243,  20.64864865,
        20.97297297,  21.40540541,  22.05405405,  22.91891892,
        23.78378378,  24.86486486,  25.83783784,  26.7027027 ,
        27.56756757,  28.54054054,  29.51351351,  30.48648649,
        31.56756757,  32.64864865,  33.62162162,  34.59459459,
        35.67567568,  36.64864865,  37.62162162,  38.59459459,
        39.67567568,  40.75675676,  41.83783784,  42.81081081,
        43.89189189,  44.97297297,  46.05405405,  47.02702703,
        48.10810811,  49.18918919,  50.27027027,  51.35135135,
        52.43243243,  53.51351351,  54.48648649,  55.56756757,
        56.75675676,  57.72972973,  58.81081081,  59.89189189])

and the volts data is

array([ 4.11041056,  4.11041056,  4.11041056,  4.11041056,  4.11041056,
        4.11041056,  4.11041056,  4.10454545,  4.09794721,  4.09208211,
        4.08621701,  4.07961877,  4.07228739,  4.06568915,  4.05909091,
        4.05175953,  4.04516129,  4.03782991,  4.03123167,  4.02463343,
        4.01803519,  4.01217009,  4.00557185,  3.99970674,  3.99384164,
        3.98797654,  3.98284457,  3.97771261,  3.97331378,  3.96891496,
        3.96451613,  3.96085044,  3.95645161,  3.95205279,  3.9483871 ,
        3.94398827,  3.94032258,  3.93665689,  3.94325513,  3.94985337,
        3.95645161,  3.96378299,  3.97038123,  3.97624633,  3.98284457,
        3.98944282,  3.99604106,  4.0026393 ,  4.00923754,  4.01510264,
        4.02096774,  4.02609971,  4.02903226,  4.03196481,  4.03416422,
        4.0356305 ,  4.03709677,  4.03856305,  4.03929619,  4.04002933,
        4.04076246,  4.04222874,  4.04296188,  4.04296188,  4.04369501,
        4.04442815,  4.04516129,  4.04516129,  4.04589443,  4.04589443,
        4.04662757,  4.04662757,  4.0473607 ,  4.0473607 ,  4.04809384,
        4.04809384,  4.04809384,  4.04882698,  4.04882698,  4.04882698,
        4.04956012,  4.04956012,  4.04956012,  4.04956012,  4.05029326,
        4.05029326,  4.05029326,  4.05029326])

I would like to determine the location of the points labeled A, B, C, D, and E. Point A is the first location where the slope goes from zero to undefined. Point B is the location where the line is no longer vertical. Point C is the minimum of the curve. Point D is where the curve is no longer vertical. Point E is where the slope is close to zero again. The Python code below determines the locations for points A and C.

tdiff = np.diff(time)
vdiff = np.diff(volts)

# point A
idxA = np.where(vdiff < 0)[0][0]
timeA = time[idxA]
voltA = volts[idxA]

# point C
idxC = volts.idxmin()
timeC = time[idxC]
voltC = volts[idxC]

How can I determine the other locations on the curve represented by points B, D, and E?

Body:
You are looking for the points that mark any location where the slope changes to or from zero or infinity. We do not not actually need to compute slopes anywhere: either yn - yn-1 == 0 and yn+1 - yn != 0, or vice versa, or the same for x.

We can take the diff of x. If one of two successive elements is zero, then the diff of the diff will be the diff or the negative diff at that point. So we just want to find and label all points where diff(x) == diff(diff(x)) and diff(x) != 0, properly adjusted for differences in size between the arrays of course. We also want all the points where the same is true for y.

In numpy terms, this is can be written as follows

def masks(vec):
    d = np.diff(vec)
    dd = np.diff(d)

    # Mask of locations where graph goes to vertical or horizontal, depending on vec
    to_mask = ((d[:-1] != 0) & (d[:-1] == -dd))
    # Mask of locations where graph comes from vertical or horizontal, depending on vec
    from_mask = ((d[1:] != 0) & (d[1:] == dd))
    return to_mask, from_mask

to_vert_mask, from_vert_mask = masks(time)
to_horiz_mask, from_horiz_mask = masks(volts)

Keep in mind that the masks are computed on second order differences, so they are two elements shorter than the inputs. Elements in the masks correspond to elements in the input arrays with a one-element border on the leading and trailing edge (hence the index [1:-1] below). You can convert the mask to indices using np.nonzero or you can get the x- and y-values directly using the masks as indices:

def apply_mask(mask, x, y):
    return x[1:-1][mask], y[1:-1][mask]

to_vert_t, to_vert_v = apply_mask(to_vert_mask, time, volts)
from_vert_t, from_vert_v = apply_mask(from_vert_mask, time, volts)
to_horiz_t, to_horiz_v = apply_mask(to_horiz_mask, time, volts)
from_horiz_t, from_horiz_v = apply_mask(from_horiz_mask, time, volts)

plt.plot(time, volts, 'b-')
plt.plot(to_vert_t, to_vert_v, 'r^', label='Plot goes vertical')
plt.plot(from_vert_t, from_vert_v, 'kv', label='Plot stops being vertical')
plt.plot(to_horiz_t, to_horiz_v, 'r>', label='Plot goes horizontal')
plt.plot(from_horiz_t, from_horiz_v, 'k<', label='Plot stops being horizontal')
plt.legend()
plt.show()

Here is the resulting plot:

Notice that because the classification is done separately, "Point A" is correctly identified as being both a spot where verticalness starts and horizontalness ends. The problem is that "Point E" does not appear to be resolvable as such according to these criteria. Zooming in shows that all of the proliferated points correctly identify horizontal line segments:

You could choose a "correct" version of "Point E" by discarding from_horiz completely, and only the last value from to_horiz:

to_horiz_t, to_horiz_v = apply_mask(to_horiz_mask, time, volts)
to_horiz_t, to_horiz_v = to_horiz_t[-1], to_horiz_v[-1]

plt.plot(time, volts, 'b-')
plt.plot(*apply_mask(to_vert_mask, time, volts), 'r^', label='Plot goes vertical')
plt.plot(*apply_mask(from_vert_mask, time, volts), 'kv', label='Plot stops being vertical')
plt.plot(to_horiz_t, to_horiz_v, 'r>', label='Plot goes horizontal')
plt.legend()
plt.show()

I am using this as a showcase for the star expansion of the results of apply_mask. The resulting plot is:

This is pretty much exactly the plot you were looking for. Discarding from_horiz also makes "Point A" be identified only as a drop to vertical, which is nice.

As multiple values in to_horiz show, this method is very sensitive to noise within the data. Your data is quite smooth, but this approach is unlikely to ever work with raw unfiltered measurements.


问:
How to draw checkbox or tick mark in GitHub Markdown table?
I am able to draw checkbox in Github README.md lists using

```<code>- [ ] (for unchecked checkbox)
- [x] (for checked checkbox)
</code>```

But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?

答: Edit the document or wiki page, and use the - [ ] and - [x] syntax to update your task list. Furthermore you can refer to this link.

Body:
I am able to draw checkbox in Github README.md lists using

- [ ] (for unchecked checkbox)
- [x] (for checked checkbox)

But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?


问:
ng serve and ng build is not working
I downloaded this github project . this is working fine when I am using NPM START. but when I am using ng serve or ng build this is not working.  this is giving the error:

error log

```<code>Versions of @angular/compiler-cli and typescript could not be
determined.The most common reason for this is a broken npm install.
Please make sure your package.json contains both
@angular/compiler-cli and typescript in devDependencies, then
delete node_modules and package-lock.json (if you have one)
and run npm install again.
</code>```

I tried npm install @angular/cli inside the project. ng serve still not working. what I am missing or doing wrong. here is my package.json

package.json

```<code>{
"name": "angular-seed",
"description": "An Angular2+PrimeNG+SystemJS seed project",
"private": true,
"scripts": {
  "start": "live-server"
},
"dependencies": {
  "@angular/common": "^2.0.0",
  "@angular/compiler": "^2.0.0",
  "@angular/core": "^2.0.0",
  "@angular/forms": "^2.0.0",
  "@angular/http": "^2.0.0",
  "@angular/platform-browser": "^2.0.0",
  "@angular/platform-browser-dynamic": "^2.0.0",
  "@angular/router": "^3.0.0",
  "core-js": "^2.4.0",
  "font-awesome": "^4.6.3",
  "ngx-bootstrap": "^1.7.1",
  "primeng": "^1.0.0-beta.17",
  "rxjs": "5.0.0-beta.12",
  "systemjs": "0.19.37",
  "zone.js": "0.6.21"
},
"devDependencies": {
  "@angular/cli": "^1.5.0",
  "live-server": "1.1.0",
  "typescript": "^2.0.0"
}
}
</code>```

答:
I don't see @angular/compiler-cli in your "devDependencies". Try

```<code>npm i --save-dev @angular/compiler-cli
</code>```

(Unfortunately, your angular versions are pretty old. The versions across all angular packages in an app have to be compatible. It's best just to put this line, "@angular/compiler-cli": "^2.0.0".)

You can remove @angular/cli from package.json. And, make sure you have globally installed angular cli. Try

```<code>ng --version
tsc --version
</code>```

to make sure you have the necessary tools installed.

Title: ng serve and ng build is not working

Body:
I downloaded this github project . this is working fine when I am using NPM START. but when I am using ng serve or ng build this is not working.  this is giving the error:

error log

Versions of @angular/compiler-cli and typescript could not be
determined.The most common reason for this is a broken npm install.
Please make sure your package.json contains both
@angular/compiler-cli and typescript in devDependencies, then
delete node_modules and package-lock.json (if you have one)
and run npm install again.

I tried npm install @angular/cli inside the project. ng serve still not working. what I am missing or doing wrong. here is my package.json

package.json

{
"name": "angular-seed",
"description": "An Angular2+PrimeNG+SystemJS seed project",
"private": true,
"scripts": {
  "start": "live-server"
},
"dependencies": {
  "@angular/common": "^2.0.0",
  "@angular/compiler": "^2.0.0",
  "@angular/core": "^2.0.0",
  "@angular/forms": "^2.0.0",
  "@angular/http": "^2.0.0",
  "@angular/platform-browser": "^2.0.0",
  "@angular/platform-browser-dynamic": "^2.0.0",
  "@angular/router": "^3.0.0",
  "core-js": "^2.4.0",
  "font-awesome": "^4.6.3",
  "ngx-bootstrap": "^1.7.1",
  "primeng": "^1.0.0-beta.17",
  "rxjs": "5.0.0-beta.12",
  "systemjs": "0.19.37",
  "zone.js": "0.6.21"
},
"devDependencies": {
  "@angular/cli": "^1.5.0",
  "live-server": "1.1.0",
  "typescript": "^2.0.0"
}
}

Body:
I don't see @angular/compiler-cli in your "devDependencies". Try

npm i --save-dev @angular/compiler-cli

(Unfortunately, your angular versions are pretty old. The versions across all angular packages in an app have to be compatible. It's best just to put this line, "@angular/compiler-cli": "^2.0.0".)

You can remove @angular/cli from package.json. And, make sure you have globally installed angular cli. Try

ng --version
tsc --version

to make sure you have the necessary tools installed.