问:
When stating a transaction using sequelize, how to achieve some statements are out of transaction?
When stating a transaction, how to achieve some statements is out of transaction.

See the following example, the first create statement didn't get transaction option, so it should be out of transaction, and when rolling back it should be in database. However, both are in transaction and both rolled back. Any comments?

```<code>    describe.only('sequelzie transaction test', () => {
        const sequelize = new Sequelize('test', null, null, {
            dialect: 'sqlite',
    })

    const UserModel = sequelize.define('user', {
        name: {
            type: Sequelize.STRING,
            primaryKey: true,
        },
    })
    beforeEach (async () => {
        await sequelize.sync({force: true})
    })

    it('partial rollback transaction should work', async () => {
        const transaction  = await sequelize.transaction()
        try {
            await UserModel.create({name: 'ron'} )
            await UserModel.create({name: 'ron', {transaction}})
            await transaction.commit()
        }
        catch (e) {
            await transaction.rollback()
        }

        const users = await UserModel.findAll()
        expect(users).to.have.length(1) // failed here, it was 0, both are rolled back
    })
})
</code>```

答:
One problem i did find out in your code was that transaction was passed incorrectly in create function

```<code>await UserModel.create({name: 'ron'}, {transaction})
</code>```

Transaction is part of options object. Also try enabling the debug option to check what queries are being executed. You will be able to discern the problem.

Body:
When stating a transaction, how to achieve some statements is out of transaction.

See the following example, the first create statement didn't get transaction option, so it should be out of transaction, and when rolling back it should be in database. However, both are in transaction and both rolled back. Any comments?

    describe.only('sequelzie transaction test', () => {
        const sequelize = new Sequelize('test', null, null, {
            dialect: 'sqlite',
    })

    const UserModel = sequelize.define('user', {
        name: {
            type: Sequelize.STRING,
            primaryKey: true,
        },
    })
    beforeEach (async () => {
        await sequelize.sync({force: true})
    })

    it('partial rollback transaction should work', async () => {
        const transaction  = await sequelize.transaction()
        try {
            await UserModel.create({name: 'ron'} )
            await UserModel.create({name: 'ron', {transaction}})
            await transaction.commit()
        }
        catch (e) {
            await transaction.rollback()
        }

        const users = await UserModel.findAll()
        expect(users).to.have.length(1) // failed here, it was 0, both are rolled back
    })
})

Body:
One problem i did find out in your code was that transaction was passed incorrectly in create function

await UserModel.create({name: 'ron'}, {transaction})

Transaction is part of options object. Also try enabling the debug option to check what queries are being executed. You will be able to discern the problem.


来源: stackexchange

问:
Lodash groupBy with moment
I am trying to group a bunch of dates by today, this week, this month and then previous months. However before I even get to this point I am struggling to get even a basic grouping by month.

```<code>const data = [{
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test77.com",
 createdAt: "2017-11-06T20:45:56.931Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-09-06T20:45:56.931Z",
 _id: "6gsb42PSSJt7PgsDG"
}, {
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test66,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-10-06T20:46:27.744Z",
 _id: "Md4wCnEsrQrWApnLS"
}, {
 campaign: "Gary",
 company_ID: "1",
 coreURL: "http://www.test55,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-07-06T20:46:27.744Z",
 _id: "5p44uiwRgqp35YXRf"
}
];

const grouper = 'updatedAt';

let groupedData = _
  .chain(data)
  .groupBy(datum => moment(datum.grouper).format("MM"))
</code>```

EDIT: However this only seems to group by "11" (todays Month)

Any help would be really appreciated

答:
datum.grouper is undefined so moment(datum.grouper) is returning the current date.

You should instead be using datum[grouper] or something like this _.property('updatedAt').

Regarding your question about how to separate the dates into today, this week, this month, and other months, please try the below:

const data = [{
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test77.com",
  createdAt: "2017-11-06T20:45:56.931Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-09-06T20:45:56.931Z",
  _id: "6gsb42PSSJt7PgsDG"
}, {
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test66,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-10-06T20:46:27.744Z",
  _id: "Md4wCnEsrQrWApnLS"
}, {
  campaign: "Gary",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-07-06T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-15T03:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-03T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-13T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-09T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}];

const groupProp = _.property('updatedAt');

let determineGroup = value => {
  // remove '2017-11-15' to actually use current date
  const now = moment('2017-11-15T10:00:03Z').startOf('day');

  if (value.isSame(now, 'day')) {
    return 'today';
  }
  if (value.isAfter(now.clone().subtract(7, 'days').startOf('day'))) {
    return 'this week';
  }
  if (value.isSame(now, 'month')) {
    return 'this month';
  }
  return value.format('MM');
};

let groupedData = _
  .chain(data)
  .groupBy(datum => determineGroup(moment(groupProp(datum))))
  .value()

console.log(groupedData);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Title: Lodash groupBy with moment

Body:
I am trying to group a bunch of dates by today, this week, this month and then previous months. However before I even get to this point I am struggling to get even a basic grouping by month.

const data = [{
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test77.com",
 createdAt: "2017-11-06T20:45:56.931Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-09-06T20:45:56.931Z",
 _id: "6gsb42PSSJt7PgsDG"
}, {
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test66,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-10-06T20:46:27.744Z",
 _id: "Md4wCnEsrQrWApnLS"
}, {
 campaign: "Gary",
 company_ID: "1",
 coreURL: "http://www.test55,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-07-06T20:46:27.744Z",
 _id: "5p44uiwRgqp35YXRf"
}
];

const grouper = 'updatedAt';

let groupedData = _
  .chain(data)
  .groupBy(datum => moment(datum.grouper).format("MM"))

EDIT: However this only seems to group by "11" (todays Month)

Any help would be really appreciated

Body:
datum.grouper is undefined so moment(datum.grouper) is returning the current date.

You should instead be using datum[grouper] or something like this _.property('updatedAt').

Regarding your question about how to separate the dates into today, this week, this month, and other months, please try the below:

const data = [{
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test77.com",
  createdAt: "2017-11-06T20:45:56.931Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-09-06T20:45:56.931Z",
  _id: "6gsb42PSSJt7PgsDG"
}, {
  campaign: "Charles",
  company_ID: "1",
  coreURL: "http://www.test66,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-10-06T20:46:27.744Z",
  _id: "Md4wCnEsrQrWApnLS"
}, {
  campaign: "Gary",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-07-06T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-15T03:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-03T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-13T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}, {
  campaign: "Fred",
  company_ID: "1",
  coreURL: "http://www.test55,com",
  createdAt: "2017-11-06T20:46:27.744Z",
  owner: "K7xTxu7PRDCuhFZRC",
  updatedAt: "2017-11-09T20:46:27.744Z",
  _id: "5p44uiwRgqp35YXRf"
}];

const groupProp = _.property('updatedAt');

let determineGroup = value => {
  // remove '2017-11-15' to actually use current date
  const now = moment('2017-11-15T10:00:03Z').startOf('day');

  if (value.isSame(now, 'day')) {
    return 'today';
  }
  if (value.isAfter(now.clone().subtract(7, 'days').startOf('day'))) {
    return 'this week';
  }
  if (value.isSame(now, 'month')) {
    return 'this month';
  }
  return value.format('MM');
};

let groupedData = _
  .chain(data)
  .groupBy(datum => determineGroup(moment(groupProp(datum))))
  .value()

console.log(groupedData);

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


问:
Rails, Paperclip not validating content type "application/octet-stream"?
I'm using paperclip to upload files of the mime-type "application/octet-stream", but they aren't validating properly.

In the controller, when I call replay.save!, I get the following error:

```<code>Validation failed: r_file has contents that are not what they are reported to be, r_file is invalid, r_file content type is invalid
</code>```

Here is the model:

```<code>class Replay < ApplicationRecord
    has_attached_file :r_file
    validates_attachment_content_type :r_file, content_type: { content_type: "application/octet-stream" }
end
</code>```

and the create method in the replay controller:

```<code>def create
    @replay = Replay.new(replay_params)
    if @replay.save
        # This never runs because it won't validate.
        puts "REPLAY SAVED."
        redirect_to @replay
    else
        puts "REPLAY NOT SAVED."
        render 'new'
    end
end
</code>```

I checked the mime-type of the file I'm trying to upload, and it is definitely of type "application/octet-stream". Is Paperclip just reading the file type incorrectly?

EDIT:

Here is the schema:

```<code>ActiveRecord::Schema.define(version: 20161203161351) do

  create_table "replays", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.string   "map"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
    t.string   "r_file_file_name"
    t.string   "r_file_content_type"
    t.integer  "r_file_file_size"
    t.datetime "r_file_updated_at"
  end

end
</code>```

答:
Validate all formats in rails Video/Image    </p>

```<code>validates_attachment_content_type :media,
      content_type: [
        'image/jpg',
        'image/jpeg',
        'image/pjpeg',
        'image/png',
        'image/x-png',
        'video/avi',
        'video/mov',
        'video/mp4',
        'video/x-flv',
        'video/3gpp',
        'video/quicktime',
        'video/x-msvideo',
        'video/x-ms-wmv',
        'flv-application/octet-stream',
        'application/octet-stream',
        'video/x-flv',
        'video/mpeg',
        'video/mpeg4',
        'video/x-la-asf',
        'video/x-ms-asf'
      ],
        :message => 'file type is not allowed'
</code>```

Body:
I'm using paperclip to upload files of the mime-type "application/octet-stream", but they aren't validating properly.

In the controller, when I call replay.save!, I get the following error:

Validation failed: r_file has contents that are not what they are reported to be, r_file is invalid, r_file content type is invalid

Here is the model:

class Replay < ApplicationRecord
    has_attached_file :r_file
    validates_attachment_content_type :r_file, content_type: { content_type: "application/octet-stream" }
end

and the create method in the replay controller:

def create
    @replay = Replay.new(replay_params)
    if @replay.save
        # This never runs because it won't validate.
        puts "REPLAY SAVED."
        redirect_to @replay
    else
        puts "REPLAY NOT SAVED."
        render 'new'
    end
end

I checked the mime-type of the file I'm trying to upload, and it is definitely of type "application/octet-stream". Is Paperclip just reading the file type incorrectly?

EDIT:

Here is the schema:

ActiveRecord::Schema.define(version: 20161203161351) do

  create_table "replays", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.string   "map"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
    t.string   "r_file_file_name"
    t.string   "r_file_content_type"
    t.integer  "r_file_file_size"
    t.datetime "r_file_updated_at"
  end

end

Body:
Validate all formats in rails Video/Image

validates_attachment_content_type :media,
      content_type: [
        'image/jpg',
        'image/jpeg',
        'image/pjpeg',
        'image/png',
        'image/x-png',
        'video/avi',
        'video/mov',
        'video/mp4',
        'video/x-flv',
        'video/3gpp',
        'video/quicktime',
        'video/x-msvideo',
        'video/x-ms-wmv',
        'flv-application/octet-stream',
        'application/octet-stream',
        'video/x-flv',
        'video/mpeg',
        'video/mpeg4',
        'video/x-la-asf',
        'video/x-ms-asf'
      ],
        :message => 'file type is not allowed'


问:
In Intellij Idea, how to keep showing context information?
I know for sure that by clicking hot key alt + q, the context of current method or class could show up just like:

But is there any way to make the IDE keep showing the context information at the top of the edit area?

答:
You can't keep the method definition for the 'currently active' method pinned to the top of the editor but if your goal is to display the method definition for the 'currently active' method while you are editing that method then you could use the Structure tool window and select Autoscroll from source. This will show you the definition of the method you are currently editing / your cursor is currently sitting in.

Here's a screenshot:

Autoscroll from source is the last icon on the right at the top of the Structure tool window.

You can activate the Structure tool window via keystokes (e.g. ALT 7), to identify the correct keystroke just have a look at the keystroke associated with the menu item: View > Tool Windows > Structure.

More details in the docs


问:
Change home page url using htaccess
In my framework, the home page is

```<code>http://localhost:8585/web1/dashboard
</code>```

I want to change that url of the home page to

```<code>http://localhost:8585/web1/
</code>```

I've tried both RewriteRule ^dashboard(.*)$ $1 and RewriteRule ^(index)$ /dashboard [L] but it didn't work.

答:
Let's dive in to the rules you have provided!

RewriteRule ^dashboard(.*)$ $1 Looking at the (.*) The meaning of the dot is that it can be any character (but only one). So .* means that it can be a lot of character. This is typically used to capture the entire requested url, without the domain. The $ at the end means quite literally that the host ends with the requested url (remember; that's without the domain) thus making no sense. How you should use these rules in a 301 redirect:

```<code>RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
</code>```

In this example we redirecting any traffic that is hitting our server, capturing the requested url and redirecting it to example.com with the captured url passed down as a parameter $1.

RewriteRule ^(index)$ /dashboard I can see where you are going with the second rewrite url. Trying to capture the index group and redirecting it to dashboard. In itself is a valid way to describe it but wrongly implemented. Based on our first explanation the (index)$ group states the requested url has to be index or else this rule won't be met. So.. that means it's never met because the url never will be just index.

What you have to do:
If you just want to redirect the dashboard page to web1/ you use a rule as follows:

```<code>RewriteRule    ^web1/dashboard/?$    web1/   [NC,L]
</code>```

This rule works for rewriting "http://localhost/web1/dashboard" to "http://localhost/web1/". However if you have pages behind the dashboard that need to be redirected as well you can apply this rule:

```<code>RewriteRule    ^web1/dashboard/(.*)$    web1/$1   [NC,L]
</code>```

Can you spot the difference? ;-)

Some sources:

htaccess tester, brilliant tool

URL Rewriting Guide - Apache docs

Title: Change home page url using htaccess

Body:
In my framework, the home page is

http://localhost:8585/web1/dashboard

I want to change that url of the home page to

http://localhost:8585/web1/

I've tried both RewriteRule ^dashboard(.*)$ $1 and RewriteRule ^(index)$ /dashboard [L] but it didn't work.

Body:
Let's dive in to the rules you have provided!

RewriteRule ^dashboard(.*)$ $1 Looking at the (.*) The meaning of the dot is that it can be any character (but only one). So .* means that it can be a lot of character. This is typically used to capture the entire requested url, without the domain. The $ at the end means quite literally that the host ends with the requested url (remember; that's without the domain) thus making no sense. How you should use these rules in a 301 redirect:

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

In this example we redirecting any traffic that is hitting our server, capturing the requested url and redirecting it to example.com with the captured url passed down as a parameter $1.

RewriteRule ^(index)$ /dashboard I can see where you are going with the second rewrite url. Trying to capture the index group and redirecting it to dashboard. In itself is a valid way to describe it but wrongly implemented. Based on our first explanation the (index)$ group states the requested url has to be index or else this rule won't be met. So.. that means it's never met because the url never will be just index.

What you have to do:
If you just want to redirect the dashboard page to web1/ you use a rule as follows:

RewriteRule    ^web1/dashboard/?$    web1/   [NC,L]

This rule works for rewriting "http://localhost/web1/dashboard" to "http://localhost/web1/". However if you have pages behind the dashboard that need to be redirected as well you can apply this rule:

RewriteRule    ^web1/dashboard/(.*)$    web1/$1   [NC,L]

Can you spot the difference? ;-)

Some sources:

htaccess tester, brilliant tool

URL Rewriting Guide - Apache docs


问:
How do I append to a file in hadoop?
I want to create a file in HDFS that has a bunch of lines, each generated by a different call to map. I don't care about the order of the lines, just that they all get added to the file. How do I accomplish this?

If this is not possible, then is there a standard way to generate unique file names to put each line of output into a separate file?

答: Both your map and reduce functions should output the lines. In other words, your reduce function is a pass through function that doesn't do much. Set the number of reducers to 1. The output will be a list of all the lines in one file.</p>

ContentLicense: CC BY-SA 2.5

Title: How do I append to a file in hadoop?


问:
How can we extract video URL from xml response
I am building a app in which i need to call a 3rd party api to play video directly on RHC box.
the party provided a url which is when it hit on url gives XML response.
how can i extract the video url from xml response.
Url :
http://something/math11072016part2.smil/jwplayer.smil

this type of Required URL :http://something/97760.mp4

答:
By applying the following xpath expression on the received XML, you'll get a list of video nodes:

```<code>smil/body/switch/video
</code>```

Body:
By applying the following xpath expression on the received XML, you'll get a list of video nodes:

smil/body/switch/video


问:
How to set if else with jQuery on hide show functions
I have a simple jQuery toggle button but I don't want to use toggleslide. If it is loaded homepage, the div must be opened and have a button to hide.
But if it is loaded another page, div must be closed and have button to show
HEre is two code, that doesn't work. I try to add them together in HTML but doesn't work

For homepage:

```<code>$(document).ready(function(){
   $("#flip").click(function(){
    if(window.location.href == 'http://homepage/')
       $("#panel").hide("fast");
   });
});
</code>```

for another page:

```<code>$(document).ready(function(){
   $("#flip").click(function(){
    if(window.location.href != 'http://homepage/')
       $("#panel").show("fast");
   });
});
</code>```

答:
This is what you want. I am taking input just to show you a demo.

var x = prompt("Whichpage is this ? ");
$(document).ready(function(){
  if(x == 'http://homepage/')
    $("#panel").show("fast");
  else
    $("#panel").hide("fast");
});

$("#flip").click(function(){
  $("#panel").toggle("fast");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="panel">I am a panel</div>
<button id="flip">Flip</button></code>```

For your case just set var x = window.location.href

Body:
I have a simple jQuery toggle button but I don't want to use toggleslide. If it is loaded homepage, the div must be opened and have a button to hide.
But if it is loaded another page, div must be closed and have button to show
HEre is two code, that doesn't work. I try to add them together in HTML but doesn't work

For homepage:

$(document).ready(function(){
   $("#flip").click(function(){
    if(window.location.href == 'http://homepage/')
       $("#panel").hide("fast");
   });
});

for another page:

$(document).ready(function(){
   $("#flip").click(function(){
    if(window.location.href != 'http://homepage/')
       $("#panel").show("fast");
   });
});

Body:
This is what you want. I am taking input just to show you a demo.

var x = prompt("Whichpage is this ? ");
$(document).ready(function(){
  if(x == 'http://homepage/')
    $("#panel").show("fast");
  else
    $("#panel").hide("fast");
});

$("#flip").click(function(){
  $("#panel").toggle("fast");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="panel">I am a panel</div>
<button id="flip">Flip</button>

For your case just set var x = window.location.href


问:
How to create an Azure Function that will POST to an Azure table?
I have created a simple backend using Azure Easy Tables and I was wondering how I could use Azure Functions to perform CRUD. Right now I'm using the javascript client SDK and have it on my website but I know that this is not at all secure to say the least.

Currently, I'm using a triggered Azure Function to send emails. I then call this function from my website. I wanted to do the same for my CRUD operations. Any help is appreciated!

```<code>    module.exports = function (context, requ) {
    context.log('JavaScript HTTP trigger function processed a request.');
    var http = require("https");

var options = {
  "method": "POST",
  "hostname": "EMAIL.API",
  "port": null,
  "path": "mail/send",
  "headers": {
    "authorization": "AUTH",
    "content-type": "application/json"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.write(JSON.stringify(
    { personalizations:
   [ { to: [ { email: requ.query.email, name: requ.query.name } ],
       subject: 'AutoConscience Registration' } ],
  from: { email: 'noreply@conscience.ac', name: 'AutoConscience Support Team' },
  reply_to: { email: '', name: 'alcovesdev' },
  subject: 'AutoConscience Registration',
</code>```

答:
you could use azure functions native way of writing to azure tables.

Javascript example.

Body:
I have created a simple backend using Azure Easy Tables and I was wondering how I could use Azure Functions to perform CRUD. Right now I'm using the javascript client SDK and have it on my website but I know that this is not at all secure to say the least.

Currently, I'm using a triggered Azure Function to send emails. I then call this function from my website. I wanted to do the same for my CRUD operations. Any help is appreciated!

    module.exports = function (context, requ) {
    context.log('JavaScript HTTP trigger function processed a request.');
    var http = require("https");

var options = {
  "method": "POST",
  "hostname": "EMAIL.API",
  "port": null,
  "path": "mail/send",
  "headers": {
    "authorization": "AUTH",
    "content-type": "application/json"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.write(JSON.stringify(
    { personalizations:
   [ { to: [ { email: requ.query.email, name: requ.query.name } ],
       subject: 'AutoConscience Registration' } ],
  from: { email: 'noreply@conscience.ac', name: 'AutoConscience Support Team' },
  reply_to: { email: '', name: 'alcovesdev' },
  subject: 'AutoConscience Registration',


问:
Removing subarrays that share a key-value pair with another multidimensional array
I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.

```<code>$array1 = Array
(
    [0] => Array
        (
            [stu_id] => 1
            [name] => mr.a
        )
    [1] => Array
        (
            [stu_id] => 3
            [name] => mr.b
        )
)

$array2 = Array
(
    [0] => Array
        (
            [id] => 1
            [stu_id] => 1
            [data] => abc
        )
    [1] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
    [3] => Array
        (
            [id] => 3
            [stu_id] => 3
            [data] => aaa
        )
)

$result_array = Array
(
    [0] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
)
</code>```

I tried array_diff, $result_array = array_diff($array2, $array1);  but it's not working.

Please help me to do this.

答:
```<code>foreach($array1 as $data1){
    foreach($array2 as $k => $data2){
        if($data2["stu_id"] == $data1["stu_id"]){
            unset($array2[$k]);
            break;
        }
    }
}
$result_array = $array2;
</code>```

Body:
I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.

$array1 = Array
(
    [0] => Array
        (
            [stu_id] => 1
            [name] => mr.a
        )
    [1] => Array
        (
            [stu_id] => 3
            [name] => mr.b
        )
)

$array2 = Array
(
    [0] => Array
        (
            [id] => 1
            [stu_id] => 1
            [data] => abc
        )
    [1] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
    [3] => Array
        (
            [id] => 3
            [stu_id] => 3
            [data] => aaa
        )
)

$result_array = Array
(
    [0] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
)

I tried array_diff, $result_array = array_diff($array2, $array1);  but it's not working.

Please help me to do this.


问:
MS SQL Server - Frequent Deadlock Issues
Target Database : MS SQL Server 2012

Requirement : Maintain summary of user’s workload in a table. Following is the table structure used to maintain this summary. Table is getting updated on modification of status of workitem assigned to user.

PARTICIPANT_ID   varchar NO  PK, Unique non clustered index

OFFERED_COUNT    numeric YES

ALLOCATED_COUNT  numeric YES

STARTED_COUNT    numeric YES

SUSPENDED_COUNT  numeric YES

Issue : We are facing frequent deadlocks on this table. Herewith I have attached deadlock graph for reference.

Investigation done so far :

Target Rows (Updates) in deadlocks are independent to each other so no question of one transaction waiting for other to relinquish lock.Even inserts to the table becomes part of deadlock.

Same transaction is working with similar concurrent load in Oracle.

Suspecting that table is getting locked instead of particular row, we even tried to disable escalation of locks at a table using following command but deadlocks persisted.

ALTER TABLE Table_name SET (LOCK_ESCALATION DISABLE)

Deadlock graph

```<code><deadlock>
 <victim-list>
  <victimProcess id="process133f03d498" />
 </victim-list>
 <process-list>
  <process id="process133f03d498" taskpriority="0" logused="3308" waitresource="RID: 11:1:819250:71" waittime="2377" ownerId="29578701" transactionname="implicit_transaction" lasttranstarted="2017-11-09T09:29:43.397" XDES="0x10b0b716a8" lockMode="U" schedulerid="6" kpid="7332" status="suspended" spid="210" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-11-09T09:29:45.977" lastbatchcompleted="2017-11-09T09:29:45.397" lastattention="1900-01-01T00:00:00.397" clientapp="jTDS" hostname="PAWSPPAS02" hostpid="123" loginname="STG_SUITE_SSO" isolationlevel="read committed (2)" xactid="29578701" currentdb="11" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
   <executionStack>
    <frame procname="adhoc" line="1" stmtstart="40" sqlhandle="0x02000000ee409c1fd278abb7f476707399656cbedec9d1960000000000000000000000000000000000000000">
update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]-1 where [PARTICIPANT_ID]= @P0    </frame>
   </executionStack>
   <inputbuf>
(@P0 nvarchar(4000))update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]-1 where [PARTICIPANT_ID]= @P0    </inputbuf>
  </process>
  <process id="processc70140188" taskpriority="0" logused="85392" waitresource="RID: 11:1:819250:30" waittime="2196" ownerId="29574187" transactionname="implicit_transaction" lasttranstarted="2017-11-09T09:29:16.427" XDES="0x1150f5d6a8" lockMode="U" schedulerid="4" kpid="384" status="suspended" spid="141" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-11-09T09:29:46.157" lastbatchcompleted="2017-11-09T09:29:45.470" lastattention="1900-01-01T00:00:00.470" clientapp="jTDS" hostname="PAWSPPAS02" hostpid="123" loginname="STG_SUITE_SSO" isolationlevel="read committed (2)" xactid="29574187" currentdb="11" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
   <executionStack>
    <frame procname="adhoc" line="1" stmtstart="40" sqlhandle="0x020000001c3c261d27cfa98e13a9cb06f6c30e40cfcaa4a50000000000000000000000000000000000000000">
update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]+1 where [PARTICIPANT_ID]= @P0    </frame>
   </executionStack>
   <inputbuf>
(@P0 nvarchar(4000))update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]+1 where [PARTICIPANT_ID]= @P0    </inputbuf>
  </process>
 </process-list>
 <resource-list>
  <ridlock fileid="1" pageid="819250" dbid="11" objectname="STG_SUITE_SSO.dbo.RS_WI_PARTICIPANT_SUMM" id="lock1236714900" mode="X" associatedObjectId="72057599198953472">
   <owner-list>
    <owner id="processc70140188" mode="X" />
   </owner-list>
   <waiter-list>
    <waiter id="process133f03d498" mode="U" requestType="wait" />
   </waiter-list>
  </ridlock>
  <ridlock fileid="1" pageid="819250" dbid="11" objectname="STG_SUITE_SSO.dbo.RS_WI_PARTICIPANT_SUMM" id="lockdacb14f00" mode="X" associatedObjectId="72057599198953472">
   <owner-list>
    <owner id="process133f03d498" mode="X" />
   </owner-list>
   <waiter-list>
    <waiter id="processc70140188" mode="U" requestType="wait" />
   </waiter-list>
  </ridlock>
 </resource-list>
</deadlock>
</code>```

答:
One thread has updated the row 819250:71 and now wants to update the row 819250:30, the other has updated the row 819250:30 and now wants to update the row 819250:71.

I can only speculate about what is going on here (since you are omitting so many details), but my guess is that the application has some logic that is updating two 'participants' in some sort of exchange and, inside a database transaction, is trying to increase one's amount +1 and then decrease the other one's amount -1. However, the application logic is doing it consistently in opposite order (on thread is doing in a transaction [A+=1, B-=1] while the other is doing it [B+=1, A-=1]). No schema design can prevent this deadlock, only application logic change. Look into why concurrent opposite updates are so frequent.

This does not seem to be a issue of using a non-unique non-clustered index on [PARTICIPANT_ID], because in that case the engine would locate the rows 819250:71 and 819250:30 in the same order for both statements and would not deadlock. Hence my conclusion that we have (at least) two update statements in a single transaction that updates two different rows (two @P0 values) and the app logic is updating the same set of participants in opposite order from 2 transactions (2 requests perhaps).

Furthermore:

```<code><process id="498" "RID: 11:1:819250:71" lasttranstarted="2017-11-09T09:29:43.397" lastbatchstarted="2017-11-09T09:29:45.977" lastbatchcompleted="2017-11-09T09:29:45.397"... >
<process id="188" "RID: 11:1:819250:30" lasttranstarted="2017-11-09T09:29:16.427" lastbatchstarted="2017-11-09T09:29:46.157" lastbatchcompleted="2017-11-09T09:29:45.470" ...>
</code>```

If you look at the two transactions:

process 1 started the transaction at 9:29:43.397, completed a batch at 9:29:45.397 and started the current batch at 9:29:45.977

process 2 started the transaction at 9:29:16.427, completed a batch at 9:29:45.470 and started the current batch at 9:29:46.157

This time sequence corroborates my hypothesis. The transactions contain a sequence of batches, indicating individual updates (eg. Entity Framework apply changes or similar),  which apply to different rows (different IDs). The IDs are overlapping and the updates are applied in inconsistent order (again, typical behavior of an ORM like EF applying changes).

If my speculation is right, then you should look at locking a higher level logical entity first. If these are participants, there must be something they participate into, like a game. Before updating the participants, lock the game: eg. using sp_getapplock on the [GAME_ID] at the start of the transaction. This way the order of updating the participants is no longer dangerous for deadlocks, because the updates are serialized for each game.

Other solution is to sort the participants before applying the updates so that every transaction updates the rows in the same order.

We do have only one non clustered index on [PARTICIPANT_ID] column

Almost certain this should be a clustered index. There are very few cases when having a non-clustered index and a heap make sense.

Body:
Target Database : MS SQL Server 2012

Requirement : Maintain summary of user’s workload in a table. Following is the table structure used to maintain this summary. Table is getting updated on modification of status of workitem assigned to user.

PARTICIPANT_ID   varchar NO  PK, Unique non clustered index

OFFERED_COUNT    numeric YES

ALLOCATED_COUNT  numeric YES

STARTED_COUNT    numeric YES

SUSPENDED_COUNT  numeric YES

Issue : We are facing frequent deadlocks on this table. Herewith I have attached deadlock graph for reference.

Investigation done so far :

Target Rows (Updates) in deadlocks are independent to each other so no question of one transaction waiting for other to relinquish lock.Even inserts to the table becomes part of deadlock.

Same transaction is working with similar concurrent load in Oracle.

Suspecting that table is getting locked instead of particular row, we even tried to disable escalation of locks at a table using following command but deadlocks persisted.

ALTER TABLE Table_name SET (LOCK_ESCALATION DISABLE)

Deadlock graph

<deadlock>
 <victim-list>
  <victimProcess id="process133f03d498" />
 </victim-list>
 <process-list>
  <process id="process133f03d498" taskpriority="0" logused="3308" waitresource="RID: 11:1:819250:71" waittime="2377" ownerId="29578701" transactionname="implicit_transaction" lasttranstarted="2017-11-09T09:29:43.397" XDES="0x10b0b716a8" lockMode="U" schedulerid="6" kpid="7332" status="suspended" spid="210" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-11-09T09:29:45.977" lastbatchcompleted="2017-11-09T09:29:45.397" lastattention="1900-01-01T00:00:00.397" clientapp="jTDS" hostname="PAWSPPAS02" hostpid="123" loginname="STG_SUITE_SSO" isolationlevel="read committed (2)" xactid="29578701" currentdb="11" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
   <executionStack>
    <frame procname="adhoc" line="1" stmtstart="40" sqlhandle="0x02000000ee409c1fd278abb7f476707399656cbedec9d1960000000000000000000000000000000000000000">
update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]-1 where [PARTICIPANT_ID]= @P0    </frame>
   </executionStack>
   <inputbuf>
(@P0 nvarchar(4000))update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]-1 where [PARTICIPANT_ID]= @P0    </inputbuf>
  </process>
  <process id="processc70140188" taskpriority="0" logused="85392" waitresource="RID: 11:1:819250:30" waittime="2196" ownerId="29574187" transactionname="implicit_transaction" lasttranstarted="2017-11-09T09:29:16.427" XDES="0x1150f5d6a8" lockMode="U" schedulerid="4" kpid="384" status="suspended" spid="141" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-11-09T09:29:46.157" lastbatchcompleted="2017-11-09T09:29:45.470" lastattention="1900-01-01T00:00:00.470" clientapp="jTDS" hostname="PAWSPPAS02" hostpid="123" loginname="STG_SUITE_SSO" isolationlevel="read committed (2)" xactid="29574187" currentdb="11" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128058">
   <executionStack>
    <frame procname="adhoc" line="1" stmtstart="40" sqlhandle="0x020000001c3c261d27cfa98e13a9cb06f6c30e40cfcaa4a50000000000000000000000000000000000000000">
update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]+1 where [PARTICIPANT_ID]= @P0    </frame>
   </executionStack>
   <inputbuf>
(@P0 nvarchar(4000))update [RS_WI_PARTICIPANT_SUMM] set [ALLOCATED_COUNT]=[ALLOCATED_COUNT]+1 where [PARTICIPANT_ID]= @P0    </inputbuf>
  </process>
 </process-list>
 <resource-list>
  <ridlock fileid="1" pageid="819250" dbid="11" objectname="STG_SUITE_SSO.dbo.RS_WI_PARTICIPANT_SUMM" id="lock1236714900" mode="X" associatedObjectId="72057599198953472">
   <owner-list>
    <owner id="processc70140188" mode="X" />
   </owner-list>
   <waiter-list>
    <waiter id="process133f03d498" mode="U" requestType="wait" />
   </waiter-list>
  </ridlock>
  <ridlock fileid="1" pageid="819250" dbid="11" objectname="STG_SUITE_SSO.dbo.RS_WI_PARTICIPANT_SUMM" id="lockdacb14f00" mode="X" associatedObjectId="72057599198953472">
   <owner-list>
    <owner id="process133f03d498" mode="X" />
   </owner-list>
   <waiter-list>
    <waiter id="processc70140188" mode="U" requestType="wait" />
   </waiter-list>
  </ridlock>
 </resource-list>
</deadlock>

Body:
One thread has updated the row 819250:71 and now wants to update the row 819250:30, the other has updated the row 819250:30 and now wants to update the row 819250:71.

I can only speculate about what is going on here (since you are omitting so many details), but my guess is that the application has some logic that is updating two 'participants' in some sort of exchange and, inside a database transaction, is trying to increase one's amount +1 and then decrease the other one's amount -1. However, the application logic is doing it consistently in opposite order (on thread is doing in a transaction [A+=1, B-=1] while the other is doing it [B+=1, A-=1]). No schema design can prevent this deadlock, only application logic change. Look into why concurrent opposite updates are so frequent.

This does not seem to be a issue of using a non-unique non-clustered index on [PARTICIPANT_ID], because in that case the engine would locate the rows 819250:71 and 819250:30 in the same order for both statements and would not deadlock. Hence my conclusion that we have (at least) two update statements in a single transaction that updates two different rows (two @P0 values) and the app logic is updating the same set of participants in opposite order from 2 transactions (2 requests perhaps).

Furthermore:

<process id="498" "RID: 11:1:819250:71" lasttranstarted="2017-11-09T09:29:43.397" lastbatchstarted="2017-11-09T09:29:45.977" lastbatchcompleted="2017-11-09T09:29:45.397"... >
<process id="188" "RID: 11:1:819250:30" lasttranstarted="2017-11-09T09:29:16.427" lastbatchstarted="2017-11-09T09:29:46.157" lastbatchcompleted="2017-11-09T09:29:45.470" ...>

If you look at the two transactions:

process 1 started the transaction at 9:29:43.397, completed a batch at 9:29:45.397 and started the current batch at 9:29:45.977

process 2 started the transaction at 9:29:16.427, completed a batch at 9:29:45.470 and started the current batch at 9:29:46.157

This time sequence corroborates my hypothesis. The transactions contain a sequence of batches, indicating individual updates (eg. Entity Framework apply changes or similar),  which apply to different rows (different IDs). The IDs are overlapping and the updates are applied in inconsistent order (again, typical behavior of an ORM like EF applying changes).

If my speculation is right, then you should look at locking a higher level logical entity first. If these are participants, there must be something they participate into, like a game. Before updating the participants, lock the game: eg. using sp_getapplock on the [GAME_ID] at the start of the transaction. This way the order of updating the participants is no longer dangerous for deadlocks, because the updates are serialized for each game.

Other solution is to sort the participants before applying the updates so that every transaction updates the rows in the same order.

We do have only one non clustered index on [PARTICIPANT_ID] column

Almost certain this should be a clustered index. There are very few cases when having a non-clustered index and a heap make sense.


问:
Python: Why am I getting a "ZeroDivisionError: division by zero" in function?
My goal is to count the total amount of tweets in a file that fall under certain time zones.
I have the following function (I have noted the trouble area near the end of the function with comments):

```<code>def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0

for line in inFile:
    entry = line.split()

    for n in range(0, len(entry) - 1):
        entry[n] = entry[n].strip("[],!?#./-=+_@")
        if n > 4:   # n>4 because words begin on 5th index of list
            entry[n] = entry[n].lower()
            words.append(entry[n])

    lat = float(entry[0])
    long = float(entry[1])

    timezone = getTimeZone(lat, long)
    if timezone == "eastern":
        easternTweets += 1
    if timezone == "central":
        centralTweets += 1
    if timezone == "mountain":
        mountainTweets += 1
    if timezone == "pacific":
        pacificTweets += 1

    for i in range(0, len(words)):
        for k in range(0, len(keyword)):
            if words[i] == keyword[k]:
                value = int(sents[k])
                if timezone == "eastern":
                    eastern += value
                    a += 1
                if timezone == "central":
                    central += value
                    b += 1
                if timezone == "mountain":
                    mountain += value
                    c += 1
                if timezone == "pacific":
                    pacific += value
                    d += 1

# the values of a,b,c,d are 0
easternTotal = eastern/a    # getting error
centralTotal = central/b    # for
mountainTotal = mountain/c  # these
pacificTotal = pacific/d    # values

print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)
</code>```

I am getting a ZeroDivisionError: division by zero error for easternTotal and the other total values that use a, b, c, and d for division.

If I print the values of a, b, c, or d it shows 0. My question is why are their values 0? Does the value of a, b, c, and d not change in the if statements?

答:
you divide eastern by 0. You can avoid it by doing

```<code>easternTotal = eastern/a if a > 0 else eastern
</code>```

Body:
My goal is to count the total amount of tweets in a file that fall under certain time zones.
I have the following function (I have noted the trouble area near the end of the function with comments):

def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0

for line in inFile:
    entry = line.split()

    for n in range(0, len(entry) - 1):
        entry[n] = entry[n].strip("[],!?#./-=+_@")
        if n > 4:   # n>4 because words begin on 5th index of list
            entry[n] = entry[n].lower()
            words.append(entry[n])

    lat = float(entry[0])
    long = float(entry[1])

    timezone = getTimeZone(lat, long)
    if timezone == "eastern":
        easternTweets += 1
    if timezone == "central":
        centralTweets += 1
    if timezone == "mountain":
        mountainTweets += 1
    if timezone == "pacific":
        pacificTweets += 1

    for i in range(0, len(words)):
        for k in range(0, len(keyword)):
            if words[i] == keyword[k]:
                value = int(sents[k])
                if timezone == "eastern":
                    eastern += value
                    a += 1
                if timezone == "central":
                    central += value
                    b += 1
                if timezone == "mountain":
                    mountain += value
                    c += 1
                if timezone == "pacific":
                    pacific += value
                    d += 1

# the values of a,b,c,d are 0
easternTotal = eastern/a    # getting error
centralTotal = central/b    # for
mountainTotal = mountain/c  # these
pacificTotal = pacific/d    # values

print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)

I am getting a ZeroDivisionError: division by zero error for easternTotal and the other total values that use a, b, c, and d for division.

If I print the values of a, b, c, or d it shows 0. My question is why are their values 0? Does the value of a, b, c, and d not change in the if statements?

Body:
you divide eastern by 0. You can avoid it by doing

easternTotal = eastern/a if a > 0 else eastern


问:
Array of Array of structs in c99
I am trying to implement hash maps in c. I am trying to go about this by creating a struct to hold the hash and key like this.

```<code>struct bucket{
char * key;
char * value;
};
</code>```

Then i am create an array of these structs to hold all the hashs that are the same but with different keys. like so:

```<code>struct bucket * buckets;
buckets = malloc(numberOfBuckets);
</code>```

Then where i am getting stuck is making an array to store these arrays in. I thought it was done like this:

```<code>struct bucket * arrayOfArrays;
arrayOfArrays = malloc(++numberOfKeys);
arrayOfArrays[0] = buckets;
</code>```

which is giving me the error:

```<code>incompatible types when assigning to type 'struct bucket' from type 'struct bucket *'
</code>```

答:
```<code>struct bucket * arrayOfArrays;
arrayOfArrays[0] = buckets;
</code>```

Change this to

```<code>struct bucket ** arrayOfArrays;
arrayOfArrays = malloc(sizeof(struct bucket *) * numberOfArrays);
arrayOfArrays[0] = buckets;
</code>```

And it should work for you.

You also need to change the first allocation to get enough bytes:

```<code>struct bucket * buckets;
buckets = malloc(sizeof(struct bucket) * numberOfBuckets);
</code>```

Title: Array of Array of structs in c99

Body:
I am trying to implement hash maps in c. I am trying to go about this by creating a struct to hold the hash and key like this.

struct bucket{
char * key;
char * value;
};

Then i am create an array of these structs to hold all the hashs that are the same but with different keys. like so:

struct bucket * buckets;
buckets = malloc(numberOfBuckets);

Then where i am getting stuck is making an array to store these arrays in. I thought it was done like this:

struct bucket * arrayOfArrays;
arrayOfArrays = malloc(++numberOfKeys);
arrayOfArrays[0] = buckets;

which is giving me the error:

incompatible types when assigning to type 'struct bucket' from type 'struct bucket *'

Body:
struct bucket * arrayOfArrays;
arrayOfArrays[0] = buckets;

Change this to

struct bucket ** arrayOfArrays;
arrayOfArrays = malloc(sizeof(struct bucket *) * numberOfArrays);
arrayOfArrays[0] = buckets;

And it should work for you.

You also need to change the first allocation to get enough bytes:

struct bucket * buckets;
buckets = malloc(sizeof(struct bucket) * numberOfBuckets);


问:
Can't get an object's class name in Python
I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object:

```<code>>>> import re
>>> x = re.compile('test')
>>> x.__class__.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __class__
</code>```

...

```<code>>>> type(x)
<type '_sre.SRE_Pattern'>
>>> isinstance(x, _sre.SRE_Pattern)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_sre' is not defined
>>>
>>>
>>> isinstance(x, '_sre.SRE_Pattern')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
>>>
</code>```

Any ideas?

答:
```<code>In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True

In [14]: type(type(x))
Out[14]: <type 'type'>
</code>```

I think it relates to the type/object subtilities and to the re module implemetation. You can read a nice article here.

Body:
I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object:

>>> import re
>>> x = re.compile('test')
>>> x.__class__.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __class__

...

>>> type(x)
<type '_sre.SRE_Pattern'>
>>> isinstance(x, _sre.SRE_Pattern)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_sre' is not defined
>>>
>>>
>>> isinstance(x, '_sre.SRE_Pattern')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
>>>

Any ideas?

Body:
In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True

In [14]: type(type(x))
Out[14]: <type 'type'>

I think it relates to the type/object subtilities and to the re module implemetation. You can read a nice article here.


问:
Java - ArrayList<> and LinkedList<> - class as an identifier
https://imgur.com/nb6sjuK

I don't get it what the identifier  does in this example, I'm new with programming and what I realize is that ArrayList<String> creates the list of Strings and same with LinkedList<String> but what happens when you push a class in the identifier, like - LinkedList<Song> - and Song is a class . Thanks in advance.

```<code>public class Main {
    private static ArrayList<Album> albums = new ArrayList<Album>();

    LinkedList<Song> playlist = new LinkedList<Song>();

    public static void main(String[] args) {

    // write your code here

        Album album = new Album("StormBringer" , "Deep Purple");
        album.addSong("Stormbringer" , 4.6);
        album.addSong("Love don't mean a thing" , 4.22);
</code>```

答:
but what happens when you push a class in the identifier?

First of all it's not an identifier it's a Type, and this is how Generics works, you pass a Type between <>, so the compiler knows the expected Type for this Generic class (here the Collection). And Collections List, Set... are good examples for Generics implementations.

And like Song is a class String is also a predefined class in the java.lang package, so when you pass a class to your collection, the compiler will expect that all the elements in this collection are of this Type.

For example in your code:

```<code>LinkedList<Song> playlist = new LinkedList<Song>();
</code>```

All playlist items are expected to be instances of Song class.

Body:
https://imgur.com/nb6sjuK

I don't get it what the identifier  does in this example, I'm new with programming and what I realize is that ArrayList<String> creates the list of Strings and same with LinkedList<String> but what happens when you push a class in the identifier, like - LinkedList<Song> - and Song is a class . Thanks in advance.

public class Main {
    private static ArrayList<Album> albums = new ArrayList<Album>();

    LinkedList<Song> playlist = new LinkedList<Song>();

    public static void main(String[] args) {

    // write your code here

        Album album = new Album("StormBringer" , "Deep Purple");
        album.addSong("Stormbringer" , 4.6);
        album.addSong("Love don't mean a thing" , 4.22);

Body:
but what happens when you push a class in the identifier?

First of all it's not an identifier it's a Type, and this is how Generics works, you pass a Type between <>, so the compiler knows the expected Type for this Generic class (here the Collection). And Collections List, Set... are good examples for Generics implementations.

And like Song is a class String is also a predefined class in the java.lang package, so when you pass a class to your collection, the compiler will expect that all the elements in this collection are of this Type.

For example in your code:

LinkedList<Song> playlist = new LinkedList<Song>();

All playlist items are expected to be instances of Song class.


问:
Spring security custom logout null pointer exception
What I'd like my code to do: When user logs in I want to use default Spring Security to log him in. Then in LoginSuccessHandler I'm creating and saving to a databse a token. Using default logout, in LogoutSuccessHandler I need to delete the token from database.

My issue: I'm using Spring Security for login and logout. Login works correctly.  Logout used to work correctly as well, but a couple of days ago I started receiving NullPointerException which is caused by null Authentication in LogoutSuccessHandler. Also, I'd like my API to be as stateless as possible. But I'm wondering; should I disable creating session for Spring Security will login/logout still work or does it need to create some king of session? I googled a couple of questions about it, but majority of them suggested that something is wrong with configuration. I tried a couple of different ones, unfortunately none worked.

My code:
WebSecurityConfig.java

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RESTAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private RESTAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    @Autowired
    private RESTAuthenticationFailureHandler restAuthenticationFailureHandler;
    @Autowired
    private RESTLogoutSuccessHandler restLogoutSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("**/anna/**").authenticated()
                .anyRequest().permitAll();

        http
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(restLogoutSuccessHandler);

//        http.sessionManagement()
//                .sessionCreationPolicy(SessionCreationPolicy.NEVER);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
}
</code>```

RESTLogoutSuccessHandler.java

```<code>@Component
public class RESTLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private UserRepository userRepository;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {

        User authUser = (User) authentication.getPrincipal();
        String userName = authUser.getUsername();
        com.shareabook.model.User user = userRepository.findByUserName(userName);
        user.setToken("");
        userRepository.save(user);
    }
}
</code>```

Stacktrace

```<code>java.lang.NullPointerException: null
    at com.shareabook.security.RESTLogoutSuccessHandler.onLogoutSuccess(RESTLogoutSuccessHandler.java:28) ~[classes/:na]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:111) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_77]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_77]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_77]
</code>```

答:
authUser is null that is the cause for the exeception.

authUser is null because the LogoutFilter invoke the LogoutHandler before it invoke the logoutSuccessHandler.onLogoutSuccess.

LogoutFilter:

```<code>public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (requiresLogout(request, response)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (logger.isDebugEnabled()) {
            logger.debug("Logging out user '" + auth
                    + "' and transferring to logout destination");
        }

        this.handler.logout(request, response, auth);

        logoutSuccessHandler.onLogoutSuccess(request, response, auth);

        return;
    }

    chain.doFilter(request, response);
}
</code>```

A typical LogoutHander implementation like SpringContextLogoutHander clear the authentication. But you can disable this behavior by setting clearAuthentication to false

SecurityContextLogoutHandler:

```<code>public void logout(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) {
    Assert.notNull(request, "HttpServletRequest required");
    if (invalidateHttpSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            logger.debug("Invalidating session: " + session.getId());
            session.invalidate();
        }
    }

    if (clearAuthentication) {
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
    }

    SecurityContextHolder.clearContext();
}
</code>```

Body:
What I'd like my code to do: When user logs in I want to use default Spring Security to log him in. Then in LoginSuccessHandler I'm creating and saving to a databse a token. Using default logout, in LogoutSuccessHandler I need to delete the token from database.

My issue: I'm using Spring Security for login and logout. Login works correctly.  Logout used to work correctly as well, but a couple of days ago I started receiving NullPointerException which is caused by null Authentication in LogoutSuccessHandler. Also, I'd like my API to be as stateless as possible. But I'm wondering; should I disable creating session for Spring Security will login/logout still work or does it need to create some king of session? I googled a couple of questions about it, but majority of them suggested that something is wrong with configuration. I tried a couple of different ones, unfortunately none worked.

My code:
WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RESTAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private RESTAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    @Autowired
    private RESTAuthenticationFailureHandler restAuthenticationFailureHandler;
    @Autowired
    private RESTLogoutSuccessHandler restLogoutSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("**/anna/**").authenticated()
                .anyRequest().permitAll();

        http
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(restLogoutSuccessHandler);

//        http.sessionManagement()
//                .sessionCreationPolicy(SessionCreationPolicy.NEVER);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
}

RESTLogoutSuccessHandler.java

@Component
public class RESTLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private UserRepository userRepository;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {

        User authUser = (User) authentication.getPrincipal();
        String userName = authUser.getUsername();
        com.shareabook.model.User user = userRepository.findByUserName(userName);
        user.setToken("");
        userRepository.save(user);
    }
}

Stacktrace

java.lang.NullPointerException: null
    at com.shareabook.security.RESTLogoutSuccessHandler.onLogoutSuccess(RESTLogoutSuccessHandler.java:28) ~[classes/:na]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:111) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_77]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_77]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_77]

Body:
authUser is null that is the cause for the exeception.

authUser is null because the LogoutFilter invoke the LogoutHandler before it invoke the logoutSuccessHandler.onLogoutSuccess.

LogoutFilter:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (requiresLogout(request, response)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (logger.isDebugEnabled()) {
            logger.debug("Logging out user '" + auth
                    + "' and transferring to logout destination");
        }

        this.handler.logout(request, response, auth);

        logoutSuccessHandler.onLogoutSuccess(request, response, auth);

        return;
    }

    chain.doFilter(request, response);
}

A typical LogoutHander implementation like SpringContextLogoutHander clear the authentication. But you can disable this behavior by setting clearAuthentication to false

SecurityContextLogoutHandler:

public void logout(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) {
    Assert.notNull(request, "HttpServletRequest required");
    if (invalidateHttpSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            logger.debug("Invalidating session: " + session.getId());
            session.invalidate();
        }
    }

    if (clearAuthentication) {
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
    }

    SecurityContextHolder.clearContext();
}


问:
Should I use @PostContruct or Context refresh event to connect to CTI server
I am developing a REST service which will connect to a CTI server through TCP and the connection will be kept opened until the my REST service is running.

Currently I am reading the server parameters from properties file and creating bean, after the bean is constructed, the server connection will be initiated using @PostConstruct. Is it good to use @PostConstruct for this scenario or should I use context refresh event.

I tested application using both @PostConstruct and context refresh, both are working good how ever I want to follow the best practices.

Note : I searched the forum and got some answers, but not related to my scenario

答: Technically there is no difference. You have already tested that part. I think @PostConstruct makes more sense mainly because the connection you are creating is specific to this bean. Creating a new ApplicationContextListener wouldn't make much sense as the connection is not at a context level.


问:
How to update recyclerview when an activity is deleted which is open from recyclerview adapter
I am using Recyclerview adapter to populate Recyclerview. After populating Recyclerview from SQLite, If user want to open an recyclerview item need to click on that item and adapter open the related activity. Here is an image which can help you understand easily.

When an activity is open user can delete that post from SQLite by clicking delete button after deleting data recyclerview should dynamically update data.

答:
if you display list of companies in recyclerview once you click to show detailes of company and you delete the company once back you should found the item disappear this what my code do</p>

```<code> protected void onResume()
{
    super.onResume();
    Log.i("TAG", "resume");
    if(yourlist.size() > 0)
    {
        yourlist.clear();
        yourlist.addAll(where your data come from
        ex:databaseHelper.GetOrganization());
        youradapter.notifyDataSetChanged();
    }
}
</code>```

Body:
if you display list of companies in recyclerview once you click to show detailes of company and you delete the company once back you should found the item disappear this what my code do

 protected void onResume()
{
    super.onResume();
    Log.i("TAG", "resume");
    if(yourlist.size() > 0)
    {
        yourlist.clear();
        yourlist.addAll(where your data come from
        ex:databaseHelper.GetOrganization());
        youradapter.notifyDataSetChanged();
    }
}


问:
Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides

I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/

I get the following Exception:

```<code>2014-02-14 16:25:21.614  INFO 9032 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638  INFO 9032 --- [           main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
    at hu.kumite.Application.main(Application.java:17)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
    ... 7 more
</code>```

The application starter class is this:

```<code>@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTasks.class, args);
    }
}
</code>```

As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:

```<code>@EnableScheduling
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}
</code>```

I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?

答:
Problem is exclusion of starter tomcat, I tried exclude it and use vert.x, so when I integrate wit Spring Admin, started problems</p>

```<code><dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides

I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/

I get the following Exception:

2014-02-14 16:25:21.614  INFO 9032 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638  INFO 9032 --- [           main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
    at hu.kumite.Application.main(Application.java:17)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
    ... 7 more

The application starter class is this:

@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTasks.class, args);
    }
}

As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:

@EnableScheduling
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}

I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?

Body:
Problem is exclusion of starter tomcat, I tried exclude it and use vert.x, so when I integrate wit Spring Admin, started problems

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>