问:
Programmatically Sort Data in Excel After Using Subtotal Function Using C#
I have data that I want to apply the subtotal function to and then sort the resulting data in descending order. So far I've managed to get my code to apply the subtotal function and then change the view so it only displays the column I want sorted. I cannot figure out how to use the .Sort method at this point to only sort the visible data.

My code to implement the subtotals:

```<code>xcel.Range range = excelWorksheet.UsedRange;
        range.Subtotal(1, Excel.XlConsolidationFunction.xlSum, Type.Missing, (object)true, (object)false, Excel.XlSummaryRow.xlSummaryBelow);
</code>```

My code to change the view to just the column I want sorted:

```<code>excelWorksheet.Outline.ShowLevels(2, Type.Missing);
</code>```

At this point I've tried many variations of the .Sort method using just about all the ranges I can think of (visible range, explicitly stating the column I want, the entire worksheet, the used range before the subtotal filter, the used range after the subtotal filter). I've also tried recording a macro inside Excel, but I cannot figure out how to convert that back to C#.

The Excel macro that does exactly that I need is:

```<code>Range("G3").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("G3"), _
    SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("A2:G2853")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
</code>```

Does anyone know how to sort the data after subtotal grouping has been applied?

答:
I had the same issue but I just took the Macro (very similar to yours) and I tried to match it against the Excel method Sort. The below worked for me:</p>

```<code>     range.Sort(Key1: range.Columns[8], Order1: ExcelM.XlSortOrder.xlDescending,
                Header: ExcelM.XlYesNoGuess.xlYes,MatchCase: false,
                Orientation: ExcelM.XlSortOrientation.xlSortColumns,
                SortMethod:ExcelM.XlSortMethod.xlPinYin
                );
</code>```

Body:
I have data that I want to apply the subtotal function to and then sort the resulting data in descending order. So far I've managed to get my code to apply the subtotal function and then change the view so it only displays the column I want sorted. I cannot figure out how to use the .Sort method at this point to only sort the visible data.

My code to implement the subtotals:

xcel.Range range = excelWorksheet.UsedRange;
        range.Subtotal(1, Excel.XlConsolidationFunction.xlSum, Type.Missing, (object)true, (object)false, Excel.XlSummaryRow.xlSummaryBelow);

My code to change the view to just the column I want sorted:

excelWorksheet.Outline.ShowLevels(2, Type.Missing);

At this point I've tried many variations of the .Sort method using just about all the ranges I can think of (visible range, explicitly stating the column I want, the entire worksheet, the used range before the subtotal filter, the used range after the subtotal filter). I've also tried recording a macro inside Excel, but I cannot figure out how to convert that back to C#.

The Excel macro that does exactly that I need is:

Range("G3").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("G3"), _
    SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("A2:G2853")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Does anyone know how to sort the data after subtotal grouping has been applied?

Body:
I had the same issue but I just took the Macro (very similar to yours) and I tried to match it against the Excel method Sort. The below worked for me:

     range.Sort(Key1: range.Columns[8], Order1: ExcelM.XlSortOrder.xlDescending,
                Header: ExcelM.XlYesNoGuess.xlYes,MatchCase: false,
                Orientation: ExcelM.XlSortOrientation.xlSortColumns,
                SortMethod:ExcelM.XlSortMethod.xlPinYin
                );


来源: stackexchange

问:
Click event triggered from parent page not working in IE
I am working with a filter on page to display different products. I am trying to make it so that when you click a button from an external page, it navigates to the product page and automatically clicks the "organics filter" checkbox and then displays the organic items. This code works in every browser except IE and EDGE. Any ideas what could be wrong? It appears to click the organics checkbox but it does not actually click the submit button for IE and EDGE.

**Update: It works if I put an alert after the window.load function. I think its a timing issue or something. Anyone have any suggestions?

```<code>//force organic filter if coming from organics article
    $(window).load(function(){
    var organicURL = document.referrer;
    if (organicURL === "http://www.sampleurl.com") {
       $('#organicFilter').trigger('click');
       if ($('#organicFilter').is(':checked')) {
          $('#submitFilter').trigger('click');
       }
    }
    });
</code>```

答:
I fixed it by adding this below:

```<code>$(window).load(function(){
var organicURL = document.referrer;
if (organicURL === "http://www.centowine.com/articles/2017/cento_organics.php") {
   $('#organicFilter').trigger('click');
   if ($('#organicFilter').is(':checked')) {
     setTimeout(function(){ $('#submitFilter').click()}, 500);
   }
}
});
</code>```

Just needed to add a timeout it was loading too soon. Before the document loaded.

ContentLicense: CC BY-SA 3.0

Body:
I am working with a filter on page to display different products. I am trying to make it so that when you click a button from an external page, it navigates to the product page and automatically clicks the "organics filter" checkbox and then displays the organic items. This code works in every browser except IE and EDGE. Any ideas what could be wrong? It appears to click the organics checkbox but it does not actually click the submit button for IE and EDGE.

**Update: It works if I put an alert after the window.load function. I think its a timing issue or something. Anyone have any suggestions?

//force organic filter if coming from organics article
    $(window).load(function(){
    var organicURL = document.referrer;
    if (organicURL === "http://www.sampleurl.com") {
       $('#organicFilter').trigger('click');
       if ($('#organicFilter').is(':checked')) {
          $('#submitFilter').trigger('click');
       }
    }
    });

Body:
I fixed it by adding this below:

$(window).load(function(){
var organicURL = document.referrer;
if (organicURL === "http://www.centowine.com/articles/2017/cento_organics.php") {
   $('#organicFilter').trigger('click');
   if ($('#organicFilter').is(':checked')) {
     setTimeout(function(){ $('#submitFilter').click()}, 500);
   }
}
});

Just needed to add a timeout it was loading too soon. Before the document loaded.


问:
VS2015 JavaScript intelliSense does not work
I just do not know how to adjust VS2015 JavaScript intelliSense.
I have durandal project and use some standard libraries, and syncfusion controls.
I tried with vs2015 update1, update2 and update3 and none of them work.

In root folder of my project I add Scripts/_references.js.
Since I am using require I add only those two lines of code in _references.js:

```<code>/// <autosync enabled="false" />
/// <reference path="../bower_components/requirejs/require.js" data-main="../app/main.js" start-page="../index.html" />
</code>```

I also tried to turn on auto sync and to update all files in _references.js, it did not help.
My college work on the same project and intelliSense work perfect in his VS2015.

When I open JavaScript Output tab, I see:

```<code>Referenced file '../../durandal/system.js' not found.
Referenced file '../../web/ej.togglebutton.js' not found.
Referenced file '../../knockout.js' not found.
</code>```

Seem it work to my college, file structure is ok, I just do not know what to do ?

答:
Does your project/solution is on another drive? I mean on a different drive of the VS installation. This problem has happened to me because my VS installation is on Drive "C", and my solution on Drive "D". In the JavaScript Language Service Output windows, I saw "Referenced file '../../../../project/scripts/main.js' not found.". When I move the project to the C Drive, everything is working as expected.

Also, here is my _reference.js file:

```<code>/// <autosync enabled="false" />
/// <reference path="require.js" data-main="main" />
</code>```

Finally, if I don't use modules naming with define, intellisense don't work.

Body:
I just do not know how to adjust VS2015 JavaScript intelliSense.
I have durandal project and use some standard libraries, and syncfusion controls.
I tried with vs2015 update1, update2 and update3 and none of them work.

In root folder of my project I add Scripts/_references.js.
Since I am using require I add only those two lines of code in _references.js:

/// <autosync enabled="false" />
/// <reference path="../bower_components/requirejs/require.js" data-main="../app/main.js" start-page="../index.html" />

I also tried to turn on auto sync and to update all files in _references.js, it did not help.
My college work on the same project and intelliSense work perfect in his VS2015.

When I open JavaScript Output tab, I see:

Referenced file '../../durandal/system.js' not found.
Referenced file '../../web/ej.togglebutton.js' not found.
Referenced file '../../knockout.js' not found.

Seem it work to my college, file structure is ok, I just do not know what to do ?

Body:
Does your project/solution is on another drive? I mean on a different drive of the VS installation. This problem has happened to me because my VS installation is on Drive "C", and my solution on Drive "D". In the JavaScript Language Service Output windows, I saw "Referenced file '../../../../project/scripts/main.js' not found.". When I move the project to the C Drive, everything is working as expected.

Also, here is my _reference.js file:

/// <autosync enabled="false" />
/// <reference path="require.js" data-main="main" />

Finally, if I don't use modules naming with define, intellisense don't work.


问:
Get coordinates of a particular section of the image
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

```<code><img src="image link here" usemap="#mapname">
    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>
</code>```

答: I use a chrome extension I got called Page Ruler. What I do is use the extension to draw a rectangle from the pixel with the coordinate 0,0 to a target pixel. The bar at the top shows the width and height of the rectangle.  There are also other tools, such as Meazure, which can do the same thing.</p>

Body:
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>


问:
Google Chrome developer tools disabled
My Google Chrome developer tools are disabled.  I'm not sure how it happened.  I was using them in the morning then went to use them in the afternoon and the F12 button wouldn't do anything.  Same with ctrl+shift+i.

If I navigate the 'Tools' menu, I can see the 'developer tools' link, but it is grayed out and disabled.  Does anyone have any idea how to re-enable them?  I uninstalled/re-installed chrome twice but no help.

答:
Found another issue with the Dev Tools not opening/ working

If the Block access to a list of URLs Enabled
and "file", "" is in it
or
file:// is not in the whitlist of url, the DEV Tools wont open either :)

Maybe that helps someone

ContentLicense: CC BY-SA 4.0

Title: Google Chrome developer tools disabled


问:
Skip validation for related objects - rails activerecord
```<code>class Author
  has_many :books

  validates :email, :presence => true
end

class Book
  belongs_to :author

  validates :title, :presence => true
end
</code>```

Skipping validations is easy:

```<code>a = Author.new
a.save(:validate => false)
</code>```

However, I need skip author validations when creating a book without skipping books validations, like this:

```<code>b = Book.new
b.title = "A Book"

b.author = Author.last
b.save
</code>```

答:
I quite did not understand your question. In your example you are not creating any new author object:

```<code>>     b = Book.new
>     b.title = "A Book"
>
>     b.author = Author.last
>     b.save
</code>```

If you are trying to create a new author without an email, can't you just do:

```<code>b = Book.new
b.title = "A Book"

author = Author.new
author.save(:validate => false)

b.author = author
b.save
</code>```

Hmm... maybe I'm just missing something obvious here.

ContentLicense: CC BY-SA 2.5

Body:
class Author
  has_many :books

  validates :email, :presence => true
end

class Book
  belongs_to :author

  validates :title, :presence => true
end

Skipping validations is easy:

a = Author.new
a.save(:validate => false)

However, I need skip author validations when creating a book without skipping books validations, like this:

b = Book.new
b.title = "A Book"

b.author = Author.last
b.save

Body:
I quite did not understand your question. In your example you are not creating any new author object:

>     b = Book.new
>     b.title = "A Book"
>
>     b.author = Author.last
>     b.save

If you are trying to create a new author without an email, can't you just do:

b = Book.new
b.title = "A Book"

author = Author.new
author.save(:validate => false)

b.author = author
b.save

Hmm... maybe I'm just missing something obvious here.


问:
Recoding floats in a list
I have a list of floats, which looks like this:

```<code>predictions_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7,...]
</code>```

I want to clean this data, by giving number higher than 10.0 a 10.0 and numbers lower than 0.0 (so all negative numbers) a 0.0. I'm doing this with the following if statement:

```<code>predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)
</code>```

This code seems to work, but the funny thing is that:

```<code>len(predictions_dec)
1222
len(predictions_clean)
1816
</code>```

My understanding of if statements is not that great. Where in the if statement am I doing something wrong?

答:
Your code will append something for any number that is greater than 10.0 twice.

```<code>predictions_clean = []
for pred in predictions_dec:
    if pred >= 10: #e.g. 12, we append 10.0
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:         #and now 12 is not less that 0, so append that
        predictions_clean.append(pred)
</code>```

You want elseif

```<code>predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    elif pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)
</code>```

You can manage this with a list comprehsenion

```<code>predictions_clean = [0.0 if x < 0 else (10 if x > 10 else x) for x in predictions_dec]
</code>```

Title: Recoding floats in a list

Body:
I have a list of floats, which looks like this:

predictions_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7,...]

I want to clean this data, by giving number higher than 10.0 a 10.0 and numbers lower than 0.0 (so all negative numbers) a 0.0. I'm doing this with the following if statement:

predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)

This code seems to work, but the funny thing is that:

len(predictions_dec)
1222
len(predictions_clean)
1816

My understanding of if statements is not that great. Where in the if statement am I doing something wrong?

Body:
Your code will append something for any number that is greater than 10.0 twice.

predictions_clean = []
for pred in predictions_dec:
    if pred >= 10: #e.g. 12, we append 10.0
        predictions_clean.append(10.0)
    if pred <= 0:
        predictions_clean.append(0.0)
    else:         #and now 12 is not less that 0, so append that
        predictions_clean.append(pred)

You want elseif

predictions_clean = []
for pred in predictions_dec:
    if pred >= 10:
        predictions_clean.append(10.0)
    elif pred <= 0:
        predictions_clean.append(0.0)
    else:
        predictions_clean.append(pred)

You can manage this with a list comprehsenion

predictions_clean = [0.0 if x < 0 else (10 if x > 10 else x) for x in predictions_dec]


问:
Cannot POST /user/register
I'm trying to learn MEAN stack with a tutorial and I'm sticking in some point when I tried to test post method with POSTMAN I've searched and tried many ways and can't find the answer yet.

Codes are : app.js

```<code>const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    passport = require('passport'),
    mongoose = require('mongoose');

const users = require('./routes/users'),
    config = require('./config/database');

//Connect to database
mongoose.connect(config.database);
//On Connection
mongoose.connection.on('connected', () => {
    console.log('Connected to database : ' + config.database);
});
//On Error
mongoose.connection.on('error', (err) => {
    console.log('Database error : ' + err);
});

const app = express();

//Port number
const port = 3000;

//Cors Middleware
app.use(cors());

app.use(express.static(path.join(__dirname, 'public')));

//Body Parser Middleware
app.use(bodyParser.json());

app.use('/users', users);

//Index route
app.get('/', (req, res) => {
    res.send('Invalid response');
});
app.post('/', (req, res) => {
    res.send('Invalid response');
})

//Start Server
app.listen(port, () => {
    console.log('Server stated with port : ' + port);
});
</code>```

Route code: users.js

```<code>const express = require('express'),
    passport = require('passport'),
    jwt = require('jsonwebtoken'),
    router = express.Router();

const User = require('../models/user');

//Register
router.post('/register', (req, res, next) => {
    let newUser = new User({
        name: req.body.name,
        email: req.body.email,
        username: req.body.username,
        passowrd: req.body.passowrd
    });

    User.addUser(newUser, (err, user) => {
        if (err) {
            res.json({ success: false, msg: 'Failed to register user!' });
        } else {
            res.json({ success: true, msg: 'User Registered' });
        }
    });
});

module.exports = router;
</code>```

Model code: user.js

```<code>const mongoose = require('mongoose'),
    bcrypt = require('bcryptjs'),
    config = require('../config/database');

//User Schema
const userSchema = mongoose.Schema({
    name: {
        type: String
    },
    email: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    passowrd: {
        type: String,
        required: true
    }
});

module.exports.addUser = function (newUser, callback) {
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.passowrd, salt, (err, hash) => {
            if (err) throw err;
            newUser.passowrd = hash;
            newUser.save(callback);
        });
    });
}

const User = module.exports = mongoose.model('User', userSchema);
</code>```

POSTMAN config :

Method : POST

URL
    http://localhost:3000/users/register

Header
    key: Content-Type ,
    value: application/json

```<code>Body
{
    "name": "Wai Lin Aung",
    "email": "wailinaung@mail.com",
    "username": "Wai Lin",
    "passowrd": "123456"
}
</code>```

POSTMAN output:

HTML
    ```Cannot POST /user/register```

JSON :
    Unexpected '<'

Terminal Log:

```<code>[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
/Users/wailin/Documents/Projects/meanauthapp/app.js:41
app.post('/', (req,res))
            ^

ReferenceError: req is not defined
    at Object.<anonymous> (/Users/wailin/Documents/Projects/meanauthapp/app.js:41:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3
</code>```

Updated Log:

```<code>[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server stated with port : 3000
Connected to database : mongodb://localhost:/27017/meanauth
TypeError: User.addUser is not a function
    at router.post (/Users/wailin/Documents/Projects/meanauthapp/routes/users.js:17:10)
    at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
    at /Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:174:3)
    at router (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:317:13)
    at /Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:275:10)
    at /Users/wailin/Documents/Projects/meanauthapp/node_modules/body-parser/lib/read.js:129:5
</code>```

答:
Your error below is in the app.js.

```<code>[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
/Users/wailin/Documents/Projects/meanauthapp/app.js:41
app.post('/', (req,res))
</code>```

AFAIK req, res are properties from express.Router(). But you just call this in your router-files but not in your app.js

Title: Cannot POST /user/register

Body:
I'm trying to learn MEAN stack with a tutorial and I'm sticking in some point when I tried to test post method with POSTMAN I've searched and tried many ways and can't find the answer yet.

Codes are : app.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    passport = require('passport'),
    mongoose = require('mongoose');

const users = require('./routes/users'),
    config = require('./config/database');

//Connect to database
mongoose.connect(config.database);
//On Connection
mongoose.connection.on('connected', () => {
    console.log('Connected to database : ' + config.database);
});
//On Error
mongoose.connection.on('error', (err) => {
    console.log('Database error : ' + err);
});

const app = express();

//Port number
const port = 3000;

//Cors Middleware
app.use(cors());

app.use(express.static(path.join(__dirname, 'public')));

//Body Parser Middleware
app.use(bodyParser.json());

app.use('/users', users);

//Index route
app.get('/', (req, res) => {
    res.send('Invalid response');
});
app.post('/', (req, res) => {
    res.send('Invalid response');
})

//Start Server
app.listen(port, () => {
    console.log('Server stated with port : ' + port);
});

Route code: users.js

const express = require('express'),
    passport = require('passport'),
    jwt = require('jsonwebtoken'),
    router = express.Router();

const User = require('../models/user');

//Register
router.post('/register', (req, res, next) => {
    let newUser = new User({
        name: req.body.name,
        email: req.body.email,
        username: req.body.username,
        passowrd: req.body.passowrd
    });

    User.addUser(newUser, (err, user) => {
        if (err) {
            res.json({ success: false, msg: 'Failed to register user!' });
        } else {
            res.json({ success: true, msg: 'User Registered' });
        }
    });
});

module.exports = router;

Model code: user.js

const mongoose = require('mongoose'),
    bcrypt = require('bcryptjs'),
    config = require('../config/database');

//User Schema
const userSchema = mongoose.Schema({
    name: {
        type: String
    },
    email: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    passowrd: {
        type: String,
        required: true
    }
});

module.exports.addUser = function (newUser, callback) {
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.passowrd, salt, (err, hash) => {
            if (err) throw err;
            newUser.passowrd = hash;
            newUser.save(callback);
        });
    });
}

const User = module.exports = mongoose.model('User', userSchema);

POSTMAN config :

Method : POST

URL
    http://localhost:3000/users/register

Header
    key: Content-Type ,
    value: application/json

Body
{
    "name": "Wai Lin Aung",
    "email": "wailinaung@mail.com",
    "username": "Wai Lin",
    "passowrd": "123456"
}

POSTMAN output:

HTML

Cannot POST /user/register

JSON :
    Unexpected '<'

Terminal Log:

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
/Users/wailin/Documents/Projects/meanauthapp/app.js:41
app.post('/', (req,res))
            ^

ReferenceError: req is not defined
    at Object.<anonymous> (/Users/wailin/Documents/Projects/meanauthapp/app.js:41:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3

Updated Log:

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server stated with port : 3000
Connected to database : mongodb://localhost:/27017/meanauth
TypeError: User.addUser is not a function
    at router.post (/Users/wailin/Documents/Projects/meanauthapp/routes/users.js:17:10)
    at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
    at /Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:174:3)
    at router (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:317:13)
    at /Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/wailin/Documents/Projects/meanauthapp/node_modules/express/lib/router/index.js:275:10)
    at /Users/wailin/Documents/Projects/meanauthapp/node_modules/body-parser/lib/read.js:129:5

Body:
Your error below is in the app.js.

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
/Users/wailin/Documents/Projects/meanauthapp/app.js:41
app.post('/', (req,res))

AFAIK req, res are properties from express.Router(). But you just call this in your router-files but not in your app.js


问:
Get a reference to currently active dataSource in Spring Boot
I want to implement db data init via DataSourceInitializer.

I have these as methods just below my Spring Boot main method, but it seems that it doesn't get executed at all (I tried with intentional removal of characters just to trigger an error which would confirm the execution. Nothing happened.):

```<code>@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource getDataSource() {

    // i was hoping this was going to pull my current datasource, as
    // defined in application.properties
    return DataSourceBuilder
            .create()
            .build();
}

@Bean
public DataSourceInitializer dataSourceInitializer() {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

    // the call to the above method
    dataSourceInitializer.setDataSource(getDataSource());

    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

    return dataSourceInitializer;
}
</code>```

UPDATE: This question was aimed at getting a reference to the dataSource in use. This question explains how to init the data in a very simple way:
DataSourceInitializer is not working on Spring boot 1.2

答:
You are saying you have those method below your application main method and you are not autowiring the datasource, so you are creating an instance directly and so that not using the properties. You need to use the singleton object created by Spring. In order to do that you have two possibilities:

First option, and the one you should use, is declare a config class to create your beans:

```<code>@Configuration
public class DatasourceConfig
{

    @ConfigurationProperties(prefix="spring.datasource")
    @Bean
    public DataSource getDataSource() {

        // i was hoping this was going to pull my current datasource, as
        // defined in application.properties
        return DataSourceBuilder
                .create()
                .build();
    }

    @Bean
    public DataSourceInitializer dataSourceInitializer() {
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

        // the call to the above method
        dataSourceInitializer.setDataSource(getDataSource());

        dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

        return dataSourceInitializer;
    }

}
</code>```

Using @Configuration, even calling the method directly, as Configuration classes are subclassed at startup-time with CGLIB, you are getting the object created by Spring.

Further information about how Java-based configuration works internally

Second option is auto-wire the datasource in the second method:

```<code>@Bean
@Autowired
public DataSourceInitializer dataSourceInitializer(DataSource myDatasource) {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

    dataSourceInitializer.setDataSource(myDatasource);
    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

    return dataSourceInitializer;
}
</code>```

Body:
I want to implement db data init via DataSourceInitializer.

I have these as methods just below my Spring Boot main method, but it seems that it doesn't get executed at all (I tried with intentional removal of characters just to trigger an error which would confirm the execution. Nothing happened.):

@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource getDataSource() {

    // i was hoping this was going to pull my current datasource, as
    // defined in application.properties
    return DataSourceBuilder
            .create()
            .build();
}

@Bean
public DataSourceInitializer dataSourceInitializer() {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

    // the call to the above method
    dataSourceInitializer.setDataSource(getDataSource());

    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

    return dataSourceInitializer;
}

UPDATE: This question was aimed at getting a reference to the dataSource in use. This question explains how to init the data in a very simple way:
DataSourceInitializer is not working on Spring boot 1.2

Body:
You are saying you have those method below your application main method and you are not autowiring the datasource, so you are creating an instance directly and so that not using the properties. You need to use the singleton object created by Spring. In order to do that you have two possibilities:

First option, and the one you should use, is declare a config class to create your beans:

@Configuration
public class DatasourceConfig
{

    @ConfigurationProperties(prefix="spring.datasource")
    @Bean
    public DataSource getDataSource() {

        // i was hoping this was going to pull my current datasource, as
        // defined in application.properties
        return DataSourceBuilder
                .create()
                .build();
    }

    @Bean
    public DataSourceInitializer dataSourceInitializer() {
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

        // the call to the above method
        dataSourceInitializer.setDataSource(getDataSource());

        dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

        return dataSourceInitializer;
    }

}

Using @Configuration, even calling the method directly, as Configuration classes are subclassed at startup-time with CGLIB, you are getting the object created by Spring.

Further information about how Java-based configuration works internally

Second option is auto-wire the datasource in the second method:

@Bean
@Autowired
public DataSourceInitializer dataSourceInitializer(DataSource myDatasource) {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();

    dataSourceInitializer.setDataSource(myDatasource);
    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

    return dataSourceInitializer;
}


问:
Is there python code to convert nltk.tag taggedsent_to_conll (-U?) into conll-x format?
I'm uncertain whether taggedsent_to_conll output is in CoNLL-U format, although posts/replies by others seems to suggest that it is. </p>

答:
Today, I did a Google search with "conll-u to conll-x", got

https://github.com/UniversalDependencies/tools

README refers to the following perl script: conllu_to_conllx.pl


问:
How to learn CouchDB API without documentation?
Since CouchDB has very few API documentation (at least I can not find it), I would like to inspect some JavaScript objecs myself. What is the best way to do this?

For example, show functions recive the request object req as argument. How to find out, which properties (cookies, requested url,...) this request object precisely has?

答: You can write code to inspect what properties an object has, see Iterating over every property of an object in javascript using Prototype?</p>


问:
Using multiple arrays in Awk without duplication of code
I have working code

```<code>BEGIN { FS=";"; }   # field separator
{
    if (match($2, /[0-9]+/)) {           # matching `ID` value
        m=substr($2, RSTART, RLENGTH);
        a[m]++;                          # accumulating number of lines for each `ID`
        print > m"_count.txt";    # writing lines pertaining to certain `ID` into respective file
    }
}
END {
    for(i in a) {
        print "mv "i"_count.txt "i"_"a[i]".txt"  # renaming files with actual counts
    }
}
</code>```

Now i need to change it to do something like this.
So i have three arrays of IDs and each array means separate folders to save result.

```<code>BEGIN { FS=";"; }   # field separator
{
    array1=(125 258 698 874)
    array2=(956 887 4455 22)
    array3=(111 444 558 966 332)
    if ($1 == $2) {varR=$3} else {varR=$2}
    if (match(varR, /[0-9]+/)) {           # matching `ID` value
        if ( varR in array1 ) {
            FolderName = "folder1/"
            m1=substr(varR, RSTART, RLENGTH);
            a1[m1]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m1)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array2 ) {
            FolderName = "folder2/"
            m2=substr(varR, RSTART, RLENGTH);
            a2[m2]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m2)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array3 ) {
            FolderName = "folder3/"
            m3=substr(varR, RSTART, RLENGTH);
            a3[m3]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m3)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
    }
}
END {
    for(i in a1) {
        print "mv "i"_count.txt "i"_"a1[i]".txt"  # renaming files with actual counts
    }
    for(i in a2) {
        print "mv "i"_count.txt "i"_"a2[i]".txt"  # renaming files with actual counts
    }
    for(i in a3) {
        print "mv "i"_count.txt "i"_"a3[i]".txt"  # renaming files with actual counts
    }
}
</code>```

As i need to save matching ID to txt files and put in needed folder
What if i have 100 arrays? I need to duplicate code for each one?

答:
Using GNU Awk's multi-dimensional array support, here's a simplified solution that demonstrates the techniques you need:

```<code>$ gawk '
  BEGIN { FS=";" }   # field separator
  {
      # Initialize the sub-arrays of the multi-dimensional array.
      array[1][""]; split("125;258;698;874", aux); for (i in aux) array[1][aux[i]]
      array[2][""]; split("956;887;4455;22", aux); for (i in aux) array[2][aux[i]]
      array[3][""]; split("111;444;558;966;332", aux); for (i in aux) array[3][aux[i]]
      n = length(array) # The count of sub-arrays
      if ($1 == $2) {varR=$3} else {varR=$2}
      if (match(varR, /[0-9]+/)) {           # matching `ID` value
        for (i=1;i<=n;++i) {                 # loop over all arrays
          if (varR in array[i]) {            # look for the ID among the array keys
            print "folder" i
            break
          }
        }
      }
  }
' <<<'1;1;4455'
folder 2
</code>```

See this answer of mine for an explanation of the array-initialization and multi-dimensional array techniques used in this command.

Note that the array initialization stores the numbers in the keys of arrays array[<n>], because that's what needed to look up values with <value> in array[<n>].

What you tried:

Awk has no array-initializer syntax; what array1=(125 258 698 874) in your code creates is a single string: "125258698874":

The surrounding () have no effect here (they're just for precedence).

Placing tokens - whether numeric or string - right next to each other in Awk performs string concatenation.

Perhaps you mistakenly think that Bash's array-initializer syntax works in Awk too.

( varR in array1 ) looks for varR among the indices (keys) of array1, but had your array initialization worked the way it does in Bash, you'd have to check the values instead.

Body:
I have working code

BEGIN { FS=";"; }   # field separator
{
    if (match($2, /[0-9]+/)) {           # matching `ID` value
        m=substr($2, RSTART, RLENGTH);
        a[m]++;                          # accumulating number of lines for each `ID`
        print > m"_count.txt";    # writing lines pertaining to certain `ID` into respective file
    }
}
END {
    for(i in a) {
        print "mv "i"_count.txt "i"_"a[i]".txt"  # renaming files with actual counts
    }
}

Now i need to change it to do something like this.
So i have three arrays of IDs and each array means separate folders to save result.

BEGIN { FS=";"; }   # field separator
{
    array1=(125 258 698 874)
    array2=(956 887 4455 22)
    array3=(111 444 558 966 332)
    if ($1 == $2) {varR=$3} else {varR=$2}
    if (match(varR, /[0-9]+/)) {           # matching `ID` value
        if ( varR in array1 ) {
            FolderName = "folder1/"
            m1=substr(varR, RSTART, RLENGTH);
            a1[m1]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m1)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array2 ) {
            FolderName = "folder2/"
            m2=substr(varR, RSTART, RLENGTH);
            a2[m2]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m2)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
        if ( varR in array3 ) {
            FolderName = "folder3/"
            m3=substr(varR, RSTART, RLENGTH);
            a3[m3]++;                          # accumulating number of lines for each `ID`
            print > (FolderName m3)"_count.txt";    # writing lines pertaining to certain `ID` into respective file
        }
    }
}
END {
    for(i in a1) {
        print "mv "i"_count.txt "i"_"a1[i]".txt"  # renaming files with actual counts
    }
    for(i in a2) {
        print "mv "i"_count.txt "i"_"a2[i]".txt"  # renaming files with actual counts
    }
    for(i in a3) {
        print "mv "i"_count.txt "i"_"a3[i]".txt"  # renaming files with actual counts
    }
}

As i need to save matching ID to txt files and put in needed folder
What if i have 100 arrays? I need to duplicate code for each one?

Body:
Using GNU Awk's multi-dimensional array support, here's a simplified solution that demonstrates the techniques you need:

$ gawk '
  BEGIN { FS=";" }   # field separator
  {
      # Initialize the sub-arrays of the multi-dimensional array.
      array[1][""]; split("125;258;698;874", aux); for (i in aux) array[1][aux[i]]
      array[2][""]; split("956;887;4455;22", aux); for (i in aux) array[2][aux[i]]
      array[3][""]; split("111;444;558;966;332", aux); for (i in aux) array[3][aux[i]]
      n = length(array) # The count of sub-arrays
      if ($1 == $2) {varR=$3} else {varR=$2}
      if (match(varR, /[0-9]+/)) {           # matching `ID` value
        for (i=1;i<=n;++i) {                 # loop over all arrays
          if (varR in array[i]) {            # look for the ID among the array keys
            print "folder" i
            break
          }
        }
      }
  }
' <<<'1;1;4455'
folder 2

See this answer of mine for an explanation of the array-initialization and multi-dimensional array techniques used in this command.

Note that the array initialization stores the numbers in the keys of arrays array[<n>], because that's what needed to look up values with <value> in array[<n>].

What you tried:

Awk has no array-initializer syntax; what array1=(125 258 698 874) in your code creates is a single string: "125258698874":

The surrounding () have no effect here (they're just for precedence).

Placing tokens - whether numeric or string - right next to each other in Awk performs string concatenation.

Perhaps you mistakenly think that Bash's array-initializer syntax works in Awk too.

( varR in array1 ) looks for varR among the indices (keys) of array1, but had your array initialization worked the way it does in Bash, you'd have to check the values instead.


问:
notifydatasetchanged not working from async task
hi i think my issue is related to this notifyDataSetChanged not working on RecyclerView
im trying to refresh my layout from an async task but when im calling notify datasetchanged nothing happens, but if i create a new instance of the adapter and call notifydatasetchanged then it does work ive tried a few things to no avail and wonder what im doing wrong,

i reference it like this

```<code> public ListAdapter cardAdapter;
</code>```

then in onCreate i initialise everything to do with my recycler view, (the only bit thats needed here is how i initialise my adapter but for clarity ill add everything to do with my recycler view)

```<code>   staggeredGridLayoutManagerVertical = new
   customLinearLayoutManager(this,customLinearLayoutManager.VERTICAL,false);
    recyclerView = (RecyclerView) findViewById(R.id.list_view);
    OnItemTouchListener itemTouchListener = new
    FinalListActivity.OnItemTouchListener() {
        @Override
        public void onCardClick(View view, int position) {
            //removeAt(position);
            list.remove(position);
            cardAdapter.notifyItemRemoved(position);
        }

        @Override
        public void onCardLongClick(View view, int position) {
            //clearGrid();
        }
    };
    cardAdapter = new ListAdapter(list,this,itemTouchListener);
    recyclerView.setLayoutManager(staggeredGridLayoutManagerVertical);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(cardAdapter);
    //cardAdapter.notifyDataSetChanged();

    ItemTouchHelper.Callback callback =
            new SimpleItemTouchHelperCallback(cardAdapter);
    mItemTouchHelper = new ItemTouchHelper(callback);
    mItemTouchHelper.attachToRecyclerView(recyclerView);
</code>```

if i add items to the list before these methods then my recycler view shows the information but what i want is to grab the information in an async task and populate the list in onPostExecute but when i call

```<code>cardAdapter.notifyDataSetChanged();
</code>```

from onPostExecute nothing happens, any help?

EDIT
adding the adapter

```<code>public class ListAdapter extends
RecyclerView.Adapter<ListAdapter.MyViewHolder>
implements ItemTouchHelperAdapter{
private List<String> cardMakerList;
private OnStartDragListener mDragStartListener;
private FinalListActivity.OnItemTouchListener onItemTouchListener;

public class MyViewHolder extends RecyclerView.ViewHolder{
    public EditText cardText;
    public ImageView close;
    public ContentLoadingProgressBar progress;
    public ImageView handleView;
    public RelativeLayout cardBack;

    public MyViewHolder(View view){
        super(view);
        cardText = (EditText) view.findViewById(R.id.cardText);
        close = (ImageView) view.findViewById(R.id.close);
        cardBack =(RelativeLayout)view.findViewById(R.id.cardLayout);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemTouchListener.onCardClick(v, getPosition());
            }
        });
        /*
        close.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                onItemTouchListener.onCardLongClick(v, getPosition());
                return true;
            }
        });
        */
        progress = (ContentLoadingProgressBar)
        view.findViewById(R.id.progress);
        handleView = (ImageView)view.findViewById(R.id.handle);
    }

}
public ListAdapter(List<String> cardMakerList,OnStartDragListener
dragStartListener,FinalListActivity.OnItemTouchListener onItemTouchListener)
{
    this.cardMakerList = cardMakerList;
    mDragStartListener = dragStartListener;
    this.onItemTouchListener = onItemTouchListener;
}
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    if (fromPosition < toPosition){
        for (int i = fromPosition; i < toPosition; i++){
            Collections.swap(cardMakerList,i,i+1);
        }
    }else{
        for (int i = fromPosition; i > toPosition; i--){
            Collections.swap(cardMakerList,i,i-1);
        }
    }
    notifyItemMoved(fromPosition,toPosition);
    return true;
}
@Override
public void onItemDismiss(int position) {
    cardMakerList.remove(position);
    notifyItemRemoved(position);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view_holder, parent, false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position)
{
    String cardString = cardMakerList.get(position);
    holder.cardText.setText(cardString);
    holder.handleView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEventCompat.getActionMasked(event) ==
                    MotionEvent.ACTION_DOWN) {
                mDragStartListener.onStartDrag(holder);
            }
            return false;
        }
    });
    holder.close.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //cardMakerList.remove(position);
            return false;
        }
    });
}
@Override
public int getItemCount(){
    return cardMakerList.size();
}
}
</code>```

答:
There is many reasons that this might occur, and one of them is the list variable is not being updated because at some point it loses it's primary instance and the adapter no longer listens to it. In this case you should implement in your adapter a method like

```<code>public void refreshMyList(List<String> list){
    this.cardMakerList.clear();
    this.cardMakerList.addAll(list);
    this.notifyDataSetChanged();
}
</code>```

Now every time you want to refresh the RecyclerView just call this method with the new list.

Body:
hi i think my issue is related to this notifyDataSetChanged not working on RecyclerView
im trying to refresh my layout from an async task but when im calling notify datasetchanged nothing happens, but if i create a new instance of the adapter and call notifydatasetchanged then it does work ive tried a few things to no avail and wonder what im doing wrong,

i reference it like this

 public ListAdapter cardAdapter;

then in onCreate i initialise everything to do with my recycler view, (the only bit thats needed here is how i initialise my adapter but for clarity ill add everything to do with my recycler view)

   staggeredGridLayoutManagerVertical = new
   customLinearLayoutManager(this,customLinearLayoutManager.VERTICAL,false);
    recyclerView = (RecyclerView) findViewById(R.id.list_view);
    OnItemTouchListener itemTouchListener = new
    FinalListActivity.OnItemTouchListener() {
        @Override
        public void onCardClick(View view, int position) {
            //removeAt(position);
            list.remove(position);
            cardAdapter.notifyItemRemoved(position);
        }

        @Override
        public void onCardLongClick(View view, int position) {
            //clearGrid();
        }
    };
    cardAdapter = new ListAdapter(list,this,itemTouchListener);
    recyclerView.setLayoutManager(staggeredGridLayoutManagerVertical);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(cardAdapter);
    //cardAdapter.notifyDataSetChanged();

    ItemTouchHelper.Callback callback =
            new SimpleItemTouchHelperCallback(cardAdapter);
    mItemTouchHelper = new ItemTouchHelper(callback);
    mItemTouchHelper.attachToRecyclerView(recyclerView);

if i add items to the list before these methods then my recycler view shows the information but what i want is to grab the information in an async task and populate the list in onPostExecute but when i call

cardAdapter.notifyDataSetChanged();

from onPostExecute nothing happens, any help?

EDIT
adding the adapter

public class ListAdapter extends
RecyclerView.Adapter<ListAdapter.MyViewHolder>
implements ItemTouchHelperAdapter{
private List<String> cardMakerList;
private OnStartDragListener mDragStartListener;
private FinalListActivity.OnItemTouchListener onItemTouchListener;

public class MyViewHolder extends RecyclerView.ViewHolder{
    public EditText cardText;
    public ImageView close;
    public ContentLoadingProgressBar progress;
    public ImageView handleView;
    public RelativeLayout cardBack;

    public MyViewHolder(View view){
        super(view);
        cardText = (EditText) view.findViewById(R.id.cardText);
        close = (ImageView) view.findViewById(R.id.close);
        cardBack =(RelativeLayout)view.findViewById(R.id.cardLayout);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemTouchListener.onCardClick(v, getPosition());
            }
        });
        /*
        close.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                onItemTouchListener.onCardLongClick(v, getPosition());
                return true;
            }
        });
        */
        progress = (ContentLoadingProgressBar)
        view.findViewById(R.id.progress);
        handleView = (ImageView)view.findViewById(R.id.handle);
    }

}
public ListAdapter(List<String> cardMakerList,OnStartDragListener
dragStartListener,FinalListActivity.OnItemTouchListener onItemTouchListener)
{
    this.cardMakerList = cardMakerList;
    mDragStartListener = dragStartListener;
    this.onItemTouchListener = onItemTouchListener;
}
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    if (fromPosition < toPosition){
        for (int i = fromPosition; i < toPosition; i++){
            Collections.swap(cardMakerList,i,i+1);
        }
    }else{
        for (int i = fromPosition; i > toPosition; i--){
            Collections.swap(cardMakerList,i,i-1);
        }
    }
    notifyItemMoved(fromPosition,toPosition);
    return true;
}
@Override
public void onItemDismiss(int position) {
    cardMakerList.remove(position);
    notifyItemRemoved(position);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view_holder, parent, false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position)
{
    String cardString = cardMakerList.get(position);
    holder.cardText.setText(cardString);
    holder.handleView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEventCompat.getActionMasked(event) ==
                    MotionEvent.ACTION_DOWN) {
                mDragStartListener.onStartDrag(holder);
            }
            return false;
        }
    });
    holder.close.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //cardMakerList.remove(position);
            return false;
        }
    });
}
@Override
public int getItemCount(){
    return cardMakerList.size();
}
}

Body:
There is many reasons that this might occur, and one of them is the list variable is not being updated because at some point it loses it's primary instance and the adapter no longer listens to it. In this case you should implement in your adapter a method like

public void refreshMyList(List<String> list){
    this.cardMakerList.clear();
    this.cardMakerList.addAll(list);
    this.notifyDataSetChanged();
}

Now every time you want to refresh the RecyclerView just call this method with the new list.


问:
Redirect http to https via nginx
I have a completely stock installation of nginx version: nginx/1.10.0 (Ubuntu) on Ubuntu 16.04 other than /etc/nginx/sites-enabled/default being replaced with the following...

```<code>server {
    listen 443 default_server;
    server_name www.example.com;

    ssl_certificate           /etc/nginx/cert.crt;
    ssl_certificate_key       /etc/nginx/cert.key;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_pass http://localhost:8080; # my existing apache instance
        proxy_set_header Host $host;

        # re-write redirects to http as to https, example: /home
        proxy_redirect http:// https://;
    }
}
</code>```

Which has the purpose of being a https wrapper around a http api running on port 8080.

I am now trying to make it so that when someone goes to my site on http port 80, it redirects them to https. I have tried every other documented fix, mostly based around something like this...

```<code>server {
   listen 80;
   return 301 https://$host$request_uri;
}
</code>```

... and nothing seems to have any effect what so ever and you always get the WELCOME TO NGINX page.

答:
I want to leave a more recent update here since nginx has changed since this question was asked.

You can redirect http requests with the following lines:

```<code>server {
    listen      80;
    server_name example.com;
    rewrite     ^   https://example.com$request_uri? permanent;
}
</code>```

Title: Redirect http to https via nginx

Body:
I have a completely stock installation of nginx version: nginx/1.10.0 (Ubuntu) on Ubuntu 16.04 other than /etc/nginx/sites-enabled/default being replaced with the following...

server {
    listen 443 default_server;
    server_name www.example.com;

    ssl_certificate           /etc/nginx/cert.crt;
    ssl_certificate_key       /etc/nginx/cert.key;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_pass http://localhost:8080; # my existing apache instance
        proxy_set_header Host $host;

        # re-write redirects to http as to https, example: /home
        proxy_redirect http:// https://;
    }
}

Which has the purpose of being a https wrapper around a http api running on port 8080.

I am now trying to make it so that when someone goes to my site on http port 80, it redirects them to https. I have tried every other documented fix, mostly based around something like this...

server {
   listen 80;
   return 301 https://$host$request_uri;
}

... and nothing seems to have any effect what so ever and you always get the WELCOME TO NGINX page.

Body:
I want to leave a more recent update here since nginx has changed since this question was asked.

You can redirect http requests with the following lines:

server {
    listen      80;
    server_name example.com;
    rewrite     ^   https://example.com$request_uri? permanent;
}


问:
Python: Youtube-dl status after conversion to mp3
I'm writing a script to download mp3 songs from web. first i'll be scraping in youtube. if found, download it using youtube-dl and convert it to mp3. If not found(done by using os.path.isfile), scrap in beemp3(for this sample) or mp3skulls etc. The script for only ytdownload and file check is below:

```<code>from bs4 import BeautifulSoup
from urllib.request import urlopen,Request,urlretrieve
import re
import youtube_dl
import sys
import os

def ytscrape(searchurl,baseurl):
    """normal scraping"""
    req = Request(searchurl, headers={'User-Agent':'Mozilla/5.0'})
    lst[:] = []
    url = urlopen(req)
    soup = BeautifulSoup(url, 'lxml')
    for i in soup.find_all('div',{'class':['yt-lockup-content','yt-lockup-meta-info']},limit=10):
        for link,views in zip(i.select('h3 > a'),i.select('ul > li')):
            if views is not None and views.next_sibling is not None:
                lst.append([baseurl+link.get('href'),views.next_sibling.text])
    for i in lst:
        i[1] = int(re.sub(r' views|,','',i[1]))
    lst.sort(key = lambda x:x[1])
    url.close()
    return lst[-1][0]

def dl_frm_youtube(yt_lnk,dlpath):
    """passes the youtube url of the song. it extracts audio alone and saves it
    in local.
    yt_lnk : youtube url for song which is priortised based on channel/views.
    """
    ydl_opts = {'format':'bestaudio/best','outtmpl':dlpath+'\\%(title)s.%(ext)s','postprocessors':[{'key':'FFmpegExtractAudio','preferredcodec':'mp3','preferredquality':'192',}]}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([yt_lnk])
        if os.path.isfile(dlpath+'\\%(title)s.%(ext)s'):
            print('found')
        else:
            print('not found')

def main():
    song = 'numb'
    artist = 'linkin park'
    baseurl = 'https://www.youtube.com'
    if sys.platform == 'win32':
        dlpath = os.path.join(os.environ['USERPROFILE'],'Music','spd')
        if not os.path.exists(dlpath):
            os.mkdir(dlpath)
    else:
        dlpath = '~/Music/' + song + '.mp3'
    searchurl = baseurl + '/results?search_query=' + '+' + artist.replace(chr(32),'+') + '+' + song.replace(chr(32),'+')
    dl_frm_youtube(ytscrape(searchurl,baseurl),dlpath)

lst = []
main()
</code>```

When I tried to do file check, it failed eventhough the song downloaded and is present in the path. since it failed, it went to next function and downloaded that as well causing me to have 2 songs in my path.

So, my question is how to setup that file check so that it should print found when its present in the dlpath.

TIA

EDIT:
As per phihag comments, I removed all useless info, changed code to have only problem part and hardcoded the inputs.

答:
Finally, I was able to find out why. It seems %(title)s.%(ext)s only seems to hold values inside ydl_opts dict. this answer helped me.

I changed my code inside dl_frm_youtube to this:

```<code>with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        #ydl.download([yt_lnk])
        info = ydl.extract_info(yt_lnk, download=True)
        songname = info.get('title', None)
        #print(songname)
        if os.path.isfile(dlpath+'\\'+songname+'.mp3'):
            print('found')
</code>```

and it works perfectly. Answering it in case if someone find it useful.

Body:
I'm writing a script to download mp3 songs from web. first i'll be scraping in youtube. if found, download it using youtube-dl and convert it to mp3. If not found(done by using os.path.isfile), scrap in beemp3(for this sample) or mp3skulls etc. The script for only ytdownload and file check is below:

from bs4 import BeautifulSoup
from urllib.request import urlopen,Request,urlretrieve
import re
import youtube_dl
import sys
import os

def ytscrape(searchurl,baseurl):
    """normal scraping"""
    req = Request(searchurl, headers={'User-Agent':'Mozilla/5.0'})
    lst[:] = []
    url = urlopen(req)
    soup = BeautifulSoup(url, 'lxml')
    for i in soup.find_all('div',{'class':['yt-lockup-content','yt-lockup-meta-info']},limit=10):
        for link,views in zip(i.select('h3 > a'),i.select('ul > li')):
            if views is not None and views.next_sibling is not None:
                lst.append([baseurl+link.get('href'),views.next_sibling.text])
    for i in lst:
        i[1] = int(re.sub(r' views|,','',i[1]))
    lst.sort(key = lambda x:x[1])
    url.close()
    return lst[-1][0]

def dl_frm_youtube(yt_lnk,dlpath):
    """passes the youtube url of the song. it extracts audio alone and saves it
    in local.
    yt_lnk : youtube url for song which is priortised based on channel/views.
    """
    ydl_opts = {'format':'bestaudio/best','outtmpl':dlpath+'\\%(title)s.%(ext)s','postprocessors':[{'key':'FFmpegExtractAudio','preferredcodec':'mp3','preferredquality':'192',}]}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([yt_lnk])
        if os.path.isfile(dlpath+'\\%(title)s.%(ext)s'):
            print('found')
        else:
            print('not found')

def main():
    song = 'numb'
    artist = 'linkin park'
    baseurl = 'https://www.youtube.com'
    if sys.platform == 'win32':
        dlpath = os.path.join(os.environ['USERPROFILE'],'Music','spd')
        if not os.path.exists(dlpath):
            os.mkdir(dlpath)
    else:
        dlpath = '~/Music/' + song + '.mp3'
    searchurl = baseurl + '/results?search_query=' + '+' + artist.replace(chr(32),'+') + '+' + song.replace(chr(32),'+')
    dl_frm_youtube(ytscrape(searchurl,baseurl),dlpath)

lst = []
main()

When I tried to do file check, it failed eventhough the song downloaded and is present in the path. since it failed, it went to next function and downloaded that as well causing me to have 2 songs in my path.

So, my question is how to setup that file check so that it should print found when its present in the dlpath.

TIA

EDIT:
As per phihag comments, I removed all useless info, changed code to have only problem part and hardcoded the inputs.

Body:
Finally, I was able to find out why. It seems %(title)s.%(ext)s only seems to hold values inside ydl_opts dict. this answer helped me.

I changed my code inside dl_frm_youtube to this:

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        #ydl.download([yt_lnk])
        info = ydl.extract_info(yt_lnk, download=True)
        songname = info.get('title', None)
        #print(songname)
        if os.path.isfile(dlpath+'\\'+songname+'.mp3'):
            print('found')

and it works perfectly. Answering it in case if someone find it useful.


问:
Apache Beam returns "Input values must not be mutated in any way." when using local direct runner
I wrote an Apache Beam DoFn

```<code>static class FillLocation extends DoFn<TrackingRequest, TrackingRequest> {
        @ProcessElement
        public void processElement(ProcessContext c) {
            TrackingRequest rq = c.element();
            rq.location = getLocationFromIP(rq.IP);
            c.output(rq);
        }
}
</code>```

And it gave me this error when testing it locally
 PTransform .. illegaly mutated value .. of class.....

```<code> Input values must not be mutated in any way.
    at org.apache.beam.runners.direct.ImmutabilityEnforcementFactory$ImmutabilityCheckingEnforcement.verifyUnmodified(ImmutabilityEnforcementFactory.java:96)
    at org.apache.beam.runners.direct.ImmutabilityEnforcementFactory$ImmutabilityCheckingEnforcement.afterElement(ImmutabilityEnforcementFactory.java:71)
    at org.apache.beam.runners.direct.TransformExecutor.processElements(TransformExecutor.java:149)
    at org.apache.beam.runners.direct.TransformExecutor.run(TransformExecutor.java:107)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
Your function modified the location field of the input TrackingRequest element. This is not allowed by the Dataflow.

The doc says:

The current element of the input PCollection is returned by c.element(). It should be considered immutable. The Dataflow runtime will not mutate the element, so it is safe to cache, etc. The element should not be mutated by any of the DoFn methods, because it may be cached elsewhere, retained by the Dataflow runtime, or used in other unspecified ways.

You can create a copy of the input element, modify the field, and send the copy out as output.

Body:
I wrote an Apache Beam DoFn

static class FillLocation extends DoFn<TrackingRequest, TrackingRequest> {
        @ProcessElement
        public void processElement(ProcessContext c) {
            TrackingRequest rq = c.element();
            rq.location = getLocationFromIP(rq.IP);
            c.output(rq);
        }
}

And it gave me this error when testing it locally
 PTransform .. illegaly mutated value .. of class.....

 Input values must not be mutated in any way.
    at org.apache.beam.runners.direct.ImmutabilityEnforcementFactory$ImmutabilityCheckingEnforcement.verifyUnmodified(ImmutabilityEnforcementFactory.java:96)
    at org.apache.beam.runners.direct.ImmutabilityEnforcementFactory$ImmutabilityCheckingEnforcement.afterElement(ImmutabilityEnforcementFactory.java:71)
    at org.apache.beam.runners.direct.TransformExecutor.processElements(TransformExecutor.java:149)
    at org.apache.beam.runners.direct.TransformExecutor.run(TransformExecutor.java:107)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)


问:
Sorting an array with multiple elements
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks. </p>

```<code>public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}
</code>```

答: Why not use a SortedMap of Date->String>?</p>

Title: Sorting an array with multiple elements

Body:
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks.

public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}


问:
Hiding links based on Authentication Angular 2
I am trying to hide instantly Navbar links based on user authentication without page refresh

AppComponent.html

```<code><div class="content">
    <md-toolbar>
        <md-icon>menu</md-icon>
        <span class="fill-space"></span>
        <button md-icon-button><md-icon>search</md-icon></button>
        <md-input-container>
            <input mdInput name="search" #search placeholder="Search">
        </md-input-container>

        <button md-raised-button color="primary" (click)="OpenLoginDialog()" *ngIf="!isAuthenticated">Login</button>
        <button md-raised-button (click)="OpenSignupDialog()" *ngIf="!isAuthenticated">Signup</button>
        <button md-raised-button (click)="Logout()" *ngIf="isAuthenticated">Logout</button>
    </md-toolbar>
</div>
</code>```

Authentication Service

```<code>import { Injectable } from "@angular/core";
import { Observable } from "Rxjs";
import { Http, Headers } from "@angular/http";
import { User } from "./UserModel";

@Injectable()
export class AuthenticationService {
    isLoggedin: boolean = false;

redirectUrl: string;
constructor(private http: Http) { }
login(model: User) {
    debugger;
    let headers = new Headers({ 'Content-Type': 'application/json' });
    return this.http.post("/Account/Login", JSON.stringify({ model }), { headers: headers }).map(res => res.json()).map(res => {
        debugger;

        if (res.isSuccess) {
            localStorage.setItem("auth_token", res.UserInfo);
            this.isLoggedin = true;
        }
        return res.isSuccess;
    });

}
logout(): void
{
    localStorage.removeItem('auth_token');
    this.isLoggedin = false;
}
isLoggedIn() {
    debugger;
    if (localStorage.getItem("auth_token") == null) {
        this.isLoggedin = false;
        return this.isLoggedin;
    }
    else {
        return true;
    }
}
}
</code>```

App.Component

```<code>    import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Validate } from "./Custom.Validator";
import { MdDialog } from "@angular/material";
import { DialogComponent } from "./Dialog.Component";
import { LoginComponent } from "./Login.Component";
import { SignupComponent } from "./Signup.Component";
import { AuthenticationService } from "./Authentication.Service";
@Component({
    selector: 'app-main',
    templateUrl: "../App/App.html",
    styles: [`div {
    padding: 1rem;
  }`]
})

export class AppComponent implements OnInit {
    selectedEmoji: string;
    isAuthenticated: boolean;
    myForm: FormGroup;
    constructor(private fb: FormBuilder, public dialog: MdDialog, public authService: AuthenticationService) { }
    ngOnInit() {
        this.myForm = this.fb.group({
            state: ['', Validators.required],
            zip: ['', [Validators.required, Validate]],
        });
        this.isLoggedIn();
    }
    openEmojiDialog() {
        let dialog = this.dialog.open(DialogComponent);
        dialog.afterClosed().subscribe(selection => {
            if (selection) {
                this.selectedEmoji = selection;

            }
            else {

            }
        });
    }
    OpenLoginDialog() {
        let dialog = this.dialog.open(LoginComponent);
    }
    OpenSignupDialog() {
        let dialog = this.dialog.open(SignupComponent);
    }
    Logout() {
        this.authService.logout();
    }
    isLoggedIn()
    {
        this.isAuthenticated = this.authService.isLoggedIn();
    }
}
</code>```

The Links are hiding only after page refresh but I want it to hide instantly after user authentication

答:
Since you already have a function in your Authentication Service and you are already injecting the Authentication Service into your App.Component, go ahead and use a simple *ngIf="authService.isLoggedIn()" instead of creating a local variable in your App.Component where that data will get stale.

It would look something like this in use:

```<code><li *ngIf="authService.isLoggedIn()">
  <a [routerLink]="['/path1']">Path 1</a>
</li>
<li *ngIf="authService.isLoggedIn()">
  <a [routerLink]="['/path2']">Path 2</a>
</li>
</code>```

It could be shortened to use the variable you already have available in the authentication service to just *ngIf="authService.isLoggedin".

Body:
I am trying to hide instantly Navbar links based on user authentication without page refresh

AppComponent.html

    <md-toolbar>
        <md-icon>menu</md-icon>

        <button md-icon-button><md-icon>search</md-icon></button>
        <md-input-container>
            <input mdInput name="search" #search placeholder="Search">
        </md-input-container>

        <button md-raised-button color="primary" (click)="OpenLoginDialog()" *ngIf="!isAuthenticated">Login</button>
        <button md-raised-button (click)="OpenSignupDialog()" *ngIf="!isAuthenticated">Signup</button>
        <button md-raised-button (click)="Logout()" *ngIf="isAuthenticated">Logout</button>
    </md-toolbar>

Authentication Service

import { Injectable } from "@angular/core";
import { Observable } from "Rxjs";
import { Http, Headers } from "@angular/http";
import { User } from "./UserModel";

@Injectable()
export class AuthenticationService {
    isLoggedin: boolean = false;

redirectUrl: string;
constructor(private http: Http) { }
login(model: User) {
    debugger;
    let headers = new Headers({ 'Content-Type': 'application/json' });
    return this.http.post("/Account/Login", JSON.stringify({ model }), { headers: headers }).map(res => res.json()).map(res => {
        debugger;

        if (res.isSuccess) {
            localStorage.setItem("auth_token", res.UserInfo);
            this.isLoggedin = true;
        }
        return res.isSuccess;
    });

}
logout(): void
{
    localStorage.removeItem('auth_token');
    this.isLoggedin = false;
}
isLoggedIn() {
    debugger;
    if (localStorage.getItem("auth_token") == null) {
        this.isLoggedin = false;
        return this.isLoggedin;
    }
    else {
        return true;
    }
}
}

App.Component

    import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Validate } from "./Custom.Validator";
import { MdDialog } from "@angular/material";
import { DialogComponent } from "./Dialog.Component";
import { LoginComponent } from "./Login.Component";
import { SignupComponent } from "./Signup.Component";
import { AuthenticationService } from "./Authentication.Service";
@Component({
    selector: 'app-main',
    templateUrl: "../App/App.html",
    styles: [`div {
    padding: 1rem;
  }`]
})

export class AppComponent implements OnInit {
    selectedEmoji: string;
    isAuthenticated: boolean;
    myForm: FormGroup;
    constructor(private fb: FormBuilder, public dialog: MdDialog, public authService: AuthenticationService) { }
    ngOnInit() {
        this.myForm = this.fb.group({
            state: ['', Validators.required],
            zip: ['', [Validators.required, Validate]],
        });
        this.isLoggedIn();
    }
    openEmojiDialog() {
        let dialog = this.dialog.open(DialogComponent);
        dialog.afterClosed().subscribe(selection => {
            if (selection) {
                this.selectedEmoji = selection;

            }
            else {

            }
        });
    }
    OpenLoginDialog() {
        let dialog = this.dialog.open(LoginComponent);
    }
    OpenSignupDialog() {
        let dialog = this.dialog.open(SignupComponent);
    }
    Logout() {
        this.authService.logout();
    }
    isLoggedIn()
    {
        this.isAuthenticated = this.authService.isLoggedIn();
    }
}

The Links are hiding only after page refresh but I want it to hide instantly after user authentication

Body:
Since you already have a function in your Authentication Service and you are already injecting the Authentication Service into your App.Component, go ahead and use a simple *ngIf="authService.isLoggedIn()" instead of creating a local variable in your App.Component where that data will get stale.

It would look something like this in use:

<li *ngIf="authService.isLoggedIn()">
  <a [routerLink]="['/path1']">Path 1</a>
</li>
<li *ngIf="authService.isLoggedIn()">
  <a [routerLink]="['/path2']">Path 2</a>
</li>

It could be shortened to use the variable you already have available in the authentication service to just *ngIf="authService.isLoggedin".


问:
How to change the Event name of a session in AppSee from an iOS application?
Does anyone know, how to change the event name on Appsee? I am able to update the screen name using AppSee delegate method. But when I am using the add event operation, it's adding a separate event on Appsee session. I don't want to add a new event name. I would like to upgrade the auto generated event name with my custom event name.

Any idea if there is any iOS Appsee API available to do that. There is no documentation on Appsee that how to change a auto generated action event name.

答: What you are referring to are "actions" in the Appsee terminology, and cannot be modified. You can contact their support so they disable the auto recognition of actions and then you can manually add the custom ones you'd like.


问:
Get single record from database Django
I am new to Django and trying to make a basic website and having a few difficulties getting the relevant record for a page.

Models.py

```<code>import datetime
from django.db import models
from django.conf import settings
from ckeditor.fields import RichTextField
from markdown import markdown

class LiveEntryManager(models.Manager):
      def get_query_set(self):
      return super(LiveEntryManager,self).get_query_set().filter(status=self.model.LIVE_STATUS)

class Page(models.Model):
      LIVE_STATUS = 1
      HIDDEN_STATUS = 2
      STATUS_CHOICES = (
            (LIVE_STATUS, 'Live'),
            (HIDDEN_STATUS, 'Hidden'),
       )
      title = models.CharField(max_length=250, help_text='Max 250 characters.')
      slug = models.SlugField(unique=True, help_text='Suggested automatically generated from the title. Must be unique')
      description = RichTextField()
      description_html = models.TextField(editable=False, blank=True)
      status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS,
                           help_text="Only pages with live status will be publicly displayed")

      def save(self, force_insert=False, force_update=False):
          self.description_html = markdown(self.description)
          super(Page, self).save(force_insert, force_update)

      def get_record(self):
          return self.objects.get()

      #Managers
      live = LiveEntryManager()
      objects = models.Manager()

      class Meta:
            ordering = ['title']
            verbose_name_plural = "Pages"

      def __unicode__(self):
          return self.title

      def get_absolute_url(self):
          return "/%s/" % self.slug

class Image(models.Model):
      page = models.ForeignKey(Page)
      name = models.CharField(max_length=250)
      image = models.ImageField(upload_to='gallery')

      class Meta:
            ordering = ['name']

      def __unicode__(self):
          return self.name
</code>```

And Views.py

```<code>from django.shortcuts import get_object_or_404, render_to_response
from django.views.generic.list_detail import object_list
from mainsite.models import Page, Image

def home(request):
    return render_to_response('templates/home.html')

def page(request, slug):
    one_page = get_object_or_404(Page, slug=slug)
    return render_to_response('templates/page/page.html',
                          { 'object_list': one_page.get_record() })
</code>```

and Urls.py

```<code>urlpatterns = patterns('',
   # Examples:
   url(r'^$', 'mainsite.views.home', name='home'),
   # url(r'^disability/', include('disability.foo.urls')),
   url(r'^page/(?P<slug>[-\w]+)/$', 'mainsite.views.page'),
   # Uncomment the admin/doc line below to enable admin documentation:
   # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
   url(r'^grappelli/', include('grappelli.urls')),
   # Uncomment the next line to enable the admin:
   url(r'^admin/', include(admin.site.urls)),
</code>```

)

What I want to do is to be able to go to say /page/test and get the title, description and image for that object only. I know how to get all objects and display them in a template but cannot figure out how to get a single record and would be grateful of some help.

Thanks

答:
If you would want to query the database for a single Page model you could use

```<code>views.py

from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from models import Pages

def page(request, slug):
    try:
        page = Pages.objects.get(slug=slug)
    except ObjectDoesNotExist:
        return HttpResponse(status=404)
    return render(request, 'templates/page/page.html', {'page': page})
</code>```

Then just use

```<code>{{page.title}}
</code>```

or something like that in your template.

Also, if you want to query and have an iterable list returned intead you coule use

```<code>Pages.objects.filter()
</code>```

instead of

```<code>Pages.objects.get()
</code>```

Title: Get single record from database Django

Body:
I am new to Django and trying to make a basic website and having a few difficulties getting the relevant record for a page.

Models.py

import datetime
from django.db import models
from django.conf import settings
from ckeditor.fields import RichTextField
from markdown import markdown

class LiveEntryManager(models.Manager):
      def get_query_set(self):
      return super(LiveEntryManager,self).get_query_set().filter(status=self.model.LIVE_STATUS)

class Page(models.Model):
      LIVE_STATUS = 1
      HIDDEN_STATUS = 2
      STATUS_CHOICES = (
            (LIVE_STATUS, 'Live'),
            (HIDDEN_STATUS, 'Hidden'),
       )
      title = models.CharField(max_length=250, help_text='Max 250 characters.')
      slug = models.SlugField(unique=True, help_text='Suggested automatically generated from the title. Must be unique')
      description = RichTextField()
      description_html = models.TextField(editable=False, blank=True)
      status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS,
                           help_text="Only pages with live status will be publicly displayed")

      def save(self, force_insert=False, force_update=False):
          self.description_html = markdown(self.description)
          super(Page, self).save(force_insert, force_update)

      def get_record(self):
          return self.objects.get()

      #Managers
      live = LiveEntryManager()
      objects = models.Manager()

      class Meta:
            ordering = ['title']
            verbose_name_plural = "Pages"

      def __unicode__(self):
          return self.title

      def get_absolute_url(self):
          return "/%s/" % self.slug

class Image(models.Model):
      page = models.ForeignKey(Page)
      name = models.CharField(max_length=250)
      image = models.ImageField(upload_to='gallery')

      class Meta:
            ordering = ['name']

      def __unicode__(self):
          return self.name

And Views.py

from django.shortcuts import get_object_or_404, render_to_response
from django.views.generic.list_detail import object_list
from mainsite.models import Page, Image

def home(request):
    return render_to_response('templates/home.html')

def page(request, slug):
    one_page = get_object_or_404(Page, slug=slug)
    return render_to_response('templates/page/page.html',
                          { 'object_list': one_page.get_record() })

and Urls.py

urlpatterns = patterns('',
   # Examples:
   url(r'^$', 'mainsite.views.home', name='home'),
   # url(r'^disability/', include('disability.foo.urls')),
   url(r'^page/(?P<slug>[-\w]+)/$', 'mainsite.views.page'),
   # Uncomment the admin/doc line below to enable admin documentation:
   # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
   url(r'^grappelli/', include('grappelli.urls')),
   # Uncomment the next line to enable the admin:
   url(r'^admin/', include(admin.site.urls)),

)

What I want to do is to be able to go to say /page/test and get the title, description and image for that object only. I know how to get all objects and display them in a template but cannot figure out how to get a single record and would be grateful of some help.

Thanks

Body:
If you would want to query the database for a single Page model you could use

views.py

from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from models import Pages

def page(request, slug):
    try:
        page = Pages.objects.get(slug=slug)
    except ObjectDoesNotExist:
        return HttpResponse(status=404)
    return render(request, 'templates/page/page.html', {'page': page})

Then just use

{{page.title}}

or something like that in your template.

Also, if you want to query and have an iterable list returned intead you coule use

Pages.objects.filter()

instead of

Pages.objects.get()


问:
changing a sql view query into a relational algebra?
I want to convert this sql query into relational algebra.

sql query:

```<code>SELECT *
FROM Library
WHERE libName='florence'
</code>```

答:
I don't know what you mean with convert to relational algebra. But in relational algebra that sentence would be:

Basically, the SELECT operation over the Library table, with a condition.

Body:
I want to convert this sql query into relational algebra.

sql query:

SELECT *
FROM Library
WHERE libName='florence'


问:
How to convert n rows of xlsx to csv in Python while preserving date values
I am trying to convert an xlsx file to one CSV file containing the header and another CSV file containing the actual data.
I have the following requirements:

Header does not start at first row but at row start_line.

Dates should not be considered as floats but in some string format.

I don't know the total number of rows or columns of the file beforehand. I also don't want to specify which column is a date.

Using pandas I get stuck at number 1.
I wanted to achieve this in two separate reads where I read from start_line to start_line+1 and from start_line+1 to the end.
However it seems like it is not possible to read n lines from an offset. Below is the code I use to just get one file including the header.

```<code>import pandas as pd
def parse_excel(file,start_line,sheet,table):
    sh = pd.read_excel(file,sheet,skiprows=start_line)
    sh.to_csv("output.csv",sep='\t',encoding='utf-8',index=False)
</code>```

Next I have tried this using xlrd but this library treats all dates as floats like in Excel. The only workaround here seems to go through all individual cells which does not seem very efficient or well coded. What I have now:

```<code>import xlrd
def parse_excel(file,start_line,sheet,table):
    with xlrd.open_workbook(file) as wb:
        sh = wb.sheet_by_name(sheet)
        header_written = False
        with open('{0}.csv'.format(table),'wb') as csv_file:
            wr = csv.writer(csv_file,delimiter='\t')
            for rownum in range(sh.nrows):
                if not header_written and start_line == rownum:
                    with open('{0}_header.csv'.format(table),'wb') as header:
                        hwr = csv.writer(header,delimiter='\t')
                        hwr.writerow(sh.row_values(rownum))
                        header_written = True
                elif header_written:
                    wr.writerow(sh.row_values(rownum))
</code>```

Please point me to other solutions/libraries, show a workaround for either one of the above or explain why I should go for the xlrd workaround checking each individual cell.

答:
As long as all of your data is below your header row then following should work. Assuming the header row is at row n (indexing beginning at 0 not 1 like excel).

```<code>df = pd.read_excel('filepath', header=n)
df.head(0).to_csv('header.csv', index=False)
df.to_csv('output.csv', header=None, index=False)
</code>```

Body:
I am trying to convert an xlsx file to one CSV file containing the header and another CSV file containing the actual data.
I have the following requirements:

Header does not start at first row but at row start_line.

Dates should not be considered as floats but in some string format.

I don't know the total number of rows or columns of the file beforehand. I also don't want to specify which column is a date.

Using pandas I get stuck at number 1.
I wanted to achieve this in two separate reads where I read from start_line to start_line+1 and from start_line+1 to the end.
However it seems like it is not possible to read n lines from an offset. Below is the code I use to just get one file including the header.

import pandas as pd
def parse_excel(file,start_line,sheet,table):
    sh = pd.read_excel(file,sheet,skiprows=start_line)
    sh.to_csv("output.csv",sep='\t',encoding='utf-8',index=False)

Next I have tried this using xlrd but this library treats all dates as floats like in Excel. The only workaround here seems to go through all individual cells which does not seem very efficient or well coded. What I have now:

import xlrd
def parse_excel(file,start_line,sheet,table):
    with xlrd.open_workbook(file) as wb:
        sh = wb.sheet_by_name(sheet)
        header_written = False
        with open('{0}.csv'.format(table),'wb') as csv_file:
            wr = csv.writer(csv_file,delimiter='\t')
            for rownum in range(sh.nrows):
                if not header_written and start_line == rownum:
                    with open('{0}_header.csv'.format(table),'wb') as header:
                        hwr = csv.writer(header,delimiter='\t')
                        hwr.writerow(sh.row_values(rownum))
                        header_written = True
                elif header_written:
                    wr.writerow(sh.row_values(rownum))

Please point me to other solutions/libraries, show a workaround for either one of the above or explain why I should go for the xlrd workaround checking each individual cell.

Body:
As long as all of your data is below your header row then following should work. Assuming the header row is at row n (indexing beginning at 0 not 1 like excel).

df = pd.read_excel('filepath', header=n)
df.head(0).to_csv('header.csv', index=False)
df.to_csv('output.csv', header=None, index=False)