问:
Automate turning on and off of redis cluster
I'm trying to automate the turning on and off process of Redis Cluster in aws. I saw the following link for reference (https://forums.aws.amazon.com/thread.jspa?threadID=149772). Is there a way to do it via cloudwatch ?

I am very new to aws platform.

答:
Check the documentation regarding scale in/out
https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/redis-cluster-resharding-online.html It also has commands to reshard a cluster manually.

Check CloudWatch metrics from the Redis cluster. https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/CacheMetrics.HostLevel.html and https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/CacheMetrics.Redis.html Choose the metrics that will trigger autoscaling

You can trigger an AWS Lambda on some event for a metric https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/RunLambdaSchedule.html

From the Lambda you cal call aws cli to reshard the cluster as described in 1. Example: https://alestic.com/2016/11/aws-lambda-awscli/

If you need to turn off the cluster completely, instead of the resharding commands just use https://docs.aws.amazon.com/cli/latest/reference/elasticache/delete-cache-cluster.html


来源: stackexchange

问:
What does the tag <link rel="author" .. do?
I'm currently trying to learn HTML and I have a question about the link element: <link rel="author" href="URL">. What does this element do?

My book says:

establishing a relationship between a document and an author
  (document).

But what does this really mean?

A visitor of my website can't see it, it is not displayed anywhere, so who or what is using this element?

答:
You have to remember that HTML is a structured language that is meant to be read by machines and then used to render to something that is much more easily read by humans.  A browser takes all the HTML and then uses it to know how to render a webpage.  The <link>, <meta> and other tags in the  are read by a machine and, although they don't directly render to something that is visible to humans, they still play a part in the overall experience.

The <link> tag can be used in a number of ways by the machine piece that reads the HTML document.  For example, a web crawler might read the document and present search results to you if you were to search for a specific author.  If the document said that it was written by Bob Barker and you searched Google for articles written by Bob Barker, this is how it would know how to present the document to you.

Let's also say that the browser wanted to provide an easy way for you to get in touch with an author of a page, the easiest way for it to know who to put you in contact with is to read this element since its purpose is explicitly (from MDN):

Defines a hyperlink to a page describing the author or providing a way
  to contact the author.

That <link> tag is only one example though.  One of the more current ways to express metadata is through <meta> tags.  I'm not completely up to date on all the ways they are used, but consider this example:

When I search Google for "html card meta" I am presented with this article The Essential Meta Tags for Social Media  as the first result:

If you look closely, you will see that it has a date next to the article "Jun 20, 2016".  That's the publication date.  The only reason Google is able to reasonably discern this is because of the <meta property="article:published_time" content="2016-06-20T13:18:32+00:00"> tag in the actual source of the article page.  It would have to guess from other page features otherwise.

ContentLicense: CC BY-SA 4.0

Body:
You have to remember that HTML is a structured language that is meant to be read by machines and then used to render to something that is much more easily read by humans.  A browser takes all the HTML and then uses it to know how to render a webpage.  The <link>, <meta> and other tags in the <head> are read by a machine and, although they don't directly render to something that is visible to humans, they still play a part in the overall experience.

The <link> tag can be used in a number of ways by the machine piece that reads the HTML document.  For example, a web crawler might read the document and present search results to you if you were to search for a specific author.  If the document said that it was written by Bob Barker and you searched Google for articles written by Bob Barker, this is how it would know how to present the document to you.

Let's also say that the browser wanted to provide an easy way for you to get in touch with an author of a page, the easiest way for it to know who to put you in contact with is to read this element since its purpose is explicitly (from MDN):

Defines a hyperlink to a page describing the author or providing a way
  to contact the author.

That <link> tag is only one example though.  One of the more current ways to express metadata is through <meta> tags.  I'm not completely up to date on all the ways they are used, but consider this example:

When I search Google for "html card meta" I am presented with this article The Essential Meta Tags for Social Media  as the first result:

If you look closely, you will see that it has a date next to the article "Jun 20, 2016".  That's the publication date.  The only reason Google is able to reasonably discern this is because of the <meta property="article:published_time" content="2016-06-20T13:18:32+00:00"> tag in the actual source of the article page.  It would have to guess from other page features otherwise.


问:
sqlite query due date
I am trying to make a query in sqlite where it shows invoices that has passed their due date.
I tried:

```<code>SELECT i.invoice_ID AS 'Invoice ID', i.due_date AS 'Due Date', i.invoice_total_amount AS 'Invoice Total'
FROM invoice as i
WHERE date(due_date) > date('now');
</code>```

But that doesn't work. How can I do this correctly?

UPDATE:

My table only contains:

```<code>INSERT INTO invoice VALUES (1, 1, 1, 2007-02-01, 2007-02-27, 10028);
</code>```

The result og my query is:

答:
You are querying for due date greater than now; which means the reverse (invoces that did NOT pass their due date)

use WHERE date(due_date) < date('now');

UPDATE:

As per update in question, you're inserting your values wrong. You are trying to use Text format for date, but you aren't quoting it, so instead you end up using integer format. Instead, quote to get text:

```<code>INSERT INTO invoice VALUES (1, 1, 1, '2007-02-01', '2007-02-27', 10028);
</code>```

Title: sqlite query due date

Body:
I am trying to make a query in sqlite where it shows invoices that has passed their due date.
I tried:

SELECT i.invoice_ID AS 'Invoice ID', i.due_date AS 'Due Date', i.invoice_total_amount AS 'Invoice Total'
FROM invoice as i
WHERE date(due_date) > date('now');

But that doesn't work. How can I do this correctly?

UPDATE:

My table only contains:

INSERT INTO invoice VALUES (1, 1, 1, 2007-02-01, 2007-02-27, 10028);

The result og my query is:

Body:
You are querying for due date greater than now; which means the reverse (invoces that did NOT pass their due date)

use WHERE date(due_date) < date('now');

UPDATE:

As per update in question, you're inserting your values wrong. You are trying to use Text format for date, but you aren't quoting it, so instead you end up using integer format. Instead, quote to get text:

INSERT INTO invoice VALUES (1, 1, 1, '2007-02-01', '2007-02-27', 10028);


问:
Why did deploying a single report also overwrite the data source?
We had a problem earlier when deploying a single report to the production environment, when, for reasons we don't understand, SSRS decided to also overwrite the Data Source associated with the report with settings that do not even match those currently in the project.

We want to understand why/how this happens, and what we need to be doing to control it - ie, what are we missing about SSRS that we need to be aware of.

The steps we took were as follows:

Before starting: This is to update an existing report, not a new report, so the Prod report server already has the Data Source and the (old) Report Definition. The Data Source (shared) does not need to be changed at all, nor do we believe we did anything that should have prompted SSRS to do so. We only intended to overwrite the old report definition with the new one.

Data Source within project modified to point to the production Sql Server source

Deployment settings within the project modified to point to the production Report Server

The single report deployed (literally by right-clicking TheReport.rdl in the Solution Explorer and then clicking Deploy). That is everything we did. We did not deploy or change anything else.

Expected result: report definition on the prod server overwritten with the new report. Data Source completely unchanged, because why would it be? We didn't deploy that (and in any case, the one in the project is pointing to prod, so it shouldn't even matter if it did)

Actual result: Report overwritten as expected. Data Source also overwritten... with the old dev settings. Not the ones currently in the project. All the other reports sharing this data source suddenly stop working or display dev server data.

What are we doing wrong? SSRS quietly overwriting the associated Data Source on the server when deploying a single report seems dangerous (we would likely have missed that it had even happened, had the data on these particular dev and live environments been similar enough) so I presume we are missing something we should be doing/checking when deploying reports, but are at a loss as to exactly what.

答:
That is configuration to copy your datasources and datasets to the report portal or not. You can change the configuration by right click on your report project and select properties that will open up the property pages. There is an option to overwrite default settings. Please check below image for more details

By using the above configuration it will deploy dataset and data sources on SSRS server only if it is not exists on the server.

Hope this will work.


问:
Easily mockable HTTP client framework for C#
In a upcoming project I'm going to write an application in C# which partly has to communicate with a HTTP server. I'm very fond of writing my code TDD-style, and I would just love it if I could mock all of the HTTP requests in my tests.

Does any one here know about an easly mockable HTTP client framework?

Ps. I usually use Moq for mocks. If you know of some free mocking framework that would be better to mock HTTP requests, that would be nice too.

答:
I suggest you use the framework support for this i.e. System.Net.WebRequest.

Define a really simple interface, and a simple wrapper for the webrequest. This way you will get what you want, and won't add an external dependency for something the framework already does well.

OwnerDisplayName: Presidenten

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Freddy Rios


问:
Generate Spring MVC controller from Swagger/OpenAPI
Is there a way how to generate controller Spring MVC code from Swagger/OpenAPI specification?

I know Swagger can be generated from existing Spring code but is this possible the other way round ?

答:
You are basically looking for generation of swagger server-side code. If you would like to generate it while you are building your application and if you are using maven you can use the following plugin:

```<code><plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>${swagger.codegen.version}</version>
<executions>
  <execution>
    <goals>
      <goal>generate</goal>
    </goals>
    <configuration>
      <inputSpec>${swagger.yaml.file}</inputSpec>
      <language>spring</language>
      <configOptions>
        <sourceFolder>${swagger.generated.sourcepath}</sourceFolder>
        <!-- <interfaceOnly>true</interfaceOnly> -->
        <dateLibrary>java8</dateLibrary>
      </configOptions>
      <typeMappings>
        <typeMapping>OffsetDateTime=Instant</typeMapping>
      </typeMappings>
      <importMappings>
        <importMapping>java.time.OffsetDateTime=java.time.Instant</importMapping>
      </importMappings>
      <modelPackage>${project.groupId}.${project.artifactId}.swagger.model</modelPackage>
      <apiPackage>${project.groupId}.${project.artifactId}.swagger.api</apiPackage>
      <invokerPackage>${project.groupId}.${project.artifactId}.swagger.invoker</invokerPackage>
    </configuration>
  </execution>
</executions>
</plugin>
</code>```

Please note the commented part interfaceOnly if set to true, it will only create the APIs class with default as NOT_IMPLEMENTED and you would have to write the implementation.

Add following dependency:

```<code><dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-annotations</artifactId>
  <version>${swagger.annotations.version}</version>
  <scope>compile</scope>
</dependency>
</code>```

I used the following properties:

```<code><properties>
    <swagger.codegen.version>2.4.1</swagger.codegen.version>
    <swagger.yaml.file>${project.basedir}/swagger.yaml</swagger.yaml.file>
    <swagger.annotations.version>1.5.21</swagger.annotations.version>
    <swagger.generated.sourcepath>src/main/java</swagger.generated.sourcepath>
</properties>
</code>```

The other static approach that would require the generation of controller manually when there is a change in the swagger file would be to use swagger editor.

ContentLicense: CC BY-SA 3.0

Body:
You are basically looking for generation of swagger server-side code. If you would like to generate it while you are building your application and if you are using maven you can use the following plugin:

<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>${swagger.codegen.version}</version>
<executions>
  <execution>
    <goals>
      <goal>generate</goal>
    </goals>
    <configuration>
      <inputSpec>${swagger.yaml.file}</inputSpec>
      <language>spring</language>
      <configOptions>
        <sourceFolder>${swagger.generated.sourcepath}</sourceFolder>
        <!-- <interfaceOnly>true</interfaceOnly> -->
        <dateLibrary>java8</dateLibrary>
      </configOptions>
      <typeMappings>
        <typeMapping>OffsetDateTime=Instant</typeMapping>
      </typeMappings>
      <importMappings>
        <importMapping>java.time.OffsetDateTime=java.time.Instant</importMapping>
      </importMappings>
      <modelPackage>${project.groupId}.${project.artifactId}.swagger.model</modelPackage>
      <apiPackage>${project.groupId}.${project.artifactId}.swagger.api</apiPackage>
      <invokerPackage>${project.groupId}.${project.artifactId}.swagger.invoker</invokerPackage>
    </configuration>
  </execution>
</executions>
</plugin>

Please note the commented part interfaceOnly if set to true, it will only create the APIs class with default as NOT_IMPLEMENTED and you would have to write the implementation.

Add following dependency:

<dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-annotations</artifactId>
  <version>${swagger.annotations.version}</version>
  <scope>compile</scope>
</dependency>

I used the following properties:

<properties>
    <swagger.codegen.version>2.4.1</swagger.codegen.version>
    <swagger.yaml.file>${project.basedir}/swagger.yaml</swagger.yaml.file>
    <swagger.annotations.version>1.5.21</swagger.annotations.version>
    <swagger.generated.sourcepath>src/main/java</swagger.generated.sourcepath>
</properties>

The other static approach that would require the generation of controller manually when there is a change in the swagger file would be to use swagger editor.


问:
How to remove a non-empty directory with OCaml?
I tried to remove a directory using Sys.remove "mydir", but this results in an exception: Exception: Sys_error u"mydir: Is a directory"..

Next I looked at Unix.rmdir "mydir", but that did not work because the directory is not empty (it resulted in Exception: Unix.Unix_error (27, "rmdir", "mydir").

So I guess the only way to delete a non-empty directory is to get the list of files in the directory using Sys.readdir "mydir", then delete its contents recursively before finally deleting the empty directory using Unix.rmdir.

What is the idiomatic way of removing a non-empty directory using OCaml?

答:
You have to recursively remove its contents first, using Sys.remove and Sys.readdir, and, once it is empty, remove the directory itself, e.g.,

```<code>let rec rmrf path = match Sys.is_directory path with
  | true ->
    Sys.readdir path |>
    Array.iter (fun name -> rmrf (Filename.concat path name));
    Unix.rmdir path
  | false -> Sys.remove path
</code>```

Alternatively, you can use the OCaml Fileutils library, which provides POSIX compliant file utilities, namely the rm function, that could recursively (and portably) delete the whole directory, e.g.,

```<code> FileUtil.rm ~recurse:true [dir]
</code>```

Body:
You have to recursively remove its contents first, using Sys.remove and Sys.readdir, and, once it is empty, remove the directory itself, e.g.,

let rec rmrf path = match Sys.is_directory path with
  | true ->
    Sys.readdir path |>
    Array.iter (fun name -> rmrf (Filename.concat path name));
    Unix.rmdir path
  | false -> Sys.remove path

Alternatively, you can use the OCaml Fileutils library, which provides POSIX compliant file utilities, namely the rm function, that could recursively (and portably) delete the whole directory, e.g.,

 FileUtil.rm ~recurse:true [dir]


问:
Capturing a property of an object for a closure in Swift
I'm rewriting some code to append jobs to an array of closures rather than execute them directly:

```<code>var someObject: SomeType?
var jobsArray: [() -> ()] = []

// before rewriting
doExpensiveOperation(someObject!.property)

// 1st attempt at rewriting
jobsArray.append {
    doExpensiveOperation(someObject!.property)
}
</code>```

However, because the value of someObject might change before the closure is executed, I'm now adding a closure list as follows:

```<code>// 2nd attempt at rewriting
jobsArray.append { [someObject] in
    doExpensiveOperation(someObject!.property)
}
</code>```

Hopefully then if, say, someObject is subsequently set to nil before the closure executes, the closure will still access the intended instance.

But what's the neatest way to deal with the possibility that the value of .property might change before the closure is executed? Is there a better way than this?

```<code>// 3rd attempt at rewriting
let p = someObject!.property
jobsArray.append {
    doExpensiveOperation(p)
}
</code>```

I'm not very keen on this solution because it means changing the original line of code. I'd prefer this but it doesn't work:

```<code>// 4th attempt at rewriting
jobsArray.append { [someObject!.property] in
    doExpensiveOperation(someObject!.property)
}
</code>```

Pretty new to Swift, so all guidance gratefully received. Thanks!

答:
A capture list such as [someObject] is actually syntactic sugar for [someObject = someObject], where the right hand side can be an arbitrary expression that gets bound to a new constant upon the closure being formed.

Therefore one option is to write your example as:

```<code>jobsArray.append { [property = someObject!.property] in
  doExpensiveOperation(property)
}
</code>```

Body:
I'm rewriting some code to append jobs to an array of closures rather than execute them directly:

var someObject: SomeType?
var jobsArray: [() -> ()] = []

// before rewriting
doExpensiveOperation(someObject!.property)

// 1st attempt at rewriting
jobsArray.append {
    doExpensiveOperation(someObject!.property)
}

However, because the value of someObject might change before the closure is executed, I'm now adding a closure list as follows:

// 2nd attempt at rewriting
jobsArray.append { [someObject] in
    doExpensiveOperation(someObject!.property)
}

Hopefully then if, say, someObject is subsequently set to nil before the closure executes, the closure will still access the intended instance.

But what's the neatest way to deal with the possibility that the value of .property might change before the closure is executed? Is there a better way than this?

// 3rd attempt at rewriting
let p = someObject!.property
jobsArray.append {
    doExpensiveOperation(p)
}

I'm not very keen on this solution because it means changing the original line of code. I'd prefer this but it doesn't work:

// 4th attempt at rewriting
jobsArray.append { [someObject!.property] in
    doExpensiveOperation(someObject!.property)
}

Pretty new to Swift, so all guidance gratefully received. Thanks!

Body:
A capture list such as [someObject] is actually syntactic sugar for [someObject = someObject], where the right hand side can be an arbitrary expression that gets bound to a new constant upon the closure being formed.

Therefore one option is to write your example as:

jobsArray.append { [property = someObject!.property] in
  doExpensiveOperation(property)
}


问:
IntelliJ Column Selection using Cursor Keys
Is it possible to some how setup IntelliJ IDEA so that I can column select with the cursor keys similarly to how I might in Notepad++, Visual Studio, or FlashDevelop.

For instance when I'm typing code I almost always do my navigation solely through use of the keyboard. In the IDEs mentioned previously I can quickly select blocks of code by holding Shift + Alt then tapping ↑ to extend my cursor across the lines above. I can then hold Shift + Alt + Ctrl and tap ← or → to quickly jump across words and select the chunk of text I want.

In IntelliJ IDEA I have to constantly enable and disable Column Selection Mode using the Shift + Alt + Insert and even then it doesn't quite function as it does in the other IDEs or Text Editors.

Any ideas?

答:
Most convenient way is to:

MAC: Hold Option+Shift and click with mouse.

Windows: Hold Alt and click with mouse.


问:
Can I define a Clojure protocol with methods starting with ":"?
I would like to provide some methods for a clojure protocol starting with the : character. Is there any way to override this in Clojure?</p>

答:
Don't think so. Clojure keywords are implemented in the reader and I don't think there's any way of overriding that behavior.

When you use a keyword as a function, that is equivalent to (get arg :keyword). You can extend what that does by implementing ILookup in your protocol.

Joost.


问:
Android unit testing Location not mocked
I am trying to test my presenter and I need a mocked location, however, I get null or have default values such as 0.0 for lat, long, bearing and so on

I have already tried creating a new Location object and initializing all the fields I need.

```<code>    val latitude = 37.422
    val longitude = -122.084

    val mockLocation = mock(Location::class.java)
    mockLocation.latitude = latitude
    mockLocation.longitude = longitude

    presenter.loadsAirpots(latitude, longitude)
    presenter.locationChanged(mockLocation)

    System.out.println(mockLocation.latitude)
</code>```

I expect latitude to be 37.422 but the actual output is 0.0

答:
When you mock an object the real implementation won't be called.
You are trying to call setLatitude(latitude) but it won't change the value.

If you want to mock the object you should do:

```<code>val mockLocation = mock(Location::class.java)
given(mockLocation.getLatitude()).willReturn(latitude)
given(mockLocation.getLongitude()).willReturn(longitude)
</code>```

Or you could create a real object:

```<code>val realLocation = Location("provider")
realLocation.latitude = latitude
realLocation.longitude = longitude
</code>```

Body:
I am trying to test my presenter and I need a mocked location, however, I get null or have default values such as 0.0 for lat, long, bearing and so on

I have already tried creating a new Location object and initializing all the fields I need.

    val latitude = 37.422
    val longitude = -122.084

    val mockLocation = mock(Location::class.java)
    mockLocation.latitude = latitude
    mockLocation.longitude = longitude

    presenter.loadsAirpots(latitude, longitude)
    presenter.locationChanged(mockLocation)

    System.out.println(mockLocation.latitude)

I expect latitude to be 37.422 but the actual output is 0.0

Body:
When you mock an object the real implementation won't be called.
You are trying to call setLatitude(latitude) but it won't change the value.

If you want to mock the object you should do:

val mockLocation = mock(Location::class.java)
given(mockLocation.getLatitude()).willReturn(latitude)
given(mockLocation.getLongitude()).willReturn(longitude)

Or you could create a real object:

val realLocation = Location("provider")
realLocation.latitude = latitude
realLocation.longitude = longitude


问:
How to seconds convert to day,hours and seconds in moment.js with reactjs and typescript
I want this : i have seconds. if i give seconds to moment function i  want this values day, hours, seconds.

I had used moment.js and i get to output log also but i could not get particular key values.

Installed package :

```<code>"moment": "^2.24.0"
</code>```

Usage:

```<code>import moment from 'moment';

const value: number = 172200;
const convertType: any = moment.duration(value, 'seconds');
console.log('convertType:', convertType);
</code>```

Log output:

```<code>convertType:
Duration {
_data:  { days: 1 ,hours: 23, milliseconds: 0, minutes: 50, months: 0
          seconds: 0, years: 0 }
_days: 0
_isValid: true
_locale: Locale {...}
_milliseconds: 172200000
_months: 0
}
</code>```

how do i get _data values from Duration {}.

```<code>_data: {days: 1 ,hours: 23, milliseconds: 0, minutes: 50, months: 0
      seconds: 0, years: 0}
</code>```

i had tried this way but i get undefined

```<code>console.log('output:', convertType.Duration);
</code>```

答:
This works well here:</p>

```<code>const value=172200;
const any=moment.duration(value, 'seconds');
const data=any._data
console.log(`Duration: ${data.years} Years, ${data.months} Months, ${data.days} Days, ${data.hours} Hours, ${data.minutes} Minutes, ${data.seconds} Seconds, ${data.milliseconds} Milliseconds   `)
</code>```

Body:
I want this : i have seconds. if i give seconds to moment function i  want this values day, hours, seconds.

I had used moment.js and i get to output log also but i could not get particular key values.

Installed package :

"moment": "^2.24.0"

Usage:

import moment from 'moment';

const value: number = 172200;
const convertType: any = moment.duration(value, 'seconds');
console.log('convertType:', convertType);

Log output:

convertType:
Duration {
_data:  { days: 1 ,hours: 23, milliseconds: 0, minutes: 50, months: 0
          seconds: 0, years: 0 }
_days: 0
_isValid: true
_locale: Locale {...}
_milliseconds: 172200000
_months: 0
}

how do i get _data values from Duration {}.

_data: {days: 1 ,hours: 23, milliseconds: 0, minutes: 50, months: 0
      seconds: 0, years: 0}

i had tried this way but i get undefined

console.log('output:', convertType.Duration);

Body:
This works well here:

const value=172200;
const any=moment.duration(value, 'seconds');
const data=any._data
console.log(`Duration: ${data.years} Years, ${data.months} Months, ${data.days} Days, ${data.hours} Hours, ${data.minutes} Minutes, ${data.seconds} Seconds, ${data.milliseconds} Milliseconds   `)


问:
network plugin is not ready: cni config uninitialized
KubeletNotReady

runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady
 message:docker: network plugin is not ready: cni config uninitialized

I don't know how to make the network plugin ready

答:
While you run kubectl describe node <node_name>
In the Conditions table, the Ready type will contain this message if you did not initialized cni. Proper initialization can be obtained by installing network addon. I will point you to 2 most used: Weave and Flannel

1) Weave

```<code>$ export kubever=$(kubectl version | base64 | tr -d '\n')
$ kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$kubever"
</code>```

After executing those two commands you should see node in status "Ready"

```<code>$ kubectl get nodes
</code>```

You could also check status

```<code>$ kubectl get cs
</code>```

2) Flannel

```<code>$ kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/62e44c867a2846fefb68bd5f178daf4da3095ccb/Documentation/kube-flannel.yml
</code>```

3) Kubernetes documentation will explain how install other network addons. In this article each CNI provider have a short description.

Body:
While you run kubectl describe node <node_name>
In the Conditions table, the Ready type will contain this message if you did not initialized cni. Proper initialization can be obtained by installing network addon. I will point you to 2 most used: Weave and Flannel

1) Weave

$ export kubever=$(kubectl version | base64 | tr -d '\n')
$ kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$kubever"

After executing those two commands you should see node in status "Ready"

$ kubectl get nodes

You could also check status

$ kubectl get cs

2) Flannel

$ kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/62e44c867a2846fefb68bd5f178daf4da3095ccb/Documentation/kube-flannel.yml

3) Kubernetes documentation will explain how install other network addons. In this article each CNI provider have a short description.


问:
How to correctly create push buttons on winApi as well as Handle its messages
So my program works, all apart from one thing, I would like for my button, 'pushBtn' , aka BTN_PUSH_TALK , to send a BN_PUSHED or BN_UNPUSHED message so I can handle it accordingly.

Following steps online, as well as trial and improvement, right now the only response I ever get is once I am done holding / clicking the button.

```<code>       pushBtn = CreateWindowEx(0, L"BUTTON", L"TALK", WS_CHILD |
       WS_VISIBLE |
       BS_DEFPUSHBUTTON , 0 , 290 , 50, 50,
   hWnd,(HMENU)BTN_PUSH_TALK, GetModuleHandle(NULL), NULL);
</code>```

Handler (or at least what matters) :

```<code> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
    bool asd;
    switch (message)
    {
    case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);

        // Parse the menu selections:
        switch (wmId)
        {
        case BTN_PUSH_TALK:
            switch (HIWORD(wParam))
            {
            case BN_UNPUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(false);
                }
                break;
            case BN_PUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(true);
                }
                break;
            }
            break;
</code>```

I expected once i clicked and held down the button , that the BN_PUSHED case would be entered, however it is not.
On letting go, I expect the BN_UNPUSHED case to be entered, but this was not the case either.
case BTN_PUSH_TALK is reached, meaning the button is identifiable, however the switch case within this block of code is never reached.

答: Buttons send WM_COMMAND on click. To achieve a push/release notification you must subclass the button class (SetWindowLongPtr() with GWLP_WNDPROC) and then handle WM_LBUTTONDOWN and WM_LBUTTONUP in your new Window Proc.</p>

Body:
So my program works, all apart from one thing, I would like for my button, 'pushBtn' , aka BTN_PUSH_TALK , to send a BN_PUSHED or BN_UNPUSHED message so I can handle it accordingly.

Following steps online, as well as trial and improvement, right now the only response I ever get is once I am done holding / clicking the button.

       pushBtn = CreateWindowEx(0, L"BUTTON", L"TALK", WS_CHILD |
       WS_VISIBLE |
       BS_DEFPUSHBUTTON , 0 , 290 , 50, 50,
   hWnd,(HMENU)BTN_PUSH_TALK, GetModuleHandle(NULL), NULL);

Handler (or at least what matters) :

 LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
    bool asd;
    switch (message)
    {
    case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);

        // Parse the menu selections:
        switch (wmId)
        {
        case BTN_PUSH_TALK:
            switch (HIWORD(wParam))
            {
            case BN_UNPUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(false);
                }
                break;
            case BN_PUSHED:
                if (connected && inputChoiceStr == "Push To Talk") {
                    tplug->setDuck(true);
                }
                break;
            }
            break;

I expected once i clicked and held down the button , that the BN_PUSHED case would be entered, however it is not.
On letting go, I expect the BN_UNPUSHED case to be entered, but this was not the case either.
case BTN_PUSH_TALK is reached, meaning the button is identifiable, however the switch case within this block of code is never reached.


问:
Why I can not use IF in here?
I am trying to remove and drop a table if the the table has no data or empty, so I wrote this Statement in PostgreSQL, but I am encountering an error saying syntax error near IF.

I can divide this to 2 different SQL statements, but I want to run this as one query.

```<code>IF (SELECT COUNT(*) FROM ${tableName}) > 0
    BEGIN
        DROP TABLE ${tableName}
    END
</code>```

I also tried this:

```<code>IF (SELECT COUNT(*) FROM zzz > 0) THEN
    DROP TABLE zzz
END IF

ERROR:  syntax error at or near "SELECT"
LINE 2: SELECT COUNT(*) FROM zzz > 0
        ^
SQL state: 42601
Character: 7
</code>```

答:
If you want to do this with SQL, you'll have to use a DO statement:

```<code>DO
$$BEGIN
   IF (SELECT Count(*) FROM zzz) > 0 THEN
      DROP TABLE zzz;
   END IF;
END;$$;
</code>```

Title: Why I can not use IF in here?

Body:
I am trying to remove and drop a table if the the table has no data or empty, so I wrote this Statement in PostgreSQL, but I am encountering an error saying syntax error near IF.

I can divide this to 2 different SQL statements, but I want to run this as one query.

IF (SELECT COUNT(*) FROM ${tableName}) > 0
    BEGIN
        DROP TABLE ${tableName}
    END

I also tried this:

IF (SELECT COUNT(*) FROM zzz > 0) THEN
    DROP TABLE zzz
END IF

ERROR:  syntax error at or near "SELECT"
LINE 2: SELECT COUNT(*) FROM zzz > 0
        ^
SQL state: 42601
Character: 7

Body:
If you want to do this with SQL, you'll have to use a DO statement:

DO
$$BEGIN
   IF (SELECT Count(*) FROM zzz) > 0 THEN
      DROP TABLE zzz;
   END IF;
END;$$;


问:
How to enable scrollbar on overflow in JPanel?
I don't want to show data from the database in tabular format so I have tried something like you have seen in the code. I have have added new JPanel containers consisting of button and label each time a record is retrieved from the database. But due to large amount of data, the panels are getting overflowed but no scroll option is getting enabled.

I have tried using JScrollPane many times but none of the ways helped me.

```<code>public class Test2 extends javax.swing.JFrame {

    private Connection con;
    private Statement st;
    private ResultSet rt;
    public int PageId = 8236;

    /**
     * Creates new form Test2
     */
    public Test2() {
        initComponents();

        this.setLocationRelativeTo(null);
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521","practice","perfect");
            st = con.createStatement();

            int height = 100;
            int width = sc.getWidth();
            int x = 0;
            int y = 0;

            ResultSet rs=st.executeQuery("select id, firstname || ' ' || lastname, salary from employee");
            while(rs.next()){
                JPanel g = new JPanel();
                g.setBounds(x, y, width, height);
                g.setBackground(Color.yellow);
                JLabel l = new JLabel(rs.getString(1));
                JLabel l1 = new JLabel(rs.getString(2));
                JLabel sal = new JLabel(rs.getString(3));
                JButton b = new JButton("View profile");
                b.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        JOptionPane.showMessageDialog(sc, "Clicked!!");
                    }
                });
                g.add(l);
                g.add(l1);
                g.add(b);
                sc.add(g);

                y += (height + 10);
            }
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(this, "Can't connect", "connection error", JOptionPane.ERROR_MESSAGE);
            System.out.println(e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        sc = new javax.swing.JPanel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        sc.setAutoscrolls(true);

        javax.swing.GroupLayout scLayout = new javax.swing.GroupLayout(sc);
        sc.setLayout(scLayout);
        scLayout.setHorizontalGroup(
            scLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 252, Short.MAX_VALUE)
        );
        scLayout.setVerticalGroup(
            scLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 483, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Test2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel sc;
    // End of variables declaration
}
</code>```

答:
I don't want to show data from the database in tabular format

Why? Based on the code you provided the output will look terrible. You create multiple labels based on the text. That means the size of each label can be different which means the layout of each label over multiple rows will be random and unaligned.

If you want a button in a table column then check out: Table Button Column.

the panels are getting overflowed but no scroll option is getting enabled.

```<code>sc.setAutoscrolls(true);
</code>```

That is not how you add scrolling to a component. The component needs to be added to a JScrollPane:

```<code>JPanel scrollingPanel = new JPanel();
scrollingPanel.setLayout(...);
scrollingPanel.add(...);
scrollingPanel.add(...);

getContentPane.add(new JScrollPane(scrollingPanel), BorderLayout.CENTER);
pack();
</code>```

Note, I have never used the SpringLayout. I suggest you learn how to create your GUI's manually so you are not depending on the IDE to generated your code. It will be easier to understand and maintain the code.

Body:
I don't want to show data from the database in tabular format so I have tried something like you have seen in the code. I have have added new JPanel containers consisting of button and label each time a record is retrieved from the database. But due to large amount of data, the panels are getting overflowed but no scroll option is getting enabled.

I have tried using JScrollPane many times but none of the ways helped me.

public class Test2 extends javax.swing.JFrame {

    private Connection con;
    private Statement st;
    private ResultSet rt;
    public int PageId = 8236;

    /**
     * Creates new form Test2
     */
    public Test2() {
        initComponents();

        this.setLocationRelativeTo(null);
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521","practice","perfect");
            st = con.createStatement();

            int height = 100;
            int width = sc.getWidth();
            int x = 0;
            int y = 0;

            ResultSet rs=st.executeQuery("select id, firstname || ' ' || lastname, salary from employee");
            while(rs.next()){
                JPanel g = new JPanel();
                g.setBounds(x, y, width, height);
                g.setBackground(Color.yellow);
                JLabel l = new JLabel(rs.getString(1));
                JLabel l1 = new JLabel(rs.getString(2));
                JLabel sal = new JLabel(rs.getString(3));
                JButton b = new JButton("View profile");
                b.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        JOptionPane.showMessageDialog(sc, "Clicked!!");
                    }
                });
                g.add(l);
                g.add(l1);
                g.add(b);
                sc.add(g);

                y += (height + 10);
            }
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(this, "Can't connect", "connection error", JOptionPane.ERROR_MESSAGE);
            System.out.println(e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        sc = new javax.swing.JPanel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        sc.setAutoscrolls(true);

        javax.swing.GroupLayout scLayout = new javax.swing.GroupLayout(sc);
        sc.setLayout(scLayout);
        scLayout.setHorizontalGroup(
            scLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 252, Short.MAX_VALUE)
        );
        scLayout.setVerticalGroup(
            scLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 483, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Test2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel sc;
    // End of variables declaration
}

Body:
I don't want to show data from the database in tabular format

Why? Based on the code you provided the output will look terrible. You create multiple labels based on the text. That means the size of each label can be different which means the layout of each label over multiple rows will be random and unaligned.

If you want a button in a table column then check out: Table Button Column.

the panels are getting overflowed but no scroll option is getting enabled.

sc.setAutoscrolls(true);

That is not how you add scrolling to a component. The component needs to be added to a JScrollPane:

JPanel scrollingPanel = new JPanel();
scrollingPanel.setLayout(...);
scrollingPanel.add(...);
scrollingPanel.add(...);

getContentPane.add(new JScrollPane(scrollingPanel), BorderLayout.CENTER);
pack();

Note, I have never used the SpringLayout. I suggest you learn how to create your GUI's manually so you are not depending on the IDE to generated your code. It will be easier to understand and maintain the code.


问:
Angular : load an extrenal JS file script after Component View loaded
Under my Anglar 5 app, I have a js script file which I want to load dynamically after the loading of my component view,

this is because my script acts with my component template, and need to have the view loaded to run

I have tried this :

```<code>export class MyComponent implements AfterViewInit{
   title = 'app';
   ngAfterViewInit() {
     this.loadScript('http://www.some-library.com/library.js');
     // OR THIS
     this.loadScript('../assets/js/my-library.js');
   }
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }
}
</code>```

But it still loads my js before the loading of my component HTML file. , and this results on the non-running of my script.

(i see it in the body but in reality, it's not working)

My purpose is to load my js file after my component is loaded.

Suggestions ?

答:
Use the AfterContentChecked LifeCycle.

AfterContent hooks
  AfterContent hooks are similar to the AfterView hooks. The key difference is in the child component.

-The AfterView hooks concern ViewChildren, the child components whose element tags appear within the component's template.

-The AfterContent hooks concern ContentChildren, the child components that Angular projected into the component.

Another approach:

I solved this a long time ago with:

```<code>ngAfterViewInit() {
    setTimeout(() => {
        doSomething();
    }, 0);
}
</code>```

Body:
Under my Anglar 5 app, I have a js script file which I want to load dynamically after the loading of my component view,

this is because my script acts with my component template, and need to have the view loaded to run

I have tried this :

export class MyComponent implements AfterViewInit{
   title = 'app';
   ngAfterViewInit() {
     this.loadScript('http://www.some-library.com/library.js');
     // OR THIS
     this.loadScript('../assets/js/my-library.js');
   }
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }
}

But it still loads my js before the loading of my component HTML file. , and this results on the non-running of my script.

(i see it in the body but in reality, it's not working)

My purpose is to load my js file after my component is loaded.

Suggestions ?

Body:
Use the AfterContentChecked LifeCycle.

AfterContent hooks
  AfterContent hooks are similar to the AfterView hooks. The key difference is in the child component.

-The AfterView hooks concern ViewChildren, the child components whose element tags appear within the component's template.

-The AfterContent hooks concern ContentChildren, the child components that Angular projected into the component.

Another approach:

I solved this a long time ago with:

ngAfterViewInit() {
    setTimeout(() => {
        doSomething();
    }, 0);
}


问:
ImageView edges get cut off while rotating in GridView
I'm making memory game in Android.
I decided to use GridView with adapter, which inflates image inside every of cell.

Problem is that images in first row get cut of while 3D rotating around y axis,
 like this:

This does not happen with images in last row.
Only way I managed to avoid this behaviour was to increase padding for each image, but that changes by layout too much. I also tried adding top padding and/or margin to GridView, but that did not help.
Is there any way to make images in first rotate without this issue?
Here is my layout code:

```<code>  <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context="com.example.alen.matchinggameaddiko.activities.GameActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="150dp"
        android:layout_height="0px"
        android:layout_marginLeft="26dp"
        android:layout_marginTop="0dp"
        android:src="@drawable/addiko_logo_white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <GridView
        android:id="@+id/grid_game"
        android:layout_width="0px"
        android:layout_height="0px"
        android:layout_marginBottom="10dp"
        android:layout_marginEnd="@dimen/gridImagesMarginLeft"
        android:layout_marginStart="@dimen/gridImagesMarginRight"
        android:numColumns="4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
</android.support.constraint.ConstraintLayout>
</code>```

Thanks!

答: In a RecyclerView that I had the same issue, what worked was adding android:clipChildren="false" in the RecyclerView and android:clipToPadding="false" in the root layout of the adapter of the RecyclerView.

Body:
I'm making memory game in Android.
I decided to use GridView with adapter, which inflates image inside every of cell.

Problem is that images in first row get cut of while 3D rotating around y axis,
 like this:

This does not happen with images in last row.
Only way I managed to avoid this behaviour was to increase padding for each image, but that changes by layout too much. I also tried adding top padding and/or margin to GridView, but that did not help.
Is there any way to make images in first rotate without this issue?
Here is my layout code:

  <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context="com.example.alen.matchinggameaddiko.activities.GameActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="150dp"
        android:layout_height="0px"
        android:layout_marginLeft="26dp"
        android:layout_marginTop="0dp"
        android:src="@drawable/addiko_logo_white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <GridView
        android:id="@+id/grid_game"
        android:layout_width="0px"
        android:layout_height="0px"
        android:layout_marginBottom="10dp"
        android:layout_marginEnd="@dimen/gridImagesMarginLeft"
        android:layout_marginStart="@dimen/gridImagesMarginRight"
        android:numColumns="4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
</android.support.constraint.ConstraintLayout>

Thanks!


问:
How to import java source code into the project
I'm new to Java and got very confused when I encountered a library thats not in .jar form. I want to use openPDF so I downloaded the source code here(https://github.com/LibrePDF/OpenPDF/releases/tag/1.2.17). Note that I can't use maven since my work computer is not connected to the internet.

I am using IntelliJ and tried to add the .zip file as library by right clicking the project and adding it as a library, just like how I did it with another .jar file. So far got no errors.

However when I try to import in my code following this example(https://netjs.blogspot.com/2018/10/how-to-create-pdf-in-java-using-openpdf.html) it cannot find "com.lowagie".

答:
Welcome to stack overflow and to java!

Try to avoid linking in actual java source files, this will make it harder for you to kepp track of what is your code, and what is someone else's code, especially if you import a lot of projects like that.

If you can't access the internet I suggest downloading a pre-build jar made for that project.

You can manually download this particular jar file from maven central repository, which happens to have this project available.

https://mvnrepository.com/artifact/com.github.librepdf/openpdf/1.2.17


问:
How to press key and do a function in the background of tkinter GUI?
I'm making a program that make a optional copy, for example when pressing a key like num 1 which paste something you chose in program  or num 2 which paste something you chose in program..
but that program should work in background (minimized) but it doesn't work..

```<code>from tkinter import *
from tkinter import ttk

first = ''
second = ''

root = Tk()
#root.withdraw()
ttk.Label(root, text="1st copy").grid(row=0, column=0, padx=3, sticky='w')

copy1 = ttk.Entry(root, width=36)
copy1.grid(row=0, column=1, columnspan=2)

ttk.Label(root, text="2nd copy").grid(row=1, column=0, padx=3, sticky='w')

copy2 = ttk.Entry(root, width=36)
copy2.grid(row=1, column=1, columnspan=2)

savebutton = ttk.Button(root, text='save')
savebutton.grid(row=2, column=2, sticky='e')
savebutton.config(command=lambda:save())

def save():
    global first, second
    first = copy1.get()
    second = copy2.get()

def BuClick(x):
    global first, second

    root.clipboard_clear()
    if x == 1:
        root.clipboard_append(first)
    else:
        root.clipboard_append(second)
    root.update()

root.bind('1', lambda x = 1:BuClick(1))
root.bind('2', lambda y = 2:BuClick(2))
</code>```

so how I can make it work in background ??
Thanks in advance..

答: In Tkinter to do something in the background you should use the after method. This puts and event onto the UI event queue that calls your function after some delay. In this case root.bind('<Key-1>', lambda: root.after_idle(BuClick(first))) should do it. This schedules a call to BuClick once the event queue is idle (ie: not processing other UI events like mouse movement or window redrawing etc).

Body:
I'm making a program that make a optional copy, for example when pressing a key like num 1 which paste something you chose in program  or num 2 which paste something you chose in program..
but that program should work in background (minimized) but it doesn't work..

from tkinter import *
from tkinter import ttk

first = ''
second = ''

root = Tk()
#root.withdraw()
ttk.Label(root, text="1st copy").grid(row=0, column=0, padx=3, sticky='w')

copy1 = ttk.Entry(root, width=36)
copy1.grid(row=0, column=1, columnspan=2)

ttk.Label(root, text="2nd copy").grid(row=1, column=0, padx=3, sticky='w')

copy2 = ttk.Entry(root, width=36)
copy2.grid(row=1, column=1, columnspan=2)

savebutton = ttk.Button(root, text='save')
savebutton.grid(row=2, column=2, sticky='e')
savebutton.config(command=lambda:save())

def save():
    global first, second
    first = copy1.get()
    second = copy2.get()

def BuClick(x):
    global first, second

    root.clipboard_clear()
    if x == 1:
        root.clipboard_append(first)
    else:
        root.clipboard_append(second)
    root.update()

root.bind('1', lambda x = 1:BuClick(1))
root.bind('2', lambda y = 2:BuClick(2))

so how I can make it work in background ??
Thanks in advance..


问:
New To Visual Studio Code, having problems with pandas/numpy
I normally use PyCharm for python coding, but just for the heck of it, I tried to use Visual Studio Code today, and I'm having some problems.

So I followed the steps shown in the "Getting Started with Python in VS Code" page, and I copied this to my new python project:

```<code>import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

x = np.linspace(0, 20, 100)  # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x))       # Plot the sine of each x point
plt.show()                   # Display the plot
</code>```

just to test if it works well, and for some random reason, whenever I run this code through terminal/cmd in VSCode, I get this:

```<code>ImportError: Missing required dependencies ['numpy']
</code>```

BUT when I use the Debug Mode, it seems to work perfectly fine.

similar thing happened when I tried to run my previous projects through VSCode.  So I thought maybe it was just the problem with my environment, so I changed it to the one where I have my tools installed, but nope, I still got the error.

I tried uninstalling then installing again and that didn't work as well.
I Seriously don't know what's happening right now. Why does it work well in Debug Mode but not in terminal/cmd? does anyone know what to do in this situation?

Thanks!

答: Got this error and was able to fix it by running conda init in the Python Debug Console terminal, and then closing the terminal before starting a new debug session.

Body:
I normally use PyCharm for python coding, but just for the heck of it, I tried to use Visual Studio Code today, and I'm having some problems.

So I followed the steps shown in the "Getting Started with Python in VS Code" page, and I copied this to my new python project:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

x = np.linspace(0, 20, 100)  # Create a list of evenly-spaced numbers over the range
plt.plot(x, np.sin(x))       # Plot the sine of each x point
plt.show()                   # Display the plot

just to test if it works well, and for some random reason, whenever I run this code through terminal/cmd in VSCode, I get this:

ImportError: Missing required dependencies ['numpy']

BUT when I use the Debug Mode, it seems to work perfectly fine.

similar thing happened when I tried to run my previous projects through VSCode.  So I thought maybe it was just the problem with my environment, so I changed it to the one where I have my tools installed, but nope, I still got the error.

I tried uninstalling then installing again and that didn't work as well.
I Seriously don't know what's happening right now. Why does it work well in Debug Mode but not in terminal/cmd? does anyone know what to do in this situation?

Thanks!


问:
MySQL is not using index for ORDER BY
I have index on (column_1, column_2, column_3) and when I run this query

```<code>SELECT * FROM table ORDER BY column_1 DESC, column_2 ASC, column_3 ASC
</code>```

that index is not used.

I would need that index to be used since there is large difference in query time when I only use ORDER BY column_1 DESC (around 0.0005 seconds) and ORDER BY column_1 DESC, column_2 ASC, column_3 ASC (around 0.4 seconds).

Also that index is not even used in ORDER BY column_1 DESC.

This is EXPLAIN for ORDER BY column_1 DESC, column_2 ASC, column_3 ASC, same is for only ORDER BY column_1 DESC:

Is there a reason why index is not used?

答:
Your index-definition needs to match the sorting order you are querying, or at least the mixed sorting direction (that is, either DESC, ASC, ASC or ASC, DESC, DESC). The ORDER BY-docs say:

If a query mixes ASC and DESC, the optimizer can use an index on the columns if the index also uses corresponding mixed ascending and descending columns. [...] The optimizer can use an index on (key_part1, key_part2) if key_part1 is descending and key_part2 is ascending. It can also use an index on those columns (with a backward scan) if key_part1 is ascending and key_part2 is descending.

See here for more information.

Title: MySQL is not using index for ORDER BY

Body:
I have index on (column_1, column_2, column_3) and when I run this query

SELECT * FROM table ORDER BY column_1 DESC, column_2 ASC, column_3 ASC

that index is not used.

I would need that index to be used since there is large difference in query time when I only use ORDER BY column_1 DESC (around 0.0005 seconds) and ORDER BY column_1 DESC, column_2 ASC, column_3 ASC (around 0.4 seconds).

Also that index is not even used in ORDER BY column_1 DESC.

This is EXPLAIN for ORDER BY column_1 DESC, column_2 ASC, column_3 ASC, same is for only ORDER BY column_1 DESC:

Is there a reason why index is not used?


问:
Leetcode: why it behaviors different for ``at`` method for **string Class** on **Submit** and **Run Code**
I am doing a problem on leetcode. The description of this problem is as follows:

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

```<code>Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.
</code>```

Example 2:

```<code>Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.
</code>```

I tried to do some comparison before I used the at method.

```<code>class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s)
    {
        if (!s.length() || s.length() == 1 || s.length() == 2)
            return s.length();

        unsigned int left = 0, right = 0; // Use sliding window

        map<char, int> mp;

        int count;

        int len = s.length();

        int res = 1; // default answer

        while (right < len) {
            if (right < len && (mp.find(s.at(right)) == mp.end() || mp[s.at(right)] == 0)) {
                count++;
            }
            mp[s.at(right)]++;
            right++;

            if (count > 2) // if count is out of scope, just undo last action
            {
                count--;
                right--;
                if (right < len)
                    mp[s.at(right)]--;

                if (right - left > res) {
                    res = right - left;
                }

                while (count == 2) {
                    mp[s.at(left)]--;
                    if (mp[s.at(left)] == 0)
                        count--;
                    left++;
                }
            }
        }

        return right - left > res ? right - left : res;
    }
};
</code>```

Since all the inputs must be valid.

My problem is that for input aac, I clicked the Run Code button, it works fine.

However, when I click Submit, it will fail on this case. Actually I bumped into this problem several times. I just want to know whether it is a compiler problem?

答: You failed to initialise the variable count, so your program has undefined behaviour.

Body:
I am doing a problem on leetcode. The description of this problem is as follows:

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.

I tried to do some comparison before I used the at method.

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s)
    {
        if (!s.length() || s.length() == 1 || s.length() == 2)
            return s.length();

        unsigned int left = 0, right = 0; // Use sliding window

        map<char, int> mp;

        int count;

        int len = s.length();

        int res = 1; // default answer

        while (right < len) {
            if (right < len && (mp.find(s.at(right)) == mp.end() || mp[s.at(right)] == 0)) {
                count++;
            }
            mp[s.at(right)]++;
            right++;

            if (count > 2) // if count is out of scope, just undo last action
            {
                count--;
                right--;
                if (right < len)
                    mp[s.at(right)]--;

                if (right - left > res) {
                    res = right - left;
                }

                while (count == 2) {
                    mp[s.at(left)]--;
                    if (mp[s.at(left)] == 0)
                        count--;
                    left++;
                }
            }
        }

        return right - left > res ? right - left : res;
    }
};

Since all the inputs must be valid.

My problem is that for input aac, I clicked the Run Code button, it works fine.

However, when I click Submit, it will fail on this case. Actually I bumped into this problem several times. I just want to know whether it is a compiler problem?


问:
regexp to match simple markdown
I'm trying to figure out the regexp to match all the occurences of *this kind of strings*. Two additional rules unfortunately made this thing more complicated than I thought:

tagged string should start with * followed by non-whitespace character (so * this one* should not be matched

tagged string should end with non-whitespace followed by * followed by whitespace (so *this one * and *this o*ne should not be matched

I started with simplest regexp \*\S([^\*]+)?\* which for my testing string:

*foo 1 * 2 bar* foo *b* azz *qu **ux*

matches places in square brackets:

[*foo 1 *] 2 bar* foo [*b*] azz [*qu *][*ux*]

and this is what I'd like to achieve:

[*foo 1 * 2 bar*] foo [*b*] azz [*qu **ux*]

so 2 problems appear:

how to express in a regexp a rule from 2. "search till first non-whitespace followed * followed by whitespace appears"? positive lookahead?

how to match whitespace from rule 2. but not include it into result, which \*\S([^\*]+)?\*\s would do?

答:
```<code>public class Test {

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\*\\S.*?(?<!\\s)\\*(?=\\s|$)");
        Matcher matcher = pattern.matcher("*foo 1 * 2 bar* foo *b* azz *qu **ux*");
        int i = 1;
        while(matcher.find()) {
            System.out.printf("%d: %s%n", i++, matcher.group());
        }
    }
}
</code>```

*\S : * followed by a non-whitespace char

.*? : consume chars non-greedy.

(?<!\s)* : * following non-whitespace char. This is negative look
   behind, which does not consume non-whitespace char.

(?=\s|$) : positive lookahead. * should be followed by whitespace or
   end of line.

Title: regexp to match simple markdown

Body:
public class Test {

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\*\\S.*?(?<!\\s)\\*(?=\\s|$)");
        Matcher matcher = pattern.matcher("*foo 1 * 2 bar* foo *b* azz *qu **ux*");
        int i = 1;
        while(matcher.find()) {
            System.out.printf("%d: %s%n", i++, matcher.group());
        }
    }
}

*\S : * followed by a non-whitespace char

.*? : consume chars non-greedy.

(?<!\s)* : * following non-whitespace char. This is negative look
   behind, which does not consume non-whitespace char.

(?=\s|$) : positive lookahead. * should be followed by whitespace or
   end of line.


问:
Showing loading with Lottie with AsyncTask
I am supposed to use the Android standard for showing loading in my app. I see this awesome library's in Lottie https://lottiefiles.com/890-loading-animation. Can someone help me understand how to use it in Asynctask in Android and on an overlay in Android?

I was able to do start and stop animation.

答:
You just add this in your app gradle dependencies

```<code>dependencies {
  implementation 'com.airbnb.android:lottie:$lottieVersion'
}
</code>```

and include in layout file

```<code><com.airbnb.lottie.LottieAnimationView
            android:id="@+id/originalTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="16dp"
            app:lottie_rawRes="@raw/name"
            app:lottie_autoPlay="true"
            app:lottie_loop="true"/>
</code>```

@raw/name is resource file you downloaded from https://lottiefiles.com/890-loading-animation

You can checkout lottie samples on git https://github.com/airbnb/lottie-android/tree/4ea04fd194649d48b217f91c260735f7d0852187/LottieSample

Body:
You just add this in your app gradle dependencies

dependencies {
  implementation 'com.airbnb.android:lottie:$lottieVersion'
}

and include in layout file

<com.airbnb.lottie.LottieAnimationView
            android:id="@+id/originalTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="16dp"
            app:lottie_rawRes="@raw/name"
            app:lottie_autoPlay="true"
            app:lottie_loop="true"/>

@raw/name is resource file you downloaded from https://lottiefiles.com/890-loading-animation

You can checkout lottie samples on git https://github.com/airbnb/lottie-android/tree/4ea04fd194649d48b217f91c260735f7d0852187/LottieSample


问:
Can you "line-break" a table using CSS by width or number of columns?
I have an HTML table with 17 columns over 2 header rows and 1 body row. On most desktop views, this table fits nicely with my design, but on small screens the table overhangs its parent element and a significant amount of horizontal scroll is created.

I was wondering if there's a way in CSS/HTML/JS to catch a table going over a certain width, or counting a number of columns (or any other sensible way of doing it), and causing it to 'break' over into a new line, the same way a line break would be added to a paragraph. I want to catch this programatically (rather than just rewriting the table to multiple tables) as the large-screen experience is dramatically better without this hypothetical column-line break.

Ideally I'd like to keep the css definitions of table-cell etc (as in, not just make everything display: block and be done with it).

To add to the complications, some of the header cells in the top row span two columns. I'm hoping a solution can be found that either doesn't break those cells, or copies the text in the cell to both columns after a break is made.

This is all inside the Foundation 6 framework, if there's any tools there that I've missed. I tried using Foundation's
, but it doesn't work - it only shows the body row, I think because some of the header cells span multiple columns.

答: Having done more research, I can see there's no 'proper' way to do what I wanted to do. In my case, the simplest way to achieve the desired result visually was to make each column/column pair its own table, and then make those tables display as blocks and float to the left. This isn't great semantically (a new table for every major data point), but it's for an internal tool to be used by a small team, so I'm not spending more time on this.


问:
Error 403 accessing admin/groups OIDC API from Keycloak
Using keycloak-authz-client (6.0.1) only (no Spring Security), I need to read user informations AND user groups from my service provider.

After getting a proper access token, thanks to the AuthzClient, I was able to reach user information API:

    UriBuilder target = UriBuilder.fromUri(kcURL);
    target.path("realms/{realm}/protocol/openid-connect/userinfo")
          .resolveTemplate("realm", this.realm);

    UserInfoOIDC info = new UserInfoOIDC();
    try {
        UserInfo response = this.buildBearerInvocation(target, accessToken).get(UserInfo.class);
        info.setName(response.getName());
        info.setUsername(response.getPreferredUsername());
        info.setCompleted(true);
        log.info("User info successfully retrieved from {}", this.realm);
    } catch (WebApplicationException e) {
        log.error("User info failure on {}: {}", this.realm, e.getMessage());
    }
...
    private Invocation.Builder buildBearerInvocation(UriBuilder target, String accessToken) {
        WebTarget webTarget = restClient.target(target);
        Invocation.Builder builder = webTarget.request(APPLICATION_JSON)
                .header(AUTHORIZATION, "Bearer " + accessToken);
        return builder;
    }
```

<p>But I couldn't access the "admin API":</p>

<pre class="lang-java prettyprint-override"><code>    UriBuilder target = UriBuilder.fromUri(kcURL);
    target.path("admin/realms/" + this.realm);
    target.path("users/" + userId);
    target.path("groups");
    try {
        return this.buildBearerInvocation(target, accessToken)
                .get(GroupRepresentation.class);
    } catch (WebApplicationException e) {
        log.error("User groups failure on realms {}: {}", this.realm, e.getMessage());
    }
</code>```

[main] INFO com.LoggingFilter - Processing http://localhost:8080/auth/admin/realms/TestRealm/users/0f443554-01d0-4b40-a652-0c8c174632d4/groups
[main] ERROR com.KeycloakProvider - User groups failure on realms TestRealm: HTTP 403 Forbidden

I'm wondering if that might simply come from insufficient user access rights or rather from a CORS issue here (I've added "127.0.0.1 localhost-auth" to my etc/hosts file, not sure at all that would be of any help here, though).
How can I open the "admin API" to a user, more CORS configuration or any special role for the user?

EDITED - the Keycloak Admin Client won't help here (HTTP 403 Forbidden as well):

    @Test
    public void checkKeycloakAdminClient() {
        Keycloak client = KeycloakBuilder.builder()
                .serverUrl(url)
                .realm(realm)
                .username(adminUsername)
                .password(adminPassword)
                .clientId(clientId)
                .clientSecret(clientSecret)
                .build();
        RealmResource realmResource = client.realm(realm);

        UsersResource usersResource = realmResource.users();
        List<UserRepresentation> users = usersResource.search(username);
    }
```

答: Assign all "view-..." and "query-..." available Client Roles from "realm-management" realm's client to the admin user (see User/Role Mappings).</p>

Body:
Using keycloak-authz-client (6.0.1) only (no Spring Security), I need to read user informations AND user groups from my service provider.

After getting a proper access token, thanks to the AuthzClient, I was able to reach user information API:

    UriBuilder target = UriBuilder.fromUri(kcURL);
    target.path("realms/{realm}/protocol/openid-connect/userinfo")
          .resolveTemplate("realm", this.realm);

    UserInfoOIDC info = new UserInfoOIDC();
    try {
        UserInfo response = this.buildBearerInvocation(target, accessToken).get(UserInfo.class);
        info.setName(response.getName());
        info.setUsername(response.getPreferredUsername());
        info.setCompleted(true);
        log.info("User info successfully retrieved from {}", this.realm);
    } catch (WebApplicationException e) {
        log.error("User info failure on {}: {}", this.realm, e.getMessage());
    }
...
    private Invocation.Builder buildBearerInvocation(UriBuilder target, String accessToken) {
        WebTarget webTarget = restClient.target(target);
        Invocation.Builder builder = webTarget.request(APPLICATION_JSON)
                .header(AUTHORIZATION, "Bearer " + accessToken);
        return builder;
    }

But I couldn't access the "admin API":

    UriBuilder target = UriBuilder.fromUri(kcURL);
    target.path("admin/realms/" + this.realm);
    target.path("users/" + userId);
    target.path("groups");
    try {
        return this.buildBearerInvocation(target, accessToken)
                .get(GroupRepresentation.class);
    } catch (WebApplicationException e) {
        log.error("User groups failure on realms {}: {}", this.realm, e.getMessage());
    }

[main] INFO com.LoggingFilter - Processing http://localhost:8080/auth/admin/realms/TestRealm/users/0f443554-01d0-4b40-a652-0c8c174632d4/groups
[main] ERROR com.KeycloakProvider - User groups failure on realms TestRealm: HTTP 403 Forbidden

I'm wondering if that might simply come from insufficient user access rights or rather from a CORS issue here (I've added "127.0.0.1 localhost-auth" to my etc/hosts file, not sure at all that would be of any help here, though).
How can I open the "admin API" to a user, more CORS configuration or any special role for the user?

EDITED - the Keycloak Admin Client won't help here (HTTP 403 Forbidden as well):

    @Test
    public void checkKeycloakAdminClient() {
        Keycloak client = KeycloakBuilder.builder()
                .serverUrl(url)
                .realm(realm)
                .username(adminUsername)
                .password(adminPassword)
                .clientId(clientId)
                .clientSecret(clientSecret)
                .build();
        RealmResource realmResource = client.realm(realm);

        UsersResource usersResource = realmResource.users();
        List<UserRepresentation> users = usersResource.search(username);
    }


问:
Getting MonthAndYear name in sql?
I need a small script to get the current month name and current year. So as to create a unique batch to store statements. My preferred format is January2011 or Feb2011 whichever is easier to get. i.e. MonthYear</p>

答:
You can use the following:</p>

```<code>select datename(month,getdate()) + cast(datepart(year,getdate()) as char(4))
</code>```

Title: Getting MonthAndYear name in sql?

Body:
You can use the following:

select datename(month,getdate()) + cast(datepart(year,getdate()) as char(4))


问:
Custom resource/claim not being returned in "userinfo"
I'm trying to add some custom claims to my IdentityServer4 flow, but I can't get them to show up in the /userinfo endpoint.

I'm only using "in memory" configuration for now, so in this I have created a new IdentityResource with my custom scope:

new IdentityResource {
    DisplayName = "My Custom Resource",
    Name = "mycustom",
    UserClaims = new List<string> {
        "mycustom.myvalue"
    }
}
```

<p>And I've set my client to be able to use this:</p>

<pre class="lang-cs prettyprint-override"><code>new Client {
    AllowedScopes = {
        IdentityServerConstants.StandardScopes.OpenId,
        "mycustom"
    }
}
</code>```

Then, whenever a login is successful, I do the following to sign in the user before redirecting back to /authorize/callback

await _events.RaiseAsync(new UserLoginSuccessEvent(
    "provider",
    "providerUserID",
    "subjectID",
    "name"));
await HttpContext.SignInAsync(
    "subject",
    "name",
    new AuthenticationProperties(),
    new Claim("mycustom.myvalue", "987654321"));
```

Now, I can do a full authorize flow with ?scope=openid+mycustom, but when I make the call to the userinfo endpoint, it does not return mycustom.myvalue

I'm probably only missing some minor detail, but I can't for the life of me figure out what... so what am I missing to get this to work?

答:
It doesn't work because when you add your claim via HttpContext.SignInAsync(..., new Claim("mycustom.myvalue", "987654321")) it is only retained whenever the user is actually present and the ClaimsPrincipal is created through the cookie authentication.

Because you are doing the roundtrip back to /userinfo it will only give you claims that the default IProfileService would normally return and it can't possibly know about that extra claim.

Try adding this claim to one of the TestUser directly (if you are using in memory users):

```<code>    public static List<TestUser> GetUsers()
    {
        return new List<TestUser>
        {
            new TestUser
            {
                SubjectId = "1",
                Username = "alice",
                Password = "password",

                Claims = new []
                {
                    new Claim("name", "Alice"),
                    new Claim("website", "https://alice.com"),
                    new Claim("mycustom.myvalue", "987654321")
                }
            }....
</code>```

Body:
I'm trying to add some custom claims to my IdentityServer4 flow, but I can't get them to show up in the /userinfo endpoint.

I'm only using "in memory" configuration for now, so in this I have created a new IdentityResource with my custom scope:

new IdentityResource {
    DisplayName = "My Custom Resource",
    Name = "mycustom",
    UserClaims = new List<string> {
        "mycustom.myvalue"
    }
}

And I've set my client to be able to use this:

new Client {
    AllowedScopes = {
        IdentityServerConstants.StandardScopes.OpenId,
        "mycustom"
    }
}

Then, whenever a login is successful, I do the following to sign in the user before redirecting back to /authorize/callback

await _events.RaiseAsync(new UserLoginSuccessEvent(
    "provider",
    "providerUserID",
    "subjectID",
    "name"));
await HttpContext.SignInAsync(
    "subject",
    "name",
    new AuthenticationProperties(),
    new Claim("mycustom.myvalue", "987654321"));

Now, I can do a full authorize flow with ?scope=openid+mycustom, but when I make the call to the userinfo endpoint, it does not return mycustom.myvalue

I'm probably only missing some minor detail, but I can't for the life of me figure out what... so what am I missing to get this to work?

Body:
It doesn't work because when you add your claim via HttpContext.SignInAsync(..., new Claim("mycustom.myvalue", "987654321")) it is only retained whenever the user is actually present and the ClaimsPrincipal is created through the cookie authentication.

Because you are doing the roundtrip back to /userinfo it will only give you claims that the default IProfileService would normally return and it can't possibly know about that extra claim.

Try adding this claim to one of the TestUser directly (if you are using in memory users):

    public static List<TestUser> GetUsers()
    {
        return new List<TestUser>
        {
            new TestUser
            {
                SubjectId = "1",
                Username = "alice",
                Password = "password",

                Claims = new []
                {
                    new Claim("name", "Alice"),
                    new Claim("website", "https://alice.com"),
                    new Claim("mycustom.myvalue", "987654321")
                }
            }....


问:
Getting 405 error code when using Cloudfront to origin on ec2 instance
I created a cloudfront distribution that connected to 2 origins:
1. s3 static website I uploaded.
2. ec2 instance with nginx docker with the following configuration:

```<code>location /api {
        proxy_pass http://my_app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  client_max_body_size 1000M;
  server_tokens off;
</code>```

I configure 2 behaviors
s3 with Default (*) path pattern allowing all HTTP methods use origin cache headers. forward all caching and string.

ec2 path pattern api allowing all HTTP methods use origin cache headers. forward all caching and string.

and I'm getting 405

```<code><html>
<head><title>405 Method Not Allowed</title></head>
<body>
<h1>405 Method Not Allowed</h1>
<ul>
<li>Code: MethodNotAllowed</li>
<li>Message: The specified method is not allowed against this resource.</li>
<li>Method: POST</li>
<li>ResourceType: OBJECT</li>
<li>RequestId: 871316565A038A65</li>
<li>HostId: BHbdP09UWX2xCvW6qqpOQYaGwy4lvgrVVYoSCaLrSBZ2TALZT5kk9Po7k6Akq2FYZ6NojFyINBk=</li>
</ul>
<hr/>
</body>
</html>
</code>```

答:
The response is coming from S3 as you can see RequestId and HostId in the response.
S3 supports POST http request but you need to make sure that it has Form-Data. S3 with POST request only accept Form data.
https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html

If you can't use Form-data, use PUT request to CloudFront.

Body:
I created a cloudfront distribution that connected to 2 origins:
1. s3 static website I uploaded.
2. ec2 instance with nginx docker with the following configuration:

location /api {
        proxy_pass http://my_app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  client_max_body_size 1000M;
  server_tokens off;

I configure 2 behaviors
s3 with Default (*) path pattern allowing all HTTP methods use origin cache headers. forward all caching and string.

ec2 path pattern api allowing all HTTP methods use origin cache headers. forward all caching and string.

and I'm getting 405

<title>405 Method Not Allowed</title>

405 Method Not Allowed

Code: MethodNotAllowed

Message: The specified method is not allowed against this resource.

Method: POST

ResourceType: OBJECT

RequestId: 871316565A038A65

HostId: BHbdP09UWX2xCvW6qqpOQYaGwy4lvgrVVYoSCaLrSBZ2TALZT5kk9Po7k6Akq2FYZ6NojFyINBk=


问:
Ant patterns configuration
I have this Spring configuration and OAuth2:

```<code>public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource-server-rest-api";
    private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
    private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
    private static final String SECURED_PATTERN = "/api/**";
    private static final String PUBLIC_PATTERN = "/api/*/public/**";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                    .anonymous()
                .and()
                    .requestMatchers()
                        .antMatchers(SECURED_PATTERN)
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
                .anyRequest().access(SECURED_READ_SCOPE);
    }
}
</code>```

Now I want to add Swagger to my project. I configured a SwaggerController:

```<code>@Controller //note - this is a spring-boot controller, not @RestController
public class SwaggerController {

    public static final String SWAGGER_URL = "/api/v1/public/swagger/docs";
    public static final String SWAGGER_HTML = "/swagger-ui.html";

    @RequestMapping(SWAGGER_URL)
    public String home() {
        return "redirect:" + SWAGGER_HTML;
    }
}
</code>```

The problem is that I cannot make the "/swagger-ui.html" path not to trigger the Spring Login.
I tried this (note that I added antMatchers for the Swagger html):

```<code>@Override
    public void configure(HttpSecurity http) throws Exception {
        http
                ...
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers("/swagger-ui.htm").permitAll()// No authentication
</code>```

...
        }

But it did not work.
How do I need to configure the HttpSecurity?

答:
So the swagger home page should redirect to /swagger-ui.html ?

If yes, you have a typo when configuring HttpSecurity, which you only type htm only. So change to :

```<code> .antMatchers("/swagger-ui.html").permitAll()
</code>```

On the other hand , if the swagger home page is /swagger-ui.htm . Then you change the SWAGGER_HTML in your controller to :

```<code> public static final String SWAGGER_HTML = "/swagger-ui.htm";
</code>```

Title: Ant patterns configuration

Body:
I have this Spring configuration and OAuth2:

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource-server-rest-api";
    private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
    private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
    private static final String SECURED_PATTERN = "/api/**";
    private static final String PUBLIC_PATTERN = "/api/*/public/**";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                    .anonymous()
                .and()
                    .requestMatchers()
                        .antMatchers(SECURED_PATTERN)
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
                .anyRequest().access(SECURED_READ_SCOPE);
    }
}

Now I want to add Swagger to my project. I configured a SwaggerController:

@Controller //note - this is a spring-boot controller, not @RestController
public class SwaggerController {

    public static final String SWAGGER_URL = "/api/v1/public/swagger/docs";
    public static final String SWAGGER_HTML = "/swagger-ui.html";

    @RequestMapping(SWAGGER_URL)
    public String home() {
        return "redirect:" + SWAGGER_HTML;
    }
}

The problem is that I cannot make the "/swagger-ui.html" path not to trigger the Spring Login.
I tried this (note that I added antMatchers for the Swagger html):

@Override
    public void configure(HttpSecurity http) throws Exception {
        http
                ...
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers("/swagger-ui.htm").permitAll()// No authentication

...
        }

But it did not work.
How do I need to configure the HttpSecurity?

Body:
So the swagger home page should redirect to /swagger-ui.html ?

If yes, you have a typo when configuring HttpSecurity, which you only type htm only. So change to :

 .antMatchers("/swagger-ui.html").permitAll()

On the other hand , if the swagger home page is /swagger-ui.htm . Then you change the SWAGGER_HTML in your controller to :

 public static final String SWAGGER_HTML = "/swagger-ui.htm";


问:
xib file doesn't appear mobile layout in storyboard
When I try to make autolayout I can't choose the iPhone model to work on it.

答: No you can not choose different models as we can do in storyboard. But you can set custom width (according to different devices) and height (as you want) so you will fill same like iPhone models.</p>


问:
MySQL ORDER By one Specific value in column (having comma separated values)
I want to sort the user record according to city (chosen from the drop-down list). like if I pass city_id 22 in my query then i want all the row first which are having city_ids 22 then the rest of the rows.

I know WHERE find_in_set('22',city_ids) will give me the correct result but it will not return the all rows so I want to achieve it using some ORDER BY .

I have tried ORDER BY FIND_IN_SET('22',city_ids) but its not working. How do I fix this, any best way?

User Table:

```<code>Id    Name     city_ids
1     AAAAA    10,22,30
2     BBBBB    11,28
3     CCCCC    15,22,44
4     DDDDD    19,99,
5     EEEEE    55,27,22
</code>```

Want Sorted Output like below:

```<code>Id    Name     city_ids
1     AAAAA    10,22,30
3     CCCCC    15,22,44
5     EEEEE    55,27,22
2     BBBBB    11,28
4     DDDDD    19,99,
</code>```

答:
The expression:

```<code>FIND_IN_SET('22', city_ids) > 0
</code>```

will return 1 for all rows where '22' exists in column city_ids and 0 for the others.

So, after that you need add one more level for sorting by id ascending:

```<code>ORDER BY
  FIND_IN_SET('22', city_ids) > 0 DESC,
  id
</code>```

See the demo.

Results:

```<code>| Id  | Name  | city_ids |
| --- | ----- | -------- |
| 1   | AAAAA | 10,22,30 |
| 3   | CCCCC | 15,22,44 |
| 5   | EEEEE | 55,27,22 |
| 2   | BBBBB | 11,28    |
| 4   | DDDDD | 19,99    |
</code>```

Body:
I want to sort the user record according to city (chosen from the drop-down list). like if I pass city_id 22 in my query then i want all the row first which are having city_ids 22 then the rest of the rows.

I know WHERE find_in_set('22',city_ids) will give me the correct result but it will not return the all rows so I want to achieve it using some ORDER BY .

I have tried ORDER BY FIND_IN_SET('22',city_ids) but its not working. How do I fix this, any best way?

User Table:

Id    Name     city_ids
1     AAAAA    10,22,30
2     BBBBB    11,28
3     CCCCC    15,22,44
4     DDDDD    19,99,
5     EEEEE    55,27,22

Want Sorted Output like below:

Id    Name     city_ids
1     AAAAA    10,22,30
3     CCCCC    15,22,44
5     EEEEE    55,27,22
2     BBBBB    11,28
4     DDDDD    19,99,

Body:
The expression:

FIND_IN_SET('22', city_ids) > 0

will return 1 for all rows where '22' exists in column city_ids and 0 for the others.

So, after that you need add one more level for sorting by id ascending:

ORDER BY
  FIND_IN_SET('22', city_ids) > 0 DESC,
  id

See the demo.

Results:

| Id  | Name  | city_ids |
| --- | ----- | -------- |
| 1   | AAAAA | 10,22,30 |
| 3   | CCCCC | 15,22,44 |
| 5   | EEEEE | 55,27,22 |
| 2   | BBBBB | 11,28    |
| 4   | DDDDD | 19,99    |