问:
protoc-jar-maven-plugin: Not generating grpc service stubs
I have added maven configuration as follows.

```<code>        <plugin>
              <groupId>com.github.os72</groupId>
              <artifactId>protoc-jar-maven-plugin</artifactId>
              <version>3.5.1</version>
              <executions>
                  <execution>
                      <phase>generate-sources</phase>
                      <goals>
                          <goal>run</goal>
                      </goals>
                      <configuration>
                          <protocArtifact>com.google.protobuf:protoc:3.0.0</protocArtifact>
                          <inputDirectories>
                              <include>src/main/protobuf</include>
                          </inputDirectories>
                         <outputTargets>
                              <outputTarget>
                                  <type>java</type>
                                  <outputDirectory>src/main/java</outputDirectory>
                              </outputTarget>
                              <outputTarget>
                                  <type>grpc-java</type>
                                  <outputDirectory>src/main/java</outputDirectory>
                                  <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.1</pluginArtifact>
                              </outputTarget>
                          </outputTargets>
                      </configuration>
                  </execution>
              </executions>
       </plugin>
</code>```

I am executing it by "mvn protoc-jar:run", however it skips the grpc service stubs, only coverts "messages" to java code.

output is

```<code>[INFO] Protoc version: 3.5.1
protoc-jar: protoc version: 3.5.1, detected platform: osx-x86_64 (mac os x/x86_64)
protoc-jar: embedded: bin/3.5.1/protoc-3.5.1-osx-x86_64.exe
protoc-jar: executing: [/var/folders/9y/w8qrc__9513dv57323sjdlmw0000gn/T/protocjar320569499467403052/bin/protoc.exe, --version]
libprotoc 3.5.1
[INFO] Protoc command: /var/folders/9y/w8qrc__9513dv57323sjdlmw0000gn/T/protocjar320569499467403052/bin/protoc.exe
[INFO] Input directories:
[INFO]     /Users/dev/learn/proto-java/src/main/protobuf
[INFO] Output targets:
[INFO]     java: /Users/dev/learn/proto-java/target/generated-sources (add: main, clean: false, plugin: null, outputOptions: null)
[INFO]     Processing (java): helloworld.proto
protoc-jar: executing: [/var/folders/9y/w8qrc__9513dv57323sjdlmw0000gn/T/protocjar320569499467403052/bin/protoc.exe, -I/Users/dev/learn/proto-java/src/main/protobuf, --java_out=/Users/dev/learn/proto-java/target/generated-sources, /Users/dev/learn/proto-java/src/main/protobuf/helloworld.proto]
[INFO] Adding generated classes to classpath
</code>```

I've a simple proto file defined as

```<code>syntax = "proto3";

option java_multiple_files = true;
option java_package = "-.-.-.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
    // Sends a greeting
    rpc SayHello (HelloRequest) returns (HelloReply) {}
    rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
    string name = 1;
}

// The response message containing the greetings
message HelloReply {
    string message = 1;
}
</code>```

I only output files generated as HelloReply, HelloReplyOrBuilder, HelloRequest, HelloRequestOrBuilder, HelloWorldProto. The Greeter Grpc service stub is missing. I am new to maven, am I missing something.

答:
```<code> <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.5.1</version>
            <configuration>
                <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier}</pluginArtifact>
            </configuration>
            <executions>
                <execution>
                    <id>protobuf-generate</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

Body:
I have added maven configuration as follows.

        <plugin>
              <groupId>com.github.os72</groupId>
              <artifactId>protoc-jar-maven-plugin</artifactId>
              <version>3.5.1</version>
              <executions>
                  <execution>
                      <phase>generate-sources</phase>
                      <goals>
                          <goal>run</goal>
                      </goals>
                      <configuration>
                          <protocArtifact>com.google.protobuf:protoc:3.0.0</protocArtifact>
                          <inputDirectories>
                              <include>src/main/protobuf</include>
                          </inputDirectories>
                         <outputTargets>
                              <outputTarget>
                                  <type>java</type>
                                  <outputDirectory>src/main/java</outputDirectory>
                              </outputTarget>
                              <outputTarget>
                                  <type>grpc-java</type>
                                  <outputDirectory>src/main/java</outputDirectory>
                                  <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.1</pluginArtifact>
                              </outputTarget>
                          </outputTargets>
                      </configuration>
                  </execution>
              </executions>
       </plugin>

I am executing it by "mvn protoc-jar:run", however it skips the grpc service stubs, only coverts "messages" to java code.

output is

[INFO] Protoc version: 3.5.1
protoc-jar: protoc version: 3.5.1, detected platform: osx-x86_64 (mac os x/x86_64)
protoc-jar: embedded: bin/3.5.1/protoc-3.5.1-osx-x86_64.exe
protoc-jar: executing: [/var/folders/9y/w8qrc__9513dv57323sjdlmw0000gn/T/protocjar320569499467403052/bin/protoc.exe, --version]
libprotoc 3.5.1
[INFO] Protoc command: /var/folders/9y/w8qrc__9513dv57323sjdlmw0000gn/T/protocjar320569499467403052/bin/protoc.exe
[INFO] Input directories:
[INFO]     /Users/dev/learn/proto-java/src/main/protobuf
[INFO] Output targets:
[INFO]     java: /Users/dev/learn/proto-java/target/generated-sources (add: main, clean: false, plugin: null, outputOptions: null)
[INFO]     Processing (java): helloworld.proto
protoc-jar: executing: [/var/folders/9y/w8qrc__9513dv57323sjdlmw0000gn/T/protocjar320569499467403052/bin/protoc.exe, -I/Users/dev/learn/proto-java/src/main/protobuf, --java_out=/Users/dev/learn/proto-java/target/generated-sources, /Users/dev/learn/proto-java/src/main/protobuf/helloworld.proto]
[INFO] Adding generated classes to classpath

I've a simple proto file defined as

syntax = "proto3";

option java_multiple_files = true;
option java_package = "-.-.-.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
    // Sends a greeting
    rpc SayHello (HelloRequest) returns (HelloReply) {}
    rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
    string name = 1;
}

// The response message containing the greetings
message HelloReply {
    string message = 1;
}

I only output files generated as HelloReply, HelloReplyOrBuilder, HelloRequest, HelloRequestOrBuilder, HelloWorldProto. The Greeter Grpc service stub is missing. I am new to maven, am I missing something.


来源: stackexchange

问:
focusing ng-select filter input on drop down open
I'm using ng-select and have a custom filter header template defined which contains an input.

I would like the input to receive focus when the dropdown is opened for the select, but I cant figure out how to.

I have an example here -> https://stackblitz.com/edit/angular-playground-f57jog

I did try attaching to the ng-select (open) output and calling focus() on my input element, but this fails for me.

Whats the correct approach here?
Thanks

答:
There is a timing issue between when the ng-select open callback is fired and the filterInput element is actually rendered.  Your syntax is right, but filterInput is undefined when ng-select open emits.  Refer to the following error from debug console in your provided stackblitz:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

One approach to resolving this issue is to delay calling focus on the undefined element within the open callback.  Below I've done just that by 1) capturing the filterInput ElementRef via @ViewChild, 2) refactor your current focus logic into a method within the component and added 250 ms delay, and 3) calling said method using the ng-select component open event emitter.  I've provided an RxJS alternative to step 2 as well if preferred.

app.component.ts

```<code>// 1
@ViewChild('filterInput') filterInput: ElementRef;

// 2
setFilterFocus() {
  setTimeout((() => { this.filterInput.nativeElement.focus() }).bind(this), 250)
}
</code>```

app.component.html

```<code><!-- 3 -->
<ng-select #api [items]="cars"
          [virtualScroll]="true"
          [loading]="loading"
          bindLabel="brand"
          bindValue="id"
          (scroll)="onScroll($event)"
          (scrollToEnd)="onScrollToEnd()"
          [dropdownPosition]="'bottom'"
          [searchable]="false"
          [(ngModel)]="selectedCar2"
          [searchFn]="customSearchFn"
          (change)="onChange($event)"
          (open)="setFilterFocus()">
</code>```

Step 2 revisited - instead using RxJS

app.component.ts additional imports

```<code>import { of } from 'rxjs';
import { delay, tap } from 'rxjs/operators';
</code>```

app.component.ts setFilterFocus RxJS style

```<code>setFilterFocus() {
    of(null)
      .pipe(
        delay(250),
        tap(() => this.filterInput.nativeElement.focus()))
      .subscribe();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There is a timing issue between when the ng-select open callback is fired and the filterInput element is actually rendered.  Your syntax is right, but filterInput is undefined when ng-select open emits.  Refer to the following error from debug console in your provided stackblitz:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

One approach to resolving this issue is to delay calling focus on the undefined element within the open callback.  Below I've done just that by 1) capturing the filterInput ElementRef via @ViewChild, 2) refactor your current focus logic into a method within the component and added 250 ms delay, and 3) calling said method using the ng-select component open event emitter.  I've provided an RxJS alternative to step 2 as well if preferred.

app.component.ts

// 1
@ViewChild('filterInput') filterInput: ElementRef;

// 2
setFilterFocus() {
  setTimeout((() => { this.filterInput.nativeElement.focus() }).bind(this), 250)
}

app.component.html

<!-- 3 -->
<ng-select #api [items]="cars"
          [virtualScroll]="true"
          [loading]="loading"
          bindLabel="brand"
          bindValue="id"
          (scroll)="onScroll($event)"
          (scrollToEnd)="onScrollToEnd()"
          [dropdownPosition]="'bottom'"
          [searchable]="false"
          [(ngModel)]="selectedCar2"
          [searchFn]="customSearchFn"
          (change)="onChange($event)"
          (open)="setFilterFocus()">

Step 2 revisited - instead using RxJS

app.component.ts additional imports

import { of } from 'rxjs';
import { delay, tap } from 'rxjs/operators';

app.component.ts setFilterFocus RxJS style

setFilterFocus() {
    of(null)
      .pipe(
        delay(250),
        tap(() => this.filterInput.nativeElement.focus()))
      .subscribe();
}


问:
how we can specify input language for specific EditText(not for whole app) any help will be appreciated
how we can specify input language for specific EditText(not for the whole app) any help will be appreciated ..for example, for EditText1, I want to open the English keyboard and for EditText2 want to open some other language any help...</p>

答:
You can't change the user's keyboard. Only system apps can do that.

One possible workaround is to create your own custom keyboard views and switch programmatically.

For this, you have to create separate layouts and classes(extends KeyboardView) for each language keyboard


问:
Case-Insensitive array search
I am trying to search an NSMutableArray for a string.  I am using containsObject: currently but it looks like this is case sensitive.  I need to search for all combinations of the given string (trip).  Any ideas would be greatly appreciated.

```<code>if ([self.theArray containsObject:trip]) {
</code>```

}

答:
Create a category for NSArray and add this function in there.</p>

```<code>- (BOOL)containsStringCaseInsensitive:(NSString *)key {
    key = [key lowercaseString];
    for (int i = ([self count] - 1); i >= 0; i--) {
        NSObject * obj = [self objectAtIndex:i];
        if ([obj isKindOfClass:[NSString class]]) {
            NSString * strInArray = [(NSString *)obj lowercaseString];
            if ([key isEqualToString:strInArray]) {
                return YES;
            }
        }
    }

    return NO;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Case-Insensitive array search

Body:
I am trying to search an NSMutableArray for a string.  I am using containsObject: currently but it looks like this is case sensitive.  I need to search for all combinations of the given string (trip).  Any ideas would be greatly appreciated.

if ([self.theArray containsObject:trip]) {

}

Body:
Create a category for NSArray and add this function in there.

- (BOOL)containsStringCaseInsensitive:(NSString *)key {
    key = [key lowercaseString];
    for (int i = ([self count] - 1); i >= 0; i--) {
        NSObject * obj = [self objectAtIndex:i];
        if ([obj isKindOfClass:[NSString class]]) {
            NSString * strInArray = [(NSString *)obj lowercaseString];
            if ([key isEqualToString:strInArray]) {
                return YES;
            }
        }
    }

    return NO;
}


问:
IIS10 in Windows-Server-2016(AWS) unable to redirect HTTP request to HTTPS
IIS-10 in windows-server-2016 unable to redirect HTTP request to HTTPS.

I tried almost all configurations that are available over internet but still no success.

Note: My server will get sub-directory url as well and few example as like:

http://abctest.com/subfolder_1

http://abctest.com/subfolder_2

http://abctest.com

etc.

There could be N number of subfolders.), But IIS-10 unable to redirect Http request to Https.

Please find below configuration in IIS-10 GUI and also web.config file:

答:
```<code>    <rewrite>
        <rules>
            <rule name="http -> https" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions trackAllCaptures="true">
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" redirectType="Temporary" />
            </rule>
        </rules>
    </rewrite>
</code>```

Here is a working version I use for that in a production environment. Works for any binding that is tied to the site as well as with sub folders. If you don't like xml here is a screen shot of what it looks like. And then the only other thing that has caught me a time or two is make sure you have both the http and https binding of the url you are wanting to redirect.

Body:
    <rewrite>
        <rules>
            <rule name="http -> https" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions trackAllCaptures="true">
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" redirectType="Temporary" />
            </rule>
        </rules>
    </rewrite>

Here is a working version I use for that in a production environment. Works for any binding that is tied to the site as well as with sub folders. If you don't like xml here is a screen shot of what it looks like. And then the only other thing that has caught me a time or two is make sure you have both the http and https binding of the url you are wanting to redirect.


问:
Styling different width columns in same row Bootstrap
I've just got back in to learning bootstrap, html and css. So far I have three cards in a row of different widths using the bootstrap grid the horizontal card template. My problem is that I want my layout to be the same in each card, The title and paragraph should be the same distance away in each and the fav / info button the same distance from the title. Also, I managed to get the first two columns close but somehow there is weird extra large spacing between the image and title of the last and largest column. How can I do this?

I've tried to manually adjust the positions of the elements in each card but it's hard to get them consistent, it also made my code a mess with extra ids for very similar things. As for the odd spacing I've tried to find the issue using developer tools on chrome to change the width, padding etc but not sure what is causing this. The columns I have are col-md-3, col-md-4 and col-md-5.

these are my cards

```<code><div class="row">
<div class="col-md-3">

 <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-4">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1517/100633l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">Attack on Titan</h5>
        <p class="card-text">Airs Sunday :: 10 eps</p>"
 <div class="col-md-4">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1068/97169l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">The Rising of the Shield Hero</h5>
        <p class="card-text">Airs Wednesday :: 26 eps</p>

                <div class="status"></div>
      </div>
    </div>
  </div>
</div>
  </div>

 <div class="col-md-5">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1130/99458l.jpg" class="card-img-top" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">Hitori Bocchi no Maru Maru Seikatsu</h5>
        <p class="card-text">Airs Saturday :: 12 eps</p>
                <div class="status"></div>

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

I also added it to my codepen to better see also https://codepen.io/Shiro01/pen/YbRQmQ

I'm trying to get them similar to the cards on this site https://anichart.net/airing

I want to have the column fit the content and don't want the title breaking on to another line. I want the distance of the elements to be as equally spaced as possible so the whole design looks consistent. Thank you.

答:
remove that class=" no-gutters" ,  and add class="container-fluid" before row

not try to edit boostrap class it destroy its responsive structure

And your stutus bar can adjust with position absolute or change your style

```<code>status {
background-color: #662481;
height: 76px;
width: 10px;
position: relative;
left: 187px;
top: -103px;
margin: 0;
padding: 0;code here
</code>```

Body:
I've just got back in to learning bootstrap, html and css. So far I have three cards in a row of different widths using the bootstrap grid the horizontal card template. My problem is that I want my layout to be the same in each card, The title and paragraph should be the same distance away in each and the fav / info button the same distance from the title. Also, I managed to get the first two columns close but somehow there is weird extra large spacing between the image and title of the last and largest column. How can I do this?

I've tried to manually adjust the positions of the elements in each card but it's hard to get them consistent, it also made my code a mess with extra ids for very similar things. As for the odd spacing I've tried to find the issue using developer tools on chrome to change the width, padding etc but not sure what is causing this. The columns I have are col-md-3, col-md-4 and col-md-5.

these are my cards

Attack on Titan

Airs Sunday :: 10 eps
"

The Rising of the Shield Hero

Airs Wednesday :: 26 eps

Hitori Bocchi no Maru Maru Seikatsu

Airs Saturday :: 12 eps

I also added it to my codepen to better see also https://codepen.io/Shiro01/pen/YbRQmQ

I'm trying to get them similar to the cards on this site https://anichart.net/airing

I want to have the column fit the content and don't want the title breaking on to another line. I want the distance of the elements to be as equally spaced as possible so the whole design looks consistent. Thank you.

Body:
remove that class=" no-gutters" ,  and add class="container-fluid" before row

not try to edit boostrap class it destroy its responsive structure

And your stutus bar can adjust with position absolute or change your style

status {
background-color: #662481;
height: 76px;
width: 10px;
position: relative;
left: 187px;
top: -103px;
margin: 0;
padding: 0;code here


问:
azure devops release pipeline keeps failing at kubectl apply?
In azure devops portal, my release pipeline keeps failing at kubectl apply.It says the server could not find the requested resource.

NOTE: I haven't created a kubernetes clusture in azure portal yet.so when I went to the portal to create one, it is asking for paid subscription.

logs of the release pipeline

```<code>2019-05-30T06:07:09.1230513Z ##[section]Starting: kubectl apply
2019-05-30T06:07:09.1348192Z ==============================================================================
2019-05-30T06:07:09.1348303Z Task         : Deploy to Kubernetes
2019-05-30T06:07:09.1348381Z Description  : Deploy, configure, update your Kubernetes cluster in Azure Container Service by running kubectl commands.
2019-05-30T06:07:09.1348441Z Version      : 0.151.2
2019-05-30T06:07:09.1348510Z Author       : Microsoft Corporation
2019-05-30T06:07:09.1348566Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=851275)
2019-05-30T06:07:09.1348638Z ==============================================================================
2019-05-30T06:07:12.7827969Z [command]d:\a\_temp\kubectlTask\1559196429507\kubectl.exe --kubeconfig d:\a\_temp\kubectlTask\1559196429507\config apply -f d:\a\r1\a\_devops-sample-CI\drop\Tomcat.yaml
2019-05-30T06:07:15.1191531Z deployment "tomcat-deployment" configured
2019-05-30T06:07:15.1300152Z error: error validating "d:\\a\\r1\\a\\_devops-sample-CI\\drop\\Tomcat.yaml": error validating data: the server could not find the requested resource; if you choose to ignore these errors, turn validation off with --validate=false
2019-05-30T06:07:15.1454497Z ##[error]d:\a\_temp\kubectlTask\1559196429507\kubectl.exe failed with return code: 1
2019-05-30T06:07:15.1634357Z ##[section]Finishing: kubectl apply
</code>```

Tomcat.yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcat-deployment
  labels:
    app: tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tomcat
  template:
    metadata:
      labels:
        app: tomcat
    spec:
      containers:
      - name: tomcat
        image: suji165475/devops-sample:113
        ports:
        - containerPort: 80

---

kind: Service
apiVersion: v1
metadata:
  name: tomcat-service
spec:
  type: LoadBalancer
  selector:
    app: tomcat
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

</code>```

why is the server saying that it couldn't find the requested resource even though I have made sure that I created the build artifact(containing tomcat.yaml in drop folder) properly from the build ci pipeline?? Could this be due to the fact that I havent created the kubernetes clusture yet or is this due to some other reason??

also would using nodeport instead of LoadBalancer work on azure devops??

答: I'm fairly certain if you are using local kubernetes cluster and given this error - the issue is with the fact that Azure Devops cant reach you kubernetes cluster. You should make sure your cluster is exposed on a certain IP and ports are not blocked.</p>

Body:
In azure devops portal, my release pipeline keeps failing at kubectl apply.It says the server could not find the requested resource.

NOTE: I haven't created a kubernetes clusture in azure portal yet.so when I went to the portal to create one, it is asking for paid subscription.

logs of the release pipeline

2019-05-30T06:07:09.1230513Z ##[section]Starting: kubectl apply
2019-05-30T06:07:09.1348192Z ==============================================================================
2019-05-30T06:07:09.1348303Z Task         : Deploy to Kubernetes
2019-05-30T06:07:09.1348381Z Description  : Deploy, configure, update your Kubernetes cluster in Azure Container Service by running kubectl commands.
2019-05-30T06:07:09.1348441Z Version      : 0.151.2
2019-05-30T06:07:09.1348510Z Author       : Microsoft Corporation
2019-05-30T06:07:09.1348566Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=851275)
2019-05-30T06:07:09.1348638Z ==============================================================================
2019-05-30T06:07:12.7827969Z [command]d:\a\_temp\kubectlTask\1559196429507\kubectl.exe --kubeconfig d:\a\_temp\kubectlTask\1559196429507\config apply -f d:\a\r1\a\_devops-sample-CI\drop\Tomcat.yaml
2019-05-30T06:07:15.1191531Z deployment "tomcat-deployment" configured
2019-05-30T06:07:15.1300152Z error: error validating "d:\\a\\r1\\a\\_devops-sample-CI\\drop\\Tomcat.yaml": error validating data: the server could not find the requested resource; if you choose to ignore these errors, turn validation off with --validate=false
2019-05-30T06:07:15.1454497Z ##[error]d:\a\_temp\kubectlTask\1559196429507\kubectl.exe failed with return code: 1
2019-05-30T06:07:15.1634357Z ##[section]Finishing: kubectl apply

Tomcat.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcat-deployment
  labels:
    app: tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tomcat
  template:
    metadata:
      labels:
        app: tomcat
    spec:
      containers:
      - name: tomcat
        image: suji165475/devops-sample:113
        ports:
        - containerPort: 80

---

kind: Service
apiVersion: v1
metadata:
  name: tomcat-service
spec:
  type: LoadBalancer
  selector:
    app: tomcat
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

why is the server saying that it couldn't find the requested resource even though I have made sure that I created the build artifact(containing tomcat.yaml in drop folder) properly from the build ci pipeline?? Could this be due to the fact that I havent created the kubernetes clusture yet or is this due to some other reason??

also would using nodeport instead of LoadBalancer work on azure devops??


问:
How to get last sunday's date from today's date using shell script?
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

```<code>a=`date -dlast-sunday +%Y%m%d`
</code>```

but this gives a date of Sunday before the last one.

答:
The command to print the date of last Sunday by taking today's date is :   </p>

```<code>a=$(date -d 'last Sunday ' +"%A %F")
echo $a
</code>```

Body:
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

a=`date -dlast-sunday +%Y%m%d`

but this gives a date of Sunday before the last one.

Body:
The command to print the date of last Sunday by taking today's date is :

a=$(date -d 'last Sunday ' +"%A %F")
echo $a


问:
What is the casting in AgensGraph ver 1.3 double quote
I used agensgraph version 1.3.
Following query

```<code>'MATCH (a:movie) RETURN a.title
</code>```

gives result:

```<code>              title
---------------------------------
 "The Matrix"
 "The Matrix Reloaded"
 "The Matrix Revolutions"
 "The Devils Advocate"
 "A Few Good Men"
 "Top Gun"
 "Jerry Maguire"
 "Stand By Me"
</code>```

I don't know why is double quote operator.
What is the way to replace ""?

答:
You can use function "btrim" for removing needless quotes.

```<code>agens=# select btrim( n.value::text, '"' ) from ( match (n) return n.value ) as n;
 btrim
-------
 test
(1 row)
</code>```

You must use trim on SQL part of quires for removing quotes.

Body:
I used agensgraph version 1.3.
Following query

'MATCH (a:movie) RETURN a.title

gives result:

              title
---------------------------------
 "The Matrix"
 "The Matrix Reloaded"
 "The Matrix Revolutions"
 "The Devils Advocate"
 "A Few Good Men"
 "Top Gun"
 "Jerry Maguire"
 "Stand By Me"

I don't know why is double quote operator.
What is the way to replace ""?

Body:
You can use function "btrim" for removing needless quotes.

agens=# select btrim( n.value::text, '"' ) from ( match (n) return n.value ) as n;
 btrim
-------
 test
(1 row)

You must use trim on SQL part of quires for removing quotes.


问:
How to create a new row after 3 column in my code
I am customizing a theme in which there was a option to add only three services sections. I had added more three sections and are getting reflected on my HTML. defacult is is createing somthing like this :

row > col1 > col1 > col1 > col1 > col1 > col1

I want to create Like this :

row > col1 > col1 > col1
row > col1 > col1 > col1

Kindly help me with this

```<code><?php
/**
 * lessons Section
 *
 * @package Preschool_and_Kindergarten
*/
     $title        = get_theme_mod( 'preschool_and_kindergarten_lessons_section_title' );
     $description  = get_theme_mod( 'preschool_and_kindergarten_lessons_section_description' );
     $lesson_one   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_one' );
     $lesson_two   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_two' );
     $lesson_three = get_theme_mod( 'preschool_and_kindergarten_lesson_post_three' );
     $lesson_four = get_theme_mod( 'preschool_and_kindergarten_lesson_post_four' );
     $lesson_five = get_theme_mod( 'preschool_and_kindergarten_lesson_post_five' );
     $lesson_six = get_theme_mod( 'preschool_and_kindergarten_lesson_post_six' );
     $lessons_posts = array( $lesson_one, $lesson_two, $lesson_three, $lesson_four, $lesson_five, $lesson_six );
     $lessons_posts = array_diff( array_unique( $lessons_posts ), array('') );
?>
<section class="section-2">
    <div class="container">
        <?php
            preschool_and_kindergarten_get_section_header( $title, $description );

            if( $lessons_posts ):

                $lesson_qry = new WP_Query(array(
                    'post__in'   => $lessons_posts,
                    'orderby'   => 'post__in',
                    'posts_per_page' => -1,
                    'ignore_sticky_posts' => true
                    ));

                if( $lesson_qry->have_posts() ){ ?>
                    <div class="row">

                       <?php
                        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                            <div class="col">

                                <?php
                                    if( has_post_thumbnail() ){ ?>
                                        <div class="img-holder">
                                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                        </div>
                                <?php } ?>

                                <div class="text-holder">
                                    <h3 class="title"><?php the_title(); ?></h3>
                                    <?php the_content(); ?>
                                </div>

                            </div>

                        <?php } ?>

                    </div>
                <?php }
            wp_reset_postdata();
        endif; ?>
    </div>
</section>
</code>```

答:
May be you need something like this

if( $lesson_qry->have_posts() ){ ?>
       <?php
        $i = 0;
        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

            <?php if( ($i % 3) == 0) {?>

            <?php } ?>

                <?php
                    if( has_post_thumbnail() ){ ?>

                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>

                <?php } ?>

<?php the_title(); ?>

                    <?php the_content(); ?>

            <?php if( ($i % 3) == 0) { ?>

            <?php
                }
           $i++;
        } ?>

<?php } ?>
```

Body:
I am customizing a theme in which there was a option to add only three services sections. I had added more three sections and are getting reflected on my HTML. defacult is is createing somthing like this :

row > col1 > col1 > col1 > col1 > col1 > col1

I want to create Like this :

row > col1 > col1 > col1
row > col1 > col1 > col1

Kindly help me with this

<?php
/**
 * lessons Section
 *
 * @package Preschool_and_Kindergarten
*/
     $title        = get_theme_mod( 'preschool_and_kindergarten_lessons_section_title' );
     $description  = get_theme_mod( 'preschool_and_kindergarten_lessons_section_description' );
     $lesson_one   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_one' );
     $lesson_two   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_two' );
     $lesson_three = get_theme_mod( 'preschool_and_kindergarten_lesson_post_three' );
     $lesson_four = get_theme_mod( 'preschool_and_kindergarten_lesson_post_four' );
     $lesson_five = get_theme_mod( 'preschool_and_kindergarten_lesson_post_five' );
     $lesson_six = get_theme_mod( 'preschool_and_kindergarten_lesson_post_six' );
     $lessons_posts = array( $lesson_one, $lesson_two, $lesson_three, $lesson_four, $lesson_five, $lesson_six );
     $lessons_posts = array_diff( array_unique( $lessons_posts ), array('') );
?>

        <?php
            preschool_and_kindergarten_get_section_header( $title, $description );

            if( $lessons_posts ):

                $lesson_qry = new WP_Query(array(
                    'post__in'   => $lessons_posts,
                    'orderby'   => 'post__in',
                    'posts_per_page' => -1,
                    'ignore_sticky_posts' => true
                    ));

                if( $lesson_qry->have_posts() ){ ?>

                       <?php
                        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                                <?php
                                    if( has_post_thumbnail() ){ ?>

                                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>

                                <?php } ?>

<?php the_title(); ?>

                                    <?php the_content(); ?>

                        <?php } ?>

                <?php }
            wp_reset_postdata();
        endif; ?>

Body:
May be you need something like this

if( $lesson_qry->have_posts() ){ ?>
       <?php
        $i = 0;
        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

            <?php if( ($i % 3) == 0) {?>
                <div class="row">
            <?php } ?>
            <div class="col">
                <?php
                    if( has_post_thumbnail() ){ ?>
                        <div class="img-holder">
                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                        </div>
                <?php } ?>

                <div class="text-holder">
                    <h3 class="title"><?php the_title(); ?></h3>
                    <?php the_content(); ?>
                </div>

            </div>
            <?php if( ($i % 3) == 0) { ?>
                </div>
            <?php
                }
           $i++;
        } ?>

    </div>
<?php } ?>


问:
Check all checkboxes vuejs
I'm displaying a list of users in a table, each row has a checkbox to select the user and the checkbox value is the user's ID. The selected IDs are in turn displayed in a span below the table.

How can I select all checkboxes and deselect all checkboxes on the click of a "select all" checkbox that I have in the header of my table? Do I interact with the DOM to do this or through the vue object, I'm thinking it should be the latter but quite unsure how to approach what appears to be an easy task?! Any help would be appreciated!

HTML

```<code><div id="app">
    <h4>Users</h4>
    <div>
        <table>
            <tr>
                <th>Name</th>
                <th>Select <input type="checkbox" @click="selectAll"></th>
            </tr>
            <tr v-for="user in users">
                <td>{{ user.name }}</td>
                <td><input type="checkbox" v-model="selected" value="{{ user.id }}"></td>
            </tr>
        </table>
    </div>

    <span>Selected Ids: {{ selected| json }}</span>
</div>
</code>```

Javascript/Vuejs

```<code>new Vue({
    el: '#app',
    data: {
        users: [
            { "id": "1", "name": "Shad Jast", "email": "pfeffer.matt@yahoo.com",
            { "id": "2", "name": "Duane Metz", "email": "mohammad.ferry@yahoo.com"},
            { "id": "3", "name": "Myah Kris", "email": "evolkman@hotmail.com"},
            { "id": "4", "name": "Dr. Kamron Wunsch", "email": "lenora95@leannon.com"},
            { "id": "5", "name": "Brendon Rogahn", "email": "verlie.buckridge@yahoo.com"}
        ],
        selected: []
    },
    methods: {
        selectAll: function() {
            // ?
        }
    }
})
</code>```

答:
I have a more simple solution as following and it has all you want. The real data should be put into a map indexed the name as the label of checkbox for future easy to access.</p>

```<code><template>
  <div align="left">
    <div>
      <input type="checkbox" id="all" :checked="allNamesSelected" @click="selectAll()">
      <label for="all">All</label>
    </div>
    <div v-for="(name) in names" :key="name">
      <input type="checkbox" :id="name" :value="name" :check="isChecked(name)" v-model="selectedNames">
      <label :for="name">{{name}}</label>
    </div>
  </div>
</template>

<script>
export default {
    data() {
        return {
            names: ['Automotive', 'Beauty', 'Branding', 'B to B'],
            selectedNames: [],
        };
    },
    computed: {
        allNamesSelected() {
            return this.names.length == this.selectedNames.length;
        },
    },
    methods: {
        selectAll() {
            if (this.allNamesSelected) {
                this.selectedNames = [];
            } else {
                this.selectedNames = this.names.slice();
            }
        },
        isChecked(name) {
            return this.selectedNames.includes(name);
        }
    }
}
</script>
</code>```

Title: Check all checkboxes vuejs

Body:
I'm displaying a list of users in a table, each row has a checkbox to select the user and the checkbox value is the user's ID. The selected IDs are in turn displayed in a span below the table.

How can I select all checkboxes and deselect all checkboxes on the click of a "select all" checkbox that I have in the header of my table? Do I interact with the DOM to do this or through the vue object, I'm thinking it should be the latter but quite unsure how to approach what appears to be an easy task?! Any help would be appreciated!

HTML

Users

                Name
                Select <input type="checkbox" @click="selectAll">

                {{ user.name }}
                <input type="checkbox" v-model="selected" value="{{ user.id }}">

    Selected Ids: {{ selected| json }}

Javascript/Vuejs

new Vue({
    el: '#app',
    data: {
        users: [
            { "id": "1", "name": "Shad Jast", "email": "pfeffer.matt@yahoo.com",
            { "id": "2", "name": "Duane Metz", "email": "mohammad.ferry@yahoo.com"},
            { "id": "3", "name": "Myah Kris", "email": "evolkman@hotmail.com"},
            { "id": "4", "name": "Dr. Kamron Wunsch", "email": "lenora95@leannon.com"},
            { "id": "5", "name": "Brendon Rogahn", "email": "verlie.buckridge@yahoo.com"}
        ],
        selected: []
    },
    methods: {
        selectAll: function() {
            // ?
        }
    }
})

Body:
I have a more simple solution as following and it has all you want. The real data should be put into a map indexed the name as the label of checkbox for future easy to access.

<template>
  <div align="left">
    <div>
      <input type="checkbox" id="all" :checked="allNamesSelected" @click="selectAll()">
      <label for="all">All</label>
    </div>
    <div v-for="(name) in names" :key="name">
      <input type="checkbox" :id="name" :value="name" :check="isChecked(name)" v-model="selectedNames">
      <label :for="name">{{name}}</label>
    </div>
  </div>
</template>

<script>
export default {
    data() {
        return {
            names: ['Automotive', 'Beauty', 'Branding', 'B to B'],
            selectedNames: [],
        };
    },
    computed: {
        allNamesSelected() {
            return this.names.length == this.selectedNames.length;
        },
    },
    methods: {
        selectAll() {
            if (this.allNamesSelected) {
                this.selectedNames = [];
            } else {
                this.selectedNames = this.names.slice();
            }
        },
        isChecked(name) {
            return this.selectedNames.includes(name);
        }
    }
}
</script>


问:
Implementing OSDP encryption problems
I'm having trouble implementing the encryption part of the OSDP protocol on an Arduino.
http://www.siaonline.org/SiteAssets/SIAStore/Standards/OSDP_V2%201_5_2014.pdf

I've successfully done the negotiation part and have verified the RMAC-I response by decrypting the data and comparing with the plaintext. The part I'm stuck on is the encryption of the data packets. According to the spec, I use the RMAC-I response as my ICV for the aes128 CBC and I encrypt the packet using the S-MAC2 key.

My POLL packet (in hex) is as follows:

53 01 0e 00 0c 02 15 60

This gets padded

53 01 0e 00 0c 02 15 60 80 00 00 00 00 00 00 00

This gets xored with the ICV then encrypted with S-MAC2 as the key.

The first 4 bytes of the result is stored in the packet and sent

53 01 0e 00 0c 02 15 60 91 86 b9 3d 4a 29

Unfortunately the reader rejects the poll command with a NAK 06

I'm presuming my MAC values have not been computed correctly as I've compared my packet with the HID DTK tool (obviously the MAC and CRC values are the only difference). Can someone validate my process?

答:
2.1.7 is the current SIA spec.  IEC 60839-11-5 should be out soon. (the IEC standards version.)

The processing your describe is for the MAC suffix not the payload encryption.  MAC2 because it's only one block long (else you'd use MAC1 and then MAC2.)  OSDP uses AES to encrypt a throw-away copy of the entire message and then uses some bytes of the last cipherblock as the MAC that is transmitted.   OSDP encrypts the payload, if there is one.  In modern AES implementations you pass in an IV and a key and a buffer so one would not look at it as xoring the IV with the plaintext.

Title: Implementing OSDP encryption problems


问:
Using an illegal UTF-8 octet as a delimiter in a std::string
Hopefully improved and more focused version of my question:

For reasons that would be misleading to explain (see below), I have to store several UTF-8 encoded strings within a single string. (String means a C++ std::string here)

My approach is to join the strings with one of the illegal UTF-8 octets (0xC0, 0xC1, 0xF5-0xFF) as a delimiter as these octets can never appear within a valid UTF-8 sequence. (As 0x00 is a valid UTF-8 octet, I think it's not appropriate for my intended misuse.)

All considerations regarding performance aside, are there any problems with this approach I'm not aware of? Is there any reason to prefer one of the illegal octets?

..

In my original question I tried to provide more context, but that lead to several questions about performance issues and the intended trade-off. But my question is not about those trade-offs, its just about how technically feasible and valid my approach is.

答:
As others mentioned, using any byte that works in your situation will work just fine in an std::string. Although if your strings do not otherwise use '\0', it may be cleaner to use such rather than an illegal UTF-8 byte.

If your implementation is satisfactory in terms of speed, then I would imagine that's that. Otherwise, you could look into how databases are being managed. In that case you'd use buffers of a fixed size. The big advantage is that you would not break the memory in many small chunks and run in memory allocation problems later. Also speed wise, you would allocate those blocks once and re-use them many times. The malloc() and free() functions are expensive, especially if you have a tons of objects (new and delete operators call those functions.)

Now to save even more memory, since it sounds that is the main goal, and if possible in your situation, you could consider compressing your strings with zlib. I would use the fastest compression mode and see whether the resulting buffer is smaller, if yes, use it. Otherwise keep the uncompressed string. This requires you to save a size (4 bytes) per string. You can set the size to 0 when the buffer is not compressed.

One other things I'd like to mention is the fact that using an illegal byte will possibly be confusing to a future programmer maintaining that code base. No matter how many comments you have there, they will probably not read them anyway... you know... programmers just tend to read the code, not so much the comments. If it is something you are worried about, you could save your concatenated strings in a vector instead. Your split function would take a vector of char as input and return a vector of strings as its results.

Another possibility is to make use of swap memory through mmap(). This can be tedious, though, when handling dynamic data. This is where a database like scheme helps very much. You would allocate blocks (i.e. 64Kb at a time) and manage your data on a per block basis. When a string grows too big for the current block, move it to a new block... The advantage of this technique is that the data remains in memory unless the OS decides that it needs some of the RAM your software is using and it can swap it out an any time. To you, that swapping will be totally transparent. It also makes it much faster than hitting the default swap which has to manage your memory in a much less efficient manner.


问:
Elasticsearch querying number of dates in array matching query
I have documents in the following form

```<code>PUT test_index/_doc/1
{
    "dates" : [
      "2018-07-15T14:12:12",
      "2018-09-15T14:12:12",
      "2018-11-15T14:12:12",
      "2019-01-15T14:12:12",
      "2019-03-15T14:12:12",
      "2019-04-15T14:12:12",
      "2019-05-15T14:12:12"],
    "message" : "hello world"
}
</code>```

How do I query for documents such that there are n number of dates within the dates array falling in between two specified dates?

For example: Find all documents with 3 dates in the dates array falling in between "2018-05-15T14:12:12" and "2018-12-15T14:12:12" -- this should return the above document as "2018-07-15T14:12:12", "2018-09-15T14:12:12" and "2018-11-15T14:12:12" fall between "2018-05-15T14:12:12" and "2018-12-15T14:12:12".

答:
You can create dates as a nested document and use bucket selector aggregation.

```<code>{
  "empId":1,
  "dates":[
             {
               "Days":"2019-01-01"
             },
             {
               "Days":"2019-01-02"
             }
          ]
}
</code>```

Mapping:

```<code> "mappings" : {
      "properties" : {
       "empId" : {
              "type" : "keyword"
        },
        "dates" : {
          "type" : "nested",
          "properties" : {
            "Days" : {
              "type" : "date"
            }
          }
        }
     }
  }
</code>```

```<code>GET profile/_search
{
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "dates",
          "query": {
            "range": {
              "dates.Days": {
                "format": "yyyy-MM-dd",
                "gte": "2019-05-01",
                "lte": "2019-05-30"
              }
            }
          }
        }
      }
    }
  },
  "aggs": {
    "terms_parent_id": {
      "terms": {
        "field": "empId"
      },
      "aggs": {
        "availabilities": {
          "nested": {
            "path": "dates"
          },
          "aggs": {
            "avail": {
              "range": {
                "field": "dates.Days",
                "ranges": [
                  {
                    "from": "2019-05-01",
                    "to": "2019-05-30"
                  }
                ]
              },
              "aggs": {
                "count_Total": {
                  "value_count": {
                    "field": "dates.Days"
                  }
                }
              }
            },
            "max_hourly_inner": {
              "max_bucket": {
                "buckets_path": "avail>count_Total"
              }
            }
          }
        },
        "bucket_selector_page_id_term_count": {
          "bucket_selector": {
            "buckets_path": {
              "children_count": "availabilities>max_hourly_inner"
            },
            "script": "params.children_count>=19;"  ---> give the number of days that should match
          }
        },
        "hits": {
              "top_hits": {
                "size": 10
              }
            }
      }
    }
  }
}
</code>```

Body:
I have documents in the following form

PUT test_index/_doc/1
{
    "dates" : [
      "2018-07-15T14:12:12",
      "2018-09-15T14:12:12",
      "2018-11-15T14:12:12",
      "2019-01-15T14:12:12",
      "2019-03-15T14:12:12",
      "2019-04-15T14:12:12",
      "2019-05-15T14:12:12"],
    "message" : "hello world"
}

How do I query for documents such that there are n number of dates within the dates array falling in between two specified dates?

For example: Find all documents with 3 dates in the dates array falling in between "2018-05-15T14:12:12" and "2018-12-15T14:12:12" -- this should return the above document as "2018-07-15T14:12:12", "2018-09-15T14:12:12" and "2018-11-15T14:12:12" fall between "2018-05-15T14:12:12" and "2018-12-15T14:12:12".

Body:
You can create dates as a nested document and use bucket selector aggregation.

{
  "empId":1,
  "dates":[
             {
               "Days":"2019-01-01"
             },
             {
               "Days":"2019-01-02"
             }
          ]
}

Mapping:

 "mappings" : {
      "properties" : {
       "empId" : {
              "type" : "keyword"
        },
        "dates" : {
          "type" : "nested",
          "properties" : {
            "Days" : {
              "type" : "date"
            }
          }
        }
     }
  }

GET profile/_search
{
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "dates",
          "query": {
            "range": {
              "dates.Days": {
                "format": "yyyy-MM-dd",
                "gte": "2019-05-01",
                "lte": "2019-05-30"
              }
            }
          }
        }
      }
    }
  },
  "aggs": {
    "terms_parent_id": {
      "terms": {
        "field": "empId"
      },
      "aggs": {
        "availabilities": {
          "nested": {
            "path": "dates"
          },
          "aggs": {
            "avail": {
              "range": {
                "field": "dates.Days",
                "ranges": [
                  {
                    "from": "2019-05-01",
                    "to": "2019-05-30"
                  }
                ]
              },
              "aggs": {
                "count_Total": {
                  "value_count": {
                    "field": "dates.Days"
                  }
                }
              }
            },
            "max_hourly_inner": {
              "max_bucket": {
                "buckets_path": "avail>count_Total"
              }
            }
          }
        },
        "bucket_selector_page_id_term_count": {
          "bucket_selector": {
            "buckets_path": {
              "children_count": "availabilities>max_hourly_inner"
            },
            "script": "params.children_count>=19;"  ---> give the number of days that should match
          }
        },
        "hits": {
              "top_hits": {
                "size": 10
              }
            }
      }
    }
  }
}


问:
SBT plugins not using custom resolvers
I am trying to add sbt-native-packager plugin to my sbt build. For a number of reasons, I do not want my build to rely on default sbt repositories, I have blocked access to them on the network and added a resolver to my <project_home>/project/plugins.sbt in the following way:

```<code>resolvers += "local-repo-plugins" at "file:///" + baseDirectory.value + "/libs/repo/"
resolvers += Resolver.url("my-ivy-proxy-plugins", url("http://fullURLForRepo/"))(Patterns("[organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext]") )

addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.7.4")
</code>```

I can confirm the plugin it is hosted in my ivy proxy, but that is not even the issue, because sbt is still trying to go to default repos:

```<code>[info] Resolving com.typesafe.sbt#sbt-native-packager;0.7.4 ...
[error] Server access Error: Connection timed out url=https://repo.typesafe.com/typesafe/ivy-releases/com.typesafe.sbt/sbt-native-packager/scala_2.10/sbt_0.13/0.7.4/ivys/ivy.xml
[error] Server access Error: Connection timed out url=https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/com.typesafe.sbt/sbt-native-packager/scala_2.10/sbt_0.13/0.7.4/ivys/ivy.xml
[error] Server access Error: Connection timed out url=https://repo1.maven.org/maven2/com/typesafe/sbt/sbt-native-packager_2.10_0.13/0.7.4/sbt-native-packager-0.7.4.pom
</code>```

Also, this very same custom resolver works just fine (together with a couple of other ones, including one based on local filesystem) on my <project_home>/build.sbt when resolving library dependencies.

While I understand why the resolvers used in my project build are not the same used in my <project_home>/project/plugins.sbt, I have several questions regarding the issue I just described:

Is this the right way to define resolvers for plugins? just adding them to the <project_home>/project/plugins.sbt with that syntax?

If the answer to question 1) is yes: is there any way to avoid redundancy when defining these resolvers? e.g. I have defined exactly the very same ones in <project_home>/build.sbt

And the most important: why is the sbt build not using my ivy proxy, as specified in the resolver, to retrieve the sbt-native-packager plugin?

答: It seems the documents are not updated yet which ask you to put resolvers in plugins.sbt. Moving resolvers ++= Seq("Artima Maven Repository" at "http://repo.artima.com/releases") to build.sbt fixes the issue.

Title: SBT plugins not using custom resolvers

Body:
I am trying to add sbt-native-packager plugin to my sbt build. For a number of reasons, I do not want my build to rely on default sbt repositories, I have blocked access to them on the network and added a resolver to my <project_home>/project/plugins.sbt in the following way:

resolvers += "local-repo-plugins" at "file:///" + baseDirectory.value + "/libs/repo/"
resolvers += Resolver.url("my-ivy-proxy-plugins", url("http://fullURLForRepo/"))(Patterns("[organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext]") )

addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.7.4")

I can confirm the plugin it is hosted in my ivy proxy, but that is not even the issue, because sbt is still trying to go to default repos:

[info] Resolving com.typesafe.sbt#sbt-native-packager;0.7.4 ...
[error] Server access Error: Connection timed out url=https://repo.typesafe.com/typesafe/ivy-releases/com.typesafe.sbt/sbt-native-packager/scala_2.10/sbt_0.13/0.7.4/ivys/ivy.xml
[error] Server access Error: Connection timed out url=https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/com.typesafe.sbt/sbt-native-packager/scala_2.10/sbt_0.13/0.7.4/ivys/ivy.xml
[error] Server access Error: Connection timed out url=https://repo1.maven.org/maven2/com/typesafe/sbt/sbt-native-packager_2.10_0.13/0.7.4/sbt-native-packager-0.7.4.pom

Also, this very same custom resolver works just fine (together with a couple of other ones, including one based on local filesystem) on my <project_home>/build.sbt when resolving library dependencies.

While I understand why the resolvers used in my project build are not the same used in my <project_home>/project/plugins.sbt, I have several questions regarding the issue I just described:

Is this the right way to define resolvers for plugins? just adding them to the <project_home>/project/plugins.sbt with that syntax?

If the answer to question 1) is yes: is there any way to avoid redundancy when defining these resolvers? e.g. I have defined exactly the very same ones in <project_home>/build.sbt

And the most important: why is the sbt build not using my ivy proxy, as specified in the resolver, to retrieve the sbt-native-packager plugin?


问:
Java Regex to match multiple lines
Following is Sample the data on which regex should be applied:

```<code>2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Filter -> Map (1/1) (824780055001546646d35df7a64cfe3c) switched from CANCELING to CANCELED.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Try to restart or fail the job  (3064130e1dccead0b037f193d3699c3b) if no longer possible.
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Could not restart the job  (3064130e1dccead0b037f193d3699c3b) because the restart strategy prevented it.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Stopping checkpoint coordinator for job 3064130e1dccead0b037f193d3699c3b.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore  - Shutting down
2019-05-27 10:49:18,419 INFO  org.apache.flink.runtime.dispatcher.StandaloneDispatcher      - Job 3064130e1dccead0b037f193d3699c3b reached globally terminal state FAILED.
</code>```

Basically what I want to extract is time stamp and ERROR with message:

For an instance:

```<code>TimeStamp               Error
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Here Error message is split into multiple lines to for that I have written java pattern like below:

```<code>((?m)\\d{4}-[01]\\d-[0-3]\\d\\s[0-2]\\d((:[0-5]\\d)?){2}[\\s\\S]*ERROR[\\s\\S]*[ ]*at [\\s\\S]*)
</code>```

But it returns me all the content of the file.

What should I do to make it work so that it will give me multi-line error message too.

答:
Your pattern looks off, and also you should be using a pattern in dot all mode, since the portion of the stack trace which you want to capture may span across more one than line.  I suggest using the following regex pattern:

```<code>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} ERROR.*?(?=\bat\b)
</code>```

This matches a timestamp, followed by ERROR and then all content until reaching the first at.

Here is a working test script:

```<code>String input = "2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.\njava.lang.IllegalArgumentException: json can not be null or empty\n    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)";
String pattern = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} ERROR.*?(?=\\bat\\b)";
Pattern r = Pattern.compile(pattern, Pattern.DOTALL);
Matcher m = r.matcher(input);
if (m.find()) {
    System.out.println(m.group(0));
}
</code>```

Output:

```<code>2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
</code>```

Title: Java Regex to match multiple lines

Body:
Following is Sample the data on which regex should be applied:

2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Filter -> Map (1/1) (824780055001546646d35df7a64cfe3c) switched from CANCELING to CANCELED.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Try to restart or fail the job  (3064130e1dccead0b037f193d3699c3b) if no longer possible.
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Could not restart the job  (3064130e1dccead0b037f193d3699c3b) because the restart strategy prevented it.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Stopping checkpoint coordinator for job 3064130e1dccead0b037f193d3699c3b.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore  - Shutting down
2019-05-27 10:49:18,419 INFO  org.apache.flink.runtime.dispatcher.StandaloneDispatcher      - Job 3064130e1dccead0b037f193d3699c3b reached globally terminal state FAILED.

Basically what I want to extract is time stamp and ERROR with message:

For an instance:

TimeStamp               Error
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)

Here Error message is split into multiple lines to for that I have written java pattern like below:

((?m)\\d{4}-[01]\\d-[0-3]\\d\\s[0-2]\\d((:[0-5]\\d)?){2}[\\s\\S]*ERROR[\\s\\S]*[ ]*at [\\s\\S]*)

But it returns me all the content of the file.

What should I do to make it work so that it will give me multi-line error message too.

Body:
Your pattern looks off, and also you should be using a pattern in dot all mode, since the portion of the stack trace which you want to capture may span across more one than line.  I suggest using the following regex pattern:

\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} ERROR.*?(?=\bat\b)

This matches a timestamp, followed by ERROR and then all content until reaching the first at.

Here is a working test script:

String input = "2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.\njava.lang.IllegalArgumentException: json can not be null or empty\n    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)";
String pattern = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} ERROR.*?(?=\\bat\\b)";
Pattern r = Pattern.compile(pattern, Pattern.DOTALL);
Matcher m = r.matcher(input);
if (m.find()) {
    System.out.println(m.group(0));
}

Output:

2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty


问:
How to get empty result set with a CASE statement?
I cannot get an empty result in CASE statement. The following query returns NULL as the result:

SELECT CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END;
```

I want to get empty result (without any rows).

答:
You can filter out NULL values in the outer WHERE clause.

SELECT CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END
WHERE CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END IS NOT NULL;
```

<p>or</p>

```SELECT *
FROM (
        SELECT CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END as result_case
) x
WHERE result_case IS NOT NULL;
```

Body:
I cannot get an empty result in CASE statement. The following query returns NULL as the result:

SELECT CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END;

I want to get empty result (without any rows).

Body:
You can filter out NULL values in the outer WHERE clause.

SELECT CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END
WHERE CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END IS NOT NULL;

or

SELECT *
FROM (
        SELECT CASE WHEN ('test' IS NULL) THEN (SELECT 'null_result') ELSE (SELECT 'empty_result' WHERE 1<>1) END as result_case
) x
WHERE result_case IS NOT NULL;


问:
Command to script database structure and data
Every time I want to create a script of the database structure (and data) of our deployment database (a brand new database with the software's basic data), I have go to SSMS, select the database, Tasks -> Scripts -> Generate Scripts. Then I have a very specific setting which I have to change every single time to the same values.

This is very time consuming and looks like a task that could very well be automated. Is it possible to automate this task from within SSMS, with my specific settings? If not, is there a way to automate it outside SSMS? I do not discard writing a C# console program to perform that, this task is not for the final user it's for our labs.

UPDATE

The objective here, as usual, is getting the solution which will take less time. So, before I got to the C# coding level, I would like to try automating the existing tools. The order would be:

Can I automate from SSMS?

Can I automate by running a outside script?

How can I automate with C# coding? (the learning resources were pointed out by Nicholas Carey)

答:
Look at SMO: http://msdn.microsoft.com/en-us/library/ms162169(v=SQL.100).aspx

Then script your database, put the scripts in source control and require that changes be made via scripts.


问:
ansible task with condition
I am using the below task in my play book and trying to set condition using "when" to trigger the task.

the blow one is working

```<code>ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -e vdom= -vvv
</code>```

if i remove var vdom playbook stopped

ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -vvv

```<code> tasks:
  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}/{{ vdom }}"
    register: results
    tags: ADDLAG
    when: vdom != ""

  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}"
    register: results
    tags: ADDLAG
    when: vdom == "" or vdom is not defined
</code>```

答:
Change the conditions to

```<code>when: vdom|default("")|length > 0
</code>```

respectively

```<code>when: vdom|default("")|length == 0
</code>```

Title: ansible task with condition

Body:
I am using the below task in my play book and trying to set condition using "when" to trigger the task.

the blow one is working

ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -e vdom= -vvv

if i remove var vdom playbook stopped

ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -vvv

 tasks:
  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}/{{ vdom }}"
    register: results
    tags: ADDLAG
    when: vdom != ""

  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}"
    register: results
    tags: ADDLAG
    when: vdom == "" or vdom is not defined

Body:
Change the conditions to

when: vdom|default("")|length > 0

respectively

when: vdom|default("")|length == 0


问:
Can source string be converted to destination string?
Is there a sequence of transformation steps to convert given source string to destination string?

Note: At every step, one character can be transformed (replacement should be a character between 'A'-'Z') and all the occurrences of that character have to be transformed.
Examples are given below.

```<code>Source: "ABA"
Dest: "BAB"
Output: True
Explanation: ABA -> A**C**A -> **B**C**B** -> B**A**B

Source: "AA"
Dest: "BC"
Output: False
Explanation: AA -> BB
</code>```

I think HashMap works. But is there another Data Structure where I don't go about comparing Character by Character?

答:
You can try this:</p>

```<code>private static boolean test(String s1, String s2) {

    if(s1.length() != s2.length()) return false;

    Map<Character, Character> map = new HashMap<>();

    for (int i = 0; i < s1.length(); i++) {
        char c1 = s1.charAt(i);
        char c2 = s2.charAt(i);

        if (map.containsKey(c1)) {
            if (!map.get(c1).equals(c2)) {
                return false;
            }
        } else {
            map.put(c1, c2);
        }
    }
    return map.size() < 26;
}
</code>```

Body:
Is there a sequence of transformation steps to convert given source string to destination string?

Note: At every step, one character can be transformed (replacement should be a character between 'A'-'Z') and all the occurrences of that character have to be transformed.
Examples are given below.

Source: "ABA"
Dest: "BAB"
Output: True
Explanation: ABA -> A**C**A -> **B**C**B** -> B**A**B

Source: "AA"
Dest: "BC"
Output: False
Explanation: AA -> BB

I think HashMap works. But is there another Data Structure where I don't go about comparing Character by Character?

Body:
You can try this:

private static boolean test(String s1, String s2) {

    if(s1.length() != s2.length()) return false;

    Map<Character, Character> map = new HashMap<>();

    for (int i = 0; i < s1.length(); i++) {
        char c1 = s1.charAt(i);
        char c2 = s2.charAt(i);

        if (map.containsKey(c1)) {
            if (!map.get(c1).equals(c2)) {
                return false;
            }
        } else {
            map.put(c1, c2);
        }
    }
    return map.size() < 26;
}


问:
Get 24 Hour time format in datetime variable
I am using DateTime.TryParseExact function to get the datetime value in variable using following code

```<code> DateTime dt;
 CultureInfo provider = CultureInfo.InvariantCulture;
 System.Globalization.DateTimeStyles style = DateTimeStyles.None;
 string[] format = new string[] { "d/MMM/yy H:m:s tt","d-MMM-yy H:m:s tt" };
 string strDate = "24-May-13 12:03:03 AM";
 DateTime.TryParseExact(strDate, format, provider, style, out dt);
</code>```

Now what it does it parse the datetime correctly and give me result 24-May-2013 12:03:03
But i want it should return me like this 24-May-2013 00:03:033

How can i do this ?

答:
```<code>using System.Globalization;

//Your datetime variable value for example or you can get it from the database
//2019-05-31 03:00:00 PM
DateTime datetime = DateTime.ParseExact("2019-05-31 03:00:00 PM", "yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);

//2019-05-31 15:00:00
string _24HoursFormat = datetime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

//15:00:00
string _24HoursFormatTimeOnly = datetime.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
</code>```

Body:
I am using DateTime.TryParseExact function to get the datetime value in variable using following code

 DateTime dt;
 CultureInfo provider = CultureInfo.InvariantCulture;
 System.Globalization.DateTimeStyles style = DateTimeStyles.None;
 string[] format = new string[] { "d/MMM/yy H:m:s tt","d-MMM-yy H:m:s tt" };
 string strDate = "24-May-13 12:03:03 AM";
 DateTime.TryParseExact(strDate, format, provider, style, out dt);

Now what it does it parse the datetime correctly and give me result 24-May-2013 12:03:03
But i want it should return me like this 24-May-2013 00:03:033

How can i do this ?


问:
Find missing dates from a range of dates in MongoDB
I have a collection which contains a serviceDate field for a particular operation.
I need to find for a given date range is there any serviceDate which is missing and if it is found the return list of serviceDate dates missing between the range of date in MongoDB.
Sample JSON for my collection is as below.

```<code>{
    "_id" : ObjectId("5cefdb46bfbe1c0001f38413"),
    "category" : "RENT",
    "serviceDate" : ISODate("2019-06-15T05:30:00.000+05:30")
},

{
    "_id" : ObjectId("5cefdb46bfbe1c0001f38412"),
    "category" : "RENT",
    "serviceDate" : ISODate("2019-06-14T05:30:00.000+05:30")
},

{
    "_id" : ObjectId("5cefdb46bfbe1c0001f38411"),
    "category" : "RENT",
    "serviceDate" : ISODate("2019-06-13T05:30:00.000+05:30")
}
</code>```

Example:

Case 1:
If a collection has 10 documents and the serciceDate starting from 1-June-2019 to 10-June-2019.
In my Query I am passing 4-June-2019 to 7-June-2019 than result should be null.

Case 2:
If a collection has 9 documents and the serciceDate starting from 1-June-2019 to 10-June-2019, but 6-June-2019 is missing.
In my Query I am passing 4-June-2019 to 7-June-2019 than result should be 6-June-2019.

Case 3:
If a collection has 9 documents and the serciceDate starting from 1-June-2019 to 10-June-2019, but 6-June-2019, 5-June-2019 is missing.
In my Query I am passing 4-June-2019 to 7-June-2019 than result should be 6-June-2019 and 5-June-2019.

答:
You need to first find all the dates between the date range you pass in the query. Which you have to do with some javascript trick.

```<code>function getDates(startDate, stopDate) {
  var dateArray = []
  var currentDate = moment(startDate)
  var stopDate = moment(stopDate)
  while (currentDate <= stopDate) {
    dateArray.push(moment(currentDate).format('YYYY-MM-DD'))
    currentDate = moment(currentDate).add(1, 'days')
  }
  return dateArray
}

const dateArray = getDates(startDate, startDate)

//Output will be something like
dateArray = [ "2018-09-01", "2018-09-02", "2018-09-03", "2018-09-04", "2018-09-05" ]
</code>```

Now you you can use aggregation to find the $setDifference to get the non-existing serviceDates.

```<code>db.collection.aggregate([
  { '$match': {
    'serviceDate': { '$gte': startDate, '$lte': endDate }
  }},
  { '$group': {
    '_id': null,
    'dates': { '$push': { '$dateToString': { 'date': '$serviceDate', 'format': '%Y-%m-%d' }}}
  }},
  { '$project': {
    'missingDates': { '$setDifference': [dateArray, '$dates'] }
  }}
])
</code>```

Body:
I have a collection which contains a serviceDate field for a particular operation.
I need to find for a given date range is there any serviceDate which is missing and if it is found the return list of serviceDate dates missing between the range of date in MongoDB.
Sample JSON for my collection is as below.

{
    "_id" : ObjectId("5cefdb46bfbe1c0001f38413"),
    "category" : "RENT",
    "serviceDate" : ISODate("2019-06-15T05:30:00.000+05:30")
},

{
    "_id" : ObjectId("5cefdb46bfbe1c0001f38412"),
    "category" : "RENT",
    "serviceDate" : ISODate("2019-06-14T05:30:00.000+05:30")
},

{
    "_id" : ObjectId("5cefdb46bfbe1c0001f38411"),
    "category" : "RENT",
    "serviceDate" : ISODate("2019-06-13T05:30:00.000+05:30")
}

Example:

Case 1:
If a collection has 10 documents and the serciceDate starting from 1-June-2019 to 10-June-2019.
In my Query I am passing 4-June-2019 to 7-June-2019 than result should be null.

Case 2:
If a collection has 9 documents and the serciceDate starting from 1-June-2019 to 10-June-2019, but 6-June-2019 is missing.
In my Query I am passing 4-June-2019 to 7-June-2019 than result should be 6-June-2019.

Case 3:
If a collection has 9 documents and the serciceDate starting from 1-June-2019 to 10-June-2019, but 6-June-2019, 5-June-2019 is missing.
In my Query I am passing 4-June-2019 to 7-June-2019 than result should be 6-June-2019 and 5-June-2019.

Body:
You need to first find all the dates between the date range you pass in the query. Which you have to do with some javascript trick.

function getDates(startDate, stopDate) {
  var dateArray = []
  var currentDate = moment(startDate)
  var stopDate = moment(stopDate)
  while (currentDate <= stopDate) {
    dateArray.push(moment(currentDate).format('YYYY-MM-DD'))
    currentDate = moment(currentDate).add(1, 'days')
  }
  return dateArray
}

const dateArray = getDates(startDate, startDate)

//Output will be something like
dateArray = [ "2018-09-01", "2018-09-02", "2018-09-03", "2018-09-04", "2018-09-05" ]

Now you you can use aggregation to find the $setDifference to get the non-existing serviceDates.

db.collection.aggregate([
  { '$match': {
    'serviceDate': { '$gte': startDate, '$lte': endDate }
  }},
  { '$group': {
    '_id': null,
    'dates': { '$push': { '$dateToString': { 'date': '$serviceDate', 'format': '%Y-%m-%d' }}}
  }},
  { '$project': {
    'missingDates': { '$setDifference': [dateArray, '$dates'] }
  }}
])


问:
Search multiple columns and return top cell value
I have an INDEX formula that will take a value from the first cell in a row, search multiple columns of another sheet for a match and return the corresponding header row value when the match is found.

The problem is that I have to manually copy this formula down in order for it to apply to every row.  But more to the point, if I edit the formula or create new rows, I need to make sure I apply that edit to every row.  I would much rather have a single formula at the top of the column that applies to all cells below.

```<code>=INDEX(subTaskCategories!$C$1:$J$1,MAX(IF(subTaskCategories!$C$2:$J=A2,COLUMN(subTaskCategories!$C$2:$J)-COLUMN(A2)-1)))
</code>```

What is an alternative to INDEX that will search multiple columns and return the header when a match is found that can also be wrapped in an ARRAYFORMULA?

My sheet in subTaskData!C2

答:
paste in B2 cell:

```<code>=ARRAYFORMULA(IFERROR(VLOOKUP(REGEXEXTRACT(C2:C, "^~ (.*) ~$"),
 TRIM(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(
 QUERY(TRANSPOSE(IF(INDIRECT("taskCategories!C2:"&ADDRESS(ROWS(taskCategories!A1:A),
 COLUMNS(taskCategories!A1:AA1), 4))<>"", "♥"&INDIRECT("taskCategories!C2:"&
 ADDRESS(ROWS(taskCategories!A1:A), COLUMNS(taskCategories!A1:AA1), 4))&"♦"&
 INDIRECT("taskCategories!C1:"&ADDRESS(1, COLUMNS(taskCategories!A1:AA1), 4)), ))
 , , 999^99)), , 999^99), "♥")), "♦")), 2, 0)))
</code>```

paste in C2 cell:

```<code>=ARRAYFORMULA(IFERROR(VLOOKUP(A2:A, TRIM(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(
 QUERY(TRANSPOSE(IF(INDIRECT("subtaskCategories!C2:"&ADDRESS(ROWS(subTaskCategories!A1:A),
 COLUMNS(subTaskCategories!A1:AA1), 4))<>"", "♥"&INDIRECT("subtaskCategories!C2:"&
 ADDRESS(ROWS(subTaskCategories!A1:A), COLUMNS(subTaskCategories!A1:AA1), 4))&"♦"&
 INDIRECT("subtaskCategories!C1:"&ADDRESS(1, COLUMNS(subTaskCategories!A1:AA1), 4)), ))
 , , 999^99)), , 999^99), "♥")), "♦")), 2, 0)))
</code>```

Body:
I have an INDEX formula that will take a value from the first cell in a row, search multiple columns of another sheet for a match and return the corresponding header row value when the match is found.

The problem is that I have to manually copy this formula down in order for it to apply to every row.  But more to the point, if I edit the formula or create new rows, I need to make sure I apply that edit to every row.  I would much rather have a single formula at the top of the column that applies to all cells below.

=INDEX(subTaskCategories!$C$1:$J$1,MAX(IF(subTaskCategories!$C$2:$J=A2,COLUMN(subTaskCategories!$C$2:$J)-COLUMN(A2)-1)))

What is an alternative to INDEX that will search multiple columns and return the header when a match is found that can also be wrapped in an ARRAYFORMULA?

My sheet in subTaskData!C2

Body:
paste in B2 cell:

=ARRAYFORMULA(IFERROR(VLOOKUP(REGEXEXTRACT(C2:C, "^~ (.*) ~$"),
 TRIM(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(
 QUERY(TRANSPOSE(IF(INDIRECT("taskCategories!C2:"&ADDRESS(ROWS(taskCategories!A1:A),
 COLUMNS(taskCategories!A1:AA1), 4))<>"", "♥"&INDIRECT("taskCategories!C2:"&
 ADDRESS(ROWS(taskCategories!A1:A), COLUMNS(taskCategories!A1:AA1), 4))&"♦"&
 INDIRECT("taskCategories!C1:"&ADDRESS(1, COLUMNS(taskCategories!A1:AA1), 4)), ))
 , , 999^99)), , 999^99), "♥")), "♦")), 2, 0)))

paste in C2 cell:

=ARRAYFORMULA(IFERROR(VLOOKUP(A2:A, TRIM(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(
 QUERY(TRANSPOSE(IF(INDIRECT("subtaskCategories!C2:"&ADDRESS(ROWS(subTaskCategories!A1:A),
 COLUMNS(subTaskCategories!A1:AA1), 4))<>"", "♥"&INDIRECT("subtaskCategories!C2:"&
 ADDRESS(ROWS(subTaskCategories!A1:A), COLUMNS(subTaskCategories!A1:AA1), 4))&"♦"&
 INDIRECT("subtaskCategories!C1:"&ADDRESS(1, COLUMNS(subTaskCategories!A1:AA1), 4)), ))
 , , 999^99)), , 999^99), "♥")), "♦")), 2, 0)))


问:
How to use Python `secret` module to generate random integer?
In Python 3.6, new module, secrets, was added.

What is the most efficient way to generate random integer in range [n, m) using this module?

I tried choice(range(n, m)), but I doubt it is the best way.

答:
Not enough rep to comment but to add on to user2357112's answer if you run a quick execution time test they actually report basically identical.</p>

```<code>Best of 3 trials with 1,000,000 loops per trial:
        randrange() 1.39906 seconds total time.
        choice() 1.39431 seconds total time.
</code>```

Body:
Not enough rep to comment but to add on to user2357112's answer if you run a quick execution time test they actually report basically identical.

Best of 3 trials with 1,000,000 loops per trial:
        randrange() 1.39906 seconds total time.
        choice() 1.39431 seconds total time.


问:
How to split existing partitions
I have multiple partitions on my table as below.

Partition- Day_20190509 with high value of 20190510

Partition- Day_20190520 with high value of 20190521

Partition- Day_99999999 with MAXVALUE as high.

I want to create three new partitions for Day_20190510,Day_20190513,Day_20190514 with high values as 20190513,20190514,20190520 respectively.

I believe this can done using SPLIT partitions but could not understand how I can create partitions in between. Can someone assist with the query for this?

I tried using partition split option but could not understand what will be my range part and new partitions

```<code>ALTER TABLE table_name SPLIT PARTITION partition_name
  AT (range_part_value)
  INTO
  (
    PARTITION new_part1
      [TABLESPACE tablespace_name],
    PARTITION new_part2
      [TABLESPACE tablespace_name]
  );
</code>```

答:
Values you described as high values (20190513,20190514,20190520) in new partitions (Day_20190510,Day_20190513,Day_20190514) belong to the current partition: Day_20190520 (Value range: 20190511 - 20190521)

So current partition Day_20190520 must be split as follows:

```<code> ALTER TABLE table_name SPLIT PARTITION Day_20190520 INTO
  (PARTITION Day_20190510 VALUES LESS THAN (20190514), -- 20190513 + 1
   PARTITION Day_20190513 VALUES LESS THAN (20190515), -- 20190514 + 1
   PARTITION Day_20190514 VALUES LESS THAN (20190521), -- 20190520 + 1
   PARTITION Day_20190520_1);
</code>```

Hope this will solve your problem.

Title: How to split existing partitions

Body:
I have multiple partitions on my table as below.

Partition- Day_20190509 with high value of 20190510

Partition- Day_20190520 with high value of 20190521

Partition- Day_99999999 with MAXVALUE as high.

I want to create three new partitions for Day_20190510,Day_20190513,Day_20190514 with high values as 20190513,20190514,20190520 respectively.

I believe this can done using SPLIT partitions but could not understand how I can create partitions in between. Can someone assist with the query for this?

I tried using partition split option but could not understand what will be my range part and new partitions

ALTER TABLE table_name SPLIT PARTITION partition_name
  AT (range_part_value)
  INTO
  (
    PARTITION new_part1
      [TABLESPACE tablespace_name],
    PARTITION new_part2
      [TABLESPACE tablespace_name]
  );

Body:
Values you described as high values (20190513,20190514,20190520) in new partitions (Day_20190510,Day_20190513,Day_20190514) belong to the current partition: Day_20190520 (Value range: 20190511 - 20190521)

So current partition Day_20190520 must be split as follows:

 ALTER TABLE table_name SPLIT PARTITION Day_20190520 INTO
  (PARTITION Day_20190510 VALUES LESS THAN (20190514), -- 20190513 + 1
   PARTITION Day_20190513 VALUES LESS THAN (20190515), -- 20190514 + 1
   PARTITION Day_20190514 VALUES LESS THAN (20190521), -- 20190520 + 1
   PARTITION Day_20190520_1);

Hope this will solve your problem.


问:
Subtracting DataFrames by a single ID column - duplicate columns behave differently
I am trying to compare two DataFrames with the same schema (in Spark 1.6.0, using Scala) to determine which rows in the newer table have been added (i.e. are not present in the older table).

I need to do this by ID (i.e. examining a single column, not the whole row, to see what is new). Some rows may have changed between the versions, in that they have the same id in both versions, but the other columns have changed - I do not want these in the output, so I cannot simply subtract the two versions.

Based on various suggestions, I am doing a left-outer join on the chosen ID column, then selecting rows with nulls in columns from the right side of the join (indicating that they were not present in the older version of the table):

```<code>def diffBy(field:String, newer:DataFrame, older:DataFrame): DataFrame = {
  newer.join(older, newer(field) === older(field), "left_outer")
       .select(older(field).isNull)
       // TODO just select the leftmost columns, removing the nulls
}
</code>```

However, this does not work. (row 3 exists only in the newer version, so should be output):

```<code>scala> newer.show
+---+-------+
| id|  value|
+---+-------+
|  3|  three|
|  2|two-new|
+---+-------+

scala> older.show
+---+-------+
| id|  value|
+---+-------+
|  1|    one|
|  2|two-old|
+---+-------+

scala> diffBy("id", newer, older).show
+---+-----+---+-----+
| id|value| id|value|
+---+-----+---+-----+
+---+-----+---+-----+
</code>```

The join is working as expected:

```<code>scala> val joined = newer.join(older, newer("id") === older("id"), "left_outer")
scala> joined.show
+---+-------+----+-------+
| id|  value|  id|  value|
+---+-------+----+-------+
|  2|two-new|   2|two-old|
|  3|  three|null|   null|
+---+-------+----+-------+
</code>```

So the problem is in the selection of the column for filtering.

```<code>joined.where(older("id").isNull).show
+---+-----+---+-----+
| id|value| id|value|
+---+-----+---+-----+
+---+-----+---+-----+
</code>```

Perhaps it is due to the duplicate id column names in the join? But if I use the value column (which is also duplicated) instead to detect nulls, it works as expected:

```<code>joined.where(older("value").isNull).show
+---+-----+----+-----+
| id|value|  id|value|
+---+-----+----+-----+
|  3|three|null| null|
+---+-----+----+-----+
</code>```

What is going on here - and why is the behaviour different for id and value?

答:
You can solve the problem using a special spark join called "leftanti" . It is equivalent to minus (in Oracle PL SQL).

```<code>val joined = newer.join(older, newer("id") === older("id"), "leftanti")
</code>```

This will only select columns from newer.

Body:
I am trying to compare two DataFrames with the same schema (in Spark 1.6.0, using Scala) to determine which rows in the newer table have been added (i.e. are not present in the older table).

I need to do this by ID (i.e. examining a single column, not the whole row, to see what is new). Some rows may have changed between the versions, in that they have the same id in both versions, but the other columns have changed - I do not want these in the output, so I cannot simply subtract the two versions.

Based on various suggestions, I am doing a left-outer join on the chosen ID column, then selecting rows with nulls in columns from the right side of the join (indicating that they were not present in the older version of the table):

def diffBy(field:String, newer:DataFrame, older:DataFrame): DataFrame = {
  newer.join(older, newer(field) === older(field), "left_outer")
       .select(older(field).isNull)
       // TODO just select the leftmost columns, removing the nulls
}

However, this does not work. (row 3 exists only in the newer version, so should be output):

scala> newer.show
+---+-------+
| id|  value|
+---+-------+
|  3|  three|
|  2|two-new|
+---+-------+

scala> older.show
+---+-------+
| id|  value|
+---+-------+
|  1|    one|
|  2|two-old|
+---+-------+

scala> diffBy("id", newer, older).show
+---+-----+---+-----+
| id|value| id|value|
+---+-----+---+-----+
+---+-----+---+-----+

The join is working as expected:

scala> val joined = newer.join(older, newer("id") === older("id"), "left_outer")
scala> joined.show
+---+-------+----+-------+
| id|  value|  id|  value|
+---+-------+----+-------+
|  2|two-new|   2|two-old|
|  3|  three|null|   null|
+---+-------+----+-------+

So the problem is in the selection of the column for filtering.

joined.where(older("id").isNull).show
+---+-----+---+-----+
| id|value| id|value|
+---+-----+---+-----+
+---+-----+---+-----+

Perhaps it is due to the duplicate id column names in the join? But if I use the value column (which is also duplicated) instead to detect nulls, it works as expected:

joined.where(older("value").isNull).show
+---+-----+----+-----+
| id|value|  id|value|
+---+-----+----+-----+
|  3|three|null| null|
+---+-----+----+-----+

What is going on here - and why is the behaviour different for id and value?

Body:
You can solve the problem using a special spark join called "leftanti" . It is equivalent to minus (in Oracle PL SQL).

val joined = newer.join(older, newer("id") === older("id"), "leftanti")

This will only select columns from newer.