问:
Python argparser mutually exclusive with same argument in multiple groups
I use argparser as a generic way to provide inputs on multiple different files, that are used to generate at the end a json, and sent to a database.
Have that said, I want to use multiple mutually exclusive groups, with the option to a flag being part of multiple different groups (as in the example below).

```<code>parser = argparser.argumentParser

group1 = parser.add_mutually_exclusive_group()
group2 = parser.add_mutually_exclusive_group(required=True)
group3 = parser.add_mutually_exclusive_group()

group1.add_argument('-a', type=int)
group1.add_argument('-d', type=int)

group2.add_argument('-z', type=int)
group2.add_argument('-x', type=int)

group3.add_argument('-a', type=int)
group3.add_argument('-z', type=int)
</code>```

it means that -d and -z can go together (but -z or -x are mandatory), giving me the option to have -a -d -x OR -z -d

for some reason, the argparser thinks each one of the -a or -z flags are conflicting, so i have added the conflict_handler to 'resolve', but seems to have no effect

答:
I think what you're looking for is the sub_parsers option from argparse.
Kindly check the link from the python docs add_subparsers.

Body:
I use argparser as a generic way to provide inputs on multiple different files, that are used to generate at the end a json, and sent to a database.
Have that said, I want to use multiple mutually exclusive groups, with the option to a flag being part of multiple different groups (as in the example below).

parser = argparser.argumentParser

group1 = parser.add_mutually_exclusive_group()
group2 = parser.add_mutually_exclusive_group(required=True)
group3 = parser.add_mutually_exclusive_group()

group1.add_argument('-a', type=int)
group1.add_argument('-d', type=int)

group2.add_argument('-z', type=int)
group2.add_argument('-x', type=int)

group3.add_argument('-a', type=int)
group3.add_argument('-z', type=int)

it means that -d and -z can go together (but -z or -x are mandatory), giving me the option to have -a -d -x OR -z -d

for some reason, the argparser thinks each one of the -a or -z flags are conflicting, so i have added the conflict_handler to 'resolve', but seems to have no effect


来源: stackexchange

问:
FabricJS - Create group of objects including custom extended object
I'm using Fabric JS to draw on a canvas. I've created a custom object called LineArrow which extends the fabric.Line object and adds an arrow to the end. Here is the basic code and a JSFiddle of it working https://jsfiddle.net/oyqw228o/9/

```<code>const LineArrow = fabric.util.createClass(fabric.Line, {
  type: 'line-arrow',

  initialize(element, options) {
    options || (options = {});
    this.callSuper('initialize', element, options);

    // Set default options
    this.set({
      hasBorders: false,
      hasControls: false,
      perPixelTargetFind: true,
    });
  },

  _render(ctx) {
    this.callSuper('_render', ctx);

    // do not render if width/height are zeros or object is not visible
    if (this.width === 0 || this.height === 0 || !this.visible) return;
    ctx.save();

    const xDiff = this.x2 - this.x1;
    const yDiff = this.y2 - this.y1;
    const angle = Math.atan2(yDiff, xDiff);
    ctx.translate((this.x2 - this.x1) / 2, (this.y2 - this.y1) / 2);
    ctx.rotate(angle);
    ctx.beginPath();
    // Move 5px in front of line to start the arrow so it does not have the square line end showing in front (0,0)
    ctx.moveTo(5, 0);
    ctx.lineTo(-5, 5);
    ctx.lineTo(-5, -5);
    ctx.closePath();
    ctx.fillStyle = this.stroke;
    ctx.fill();
    ctx.restore();
  },
});
</code>```

This renders as expected, however what I want to do is to add 'anchor points' to the start and end of this object to allow people to alter the line. The anchor points should only display if the line is selected. This is how I'd like it to look:

Here is a JSFiddle trying to render a group consisting of the custom line and 2 basic fabric.Circle objects https://jsfiddle.net/6v0s0h1x/3/

I get the error Uncaught TypeError: o.setCoords is not a function.

答:
Create two circle and add to canvas. When you select a line object you need to make the circle visible using visible = true.
And set left and top of circles from selected line points(x1,y1,x2,y2).

On moving of circle you need to get the points from left/top and set to selected line points.

On selected line deselect disable the circles .

Here is jsFiddle.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Fabric JS to draw on a canvas. I've created a custom object called LineArrow which extends the fabric.Line object and adds an arrow to the end. Here is the basic code and a JSFiddle of it working https://jsfiddle.net/oyqw228o/9/

const LineArrow = fabric.util.createClass(fabric.Line, {
  type: 'line-arrow',

  initialize(element, options) {
    options || (options = {});
    this.callSuper('initialize', element, options);

    // Set default options
    this.set({
      hasBorders: false,
      hasControls: false,
      perPixelTargetFind: true,
    });
  },

  _render(ctx) {
    this.callSuper('_render', ctx);

    // do not render if width/height are zeros or object is not visible
    if (this.width === 0 || this.height === 0 || !this.visible) return;
    ctx.save();

    const xDiff = this.x2 - this.x1;
    const yDiff = this.y2 - this.y1;
    const angle = Math.atan2(yDiff, xDiff);
    ctx.translate((this.x2 - this.x1) / 2, (this.y2 - this.y1) / 2);
    ctx.rotate(angle);
    ctx.beginPath();
    // Move 5px in front of line to start the arrow so it does not have the square line end showing in front (0,0)
    ctx.moveTo(5, 0);
    ctx.lineTo(-5, 5);
    ctx.lineTo(-5, -5);
    ctx.closePath();
    ctx.fillStyle = this.stroke;
    ctx.fill();
    ctx.restore();
  },
});

This renders as expected, however what I want to do is to add 'anchor points' to the start and end of this object to allow people to alter the line. The anchor points should only display if the line is selected. This is how I'd like it to look:

Here is a JSFiddle trying to render a group consisting of the custom line and 2 basic fabric.Circle objects https://jsfiddle.net/6v0s0h1x/3/

I get the error Uncaught TypeError: o.setCoords is not a function.


问:
minimum Age validation laravel
I want to validation a users information like date of birth for that i have used following line of statement in validation, But how do i make it dynamic so users minimum age could be 13. below that can't register?</p>

```<code>  return Validator::make($data, [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'date_of_birth' =>'required|date|before:2011-06-08',
        ]);
</code>```

答:
You can use Carbon for that like this :

```<code>return Validator::make($data, [
        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'date_of_birth' =>'required|date|before:'.Carbon::now()->subYears(13),
    ]);
</code>```

Ps : Don't forget to add the the import use Carbon\Carbon;.

Title: minimum Age validation laravel

Body:
I want to validation a users information like date of birth for that i have used following line of statement in validation, But how do i make it dynamic so users minimum age could be 13. below that can't register?

  return Validator::make($data, [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'date_of_birth' =>'required|date|before:2011-06-08',
        ]);

Body:
You can use Carbon for that like this :

return Validator::make($data, [
        'first_name' => 'required|string|max:255',
        'last_name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'date_of_birth' =>'required|date|before:'.Carbon::now()->subYears(13),
    ]);

Ps : Don't forget to add the the import use Carbon\Carbon;.


问:
How To pass php variable into ajax data
How can I send PHP  variable sprod into ajax i need to send this id to check.php page </p>

```<code><script>
function getState(val) {

    $.ajax({
    type: "POST",
    url: "check.php",
    data: {id: val, id2:$prod },
    dataType:'json',
    success: function(data){
        $("#style_code").children().remove();
        $("#style_image").children().remove();

         data.option.forEach(function (item) {
                $("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
                $('#style_image').append('<img  src="images/'+item.image_name+'" data-imagezoom="true" class="img-responsive" alt="" />')
            //$("#style_image").html(data);
            });
    }
    });
}
</script>
</code>```

答:
use <?php echo $prod ?> to access php variables in ajax.

```<code> data: {id: val, id2:<?php echo $prod ?> },
</code>```

Title: How To pass php variable into ajax data

Body:
use <?php echo $prod ?> to access php variables in ajax.

 data: {id: val, id2:<?php echo $prod ?> },


问:
can't install adminator admin dashboard using git
this is my first time using git, I am trying to install adminator admin dashboard and I am following the rules and solve problems, but now this problem couldn't solve it from hours!! I am so confused and don't know what to do, can you help me please??

--when I type npm install everything go smoothly until this happening:

```<code> ==> cwd: C:\Users\Zeineb\Adminator\node_modules\better-sqlite3
 ==> node-gyp rebuild
 C:\Users\Zeineb\Adminator\node_modules\better-sqlite3>if not defined
 npm_config_node_gyp (node "C:\Users\Zeineb\Adminator\node_modules\better-
 sqlite3\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node
 "" rebuild )
 Building the projects in this solution one at a time. To enable parallel
 build, please add the "/m" switch.
 unpack_sqlite_dep
 'python' is not recognized as an internal or external command,
 operable program or batch file.
 C:\Program Files
 (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(171,5):
 error MSB6006: "cmd.exe" exi
 ted with code 1. [C:\Users\Zeineb\Adminator\node_modules\better-
 sqlite3\build\deps\action_before_build.vcxproj]
 gyp ERR! build error
 gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe`
 failed with exit code: 1
 gyp ERR! stack     at ChildProcess.onExit
 (C:\Users\Zeineb\Adminator\node_modules\node-gyp\lib\build.js:258:23)
 gyp ERR! stack     at ChildProcess.emit (events.js:159:13)
 gyp ERR! stack     at Process.ChildProcess._handle.onexit
 (internal/child_process.js:209:12)
 gyp ERR! System Windows_NT 10.0.15063
 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe"
 "C:\\Users\\Zeineb\\Adminator\\node_modules\\node-gyp\\bin\\node-gyp.js"
 "rebuild"
 gyp ERR! cwd C:\Users\Zeineb\Adminator\node_modules\better-sqlite3
 gyp ERR! node -v v9.2.0
 gyp ERR! node-gyp -v v3.6.2
 gyp ERR! not ok
 Error: exit code 1
 at ChildProcess.<anonymous> (C:\Users\Zeineb\Adminator\node_modules\lzz-
 gyp\lib\exec.js:19:12)
 at ChildProcess.emit (events.js:159:13)
 at Process.ChildProcess._handle.onexit (internal/child_process.js:209:12)
</code>```

and at the end of the installation this is written :

```<code>npm notice created a lockfile as package-lock.json. You should commit this
file.
npm WARN postcss-html@0.11.0 requires a peer of postcss-sass@>=0.2.0 but
none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3
(node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for
fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current:
{"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: better-sqlite3@4.0.3
(node_modules\better-sqlite3):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: better-sqlite3@4.0.3
install: `node deps/install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
</code>```

I am using windows 10 , npm v 5.5.1

答:
Solved !!

I first tried to install Python via git, it didn't install or I did something wrong since I am a newbie at git environment, so I installed it via visual studio, and put the following into path environment variables :

```<code> 1)C:\Python27amd64
 2)C:\Python27amd64\Lib\site-packages\
 3)C:\Python27amd64\Scripts
</code>```

Now everything is working totally fine, all thanks to @TGrif for making me re-check the Python thing.

Body:
this is my first time using git, I am trying to install adminator admin dashboard and I am following the rules and solve problems, but now this problem couldn't solve it from hours!! I am so confused and don't know what to do, can you help me please??

--when I type npm install everything go smoothly until this happening:

 ==> cwd: C:\Users\Zeineb\Adminator\node_modules\better-sqlite3
 ==> node-gyp rebuild
 C:\Users\Zeineb\Adminator\node_modules\better-sqlite3>if not defined
 npm_config_node_gyp (node "C:\Users\Zeineb\Adminator\node_modules\better-
 sqlite3\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node
 "" rebuild )
 Building the projects in this solution one at a time. To enable parallel
 build, please add the "/m" switch.
 unpack_sqlite_dep
 'python' is not recognized as an internal or external command,
 operable program or batch file.
 C:\Program Files
 (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(171,5):
 error MSB6006: "cmd.exe" exi
 ted with code 1. [C:\Users\Zeineb\Adminator\node_modules\better-
 sqlite3\build\deps\action_before_build.vcxproj]
 gyp ERR! build error
 gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe`
 failed with exit code: 1
 gyp ERR! stack     at ChildProcess.onExit
 (C:\Users\Zeineb\Adminator\node_modules\node-gyp\lib\build.js:258:23)
 gyp ERR! stack     at ChildProcess.emit (events.js:159:13)
 gyp ERR! stack     at Process.ChildProcess._handle.onexit
 (internal/child_process.js:209:12)
 gyp ERR! System Windows_NT 10.0.15063
 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe"
 "C:\\Users\\Zeineb\\Adminator\\node_modules\\node-gyp\\bin\\node-gyp.js"
 "rebuild"
 gyp ERR! cwd C:\Users\Zeineb\Adminator\node_modules\better-sqlite3
 gyp ERR! node -v v9.2.0
 gyp ERR! node-gyp -v v3.6.2
 gyp ERR! not ok
 Error: exit code 1
 at ChildProcess.<anonymous> (C:\Users\Zeineb\Adminator\node_modules\lzz-
 gyp\lib\exec.js:19:12)
 at ChildProcess.emit (events.js:159:13)
 at Process.ChildProcess._handle.onexit (internal/child_process.js:209:12)

and at the end of the installation this is written :

npm notice created a lockfile as package-lock.json. You should commit this
file.
npm WARN postcss-html@0.11.0 requires a peer of postcss-sass@>=0.2.0 but
none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3
(node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for
fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current:
{"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: better-sqlite3@4.0.3
(node_modules\better-sqlite3):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: better-sqlite3@4.0.3
install: `node deps/install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

I am using windows 10 , npm v 5.5.1

Body:
Solved !!

I first tried to install Python via git, it didn't install or I did something wrong since I am a newbie at git environment, so I installed it via visual studio, and put the following into path environment variables :

 1)C:\Python27amd64
 2)C:\Python27amd64\Lib\site-packages\
 3)C:\Python27amd64\Scripts

Now everything is working totally fine, all thanks to @TGrif for making me re-check the Python thing.


问:
Property observers willSet and didSet; Property getters and setters
What is the difference between willSet - didSet, and get - set, when working with this inside a property?

From my point of view, both of them can set a value for a property. When, and why, should I use willSet - didSet, and when get - set?

I know that for willSet and didSet, the structure looks like this:

```<code>var variable1 : Int = 0 {
    didSet {
        println (variable1)
    }
    willSet(newValue) {
    ..
    }
}

var variable2: Int {
    get {
        return variable2
    }
    set (newValue){
    }
}
</code>```

答:
get set:

get set are Computed Properties Which do not actually store a
  value. Instead, they provide a getter and an optional setter to
  retrieve and set other properties and values indirectly

Additionally you can define Read-Only Computed Properties.
A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value

Example get only property-

```<code> var number: Double {
        return .pi*2
    }
</code>```

willSet didSet:

willSet didSet are Property Observers

Property observers observe and respond to changes in a property’s
  value. Property observers are called every time a property’s value is
  set, even if the new value is the same as the property’s current
  value.

willSet is called just before the value is stored.

didSet is called immediately after the new value is stored.

Example -

```<code>var score: Int = 0 {
    willSet(newScore) {
        print("willSet  score to \(newScore)")
    }
    didSet {
        print("didSet score to \(oldValue) new score is: \(score)")
    }
}
score = 10
//Output
//willSet  score to 10
//didSet score to 0 new score is: 10
</code>```

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

ContentLicense: CC BY-SA 4.0

Body:
What is the difference between willSet - didSet, and get - set, when working with this inside a property?

From my point of view, both of them can set a value for a property. When, and why, should I use willSet - didSet, and when get - set?

I know that for willSet and didSet, the structure looks like this:

var variable1 : Int = 0 {
    didSet {
        println (variable1)
    }
    willSet(newValue) {
    ..
    }
}

var variable2: Int {
    get {
        return variable2
    }
    set (newValue){
    }
}

Body:
get set:

get set are Computed Properties Which do not actually store a
  value. Instead, they provide a getter and an optional setter to
  retrieve and set other properties and values indirectly

Additionally you can define Read-Only Computed Properties.
A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value

Example get only property-

 var number: Double {
        return .pi*2
    }

willSet didSet:

willSet didSet are Property Observers

Property observers observe and respond to changes in a property’s
  value. Property observers are called every time a property’s value is
  set, even if the new value is the same as the property’s current
  value.

willSet is called just before the value is stored.

didSet is called immediately after the new value is stored.

Example -

var score: Int = 0 {
    willSet(newScore) {
        print("willSet  score to \(newScore)")
    }
    didSet {
        print("didSet score to \(oldValue) new score is: \(score)")
    }
}
score = 10
//Output
//willSet  score to 10
//didSet score to 0 new score is: 10

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html


问:
Tweeting Automatically to twitter
I have used followint curl functionality to tweet automatically from my codeigniter page but I am getting an HTTP responce code 401 (not authorised).

the code is:

```<code>var $accounts_table = 'accounts';
var $update_url = 'http://twitter.com/statuses/update.xml';

function update_status($username, $password, $message)
{
    $ch = curl_init($this->update_url);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $username .':'.$password);

    curl_exec($ch);

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    echo $httpcode;
    // if we were successfull we need to update our last_message
    if ($httpcode == '200')
    {
        $this->db->where('active', '1');
        $this->db->update($this->accounts_table, array('last_message' => $message));

        return TRUE;
    }

    else
    {
        return FALSE;
    }
}
</code>```

Please kindly help me to solve out this issue.

Thanks in advance.

答:
AFAIK, twitter has moved onto OAuth.ie, no more basic authentication.

Read More about OAuth here.

OAuth supported libraries.

ContentLicense: CC BY-SA 2.5

Title: Tweeting Automatically to twitter

Body:
I have used followint curl functionality to tweet automatically from my codeigniter page but I am getting an HTTP responce code 401 (not authorised).

the code is:

var $accounts_table = 'accounts';
var $update_url = 'http://twitter.com/statuses/update.xml';

function update_status($username, $password, $message)
{
    $ch = curl_init($this->update_url);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $username .':'.$password);

    curl_exec($ch);

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    echo $httpcode;
    // if we were successfull we need to update our last_message
    if ($httpcode == '200')
    {
        $this->db->where('active', '1');
        $this->db->update($this->accounts_table, array('last_message' => $message));

        return TRUE;
    }

    else
    {
        return FALSE;
    }
}

Please kindly help me to solve out this issue.

Thanks in advance.


问:
adding string prefix to every log message in spring mvc log4j
I want to have my string added as prefix to every logging message in app. I mean, I have several java apps, and I want one to have some prefix in message like:

DATE, INFO(or other), [sample] (-->this is my added string) , rest of standard message

I have seen a several tutorials, but none of them worked properly for me. I have already included dependency in pom:

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

Do you have any trick or simple solution for that? To write some kind of wrapper, or configuration class?

答:
Mapped Diagnostic Context (MDC) logging allows you to set attributes associated with current thread, so that SLF4J (via your logger implementation library) can log those attributes with each logging statement without it having to be specified.
So what you need is to put your prefix text in MDC. If you're using Spring MVC then a way is to implement a HandlerInterceptor.

```<code>import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoggingInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("PREFIX", "your text");
        return true;
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.clear();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        MDC.clear();
    }
}

import com.tigerit.kai.education.util.LoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class BeanConfiguration {

   @Bean
   public LoggingInterceptor loggingHandlerInterceptor() {
      return new LoggingInterceptor();
   }

   @Bean
   public WebMvcConfigurerAdapter webConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(loggingHandlerInterceptor());
         }
      };
   }
}
</code>```

And finally add following in application.properties

```<code>logging.pattern.console=%d %-4r [%thread] %-5level PREFIX=%X{PREFIX} - %msg%n
</code>```

Body:
I want to have my string added as prefix to every logging message in app. I mean, I have several java apps, and I want one to have some prefix in message like:

DATE, INFO(or other), [sample] (-->this is my added string) , rest of standard message

I have seen a several tutorials, but none of them worked properly for me. I have already included dependency in pom:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

Do you have any trick or simple solution for that? To write some kind of wrapper, or configuration class?

Body:
Mapped Diagnostic Context (MDC) logging allows you to set attributes associated with current thread, so that SLF4J (via your logger implementation library) can log those attributes with each logging statement without it having to be specified.
So what you need is to put your prefix text in MDC. If you're using Spring MVC then a way is to implement a HandlerInterceptor.

import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoggingInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("PREFIX", "your text");
        return true;
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.clear();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        MDC.clear();
    }
}

import com.tigerit.kai.education.util.LoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class BeanConfiguration {

   @Bean
   public LoggingInterceptor loggingHandlerInterceptor() {
      return new LoggingInterceptor();
   }

   @Bean
   public WebMvcConfigurerAdapter webConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(loggingHandlerInterceptor());
         }
      };
   }
}

And finally add following in application.properties

logging.pattern.console=%d %-4r [%thread] %-5level PREFIX=%X{PREFIX} - %msg%n


问:
SKAction play sound not from begining
I want to play sound not from the beginning of the mp3 file, but from 14s after beginning. I have the following code for sound playing, but i was not successful in finding the solution:</p>

```<code>if let textAudio = textAudio {
        let wait = SKAction.wait(forDuration: 0.1)
        let play = SKAction.play()
        if view.scene! == scene02 {
            // play 14s after begining
        }
        textAudio.run(SKAction.sequence([wait, play]))
    }
</code>```

答:
You can use AVAudioPlayer and the currentTime method as explained here:

```<code>import AVFoundation
var textAudio: AVAudioPlayer?
let path = Bundle.main.path(forResource: "example.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)

do {
    textAudio = try AVAudioPlayer(contentsOf: url)
    textAudio?.currentTime = TimeInterval(14.0)
    textAudio?.play()
} catch {
    // couldn't load file :(
}
</code>```

Title: SKAction play sound not from begining

Body:
I want to play sound not from the beginning of the mp3 file, but from 14s after beginning. I have the following code for sound playing, but i was not successful in finding the solution:

if let textAudio = textAudio {
        let wait = SKAction.wait(forDuration: 0.1)
        let play = SKAction.play()
        if view.scene! == scene02 {
            // play 14s after begining
        }
        textAudio.run(SKAction.sequence([wait, play]))
    }

Body:
You can use AVAudioPlayer and the currentTime method as explained here:

import AVFoundation
var textAudio: AVAudioPlayer?
let path = Bundle.main.path(forResource: "example.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)

do {
    textAudio = try AVAudioPlayer(contentsOf: url)
    textAudio?.currentTime = TimeInterval(14.0)
    textAudio?.play()
} catch {
    // couldn't load file :(
}


问:
How to get text only from the email content ? Ruby on Rails - GMail for Ruby Gem
I am developing a Ruby on Rails website where I need to fetch emails from GMail. I am using GMail for Ruby Gem. I can fetch subject, date, etc, and even the body, but, when I fetched the body, I got a full content of the email. I am not sure if there is another field that only contains text only, but I already tried content, text, and mail but none of them are working.

This is the sample of content when I used body. I am using GIST since it's very long.

Are there anyone that can help me for this issue? Thank you.

答:
Try this code

```<code>Gmail.connect("username","password").inbox.emails.first.text_part.body.decoded
</code>```

Also if you want to remove "\n" so can use gsub for it.

```<code>Gmail.connect("username","password").inbox.emails.first.text_part.body.decoded.gsub("\n", ' ').squeeze(' ')
</code>```

If you want to do for all emails then you can do something like this

```<code>arr = []
Gmail.connect("username","password").inbox.emails.each do |email|
   arr << email.text_part.body.decoded.gsub("\n", ' ').squeeze(' ')
end
</code>```

Body:
Try this code

Gmail.connect("username","password").inbox.emails.first.text_part.body.decoded

Also if you want to remove "\n" so can use gsub for it.

Gmail.connect("username","password").inbox.emails.first.text_part.body.decoded.gsub("\n", ' ').squeeze(' ')

If you want to do for all emails then you can do something like this

arr = []
Gmail.connect("username","password").inbox.emails.each do |email|
   arr << email.text_part.body.decoded.gsub("\n", ' ').squeeze(' ')
end


问:
Marshmallow 6.0.1 onMessageReceived() called multiple times
I am using Firebase push notifications. All other mobile devices show one notification but my Marshmallow 6.0.1 shows 40 to 50 notifications.
google.message_id is changed every time.

```<code>@Override
public void onMessageReceived(String from, Bundle data) {
    // this method is called multiple times
}
</code>```

答: update firebase in your project, it is solved my problem</p>

Body:
I am using Firebase push notifications. All other mobile devices show one notification but my Marshmallow 6.0.1 shows 40 to 50 notifications.
google.message_id is changed every time.

@Override
public void onMessageReceived(String from, Bundle data) {
    // this method is called multiple times
}


问:
Patch development in DotNet
when we develop application in .NET then we create also setup at the end of development and send the setup to client. client install the setup file.

when we change our code or add new functionality in our apps then we create setup again and give back the client to install again. in this scenario if the setup file size become huge, is there any way out like patch that when we change in our code then we just create a patch and give that patch to client?

client will install that patch will get the changes and also previous functionality will be intact in application. so how could i give the only newly added functionality or change only part in the apps to client with the help of patch.

please help in detail with all the steps to implement this sort of setup development because it will be very light weight.

thanks

答:
One simple approach (especially if you are code-signing or obfuscating your assemblies) is to break your application up into a number of separate Assemblies (dlls). Then if you update the code, you only need to deploy the assemblies that have actually changed.

The most important thing is to control the dependencies: define the interfaces between the assemblies well at the beginning, and add new interfaces to extend the existing functionality (rather than making "breaking changes" to existing interfaces) so that you can make useful changes to the application without having to deploy lots of assemblies in your patch. (If there are many dependencies you will find that making a change anywhere will still require you to deploy almost all of the assemblies to the customer, which defeats the purpose somewhat).

This approach won't deliver the most compact patches possible, but it's extremely simple and easy to implement - and in many cases it can provide "acceptably small" patches. It also encourages developers to think hard about using good, modular designs with minimal dependencies - so it's worth doing (within reason) even if you add a more sophisticated patching mechanism on top.

If using a patch approach I'd also advise giving the customer a full version periodically, as the more patches you apply, the greater the risk of something getting out of sync. (Consider the way Windows Update works - The OS is incrementally updated with patches, but every now and then Microsoft issues a service pack that rolls all the small patches into one large patch, and less frequently they release a whole new version of the operating system that users must reinstall from scratch)

Title: Patch development in DotNet


问:
Bash Script (awk-sed-grep) to check whether numbers in every next line are 1 more than previous line
I have a file:

```<code>Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34
</code>```

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

Body:
I have a file:

Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

Body:
You can use this awk:

awk -F '[ ,]' 'NR==1{p=$6;next} $6!=p+1{print "Mismatched line no:"NR} {p=$6}' file

Input:

Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34

Output:

$ awk -F '[ ,]' 'NR==1{p=$6;next} $6!=p+1{print "Mismatched line no:"NR} {p=$6}' file
Mismatched line no:5


问:
How to align form components horizontally using Vuetifyjs

I'm learning vuetifyjs vuejs2, and I have difficulties to write a code which does the following through vuetify:

I expect this kind of form on vuetify:

1- a form having its components horizontally

2- these components should only be 3 select boxes, with the submit button

3- having a form which send those selected items to a page

that is where I need your with examples of code on vuetify.

At the end, I should have a form having 3 select boxes filled with their options, with a submit forwarding the result to a vue.

答:
You can achieve this using the grid layout provided by vuetify

```<code><template>
    <v-layout row wrap >
        <v-flex xs12>
               <v-form v-model="valid" ref="form">
                    <v-layout row wrap>
                        <v-flex xs3 v-for="option in selectOptions" :key="option.text">
                             <v-checkbox :label="option.text" v-model="selected" :value="option.value"></v-checkbox>
                        </v-flex>
                        <v-flex xs3>
                             <v-btn small class="primary">save</v-btn>
                        </v-flex>
                    </v-layout>
            </v-form>
            <p>selected options : {{selected}}</p>
        </v-flex>
    </v-layout>
</template>

<script>
    export default{
        data(){
            return {
                valid: false,
                selected:[],
                selectOptions:[
                    {text: 'Apples', value: 'apple'},
                    {text: 'Oranges', value: 'orange'},
                    {text: 'Grapes', value: 'grape'}
                ]
            }
        },
        }
    }
</script>
</code>```

Here is the working fiddle

Body:
You can achieve this using the grid layout provided by vuetify

<template>
    <v-layout row wrap >
        <v-flex xs12>
               <v-form v-model="valid" ref="form">
                    <v-layout row wrap>
                        <v-flex xs3 v-for="option in selectOptions" :key="option.text">
                             <v-checkbox :label="option.text" v-model="selected" :value="option.value"></v-checkbox>
                        </v-flex>
                        <v-flex xs3>
                             <v-btn small class="primary">save</v-btn>
                        </v-flex>
                    </v-layout>
            </v-form>
            <p>selected options : {{selected}}</p>
        </v-flex>
    </v-layout>
</template>

<script>
    export default{
        data(){
            return {
                valid: false,
                selected:[],
                selectOptions:[
                    {text: 'Apples', value: 'apple'},
                    {text: 'Oranges', value: 'orange'},
                    {text: 'Grapes', value: 'grape'}
                ]
            }
        },
        }
    }
</script>

Here is the working fiddle


问:
Pass "generic" JsonProvider to function in F#
I have two JsonProvider types:

```<code>type Provider1 = JsonProvider<"""{structure}""">
type Provider2 = JsonProvider<"""{}structure2""">
</code>```

I'd like to have a function, that can accept any of these and parse json using provided JsonProvider, something like this:(pseudo code, not compiling)

```<code>let parseUsingSpecificProvider json (provider : JsonProvider<GENERIC>) =
    provider.Parse json
</code>```

答:
You can define an inline function with Statically Resolved Type Parameters (SRTPs):

```<code>let inline parseUsingSpecificProvider json (provider:^T) =
    (^T : (static member Parse : string -> _) json)

// tests
#r @"packages\FSharp.Data\lib\net40\FSharp.Data.dll"
open FSharp.Data

type Provider1 = JsonProvider<""" { "name":"John"           } """>
type Provider2 = JsonProvider<""" { "name":"John", "age":94 } """>

let x = parseUsingSpecificProvider  (""" { "name":"Tomas", "age":4 } """) Unchecked.defaultof<Provider1>
let y = parseUsingSpecificProvider  (""" { "name":"Tomas", "age":4 } """) Unchecked.defaultof<Provider2>
</code>```

So it will work with any type that has the static method Parse accepting a string as input.

Body:
I have two JsonProvider types:

type Provider1 = JsonProvider<"""{structure}""">
type Provider2 = JsonProvider<"""{}structure2""">

I'd like to have a function, that can accept any of these and parse json using provided JsonProvider, something like this:(pseudo code, not compiling)

let parseUsingSpecificProvider json (provider : JsonProvider<GENERIC>) =
    provider.Parse json

Body:
You can define an inline function with Statically Resolved Type Parameters (SRTPs):

let inline parseUsingSpecificProvider json (provider:^T) =
    (^T : (static member Parse : string -> _) json)

// tests
#r @"packages\FSharp.Data\lib\net40\FSharp.Data.dll"
open FSharp.Data

type Provider1 = JsonProvider<""" { "name":"John"           } """>
type Provider2 = JsonProvider<""" { "name":"John", "age":94 } """>

let x = parseUsingSpecificProvider  (""" { "name":"Tomas", "age":4 } """) Unchecked.defaultof<Provider1>
let y = parseUsingSpecificProvider  (""" { "name":"Tomas", "age":4 } """) Unchecked.defaultof<Provider2>

So it will work with any type that has the static method Parse accepting a string as input.


问:
Is here any GUI tool that can show file with conflicts side-by-side?
I have a couple of conflicted files and I don't have access to source branches (these files are detached from the repository. There isn't any .git folder and I don't have original versions). There are some conflicts marked by git-merge:

```<code><<<<<<< HEAD
    sizeof(.......bla bla
||||||| merged common ancestors
    sizeof(.......ble ble
=======
    sizeof(.......blu blu
>>>>>>> refs/heads/TAGNAME
</code>```

Is there a way to see such file in human-readable mode, i.e. parse a single file with marked conflicts and split it to a side-by-side view?  I suppose Meld cannot do it, and KDiff3 seems to be unable to do the trick too.

git merge (tool) says that this isn't a Git repository.

git diff --no-index requires two parameters (two files to compare), and as mentioned before I don't have the input files.

答: Use P4Merge to visualize the differences. You can set it up as the default tool used by Git-Diff and Git-Merge. Here is the effect.</p>

Body:
I have a couple of conflicted files and I don't have access to source branches (these files are detached from the repository. There isn't any .git folder and I don't have original versions). There are some conflicts marked by git-merge:

<<<<<<>>>>>> refs/heads/TAGNAME

Is there a way to see such file in human-readable mode, i.e. parse a single file with marked conflicts and split it to a side-by-side view?  I suppose Meld cannot do it, and KDiff3 seems to be unable to do the trick too.

git merge (tool) says that this isn't a Git repository.

git diff --no-index requires two parameters (two files to compare), and as mentioned before I don't have the input files.


问:
Keycloak.enabled = false - returning status 500 internal error
I have a Java Spring application that has some api GET requests and I've recently added Keycloak security to it. I added the dependency and BOM for the new 3.3.0.CR2 release and updated my application.properties; and this all worked fine. This new release has an enabled feature to disable keycloak for testing purposes, I want to make use of (see here: Spring Boot Adapter Java). However, I can't get this feature to work.

If I try to access the GET api call with keycloak.enabled = true (ie: my security on, the default value), I get a 401 unortharised error, as expected.

However with keycloak.enabled = false I get a 500 internal error when I excpected a 200 and the GET response (this did happen before I ran Keycloak at all). Looking at the STS console I get a nullpointerexception in the internalBuild method on the following line with adapterConfig being null:

```<code>    if (adapterConfig.getRealm() == null) throw new RuntimeException("Must set 'realm' in config");
</code>```

If anyone has any experience of using this feature successfully or can see anything I'm doing wrong please could you help.

For reference, my application.properties about Keycloak:

```<code>keycloak.enabled=false
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=SpringBoot
keycloak.resource=product-back
keycloak.ssl-required = external
keycloak.bearer-only=true
keycloak.principal-attribute=email
</code>```

EDIT:
Full stack trace as requested:

```<code>java.lang.NullPointerException: null
    at org.keycloak.adapters.KeycloakDeploymentBuilder.internalBuild(KeycloakDeploymentBuilder.java:55) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.KeycloakDeploymentBuilder.build(KeycloakDeploymentBuilder.java:164) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver.resolve(KeycloakSpringBootConfigResolver.java:37) ~[keycloak-spring-boot-adapter-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.AdapterDeploymentContext.resolveDeployment(AdapterDeploymentContext.java:88) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.PreAuthActionsHandler.preflightCors(PreAuthActionsHandler.java:107) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.PreAuthActionsHandler.handleRequest(PreAuthActionsHandler.java:79) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter.doFilter(KeycloakPreAuthActionsFilter.java:81) ~[keycloak-spring-security-adapter-3.3.0.CR2.jar:3.3.0.CR2]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
</code>```

答:
As a workaround, excluding the configuration containing the security configuration worked for me. In my case I had moved my security configuration into a separate module called security and my configuration is named SecurityConfig. Adding the following to my properties file solved my problem:

```<code>spring.autoconfigure.exclude=com.acme.security.SecurityConfig
</code>```

Body:
I have a Java Spring application that has some api GET requests and I've recently added Keycloak security to it. I added the dependency and BOM for the new 3.3.0.CR2 release and updated my application.properties; and this all worked fine. This new release has an enabled feature to disable keycloak for testing purposes, I want to make use of (see here: Spring Boot Adapter Java). However, I can't get this feature to work.

If I try to access the GET api call with keycloak.enabled = true (ie: my security on, the default value), I get a 401 unortharised error, as expected.

However with keycloak.enabled = false I get a 500 internal error when I excpected a 200 and the GET response (this did happen before I ran Keycloak at all). Looking at the STS console I get a nullpointerexception in the internalBuild method on the following line with adapterConfig being null:

    if (adapterConfig.getRealm() == null) throw new RuntimeException("Must set 'realm' in config");

If anyone has any experience of using this feature successfully or can see anything I'm doing wrong please could you help.

For reference, my application.properties about Keycloak:

keycloak.enabled=false
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=SpringBoot
keycloak.resource=product-back
keycloak.ssl-required = external
keycloak.bearer-only=true
keycloak.principal-attribute=email

EDIT:
Full stack trace as requested:

java.lang.NullPointerException: null
    at org.keycloak.adapters.KeycloakDeploymentBuilder.internalBuild(KeycloakDeploymentBuilder.java:55) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.KeycloakDeploymentBuilder.build(KeycloakDeploymentBuilder.java:164) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver.resolve(KeycloakSpringBootConfigResolver.java:37) ~[keycloak-spring-boot-adapter-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.AdapterDeploymentContext.resolveDeployment(AdapterDeploymentContext.java:88) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.PreAuthActionsHandler.preflightCors(PreAuthActionsHandler.java:107) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.PreAuthActionsHandler.handleRequest(PreAuthActionsHandler.java:79) ~[keycloak-adapter-core-3.3.0.CR2.jar:3.3.0.CR2]
    at org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter.doFilter(KeycloakPreAuthActionsFilter.java:81) ~[keycloak-spring-security-adapter-3.3.0.CR2.jar:3.3.0.CR2]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]

Body:
As a workaround, excluding the configuration containing the security configuration worked for me. In my case I had moved my security configuration into a separate module called security and my configuration is named SecurityConfig. Adding the following to my properties file solved my problem:

spring.autoconfigure.exclude=com.acme.security.SecurityConfig