问:
How to call the jQuery module functions?
In this way, I want to understand JavaScript Module Pattern With jQuery.
I have a simple task for myself, There is one button and three jQuery functions, I want after clicking on the button, one function1 call another function2, and fucnction2 call function3 with an alert message.

My jQuery and html code.

$(document).ready(function() {
  $("#myBtn").click(function() {
    //How to add another two functions?
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type='text/javascript' src='alertScript.js'></script>
</head>

<body>
  <button type="button" class="btn btn-default btn-lg" id="myBtn">Push</button>
</body>

</html></code>```

Thanks for any advise.

答:
Try this:

$(document).ready(function() {
    $("#myBtn").click(function() {
        console.log('ok');
        fn1();
    });
});

function fn1(){
console.log("Fn 1 Called");
fn2();
}

function fn2(){
alert("Fn 2 Called");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<html>
<head>
</head>

<body>
    <button type="button" class="btn btn-default btn-lg" id="myBtn">Push</button>
</body>
</html></code>```

Body:
In this way, I want to understand JavaScript Module Pattern With jQuery.
I have a simple task for myself, There is one button and three jQuery functions, I want after clicking on the button, one function1 call another function2, and fucnction2 call function3 with an alert message.

My jQuery and html code.

$(document).ready(function() {
  $("#myBtn").click(function() {
    //How to add another two functions?
  });
});

  <button type="button" class="btn btn-default btn-lg" id="myBtn">Push</button>

Thanks for any advise.

Body:
Try this:

$(document).ready(function() {
    $("#myBtn").click(function() {
        console.log('ok');
        fn1();
    });
});

function fn1(){
console.log("Fn 1 Called");
fn2();
}

function fn2(){
alert("Fn 2 Called");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<html>
<head>
</head>

<body>
    <button type="button" class="btn btn-default btn-lg" id="myBtn">Push</button>
</body>
</html>


来源: stackexchange

问:
Android: Kotlin with Butterknife
I'm trying to use Kotlin with Butterknife for my Android Application.

Here is my build.gradle

```<code>dependencies {
    ...
    compile 'com.jakewharton:butterknife:8.0.1'
    kapt 'com.jakewharton:butterknife-compiler:8.0.1'
}

kapt {
    generateStubs = true
}
</code>```

I also has an EditText and I want to show a message using ButterKnife when it is changed:

```<code>@OnTextChanged(R.id.input)
fun test() {
   toast(1)
}
</code>```

However, nothing happens. I put a breakpoint into the function - and it is not even executed.

P.S: I have heard about kotterknife, however I have seen an example with pure Butterknife.

What am I doing wrong?

答:
In Kotlin, actually there is no need (or) necessity  for going ButterKnife concepts. because in your activity you can directly refer the view _id of the layout file as referred below.

layout.xml

```<code><Button
     android:id="@+id/btn_prestage"
     android:layout_width="20dp"
     android:layout_height="20dp"
     android:background="@drawable/prestaging_off"/>
</code>```

Activity.kt

```<code> btn_prestage.setBackgroundResource(R.drawable.staging_on)
 btn_prestage.setOnClickListener{ view ->
            Snackbar.make(view, "My Action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show() }
</code>```

build.gradle(app)

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
   dependencies {... }
}

kapt {
    generateStubs = true
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android: Kotlin with Butterknife

Body:
I'm trying to use Kotlin with Butterknife for my Android Application.

Here is my build.gradle

dependencies {
    ...
    compile 'com.jakewharton:butterknife:8.0.1'
    kapt 'com.jakewharton:butterknife-compiler:8.0.1'
}

kapt {
    generateStubs = true
}

I also has an EditText and I want to show a message using ButterKnife when it is changed:

@OnTextChanged(R.id.input)
fun test() {
   toast(1)
}

However, nothing happens. I put a breakpoint into the function - and it is not even executed.

P.S: I have heard about kotterknife, however I have seen an example with pure Butterknife.

What am I doing wrong?

Body:
In Kotlin, actually there is no need (or) necessity  for going ButterKnife concepts. because in your activity you can directly refer the view _id of the layout file as referred below.

layout.xml

<Button
     android:id="@+id/btn_prestage"
     android:layout_width="20dp"
     android:layout_height="20dp"
     android:background="@drawable/prestaging_off"/>

Activity.kt

 btn_prestage.setBackgroundResource(R.drawable.staging_on)
 btn_prestage.setOnClickListener{ view ->
            Snackbar.make(view, "My Action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show() }

build.gradle(app)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
   dependencies {... }
}

kapt {
    generateStubs = true
}


问:
Google Cloud auto-scaling thrashes between 0 and 1, even with minimum of 1
I have a managed instance group with auto scaling enabled. I have a minimum of 1 and maximum of 10 with health checks and cpu 0.8

The number of instances continually switches between 0 and 1. Every few minutes. I am unable to find the reason GCP decides to remove an instance and then immediately add it back. Health checks have no logs anywhere.

More concerning is that the minimum instances required is violated.

Thoughts? Thanks!

Edit: This may be due to instances becoming unhealthy, most likely because a firewall rule was needed to allow health checks on the instances. The health check worked for load balancing, but not instance health it seems. I'm using a custom network, so I needed to add the firewall rule.

https://cloud.google.com/compute/docs/load-balancing/health-checks#configure_a_firewall_rule_to_allow_health_checking

Will confirm/update after some monitoring time.

答:
Don't be confused between two different features: the autohealer and
the autoscaling of Managed Instance Groups.

The --min-num-replicas is a parameter of the autoscaler, setting this parameter you are sure that the target number of instances will never be set below a certain threshold. However the autohealing works on its own not following the configuration of the autoscaling.

Therefore when instances belong to a managed group and fail health checks, they are considered dead instances and removed from the pool if autohealing is enabled without taking into account the minimum number of replicas.

It is always best practise to verify that health checks are working properly in order to avoid this kind of misbehaviour. The common issues are:

Firewall rules

Wrong protocols/ports

Server not starting automatically at the powerup of the machine

Notice also that if the health checks are a bit more complex and interact with some kind of software you need to be sure that the instance is started before configuring accordingly initial delay flag, i.e. the length of the period during which the instance is known to be initializing and should not be autohealed even if unhealthy.


问:
How to find text field is readonly or not in jquery or javascript?
How can i find a box attr is readonly or not from jquery, Then only i can focus next text box.

```<code><input type="text" name="mrp1" id="mrp1" value="" readonly>
</code>```

Please give me a solution for this.

答:
In Javascript,

```<code>if(document.querySelector("#myText").readOnly) { // logic goes here }
</code>```

In Jquery,

```<code>if ( $('#mrp1').is('[readonly]') ) { // logic goes here }
</code>```

Body:
How can i find a box attr is readonly or not from jquery, Then only i can focus next text box.

<input type="text" name="mrp1" id="mrp1" value="" readonly>

Please give me a solution for this.

Body:
In Javascript,

if(document.querySelector("#myText").readOnly) { // logic goes here }

In Jquery,

if ( $('#mrp1').is('[readonly]') ) { // logic goes here }


问:
Can't bind to 'value' since it isn't a known property of 'p-dataTable'
I'm developing aspnetzero application with angular but when I'm assigning value of categories property in p-dataTable I'm getting this error in browser console:

Can't bind to 'value' since it isn't a known property of 'p-dataTable'

I have three files. First file categories.component.ts

```<code>    import { Component, Injector, OnInit } from '@angular/core';
    import { AppComponentBase } from '@shared/common/app-component-base';
    import { appModuleAnimation } from '@shared/animations/routerTransition';

    import { Http, Response, Headers, RequestOptions } from "@angular/http";
    import { AppSessionService } from '@shared/common/session/app-session.service';
    import { Category } from './category';
    import { DataTableModule, SharedModule, DataTable } from 'primeng/primeng';

    @Component({
        templateUrl: './categories.component.html',
        animations: [appModuleAnimation()]
    })
    export class CategoriesComponent extends AppComponentBase implements OnInit {

        categories: Category[];

        constructor(
            injector: Injector,
            private http: Http,
            private appSessionService: AppSessionService
        ) {
            super(injector);
        }

        ngOnInit(): void {
            this.getCategories();
        }

        getCategories(): void {

            let headers = new Headers({ 'Content-Type': 'application/json' })
            headers.append('tenantId', this.appSessionService.tenant ? this.appSessionService.tenant.id.toString() : '-1');
            let options = new RequestOptions({ headers: headers });
            this.http.get('/api/categories', options).subscribe(values => {
                this.categories = values.json();
            });
        }
    }
</code>```

Second categories.component.html

```<code>          <div [@routerTransition]>
           <div class="row margin-bottom-5">
              <div class="col-xs-12">
                  <div class="page-head">
                      <div class="page-title">
                          <h1>
                             <span>{{l("Categories")}}</span>
                         </h1>
                     </div>
                  </div>
              </div>
           </div>

        <div class="portlet light margin-bottom-0">
            <div class="portlet-body">
                <p-dataTable [value]="categories">
                    <p-column field="category.Name" header="Category"></p- column>
                </p-dataTable>
            </div>
        </div>
    </div>
</code>```

and Category class

```<code>    export class Category {
        constructor(
            public id: number,
            public name: string) { }
    }
</code>```

This is app.module.ts

```<code>import { NgModule } from '@angular/core';
import * as ngCommon from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { ModalModule, TooltipModule, TabsModule } from 'ngx-bootstrap';
import { FileUploadModule } from '@node_modules/ng2-file-upload';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './shared/layout/header.component';
import { HeaderNotificationsComponent } from './shared/layout/notifications/header-notifications.component';
import { SideBarComponent } from './shared/layout/side-bar.component';
import { FooterComponent } from './shared/layout/footer.component';
import { LoginAttemptsModalComponent } from '@app/shared/layout/login-attempts-modal.component';
import { ChangePasswordModalComponent } from '@app/shared/layout/profile/change-password-modal.component';
import { ChangeProfilePictureModalComponent } from '@app/shared/layout/profile/change-profile-picture-modal.component';
import { MySettingsModalComponent } from '@app/shared/layout/profile/my-settings-modal.component';
import { SmsVerificationModalComponent } from '@app/shared/layout/profile/sms-verification-modal.component';
import { AbpModule } from '@abp/abp.module';
import { UtilsModule } from '@shared/utils/utils.module';
import { AppCommonModule } from './shared/common/app-common.module';
import { ServiceProxyModule } from '@shared/service-proxies/service-proxy.module';
import { ImpersonationService } from './admin/users/impersonation.service';
import { LinkedAccountService } from './shared/layout/linked-account.service';
import { LinkedAccountsModalComponent } from '@app/shared/layout/linked-accounts-modal.component';
import { LinkAccountModalComponent } from '@app/shared/layout/link-account-modal.component';
import { NotificationsComponent } from './shared/layout/notifications/notifications.component';
import { NotificationSettingsModalCompoent } from './shared/layout/notifications/notification-settings-modal.component';
import { UserNotificationHelper } from './shared/layout/notifications/UserNotificationHelper';
import { ChatBarComponent } from './shared/layout/chat/chat-bar.component';
import { ChatFriendListItem } from './shared/layout/chat/chat-friend-list-item.component';
import { ChatSignalrService } from '@app/shared/layout/chat/chat-signalr.service';
import { QuickSideBarChat } from '@app/shared/layout/chat/QuickSideBarChat';
import { DataTableModule } from 'primeng/primeng';
import { PaginatorModule } from 'primeng/primeng';

@NgModule({
    declarations: [
        AppComponent,
        HeaderComponent,
        HeaderNotificationsComponent,
        SideBarComponent,
        FooterComponent,
        LoginAttemptsModalComponent,
        LinkedAccountsModalComponent,
        LinkAccountModalComponent,
        ChangePasswordModalComponent,
        ChangeProfilePictureModalComponent,
        MySettingsModalComponent,
        SmsVerificationModalComponent,
        NotificationsComponent,
        ChatBarComponent,
        ChatFriendListItem,
        NotificationSettingsModalCompoent
    ],
    imports: [
        ngCommon.CommonModule,
        FormsModule,
        HttpModule,
        JsonpModule,
        ModalModule.forRoot(),
        TooltipModule.forRoot(),
        TabsModule.forRoot(),
        FileUploadModule,
        AbpModule,
        AppRoutingModule,
        UtilsModule,
        AppCommonModule.forRoot(),
        ServiceProxyModule,
        DataTableModule,
        PaginatorModule
    ],
    providers: [
        ImpersonationService,
        LinkedAccountService,
        UserNotificationHelper,
        ChatSignalrService,
        QuickSideBarChat
    ]
})
export class AppModule { }
</code>```

答:
I have fixed this error. In aspnnetzero there are two files where it needs to import DataTable. I had to import DataTable in app/main/main.module.ts.

main.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DashboardComponent } from './dashboard/dashboard.component';
import { CategoriesComponent } from './categories/categories.component';
import { CreateOrEditCagoryModalComponent } from './categories/create-or-edit-category-modal.component';

import { ModalModule, TabsModule, TooltipModule } from 'ngx-bootstrap';
import { AppCommonModule } from '@app/shared/common/app-common.module';
import { UtilsModule } from '@shared/utils/utils.module';
import { MainRoutingModule } from './main-routing.module';
import { CountoModule } from '@node_modules/angular2-counto';
import { EasyPieChartModule } from 'ng2modules-easypiechart';
import { DataTableModule } from 'primeng/primeng'; // Here
import { PaginatorModule } from 'primeng/primeng'; // Here

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        ModalModule,
        TabsModule,
        TooltipModule,
        AppCommonModule,
        UtilsModule,
        MainRoutingModule,
        CountoModule,
        EasyPieChartModule,
        DataTableModule, // Added DataTableModule
        PaginatorModule //  Added PaginatorModule

    ],
    declarations: [
        DashboardComponent,
        CategoriesComponent,
        CreateOrEditCagoryModalComponent
    ]
})
export class MainModule { }
</code>```

Body:
I'm developing aspnetzero application with angular but when I'm assigning value of categories property in p-dataTable I'm getting this error in browser console:

Can't bind to 'value' since it isn't a known property of 'p-dataTable'

I have three files. First file categories.component.ts

    import { Component, Injector, OnInit } from '@angular/core';
    import { AppComponentBase } from '@shared/common/app-component-base';
    import { appModuleAnimation } from '@shared/animations/routerTransition';

    import { Http, Response, Headers, RequestOptions } from "@angular/http";
    import { AppSessionService } from '@shared/common/session/app-session.service';
    import { Category } from './category';
    import { DataTableModule, SharedModule, DataTable } from 'primeng/primeng';

    @Component({
        templateUrl: './categories.component.html',
        animations: [appModuleAnimation()]
    })
    export class CategoriesComponent extends AppComponentBase implements OnInit {

        categories: Category[];

        constructor(
            injector: Injector,
            private http: Http,
            private appSessionService: AppSessionService
        ) {
            super(injector);
        }

        ngOnInit(): void {
            this.getCategories();
        }

        getCategories(): void {

            let headers = new Headers({ 'Content-Type': 'application/json' })
            headers.append('tenantId', this.appSessionService.tenant ? this.appSessionService.tenant.id.toString() : '-1');
            let options = new RequestOptions({ headers: headers });
            this.http.get('/api/categories', options).subscribe(values => {
                this.categories = values.json();
            });
        }
    }

Second categories.component.html

                             {{l("Categories")}}

and Category class

    export class Category {
        constructor(
            public id: number,
            public name: string) { }
    }

This is app.module.ts

import { NgModule } from '@angular/core';
import * as ngCommon from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { ModalModule, TooltipModule, TabsModule } from 'ngx-bootstrap';
import { FileUploadModule } from '@node_modules/ng2-file-upload';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './shared/layout/header.component';
import { HeaderNotificationsComponent } from './shared/layout/notifications/header-notifications.component';
import { SideBarComponent } from './shared/layout/side-bar.component';
import { FooterComponent } from './shared/layout/footer.component';
import { LoginAttemptsModalComponent } from '@app/shared/layout/login-attempts-modal.component';
import { ChangePasswordModalComponent } from '@app/shared/layout/profile/change-password-modal.component';
import { ChangeProfilePictureModalComponent } from '@app/shared/layout/profile/change-profile-picture-modal.component';
import { MySettingsModalComponent } from '@app/shared/layout/profile/my-settings-modal.component';
import { SmsVerificationModalComponent } from '@app/shared/layout/profile/sms-verification-modal.component';
import { AbpModule } from '@abp/abp.module';
import { UtilsModule } from '@shared/utils/utils.module';
import { AppCommonModule } from './shared/common/app-common.module';
import { ServiceProxyModule } from '@shared/service-proxies/service-proxy.module';
import { ImpersonationService } from './admin/users/impersonation.service';
import { LinkedAccountService } from './shared/layout/linked-account.service';
import { LinkedAccountsModalComponent } from '@app/shared/layout/linked-accounts-modal.component';
import { LinkAccountModalComponent } from '@app/shared/layout/link-account-modal.component';
import { NotificationsComponent } from './shared/layout/notifications/notifications.component';
import { NotificationSettingsModalCompoent } from './shared/layout/notifications/notification-settings-modal.component';
import { UserNotificationHelper } from './shared/layout/notifications/UserNotificationHelper';
import { ChatBarComponent } from './shared/layout/chat/chat-bar.component';
import { ChatFriendListItem } from './shared/layout/chat/chat-friend-list-item.component';
import { ChatSignalrService } from '@app/shared/layout/chat/chat-signalr.service';
import { QuickSideBarChat } from '@app/shared/layout/chat/QuickSideBarChat';
import { DataTableModule } from 'primeng/primeng';
import { PaginatorModule } from 'primeng/primeng';

@NgModule({
    declarations: [
        AppComponent,
        HeaderComponent,
        HeaderNotificationsComponent,
        SideBarComponent,
        FooterComponent,
        LoginAttemptsModalComponent,
        LinkedAccountsModalComponent,
        LinkAccountModalComponent,
        ChangePasswordModalComponent,
        ChangeProfilePictureModalComponent,
        MySettingsModalComponent,
        SmsVerificationModalComponent,
        NotificationsComponent,
        ChatBarComponent,
        ChatFriendListItem,
        NotificationSettingsModalCompoent
    ],
    imports: [
        ngCommon.CommonModule,
        FormsModule,
        HttpModule,
        JsonpModule,
        ModalModule.forRoot(),
        TooltipModule.forRoot(),
        TabsModule.forRoot(),
        FileUploadModule,
        AbpModule,
        AppRoutingModule,
        UtilsModule,
        AppCommonModule.forRoot(),
        ServiceProxyModule,
        DataTableModule,
        PaginatorModule
    ],
    providers: [
        ImpersonationService,
        LinkedAccountService,
        UserNotificationHelper,
        ChatSignalrService,
        QuickSideBarChat
    ]
})
export class AppModule { }

Body:
I have fixed this error. In aspnnetzero there are two files where it needs to import DataTable. I had to import DataTable in app/main/main.module.ts.

main.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DashboardComponent } from './dashboard/dashboard.component';
import { CategoriesComponent } from './categories/categories.component';
import { CreateOrEditCagoryModalComponent } from './categories/create-or-edit-category-modal.component';

import { ModalModule, TabsModule, TooltipModule } from 'ngx-bootstrap';
import { AppCommonModule } from '@app/shared/common/app-common.module';
import { UtilsModule } from '@shared/utils/utils.module';
import { MainRoutingModule } from './main-routing.module';
import { CountoModule } from '@node_modules/angular2-counto';
import { EasyPieChartModule } from 'ng2modules-easypiechart';
import { DataTableModule } from 'primeng/primeng'; // Here
import { PaginatorModule } from 'primeng/primeng'; // Here

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        ModalModule,
        TabsModule,
        TooltipModule,
        AppCommonModule,
        UtilsModule,
        MainRoutingModule,
        CountoModule,
        EasyPieChartModule,
        DataTableModule, // Added DataTableModule
        PaginatorModule //  Added PaginatorModule

    ],
    declarations: [
        DashboardComponent,
        CategoriesComponent,
        CreateOrEditCagoryModalComponent
    ]
})
export class MainModule { }


问:
Ionic 2 dev and prod environment variables
I am working on Ionic 2 project and I want to configure it for a different environment like Development and Production. But, I have no idea where to put config files in ionic 2. Are there any ways to put config file and run commands

like

```<code>ionic build android --prod
</code>```

and

```<code>ionic build android --dev
</code>```

答:
Webpack plugin can be used webpack-environment-suffix-plugin to setup several environments for ionic.

Install plugin

npm install webpack-environment-suffix-plugin --save

Create your own webpack.config.js file.

```<code>const webpackConfig = require('@ionic/app-scripts/config/webpack.config');
const EnvironmentSuffixPlugin = require('webpack-environment-suffix-plugin');

const ionicEnv = ['prod', 'dev'];

const addPluginToWebpackConfig = (config, env) => {
  const plugins = config[env].plugins || [];

  config[env].plugins = [
    ...plugins,
    new EnvironmentSuffixPlugin({
      ext: 'ts',
      suffix: process.env.NODE_ENV || 'dev'
    })
  ];

  return config;
};

module.exports = () => ionicEnv.reduce(addPluginToWebpackConfig, webpackConfig);
</code>```

Update package.json

```<code>"scripts": {
    //...
    "build": "<you build script>",
    "build:prod": "NODE_ENV=\"prod\" npm run build",
    "build:dev": "NODE_ENV=\"dev\" npm run build",
    "build:test": "NODE_ENV=\"qa\" npm run build
    //...
},
"config": {
   // path to a new webpack config file.
   "ionic_webpack": "./webpack.config.js"
}
</code>```

Body:
I am working on Ionic 2 project and I want to configure it for a different environment like Development and Production. But, I have no idea where to put config files in ionic 2. Are there any ways to put config file and run commands

like

ionic build android --prod

and

ionic build android --dev

Body:
Webpack plugin can be used webpack-environment-suffix-plugin to setup several environments for ionic.

Install plugin

npm install webpack-environment-suffix-plugin --save

Create your own webpack.config.js file.

const webpackConfig = require('@ionic/app-scripts/config/webpack.config');
const EnvironmentSuffixPlugin = require('webpack-environment-suffix-plugin');

const ionicEnv = ['prod', 'dev'];

const addPluginToWebpackConfig = (config, env) => {
  const plugins = config[env].plugins || [];

  config[env].plugins = [
    ...plugins,
    new EnvironmentSuffixPlugin({
      ext: 'ts',
      suffix: process.env.NODE_ENV || 'dev'
    })
  ];

  return config;
};

module.exports = () => ionicEnv.reduce(addPluginToWebpackConfig, webpackConfig);

Update package.json

"scripts": {
    //...
    "build": "<you build script>",
    "build:prod": "NODE_ENV=\"prod\" npm run build",
    "build:dev": "NODE_ENV=\"dev\" npm run build",
    "build:test": "NODE_ENV=\"qa\" npm run build
    //...
},
"config": {
   // path to a new webpack config file.
   "ionic_webpack": "./webpack.config.js"
}


问:
How do I get items from an RSS feed using .Net Core?
How do I get items from an RSS feed using .Net Core?

The following code doesn't appear to work:

```<code>open Microsoft.SyndicationFeed
open Microsoft.SyndicationFeed.Rss

[<Test>]
let ``Get links from iTunes RSS Feed`` () =

    let url = "http://www.pwop.com/feed.aspx?show=dotnetrocks&filetype=master&tags=F%23"
    use reader = XmlReader.Create(url)
    let feedReader = RssFeedReader(reader)

    let mutable linkTemplate = {
        Title=         ""
        Url=           ""
    }

    let links =

        async {

            let links = Collections.Generic.List<Link>()

            while feedReader.Read() |> Async.AwaitTask |> Async.RunSynchronously do

                match feedReader.ElementType with
                | SyndicationElementType.Link ->
                    let item = feedReader.ReadLink() |> Async.AwaitTask |> Async.RunSynchronously
                    let link = { linkTemplate with Title= item.Title; Url= item.Uri.AbsolutePath }
                    links.Add(link)
                | _ -> ()

            return links

        } |> Async.RunSynchronously

    reader.Close()

    System.Diagnostics.Debug.WriteLine(links.[0].Title)

    links.[0].Title |> should not' (equal "")
</code>```

Specifically, items are read but there's no actual data after the read.

答:
I used the XElement class as recommended:</p>

```<code>[<Test>]
let ``Get links from iTunes RSS Feed`` () =

    let toLink (item:XElement) = {
        Id =          -1
        ProfileId =   "to be derived..."
        Title=        item.Element(XName.Get("title")) |> string
        Url=          item.Element(XName.Get("link"))  |> string
        Description = item.Element(XName.Get("description")) |> string
        ContentType=  Podcast |> contentTypeToString
        Topics =      []
        IsFeatured=   false
     }

    let baseAddress = "http://www.pwop.com/"
    let url = "feed.aspx?show=dotnetrocks&filetype=master&tags=F%23"
    use client = httpClient baseAddress

    let response = client.GetAsync(url) |> Async.AwaitTask
                                        |> Async.RunSynchronously
    let links =
        if response.IsSuccessStatusCode
           then let text = response.Content.ReadAsStringAsync()     |> Async.AwaitTask |> Async.RunSynchronously
                XElement.Parse(text).Descendants(XName.Get("item")) |> Seq.toList      |> List.map toLink
           else []

    links |> List.isEmpty |> should equal false
</code>```

Body:
How do I get items from an RSS feed using .Net Core?

The following code doesn't appear to work:

open Microsoft.SyndicationFeed
open Microsoft.SyndicationFeed.Rss

[<Test>]
let ``Get links from iTunes RSS Feed`` () =

    let url = "http://www.pwop.com/feed.aspx?show=dotnetrocks&filetype=master&tags=F%23"
    use reader = XmlReader.Create(url)
    let feedReader = RssFeedReader(reader)

    let mutable linkTemplate = {
        Title=         ""
        Url=           ""
    }

    let links =

        async {

            let links = Collections.Generic.List<Link>()

            while feedReader.Read() |> Async.AwaitTask |> Async.RunSynchronously do

                match feedReader.ElementType with
                | SyndicationElementType.Link ->
                    let item = feedReader.ReadLink() |> Async.AwaitTask |> Async.RunSynchronously
                    let link = { linkTemplate with Title= item.Title; Url= item.Uri.AbsolutePath }
                    links.Add(link)
                | _ -> ()

            return links

        } |> Async.RunSynchronously

    reader.Close()

    System.Diagnostics.Debug.WriteLine(links.[0].Title)

    links.[0].Title |> should not' (equal "")

Specifically, items are read but there's no actual data after the read.

Body:
I used the XElement class as recommended:

[<Test>]
let ``Get links from iTunes RSS Feed`` () =

    let toLink (item:XElement) = {
        Id =          -1
        ProfileId =   "to be derived..."
        Title=        item.Element(XName.Get("title")) |> string
        Url=          item.Element(XName.Get("link"))  |> string
        Description = item.Element(XName.Get("description")) |> string
        ContentType=  Podcast |> contentTypeToString
        Topics =      []
        IsFeatured=   false
     }

    let baseAddress = "http://www.pwop.com/"
    let url = "feed.aspx?show=dotnetrocks&filetype=master&tags=F%23"
    use client = httpClient baseAddress

    let response = client.GetAsync(url) |> Async.AwaitTask
                                        |> Async.RunSynchronously
    let links =
        if response.IsSuccessStatusCode
           then let text = response.Content.ReadAsStringAsync()     |> Async.AwaitTask |> Async.RunSynchronously
                XElement.Parse(text).Descendants(XName.Get("item")) |> Seq.toList      |> List.map toLink
           else []

    links |> List.isEmpty |> should equal false


问:
Are these 2 statements the same?
Do these 2 statements mean the same thing?

```<code>if ($host eq '') {
    print "Host exists\n";
}
</code>```

And

```<code>if (defined $host) {
    print "Host exists\n";
}
</code>```

答:
Even if you changed the first to:

```<code>if ($host ne '') ...
</code>```

the two statements are not equivalent, as you'd see if you ran with warnings enabled and left $host undefined.

```<code>$ perl -we 'my $host; print $host ne "" ? "Hi\n" : "Lo\n";'
Use of uninitialized value $host in string ne at -e line 1.
Lo
$ perl -we 'my $host; print defined $host ? "Hi\n" : "Lo\n";'
Lo
$ perl -we 'my $host = ""; print defined $host ? "Hi\n" : "Lo\n";'
Hi
$ perl -we 'my $host = ""; print $host ne "" ? "Hi\n" : "Lo\n";'
Lo
$
</code>```

Note that one of the answers is "Hi".  The empty string is a fine value; it is not the same as undef.

ContentLicense: CC BY-SA 2.5

Title: Are these 2 statements the same?

Body:
Do these 2 statements mean the same thing?

if ($host eq '') {
    print "Host exists\n";
}

And

if (defined $host) {
    print "Host exists\n";
}

Body:
Even if you changed the first to:

if ($host ne '') ...

the two statements are not equivalent, as you'd see if you ran with warnings enabled and left $host undefined.

$ perl -we 'my $host; print $host ne "" ? "Hi\n" : "Lo\n";'
Use of uninitialized value $host in string ne at -e line 1.
Lo
$ perl -we 'my $host; print defined $host ? "Hi\n" : "Lo\n";'
Lo
$ perl -we 'my $host = ""; print defined $host ? "Hi\n" : "Lo\n";'
Hi
$ perl -we 'my $host = ""; print $host ne "" ? "Hi\n" : "Lo\n";'
Lo
$

Note that one of the answers is "Hi".  The empty string is a fine value; it is not the same as undef.


问:
Insert a Node at a Specific Position in a Linked List
I need to insert a note at position. I didn't get any error but my answer is wrong. Could you please help me to correct my code?
 Link to question</p>

```<code>Node InsertNth(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;
 if (head == null){
        return node;
    } else {
    Node current = head;
    for (int i=0; i < position-1 ; i++){
        current = current.next;
    }

    node.next = current.next;
    current.next = node;
 return head;
}

}
</code>```

答:
Using a dummy node that points to the head can help reduce many of the check:

```<code>Node insertNth(Node head, int data, int position) {
    Node dummy = new Node();
    dummy.next = head;

    Node runner = dummy;
    for (int i = 0; i < position; ++i) {
        runner = runner.next;
    }

    Node node = new Node();
    node.data = data;
    node.next = runner.next;
    runner.next = node;

    return dummy.next;
}
</code>```

Naturally, a recursive solution is also possible:

```<code>Node insertNthRecursive(Node head, int data, int position) {
    if (position == 0) {
        Node node = new Node();
        node.data = data;
        node.next = head;
        return node;
    }
    head.next = insertNthRecursive(head.next, data, position - 1);
    return head;
}
</code>```

Body:
I need to insert a note at position. I didn't get any error but my answer is wrong. Could you please help me to correct my code?
 Link to question

Node InsertNth(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;
 if (head == null){
        return node;
    } else {
    Node current = head;
    for (int i=0; i < position-1 ; i++){
        current = current.next;
    }

    node.next = current.next;
    current.next = node;
 return head;
}

}

Body:
Using a dummy node that points to the head can help reduce many of the check:

Node insertNth(Node head, int data, int position) {
    Node dummy = new Node();
    dummy.next = head;

    Node runner = dummy;
    for (int i = 0; i < position; ++i) {
        runner = runner.next;
    }

    Node node = new Node();
    node.data = data;
    node.next = runner.next;
    runner.next = node;

    return dummy.next;
}

Naturally, a recursive solution is also possible:

Node insertNthRecursive(Node head, int data, int position) {
    if (position == 0) {
        Node node = new Node();
        node.data = data;
        node.next = head;
        return node;
    }
    head.next = insertNthRecursive(head.next, data, position - 1);
    return head;
}


问:
Article summarization in wikipedia
Wikipedia provides article summaries for most articles when using its search feature (see screenshot below). I have looked at various articles and couldn't find the text in the original article; neither in the rendered page nor in the metadata inside the Edit section.

Now, I have two questions:

How does Wikipedia show these summarizations? Are these precurated texts entered by the community or is there any underlying ML algorithm to summarize articles? In the case of the former, can you point me to the location where these data are sourced? In case of the latter, has the algorithm been open-sourced?

Does Wikipedia API support retrieving these summaries for a given article?

答: The short descriptions you're looking at are Wikidata descriptions. There are also available as a description property in the REST API summary endpoint response along with a more verbose extract, the image for the page and a bunch of there info.

Title: Article summarization in wikipedia


问:
how to use json-sql with postgresql?
I'm trying to use json-sql npm module with postgres.
But I was not able to even do select.

I think, the problem is that query from json-sql contains $p1 instead $1.
What I need to tune to be able to get postgres-like query from json-sql?

I tried to use { dialect : 'postgresql' } configuration option but still I have a problem.

As a result of code below:

```<code>let userCompSql = jsonSql.build({
    type: 'select',
    fields: ['id'],
    table: 'user_computers',
    condition: {
        'os_name' : params.osName,
        'os_minor' : params.osVersionMinor
   }})
</code>```

I get a string userCompSql: "select "id" from "user_computers" where "os_name" = $p1 and "os_minor" = 0;"
But I would like to have $1 instead of $p1 for my postgresql DB.

答: That was so easy. Just configure { namedValues: false }...</p>

Title: how to use json-sql with postgresql?

Body:
I'm trying to use json-sql npm module with postgres.
But I was not able to even do select.

I think, the problem is that query from json-sql contains $p1 instead $1.
What I need to tune to be able to get postgres-like query from json-sql?

I tried to use { dialect : 'postgresql' } configuration option but still I have a problem.

As a result of code below:

let userCompSql = jsonSql.build({
    type: 'select',
    fields: ['id'],
    table: 'user_computers',
    condition: {
        'os_name' : params.osName,
        'os_minor' : params.osVersionMinor
   }})

I get a string userCompSql: "select "id" from "user_computers" where "os_name" = $p1 and "os_minor" = 0;"
But I would like to have $1 instead of $p1 for my postgresql DB.


问:
Use maven profile properties in application.conf
In my pom.xml file, I have multiple profiles set up. I would like to use the current profile's values in my application.conf file. The Ninja Framework documentation only mentions mode configurations, however I can't find anything concerning profile configurations.

An example: The documentation mentions

```<code>database.name=database_production   # will be used when no mode is set (or prod)
%prod.database.name=database_prod   # will be used when running in prod mode
%dev.database.name=database_dev     # will be used when running in dev mode
%test.database.name=database_test   # will be used when running in test mode
</code>```

How would I be able to set different database names depending on the currently used profile?

答:
You could add whatever it is you want replaced as a property to your profile definition, and then enable maven resource filtering like this:

```<code><build>
  ..
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
  ..
</build>
<profiles>
  <profile>
    <id>developmentProfile</id>
    <properties>
      <dbName>database.name=database_dev</dbName>
    </properties>
    <activation>
      <activeByDefault>false</activeByDefault>
    </activation>
  </profile>
  <profile>
    <id>productionProfile</id>
    <properties>
      <dbName>database.name=database_prod</dbName>
    </properties>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
  </profile>
</profiles>
</code>```

Be careful, if you use spring-boot, you should reference the properties in the application.properties file like this for it to work:

```<code>someOtherProp = something
@dbName@
</code>```

After that, building the app should filter the property correctly:

```<code>mvn clean install -PdevelopmentProfile
</code>```

Result:

```<code>someOtherProp=something
database.name=database_dev
</code>```

Body:
In my pom.xml file, I have multiple profiles set up. I would like to use the current profile's values in my application.conf file. The Ninja Framework documentation only mentions mode configurations, however I can't find anything concerning profile configurations.

An example: The documentation mentions

database.name=database_production   # will be used when no mode is set (or prod)
%prod.database.name=database_prod   # will be used when running in prod mode
%dev.database.name=database_dev     # will be used when running in dev mode
%test.database.name=database_test   # will be used when running in test mode

How would I be able to set different database names depending on the currently used profile?

Body:
You could add whatever it is you want replaced as a property to your profile definition, and then enable maven resource filtering like this:

<build>
  ..
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
  ..
</build>
<profiles>
  <profile>
    <id>developmentProfile</id>
    <properties>
      <dbName>database.name=database_dev</dbName>
    </properties>
    <activation>
      <activeByDefault>false</activeByDefault>
    </activation>
  </profile>
  <profile>
    <id>productionProfile</id>
    <properties>
      <dbName>database.name=database_prod</dbName>
    </properties>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
  </profile>
</profiles>

Be careful, if you use spring-boot, you should reference the properties in the application.properties file like this for it to work:

someOtherProp = something
@dbName@

After that, building the app should filter the property correctly:

mvn clean install -PdevelopmentProfile

Result:

someOtherProp=something
database.name=database_dev


问:
Validation of a date with Hibernate
We have an existing hotel management system. I was asked to add a date validation in the "Create Accommodation" function in the system. The dialog looks like this:

The "End Date" is already validated as shown in the code below. The @Future annotation in Hibernate ensures that the date is in the future.

```<code>@NotNull
@Future
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date endDate;
</code>```

EDIT

I was asked to add a validation to the "Start date". Only the present or a future date is allowed. I tried to use a @Present annotation, but I guess there is no such thing. Unfortunately, @Future does not accept today's date. I am new to this kind of thing. So I hope someone can help me. Thank you.

答:
Now, in the updated new validator version i.e.

```<code><dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.4.Final</version>
</dependency>
</code>```

via

```<code><dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.0.Final</version>
</dependency>
</code>```

we have @FutureOrPresent and many other helpful annotations that you can use.

Title: Validation of a date with Hibernate

Body:
We have an existing hotel management system. I was asked to add a date validation in the "Create Accommodation" function in the system. The dialog looks like this:

The "End Date" is already validated as shown in the code below. The @Future annotation in Hibernate ensures that the date is in the future.

@NotNull
@Future
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date endDate;

EDIT

I was asked to add a validation to the "Start date". Only the present or a future date is allowed. I tried to use a @Present annotation, but I guess there is no such thing. Unfortunately, @Future does not accept today's date. I am new to this kind of thing. So I hope someone can help me. Thank you.

Body:
Now, in the updated new validator version i.e.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.4.Final</version>
</dependency>

via

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.0.Final</version>
</dependency>

we have @FutureOrPresent and many other helpful annotations that you can use.


问:
Creating Solr schema based on a class using SolrJ
On application startup I want to check if schema exists and:
1) if it doesn't -> create schema from Java class containing fields
2) if it differs for aforementioned class -> update the schema
3) if schema maps 1:1 with fields in Java class then do nothing

I've divided my task into 3 subtask and my first one would be to create a schema from existing Java class.

Here is my class (getters and setters omitted):

```<code>public class Order {
private String name;
private String phone;
private Address address;

private List<Amenities> amenities;
private BigDecimal distance;
private String image;
private List<Attributes> attributes;
private List<String> networks;
private OrderType orderType;
private Service service;
}
</code>```

As you can see it has quite many field types which also should be used to create a schema (recursively?). Is it even possible to create a schema like that?

答:
It should be quite simple to do:

First, you need to list all fields of the class, it could be achieved via reflection. After it, you should use Schema API, which will allow you to do CRUD operation on the fields for schema.

/schema/fields will allow you to get all fields, and then you could use replace-field for updating field, delete-field to a deletion of field and add-field for adding field. For more information just check this documentation.

Caveat: Schema API was added starting from Solr 5.3

Body:
On application startup I want to check if schema exists and:
1) if it doesn't -> create schema from Java class containing fields
2) if it differs for aforementioned class -> update the schema
3) if schema maps 1:1 with fields in Java class then do nothing

I've divided my task into 3 subtask and my first one would be to create a schema from existing Java class.

Here is my class (getters and setters omitted):

public class Order {
private String name;
private String phone;
private Address address;

private List<Amenities> amenities;
private BigDecimal distance;
private String image;
private List<Attributes> attributes;
private List<String> networks;
private OrderType orderType;
private Service service;
}

As you can see it has quite many field types which also should be used to create a schema (recursively?). Is it even possible to create a schema like that?


问:
Data Validation
So I have entered my second semester of College and they have me doing a course called Advanced COBOL. As one of my assignments I have to my make a program that tests certain things in a file to make sure the input has no errors. I get the general idea but there are just a few things I don't understand and my teacher is one of those people who will give you an assignment and make you figure it out yourself with little or no help. So here is what I need help with.

I have a field that the first 5 columns have to be numbers, the 6th column a capital letter and the last 2 numbers in a range of 01-68 or 78-99.

one of my fields has to be a string of numbers with a dash in it like 00000-000, but some have more than one dash. How can I count the dashes to identify that there is a problem.

答:
Here are a few hints...

Use a hieratical record structure to view the data in different ways. For example:

```<code> 01 ITEM-REC.
    05 ITEM-CODE.
       10 ITEM-NUM-CODE    PIC 9(3).
       10 ITEM-CHAR-CODE   PIC A(3).
          88 ITEM-TYPE-A   VALUE 'AAA' THRU 'AZZ'.
          88 ITEM-TYPE-B   VALUE 'BAA' THRU 'BZZ'.
    05 QUANTITY            PIC 9(4).
</code>```

ITEM-CODE is a 6 character group field, the first part of which is numeric (ITEM-NUM-CODE) and the last part
is alphabetic (ITEM-CHAR-CODE). You can refer to any one of these three variables in your program. When you
refer to ITEM-CODE, or any other group item, COBOL
treats the variable as if it were declared as PIC X. This means you can
MOVE just about anything into it without raising an error. For example:

```<code>MOVE 'ABCdef' TO ITEM-CODE
</code>```

or

```<code>MOVE 'ABCdef0005' TO ITEM-REC
</code>```

Neither one would cause an error even though the elementary data item ITEM-NUM-CODE is definitely not a number.
To verify the validity
of your data after a group move you should validate each elementary data item separately (unless
you know for certain no data type errors could have occurred). There are a variety of ways to do this. For
example if the data item has to be numeric the following would work:

```<code>IF ITEM-NUM-CODE IS NUMERIC
   CONTINUE
ELSE
   DISPLAY 'ITEM-NUM-CODE IS NOT NUMERIC'
   PERFORM BIG-BAD-ERROR
END-IF
</code>```

COBOL provides various class tests which can be applied against a data item. For
example: NUMERIC, ALPHABETIC and ALPHANUMERIC are commonly used.

Another common way to test for ranges of values is by defining various 88 levels - but exercise
caution. In the above
example ITEM-TYPE-A is an 88 level that defines a data range from 'AAA' through 'AZZ' based on
the collating sequence currently in effect. To verify that ITEM-CHAR-CODE contains only alphabetic
characters and the first letter is an 'A' or a 'B', you could do something like:

```<code>IF ITEM-CHAR-CODE ALPHABETIC
   DISPLAY 'ITEM-CHAR-CODE is alphabetic.'
   EVALUATE TRUE
      WHEN ITEM-TYPE-A
         DISPLAY 'ITEM-CHAR-CODE is in range AAA through AZZ'
      WHEN ITEM-TYPE-B
         DISPLAY 'ITEM-CHAR-CODE is in range BAA through BZZ'
      WHEN OTHER
         DISPLAY 'ITEM-CHAR-CODE is in some other range'
   END-EVALUATE
ELSE
   DISPLAY 'ITEM-CHAR-CODE is not alphabetic'
END-IF
</code>```

Note the separate test for ALPHABETIC above. Why do that when the 88 level tests
could have done the job? Actually the 88's are not sufficient because they
cover the entire range from AAA through AZZ based on the collating sequence currently
in effect. In
an EBCDIC based environment (a very large number of COBOL shops use EBCDIC) this captures
values such as A}\. the close-brace and backslash characters are non-alpha but
fall into the middle of
the range 'A' through 'Z' (what the #*@! is that all about?). Also note that a value such
as 'aaa' would not satisfy the ITEM-TYPE-A condition because lower case letters fall outside
the defined range. Maybe time to check out an EBCDIC character table.

Finally, you can count the number of occurrences of a character, or string of characters, in
a variable with the INSPECT verb as follows:

```<code>INSPECT ITEM-CODE TALLING DASH-COUNT FOR ALL '-'
</code>```

DASH-COUNT needs to be a numeric item and will contain the number of dash characters in ITEM-CODE. The INSPECT
verb is not so useful if you want to count the number of digits. For this you would need one statement for each digit.

It might be easier to just code a loop something like:

```<code>PERFORM VARYING I FROM 1 BY 1
           UNTIL I > LENGTH OF ITEM-CODE
   EVALUATE ITEM-CODE(I:1)
      WHEN '-'
         COMPUTE DASH-COUNT = DASH-COUNT + 1
      WHEN '0' THRU '9'
         COMPUTE DIGIT-COUNT = DIGIT-COUNT + 1
      WHEN OTHER
         COMPUTE OTHER-COUNT = OTHER-COUNT + 1
   END-EVALUATE
END-PERFORM
</code>```

Now ask yourself why I was comfortable using a zero through 9 range check? Hint: look at the collating sequence.

Hope this helps.

Title: Data Validation

Body:
Here are a few hints...

Use a hieratical record structure to view the data in different ways. For example:

 01 ITEM-REC.
    05 ITEM-CODE.
       10 ITEM-NUM-CODE    PIC 9(3).
       10 ITEM-CHAR-CODE   PIC A(3).
          88 ITEM-TYPE-A   VALUE 'AAA' THRU 'AZZ'.
          88 ITEM-TYPE-B   VALUE 'BAA' THRU 'BZZ'.
    05 QUANTITY            PIC 9(4).

ITEM-CODE is a 6 character group field, the first part of which is numeric (ITEM-NUM-CODE) and the last part
is alphabetic (ITEM-CHAR-CODE). You can refer to any one of these three variables in your program. When you
refer to ITEM-CODE, or any other group item, COBOL
treats the variable as if it were declared as PIC X. This means you can
MOVE just about anything into it without raising an error. For example:

MOVE 'ABCdef' TO ITEM-CODE

or

MOVE 'ABCdef0005' TO ITEM-REC

Neither one would cause an error even though the elementary data item ITEM-NUM-CODE is definitely not a number.
To verify the validity
of your data after a group move you should validate each elementary data item separately (unless
you know for certain no data type errors could have occurred). There are a variety of ways to do this. For
example if the data item has to be numeric the following would work:

IF ITEM-NUM-CODE IS NUMERIC
   CONTINUE
ELSE
   DISPLAY 'ITEM-NUM-CODE IS NOT NUMERIC'
   PERFORM BIG-BAD-ERROR
END-IF

COBOL provides various class tests which can be applied against a data item. For
example: NUMERIC, ALPHABETIC and ALPHANUMERIC are commonly used.

Another common way to test for ranges of values is by defining various 88 levels - but exercise
caution. In the above
example ITEM-TYPE-A is an 88 level that defines a data range from 'AAA' through 'AZZ' based on
the collating sequence currently in effect. To verify that ITEM-CHAR-CODE contains only alphabetic
characters and the first letter is an 'A' or a 'B', you could do something like:

IF ITEM-CHAR-CODE ALPHABETIC
   DISPLAY 'ITEM-CHAR-CODE is alphabetic.'
   EVALUATE TRUE
      WHEN ITEM-TYPE-A
         DISPLAY 'ITEM-CHAR-CODE is in range AAA through AZZ'
      WHEN ITEM-TYPE-B
         DISPLAY 'ITEM-CHAR-CODE is in range BAA through BZZ'
      WHEN OTHER
         DISPLAY 'ITEM-CHAR-CODE is in some other range'
   END-EVALUATE
ELSE
   DISPLAY 'ITEM-CHAR-CODE is not alphabetic'
END-IF

Note the separate test for ALPHABETIC above. Why do that when the 88 level tests
could have done the job? Actually the 88's are not sufficient because they
cover the entire range from AAA through AZZ based on the collating sequence currently
in effect. In
an EBCDIC based environment (a very large number of COBOL shops use EBCDIC) this captures
values such as A}\. the close-brace and backslash characters are non-alpha but
fall into the middle of
the range 'A' through 'Z' (what the #*@! is that all about?). Also note that a value such
as 'aaa' would not satisfy the ITEM-TYPE-A condition because lower case letters fall outside
the defined range. Maybe time to check out an EBCDIC character table.

Finally, you can count the number of occurrences of a character, or string of characters, in
a variable with the INSPECT verb as follows:

INSPECT ITEM-CODE TALLING DASH-COUNT FOR ALL '-'

DASH-COUNT needs to be a numeric item and will contain the number of dash characters in ITEM-CODE. The INSPECT
verb is not so useful if you want to count the number of digits. For this you would need one statement for each digit.

It might be easier to just code a loop something like:

PERFORM VARYING I FROM 1 BY 1
           UNTIL I > LENGTH OF ITEM-CODE
   EVALUATE ITEM-CODE(I:1)
      WHEN '-'
         COMPUTE DASH-COUNT = DASH-COUNT + 1
      WHEN '0' THRU '9'
         COMPUTE DIGIT-COUNT = DIGIT-COUNT + 1
      WHEN OTHER
         COMPUTE OTHER-COUNT = OTHER-COUNT + 1
   END-EVALUATE
END-PERFORM

Now ask yourself why I was comfortable using a zero through 9 range check? Hint: look at the collating sequence.

Hope this helps.


问:
trying to get single column data with switch case statement
I am trying to get  query the table based on role like this below but I am getting error  like this

Incorrect syntax near '='.

I am not sure why I am getting this error

below is my query

```<code>CREATE procedure [dbo].[getName]
    @AccountId int,
    @role varchar(50),
    @Activated_By nvarchar(100)
AS
BEGIN

    SELECT   Name
    FROM     pass_activationinfo
    WHERE
        CASE WHEN @role = 'Admin'
             THEN account_id = @AccountId
             ELSE Activated_By = @Activated_By
        END
END
</code>```

答:
you can use this </p>

```<code>   SELECT   Name
    FROM     pass_activationinfo
    WHERE
        (( @role = 'Admin'
             and  account_id = @AccountId)
             or Activated_By = @Activated_By)
</code>```

Body:
I am trying to get  query the table based on role like this below but I am getting error  like this

Incorrect syntax near '='.

I am not sure why I am getting this error

below is my query

CREATE procedure [dbo].[getName]
    @AccountId int,
    @role varchar(50),
    @Activated_By nvarchar(100)
AS
BEGIN

    SELECT   Name
    FROM     pass_activationinfo
    WHERE
        CASE WHEN @role = 'Admin'
             THEN account_id = @AccountId
             ELSE Activated_By = @Activated_By
        END
END

Body:
you can use this

   SELECT   Name
    FROM     pass_activationinfo
    WHERE
        (( @role = 'Admin'
             and  account_id = @AccountId)
             or Activated_By = @Activated_By)


问:
Bootstrap responsive table - dropdown in header
I have this table and I have problem with dropdown in 	. When table is in
, dropdown is in table. I need to show it over table.

Thanks for advices.

答:
Check this https://jsfiddle.net/xgvLgadu/1/

I use overflow:visible on table and th/tr.

And I change z-index of .dropdown-menu to 9999

Cheers,


问:
Excel VBA: Loop IF statement through two columns
I have a client list with various information. Column C shows inception date, Column Q shows Status.

I need to loop an IF statement through Column C that checks todays date() and if the clients corresponding status is 100%. Then adds 1 year to the date in column C if true.

```<code>Private Sub Workbook_Open()
    Dim ID As Date
    Dim Status As Long

    ID = Sheets("Kunder").Range("C" & Rows.Count).End(xlUp).Row

    If ID>= Date And Status = 1 Then
    ID.Value = ID.Value + 365
    End If

    End Sub
</code>```

Thank you very much :-)

答:
This is a basic loop with condition, looping through two columns - column A and column B. Try it step by step on an empty Excel file and you will easily adjust yours to it:

```<code>Public Sub BasicLoop()

    Dim i As Long

    For i = 1 To 100
        ActiveSheet.Cells(i, 1) = i * 2
        If i * 2 / 4 Mod 2 = 0 Then
            ActiveSheet.Cells(i, 2) = i * 4
        End If
    Next i

End Sub
</code>```

Body:
I have a client list with various information. Column C shows inception date, Column Q shows Status.

I need to loop an IF statement through Column C that checks todays date() and if the clients corresponding status is 100%. Then adds 1 year to the date in column C if true.

Private Sub Workbook_Open()
    Dim ID As Date
    Dim Status As Long

    ID = Sheets("Kunder").Range("C" & Rows.Count).End(xlUp).Row

    If ID>= Date And Status = 1 Then
    ID.Value = ID.Value + 365
    End If

    End Sub

Thank you very much :-)

Body:
This is a basic loop with condition, looping through two columns - column A and column B. Try it step by step on an empty Excel file and you will easily adjust yours to it:

Public Sub BasicLoop()

    Dim i As Long

    For i = 1 To 100
        ActiveSheet.Cells(i, 1) = i * 2
        If i * 2 / 4 Mod 2 = 0 Then
            ActiveSheet.Cells(i, 2) = i * 4
        End If
    Next i

End Sub


问:
Jquery loop table from n to n row
I have a table as below:

    Group 1

     Group 1 item 1

     Group 1 item 2

     Group 1 item 3

     group 2

     group 2 item 1

     group 3

     group 4

     group 5

     group 5 item 1

     group 5 item 2

```

Whenever I click on any row  I add a class to each row (e.g. selection). If I click on any row which has a class called group then I want to add/remove a class to all other rows (if any) in that group

e.g. If I click on first row which has class called group then I should add another class to row 2,3 and 4 and they belong to row 1 (group 1).

so loop in the rows from current row until group class is found again (e.g. row 5)

can I loop through table from n to n row?

答:
Use nextUntil() function of JQuery to change class of sub-group elements.

$(".group").on("click",function(e){

  $(this).siblings(".group").removeClass("selected-header")
  $(this).addClass("selected-header")

  $(this).siblings().not(".group").removeClass("selected")
  $(this).nextUntil(".group").addClass("selected")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected-header{
  color : green
}

.selected{
  color : blue
}</code>```

 Group 1

  Group 1 item 1

  Group 1 item 2

  Group 1 item 3

  group 2

  group 2 item 1

  group 3

  group 4

  group 5

  group 5 item 1

  group 5 item 2

```

Title: Jquery loop table from n to n row

Body:
I have a table as below:

    Group 1

     Group 1 item 1

     Group 1 item 2

     Group 1 item 3

     group 2

     group 2 item 1

     group 3

     group 4

     group 5

     group 5 item 1

     group 5 item 2

Whenever I click on any row  I add a class to each row (e.g. selection). If I click on any row which has a class called group then I want to add/remove a class to all other rows (if any) in that group

e.g. If I click on first row which has class called group then I should add another class to row 2,3 and 4 and they belong to row 1 (group 1).

so loop in the rows from current row until group class is found again (e.g. row 5)

can I loop through table from n to n row?

Body:
Use nextUntil() function of JQuery to change class of sub-group elements.

$(".group").on("click",function(e){

  $(this).siblings(".group").removeClass("selected-header")
  $(this).addClass("selected-header")

  $(this).siblings().not(".group").removeClass("selected")
  $(this).nextUntil(".group").addClass("selected")
})

.selected-header{
  color : green
}

.selected{
  color : blue
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class='group'> <td>Group 1 </td> </tr>
<tr> <td> Group 1 item 1</td> </tr>
<tr> <td> Group 1 item 2</td> </tr>
<tr> <td> Group 1 item 3</td> </tr>
<tr class='group'> <td> group 2</td> </tr>
<tr> <td> group 2 item 1</td> </tr>
<tr class='group'> <td> group 3</td> </tr>
<tr class='group'> <td> group 4</td> </tr>
<tr class='group'> <td> group 5</td> </tr>
<tr> <td> group 5 item 1</td> </tr>
<tr> <td> group 5 item 2</td> </tr>
</table>


问:
How can I get the value from another form
now i'm trying to get the value from another form. But i don't know how to make it.

This is my first form:

and this is method, when we click submit in the the form1, the page will redirect to this method.

```<code>public function input_data_inserted()
{
    $id_data_inserted = $this->input->post('id_data_inserted');
    $date = $this->input->post('date');
    $id_data = $this->input->post('id_data');
    $amount= $this->input->post('amount');
    $id_room = $this->input->post('id_room');

    $passed = FALSE;

    $checkIdData = $this->modelku->cek_idData()->result_array();
    $checkIdRoom = $this->modelku->cek_idRoom()->result_array();

    foreach ($cekIdData as $cID)
    {
        foreach ($cekIdRoom as $cIR)
        {
            if ($id_data == $cID['id_data'] && $id_room == $cIR['id_room'])
            {
                $data = array
                (
                    'id_data_inserted' => $id_data_inserted,
                    'date' => $date,
                    'id_data' => $cID['id_data'],
                    'amount' => $amount,
                    'id_room' => $cIR['id_room'],
                );

                $this->modelku->input_data($data, 'table_data_inserted');
                $data['table_data_inserted'] = $this->modelku->show_data('table_data_inserted')->result();
                $this->modelku->increase_value($amount, $id_data);
                //redirect to second form
                redirect('admin/Data/data\view_detail_data');

                $passed = TRUE;
                break;
            }
        }
    }

    if(!$passed)
    {
        echo "ERORR";
    }
}
</code>```

And this is my second form:

Method for second form:

```<code>public function input_detail_barang()
{
    $id_data = $this->input->post('id_data');
    $no_inv = $this->input->post('no_inv');
    $condition = $this->input->post('condition');

    $data = array
    (
        'id_data' => $id_data,
        'no_inv' => $no_inv,
        'condition' => $condition
    );

    //I need amount from first form, because i will use it. How can i do?

}
</code>```

Any Solution? Thx

答:
After this line you can save it to session:

```<code>$data = array (
    'id_data_inserted' => $id_data_inserted,
    'date' => $date,
    'id_data' => $cID['id_data'],
    'amount' => $amount,
    'id_room' => $cIR['id_room'], // You missed single quote here
);
$this->load->library('session');
$this->session->set_userdata("Firstformdata",$data);
</code>```

And for show this data add this line:

```<code>$this->session->userdata("Firstformdata");
</code>```

Body:
now i'm trying to get the value from another form. But i don't know how to make it.

This is my first form:

and this is method, when we click submit in the the form1, the page will redirect to this method.

public function input_data_inserted()
{
    $id_data_inserted = $this->input->post('id_data_inserted');
    $date = $this->input->post('date');
    $id_data = $this->input->post('id_data');
    $amount= $this->input->post('amount');
    $id_room = $this->input->post('id_room');

    $passed = FALSE;

    $checkIdData = $this->modelku->cek_idData()->result_array();
    $checkIdRoom = $this->modelku->cek_idRoom()->result_array();

    foreach ($cekIdData as $cID)
    {
        foreach ($cekIdRoom as $cIR)
        {
            if ($id_data == $cID['id_data'] && $id_room == $cIR['id_room'])
            {
                $data = array
                (
                    'id_data_inserted' => $id_data_inserted,
                    'date' => $date,
                    'id_data' => $cID['id_data'],
                    'amount' => $amount,
                    'id_room' => $cIR['id_room'],
                );

                $this->modelku->input_data($data, 'table_data_inserted');
                $data['table_data_inserted'] = $this->modelku->show_data('table_data_inserted')->result();
                $this->modelku->increase_value($amount, $id_data);
                //redirect to second form
                redirect('admin/Data/data\view_detail_data');

                $passed = TRUE;
                break;
            }
        }
    }

    if(!$passed)
    {
        echo "ERORR";
    }
}

And this is my second form:

Method for second form:

public function input_detail_barang()
{
    $id_data = $this->input->post('id_data');
    $no_inv = $this->input->post('no_inv');
    $condition = $this->input->post('condition');

    $data = array
    (
        'id_data' => $id_data,
        'no_inv' => $no_inv,
        'condition' => $condition
    );

    //I need amount from first form, because i will use it. How can i do?

}

Any Solution? Thx

Body:
After this line you can save it to session:

$data = array (
    'id_data_inserted' => $id_data_inserted,
    'date' => $date,
    'id_data' => $cID['id_data'],
    'amount' => $amount,
    'id_room' => $cIR['id_room'], // You missed single quote here
);
$this->load->library('session');
$this->session->set_userdata("Firstformdata",$data);

And for show this data add this line:

$this->session->userdata("Firstformdata");


问:
Bootstrap row with two columns and textareas fill up page
I'm trying to make a simple page that have a header on a row, then a row with two columns. Each column will include a textarea. I want the columns and the textareas to fill up the rest of the page. I have been searching but i can't solve this. I'm using boostrap v4.0.0-beta.2.

Here is my snippet:

  label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid" style="background: #DDDDDD">
   <div class="row">
       <div class="col-lg-12 jumbotron text-center">
           <h1>Formatter</h1>
           <p>Enter raw input to see output</p>
       </div>
   </div>
   <div class="row" style="background: #CCCCCC;">
       <div class="col-lg-6">
           <label for="input">Input:</label>
           <textarea class="form-control" id="input">
           </textarea>
       </div>
       <div class="col-lg-6">
           <label for="output">Output:</label>
           <textarea readonly class="form-control" id="output"></textarea>
        </div>
    </div>
</div></code>```

答: You can do this by setting height to textarea with JS. You have to compute height needed to fill the page

Body:
I'm trying to make a simple page that have a header on a row, then a row with two columns. Each column will include a textarea. I want the columns and the textareas to fill up the rest of the page. I have been searching but i can't solve this. I'm using boostrap v4.0.0-beta.2.

Here is my snippet:

  label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Formatter

Enter raw input to see output

           Input:
           <textarea class="form-control" id="input">
           </textarea>

           Output:
           <textarea readonly class="form-control" id="output"></textarea>


问:
How to use Angular Local storage
i'm very much new to angular and trying to access localStorage. Here is the code. Please help me figure that out if it is not the right way to define and use. Thank you.</p>

```<code>var app = angular.module("toggleApp", ['LocalStorageModule']).config(function (localStorageServiceProvider) {
        localStorageServiceProvider
            .setPrefix('test')
            .setStorageType('localStorage');
    });
    app.controller("toggleController", function ($scope, $timeout,
                                                 timerParsingService, localStorageService) {
        localStorageService.set('user' ,'yash');
</code>```

答:
you could use ng-storge module and use

$localStorage.key = value or you could also use the getter and setter

```<code>$localStorageProvider.set('key', { k: 'value' });
</code>```

Title: How to use Angular Local storage

Body:
i'm very much new to angular and trying to access localStorage. Here is the code. Please help me figure that out if it is not the right way to define and use. Thank you.

var app = angular.module("toggleApp", ['LocalStorageModule']).config(function (localStorageServiceProvider) {
        localStorageServiceProvider
            .setPrefix('test')
            .setStorageType('localStorage');
    });
    app.controller("toggleController", function ($scope, $timeout,
                                                 timerParsingService, localStorageService) {
        localStorageService.set('user' ,'yash');

Body:
you could use ng-storge module and use

$localStorage.key = value or you could also use the getter and setter

$localStorageProvider.set('key', { k: 'value' });


问:
ASP.NET MVC Menu Selected Item
OK new to MVC. I had asked this question earlier and got an answer but I am wondering if there is a simpler solution.

Say I have a master page with a menu laid out as an unordered list. How would I go about setting a css class on the currently selected menu item?

EDIT:

I am using the menu just as it comes setup out of the box when you start a new mvc app

```<code><ul id="menu">
   <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
   <li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>
</code>```

答:
The answer from Jakub Konecki led me in the right direction... here is the controller action I ended up with:

```<code>    [ChildActionOnly]
    public ActionResult MainMenu()
    {
        var items = new List<MenuItem>
        {
            new MenuItem{ Text = "Home", Action = "Index", Controller = "Home", Selected=false },
            new MenuItem{ Text = "My Profile", Action = "Index", Controller = "Profile", Selected = false},
            new MenuItem{ Text = "About", Action = "About", Controller = "Home", Selected = false }
        };

        string action = ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
        string controller = ControllerContext.ParentActionViewContext.RouteData.Values["controller"].ToString();

        foreach (var item in items)
        {
            if (item.Controller == controller && item.Action == action)
            {
                item.Selected = true;
            }
        }

        return PartialView(items);
    }
</code>```

Hope this helps someone.

Title: ASP.NET MVC Menu Selected Item

Body:
OK new to MVC. I had asked this question earlier and got an answer but I am wondering if there is a simpler solution.

Say I have a master page with a menu laid out as an unordered list. How would I go about setting a css class on the currently selected menu item?

EDIT:

I am using the menu just as it comes setup out of the box when you start a new mvc app

<%: Html.ActionLink("Home", "Index", "Home")%>

<%: Html.ActionLink("About", "About", "Home")%>

Body:
The answer from Jakub Konecki led me in the right direction... here is the controller action I ended up with:

    [ChildActionOnly]
    public ActionResult MainMenu()
    {
        var items = new List<MenuItem>
        {
            new MenuItem{ Text = "Home", Action = "Index", Controller = "Home", Selected=false },
            new MenuItem{ Text = "My Profile", Action = "Index", Controller = "Profile", Selected = false},
            new MenuItem{ Text = "About", Action = "About", Controller = "Home", Selected = false }
        };

        string action = ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
        string controller = ControllerContext.ParentActionViewContext.RouteData.Values["controller"].ToString();

        foreach (var item in items)
        {
            if (item.Controller == controller && item.Action == action)
            {
                item.Selected = true;
            }
        }

        return PartialView(items);
    }

Hope this helps someone.


问:
Select Sort by Departure on Makemytrip using Vba Internet Explorer
I am trying to select sort by Departure (early) on makemytrip (link given below) using Vba Internet explorer but not able to do it.

Link:- https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E

Please check the code given below and help the line to be get added for the same.

```<code>Sub mmtlink()

Dim IE As New SHDocVw.InternetExplorer

IE.Visible = True

IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E"

IE.document.getElementById("sorterText").Click

End sub
</code>```

答:
Thanks Buntes Lama for the great help. Please check below the answer of the question i asked.</p>

```<code>Sub mmtlink()

Dim IE As New SHDocVw.InternetExplorer
Dim htmldoc As MSHTML.HTMLDocument
Dim all As MSHTML.IHTMLElementCollection
Dim one As MSHTML.IHTMLElement

'Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E"

 Do While IE.Busy = True Or IE.readyState <> 4
 Loop

    Set htmldoc = IE.document

    Set all = htmldoc.getElementsByClassName("sortbytype")
    For Each one In all
       If one.getAttribute("Innertext") = "from BOM (early)" Then
            one.Click
       End If
    Next one

Next i
End Sub
</code>```

Body:
I am trying to select sort by Departure (early) on makemytrip (link given below) using Vba Internet explorer but not able to do it.

Link:- https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E

Please check the code given below and help the line to be get added for the same.

Sub mmtlink()

Dim IE As New SHDocVw.InternetExplorer

IE.Visible = True

IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E"

IE.document.getElementById("sorterText").Click

End sub

Body:
Thanks Buntes Lama for the great help. Please check below the answer of the question i asked.

Sub mmtlink()

Dim IE As New SHDocVw.InternetExplorer
Dim htmldoc As MSHTML.HTMLDocument
Dim all As MSHTML.IHTMLElementCollection
Dim one As MSHTML.IHTMLElement

'Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

IE.navigate "https://www.makemytrip.com/air/search?tripType=O&itinerary=DEL-DXB-D-30Nov2017&paxType=A-1&cabinClass=E"

 Do While IE.Busy = True Or IE.readyState <> 4
 Loop

    Set htmldoc = IE.document

    Set all = htmldoc.getElementsByClassName("sortbytype")
    For Each one In all
       If one.getAttribute("Innertext") = "from BOM (early)" Then
            one.Click
       End If
    Next one

Next i
End Sub


问:
Update a column only if value of two columns(combination of both) are present else insert all values in Oracle DB
In my Oracle DB, There are 3 columns in table 'basic_comment' & columns are (product_id,comment,comment_id).

I have to update a column 'comment' only if combination of columns(product_id and comment_id) is already present else insert in all the three columns.  For ex:

```<code>product_id     comment     comment_id
Ac2108         fixed          5
Ac7108         configure      3
As2108         fixed          5
</code>```

so here if (Ac2108 and 5) is present then for same row I need to change comment from 'fixed' to 'configure' or if not then insert into all the columns. Columns are to be inserted from another table "static_comment".

I have tried a merge query but it is updating other rows too in "basic_comment" table.

```<code>MERGE
INTO  basic_comment a
USING static_comment b
ON  ( a.product_id = b.product_id and a.comment_id = b.comment_id )
WHEN MATCHED
THEN
 UPDATE
SET a.comment = b.comment
WHEN NOT MATCHED
THEN
INSERT ( a.product_id
, a.comment
, a.comment_id
VALUES ( b.product_id
, b.comment
, b.comment_id);
</code>```

答:
If having trouble with the merge, could do two seperate statements, obviously not as quick, but if dataset is small it will do</p>

```<code>Update table
Set comment = ‘configure’
Where product_id is not null and comment_id is not null

Insert into table2(....,....)
Select comment_id, ‘static’
From table
Where not ( product_id is not null and comment_id is not null)
</code>```

Body:
In my Oracle DB, There are 3 columns in table 'basic_comment' & columns are (product_id,comment,comment_id).

I have to update a column 'comment' only if combination of columns(product_id and comment_id) is already present else insert in all the three columns.  For ex:

product_id     comment     comment_id
Ac2108         fixed          5
Ac7108         configure      3
As2108         fixed          5

so here if (Ac2108 and 5) is present then for same row I need to change comment from 'fixed' to 'configure' or if not then insert into all the columns. Columns are to be inserted from another table "static_comment".

I have tried a merge query but it is updating other rows too in "basic_comment" table.

MERGE
INTO  basic_comment a
USING static_comment b
ON  ( a.product_id = b.product_id and a.comment_id = b.comment_id )
WHEN MATCHED
THEN
 UPDATE
SET a.comment = b.comment
WHEN NOT MATCHED
THEN
INSERT ( a.product_id
, a.comment
, a.comment_id
VALUES ( b.product_id
, b.comment
, b.comment_id);

Body:
If having trouble with the merge, could do two seperate statements, obviously not as quick, but if dataset is small it will do

Update table
Set comment = ‘configure’
Where product_id is not null and comment_id is not null

Insert into table2(....,....)
Select comment_id, ‘static’
From table
Where not ( product_id is not null and comment_id is not null)


问:
Spring Jpa @Transactional not working
I am trying to achieve transaction roll back if one or more queries fail. so i annotated @Transactional on my service implementation class. I knowingly sent wrong data type amountpaid1 (String in this case, Double is correct data type).

But now, my first update query plus insertion on challan completes successfully.
 Second query i.e query1 fails to update as it receives wrong data type so i expect the whole transaction to roll back.

Repository

```<code>@Repository
public class UpdatePaymentImpl implements UpdatePayment {

@PersistenceContext
EntityManager em;

public PaymentResponse getFcgoApiResponse(FcgoUpdateParam updateParam){
    PaymentResponse paymentResponse = new PaymentResponse();
    try {
        final String uri = "http://a.b.c.d:xxxx/FcgoApi/api/savePayment";
        RestTemplate restTemplate = new RestTemplate();
        paymentResponse = restTemplate.postForObject(uri, updateParam,
        PaymentResponse.class);
            if (paymentResponse.getVoucherNo() != null) {
                int status = updatePayment(updateParam,
                paymentResponse.getVoucherNo());
                if (status == 0) {
                    vc.setVoucherNo(paymentResponse.getVoucherNo());
                }
            }
    }catch (Exception ex){
        ex.printStackTrace();
        logger.info(ex.getMessage());
    }
    return paymentResponse;

}

    @Transactional
    public int updatePayment(FcgoUpdateParam updateParam, String voucherno){

        try{
            String amountPaid1 = updateParam.getAmountPaid();
            Double amountPaid=Double.parseDouble(updateParam.getAmountPaid());
            String masterId= updateParam.getMasterId();
            String advCode=updateParam.getAdvCode();
            long uuid = getUniqueID();
            logger.info("generated uuid "+uuid);
            DateFormat dateFormat =new SimpleDateFormat("dd-MMM-yy h.mm.ss.000000000 a");
            SimpleDateFormat dms = new SimpleDateFormat("dd-MM-yyyy");
            String cdate = updateParam.getChallanDate();
            Date ddate= dms.parse(cdate);
            String challandate = dateFormat.format(ddate);
            String office = updateParam.getOffice();
            String username = updateParam.getUsername();
            Long id = getIdOnChallanTable()+1L;

            String challanid = String.valueOf(uuid);
            ChallanEntity challanEntity = new ChallanEntity();
            challanEntity.setAdvtcode(updateParam.getAdvCode());
            challanEntity.setAmount(amountPaid);
            challanEntity.setName(updateParam.getName());
            challanEntity.setOffice(office);
            challanEntity.setUsername(username);
            challanEntity.setStatus(updateParam.getStatus());
            challanEntity.setChallandate(challandate);
            challanEntity.setChallanid(uuid);
            challanEntity.setChallantime("null");
            challanEntity.setVoucherno(voucher no);
            Query query= em.createQuery("update
            CandidateappearagainstadvtcodeEntity cd set
     cd.paymentstatus='Completed',cd.amountpaid=:depoFee,cd.challanid=:challanid
             where cd.studentmasterid=:masterid and cd.advertisementcode=:advCode");
            logger.info("update parameter advt code: "+updateParam.getAdvCode());
            query.setParameter("depoFee",updateParam.getAmountPaid());
            query.setParameter("challanid",challanid);
            query.setParameter("masterid",masterId);
            query.setParameter("advCode",advCode)
            .executeUpdate();
            Query query1 =em.createQuery(" update CandidateappeartoadvtnumberEntity
            cnd set cnd.paymentstatus='Completed', cnd.depositedfee=:depofee where
            cnd.studentmasterid=:masterid and cnd.advertisementcode=:advcode");
            String masterId1= updateParam.getMasterId();
            String advCode1=updateParam.getAdvCode();

            query1.setParameter("depofee",amountPaid1);
            query1.setParameter("masterid",masterId1);
            query1.setParameter("advcode",advCode1)
            .executeUpdate();

            em.persist(challanEntity);
            em.flush();
        }
        catch (Exception e){
            logger.info("update error " +e);
            logger.info(e.getMessage());
            return 0;

        }
        return 1 ;
    }

    }
</code>```

Service Class

```<code>    @Service
    public class UpdatePaymentServiceImpl implements UpdatePaymentService {

    @Autowired
    UpdatePayment updatePayment;

    @Transactional
    public PaymentResponse getFcgoApiResponse(FcgoUpdateParam updateParam) {
        return updatePayment.getFcgoApiResponse(updateParam);
    }

    }
</code>```

ApplicationContext.xml

```<code>    <bean id="entityManagerFactory" class="org.springframework.
    orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.psc" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.
            HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">
                org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
   </bean>
   <bean id="transactionManager"
    class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory"
        ref="entityManagerFactory" />
    </bean>
</code>```

答:
Transactions will roll back in the event of an exception being thrown from the Transactional method.

Rollback for a runtime exception is automatic.

Rollback for checked exceptions needs to be explicitly configured.

Your Transactional method never throws an Exception as you catch all exceptions within it. So you either need to throw or rethrow from within the catch block.

```<code>@Transactional(rollbackFor = MyCustomException.class) // <<
public int updatePayment(FcgoUpdateParam updateParam, String voucherno)
    throws Exception{

    int a = 5/0; unhandled runtime exception : transaction rolls back

    try{
            //runtime exception is caught and never rethrown - no rollback
            int a = 5/0;
    }
    catch (Exception e){
            // exception in try block re-thrown: transaction rolls back
            // throw(e);
    }

    throw new MyCustomException(); //checked exception rollback only occurs if configured

    return 1 ;
}
</code>```

https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html#transaction-declarative-rolling-back

The recommended way to indicate to the Spring Framework’s transaction infrastructure that a transaction’s work is to be rolled
  back is to throw an Exception from code that is currently executing in
  the context of a transaction. The Spring Framework’s transaction
  infrastructure code will catch any unhandled Exception as it bubbles
  up the call stack, and make a determination whether to mark the
  transaction for rollback.

In its default configuration, the Spring Framework’s transaction
  infrastructure code only marks a transaction for rollback in the case
  of runtime, unchecked exceptions; that is, when the thrown exception
  is an instance or subclass of RuntimeException. ( Errors will also -
  by default - result in a rollback). Checked exceptions that are thrown
  from a transactional method do not result in rollback in the default
  configuration.

Title: Spring Jpa @Transactional not working

Body:
I am trying to achieve transaction roll back if one or more queries fail. so i annotated @Transactional on my service implementation class. I knowingly sent wrong data type amountpaid1 (String in this case, Double is correct data type).

But now, my first update query plus insertion on challan completes successfully.
 Second query i.e query1 fails to update as it receives wrong data type so i expect the whole transaction to roll back.

Repository

@Repository
public class UpdatePaymentImpl implements UpdatePayment {

@PersistenceContext
EntityManager em;

public PaymentResponse getFcgoApiResponse(FcgoUpdateParam updateParam){
    PaymentResponse paymentResponse = new PaymentResponse();
    try {
        final String uri = "http://a.b.c.d:xxxx/FcgoApi/api/savePayment";
        RestTemplate restTemplate = new RestTemplate();
        paymentResponse = restTemplate.postForObject(uri, updateParam,
        PaymentResponse.class);
            if (paymentResponse.getVoucherNo() != null) {
                int status = updatePayment(updateParam,
                paymentResponse.getVoucherNo());
                if (status == 0) {
                    vc.setVoucherNo(paymentResponse.getVoucherNo());
                }
            }
    }catch (Exception ex){
        ex.printStackTrace();
        logger.info(ex.getMessage());
    }
    return paymentResponse;

}

    @Transactional
    public int updatePayment(FcgoUpdateParam updateParam, String voucherno){

        try{
            String amountPaid1 = updateParam.getAmountPaid();
            Double amountPaid=Double.parseDouble(updateParam.getAmountPaid());
            String masterId= updateParam.getMasterId();
            String advCode=updateParam.getAdvCode();
            long uuid = getUniqueID();
            logger.info("generated uuid "+uuid);
            DateFormat dateFormat =new SimpleDateFormat("dd-MMM-yy h.mm.ss.000000000 a");
            SimpleDateFormat dms = new SimpleDateFormat("dd-MM-yyyy");
            String cdate = updateParam.getChallanDate();
            Date ddate= dms.parse(cdate);
            String challandate = dateFormat.format(ddate);
            String office = updateParam.getOffice();
            String username = updateParam.getUsername();
            Long id = getIdOnChallanTable()+1L;

            String challanid = String.valueOf(uuid);
            ChallanEntity challanEntity = new ChallanEntity();
            challanEntity.setAdvtcode(updateParam.getAdvCode());
            challanEntity.setAmount(amountPaid);
            challanEntity.setName(updateParam.getName());
            challanEntity.setOffice(office);
            challanEntity.setUsername(username);
            challanEntity.setStatus(updateParam.getStatus());
            challanEntity.setChallandate(challandate);
            challanEntity.setChallanid(uuid);
            challanEntity.setChallantime("null");
            challanEntity.setVoucherno(voucher no);
            Query query= em.createQuery("update
            CandidateappearagainstadvtcodeEntity cd set
     cd.paymentstatus='Completed',cd.amountpaid=:depoFee,cd.challanid=:challanid
             where cd.studentmasterid=:masterid and cd.advertisementcode=:advCode");
            logger.info("update parameter advt code: "+updateParam.getAdvCode());
            query.setParameter("depoFee",updateParam.getAmountPaid());
            query.setParameter("challanid",challanid);
            query.setParameter("masterid",masterId);
            query.setParameter("advCode",advCode)
            .executeUpdate();
            Query query1 =em.createQuery(" update CandidateappeartoadvtnumberEntity
            cnd set cnd.paymentstatus='Completed', cnd.depositedfee=:depofee where
            cnd.studentmasterid=:masterid and cnd.advertisementcode=:advcode");
            String masterId1= updateParam.getMasterId();
            String advCode1=updateParam.getAdvCode();

            query1.setParameter("depofee",amountPaid1);
            query1.setParameter("masterid",masterId1);
            query1.setParameter("advcode",advCode1)
            .executeUpdate();

            em.persist(challanEntity);
            em.flush();
        }
        catch (Exception e){
            logger.info("update error " +e);
            logger.info(e.getMessage());
            return 0;

        }
        return 1 ;
    }

    }

Service Class

    @Service
    public class UpdatePaymentServiceImpl implements UpdatePaymentService {

    @Autowired
    UpdatePayment updatePayment;

    @Transactional
    public PaymentResponse getFcgoApiResponse(FcgoUpdateParam updateParam) {
        return updatePayment.getFcgoApiResponse(updateParam);
    }

    }

ApplicationContext.xml

    <bean id="entityManagerFactory" class="org.springframework.
    orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.psc" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.
            HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">
                org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
   </bean>
   <bean id="transactionManager"
    class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory"
        ref="entityManagerFactory" />
    </bean>

Body:
Transactions will roll back in the event of an exception being thrown from the Transactional method.

Rollback for a runtime exception is automatic.

Rollback for checked exceptions needs to be explicitly configured.

Your Transactional method never throws an Exception as you catch all exceptions within it. So you either need to throw or rethrow from within the catch block.

@Transactional(rollbackFor = MyCustomException.class) // <<
public int updatePayment(FcgoUpdateParam updateParam, String voucherno)
    throws Exception{

    int a = 5/0; unhandled runtime exception : transaction rolls back

    try{
            //runtime exception is caught and never rethrown - no rollback
            int a = 5/0;
    }
    catch (Exception e){
            // exception in try block re-thrown: transaction rolls back
            // throw(e);
    }

    throw new MyCustomException(); //checked exception rollback only occurs if configured

    return 1 ;
}

https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html#transaction-declarative-rolling-back

The recommended way to indicate to the Spring Framework’s transaction infrastructure that a transaction’s work is to be rolled
  back is to throw an Exception from code that is currently executing in
  the context of a transaction. The Spring Framework’s transaction
  infrastructure code will catch any unhandled Exception as it bubbles
  up the call stack, and make a determination whether to mark the
  transaction for rollback.

In its default configuration, the Spring Framework’s transaction
  infrastructure code only marks a transaction for rollback in the case
  of runtime, unchecked exceptions; that is, when the thrown exception
  is an instance or subclass of RuntimeException. ( Errors will also -
  by default - result in a rollback). Checked exceptions that are thrown
  from a transactional method do not result in rollback in the default
  configuration.