问:
Pentaho report generation - white space in value (Springboot service)
I have created a springboot service for report generation using "Pentaho Reporting Engine Classic version 7.0.0.0-25.-1"

Issue:- different output compared to PRD.. On generation of HTML(other format) output

PRD's output

```<code><td valign="middle" class="style-7">ABC-1001-1700860</td>
</code>```

Related style is

```<code>.style-7 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}
</code>```

From Service

```<code><td valign="middle" class="style-4">ABC-1001-1 700860</td>
</code>```

Related style

```<code>.style-4 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}
</code>```

issue:-

CSS class name is different(but no difference, so ok..)

There is space in data.

Why space(ABC-1001-1 700860) is appearing? How to get exact output as PRD?

How to get latest pentaho(8 onwards) jars. as well?

答:
@AlainD thanks for the response.. I am getting data from Database(Postgres) using JNDI..
Basic code

```<code> ByteArrayOutputStream baos = new ByteArrayOutputStream();
 HtmlReportUtil.createStreamHTML(report, baos);
</code>```

roport object is
final MasterReport report

Setting ContentType based on format like text/html,application/pdf
characterset is UTF-8

SpringBoot(tomcat): 1.5.2.RELEASE

```<code><td valign="middle" class="style-7">ABCD STORE-2F</td>
<td valign="middle" class="style-7">ABC-1001-1 700860</td>
</code>```

some analysis..

if value contains space within it then its coming properly..ABCD STORE-2F.. value is correct.

if there there is no space and some spacial character then space is getting added.. ABC-1001-1(space)700860

pentaho PRD vs Services

by seeing above image we can see the clear difference in the display..
is there any word wrapping issue..

service -- M-N-IM-A001-MD8-1 000

PRD -- M-N-IM-A001-MD8-1000

i believe that there should not be any difference.

Body:
I have created a springboot service for report generation using "Pentaho Reporting Engine Classic version 7.0.0.0-25.-1"

Issue:- different output compared to PRD.. On generation of HTML(other format) output

PRD's output

ABC-1001-1700860

Related style is

.style-7 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}

From Service

ABC-1001-1 700860

Related style

.style-4 {
    color: black;
    font-size: 8pt;
    font-family: "Arial";
    font-weight: normal;
    font-style: normal;
    text-decoration: none;
    text-align: left;
    word-spacing: 0pt;
    letter-spacing: 0pt;
    white-space: pre-wrap;
    border-bottom: 1pt solid #ccccff;
    border-right: 1pt solid #ccccff
}

issue:-

CSS class name is different(but no difference, so ok..)

There is space in data.

Why space(ABC-1001-1 700860) is appearing? How to get exact output as PRD?

How to get latest pentaho(8 onwards) jars. as well?

Body:
@AlainD thanks for the response.. I am getting data from Database(Postgres) using JNDI..
Basic code

 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 HtmlReportUtil.createStreamHTML(report, baos);

roport object is
final MasterReport report

Setting ContentType based on format like text/html,application/pdf
characterset is UTF-8

SpringBoot(tomcat): 1.5.2.RELEASE

<td valign="middle" class="style-7">ABCD STORE-2F</td>
<td valign="middle" class="style-7">ABC-1001-1 700860</td>

some analysis..

if value contains space within it then its coming properly..ABCD STORE-2F.. value is correct.

if there there is no space and some spacial character then space is getting added.. ABC-1001-1(space)700860

pentaho PRD vs Services

by seeing above image we can see the clear difference in the display..
is there any word wrapping issue..

service -- M-N-IM-A001-MD8-1 000

PRD -- M-N-IM-A001-MD8-1000

i believe that there should not be any difference.


来源: stackexchange

问:
Subprocess in C# Application pauses unexpected
I'm currently working on a service (well at this point it's still a Console Application, as this is a lot easier to debug). The basic task of this service is to watch a folder for new *.tif Files. As soon as the Application found a .TIF file in the folder it starts another Application with the following code:

```<code>ProcessStartInfo command = new ProcessStartInfo(commandPath, commandParams);
command.RedirectStandardOutput=true;
command.UseShellExecute=false;
command.CreateNoWindow=true;

Process process = new Process();
process.startInfo = command;
process.Start();
process.WaitForExit();
</code>```

This console application then uses IrfanView to split the Multipage-TIF into multiple singlepage-TIF (I use basically the same code as above to do this). After that, I check for a Barcode on the Scanned image (with zxing library). The found Barcode is then compared to the Oracle Database. Afterwards the file is converted to PDF and moved to a specific location, based on the found Barcode.

This console Application works perfectly, when I start it myself, but as soon as the "service" starts it, it will pause after a while and don't do anything until I close the "service"-console application. Then it finishes normally.

What could be the problem?

I tried to disable the Oracle, DB check and it worked. Afterwards I disabled my Logging class and it worked too. So my guess is, that I somehow use too much ressources or something like that. But where to start?

EDIT:
Some additional information. I just debugged the process, as VS is able to attach to a process to debug. The command that hangs is Console.WriteLine (called from within the Console application which is called by my "service" console. Any way that a console in a subprocess can only have a certain amount of lines/chars? can a console-output stream have a deadlock or what is this?

答: As far as I know you cannot interact with the windows ased application using the windows service. You might be able to do that using your windws console application which you are using for testing purposes. but when you switch to service your service will ot be able to communicate with the windows based process. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm currently working on a service (well at this point it's still a Console Application, as this is a lot easier to debug). The basic task of this service is to watch a folder for new *.tif Files. As soon as the Application found a .TIF file in the folder it starts another Application with the following code:

ProcessStartInfo command = new ProcessStartInfo(commandPath, commandParams);
command.RedirectStandardOutput=true;
command.UseShellExecute=false;
command.CreateNoWindow=true;

Process process = new Process();
process.startInfo = command;
process.Start();
process.WaitForExit();

This console application then uses IrfanView to split the Multipage-TIF into multiple singlepage-TIF (I use basically the same code as above to do this). After that, I check for a Barcode on the Scanned image (with zxing library). The found Barcode is then compared to the Oracle Database. Afterwards the file is converted to PDF and moved to a specific location, based on the found Barcode.

This console Application works perfectly, when I start it myself, but as soon as the "service" starts it, it will pause after a while and don't do anything until I close the "service"-console application. Then it finishes normally.

What could be the problem?

I tried to disable the Oracle, DB check and it worked. Afterwards I disabled my Logging class and it worked too. So my guess is, that I somehow use too much ressources or something like that. But where to start?

EDIT:
Some additional information. I just debugged the process, as VS is able to attach to a process to debug. The command that hangs is Console.WriteLine (called from within the Console application which is called by my "service" console. Any way that a console in a subprocess can only have a certain amount of lines/chars? can a console-output stream have a deadlock or what is this?


问:
Store object into array and group all array with the same value in PHP
I'm working on array right now and I need to arrange this based on value.

```<code>{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                },
            ]
        }
    }
</code>```

What I need to do is to store this object into array and group all question based on segment_name like this:

```<code>{
    "data":[
         {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role "
                    "question_collection": [
                        {
                            "id": 4,
                            "question": "How old are you?"
                        }
                    ]

                },
                {
                    "segment_name": "360 Segments",
                    "question_collection":[
                        {
                           "id": 1,
                           "question": "What is your food?"
                        },
                        {
                             "id": 2,
                            "question": "sample question"
                         }
                    ]
                },

            ]
        }
    ]
}
</code>```

And this is what I've tried to do:

```<code> $array_value =[];
        foreach ($query AS $key => &$data) {
            $array_value['id'] = $data['id'];
            $array_value['title'] = $data['title'];
            $array_value['emp_position'] = $data['position'];
            $array_value['rating'] = $data['rating_count'];

            if ( is_array($data) ) {
               $array_value['segments'][$key]['segment_name'] = $data['segment'];
               $array_value['segments'][$key]['question'] = $data['question'];
            }

        }
</code>```

答:
Try this solution, You can loop by array and group all keys

```<code>$json = '{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                }
            ]
        }
    }';

$data = json_decode($json,true);

$segments = $data['data']['segments'];
$new_segemnts = array();
foreach($segments as $segemnt)
{
    $key = $segemnt['segment_name'];

    $new_segemnts[$key]['segment_name']=$segemnt['segment_name'];
    $new_segemnts[$key]['question_collection'][]=array("question"=>$segemnt['question']);

}
$data['data']['segments'] = array_values($new_segemnts);
echo json_encode($data,JSON_PRETTY_PRINT);
</code>```

DEMO

ContentLicense: CC BY-SA 3.0

Body:
I'm working on array right now and I need to arrange this based on value.

{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                },
            ]
        }
    }

What I need to do is to store this object into array and group all question based on segment_name like this:

{
    "data":[
         {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role "
                    "question_collection": [
                        {
                            "id": 4,
                            "question": "How old are you?"
                        }
                    ]

                },
                {
                    "segment_name": "360 Segments",
                    "question_collection":[
                        {
                           "id": 1,
                           "question": "What is your food?"
                        },
                        {
                             "id": 2,
                            "question": "sample question"
                         }
                    ]
                },

            ]
        }
    ]
}

And this is what I've tried to do:

 $array_value =[];
        foreach ($query AS $key => &$data) {
            $array_value['id'] = $data['id'];
            $array_value['title'] = $data['title'];
            $array_value['emp_position'] = $data['position'];
            $array_value['rating'] = $data['rating_count'];

            if ( is_array($data) ) {
               $array_value['segments'][$key]['segment_name'] = $data['segment'];
               $array_value['segments'][$key]['question'] = $data['question'];
            }

        }

Body:
Try this solution, You can loop by array and group all keys

$json = '{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                }
            ]
        }
    }';

$data = json_decode($json,true);

$segments = $data['data']['segments'];
$new_segemnts = array();
foreach($segments as $segemnt)
{
    $key = $segemnt['segment_name'];

    $new_segemnts[$key]['segment_name']=$segemnt['segment_name'];
    $new_segemnts[$key]['question_collection'][]=array("question"=>$segemnt['question']);

}
$data['data']['segments'] = array_values($new_segemnts);
echo json_encode($data,JSON_PRETTY_PRINT);

DEMO


问:
Ansible Ad-hoc commands requests vault passwords
This afternoon when running ansible ad-hoc commands I've started to be prompted for the vault passwords.

The process shouldn't need this and this was never required before.

I'm just running something like

```<code>ansible prod_servers -m shell -a "ls -al /var/logs/" --sudo
</code>```

I can just provide the password and the command works, but it's driving me crazy.

We're using ansible 1.8.4 (don't ask) :(

答: Check for vaulted files under group_vars/host_vars in your inventory – this should be the only reason why password prompt may appear for ad-hoc commands.

Body:
This afternoon when running ansible ad-hoc commands I've started to be prompted for the vault passwords.

The process shouldn't need this and this was never required before.

I'm just running something like

ansible prod_servers -m shell -a "ls -al /var/logs/" --sudo

I can just provide the password and the command works, but it's driving me crazy.

We're using ansible 1.8.4 (don't ask) :(


问:
Install keras in Anaconda3 Ubuntu
I was trying to install keras in in anaconda in Ubuntu. I followed instuction from this site. All my packages are installed properly. Also in pip list I can see keras. But when I'm trying to import keras it's saying "no module called keras".

Can anyone please help me?

答: I simply use conda install keras and it works for me.

Title: Install keras in Anaconda3 Ubuntu


问:
Update Zero to One and One to Zero in SQL Server
I have a table with flag 0 and 1.

Please tell me how to update Zero to One and One to  Zero

```<code>DECLARE @a INT, @b INT

SELECT @a = number
FROM zerone
WHERE number = 0

SELECT @b = number
FROM zerone
WHERE number = 1

BEGIN
    IF @a = 0
        UPDATE zerone
        SET number = 1
        WHERE @a = 0
    ELSE IF @b = 1
        UPDATE zerone
        SET number = 0
        WHERE @b = 1
END
</code>```

This query is not working for me.

答:
As you have seen there are so many ways to perform that task but in this case, I would prefer @Abdul Rasheed.
We can also use below IIF logical function in SQLSERVER2012 or above.

```<code>UPDATE zerone
SET number = IIF (number = 1, 0, 1)
</code>```

Body:
I have a table with flag 0 and 1.

Please tell me how to update Zero to One and One to  Zero

DECLARE @a INT, @b INT

SELECT @a = number
FROM zerone
WHERE number = 0

SELECT @b = number
FROM zerone
WHERE number = 1

BEGIN
    IF @a = 0
        UPDATE zerone
        SET number = 1
        WHERE @a = 0
    ELSE IF @b = 1
        UPDATE zerone
        SET number = 0
        WHERE @b = 1
END

This query is not working for me.

Body:
As you have seen there are so many ways to perform that task but in this case, I would prefer @Abdul Rasheed.
We can also use below IIF logical function in SQLSERVER2012 or above.

UPDATE zerone
SET number = IIF (number = 1, 0, 1)


问:
Parent doesn't grow for added scrollbar width in Firefox
When the Child dictates the width of a Parent which has overflow: auto, Firefox doesn't allow space for the added width of a scrollbar (15px) which leaves the Child getting cut off and an overflow-x to appear on the Parent.

What's the best way to fix this issue?

https://codepen.io/rhysyg03/pen/wrKQJG

```<code>.content {
  position: absolute;
  overflow-y: auto;
  min-width:150px;
  max-height: 300px;
  padding: 8px;
  background:white;
  border:1px solid rgba(0,0,0,.12);
}
</code>```

For example, adding padding-right: 15px fixes the issue but then leaves the other browser's with an extra 15px.

Or adding a fixed width to the Parent fixes issue but then you're bound to a fixed width restriction and I want to leave the Parent flexible.

Or adding overflow-x: hidden hides the scrollbar, but leaves the Child cut off.

Update: display: flex on Parent fixes the issue for regular widths (ie: an image) but not the widths set by text with whitespace: nowrap.

Thanks.

Firefox:

Chrome:

答:
you can use @-moz-document to write some styles could be recognized by firefox only. see this: https://developer.mozilla.org/en-US/docs/Web/CSS/@document.

hopes helpful.

Body:
When the Child dictates the width of a Parent which has overflow: auto, Firefox doesn't allow space for the added width of a scrollbar (15px) which leaves the Child getting cut off and an overflow-x to appear on the Parent.

What's the best way to fix this issue?

https://codepen.io/rhysyg03/pen/wrKQJG

.content {
  position: absolute;
  overflow-y: auto;
  min-width:150px;
  max-height: 300px;
  padding: 8px;
  background:white;
  border:1px solid rgba(0,0,0,.12);
}

For example, adding padding-right: 15px fixes the issue but then leaves the other browser's with an extra 15px.

Or adding a fixed width to the Parent fixes issue but then you're bound to a fixed width restriction and I want to leave the Parent flexible.

Or adding overflow-x: hidden hides the scrollbar, but leaves the Child cut off.

Update: display: flex on Parent fixes the issue for regular widths (ie: an image) but not the widths set by text with whitespace: nowrap.

Thanks.

Firefox:

Chrome:


问:
how to subtract in sql using php
I would like to subtract the quantity in my database using php

part of HTML code

```<code><label class="control-label">Medicine Name</label>
<input type="text" class="form-control" name="medname">
<label class="control-label">Quantity</label>
<input type="text" class="form-control input-sm" name="quantity">
<button type="submit" class="btn" style="background:#830006;" name="submit1">OK</button>
</code>```

PHP

```<code>if (isset($_POST['submit1'])) {
  $mediname = pg_escape_string($_POST['medname']);
  $tits = pg_escape_string($_POST['quantity']);

  $quirt = ("UPDATE medicine_invent set med_stock = med_stock - $tits where med_name = $mediname");
  $sq = pg_query($quirt);
}
</code>```

please help me. i'm still a beginner at php. Thanks a lot.

答:
if the $mediname is string you should use quote around this var   (string var)

```<code> ("UPDATE medicine_invent
       set med_stock = med_stock - $tits
       where med_name = '$mediname'");
</code>```

Anyway you should not use php var directly in your sql code for avoid sqlinjection risk  .. check for you framework/dbdriver the correct use of parametrized  query and pass the value you need  using binding param features

Title: how to subtract in sql using php

Body:
I would like to subtract the quantity in my database using php

part of HTML code

Medicine Name
<input type="text" class="form-control" name="medname">
Quantity
<input type="text" class="form-control input-sm" name="quantity">
<button type="submit" class="btn" style="background:#830006;" name="submit1">OK</button>

PHP

if (isset($_POST['submit1'])) {
  $mediname = pg_escape_string($_POST['medname']);
  $tits = pg_escape_string($_POST['quantity']);

  $quirt = ("UPDATE medicine_invent set med_stock = med_stock - $tits where med_name = $mediname");
  $sq = pg_query($quirt);
}

please help me. i'm still a beginner at php. Thanks a lot.

Body:
if the $mediname is string you should use quote around this var   (string var)

 ("UPDATE medicine_invent
       set med_stock = med_stock - $tits
       where med_name = '$mediname'");

Anyway you should not use php var directly in your sql code for avoid sqlinjection risk  .. check for you framework/dbdriver the correct use of parametrized  query and pass the value you need  using binding param features


问:
Getting IMetadataDetailsProviders to Run More than Once in ASP.NET Core
This is a tricky question which will require some deep knowledge of the ASP.NET Core framework. I'll first explain what is happening in our application in the MVC 3 implementation.

There was a complex requirement which needed to be solved involving the ModelMetaData for our ViewModels on a particular view. This is a highly configurable application. So, for one "Journal Type", a property may be mandatory, whereas for another, the exact same property may be non-mandatory. Moreover, it may be a radio-button for one "Journal Type" and a select list for another. As there was a huge number of combinations, mixing and matching for all these configuration options, it was not practical to create a separate ViewModel type for each and every possible permutation. So, there was one ViewModel type and the ModelMetaData was set on the properties of that type dynamically.

This was done by creating a custom ModelMetadataProvider (by inheriting DataAnnotationsModelMetadataProvider).

Smash-cut to now, where we are upgrading the application and writing the server stuff in ASP.NET Core. I have identified that implementing IDisplayMetadataProvider is the equivalent way of modifying Model Metadata in ASP.NET Core.

The problem is, the framework has caching built into it and any class which implements IDisplayMetadataProvider only runs once. I discovered this while debugging the ASP.NET Core framework and this comment confirms my finding. Our requirement will no longer be met with such caching, as the first time the ViewModel type is accessed, the MetadataDetailsProvider will run and the result will be cached. But, as mentioned above, owing to the highly dynamic configuration, I need it to run prior to every ModelBinding. Otherwise, we will not be able to take advantage of ModelState. The first time that endpoint is hit, the meta-data is set in stone for all future requests.

And we kinda need to leverage that recursive process of going through all the properties using reflection to set the meta-data, as we don't want to have to do that ourselves (a massive endeavour beyond my pay-scale).

So, if anyone thinks there's something in the new Core framework which I have missed, by all means let me know. Even if it is as simple as removing that caching feature of ModelBinders and IDisplayMetadataProviders (that is what I'll be looking into over the next couple of days by going through the ASP.NET source).

答:
Model Metadata is cached due to performance considerations. Class DefaultModelMetadataProvider, which is default implementation of IModelMetadataProvider interface, is responsible for this caching. If your application logic requires that metadata is rebuilt on every request, you should substitute this implementation with your own.

You will make your life easier if you inherit your implementation from DefaultModelMetadataProvider and override bare minimum for achieving your goal. Seems like GetMetadataForType(Type modelType) should be enough:

```<code>public class CustomModelMetadataProvider : DefaultModelMetadataProvider
{
    public CustomModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider)
        : base(detailsProvider)
    {
    }

    public CustomModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider, IOptions<MvcOptions> optionsAccessor)
        : base(detailsProvider, optionsAccessor)
    {
    }

    public override ModelMetadata GetMetadataForType(Type modelType)
    {
        //  Optimization for intensively used System.Object
        if (modelType == typeof(object))
        {
            return base.GetMetadataForType(modelType);
        }

        var identity = ModelMetadataIdentity.ForType(modelType);
        DefaultMetadataDetails details = CreateTypeDetails(identity);

        //  This part contains the same logic as DefaultModelMetadata.DisplayMetadata property
        //  See https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Metadata/DefaultModelMetadata.cs

        var context = new DisplayMetadataProviderContext(identity, details.ModelAttributes);
        //  Here your implementation of IDisplayMetadataProvider will be called
        DetailsProvider.CreateDisplayMetadata(context);
        details.DisplayMetadata = context.DisplayMetadata;

        return CreateModelMetadata(details);
    }
}
</code>```

To replace DefaultModelMetadataProvider with your CustomModelMetadataProvider add following in ConfigureServices():

```<code>services.AddSingleton<IModelMetadataProvider, CustomModelMetadataProvider>();
</code>```

Body:
Model Metadata is cached due to performance considerations. Class DefaultModelMetadataProvider, which is default implementation of IModelMetadataProvider interface, is responsible for this caching. If your application logic requires that metadata is rebuilt on every request, you should substitute this implementation with your own.

You will make your life easier if you inherit your implementation from DefaultModelMetadataProvider and override bare minimum for achieving your goal. Seems like GetMetadataForType(Type modelType) should be enough:

public class CustomModelMetadataProvider : DefaultModelMetadataProvider
{
    public CustomModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider)
        : base(detailsProvider)
    {
    }

    public CustomModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider, IOptions<MvcOptions> optionsAccessor)
        : base(detailsProvider, optionsAccessor)
    {
    }

    public override ModelMetadata GetMetadataForType(Type modelType)
    {
        //  Optimization for intensively used System.Object
        if (modelType == typeof(object))
        {
            return base.GetMetadataForType(modelType);
        }

        var identity = ModelMetadataIdentity.ForType(modelType);
        DefaultMetadataDetails details = CreateTypeDetails(identity);

        //  This part contains the same logic as DefaultModelMetadata.DisplayMetadata property
        //  See https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Metadata/DefaultModelMetadata.cs

        var context = new DisplayMetadataProviderContext(identity, details.ModelAttributes);
        //  Here your implementation of IDisplayMetadataProvider will be called
        DetailsProvider.CreateDisplayMetadata(context);
        details.DisplayMetadata = context.DisplayMetadata;

        return CreateModelMetadata(details);
    }
}

To replace DefaultModelMetadataProvider with your CustomModelMetadataProvider add following in ConfigureServices():

services.AddSingleton<IModelMetadataProvider, CustomModelMetadataProvider>();


问:
Asp core -Angular 2 -Capturing Headers from initial rendering from server
I have an angular client application which is loaded in asp net core. The initial request which comes from asp net core to angular app gives a few headers , How can i capture those headers in angular to reuse them later.
     I am able to capture headers or intercept calls which are made by angular , how can i capture header from initial response. Please suggest.</p>

答:
Example of GET headers

```<code>http
  .get<MyJsonData>('/data.json', {observe: 'response'})
  .subscribe(resp => {
    // Here, resp is of type HttpResponse<MyJsonData>.
    // You can inspect its headers:
    console.log(resp.headers.get('X-Custom-Header'));
    // And access the body directly, which is typed as MyJsonData as requested.
    console.log(resp.body.someField);
  });
</code>```

example of POST with headers

```<code>http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  .subscribe();
</code>```

The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

More details https://angular.io/guide/http

Edit: I am not sure what do you mean by using them later - perhaps you can save them to SessionStorage or LocalStorage if you need them after refreshing the page.

Check this also: Accessing the web page's HTTP Headers in JavaScript might help

Body:
Example of GET headers

http
  .get<MyJsonData>('/data.json', {observe: 'response'})
  .subscribe(resp => {
    // Here, resp is of type HttpResponse<MyJsonData>.
    // You can inspect its headers:
    console.log(resp.headers.get('X-Custom-Header'));
    // And access the body directly, which is typed as MyJsonData as requested.
    console.log(resp.body.someField);
  });

example of POST with headers

http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  .subscribe();

The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

More details https://angular.io/guide/http

Edit: I am not sure what do you mean by using them later - perhaps you can save them to SessionStorage or LocalStorage if you need them after refreshing the page.

Check this also: Accessing the web page's HTTP Headers in JavaScript might help


问:
hide checkbox on particular date using moment and angular js
I want to hide a checkbox on a certain date for example 17 Nov using AngularJS and MomentJS.
I used a function

```<code>$scope.today = moment('2017-11-17').toDate();
$scope.checkNov = function(value) {
  if (moment().diff(value, 'day') == 0 && moment().diff(value, 'month') == 0 && moment().diff(value, 'year') == 0) return true;
}
</code>```

and called it on div for checkbox

```<code><div ng-hide="checkNov(today)">
<input type="checkbox"></div>
</code>```

the function is returning value=true that will give ng-hide="true" then it should hide. But it is still visible.

Also how to check for exact date comparision using Moment.JS? Because when I checked using console.log it is working for 18 nov as well.

Thank you.

答:
You could try this for the exact date comparison
http://momentjs.com/docs/#/query/is-same/</p>

Body:
I want to hide a checkbox on a certain date for example 17 Nov using AngularJS and MomentJS.
I used a function

$scope.today = moment('2017-11-17').toDate();
$scope.checkNov = function(value) {
  if (moment().diff(value, 'day') == 0 && moment().diff(value, 'month') == 0 && moment().diff(value, 'year') == 0) return true;
}

and called it on div for checkbox

<input type="checkbox">

the function is returning value=true that will give ng-hide="true" then it should hide. But it is still visible.

Also how to check for exact date comparision using Moment.JS? Because when I checked using console.log it is working for 18 nov as well.

Thank you.


答:
Please try below code: its in swift 3:

```<code>    let lattitude1Array = NSMutableArray()
    let lattitude2Array = NSMutableArray()
    for record in data {
        if let status = record["status"] as? Int {
            if status == 1 {
                lattitude1Array.add(record["lattitude"])
            } else {
                lattitude2Array.add(record["lattitude"])
            }
        }
    }
</code>```

Title: How to find value from dictionary

Body:
I have following simple dictionary and I want latitude array when status 1 it is store one array and status 2 it store second array
Please help me out

 data =     (
            {
        created = "2017-11-13 09:04:18";
        "end_date" = "2017-11-13 11:49:08";
        id = 878;
        latitude = "23.032190322875977000";
        longitude = "72.565238952636720000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 11:49:08";
        "end_date" = "2017-11-13 13:13:15";
        id = 888;
        latitude = "23.032133102416992000";
        longitude = "72.565208435058600000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:13:15";
        "end_date" = "2017-11-13 13:26:26";
        id = 891;
        latitude = "23.032199859619140000";
        longitude = "72.565269470214840000";
        status = 2;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:26:26";
        "end_date" = "2017-11-13 16:54:20";
        id = 892;
        latitude = "23.032056808471680000";
        longitude = "72.565223693847660000";
        status = 2;
        "user_id" = 21;
    }

)

Body:
Please try below code: its in swift 3:

    let lattitude1Array = NSMutableArray()
    let lattitude2Array = NSMutableArray()
    for record in data {
        if let status = record["status"] as? Int {
            if status == 1 {
                lattitude1Array.add(record["lattitude"])
            } else {
                lattitude2Array.add(record["lattitude"])
            }
        }
    }


问:
Foreign characters displaying delayed on cordova ios application
We are using Webfont Loader to load google fonts. And inside the active callback of WebFont.load we load our main script and bootstrap angular.js application.

```<code><script type="text/javascript">
WebFontConfig = {
    google: {
        families: ['Open Sans:400,700,700i,400i:latin-ext']
    },
    active: function() {
        var mainScript = document.createElement('script');
        mainScript.src = "/js/main.js";
        mainScript.onload = function() {
            angular.bootstrap(document, ['cob']);
        }

        document.body.appendChild(mainScript);
    }
};

WebFont.load(WebFontConfig);
</script>
</code>```

To make browser use default fonts until the google font file loaded, we set fonts for .wf-active class

```<code>html.wf-active {
    font-family: 'Open Sans', sans-serif;
}
</code>```

Inside angular run, we switch apploaded and clear screen from loaders and show the application.

```<code>angular.module('mymodule')
    .run([function() {
        $rootScope.appLoaded = true;
    }
]);
</code>```

html

```<code><body>
    <div class="app-loader" ng-hide="appLoaded">loading...</div>
    <div class="page-container" ng-if="appLoaded">
        application loaded. <button>GİRİŞ</button>
    </div>
</body>
</code>```

We see "loading..." until the font files loaded, then application bootstraps successfully.
But the button text is rendered as "G R  " for a couple of seconds, after a while 'İ' and 'Ş' characters are loaded into screen and we see GİRİŞ on button.

I am sure the font file is loaded before application bootstraps, because the font doesn't change after the application is loaded.

May be irrelevant but, I got some image files on the page and foreign characters are rendered with the image files. So there is some kind of a wierd screen render latency.

We only have this issue on iOS application, I have tested it on iPhone 6 and 6s, and on xcode simulators.
This works as intended on browsers (safari, chrome and firefox) and on android application we create with the same cordova project.

答:
After trying various preload methods, just as I was considering to give it up, I came accross to a fact here

most browsers download fonts when they're used in a page rather than
  when they're declared in CSS.

It seems like latin-ext subset of the font is delayed until it is used inside the page.

I have solved the issue by putting a dummy character (İ) that will make it download latin-ext subset on load screen

Body:
We are using Webfont Loader to load google fonts. And inside the active callback of WebFont.load we load our main script and bootstrap angular.js application.

To make browser use default fonts until the google font file loaded, we set fonts for .wf-active class

html.wf-active {
    font-family: 'Open Sans', sans-serif;
}

Inside angular run, we switch apploaded and clear screen from loaders and show the application.

angular.module('mymodule')
    .run([function() {
        $rootScope.appLoaded = true;
    }
]);

html

loading...

        application loaded. <button>GİRİŞ</button>

We see "loading..." until the font files loaded, then application bootstraps successfully.
But the button text is rendered as "G R  " for a couple of seconds, after a while 'İ' and 'Ş' characters are loaded into screen and we see GİRİŞ on button.

I am sure the font file is loaded before application bootstraps, because the font doesn't change after the application is loaded.

May be irrelevant but, I got some image files on the page and foreign characters are rendered with the image files. So there is some kind of a wierd screen render latency.

We only have this issue on iOS application, I have tested it on iPhone 6 and 6s, and on xcode simulators.
This works as intended on browsers (safari, chrome and firefox) and on android application we create with the same cordova project.


问:
Is there a way to build the mobile nav bar in ng2-bootstrap?
I've been implementing ng2-bootstrap and Angular2.

I cannot figure out how to make the mobile navbar open / close.

Is this something that just isn't supported yet?  Or am I missing something?

Update, html:

```<code><nav class="navbar navbar-default">
    <div class="container-fluid">

    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">
            <img src="/logo.png" />
        </a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
            <li router-active>
                <a [routerLink]=" ['Index'] ">Summary<span class="sr-only">(current)</span></a>
            </li>
            <li router-active>
                <a [routerLink]=" ['Portfolio'] ">Portfolio<span class="sr-only">(current)</span></a>
            </li>
            <li router-active>
                <a [routerLink]=" ['About'] ">About<span class="sr-only">(current)</span></a>
            </li>
        </ul>
        <form class="navbar-form navbar-left" role="search">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
        <ul class="nav navbar-nav navbar-right">
            <li dropdown keyboardNav="true">
                <a href class="dropdown-toggle" role="button" aria-expanded="false" dropdownToggle>
                    <span class="glyphicon glyphicon-user" aria-hidden="true"></span>
                    Andrew Duncan
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu" role="menu">
                    <li role="menuitem"><a class="dropdown-item" href="#">Account Settings</a></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
                    <li class="divider dropdown-divider"></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Logout</a></li>
                </ul>
            </li>

        </ul>
    </div>
</div>
</code>```

Typescript:

```<code>/*
 * Angular 2 decorators and services
 */
import { Component, ViewEncapsulation } from '@angular/core';
import { RouteConfig, Router } from '@angular/router-deprecated';

import { AppState } from './app.service';
import { Home } from './home';
import { RouterActive } from './router-active';
import { BUTTON_DIRECTIVES, DROPDOWN_DIRECTIVES } from '../../node_modules/ng2-bootstrap';
/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  pipes: [ ],
  providers: [ ],
  directives: [
    RouterActive,
    BUTTON_DIRECTIVES,
    DROPDOWN_DIRECTIVES ],
  encapsulation: ViewEncapsulation.None,
  styles: [
    require('./app.css')
  ],
  template: require('./app.html')
})
@RouteConfig([
  { path: '/',      name: 'Index', component: Home, useAsDefault: true },
  { path: '/home',  name: 'Home',  component: Home },
  // Async load a component using Webpack's require with es6-promise-loader and webpack `require`
  { path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') },
  { path: '/portfolio', name: 'Portfolio', loader: () => require('es6-promise!./portfolio')('Portfolio') }
])
export class App {
  angularclassLogo = 'assets/img/angularclass-avatar.png';
  loading = false;
  url = 'https://twitter.com/AngularClass';

  constructor(
    public appState: AppState) {

  }

  ngOnInit() {
    console.log('Initial App State', this.appState.state);
  }

}

/*
 * Please review the https://github.com/AngularClass/angular2-examples/ repo for
 * more angular app examples that you may copy/paste
 * (The examples may not be updated as quickly. Please open an issue on github for us to update it)
 * For help or questions please contact us at @AngularClass on twitter
 * or our chat on Slack at https://AngularClass.com/slack-join
 */
</code>```

答:
This is a limitation of navbar (https://github.com/valor-software/ngx-bootstrap/issues/540). So you need to manipulate the DOM element.

```<code><div class="navbar-header page-scroll">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" routerLink="/">
        <img src="assets/images/logo.png">
    </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
    <ul class="nav navbar-nav navbar-right" >
        <li class="hidden">
            <a></a>
        </li>
        <li><a routerLink="/" (click)="onMenuClick()">Home</a></li>
        <li><a routerLink="/about" (click)="onMenuClick()">About</a></li>
    </ul>
</div>
</code>```

And on .ts file your minimal code shoul be:

```<code>import { Component, ElementRef, Renderer } from '@angular/core';
export class HeaderComponent {
    constructor(private el: ElementRef, private renderer: Renderer) {
    }
    onMenuClick() {
        //this.el.nativeElement.querySelector('.navbar-ex1-collapse')  get the DOM
        //this.renderer.setElementClass('DOM-Element', 'css-class-you-want-to-add', false) if 3rd value is true
        //it will add the css class. 'in' class is responsible for showing the menu, remove it.
        this.renderer.setElementClass(this.el.nativeElement.querySelector('.navbar-ex1-collapse'), 'in', false);
    }
}
</code>```

Body:
I've been implementing ng2-bootstrap and Angular2.

I cannot figure out how to make the mobile navbar open / close.

Is this something that just isn't supported yet?  Or am I missing something?

Update, html:

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

        </button>

                Summary(current)

                Portfolio(current)

                About(current)

        <form class="navbar-form navbar-left" role="search">

                <input type="text" class="form-control" placeholder="Search">

            <button type="submit" class="btn btn-default">Submit</button>
        </form>

                    Andrew Duncan

Account Settings

Another action

Something else here

Logout

Typescript:

/*
 * Angular 2 decorators and services
 */
import { Component, ViewEncapsulation } from '@angular/core';
import { RouteConfig, Router } from '@angular/router-deprecated';

import { AppState } from './app.service';
import { Home } from './home';
import { RouterActive } from './router-active';
import { BUTTON_DIRECTIVES, DROPDOWN_DIRECTIVES } from '../../node_modules/ng2-bootstrap';
/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  pipes: [ ],
  providers: [ ],
  directives: [
    RouterActive,
    BUTTON_DIRECTIVES,
    DROPDOWN_DIRECTIVES ],
  encapsulation: ViewEncapsulation.None,
  styles: [
    require('./app.css')
  ],
  template: require('./app.html')
})
@RouteConfig([
  { path: '/',      name: 'Index', component: Home, useAsDefault: true },
  { path: '/home',  name: 'Home',  component: Home },
  // Async load a component using Webpack's require with es6-promise-loader and webpack `require`
  { path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') },
  { path: '/portfolio', name: 'Portfolio', loader: () => require('es6-promise!./portfolio')('Portfolio') }
])
export class App {
  angularclassLogo = 'assets/img/angularclass-avatar.png';
  loading = false;
  url = 'https://twitter.com/AngularClass';

  constructor(
    public appState: AppState) {

  }

  ngOnInit() {
    console.log('Initial App State', this.appState.state);
  }

}

/*
 * Please review the https://github.com/AngularClass/angular2-examples/ repo for
 * more angular app examples that you may copy/paste
 * (The examples may not be updated as quickly. Please open an issue on github for us to update it)
 * For help or questions please contact us at @AngularClass on twitter
 * or our chat on Slack at https://AngularClass.com/slack-join
 */

Body:
This is a limitation of navbar (https://github.com/valor-software/ngx-bootstrap/issues/540). So you need to manipulate the DOM element.

<div class="navbar-header page-scroll">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" routerLink="/">
        <img src="assets/images/logo.png">
    </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
    <ul class="nav navbar-nav navbar-right" >
        <li class="hidden">
            <a></a>
        </li>
        <li><a routerLink="/" (click)="onMenuClick()">Home</a></li>
        <li><a routerLink="/about" (click)="onMenuClick()">About</a></li>
    </ul>
</div>

And on .ts file your minimal code shoul be:

import { Component, ElementRef, Renderer } from '@angular/core';
export class HeaderComponent {
    constructor(private el: ElementRef, private renderer: Renderer) {
    }
    onMenuClick() {
        //this.el.nativeElement.querySelector('.navbar-ex1-collapse')  get the DOM
        //this.renderer.setElementClass('DOM-Element', 'css-class-you-want-to-add', false) if 3rd value is true
        //it will add the css class. 'in' class is responsible for showing the menu, remove it.
        this.renderer.setElementClass(this.el.nativeElement.querySelector('.navbar-ex1-collapse'), 'in', false);
    }
}


问:
knockout click event fires even during data change
Knockout click event fires even during data-bind.

Below is my view

```<code> <th class="cursor-pointer underline"
data-bind="click:javascripr:SortColumn($data.ColumnID)">
</code>```

I need click event to be fired only when i click on

答:
You shoould pass the function to the click binding:

```<code> <th class="cursor-pointer underline"
data-bind="click: function() { SortColumn($data.ColumnID); }">
</code>```

Instead of calling it via this code:

```<code>SortColumn($data.ColumnID)
</code>```

Body:
Knockout click event fires even during data-bind.

Below is my view

I need click event to be fired only when i click on

Body:
You shoould pass the function to the click binding:

 <th class="cursor-pointer underline"
data-bind="click: function() { SortColumn($data.ColumnID); }">

Instead of calling it via this code:

SortColumn($data.ColumnID)


问:
Why use Slug in Codeigniter?
i have that code. i don't get why they use slug. can someone explane?
i search what is the mean of slug. I think It is like a variable, I can chance it's name. but what is the importance of slug?
yazi_model.php model->

```<code><?php
    class Yazi_model extends CI_Model{
        public function __construct(){
            $this->load->database();
        }

        public function getir_yazilar($slug = FALSE){ //why slug should be false? why we use slug for it?
            if($slug === FALSE){ //is this 'if' is necessary? I can just write last code and it will work.
                $query = $this->db->get('yazilar');
                return $query->result_array();
            }
            $query = $this->db->get_where('yazilar',array('slug' => $slug));//why slug?
            return $query->row_array();
    }
}
</code>```

Yazilar.php controller->

```<code><?php
    class Yazilar extends CI_Controller{
        public function index(){ //why not use slug
            $veri['baslik'] = 'Son yazılar';
            $veri['yazilar'] = $this->yazi_model->getir_yazilar();
            $this->load->view('tema/header');
            $this->load->view('yazilar/index',$veri);
            $this->load->view('tema/footer');
        }

        public function detay($slug = NULL){ //why slug
            $veri['yazi'] = $this->yazi_model->getir_yazilar($slug); //why slug
            if(empty($veri['yazi'])){
                show_404();
            }

            $veri['baslik'] = $veri['yazi']['baslik'];
            $this->load->view('tema/header');
            $this->load->view('yazilar/detay',$veri);
            $this->load->view('tema/footer');
        }
    }
</code>```

答:
Slugs can be used for getting SEO Friendly urls.

For example :
From:

```<code>www.site.com/index.php/blog/view/8
</code>```

To :

```<code>www.site.com/index.php/blog/view/blog-name
</code>```

store the slugs in my database table, in a column called slug, then find a post with the slug, like this:

```<code>    public function view($slug)
{
    $query = $this->db->get_where('posts', array('slug' => $slug), 1);

    // Fetch the post row, display the post view, etc...
}
</code>```

Title: Why use Slug in Codeigniter?

Body:
i have that code. i don't get why they use slug. can someone explane?
i search what is the mean of slug. I think It is like a variable, I can chance it's name. but what is the importance of slug?
yazi_model.php model->

<?php
    class Yazi_model extends CI_Model{
        public function __construct(){
            $this->load->database();
        }

        public function getir_yazilar($slug = FALSE){ //why slug should be false? why we use slug for it?
            if($slug === FALSE){ //is this 'if' is necessary? I can just write last code and it will work.
                $query = $this->db->get('yazilar');
                return $query->result_array();
            }
            $query = $this->db->get_where('yazilar',array('slug' => $slug));//why slug?
            return $query->row_array();
    }
}

Yazilar.php controller->

<?php
    class Yazilar extends CI_Controller{
        public function index(){ //why not use slug
            $veri['baslik'] = 'Son yazılar';
            $veri['yazilar'] = $this->yazi_model->getir_yazilar();
            $this->load->view('tema/header');
            $this->load->view('yazilar/index',$veri);
            $this->load->view('tema/footer');
        }

        public function detay($slug = NULL){ //why slug
            $veri['yazi'] = $this->yazi_model->getir_yazilar($slug); //why slug
            if(empty($veri['yazi'])){
                show_404();
            }

            $veri['baslik'] = $veri['yazi']['baslik'];
            $this->load->view('tema/header');
            $this->load->view('yazilar/detay',$veri);
            $this->load->view('tema/footer');
        }
    }

Body:
Slugs can be used for getting SEO Friendly urls.

For example :
From:

www.site.com/index.php/blog/view/8

To :

www.site.com/index.php/blog/view/blog-name

store the slugs in my database table, in a column called slug, then find a post with the slug, like this:

    public function view($slug)
{
    $query = $this->db->get_where('posts', array('slug' => $slug), 1);

    // Fetch the post row, display the post view, etc...
}


问:
Gridview show edit button
Im having some issues with the edit button inside a gridview.
When you click edit in the gridview, the cancel  button gets the same cssclass as the edit button. So my cancel button gets the same edit icon.

I want to change this so that the cancel button gets a different css-class. So I can give it the right icon instead of an edit ico :)

```<code><asp:CommandField ShowEditButton="True" ButtonType="Button" ControlStyle-CssClass="edit-sprite"></asp:CommandField>
</code>```

答:
Solved it with CSS instead:

table tr td .edit_sprite:first-child{/img icon edit/}

table tr td .edit_sprite{/img icon cancel/}

Title: Gridview show edit button

Body:
Im having some issues with the edit button inside a gridview.
When you click edit in the gridview, the cancel  button gets the same cssclass as the edit button. So my cancel button gets the same edit icon.

I want to change this so that the cancel button gets a different css-class. So I can give it the right icon instead of an edit ico :)

<asp:CommandField ShowEditButton="True" ButtonType="Button" ControlStyle-CssClass="edit-sprite"></asp:CommandField>


问:
Spring Cloud Bus, how to specify multiple destination in /bus/refresh?destination=?
I have a config server that using Spring Cloud Config and Spring Cloud Bus and some clients that also have Spring Cloud Bus. Each time I change the config, I use postman to send /bus/refresh to the config server. I found two ways to do that:

Refresh a specific client: http://localhost/bus/refresh/app1:dev:8080

Refresh all clients: http://localhost/bus/refresh

Is there any way to refresh two specific clients with single post request?

答:
You can give multiple application name in single /bus/refresh?destination URL with & separated as below, it will refresh configuration of two specific mentioned applications(app1 and app2):

http://localhost/bus/refresh?destination=app1:&app2:


问:
Empty Netbeans 7 palette? How to restore it?
I use Netbeans 7 on Kubuntu 12.04. I start Netbeans like this:

```<code>netbeans --cp:a /usr/share/java/xercesImpl.jar &
</code>```

cause of known issue with Netbeans and Kubuntu 12.04. In the middle of my project my palette with Swing components just .. disappeared!

I see only sth like this:

How to restore default Netbeans palette?

I checked Ctrl+Shift+8 shortcut but with no results - the problem is still the same.

**EDIT:
I dont know what I did but now I see ONLY EMPTY palette :( : **

I also tried this:

1) I cd'ed to /home/mazix/.netbeans/7.0/config/Windows2Local/Groups/commonpalette
, ls'ed and saw only this: CommonPalette.wstcgrp

2) cd'ed to /home/mazix/.netbeans/7.0/config/Windows2Local/Components and saw this:

AnalyzerTopComponent.settings            output.settings
  AnalyzeStackTopComponent.settings        projectTabLogical_tc.settings
  breakpointsView.settings                 projectTab_tc.settings
  CallHierarchyTopComponent.settings       properties_1.settings
  callstackView.settings                   properties.settings
  CommonPalette.settings                   refactoring-preview.settings
  ComponentInspector.settings

  ReporterResultTopComponent.settings CssPreviewTC.settings

  resultsView.settings debugging.settings

  search-results.settings DeclarationTopComponent.settings

  services.settings evaluator.settings

  sessionsView.settings favorites.settings

  sources.settings find-usages.settings

  StyleBuilderTC.settings gsf-testrunner-results.settings

  svnversioning.settings hgversioning.settings

  synchronize.settings JavadocTopComponent.settings

  TaskListTopComponent.settings localsView.settings

  TerminalContainerTopComponent.settings
  MultiView-java#007Cform#007C_1.settings  threadsView.settings
  MultiView-java#007Cform#007C_2.settings  versioning_output.settings
  MultiView-java#007Cform#007C_4.settings  watchesView.settings
  MultiView-java#007Cform#007C.settings    Welcome.settings
  navigatorTC.settings

and didnt see any  _hidden files :(

答: Right-click mouse button at palette box. Choose command "reset palette".</p>

Body:
I use Netbeans 7 on Kubuntu 12.04. I start Netbeans like this:

netbeans --cp:a /usr/share/java/xercesImpl.jar &

cause of known issue with Netbeans and Kubuntu 12.04. In the middle of my project my palette with Swing components just .. disappeared!

I see only sth like this:

How to restore default Netbeans palette?

I checked Ctrl+Shift+8 shortcut but with no results - the problem is still the same.

**EDIT:
I dont know what I did but now I see ONLY EMPTY palette :( : **

I also tried this:

1) I cd'ed to /home/mazix/.netbeans/7.0/config/Windows2Local/Groups/commonpalette
, ls'ed and saw only this: CommonPalette.wstcgrp

2) cd'ed to /home/mazix/.netbeans/7.0/config/Windows2Local/Components and saw this:

AnalyzerTopComponent.settings            output.settings
  AnalyzeStackTopComponent.settings        projectTabLogical_tc.settings
  breakpointsView.settings                 projectTab_tc.settings
  CallHierarchyTopComponent.settings       properties_1.settings
  callstackView.settings                   properties.settings
  CommonPalette.settings                   refactoring-preview.settings
  ComponentInspector.settings

  ReporterResultTopComponent.settings CssPreviewTC.settings

  resultsView.settings debugging.settings

  search-results.settings DeclarationTopComponent.settings

  services.settings evaluator.settings

  sessionsView.settings favorites.settings

  sources.settings find-usages.settings

  StyleBuilderTC.settings gsf-testrunner-results.settings

  svnversioning.settings hgversioning.settings

  synchronize.settings JavadocTopComponent.settings

  TaskListTopComponent.settings localsView.settings

  TerminalContainerTopComponent.settings
  MultiView-java#007Cform#007C_1.settings  threadsView.settings
  MultiView-java#007Cform#007C_2.settings  versioning_output.settings
  MultiView-java#007Cform#007C_4.settings  watchesView.settings
  MultiView-java#007Cform#007C.settings    Welcome.settings
  navigatorTC.settings

and didnt see any  _hidden files :(


答:
Do it like below:-

```<code><?php

$json = '{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "id": 4,
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "id": 1,
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "id": 2,
                    "question": "sample question"
                }
            ]
        }
    }
';

$query = json_decode($json,true);

$segment_array = [];
foreach($query['data']['segments'] as $arr){
  $segment_array[$arr['segment_name']]['segment_name'] = $arr['segment_name'];
  $segment_array[$arr['segment_name']]['question_collection'][] = ['id'=>$arr['id'],'question'=>$arr['question']] ;
}

$query['data']['segments'] = array_values($segment_array);

echo json_encode($query,JSON_PRETTY_PRINT);
</code>```

OUTPUT:- https://eval.in/902194

Title: Store object into array and group all array with the same value in PHP

Body:
I'm working on array right now and I need to arrange this based on value.

{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                },
            ]
        }
    }

What I need to do is to store this object into array and group all question based on segment_name like this:

{
    "data":[
         {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role "
                    "question_collection": [
                        {
                            "id": 4,
                            "question": "How old are you?"
                        }
                    ]

                },
                {
                    "segment_name": "360 Segments",
                    "question_collection":[
                        {
                           "id": 1,
                           "question": "What is your food?"
                        },
                        {
                             "id": 2,
                            "question": "sample question"
                         }
                    ]
                },

            ]
        }
    ]
}

And this is what I've tried to do:

 $array_value =[];
        foreach ($query AS $key => &$data) {
            $array_value['id'] = $data['id'];
            $array_value['title'] = $data['title'];
            $array_value['emp_position'] = $data['position'];
            $array_value['rating'] = $data['rating_count'];

            if ( is_array($data) ) {
               $array_value['segments'][$key]['segment_name'] = $data['segment'];
               $array_value['segments'][$key]['question'] = $data['question'];
            }

        }

Body:
Do it like below:-

<?php

$json = '{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "id": 4,
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "id": 1,
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "id": 2,
                    "question": "sample question"
                }
            ]
        }
    }
';

$query = json_decode($json,true);

$segment_array = [];
foreach($query['data']['segments'] as $arr){
  $segment_array[$arr['segment_name']]['segment_name'] = $arr['segment_name'];
  $segment_array[$arr['segment_name']]['question_collection'][] = ['id'=>$arr['id'],'question'=>$arr['question']] ;
}

$query['data']['segments'] = array_values($segment_array);

echo json_encode($query,JSON_PRETTY_PRINT);

OUTPUT:- https://eval.in/902194


答:
You could use TemplateFields instead of CommandFields:</p>

```<code>     <asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="EditButton"
                            runat="server"
                            CssClass="EditButton"
                            CommandName="Edit"
                            Text="Edit" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:LinkButton ID="UpdateButton"
                            runat="server"
                            CssClass="UpdateButton"
                            CommandName="Update"
                            Text="Update" />
            <asp:LinkButton ID="Cancel"
                            runat="server"
                            CssClass="CancelButton"
                            CommandName="Cancel"
                            Text="Cancel" />
        </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField>
         <ItemTemplate>
           <asp:LinkButton ID="DeleteButton"
                        CssClass="DeleteButton"
                        Text="Delete"
                        CommandName="Delete"
                        runat="server" />
         </ItemTemplate>
     </asp:TemplateField>
</code>```

Title: Gridview show edit button

Body:
You could use TemplateFields instead of CommandFields:

     <asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="EditButton"
                            runat="server"
                            CssClass="EditButton"
                            CommandName="Edit"
                            Text="Edit" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:LinkButton ID="UpdateButton"
                            runat="server"
                            CssClass="UpdateButton"
                            CommandName="Update"
                            Text="Update" />&nbsp;
            <asp:LinkButton ID="Cancel"
                            runat="server"
                            CssClass="CancelButton"
                            CommandName="Cancel"
                            Text="Cancel" />
        </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField>
         <ItemTemplate>
           <asp:LinkButton ID="DeleteButton"
                        CssClass="DeleteButton"
                        Text="Delete"
                        CommandName="Delete"
                        runat="server" />
         </ItemTemplate>
     </asp:TemplateField>


问:
Is it a good practice to wrap all layouts in CoordinatorLayout?
I'm thinking of a way to implement Android Snackbars in my app. Basically, I want to be able to show Snackbar from anywhere in the app.

As I found out, android.support.design.widget.Snackbar performs the best when put in android.support.design.widget.CoordinatorLayout. Otherwise, I cannot swipe it away, it shows over navigation drawer and doesn't interact with Floating Action Button.

So the question is: Is it a good practice to wrap ALL my layouts in CoordinatorLayout, get the reference for it in a BaseActivity, so that it can be passed to Snackbar from almost anywhere?

That seems to be a solid way to ensure the Snackbar and other layout components behave correctly, but... well, means touching all layouts and having one BaseActivity which is extended by all other Activities and which would be accessed from any Fragment wanting to show a Snackbar.

Is there a better way?

答:
Yes, you can wrap up your layout into a coordinator layout, like</p>

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <Button
            android:id="@+id/btnSimpleSnackbar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="Simple Snackbar" />

        <Button
            android:id="@+id/btnActionCallback"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="With Action Callback" />

        <Button
            android:id="@+id/btnCustomSnackbar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Custom Color" />

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Body:
Yes, you can wrap up your layout into a coordinator layout, like

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <Button
            android:id="@+id/btnSimpleSnackbar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="Simple Snackbar" />

        <Button
            android:id="@+id/btnActionCallback"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="With Action Callback" />

        <Button
            android:id="@+id/btnCustomSnackbar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Custom Color" />

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>


问:
Parallel Deployment Exception
when I deploy a new version (3.0.1) of my webapp on Tomcat 8 [on tomcat is deployed an older version (3.0.0)] i get this exception:

Failed to register LiveBeansView MBean; nested exception is javax.management.InstanceAlreadyExistsException

org.springframework.context.ApplicationContextException: Failed to register LiveBeansView MBean; nested exception is javax.management.InstanceAlreadyExistsException: security-base,security-api:application=/MyWebApplication
      at org.springframework.context.support.LiveBeansView.registerApplicationContext(LiveBeansView.java:72)
      at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:776)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
      at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
      at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
      at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
      at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
      at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
      at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
      at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
      at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
      at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
      at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:473)
      at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1617)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
      at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
      at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1483)
      at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:731)
      at org.apache.catalina.manager.ManagerServlet.doPut(ManagerServlet.java:424)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:651)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:589)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: javax.management.InstanceAlreadyExistsException: security-base,security-api:application=/MyWebApplication
      at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
      at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
      at org.springframework.context.support.LiveBeansView.registerApplicationContext(LiveBeansView.java:68)
      ... 51 more

In web.xml of my application i have this configuration:

```<code><context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>
<context-param>
    <param-name>spring.liveBeansView.mbeanDomain</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>
</code>```

Anyone can help me ?

答:
Since you have two deployments on your Tomcat server for the same application (albeit different versions), you'll need to name your MBeans differently. Since MBeans are accessed per server (via a single JMX endpoint), each MBean identifier has to be separate.

You have a few options to make these unique in your apps:

The simplest solution is to set endpoints.jmx.unique-names to true and let Spring Boot make the MBean paths unique for you, rather than using default names.
.

Alternatively, you can change the MBean domain by setting thespring.jmx.default-domain=applicationname for the application

And you might likely not need this, but adding here for completeness; if you're manually loading your beans in Spring Configuration, you can add the EnableMBeanExport specifying a domain as such:

```<code>@Configuration
@EnableMBeanExport(defaultDomain="first")
public class MBeanConfig {...}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Parallel Deployment Exception

Body:
when I deploy a new version (3.0.1) of my webapp on Tomcat 8 [on tomcat is deployed an older version (3.0.0)] i get this exception:

Failed to register LiveBeansView MBean; nested exception is javax.management.InstanceAlreadyExistsException

org.springframework.context.ApplicationContextException: Failed to register LiveBeansView MBean; nested exception is javax.management.InstanceAlreadyExistsException: security-base,security-api:application=/MyWebApplication
      at org.springframework.context.support.LiveBeansView.registerApplicationContext(LiveBeansView.java:72)
      at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:776)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
      at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
      at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
      at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
      at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
      at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
      at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
      at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
      at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
      at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
      at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:473)
      at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1617)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
      at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
      at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1483)
      at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:731)
      at org.apache.catalina.manager.ManagerServlet.doPut(ManagerServlet.java:424)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:651)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:589)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: javax.management.InstanceAlreadyExistsException: security-base,security-api:application=/MyWebApplication
      at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
      at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
      at org.springframework.context.support.LiveBeansView.registerApplicationContext(LiveBeansView.java:68)
      ... 51 more

In web.xml of my application i have this configuration:

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>
<context-param>
    <param-name>spring.liveBeansView.mbeanDomain</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>

Anyone can help me ?

Body:
Since you have two deployments on your Tomcat server for the same application (albeit different versions), you'll need to name your MBeans differently. Since MBeans are accessed per server (via a single JMX endpoint), each MBean identifier has to be separate.

You have a few options to make these unique in your apps:

The simplest solution is to set endpoints.jmx.unique-names to true and let Spring Boot make the MBean paths unique for you, rather than using default names.
.

Alternatively, you can change the MBean domain by setting thespring.jmx.default-domain=applicationname for the application

And you might likely not need this, but adding here for completeness; if you're manually loading your beans in Spring Configuration, you can add the EnableMBeanExport specifying a domain as such:

@Configuration
@EnableMBeanExport(defaultDomain="first")
public class MBeanConfig {...}