问:
How Do I Create Multiple Service Bus Topics Using Multiple ARM Templates?
I was wondering if there was a quick and dirty way to create new topics on an already-created Service Bus using a separate template?

Lets assume I have 2 templates, both with their own respective resources. Now, at the command prompt they have the option to deploy template1, template2, or BOTH. If template1 is selected, it should deploy its resources along with a Service Bus and a topic named 'Topic-Template1' -- And if template2 is chosen, it should do the same, but with a topic named 'Topic-Template2' -- However, if 'BOTH' is chosen as the parameter value, then I would like to deploy ONE Service Bus still, but now have TWO topics: 'Topic-Template1' & 'Topic-Template2'.

Is there a way to do this using only these two templates without them being nested and also assuming I'm doing so by calling for two new deployment commands in sequence from a PowerShell script if 'BOTH' is chosen

Assuming this is the logic in the PowerShell script for deploying template1 or template2:

```<code># Determine which application to deploy
switch ($ApplicationDeployment.ToLower())
{
    #Deploys template1
    "template1" {
        New-AzureRmResourceGroupDeployment -Name "temp1-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp1TemplateFile -TemplateParameterFile $temp1TemplateParametersFile `
                                    -Force -Verbose 2>> $temp1ErrorFileName | Out-File $temp1LogFileName -ErrorVariable ErrorMessages
    }

    #Deploys template2
    "template2" {
        New-AzureRmResourceGroupDeployment -Name "temp2-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp2TemplateFile -TemplateParameterFile $temp2TemplateParametersFile `
                                    -Force -Verbose 2>> $temp2ErrorFileName | Out-File $temp2LogFileName -ErrorVariable ErrorMessages
    }

    #Deploys both the template1 & template2 templates
    "both" {
        New-AzureRmResourceGroupDeployment -Name "temp1-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp1TemplateFile -TemplateParameterFile $temp1TemplateParametersFile `
                                    -Force -Verbose 2>> $temp1ErrorFileName | Out-File $temp1LogFileName -ErrorVariable ErrorMessagess

        New-AzureRmResourceGroupDeployment -Name "temp2-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp2TemplateFile -TemplateParameterFile $temp2TemplateParametersFile `
                                    -Force -Verbose 2>> $temp2ErrorFileName | Out-File $temp2LogFileName -ErrorVariable ErrorMessages
    }
</code>```

答:
I don't see any problem with that, just create 2 templates and make them do what you are trying to make them do. It will just work.

But your approach is flawed at best, it is better to incorporate that logic in the template and make the template decide what to deploy based on your input

Body:
I was wondering if there was a quick and dirty way to create new topics on an already-created Service Bus using a separate template?

Lets assume I have 2 templates, both with their own respective resources. Now, at the command prompt they have the option to deploy template1, template2, or BOTH. If template1 is selected, it should deploy its resources along with a Service Bus and a topic named 'Topic-Template1' -- And if template2 is chosen, it should do the same, but with a topic named 'Topic-Template2' -- However, if 'BOTH' is chosen as the parameter value, then I would like to deploy ONE Service Bus still, but now have TWO topics: 'Topic-Template1' & 'Topic-Template2'.

Is there a way to do this using only these two templates without them being nested and also assuming I'm doing so by calling for two new deployment commands in sequence from a PowerShell script if 'BOTH' is chosen

Assuming this is the logic in the PowerShell script for deploying template1 or template2:

# Determine which application to deploy
switch ($ApplicationDeployment.ToLower())
{
    #Deploys template1
    "template1" {
        New-AzureRmResourceGroupDeployment -Name "temp1-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp1TemplateFile -TemplateParameterFile $temp1TemplateParametersFile `
                                    -Force -Verbose 2>> $temp1ErrorFileName | Out-File $temp1LogFileName -ErrorVariable ErrorMessages
    }

    #Deploys template2
    "template2" {
        New-AzureRmResourceGroupDeployment -Name "temp2-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp2TemplateFile -TemplateParameterFile $temp2TemplateParametersFile `
                                    -Force -Verbose 2>> $temp2ErrorFileName | Out-File $temp2LogFileName -ErrorVariable ErrorMessages
    }

    #Deploys both the template1 & template2 templates
    "both" {
        New-AzureRmResourceGroupDeployment -Name "temp1-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp1TemplateFile -TemplateParameterFile $temp1TemplateParametersFile `
                                    -Force -Verbose 2>> $temp1ErrorFileName | Out-File $temp1LogFileName -ErrorVariable ErrorMessagess

        New-AzureRmResourceGroupDeployment -Name "temp2-$(get-date -f yyyy-MM-dd)" -ResourceGroupName $ResourceGroupName `
                                    -TemplateFile $temp2TemplateFile -TemplateParameterFile $temp2TemplateParametersFile `
                                    -Force -Verbose 2>> $temp2ErrorFileName | Out-File $temp2LogFileName -ErrorVariable ErrorMessages
    }


来源: stackexchange

问:
How to finish all activity when move to other modul via sidemenu
I will explain my problem:

I have 4 main menus can access from Dashboard page such as :

Menu A

Menu B

Menu C

Menu D

Inside each menu there are sub menu , so the tree of menus will look like (ALL Menu is an independent Activity):

Menu A -> SubA-1 -> SubA-2

Menu B -> SubB-1 -> SubB-2

Menu C -> SubC-1 -> SubC-2

Menu D -> SubD-1 -> SubD-2

When i access menu A to SubA-1 and then SubA-2. So now i inside SubA-2.
I move to Menu B from SubA-2.

From Menu B i access SubB-1. So Now i inside SubB-1. When i pressed back button i will move sequence like this :
SubB-1 -> Menu B -> SubA-2 -> SubA-1 -> Menu A

How to avoid Menu A Activity still called when pressed back button (but don't give suggest to block the back button)? I use this but not working perfectly :

```<code>intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

If you need more information about case you can put in the comment below.

UPDATED :

User not allowed back to menuA if they come from MenuB. But They still
  alowed back to Menu A if they come from subA-1 (sub menu of menu A).

Thank you.

答:
The reason why it happens is because the Android Activity has a default function wherein when you intent and not specify the type of intent, it will be by default put the activity in the backstack. In order to avoid that you just simply clear the backstack except the First one on startActivity like this

```<code>Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
</code>```

But what I think when you are doing a submenu type application, it is best to use fragment rather than activity.

ContentLicense: CC BY-SA 3.0

Body:
I will explain my problem:

I have 4 main menus can access from Dashboard page such as :

Menu A

Menu B

Menu C

Menu D

Inside each menu there are sub menu , so the tree of menus will look like (ALL Menu is an independent Activity):

Menu A -> SubA-1 -> SubA-2

Menu B -> SubB-1 -> SubB-2

Menu C -> SubC-1 -> SubC-2

Menu D -> SubD-1 -> SubD-2

When i access menu A to SubA-1 and then SubA-2. So now i inside SubA-2.
I move to Menu B from SubA-2.

From Menu B i access SubB-1. So Now i inside SubB-1. When i pressed back button i will move sequence like this :
SubB-1 -> Menu B -> SubA-2 -> SubA-1 -> Menu A

How to avoid Menu A Activity still called when pressed back button (but don't give suggest to block the back button)? I use this but not working perfectly :

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

If you need more information about case you can put in the comment below.

UPDATED :

User not allowed back to menuA if they come from MenuB. But They still
  alowed back to Menu A if they come from subA-1 (sub menu of menu A).

Thank you.

Body:
The reason why it happens is because the Android Activity has a default function wherein when you intent and not specify the type of intent, it will be by default put the activity in the backstack. In order to avoid that you just simply clear the backstack except the First one on startActivity like this

Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

But what I think when you are doing a submenu type application, it is best to use fragment rather than activity.


问:
React - Empty Array When Rendering JSON Data
Why is an empty array created when rendering this JSON array? See attached screenshot  I assume the constructor is just initiating it with a null value and filling it at a later point.

New to Javascript + React and just want to make sure I am understanding what is happening.  I will also accept critique on the garbage code that is below. Codepen link

```<code>class Jobs extends React.Component {
  render() {
    const jobs = this.props.jobs;
    console.log(jobs);
    const formattedJobs = jobs.map((job) =>
      <ul key={job.id}>
        <div class="company">{job.company_name}</div>
        <div class="title">{job.title}</div>
      </ul>
    );
    return(
      <div>{formattedJobs}</div>
    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state={
      jobs:[]
    }
  var myUrl = "https://codepen.io/jobs.json";
  fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
  }

  render() {
    return (
    <div className="app">
      <div className="header">
        <h1 id="header-title">Job Postings</h1>
      </div>
      <div className="content">
        <Jobs jobs={this.state.jobs}/>
      </div>
    </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

答:
always use fetch statements in ComponentDidMount as it is called just after your component is rendered for the very first time</p>

```<code>ComponentDidMount {
 fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
}
</code>```

Body:
Why is an empty array created when rendering this JSON array? See attached screenshot  I assume the constructor is just initiating it with a null value and filling it at a later point.

New to Javascript + React and just want to make sure I am understanding what is happening.  I will also accept critique on the garbage code that is below. Codepen link

class Jobs extends React.Component {
  render() {
    const jobs = this.props.jobs;
    console.log(jobs);
    const formattedJobs = jobs.map((job) =>

{job.company_name}

{job.title}

    );
    return(

{formattedJobs}

    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state={
      jobs:[]
    }
  var myUrl = "https://codepen.io/jobs.json";
  fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
  }

  render() {
    return (

Job Postings

        <Jobs jobs={this.state.jobs}/>

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Body:
always use fetch statements in ComponentDidMount as it is called just after your component is rendered for the very first time

ComponentDidMount {
 fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
}


问:
How to remove system redirect message from screen
I am getting dhcp server status using
service dhcpd status. Result is

Redirecting to /bin/systemctl status  dhcpd.service
  ● dhcpd.service - DHCPv4 Server Daemon
     Loaded: loaded (/usr/lib/systemd/system/dhcpd.service; enabled; vendor preset: disabled)

Active: active (running) since......

I just want to extract active and send to php (Zend) server. To do it, I used

service dhcpd status | awk '{for (I=1;I<=NF;I++) if ($I == "Active:") {print $(I+1)};}'

Result is

Redirecting to /bin/systemctl status  dhcpd.service

active

I just don't understand how to remove Redirecting to /bin/systemctl status  dhcpd.service part from the result.

I have tried these answers, but they were not addressing my issue.

Am I missing something? or is there a better way to do it? I am not familiar with shell scripts.

Thanks in advance.

答:
Just use Awk looking for the Active: string and print the status

```<code>service dhcpd status 2>&1 | awk '$1=="Active:"{print $2}'
</code>```

The part $1="Active:" looks up the line whose first column value is Active: and print the next column value which is the status you are looking for.

As suggested above, redirect the stderr, the standard error stream to stdout and apply Awk on it to filter the error message.

As suggested by anubhava in comments you could use |& in recent versions of bash to redirect stderr to stdout as

```<code>service dhcpd status |& awk '$1=="Active:"{print $2}'
</code>```

Body:
Just use Awk looking for the Active: string and print the status

service dhcpd status 2>&1 | awk '$1=="Active:"{print $2}'

The part $1="Active:" looks up the line whose first column value is Active: and print the next column value which is the status you are looking for.

As suggested above, redirect the stderr, the standard error stream to stdout and apply Awk on it to filter the error message.

As suggested by anubhava in comments you could use |& in recent versions of bash to redirect stderr to stdout as

service dhcpd status |& awk '$1=="Active:"{print $2}'


问:
pyodbc install on IBM Bluemix server error
I am trying to host my app on IBM bluemix. In my app, I have used flask and I am trying to Connect to Azure SQL Server database. So for that, I am using Pyodbc.

So in requirement.txt file I have given
pip install pyodbc
and
pip install flask.
These things are getting installed on my local machine and the app is running fine. I am getting the result from the database .

But when I am trying to deploy my application on IBM bluemix,
while pushing the files on the server it is giving me an error.
I have attached the error screenshot below.

The content of requirement.txt is here

```<code>unixodbc-dev
pyodbc==3.1.1
Flask==0.12.2
</code>```

答:
The error message error: command 'gcc' failed with exit status 1 makes it seem like perhaps you need to install the gcc C/C++ compiler on that machine.

The pyodbc docs say:

Windows

On Windows, you will need the appropriate Microsoft Visual C++ compiler. To build Python 2.4 or 2.5 versions, you will need the Visual Studio 2003 .NET compiler. Unfortunately there is no free version of this.

For Python 2.6 and above, you can use the free Visual C++ 2008 Express compiler. (Do not use the 2010 version! You need to use the version that your Python distribution was built with.)

You can create a Windows installer using: python setup.py bdist_wininst

Other

To build on other operating systems, use the gcc compiler.

On Linux, pyodbc is typically built using the unixODBC headers, so you will need unixODBC and its headers installed. On a RedHat/CentOS/Fedora box, this means you would need to install unixODBC-devel:

yum install unixODBC-devel

Related: Unable to install pyodbc on Linux

Body:
I am trying to host my app on IBM bluemix. In my app, I have used flask and I am trying to Connect to Azure SQL Server database. So for that, I am using Pyodbc.

So in requirement.txt file I have given
pip install pyodbc
and
pip install flask.
These things are getting installed on my local machine and the app is running fine. I am getting the result from the database .

But when I am trying to deploy my application on IBM bluemix,
while pushing the files on the server it is giving me an error.
I have attached the error screenshot below.

The content of requirement.txt is here

unixodbc-dev
pyodbc==3.1.1
Flask==0.12.2


问:
How to add number of views in database in php mysql
How do we add number of views ( eg  most viewed articles) in php mysql database. How to add numbers when a person click to database? </p>

答:
Several options.

Keep a log file for all request, along with some information that can be used to identify certain resources, e.g. articles - the query this global log for page view stats.

On each request of one article, increment an integer field - something like view_count - in your table. Here, the data is held locally, which is certainly faster (but leaves your request data a little spread over your database, in case you want to track other view counts, too - not just for articles).

Keep in mind, that if you want to track unique visitor views, you might need to store some additional information in your session, since you don't want to count simple page reloads as page views.

ContentLicense: CC BY-SA 2.5


问:
SQL query to find counts of numbers in running total
Suppose the table has 1 column ID and the values are as below:

```<code>ID
5
5
5
6
5
5
6
6
</code>```

the output should be

```<code>ID  count
5    3
6    1
5    2
6    2
</code>```

How can we do that in a single SQL query.

答:
If you want to find the Total count of the Records you have you can write like

select count(*) from database_name order by column_name;

Body:
Suppose the table has 1 column ID and the values are as below:

ID
5
5
5
6
5
5
6
6

the output should be

ID  count
5    3
6    1
5    2
6    2

How can we do that in a single SQL query.


问:
Walkthrough with tab view controller
I have been attempting to create a walkthrough for my app although I also have a tab view controller which is the initial view controller. I have been able to identify when a user is opening the app for the first time, but when I make the walkthrough view controller initial, I get a Sigbart error. This is because I set up my tabbar in the app delegate.

Is there a way to possibly keep the tab bar VC the initial and hide the first VC if it is the users first time opening the app?

Is there another way of doing it?

答:
There easiest way to accomplish the tutorial-like behavior for new users is:

1) Make a new View Controller be the initial one.

2) Add code to check if its the first time the user launched the app. If it is, show the tutorial, if its not, show your tab view controller.

3) You can fill this "fake initial" view controller with the same image shown in the splash screen. This way the user will feel its just the splash one.

*) An added benefit of this approach is that you can check other useful things. For example, if your app has some kind of login feature you can manage it here skipping the login window for users who have already logged in. It can also be used to update your app's resources in case you are retrieving them from a server.

Title: Walkthrough with tab view controller


问:
XHR progress bar for file upload for request AND response
I want to show the upload progress of a file through to the time the request completes from the server.

Every single example out there just shows how to do a progress bar for sending the file from browser to server and not from browser to server back to browser.

The code I have below only shows the progress of the client uploading the file to the server and not the response. Basically as soon as the request is hit on the server the progress event on the client completes which isn't what I want.

How do I do this?

xhr:

```<code>export default (url, opts = {}, uploadEvents) =>
  new Promise((res, rej) => {
    const xhr = new XMLHttpRequest();

    xhr.open(opts.method || 'get', url, true);

    Object.keys(opts.headers || {}).forEach((key) => {
      xhr.setRequestHeader(key, opts.headers[key]);
    });

    xhr.onload = e => res(e.target.responseText);
    xhr.onerror = rej;

    if (xhr.upload) {
      Object.keys(uploadEvents).forEach((key) => {
        xhr.upload.addEventListener(key, uploadEvents[key]);
      });
    }

    xhr.send(opts.body);
  });
</code>```

Request:

```<code>fetchProgress('/upload/upload', {
  method: 'post',
  body: formData,
}, {
  progress: (e) => {
    if (e.lengthComputable) {
      const progressPercent = parseInt((e.loaded / e.total) * 100, 10);

      progressPercents[i] = {
        value: progressPercent,
        id,
      };

      dispatch({
        type: 'ADD_UPLOAD_PROGRESS',
        progressPercents,
      });
    }
  },
});
</code>```

Server code:

```<code>[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
    var processAudio = await _fileStorage.TempStoreMp3Data(file);
    var audioBlob = _cloudStorage.GetBlob(CloudStorageType.Audio, processAudio.AudioName);

    await audioBlob.UploadFromPathAsync(processAudio.AudioPath, ProcessAudio.AudioContentType);

    return Ok();
}
</code>```

答:
Basically as soon as the request is hit on the server the progress event on the client completes which isn't what I want.

To get the progress based on server side operation, I suggest you create another action which could return the progress on server side. On client side, you need to invoke this action to get the progress. Code below is for your reference.

On server side, we need to define a Dictionary to store the progresses and we need to use a uploadId to connect the two actions. When invoke these 2 actions, we need to use the same uploadId from client side.

```<code>//use this dictionary to store the progress for upload
private static Dictionary<string, int> uploadProgresses = new Dictionary<string, int>();

public IActionResult GetUploadProgress(string uploadId)
{
    int progress = 0;
    uploadProgresses.TryGetValue(uploadId, out progress);
    return Content(progress.ToString());
}

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file, string uploadId)
{
    uploadProgresses.Add(uploadId, 0);
    var processAudio = await _fileStorage.TempStoreMp3Data(file);
    uploadProgresses[uploadId] = 20;
    var audioBlob = _cloudStorage.GetBlob(CloudStorageType.Audio, processAudio.AudioName);
    uploadProgresses[uploadId] = 40;
    await audioBlob.UploadFromPathAsync(processAudio.AudioPath, ProcessAudio.AudioContentType);
    uploadProgresses[uploadId] = 100;
    return Ok();
}
</code>```

Client side code sample.

```<code>var myVar = window.setInterval(function () { getUploadProgress(); }, 1000);

var uniqualId = uuidv4();

document.getElementById("uuid").innerHTML = uniqualId;

function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function getUploadProgress() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            //update your progress bar
            document.getElementById("progress").innerHTML = xhttp.responseText;
            if (xhttp.responseText == '100') {
                myStopFunction();
            }
        }
        else if (this.readyState == 4 && this.status != 200)
        {
            myStopFunction();
        }
    };
    xhttp.open("GET", "/Home/GetUploadProgress?uploadId=" + uniqualId, true);
    xhttp.send();
}

function myStopFunction() {
    window.clearInterval(myVar);
}
</code>```

Update 7/10/2017

Should we be using Session to store the upload progress instead of a static dictionary?

No, we can't use Session to store the upload progress. According the lifecycle of ASP.NET application, the state(Session) will be updated after the handler(your Action) be executed. It means the Session will not be updated until your Action executed completed.

Body:
I want to show the upload progress of a file through to the time the request completes from the server.

Every single example out there just shows how to do a progress bar for sending the file from browser to server and not from browser to server back to browser.

The code I have below only shows the progress of the client uploading the file to the server and not the response. Basically as soon as the request is hit on the server the progress event on the client completes which isn't what I want.

How do I do this?

xhr:

export default (url, opts = {}, uploadEvents) =>
  new Promise((res, rej) => {
    const xhr = new XMLHttpRequest();

    xhr.open(opts.method || 'get', url, true);

    Object.keys(opts.headers || {}).forEach((key) => {
      xhr.setRequestHeader(key, opts.headers[key]);
    });

    xhr.onload = e => res(e.target.responseText);
    xhr.onerror = rej;

    if (xhr.upload) {
      Object.keys(uploadEvents).forEach((key) => {
        xhr.upload.addEventListener(key, uploadEvents[key]);
      });
    }

    xhr.send(opts.body);
  });

Request:

fetchProgress('/upload/upload', {
  method: 'post',
  body: formData,
}, {
  progress: (e) => {
    if (e.lengthComputable) {
      const progressPercent = parseInt((e.loaded / e.total) * 100, 10);

      progressPercents[i] = {
        value: progressPercent,
        id,
      };

      dispatch({
        type: 'ADD_UPLOAD_PROGRESS',
        progressPercents,
      });
    }
  },
});

Server code:

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
    var processAudio = await _fileStorage.TempStoreMp3Data(file);
    var audioBlob = _cloudStorage.GetBlob(CloudStorageType.Audio, processAudio.AudioName);

    await audioBlob.UploadFromPathAsync(processAudio.AudioPath, ProcessAudio.AudioContentType);

    return Ok();
}

Body:
Basically as soon as the request is hit on the server the progress event on the client completes which isn't what I want.

To get the progress based on server side operation, I suggest you create another action which could return the progress on server side. On client side, you need to invoke this action to get the progress. Code below is for your reference.

On server side, we need to define a Dictionary to store the progresses and we need to use a uploadId to connect the two actions. When invoke these 2 actions, we need to use the same uploadId from client side.

//use this dictionary to store the progress for upload
private static Dictionary<string, int> uploadProgresses = new Dictionary<string, int>();

public IActionResult GetUploadProgress(string uploadId)
{
    int progress = 0;
    uploadProgresses.TryGetValue(uploadId, out progress);
    return Content(progress.ToString());
}

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file, string uploadId)
{
    uploadProgresses.Add(uploadId, 0);
    var processAudio = await _fileStorage.TempStoreMp3Data(file);
    uploadProgresses[uploadId] = 20;
    var audioBlob = _cloudStorage.GetBlob(CloudStorageType.Audio, processAudio.AudioName);
    uploadProgresses[uploadId] = 40;
    await audioBlob.UploadFromPathAsync(processAudio.AudioPath, ProcessAudio.AudioContentType);
    uploadProgresses[uploadId] = 100;
    return Ok();
}

Client side code sample.

var myVar = window.setInterval(function () { getUploadProgress(); }, 1000);

var uniqualId = uuidv4();

document.getElementById("uuid").innerHTML = uniqualId;

function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function getUploadProgress() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            //update your progress bar
            document.getElementById("progress").innerHTML = xhttp.responseText;
            if (xhttp.responseText == '100') {
                myStopFunction();
            }
        }
        else if (this.readyState == 4 && this.status != 200)
        {
            myStopFunction();
        }
    };
    xhttp.open("GET", "/Home/GetUploadProgress?uploadId=" + uniqualId, true);
    xhttp.send();
}

function myStopFunction() {
    window.clearInterval(myVar);
}

Update 7/10/2017

Should we be using Session to store the upload progress instead of a static dictionary?

No, we can't use Session to store the upload progress. According the lifecycle of ASP.NET application, the state(Session) will be updated after the handler(your Action) be executed. It means the Session will not be updated until your Action executed completed.


问:
Adding images from assets folder in adapter
I'm trying to display images from assets folder. I have this error:

```<code>Bitmap bitmap = getBitmapFormatAssets(product.getProductId());
</code>```

try { Bitmap bitmap = getBitmap(product.getProductId()); imageView.setImageResource(bitmap);

答: It must be setImageBitmap(bitmap) not setImageResource(bitmap)

Body:
I'm trying to display images from assets folder. I have this error:

Bitmap bitmap = getBitmapFormatAssets(product.getProductId());

try { Bitmap bitmap = getBitmap(product.getProductId()); imageView.setImageResource(bitmap);


问:
Google Charts - how to add a fixed scale on an axis
I'm having trouble scaling my chart correctly. My chart represents data for every hour of the day in a 24 hour format, meaning that I need the numbers 0-24 on my linechart.

I've tried adding the logScale, minValue and maxValue properties to the hAxis, but nothing is working.

As you can see on the chart, the hour axis is not spanning a fixed axis from 0-24 hours, but instead from 9-15 hours.

I also only have 3 rows in my data set, which reside on the hours 9, 14 and 15. Despite this, the lines are spanning from 9-14 as if they have values; however there is no data there, so the lines should be running along the bottom at 0 between these two points.

How can I put a fixed horizontal scale on my chart, and have individual values on my lines for each hour?

Here's my code:

```<code>google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(drawChart);

function drawChart()
{
    var json = $.getJSON('my JSON data link', function(data)
    {
        var chartStructure = new google.visualization.DataTable();
        var chartData = [];

        chartStructure.addColumn('number', 'Hour');
        chartStructure.addColumn('number', 'Pageviews');
        chartStructure.addColumn('number', 'Unique Pageviews');
        chartStructure.addColumn('number', 'Sales');
        chartStructure.addColumn('number', 'Earnings in $AUD');

        for (i = 0; i < data.length; i++)
        {
            chartData[i] = [];
            chartData[i][0] = parseInt(data[i].hour);
            chartData[i][1] = parseFloat(data[i].profit);
            chartData[i][2] = parseFloat(data[i].profit);
            chartData[i][3] = parseFloat(data[i].sales);
            chartData[i][4] = parseFloat(data[i].profit);
            // These chartData values are not correct because I am testing

            chartStructure.addRows(chartData);
        }

        var options = {
            hAxis: {
                'minValue': 0,
                'maxValue': 24
            }
        };

        var chart = new google.charts.Line(document.getElementById('todays-total-sales'));

        chart.draw(chartStructure, options);
    });
}

$(window).resize(function()
{
    drawChart();
});
</code>```

答:
```<code> var options = {
                title: "Posted Memes",
                width: 450,
                height: 300,
                is3D:true,
                bar: { groupWidth: "95%" },
                legend: { position: "none" },
                vAxis: {
                    title: 'No of Memes',
                    viewWindowMode: 'explicit',
                    viewWindow: {
                        max: 180,
                        min: 0,
                        interval: 1,
                    },

                }

            };
</code>```

Body:
I'm having trouble scaling my chart correctly. My chart represents data for every hour of the day in a 24 hour format, meaning that I need the numbers 0-24 on my linechart.

I've tried adding the logScale, minValue and maxValue properties to the hAxis, but nothing is working.

As you can see on the chart, the hour axis is not spanning a fixed axis from 0-24 hours, but instead from 9-15 hours.

I also only have 3 rows in my data set, which reside on the hours 9, 14 and 15. Despite this, the lines are spanning from 9-14 as if they have values; however there is no data there, so the lines should be running along the bottom at 0 between these two points.

How can I put a fixed horizontal scale on my chart, and have individual values on my lines for each hour?

Here's my code:

google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(drawChart);

function drawChart()
{
    var json = $.getJSON('my JSON data link', function(data)
    {
        var chartStructure = new google.visualization.DataTable();
        var chartData = [];

        chartStructure.addColumn('number', 'Hour');
        chartStructure.addColumn('number', 'Pageviews');
        chartStructure.addColumn('number', 'Unique Pageviews');
        chartStructure.addColumn('number', 'Sales');
        chartStructure.addColumn('number', 'Earnings in $AUD');

        for (i = 0; i < data.length; i++)
        {
            chartData[i] = [];
            chartData[i][0] = parseInt(data[i].hour);
            chartData[i][1] = parseFloat(data[i].profit);
            chartData[i][2] = parseFloat(data[i].profit);
            chartData[i][3] = parseFloat(data[i].sales);
            chartData[i][4] = parseFloat(data[i].profit);
            // These chartData values are not correct because I am testing

            chartStructure.addRows(chartData);
        }

        var options = {
            hAxis: {
                'minValue': 0,
                'maxValue': 24
            }
        };

        var chart = new google.charts.Line(document.getElementById('todays-total-sales'));

        chart.draw(chartStructure, options);
    });
}

$(window).resize(function()
{
    drawChart();
});


答:
Try this:</p>

```<code>Intent i=new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    finishAffinity();
    return;
}
finish();
</code>```

Title: How to finish all activity when move to other modul via sidemenu

Body:
Try this:

Intent i=new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    finishAffinity();
    return;
}
finish();


问:
iOS: displaying JSON Array in UISearchBar
i have a JSON Dict in this format

```<code>{
  "382" : "sudhir kumar",
  "268" : "David  ",
  "385" : "aayush test",
  "261" : "Mike watson",
  "277" : "TestDrivers Driver",
  "381" : "sudhir kumar",
  "380" : "sudhir kumar",
  "383" : "asdfgh asdfgh",
  "376" : " "
}
</code>```

I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected

I am using the following code it filtered name but not their related ID's with name

My code is:

```<code>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{

    tempArray = [NSArray arrayWithArray:DriverNameArray];
    //NSString *stringToSearch = textField.text;

    tempId = [NSArray arrayWithArray:DriverIdArray];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText]; // if you need case sensitive search avoid '[c]' in the predicate

    //NSPredicate * predicateid = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",stringToSearch];

    NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
    if (tempresults.count > 0)
    {
        tempArray = [NSArray arrayWithArray:tempresults];
        tempId = [NSArray arrayWithArray:tempresults];
    }
    [SEarchTable reloadData];
    //return  YES;
}
</code>```

答:
You have not posted code pertaining to what you've already tried, so I won't post code that directly gives you the solution to your question.

Your best bet is to create an array of dictionaries holding a value for the names and a value for the ID. When you display your data, display the names from the array by myArray[@"name"] convention. You can then get the index of that object and then run [myArray objectAtIndex:myCalculatedIndex][@"id"] to get the ID.

There are actually many ways to solve this problem, but this is one of them.

Body:
i have a JSON Dict in this format

{
  "382" : "sudhir kumar",
  "268" : "David  ",
  "385" : "aayush test",
  "261" : "Mike watson",
  "277" : "TestDrivers Driver",
  "381" : "sudhir kumar",
  "380" : "sudhir kumar",
  "383" : "asdfgh asdfgh",
  "376" : " "
}

I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected

I am using the following code it filtered name but not their related ID's with name

My code is:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{

    tempArray = [NSArray arrayWithArray:DriverNameArray];
    //NSString *stringToSearch = textField.text;

    tempId = [NSArray arrayWithArray:DriverIdArray];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText]; // if you need case sensitive search avoid '[c]' in the predicate

    //NSPredicate * predicateid = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",stringToSearch];

    NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
    if (tempresults.count > 0)
    {
        tempArray = [NSArray arrayWithArray:tempresults];
        tempId = [NSArray arrayWithArray:tempresults];
    }
    [SEarchTable reloadData];
    //return  YES;
}


答: Instead of imageView.setImageResource(bitmap) try to use imageView.setImageBitmap(bitmap) directly.

Title: Adding images from assets folder in adapter


问:
developing R package with templete .Rmd files findable to package function
I'm developing an R package, one of my package function is generate_report() which generate an html report with rmarkdown using a templete Rmd file and function arguments:

```<code>#' generate report based on templete file
#' @import rmarkdown
#' @export
generate_report <- function(x, y){
  rmarkdown::render('templete.Rmd', envir = list(x = x, y = y))
}
</code>```

and here is the inst/templete.Rmd file: (when the package is compiled, it will be moved to top-level folder of package:

```<code>---
title: "templete"
output: html_document
---

## Head 1

```{r}
print(x)
```

```{r}
print(y)
```
</code>```

my question is, when the package is devtools::install()ed, function generate_report() can not find file templete.Rmd, how to make the function find this templete.Rmd file in right way ?

答:
system.file is the right way, thanks @MrFlick and @Jonathan Carroll. This is my final code:

```<code>generate_report <- function(x, y, output_dir){
      file <- system.file("templete.Rmd", package = 'mypackage-name')
      if (missing(output_dir)) {
         output_dir <- getwd()
      }
      rmarkdown::render(file, envir = list(x = x, y = y), output_dir = output_dir)
    }
</code>```

Body:
I'm developing an R package, one of my package function is generate_report() which generate an html report with rmarkdown using a templete Rmd file and function arguments:

#' generate report based on templete file
#' @import rmarkdown
#' @export
generate_report <- function(x, y){
  rmarkdown::render('templete.Rmd', envir = list(x = x, y = y))
}

and here is the inst/templete.Rmd file: (when the package is compiled, it will be moved to top-level folder of package:

---
title: "templete"
output: html_document
---

## Head 1

```{r}
print(x)
```

```{r}
print(y)
```

my question is, when the package is devtools::install()ed, function generate_report() can not find file templete.Rmd, how to make the function find this templete.Rmd file in right way ?

Body:
system.file is the right way, thanks @MrFlick and @Jonathan Carroll. This is my final code:

generate_report <- function(x, y, output_dir){
      file <- system.file("templete.Rmd", package = 'mypackage-name')
      if (missing(output_dir)) {
         output_dir <- getwd()
      }
      rmarkdown::render(file, envir = list(x = x, y = y), output_dir = output_dir)
    }


问:
Access 2010 - optimization a query
Can help me please to optimize this query in database (access 2010), this query to work very slowly (if use it in a big table):

```<code>SELECT П1.Code, П1.Field, П1.Number, П1.Data, [П1].[Number]-(select П3.Number from [Table] as П3
    where П3.Field = П1.Field
    and П3.Data = (select Max(Data)
    from [Table] as П2
    where П2.Field = П1.Field and П1.Data > П2.Data)) AS Difference
FROM [Table] AS П1
ORDER BY П1.Field, П1.Data;
</code>```

I'm attach a picture: http://s33.postimg.org/otm859xtb/Table_query.png

Link in the database: http://s000.tinyupload.com/?file_id=06711692152703646964

答:
PLease try this one, just the same like Kevin ))</p>

```<code>SELECT Table.Code, Table.Field, Table.Number, Table.Data, [Table].[Number]-[t1].[number] AS Difference
FROM
(SELECT Table.Code, Table.Field, Table.Number, Table.Data
FROM [Table] INNER JOIN
(SELECT Table.Field, Max(Table.Data) AS MaxOfData
FROM [Table] GROUP BY Table.Field) AS t2 ON (t2.MaxOfData = Table.Data) AND
(Table.Field = t2.Field)) AS t1 INNER JOIN [Table] ON t1.Field = Table.Field;
</code>```

Title: Access 2010 - optimization a query

Body:
Can help me please to optimize this query in database (access 2010), this query to work very slowly (if use it in a big table):

SELECT П1.Code, П1.Field, П1.Number, П1.Data, [П1].[Number]-(select П3.Number from [Table] as П3
    where П3.Field = П1.Field
    and П3.Data = (select Max(Data)
    from [Table] as П2
    where П2.Field = П1.Field and П1.Data > П2.Data)) AS Difference
FROM [Table] AS П1
ORDER BY П1.Field, П1.Data;

I'm attach a picture: http://s33.postimg.org/otm859xtb/Table_query.png

Link in the database: http://s000.tinyupload.com/?file_id=06711692152703646964

Body:
PLease try this one, just the same like Kevin ))

SELECT Table.Code, Table.Field, Table.Number, Table.Data, [Table].[Number]-[t1].[number] AS Difference
FROM
(SELECT Table.Code, Table.Field, Table.Number, Table.Data
FROM [Table] INNER JOIN
(SELECT Table.Field, Max(Table.Data) AS MaxOfData
FROM [Table] GROUP BY Table.Field) AS t2 ON (t2.MaxOfData = Table.Data) AND
(Table.Field = t2.Field)) AS t1 INNER JOIN [Table] ON t1.Field = Table.Field;


问:
ValueError: could not convert string to float: 'FEE'
I am getting ValueError: could not convert string to float: 'FEE'
and I am unable to convert it to float by following :

```<code>df = pd.concat([df[col].str.split()
                       .str[0]
                       .str.replace(',','').astype(float) for col in df], axis=1)
</code>```

My column variable is as follows :

```<code>array(['AUTHORIZATION', 'BALANCE ADJUSTMENT', 'CARD LOAD', 'CARD UNLOAD',
       'CHARGE BACK ADVICE', 'FEE'], dtype=object)
</code>```

Please help

My dataframe has 9 columns and 2 columns show this ValueError.

One column has value like 'REV01', 'REV02' etc.
Other one has values as ['AUTHORIZATION', 'BALANCE ADJUSTMENT', 'CARD LOAD', 'CARD UNLOAD',
           'CHARGE BACK ADVICE', 'FEE']

How should I ensure I don't get this ValueError keeping both these columns ?

答:
Are you trying to convert your column into numeric types?
Also to clarify, is FEE the first value your code has to parse in the column?</p>

Body:
I am getting ValueError: could not convert string to float: 'FEE'
and I am unable to convert it to float by following :

df = pd.concat([df[col].str.split()
                       .str[0]
                       .str.replace(',','').astype(float) for col in df], axis=1)

My column variable is as follows :

array(['AUTHORIZATION', 'BALANCE ADJUSTMENT', 'CARD LOAD', 'CARD UNLOAD',
       'CHARGE BACK ADVICE', 'FEE'], dtype=object)

Please help

My dataframe has 9 columns and 2 columns show this ValueError.

One column has value like 'REV01', 'REV02' etc.
Other one has values as ['AUTHORIZATION', 'BALANCE ADJUSTMENT', 'CARD LOAD', 'CARD UNLOAD',
           'CHARGE BACK ADVICE', 'FEE']

How should I ensure I don't get this ValueError keeping both these columns ?


问:
Passing function to another function: Using a variable within the function as the argument to the functions being passed to it
A code example from a JavaScript book. I am learning about passing functions as arguments to functions. The solution explains that when we pass the hawaiianTranslator function to the sayIt function that the string "hello" is the argument for hawaiianTranslator.

Can someone please explain very simply why this is. sayIt doesn't return anything so why/how is the value of phrase being passed to the hawaiianTranslator function.

Thank you in advance

```<code>function sayIt(translator) {
    var phrase = translator("Hello");
    alert(phrase);
}

function hawaiianTranslator(word) {
if (word === "Hello") return "Aloha";
if (word === "Goodbye") return "Aloha";
}

sayIt(hawaiianTranslator);
</code>```

sayIt(hawaiianTranslator);  alerts "Aloha". How does this happen? I don't understand how the string "hello" is the argument to the function hawaiianTranslator

答:
You are passing function reference hawaiianTranslator into sayit function as argument, there you are recieving it in translator variable.  So inside sayit function you are calling translator("Hello") which will be same as hawaiianTranslator("Hello") in effect

```<code>function sayIt(translator) {
    var phrase = translator("Hello");
    alert(phrase);
}
</code>```

In the above function when you call  translator("Hello"), which will invoke hawaiianTranslator function with "Hello" as argument.

```<code>function hawaiianTranslator(word) {
    if (word === "Hello") return "Aloha";
    if (word === "Goodbye") return "Aloha";
}
</code>```

This function return the translated word. So in the first function you will get the translated word ("Aloha") in phrase variable.

Body:
A code example from a JavaScript book. I am learning about passing functions as arguments to functions. The solution explains that when we pass the hawaiianTranslator function to the sayIt function that the string "hello" is the argument for hawaiianTranslator.

Can someone please explain very simply why this is. sayIt doesn't return anything so why/how is the value of phrase being passed to the hawaiianTranslator function.

Thank you in advance

function sayIt(translator) {
    var phrase = translator("Hello");
    alert(phrase);
}

function hawaiianTranslator(word) {
if (word === "Hello") return "Aloha";
if (word === "Goodbye") return "Aloha";
}

sayIt(hawaiianTranslator);

sayIt(hawaiianTranslator);  alerts "Aloha". How does this happen? I don't understand how the string "hello" is the argument to the function hawaiianTranslator

Body:
You are passing function reference hawaiianTranslator into sayit function as argument, there you are recieving it in translator variable.  So inside sayit function you are calling translator("Hello") which will be same as hawaiianTranslator("Hello") in effect

function sayIt(translator) {
    var phrase = translator("Hello");
    alert(phrase);
}

In the above function when you call  translator("Hello"), which will invoke hawaiianTranslator function with "Hello" as argument.

function hawaiianTranslator(word) {
    if (word === "Hello") return "Aloha";
    if (word === "Goodbye") return "Aloha";
}

This function return the translated word. So in the first function you will get the translated word ("Aloha") in phrase variable.


问:
Why object could be "moved" even lacks move constructor and move assignment operator?
http://en.cppreference.com/w/cpp/language/rule_of_three

I have begun with c++11 a couple of months ago
and have watched the rule of five.

So.. I started putting copy constructor/copy assignment operator/move constructor/move assignment operator with default keyword on every class having virtual destructor.

because the rule told me that if you declare explicit destructor then your class doesn't have its implicit move constructor and move assignment operator anymore.

So I think gcc is going to complain to me that below class due to lack of move constructor and move assignment operator.

But It works well! What happend??

```<code>class Interface {
public:
    virtual ~Interface() = default;  // implicit destructor
};

class ImplA : public Interface {
public:
    virtual ~ImplA() = default; // implicit destructor
};

ImplA first;
ImplA second(first);            // copy constructor, OK. understood it.
ImplA third(std::move(first));  // move constructor, it's OK. Why?
second = first;             // copy assignment, OK. understood it.
second = std::move(first);  // move assignment, it's also OK. Why?
</code>```

答:
So I think gcc is going to complain to me that below class due to lack of move constructor and move assignment operator.

Because the operations required could be performed via copy constructor and copy assignment operator. Interface still has copy constructor and copy assignment operator which are implcitly declared. And rvalues are always possible to be bound to const Interface&.

More precisely, even without move constructor and move assignment operator provided, Interface is still MoveConstructible,

A class does not have to implement a move constructor to satisfy this
  type requirement: a copy constructor that takes a const T& argument
  can bind rvalue expressions.

and MoveAssignable.

The type does not have to implement move assignment operator in order
  to satisfy this type requirement: a copy assignment operator that
  takes its parameter by value or as a const Type&, will bind to rvalue
  argument.

BTW: If you make the move constructor and move assignment operator delete explicitly  then both copy and move operation would fail. Using with an rvalue expression the explicitly deleted overload will be selected and then fails. Using with an lvalue expression would fail too because copy constructor and copy assignment operator are implicitly declared as deleted because of the declaration of move constructor or move assignment operator.

Body:
http://en.cppreference.com/w/cpp/language/rule_of_three

I have begun with c++11 a couple of months ago
and have watched the rule of five.

So.. I started putting copy constructor/copy assignment operator/move constructor/move assignment operator with default keyword on every class having virtual destructor.

because the rule told me that if you declare explicit destructor then your class doesn't have its implicit move constructor and move assignment operator anymore.

So I think gcc is going to complain to me that below class due to lack of move constructor and move assignment operator.

But It works well! What happend??

class Interface {
public:
    virtual ~Interface() = default;  // implicit destructor
};

class ImplA : public Interface {
public:
    virtual ~ImplA() = default; // implicit destructor
};

ImplA first;
ImplA second(first);            // copy constructor, OK. understood it.
ImplA third(std::move(first));  // move constructor, it's OK. Why?
second = first;             // copy assignment, OK. understood it.
second = std::move(first);  // move assignment, it's also OK. Why?


问:
BufferedWriter throwing NPE
I am trying to write a value fetched from a hashmap into a file :

```<code>public writeToFile(HapshMap<String,String> , String fileName) {

    File myFile = new File(filePath);
    BufferedWriter bufferedWriter = null;
    Writer writer = new FileWriter(myFile,false);
    bufferedWriter = new BufferedWriter(writer);

    String paramsValue = params.get("NAME");
    bufferedWriter.write(paramsValue);
}
</code>```

In the above code , the key "NAME" is not there in the HashMap.
And it is throwing NPE .Can anyone suggest what can be done and why is NPE getting thrown?

答:
BufferedWriter does throw an NPE when you ask it to write null somewhere.

That is a situation you will have to know about and deal with. For example, replace null value with some well known string that indicates emptiness:

```<code>Object nvl(Object value, Object defaultValue) {
  return value != null ? value : defaultValue;
}
<...>
String value = nvl(map.get("Name"), ""); // using empty string instead of null
writer.write(value);
</code>```

Title: BufferedWriter throwing NPE

Body:
I am trying to write a value fetched from a hashmap into a file :

public writeToFile(HapshMap<String,String> , String fileName) {

    File myFile = new File(filePath);
    BufferedWriter bufferedWriter = null;
    Writer writer = new FileWriter(myFile,false);
    bufferedWriter = new BufferedWriter(writer);

    String paramsValue = params.get("NAME");
    bufferedWriter.write(paramsValue);
}

In the above code , the key "NAME" is not there in the HashMap.
And it is throwing NPE .Can anyone suggest what can be done and why is NPE getting thrown?

Body:
BufferedWriter does throw an NPE when you ask it to write null somewhere.

That is a situation you will have to know about and deal with. For example, replace null value with some well known string that indicates emptiness:

Object nvl(Object value, Object defaultValue) {
  return value != null ? value : defaultValue;
}
<...>
String value = nvl(map.get("Name"), ""); // using empty string instead of null
writer.write(value);


问:
Populate a drop down list based on another drop down list selected value in MVC 4
I have referred This ans of stackoverflow It is working fine but since i have taken drop down list in forms so when second dropdown list gets populate selected value in first dropdown list is getting effected. How to maintain that value??

Here is my code.

View

```<code>@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("country", ViewData["Id"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }

@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("state", ViewData["Id1"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }

@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("city", ViewData["Id2"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }
</code>```

Controller

```<code> public ActionResult Create()
    {
        FillCountry();
        FillState();
        FillCity();
        return View();
    }
    [HttpPost]
    public ActionResult Create(User ur)
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();
        con.Close();
        TempData["msg"] = "<script>alert('Inserted Successfully');</script>";
        ModelState.Clear();
        FillCountry();
        FillState();
        FillCity();
        return View();

    }
    public void FillCountry()
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tblCountry ";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }

        ViewData["Id"] = li;

    }
    public void FillState()
    {
        int id = Convert.ToInt16(Request["country"]);
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tblState where cid='" + id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        ViewData["Id1"] = li;
    }
    public void FillCity()
    {
        int id = Convert.ToInt16(Request["state"]);
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tbl_cities where StateId='" + id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        ViewData["Id2"] = li;
    }
</code>```

and also when I am using only two dropdownlist i.e ddlCountry and ddlState and select Country from ddlCountry my ddlSates is getting populated properly but the selected Country from ddlCountry is getting changed.

答:
you can use jquery like below</p>

```<code>$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>

<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have referred This ans of stackoverflow It is working fine but since i have taken drop down list in forms so when second dropdown list gets populate selected value in first dropdown list is getting effected. How to maintain that value??

Here is my code.

View

@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("country", ViewData["Id"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }

@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("state", ViewData["Id1"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }

@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("city", ViewData["Id2"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }

Controller

 public ActionResult Create()
    {
        FillCountry();
        FillState();
        FillCity();
        return View();
    }
    [HttpPost]
    public ActionResult Create(User ur)
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();
        con.Close();
        TempData["msg"] = "";
        ModelState.Clear();
        FillCountry();
        FillState();
        FillCity();
        return View();

    }
    public void FillCountry()
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tblCountry ";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }

        ViewData["Id"] = li;

    }
    public void FillState()
    {
        int id = Convert.ToInt16(Request["country"]);
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tblState where cid='" + id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        ViewData["Id1"] = li;
    }
    public void FillCity()
    {
        int id = Convert.ToInt16(Request["state"]);
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tbl_cities where StateId='" + id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        ViewData["Id2"] = li;
    }

and also when I am using only two dropdownlist i.e ddlCountry and ddlState and select Country from ddlCountry my ddlSates is getting populated properly but the selected Country from ddlCountry is getting changed.

Body:
you can use jquery like below

$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>

<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>


问:
Array of two types
I have two arrays :

```<code>Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)
</code>```

How to combine both as:

```<code>Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)
</code>```

Thanks -
Haan

答:
```<code>$dayOfWeek = array('Mon', 'Sun');
$dateWithHours = array( array('date'=>'12-20-2010', 'hours'=>4.0), array('date'=>'12-19-2010', 'hours'=>2.0) );

foreach(&$dateWithHours as $k=$v)
{
     $v['day'] = $dayOfWeek[$k];
}
</code>```

Remember that ampersand.  Without it, $v is a copy that won't alter the original.  With it, it is a reference that you can change.

Title: Array of two types

Body:
I have two arrays :

Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)

How to combine both as:

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)

Thanks -
Haan

Body:
$dayOfWeek = array('Mon', 'Sun');
$dateWithHours = array( array('date'=>'12-20-2010', 'hours'=>4.0), array('date'=>'12-19-2010', 'hours'=>2.0) );

foreach(&$dateWithHours as $k=$v)
{
     $v['day'] = $dayOfWeek[$k];
}

Remember that ampersand.  Without it, $v is a copy that won't alter the original.  With it, it is a reference that you can change.


问:
Spring-mvc with hibernate maven project
I got this error while running my project on Apache tomcat 9:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean com.cd.coe.configuration.PersistenceJPAConfig.entityManagerFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.cd.coe.configuration.PersistenceJPAConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc.driverClassName] not found
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1452)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
```

<p>This is my pom.xml:</p>

```<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cd.elibrary</groupId>
<artifactId>E-library</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>E-library Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
    <springframework.version>4.0.6.RELEASE</springframework.version>
    <hibernate.version>5.2.10.Final</hibernate.version>
    <mysql.version>5.1.31</mysql.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.3.Final</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>
</dependencies>
<build>
    <finalName>E-library</finalName>
</build>
```

<p>
And my configuration file is as follows:</p>

```@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig {

@Autowired
private Environment environment;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[] { "com.cd.coe.model" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean(name = "dataSource")
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}
```

My application.properties file is correct.

There is a problem when running this code on a server so I am not able to find the exact bug. I have tried with different versions of hibernate and mysql connector, but the issue still occurs.

答:
Try using -

```<code>@PropertySource({ "classpath:application.properties" }) //Add this annotaion at your class
</code>```

And,

```<code>environment.getProperty("jdbc.driverClassName"); //Use this to read a property
</code>```

Hope this will work for you :)

Title: Spring-mvc with hibernate maven project

Body:
I got this error while running my project on Apache tomcat 9:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean com.cd.coe.configuration.PersistenceJPAConfig.entityManagerFactory()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/cd/coe/configuration/PersistenceJPAConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.cd.coe.configuration.PersistenceJPAConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: required key [jdbc.driverClassName] not found
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:530)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1452)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)

This is my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cd.elibrary</groupId>
<artifactId>E-library</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>E-library Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
    <springframework.version>4.0.6.RELEASE</springframework.version>
    <hibernate.version>5.2.10.Final</hibernate.version>
    <mysql.version>5.1.31</mysql.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.3.Final</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>
</dependencies>
<build>
    <finalName>E-library</finalName>
</build>

And my configuration file is as follows:

@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig {

@Autowired
private Environment environment;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[] { "com.cd.coe.model" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean(name = "dataSource")
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

My application.properties file is correct.

There is a problem when running this code on a server so I am not able to find the exact bug. I have tried with different versions of hibernate and mysql connector, but the issue still occurs.

Body:
Try using -

@PropertySource({ "classpath:application.properties" }) //Add this annotaion at your class

And,

environment.getProperty("jdbc.driverClassName"); //Use this to read a property

Hope this will work for you :)


问:
How to finish all activity when move to other modul via sidemenu
I will explain my problem:

I have 4 main menus can access from Dashboard page such as :

Menu A

Menu B

Menu C

Menu D

Inside each menu there are sub menu , so the tree of menus will look like (ALL Menu is an independent Activity):

Menu A -> SubA-1 -> SubA-2

Menu B -> SubB-1 -> SubB-2

Menu C -> SubC-1 -> SubC-2

Menu D -> SubD-1 -> SubD-2

When i access menu A to SubA-1 and then SubA-2. So now i inside SubA-2.
I move to Menu B from SubA-2.

From Menu B i access SubB-1. So Now i inside SubB-1. When i pressed back button i will move sequence like this :
SubB-1 -> Menu B -> SubA-2 -> SubA-1 -> Menu A

How to avoid Menu A Activity still called when pressed back button (but don't give suggest to block the back button)? I use this but not working perfectly :

```<code>intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

If you need more information about case you can put in the comment below.

UPDATED :

User not allowed back to menuA if they come from MenuB. But They still
  alowed back to Menu A if they come from subA-1 (sub menu of menu A).

Thank you.

答: You can finish the Menu A activity that you don't want the users to go back to. For instance, in your Menu A activity, right after you call startActivity, call finish(). When the users hit the back button, they will not be able to go to the Menu A activity because it has been killed off the stack.</p>

Body:
I will explain my problem:

I have 4 main menus can access from Dashboard page such as :

Menu A

Menu B

Menu C

Menu D

Inside each menu there are sub menu , so the tree of menus will look like (ALL Menu is an independent Activity):

Menu A -> SubA-1 -> SubA-2

Menu B -> SubB-1 -> SubB-2

Menu C -> SubC-1 -> SubC-2

Menu D -> SubD-1 -> SubD-2

When i access menu A to SubA-1 and then SubA-2. So now i inside SubA-2.
I move to Menu B from SubA-2.

From Menu B i access SubB-1. So Now i inside SubB-1. When i pressed back button i will move sequence like this :
SubB-1 -> Menu B -> SubA-2 -> SubA-1 -> Menu A

How to avoid Menu A Activity still called when pressed back button (but don't give suggest to block the back button)? I use this but not working perfectly :

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

If you need more information about case you can put in the comment below.

UPDATED :

User not allowed back to menuA if they come from MenuB. But They still
  alowed back to Menu A if they come from subA-1 (sub menu of menu A).

Thank you.


问:
How do I center an SVG in a div?
I have an SVG that I am trying to center in a div. The div has a width of 900px. The SVG has a width of 400px. The SVG has its margin-left and margin-right set to auto. Doesn't work, it just acts as if the left margin is 0 (default).

Does Anyone know what's the error?

答:
Answers above look incomplete as they are talking from css point of view only.

positioning of svg within viewport is affected by two svg attributes

viewBox: defines the rectangle area for svg to cover.

preserveAspectRatio: defined where to place the viewBox wrt viewport and how to strech it if viewport changes.

Follow this link from codepen for detailed description

```<code><svg viewBox="70 160 800 190" preserveAspectRatio="xMaxYMax meet">
</code>```

Title: How do I center an SVG in a div?

Body:
Answers above look incomplete as they are talking from css point of view only.

positioning of svg within viewport is affected by two svg attributes

viewBox: defines the rectangle area for svg to cover.

preserveAspectRatio: defined where to place the viewBox wrt viewport and how to strech it if viewport changes.

Follow this link from codepen for detailed description

<svg viewBox="70 160 800 190" preserveAspectRatio="xMaxYMax meet">


问:
PHP - How to carry on the SESSION variables after a form submit
Im having issues  while using the SESSION variables. Im planning to add data to a SQL each time the user hit "Submit" on the generar.php script. I'm also counting on the login data of the first pag index.html here is where im having issues, whenever i hit "Submit" it will clean the variables. I checked several
forums looking for an answer but still i dont have an answer. Any ideas?

index.html

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">

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

Codigo del Medico
<input name="v_codigo">

Cedula del paciente
<input name="v_cedula">

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

</form>

```
</div>
</div>
</p>

<p>generar.php
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">
</head>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<tbody>
<tr>
<td>Medicamento</td>
<td>
<select name="v_meds"><option>Seleccionar</option><option>Rojo</option><option>Verde</option><option>Azul</option><option>Amarillo</option><option>Blanco</option><option>Negro</option></select>
<br>
</td>
</tr>
<tr>
<td>Via</td>
<td>
<select name="v_via"><option>Seleccionar</option><option>Oral</option><option>Rectal</option><option>Nasal</option><option>Otica</option><option>Oftalmica</option><option>Vaginal</option><option>Topica</option></select>
<br>
</td>
</tr>
<tr>
<td>Frecuencia</td>
<td>
<select name="v_frec"><option>Seleccionar</option><option>6</option><option>8</option><option>12</option><option>24</option></select>
<br>
</td>
</tr>
<tr>
<td>Duracion</td>
<td>
<select name="v_dur"><option>Seleccionar</option><option>5</option><option>7</option><option>15</option><option>30</option><option>PRN10</option><option>PRN20</option><option>PRN30</option></select>
<br>
</td>
</tr>
<tr>
<td> Enviar</td>
<td align="right"><input name="submit" value="Enviar" type="submit"></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" rowspan="1">Ver historial de recetas</td>
</tr>
</tbody>
</form>

<?php
error_reporting(E_ALL);
session_start();
if (isset($_REQUEST['v_codigo']) || isset($_REQUEST['v_cedula'])) {
 $codigo = $_REQUEST['v_codigo'];
 $cedula = $_REQUEST['v_cedula'];
}
 $_SESSION['sesion_codigo'] = $codigo;
 $_SESSION['sesion_cedula'] = $cedula;

 //$codigo1 = $_SESSION['sesion_codigo'];
 //$cedula1 = $_SESSION['sesion_cedula'];
 $tabla = 'p'.$cedula1;

 print 'Codigo: ' . $codigo . '<br/>';
 print 'Cedula: ' . $cedula . '<br/>';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name1 = $_POST['v_meds'];
 $name2 = $_POST['v_via'];
 $name3 = $_POST['v_frec'];
 $name4 = $_POST['v_dur'];
    if ($name1 == 'Seleccionar' || $name2 == 'Seleccionar' || $name3 == 'Seleccionar' || $name4 == 'Seleccionar') {
        echo "Receta contiene errores, favor llenar correctamente el formulario.<br/>";
    } else {
        echo $name1 . $name2 . $name3 . $name4;
    }
}
?>

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

EDIT 1:
I change the session_start(); to the very begining of the html file. But had same result. The first time i select the variables $codigo and $cedula they are correctl setup, when i click on submit button they disapear. The idea is that after clicking the submit button I keep the losgin data to send serveral requests in a row.

Below the images of each step. Thanks again to all who take time to answer.

Login data:
codigovar
cedulavar

First time the page is loaded
After clicking the submit button

EDIT 2: I'm also using @RamRaider code suggestions to fill the variables only if they are populated.

答:
You should start session  in top

```<code><?php
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html>
<html>
<head>
</code>```

because in your code it will show error like header already sent
when we start session in php there should not be output to page before

```<code>session_start();
</code>```

So your code should be something like this:-

```<code><?php
session_start();
error_reporting(E_ALL);
?>
<!DOCTYPE html>
<html>
<head>
</code>```

Body:
Im having issues  while using the SESSION variables. Im planning to add data to a SQL each time the user hit "Submit" on the generar.php script. I'm also counting on the login data of the first pag index.html here is where im having issues, whenever i hit "Submit" it will clean the variables. I checked several
forums looking for an answer but still i dont have an answer. Any ideas?

index.html

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">

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

Codigo del Medico
<input name="v_codigo">

Cedula del paciente
<input name="v_cedula">

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

</form>

generar.php

<!DOCTYPE html>

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

Medicamento

<select name="v_meds"><option>Seleccionar</option><option>Rojo</option><option>Verde</option><option>Azul</option><option>Amarillo</option><option>Blanco</option><option>Negro</option></select>

Via

<select name="v_via"><option>Seleccionar</option><option>Oral</option><option>Rectal</option><option>Nasal</option><option>Otica</option><option>Oftalmica</option><option>Vaginal</option><option>Topica</option></select>

Frecuencia

<select name="v_frec"><option>Seleccionar</option><option>6</option><option>8</option><option>12</option><option>24</option></select>

Duracion

<select name="v_dur"><option>Seleccionar</option><option>5</option><option>7</option><option>15</option><option>30</option><option>PRN10</option><option>PRN20</option><option>PRN30</option></select>

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

Ver historial de recetas

</form>

<?php
error_reporting(E_ALL);
session_start();
if (isset($_REQUEST['v_codigo']) || isset($_REQUEST['v_cedula'])) {
 $codigo = $_REQUEST['v_codigo'];
 $cedula = $_REQUEST['v_cedula'];
}
 $_SESSION['sesion_codigo'] = $codigo;
 $_SESSION['sesion_cedula'] = $cedula;

 //$codigo1 = $_SESSION['sesion_codigo'];
 //$cedula1 = $_SESSION['sesion_cedula'];
 $tabla = 'p'.$cedula1;

 print 'Codigo: ' . $codigo . '
';
 print 'Cedula: ' . $cedula . '
';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name1 = $_POST['v_meds'];
 $name2 = $_POST['v_via'];
 $name3 = $_POST['v_frec'];
 $name4 = $_POST['v_dur'];
    if ($name1 == 'Seleccionar' || $name2 == 'Seleccionar' || $name3 == 'Seleccionar' || $name4 == 'Seleccionar') {
        echo "Receta contiene errores, favor llenar correctamente el formulario.
";
    } else {
        echo $name1 . $name2 . $name3 . $name4;
    }
}
?>

EDIT 1:
I change the session_start(); to the very begining of the html file. But had same result. The first time i select the variables $codigo and $cedula they are correctl setup, when i click on submit button they disapear. The idea is that after clicking the submit button I keep the losgin data to send serveral requests in a row.

Below the images of each step. Thanks again to all who take time to answer.

Login data:
codigovar
cedulavar

First time the page is loaded
After clicking the submit button

EDIT 2: I'm also using @RamRaider code suggestions to fill the variables only if they are populated.

Body:
You should start session  in top

<?php
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html>
<html>
<head>

because in your code it will show error like header already sent
when we start session in php there should not be output to page before

session_start();

So your code should be something like this:-

<?php
session_start();
error_reporting(E_ALL);
?>
<!DOCTYPE html>
<html>
<head>