问:
Unable to trigger ng-click on a button when you click the button contents
I have some buttons in an html template, controlled by an AngularJS directive. The buttons ng-click event doesn't fire when you click on the buttons contents (icon and span), clicking anywhere on the padding or blank space works fine though...

This is only an issue in Safari.

I am using AngualrJS 1.4.

The icon is in an i element using classes to find the icon I want from a font file.

```<code><button ng-if="form.awesome" class="button awesome" ng-click="chooseAwesome()">
    <i class="icon icon-awesome"></i>
    <span>Awesome</span>
</button>
</code>```

Clicking in the green or orange area works fine.
The image on the right, clicking on the element in blue, doesn't trigger the click.

I have tried messing with the z-index and I have looked to see if the icon and span elements are capturing the click and preventing it from being passed to the button (which as far as I can tell they are not...)

答:
For me the solution was to move the ng-click inside the <button> tag. I had it previously in  and it was working in Chrome, but not in Firefox and IE.

After the ng-click resides in <button> instead of  tags, it works in all three browsers with no errors.

Here is my resulting code:

```<code>    <button class="btn btn-default btn-xs" ng-click="myFunction()">
    <span class="glyphicon glyphicon-th-list">
    </span></button>
</code>```

Hope this helps.

Body:
I have some buttons in an html template, controlled by an AngularJS directive. The buttons ng-click event doesn't fire when you click on the buttons contents (icon and span), clicking anywhere on the padding or blank space works fine though...

This is only an issue in Safari.

I am using AngualrJS 1.4.

The icon is in an i element using classes to find the icon I want from a font file.

<button ng-if="form.awesome" class="button awesome" ng-click="chooseAwesome()">

    Awesome
</button>

Clicking in the green or orange area works fine.
The image on the right, clicking on the element in blue, doesn't trigger the click.

I have tried messing with the z-index and I have looked to see if the icon and span elements are capturing the click and preventing it from being passed to the button (which as far as I can tell they are not...)

Body:
For me the solution was to move the ng-click inside the <button> tag. I had it previously in <span> and it was working in Chrome, but not in Firefox and IE.

After the ng-click resides in <button> instead of <span> tags, it works in all three browsers with no errors.

Here is my resulting code:

    <button class="btn btn-default btn-xs" ng-click="myFunction()">
    <span class="glyphicon glyphicon-th-list">
    </span></button>

Hope this helps.


来源: stackexchange

问:
displaying a resutset from database as individual numbers
I am trying to display a set of values as comma separated.

my data is $data = 123456789
i want to display it as (1,2,3,4,5,6,7,8,9)

i tried doing echo implode(',' ,(array)$data);
But no result.

答:
use below code

```<code>$data = 'value from database';
$data = (string)$data

$array = str_split($data);
print_r($array);
$string = implode(",",$array);
echo $string;
</code>```

Here is Sample Output

```<code> Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)
1,2,3,4,5,6,7,8,9
</code>```

According to your code

```<code>$sc1 = mysqli_query($con, "select distinct pt from pl_pts where first<>'' AND date(dtime) = CURDATE() ORDER BY pt");

while ($sc2 = mysqli_fetch_array($sc1))
    {
    $data = (string)$sc2['pt'];
    $array = str_split($data);
    $string = implode(",", $array);
    echo "(".$string.")";//concated parenthesis
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
use below code

$data = 'value from database';
$data = (string)$data

$array = str_split($data);
print_r($array);
$string = implode(",",$array);
echo $string;

Here is Sample Output

 Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)
1,2,3,4,5,6,7,8,9

According to your code

$sc1 = mysqli_query($con, "select distinct pt from pl_pts where first<>'' AND date(dtime) = CURDATE() ORDER BY pt");

while ($sc2 = mysqli_fetch_array($sc1))
    {
    $data = (string)$sc2['pt'];
    $array = str_split($data);
    $string = implode(",", $array);
    echo "(".$string.")";//concated parenthesis
    }


问:
How to add ListView items on button click using adapter
How to take data that was typed in EditText and by clicking "submit" in that window should add it to previous activity listview items?
What I need to do is:

Creating EditText and submit button

Creating listview in same Activity

By clicking submit button it should display it in listview.

I saw this similar question here:add items to listview dynamically android

But i couldn't understand the answer.Somebody please explain how to do this.

答:
Suppose you have an arraylist

```<code>ArrayList<String> dataList = new Arraylist ();
</code>```

So On clicking of button, you need to add the new data item into your data arraylist.

For this first take the value entered in edittext and store in a string.

```<code>String editedValue = yourEditText.getText.toString();
</code>```

Then we need to add this in our datalist.

Like

```<code>dataList.add(editedValue);
</code>```

And then just call adapter.notifyDataSetChanged()

```<code>yourAdapter.notifyDataSetChanged();
</code>```

It will work.

Body:
Suppose you have an arraylist

ArrayList<String> dataList = new Arraylist ();

So On clicking of button, you need to add the new data item into your data arraylist.

For this first take the value entered in edittext and store in a string.

String editedValue = yourEditText.getText.toString();

Then we need to add this in our datalist.

Like

dataList.add(editedValue);

And then just call adapter.notifyDataSetChanged()

yourAdapter.notifyDataSetChanged();

It will work.

ContentLicense: CC BY-SA 4.0


问:
How do I switch OS user in Datagrip to Postgres via SSH?
When I connect to my database remotely I use ssh to connect to the remote machine, then I run sudo -u postgres psql to access PostgresSQL. The postgres user is passwordless in my OS.

I can make an SSH tunnel connect in Datagrip, but I can't seem to find a way to switch to postgres user prior to attempting to access the database.

Is there a way to do this?

答:
First, you need to configure SSH tunnel on datasource ssh/ssl tab (host/port/username/password).
Secondly, you need to specify database credentials to your db on general tab.
Also, make sure you configured server correctly for non-local connections.

You should go to ~/.ssh/config file and set the tunnel with the user, which is used on the server, and put 'postgres' as a user name in the connection properties.

Note, it is working only in 2017.3 EAP now (release will be available this week)


问:
Jenkins Multijob filnaly result
I have Multijob structure:

```<code>Master MultiJob Project (Job)
 |----- Phase 1
            |------> JOB A
            |------> JOB D
 |----- Phase 2
            |------> JOB B
            |------> JOB D
 |----- Phase 2
            |------> JOB C
</code>```

Job D is always failed, but it's Ok for this project.
How I can exclude result job D from final results? (Because all other jobs is success, but final result is FAILED)

答:
Another solution with groovy script. Add it as Post build action in your Multijob.</p>

```<code>def subjobStatusMap = [:]

manager.build.getSubBuilds().each { subBuild->
      subJobName = subBuild.getJobName()
      subJobNumber = subBuild.getBuildNumber()
      job = hudson.model.Hudson.instance.getItem(subBuild.getJobName())
      results = job.getLastCompletedBuild().getResult()

      subjobStatusMap.put((subJobName), results)
}
manager.listener.logger.println(subjobStatusMap)

if(("SUCCESS".equals(subjobStatusMap.get("JOB_A").toString()))&& ("SUCCESS".equals(subjobStatusMap.get("JOB_B").toString())) && ("SUCCESS".equals(subjobStatusMap.get("JOB_C").toString()))) {
    manager.build.@result = hudson.model.Result.SUCCESS
}
</code>```

Title: Jenkins Multijob filnaly result

Body:
I have Multijob structure:

Master MultiJob Project (Job)
 |----- Phase 1
            |------> JOB A
            |------> JOB D
 |----- Phase 2
            |------> JOB B
            |------> JOB D
 |----- Phase 2
            |------> JOB C

Job D is always failed, but it's Ok for this project.
How I can exclude result job D from final results? (Because all other jobs is success, but final result is FAILED)

Body:
Another solution with groovy script. Add it as Post build action in your Multijob.

def subjobStatusMap = [:]

manager.build.getSubBuilds().each { subBuild->
      subJobName = subBuild.getJobName()
      subJobNumber = subBuild.getBuildNumber()
      job = hudson.model.Hudson.instance.getItem(subBuild.getJobName())
      results = job.getLastCompletedBuild().getResult()

      subjobStatusMap.put((subJobName), results)
}
manager.listener.logger.println(subjobStatusMap)

if(("SUCCESS".equals(subjobStatusMap.get("JOB_A").toString()))&& ("SUCCESS".equals(subjobStatusMap.get("JOB_B").toString())) && ("SUCCESS".equals(subjobStatusMap.get("JOB_C").toString()))) {
    manager.build.@result = hudson.model.Result.SUCCESS
}


问:
EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'details'
I have this router:

```<code>import { Route, RouterModule } from '@angular/router';
import { ProjectDetailsComponent } from '../components/project-details/project-details.component';

export const ROUTES: Route[] = [
  {
    path: '',
    redirectTo: '/details',
    pathMatch: 'full'
  },
  {
    path: 'details/:id',
    component: ProjectDetailsComponent
  }
];
</code>```

Also I have an appropriate controller, named ProjectDetailsComponent.

This is my app module, in which I have registered my routes:

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

// Custom components
import { AppComponent } from './app.component';
import { ProjectDetailsComponent } from './components/project-details/project-details.component';

// Routes
import { ROUTES } from './services/router';

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(ROUTES, { useHash: true })
  ],
  declarations: [AppComponent, ProjectDetailsComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

And its my app.component, in which I try to redirect to ProjectDetailsComponent using "/details" routes and send to it project id:

```<code>import { Component, OnInit } from '@angular/core';
import { IProject } from './domain/projects
import { Router } from '@angular/router';
// Routes
import { ROUTES } from './services/router';

@Component({
    selector: 'projects-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent implements AfterViewInit {
    public activeProject: IProject;
    public projects: Array<IProject>;

    constructor(public router: Router) {
    }

    ngOnInit() {
        this.router.navigate(['/details', this.activeProject.Id]);
    }
}
</code>```

But when I try to navigate to 'details/:id' router I get following error:

```<code>C:\Sources\SolarPro\build\debug\resources\app\node_modules\@angular\core\bundles\core.umd.js:3521 EXCEPTION: Uncaught (in promise):
   Error: Cannot match any routes. URL Segment: 'details'
</code>```

Please help me with my problem.

答:
I faced the same issue apply, all possible solution but finally, this solve my problem

```<code>export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['details']); // or redirect to default route
    }
  }
}
</code>```

This will work because angular 4 has not given any default route so handle error catch that and you can redirect to default route

Body:
I have this router:

import { Route, RouterModule } from '@angular/router';
import { ProjectDetailsComponent } from '../components/project-details/project-details.component';

export const ROUTES: Route[] = [
  {
    path: '',
    redirectTo: '/details',
    pathMatch: 'full'
  },
  {
    path: 'details/:id',
    component: ProjectDetailsComponent
  }
];

Also I have an appropriate controller, named ProjectDetailsComponent.

This is my app module, in which I have registered my routes:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

// Custom components
import { AppComponent } from './app.component';
import { ProjectDetailsComponent } from './components/project-details/project-details.component';

// Routes
import { ROUTES } from './services/router';

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(ROUTES, { useHash: true })
  ],
  declarations: [AppComponent, ProjectDetailsComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
}

And its my app.component, in which I try to redirect to ProjectDetailsComponent using "/details" routes and send to it project id:

import { Component, OnInit } from '@angular/core';
import { IProject } from './domain/projects
import { Router } from '@angular/router';
// Routes
import { ROUTES } from './services/router';

@Component({
    selector: 'projects-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent implements AfterViewInit {
    public activeProject: IProject;
    public projects: Array<IProject>;

    constructor(public router: Router) {
    }

    ngOnInit() {
        this.router.navigate(['/details', this.activeProject.Id]);
    }
}

But when I try to navigate to 'details/:id' router I get following error:

C:\Sources\SolarPro\build\debug\resources\app\node_modules\@angular\core\bundles\core.umd.js:3521 EXCEPTION: Uncaught (in promise):
   Error: Cannot match any routes. URL Segment: 'details'

Please help me with my problem.

Body:
I faced the same issue apply, all possible solution but finally, this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['details']); // or redirect to default route
    }
  }
}

This will work because angular 4 has not given any default route so handle error catch that and you can redirect to default route


问:
Disable buttons during ajax requests
I've seen many ways in jquery and Angular 1 on how to disable a submit button whilst an ajax request is being processed, but not for Angular 2.

So far on the template I have:

```<code><button type="submit" [disabled]="requestSent">Submit</button>
</code>```

and the following to toggle it's disabled state in the Typescript:

```<code>requestSent: boolean = false;

this.httpService.addNewAgent(object)
            .subscribe(
            data => {

                this.requestSent = false;

            },
            error => {

                console.log(error.error);

            }
            );
</code>```

But this is rather long winded to do on every single component. Is there a more universal way of dealing with this? Perhaps with interceptors?

答:
Thanks @DmitriyKhirniy for the reply but I wanted a more universal way of disabling buttons during ajax requests. I found a way using directives, services and the interceptor. So using this you will only ever have to apply the attribute disableDuringAjax to your button(s).

Template:

<button type="submit" disableDuringAjax>Sign In</button>
```
<p>If you have a button that also disables due to form validation you could use:</p>
```<button type="submit" disableDuringAjax [formValid]="myForm">Sign In</button>
```
<p>With the <code>[formValid]</code> simply mentioning the instance of the form in general, the directive will do rest of the work.</p>
<p>Directive (disable-button-during-ajax.directive.ts):</p>
<pre class="lang-js prettyprint-override"><code>import { Component, OnDestroy, OnInit, Directive, HostListener, HostBinding, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core';
import { BusyService } from '../../shared/services/busy.service';
import { Subscription, Subject, takeUntil } from 'rxjs';

@Directive({
    selector: '[disableDuringAjax]'
})

export class DisableButtonDuringAjax implements OnDestroy, OnInit {

    private ngUnsubscribe: Subject<any> = new Subject();

    @Input() formValid;

    subscription: Subscription;

    constructor(private _busyService: BusyService, private el: ElementRef) {

    }

    checkFormValidation(form)
    {
        if ((form.valid == true)) {
            this.checkAjaxProgress();
        }
        if ((form.valid == false)) {
            this.el.nativeElement.disabled = true;
        }
    }

    checkAjaxProgress()
    {

        this.subscription = this._busyService.busy$
        .pipe(takeUntil(this.ngUnsubscribe)).subscribe(
            response => {

                if ((response == true)) {
                    this.el.nativeElement.disabled = true;
                }

                if ((response == false)) {
                    this.el.nativeElement.disabled = false;
                }

                // Check form one more time
                if ((this.formValid != null)) {
                    if ((this.formValid.valid == false)) {
                        this.el.nativeElement.disabled = true;
                    }
                }

            }
            );
    }

    doChecks()
    {
        // If there is no form to check validation then just check the ajax progress
        if ((this.formValid == null)) {
            this.checkAjaxProgress();
        }
        // Else check the forms validation AND ajax progress
        else {
            this.checkFormValidation(this.formValid);
            this.formValid.valueChanges.pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => this.checkFormValidation(this.formValid));
        }
    }

    ngOnInit() {

        this.doChecks();

    }

    ngOnChanges(changes: SimpleChanges)
    {
        this.doChecks();
    }

    ngOnDestroy() {
        this.ngUnsubscribe.next(null);
        this.ngUnsubscribe.complete();
    }

}
</code>```

Service (busy.service.ts):

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class BusyService {

    numberOfBusyRequests: number = 0;
    numberOfNonBusyRequests: number = 0;

    // Observable navItem source
    private _busySource = new BehaviorSubject<boolean>(null);
    // Observable navItem stream
    busy$ = this._busySource.asObservable();

    constructor() { }

    changeBusy(val) {

        if ((val == true)) {
            this.numberOfBusyRequests = this.numberOfBusyRequests + 1;
        }
        else {
            this.numberOfNonBusyRequests = this.numberOfNonBusyRequests + 1;
        }

        if (this.numberOfBusyRequests == this.numberOfNonBusyRequests) {
            this._busySource.next(false);
        }
        else {
            this._busySource.next(true);
        }

    }
}
```
<p>Interceptor (your own interceptor):</p>
<pre class="lang-js prettyprint-override"><code>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/do';
import { BusyService } from './busy.service';

@Injectable()
export class ProgressInterceptor implements HttpInterceptor {

    constructor(private busyService: BusyService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).do(
            event => {

                // If request was sent
                if ((event.type == 0))
                {
                    this.busyService.changeBusy(true);
                }
                else
                {
                    this.busyService.changeBusy(false);
                }
            }
        )
    }
}
</code>```

Make sure to include the directive into your app.module or shared module.
And also make sure to include the service into your app.module.

UPDATE June 2022 - I've created a library for this now = https://www.npmjs.com/package/ngx-disable-during-ajax

Title: Disable buttons during ajax requests

Body:
I've seen many ways in jquery and Angular 1 on how to disable a submit button whilst an ajax request is being processed, but not for Angular 2.

So far on the template I have:

<button type="submit" [disabled]="requestSent">Submit</button>

and the following to toggle it's disabled state in the Typescript:

requestSent: boolean = false;

this.httpService.addNewAgent(object)
            .subscribe(
            data => {

                this.requestSent = false;

            },
            error => {

                console.log(error.error);

            }
            );

But this is rather long winded to do on every single component. Is there a more universal way of dealing with this? Perhaps with interceptors?

Body:
Thanks @DmitriyKhirniy for the reply but I wanted a more universal way of disabling buttons during ajax requests. I found a way using directives, services and the interceptor. So using this you will only ever have to apply the attribute disableDuringAjax to your button(s).

Template:

<button type="submit" disableDuringAjax>Sign In</button>

If you have a button that also disables due to form validation you could use:

<button type="submit" disableDuringAjax [formValid]="myForm">Sign In</button>

With the [formValid] simply mentioning the instance of the form in general, the directive will do rest of the work.

Directive (disable-button-during-ajax.directive.ts):

import { Component, OnDestroy, OnInit, Directive, HostListener, HostBinding, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core';
import { BusyService } from '../../shared/services/busy.service';
import { Subscription, Subject, takeUntil } from 'rxjs';

@Directive({
    selector: '[disableDuringAjax]'
})

export class DisableButtonDuringAjax implements OnDestroy, OnInit {

    private ngUnsubscribe: Subject<any> = new Subject();

    @Input() formValid;

    subscription: Subscription;

    constructor(private _busyService: BusyService, private el: ElementRef) {

    }

    checkFormValidation(form)
    {
        if ((form.valid == true)) {
            this.checkAjaxProgress();
        }
        if ((form.valid == false)) {
            this.el.nativeElement.disabled = true;
        }
    }

    checkAjaxProgress()
    {

        this.subscription = this._busyService.busy$
        .pipe(takeUntil(this.ngUnsubscribe)).subscribe(
            response => {

                if ((response == true)) {
                    this.el.nativeElement.disabled = true;
                }

                if ((response == false)) {
                    this.el.nativeElement.disabled = false;
                }

                // Check form one more time
                if ((this.formValid != null)) {
                    if ((this.formValid.valid == false)) {
                        this.el.nativeElement.disabled = true;
                    }
                }

            }
            );
    }

    doChecks()
    {
        // If there is no form to check validation then just check the ajax progress
        if ((this.formValid == null)) {
            this.checkAjaxProgress();
        }
        // Else check the forms validation AND ajax progress
        else {
            this.checkFormValidation(this.formValid);
            this.formValid.valueChanges.pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => this.checkFormValidation(this.formValid));
        }
    }

    ngOnInit() {

        this.doChecks();

    }

    ngOnChanges(changes: SimpleChanges)
    {
        this.doChecks();
    }

    ngOnDestroy() {
        this.ngUnsubscribe.next(null);
        this.ngUnsubscribe.complete();
    }

}

Service (busy.service.ts):

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class BusyService {

    numberOfBusyRequests: number = 0;
    numberOfNonBusyRequests: number = 0;

    // Observable navItem source
    private _busySource = new BehaviorSubject<boolean>(null);
    // Observable navItem stream
    busy$ = this._busySource.asObservable();

    constructor() { }

    changeBusy(val) {

        if ((val == true)) {
            this.numberOfBusyRequests = this.numberOfBusyRequests + 1;
        }
        else {
            this.numberOfNonBusyRequests = this.numberOfNonBusyRequests + 1;
        }

        if (this.numberOfBusyRequests == this.numberOfNonBusyRequests) {
            this._busySource.next(false);
        }
        else {
            this._busySource.next(true);
        }

    }
}

Interceptor (your own interceptor):

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/do';
import { BusyService } from './busy.service';

@Injectable()
export class ProgressInterceptor implements HttpInterceptor {

    constructor(private busyService: BusyService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).do(
            event => {

                // If request was sent
                if ((event.type == 0))
                {
                    this.busyService.changeBusy(true);
                }
                else
                {
                    this.busyService.changeBusy(false);
                }
            }
        )
    }
}

Make sure to include the directive into your app.module or shared module.
And also make sure to include the service into your app.module.

UPDATE June 2022 - I've created a library for this now = https://www.npmjs.com/package/ngx-disable-during-ajax


问:
How do I show/hide elements using jQuery when there are two intersecting principles governing if they are to be visible or not?
I have a web page that contains a set of elements that are marked with metadata using HTML5's "data-" tag. Each element represents a specific course or program at a school. Here's an example of what the set of elements can look like:

```<code><div class="courseBox" data-type="course" data-location="campus">info about this particular course</div>

<div class="courseBox" data-type="program" data-location="campus">info about this particular course</div>

<div class="courseBox" data-type="course" data-location="distance">info about this particular course</div>

<div class="courseBox" data-type="program" data-location="distance">info about this particular course</div>
</code>```

As you can see each element is either a course (short single course) or a program (a full education that spans over several years). Furthermore, each element is eithar campus (on campus) or distance (distance learning).

In the interface for this page the user has four buttons that can either be on/true or off/false. The four buttons are:

Course | Program | Campus | Distance

When the page loads all four buttons are on/true since the page displays all courses and programs, both on campus and distance learning.

When the user clicks one of the buttons, I want to use jQuery to hide all the elements that no longer match the criteria; in other words: a filter.

At first this seemed like an easy task. Just write something along the lines of:

```<code>$("#courseButton").toggle(function(){
   $("courseBox[data-type='course']").hide();
},
function(){
   $("courseBox[data-type='course']").show();
});
</code>```

This works fine as long as the two different ways of categorizing the elements don't collide. But consider this case:

The user first clicks the "Course"
button, which hides all the courses
(marked "courses").

Then clicks the "Distance" button
which hides all elements marked
"distance".

The user then clicks the "Course"
button again, which will show all
element marked with "courses" including
those that are marked "distance",
despite the fact that they are
supposed to be hidden.

My question now is: how do I create a filter function using jQuery that will function properly eventhough there are two different (intersecting) ways of categorizing the elements?

Thanks in advance!

/Thomas Kahn

答:
Actually, your situation is a bit trickier.  You have two groups, type and location.  You need the intersection of type and location.

This means selecting all of the items of the selected type(s) and then filtering out all of the ones that are not of selected distance(s) or vice versa.

Here is an example:

```<code>$(".button").click(function() {
    $(this).toggleClass('selected');

    $(".courseBox").hide();

    var datatypes = $(".courseBox");

    $(".button.datatype").not('.selected').each(function() {
        var selClass = $(this).attr('id').replace('Button', '');

        datatypes = datatypes.filter(".courseBox[data-type!='" + selClass + "']");
    });

    $(".button.selected.datalocation").each(function() {
        var selClass = $(this).attr('id').replace('Button', '');

        datatypes.filter(".courseBox[data-location='" + selClass + "']").show();
    });
});
</code>```

http://jsfiddle.net/jtbowden/qjpctye4/

I actually start with all items, remove any that are of a type that is not selected, and then only show those which are of a distance selected.

$(".button").click(function() {
  $(this).toggleClass('selected');

  $(".courseBox").hide();

  var datatypes = $(".courseBox");

  $(".button.datatype").not('.selected').each(function() {
    var selClass = $(this).attr('id').replace('Button', '');

    datatypes = datatypes.filter(".courseBox[data-type!='" + selClass + "']");
  });

  $(".button.selected.datalocation").each(function() {
    var selClass = $(this).attr('id').replace('Button', '');

    datatypes.filter(".courseBox[data-location='" + selClass + "']").show();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  border: 1px solid black;
  padding: 2px;
  margin: 4px;
  float: left;
  cursor: default;
}
.courseBox {
  clear: both;
  background-color: lightBlue;
  margin: 3px;
}
.selected {
  background-color: lightGreen;
}</code>```

Courses

Programs

Distance

Campus

Course Campus

Program Campus

Course Distance

Program Distance
```

ContentLicense: CC BY-SA 2.5

Body:
I have a web page that contains a set of elements that are marked with metadata using HTML5's "data-" tag. Each element represents a specific course or program at a school. Here's an example of what the set of elements can look like:

info about this particular course

info about this particular course

info about this particular course

info about this particular course

As you can see each element is either a course (short single course) or a program (a full education that spans over several years). Furthermore, each element is eithar campus (on campus) or distance (distance learning).

In the interface for this page the user has four buttons that can either be on/true or off/false. The four buttons are:

Course | Program | Campus | Distance

When the page loads all four buttons are on/true since the page displays all courses and programs, both on campus and distance learning.

When the user clicks one of the buttons, I want to use jQuery to hide all the elements that no longer match the criteria; in other words: a filter.

At first this seemed like an easy task. Just write something along the lines of:

$("#courseButton").toggle(function(){
   $("courseBox[data-type='course']").hide();
},
function(){
   $("courseBox[data-type='course']").show();
});

This works fine as long as the two different ways of categorizing the elements don't collide. But consider this case:

The user first clicks the "Course"
button, which hides all the courses
(marked "courses").

Then clicks the "Distance" button
which hides all elements marked
"distance".

The user then clicks the "Course"
button again, which will show all
element marked with "courses" including
those that are marked "distance",
despite the fact that they are
supposed to be hidden.

My question now is: how do I create a filter function using jQuery that will function properly eventhough there are two different (intersecting) ways of categorizing the elements?

Thanks in advance!

/Thomas Kahn

Body:
Actually, your situation is a bit trickier.  You have two groups, type and location.  You need the intersection of type and location.

This means selecting all of the items of the selected type(s) and then filtering out all of the ones that are not of selected distance(s) or vice versa.

Here is an example:

$(".button").click(function() {
    $(this).toggleClass('selected');

    $(".courseBox").hide();

    var datatypes = $(".courseBox");

    $(".button.datatype").not('.selected').each(function() {
        var selClass = $(this).attr('id').replace('Button', '');

        datatypes = datatypes.filter(".courseBox[data-type!='" + selClass + "']");
    });

    $(".button.selected.datalocation").each(function() {
        var selClass = $(this).attr('id').replace('Button', '');

        datatypes.filter(".courseBox[data-location='" + selClass + "']").show();
    });
});

http://jsfiddle.net/jtbowden/qjpctye4/

I actually start with all items, remove any that are of a type that is not selected, and then only show those which are of a distance selected.

$(".button").click(function() {
  $(this).toggleClass('selected');

  $(".courseBox").hide();

  var datatypes = $(".courseBox");

  $(".button.datatype").not('.selected').each(function() {
    var selClass = $(this).attr('id').replace('Button', '');

    datatypes = datatypes.filter(".courseBox[data-type!='" + selClass + "']");
  });

  $(".button.selected.datalocation").each(function() {
    var selClass = $(this).attr('id').replace('Button', '');

    datatypes.filter(".courseBox[data-location='" + selClass + "']").show();
  });
});

.button {
  border: 1px solid black;
  padding: 2px;
  margin: 4px;
  float: left;
  cursor: default;
}
.courseBox {
  clear: both;
  background-color: lightBlue;
  margin: 3px;
}
.selected {
  background-color: lightGreen;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="button selected datatype" id="courseButton">Courses</div>
<div class="button selected datatype" id="programButton">Programs</div>
<div class="button selected datalocation" id="distanceButton">Distance</div>
<div class="button selected datalocation" id="campusButton">Campus</div>

<div class="courseBox" data-type="course" data-location="campus">Course Campus</div>

<div class="courseBox" data-type="program" data-location="campus">Program Campus</div>

<div class="courseBox" data-type="course" data-location="distance">Course Distance</div>

<div class="courseBox" data-type="program" data-location="distance">Program Distance</div>


问:
Access toggle button in Android settings using appium whlie client is written in groovy and java

It's not a duplicate.

I am writing automation in Appium. I am fairly new to automation concept and Appium it self. I am using java-client.

I have a scenario in which my android app for which I am writing automation, has to take android permission. My application navigates to following setting page of Android Settings as shown below.

To automate clicks on this page I have created a Page Object which would represent this screen. in this scenario I am only interested in toggling the Switch and to learn how to get it's state.

I could get resource id for the UI Automator Viewer something like this.

So my initialization is something like this to access the switch Widget.

```<code>SwitchID { $("#switchWidget") }
</code>```

Apparently, When i run the feature file, Appium is not able to find this switch widget. But I can automate other widget inside the application I am working on. but I can't get anything on this setting screen of android.

Any help would be highly regarded.
Thanks

答:
What if the switch is checked already? If you tap you will disable it...

Try:

```<code>driver.find_element_by_xpath("//android.widget.Switch[@resource-id='android:id/switchWidget' and @checkable='true']")
</code>```

This will only get your element when is checkable

Body:
It's not a duplicate.

I am writing automation in Appium. I am fairly new to automation concept and Appium it self. I am using java-client.

I have a scenario in which my android app for which I am writing automation, has to take android permission. My application navigates to following setting page of Android Settings as shown below.

To automate clicks on this page I have created a Page Object which would represent this screen. in this scenario I am only interested in toggling the Switch and to learn how to get it's state.

I could get resource id for the UI Automator Viewer something like this.

So my initialization is something like this to access the switch Widget.

SwitchID { $("#switchWidget") }

Apparently, When i run the feature file, Appium is not able to find this switch widget. But I can automate other widget inside the application I am working on. but I can't get anything on this setting screen of android.

Any help would be highly regarded.
Thanks

Body:
What if the switch is checked already? If you tap you will disable it...

Try:

driver.find_element_by_xpath("//android.widget.Switch[@resource-id='android:id/switchWidget' and @checkable='true']")

This will only get your element when is checkable


问:
Multi nested model driven form angular 2
I'm working with ionic 2 angular 2. I want to know that how to create a multi-nested formgroup in html template.

For example:

this is form group in .ts file

```<code>HomeAddress: this.formBuilder.group({
    Address: ['', Validators.required]
    HomeAddressDetail: this.formBuilder.group({
        Country: ['', Validators.required]
        Tel: this.formBuilder.group({
            PhoneNo: ['', Validators.required],
            HomeNo: ['', Validators.required]
        }),
        Email: this.formBuilder.group({
            PrimaryEmail: ['', Validators.required],
            SecondaryEmail: ['', Validators.required]
        })
    })
});
</code>```

How can I set the HTML template according to this FormGroup.

答:
You can set the HTML template like bellow:

```<code><form [formGroup]="HomeAddress">
     <div>Address: <input type="text" formControlName="Address"></div>
     <div formGroupName="HomeAddressDetail">
         <div>Country: <input type="text" formControlName="Country"></div>
         <div formGroupName="Tel">
              Phone No: <input type="text" formControlName="PhoneNo">
              Home No: <input type="text" formControlName="HomeNo">
         </div>
         <div formGroupName="Email">
              Primary Email: <input type="text" formControlName="PrimaryEmail">
              Secondary Email: <input type="text" formControlName="SecondaryEmail">
         </div>
    </div>
</form>
</code>```

I dont know the ionic controls, I replied in angular 2. You can use same format in ionic 2. Here is the plunkr https://plnkr.co/edit/SMCAMddPNmEyHuVS0IK8?p=preview

Body:
I'm working with ionic 2 angular 2. I want to know that how to create a multi-nested formgroup in html template.

For example:

this is form group in .ts file

HomeAddress: this.formBuilder.group({
    Address: ['', Validators.required]
    HomeAddressDetail: this.formBuilder.group({
        Country: ['', Validators.required]
        Tel: this.formBuilder.group({
            PhoneNo: ['', Validators.required],
            HomeNo: ['', Validators.required]
        }),
        Email: this.formBuilder.group({
            PrimaryEmail: ['', Validators.required],
            SecondaryEmail: ['', Validators.required]
        })
    })
});

How can I set the HTML template according to this FormGroup.

Body:
You can set the HTML template like bellow:

<form [formGroup]="HomeAddress">
     <div>Address: <input type="text" formControlName="Address"></div>
     <div formGroupName="HomeAddressDetail">
         <div>Country: <input type="text" formControlName="Country"></div>
         <div formGroupName="Tel">
              Phone No: <input type="text" formControlName="PhoneNo">
              Home No: <input type="text" formControlName="HomeNo">
         </div>
         <div formGroupName="Email">
              Primary Email: <input type="text" formControlName="PrimaryEmail">
              Secondary Email: <input type="text" formControlName="SecondaryEmail">
         </div>
    </div>
</form>

I dont know the ionic controls, I replied in angular 2. You can use same format in ionic 2. Here is the plunkr https://plnkr.co/edit/SMCAMddPNmEyHuVS0IK8?p=preview


问:
SSRS what's the difference between using or not First() function for identical data per group?
If dataset looks like this:

```<code>ProdictName    Amount    GroupTotal
-----------------------------------
Prod1          10        30
Prod1          20        30
Prod2          10        40
Prod2          20        40
Prod2          30        40
</code>```

Group by ProdictName

We can calculate totals for products like
Sum(Fields!Amount.Value)

Or we can refer to GroupTotal column with First(Fields!GroupTotal.Value)

Is there any reason to use First() function for GroupTotal for dataset contents above?

And what will return Fields!Amount.Value for Prod1? Does it return 10 or 20? What it depends on?

答:
Evaluating field with or without First() function returns identical result inside one group, i.e. there is only two reasons to use the First() function: to get data from another scope or to get real first value for details group. If you need a first value (not for detail group) from current scope, you can just use Fields!Amount.Value.

It's easy to test - just create a tmp table with few columns whitch you should use as groups and one amount column and fill it with random data. Create a test report based on that tmp table with "order by amount desc". Add a groups in this report and a detail group and add for every group an additional columns with Fields!Amount.Value and First(Fields!Amount.Value) fromulas. Now you can see there is no difference for Fields!Amount.Value and First(Fields!Amount.Value) inside one group.

query for dataset

DROP TABLE IF EXISTS
 #rndt;
CREATE TABLE #rndt
(g1     INT
, g2     INT
, g3     INT
, amount DECIMAL(10, 2)
);
DECLARE @cntr1 INT, @cntr2 INT, @cntr3 INT, @cntr4 INT, @cntr1ub INT, @cntr2ub INT, @cntr3ub INT, @cntr4ub INT, @r1 INT, @r2 INT, @r3 INT;
SET @cntr1 = 0;
WHILE @cntr1 < 100
BEGIN
    SET @cntr1 = @cntr1 + 1;
    SET @r1 = ROUND(RAND() * 10000, 0);
    SET @cntr2 = 0;
    SET @cntr2ub = ROUND(RAND() * 10, 0) + 1;
    WHILE @cntr2 < @cntr2ub
        BEGIN
            SET @cntr2 = @cntr2 + 1;
            SET @r2 = ROUND(RAND() * 10000, 0);
            SET @cntr3 = 0;
            SET @cntr3ub = ROUND(RAND() * 10, 0) + 1;
            WHILE @cntr3 < @cntr3ub
                BEGIN
                    SET @cntr3 = @cntr3 + 1;
                    SET @r3 = ROUND(RAND() * 10000, 0);
                    SET @cntr4 = 0;
                    SET @cntr4ub = ROUND(RAND() * 10, 0) + 1;
                    WHILE @cntr4 < @cntr4ub
                        BEGIN
                            SET @cntr4 = @cntr4 + 1;
                            INSERT INTO #rndt
                                   SELECT
                                          @r1
                                        , @r2
                                        , @r3
                                        , ROUND(RAND() * 100000, 2);
                        END;
                END;
        END;
END;
SELECT
   g1
 , g2
 , g3
 , amount
FROM   #rndt
ORDER BY
     amount DESC;
DROP TABLE IF EXISTS
 #rndt;```

Body:
If dataset looks like this:

ProdictName    Amount    GroupTotal
-----------------------------------
Prod1          10        30
Prod1          20        30
Prod2          10        40
Prod2          20        40
Prod2          30        40

Group by ProdictName

We can calculate totals for products like
Sum(Fields!Amount.Value)

Or we can refer to GroupTotal column with First(Fields!GroupTotal.Value)

Is there any reason to use First() function for GroupTotal for dataset contents above?

And what will return Fields!Amount.Value for Prod1? Does it return 10 or 20? What it depends on?


问:
Heap memory chart in Dynatrace
I did the load testing in staging environment and I need to check heap memory usages in dashlets. Currently I am using Dynatrace 7.0 client.

Could you please help me with this?

答:
Dynatrace AppMon can record memory per PurePath or for the complete heap. In your case you are likely looking for a complete heap memory snapshot/analysis.

For this I suggest you take a look at the documentation at memory analysis and memory diagnostics in the documentation.

The memory dashlet is described in more detail at https://www.dynatrace.com/support/doc/appmon/application-monitoring/appmon-client/dashlets/total-memory-dashlet/, basically you just need to open the memory dashlet and trigger a memory dump via "Create Memory Snapshot" and select the agent for the process that you would like to analyze.

Results are displayed in a separate dashlet, see https://www.dynatrace.com/support/doc/appmon/application-monitoring/appmon-client/dashlets/total-memory-dashlet/total-memory-content-dashlet/ for documentation.

Title: Heap memory chart in Dynatrace


问:
Zero should be accepted in the input type number but not Negative values
I am doing some validations for the input type.

```<code><input
    type="number"
    min="0"
    decimal-places=""
    ng-model="candidate.ctc"
    class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
    id="ctc"
    placeholder="CCTC"
    autocomplete="off"
    required="">
</code>```

Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.

So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?

答:
You can use ngPattern to validate the input. But it won't prevent the user from typing a negative number. Use a following function to avoid typing a negative value.

 $(document).ready(function(){
  $("#ctc").keydown(function(e){

        if (e.key == "." || e.key=="-") {
            e.preventDefault();
        }
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Preventing negative values</p>
<input type="number" min="0" max="10" decimal-places="" ng-model="candidate.ctc" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition" id="ctc" placeholder="CCTC" autocomplete="off" style='width:300px' required=""/></code>```

Body:
I am doing some validations for the input type.

<input
    type="number"
    min="0"
    decimal-places=""
    ng-model="candidate.ctc"
    class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
    id="ctc"
    placeholder="CCTC"
    autocomplete="off"
    required="">

Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.

So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?

Body:
You can use ngPattern to validate the input. But it won't prevent the user from typing a negative number. Use a following function to avoid typing a negative value.

 $(document).ready(function(){
  $("#ctc").keydown(function(e){

        if (e.key == "." || e.key=="-") {
            e.preventDefault();
        }
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Preventing negative values</p>
<input type="number" min="0" max="10" decimal-places="" ng-model="candidate.ctc" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition" id="ctc" placeholder="CCTC" autocomplete="off" style='width:300px' required=""/>


问:
PHP - Is dynamic CSS/JS cached by browsers?
I'm including javascript generated by php for each page, like

Will this be cached by browser, so if you would go on another page some js might not work, because the previous page js is used?

If it is, how could I prevent caching?

答:
```<code><?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
</code>```

This should do it.

-michael

Body:
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

This should do it.

-michael


问:
Xcode 9.2 Upload to App Store fails with description length and invalid toolchain errors
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

```<code>find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323
</code>```

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

答:
UPDATE:
Although my option may let you upload the package to iTunesConnect successfully, but may fail when you click Submit for Review.

Check this screenshot

Right-Click on the archive file (.xcarchive) > Show Package Contents > Products > Applications > Right-Click on the app file > Show Package Contents > Double-Click on Info.plist to edit it

Change DTXcodeBuild's value from 9C40b to 9C40 and it will work.

Body:
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."


问:
How to update single value inside specific json array item using redux (Flatlist item click)?
I have a Flatlist with displaying name and status,
I want to toggle status of the user by clicking the  flatlist item click.
I have created the redux action and redux reducer for this purpose .But unable to change the curresponding status.

```<code>itemClick (item,index) {
  const value=false;
  this.props.listItemClick({props:'status',value});
  }

 export default (state = INITIAL_STATE, action) => {
     switch (action.type) {
        case LIST_CLICK:
        console.log(action.payload.props);
            return {...state,[action.payload.props]: action.payload.value};
        default:
            return state;

    }
};
</code>```

but not able change status corresponding to specified user. for example Raj status to false

```<code>{
"response": [{
  "name": "RAJ",
   "status": true

 }, {
 "name": "RAM",
  "status": true,

}]
}

  <FlatList
     showsVerticalScrollIndicator={false}
     removeClippedSubviews={false}
     data={this.props.response}
     ItemSeparatorComponent = {this.flatListItemSeparator}
     ListFooterComponent={this.flatListItemSeparator}
     keyExtractor={(item, index) => index}
     renderItem={({item,index}) => this.renderFlatListItem(item,index)}/>
</code>```

答:
I don't know if this is exactly what you are trying to achieve, but i'll give it a try. </p>

```<code>//call Action
this.props.listItemClick('RAJ',false});

//Action
export const listItemClick = (user,status) => {
    return {
        type: LIST_CLICK,
        payload: { user, status }
    };
};

 export default (state = INITIAL_STATE, action) => {
     switch (action.type) {
        case LIST_CLICK:
            //replace YOUR_DATA with your state var
            return {...state, YOUR_DATA: [state.YOUR_DATA.map((val,index) => {
                   if (val.name === action.payload.user) {
                      return { ...val, status: action.payload.status };
                   }
                   return { ...val };
            })]};
        default:
            return state;

    }
};
</code>```

Body:
I have a Flatlist with displaying name and status,
I want to toggle status of the user by clicking the  flatlist item click.
I have created the redux action and redux reducer for this purpose .But unable to change the curresponding status.

itemClick (item,index) {
  const value=false;
  this.props.listItemClick({props:'status',value});
  }

 export default (state = INITIAL_STATE, action) => {
     switch (action.type) {
        case LIST_CLICK:
        console.log(action.payload.props);
            return {...state,[action.payload.props]: action.payload.value};
        default:
            return state;

    }
};

but not able change status corresponding to specified user. for example Raj status to false

{
"response": [{
  "name": "RAJ",
   "status": true

 }, {
 "name": "RAM",
  "status": true,

}]
}

  <FlatList
     showsVerticalScrollIndicator={false}
     removeClippedSubviews={false}
     data={this.props.response}
     ItemSeparatorComponent = {this.flatListItemSeparator}
     ListFooterComponent={this.flatListItemSeparator}
     keyExtractor={(item, index) => index}
     renderItem={({item,index}) => this.renderFlatListItem(item,index)}/>

Body:
I don't know if this is exactly what you are trying to achieve, but i'll give it a try.

//call Action
this.props.listItemClick('RAJ',false});

//Action
export const listItemClick = (user,status) => {
    return {
        type: LIST_CLICK,
        payload: { user, status }
    };
};

 export default (state = INITIAL_STATE, action) => {
     switch (action.type) {
        case LIST_CLICK:
            //replace YOUR_DATA with your state var
            return {...state, YOUR_DATA: [state.YOUR_DATA.map((val,index) => {
                   if (val.name === action.payload.user) {
                      return { ...val, status: action.payload.status };
                   }
                   return { ...val };
            })]};
        default:
            return state;

    }
};


问:
Empty Modal PopUp in Sitecore
I'm working on displaying a Richtext in MVC Sitecore View.

Below is my code

```<code><div class="modal-body">
@Html.Sitecore().Field("{ACBE8753-2970-****-A022-4C4******4AA}")
</div>
</code>```

When I click on Modal pop up link, I see its empty (below is screenshot). Any suggestions would be much appreciated.

When I put simple HTML content. Its working. But, Rich text or simple text is not working in Modal Pop up:

答: It was because of wrong HTML references. Nothing wrong with Sitecore.</p>

Title: Empty Modal PopUp in Sitecore

Body:
I'm working on displaying a Richtext in MVC Sitecore View.

Below is my code

@Html.Sitecore().Field("{ACBE8753-2970-****-A022-4C4******4AA}")

When I click on Modal pop up link, I see its empty (below is screenshot). Any suggestions would be much appreciated.

When I put simple HTML content. Its working. But, Rich text or simple text is not working in Modal Pop up:


问:
Need samples "setThreadCount" and "setSuiteThreadPoolSize" methods in TestNG and Java
As I'm learning TestNG framework with parallel testing in selenium tests, I don't understand purpose of the setThreadCount and setSuiteThreadPoolSize methods that means I can't see the difference in the result.

I may be wrong so can anyone please provide simple program for understanding the uses of these two methods?

Thanks

Karunagara Pandi

答:
setThreadCount is for setting maximum number of test classes to run concurrently in a testNGxml.

setSuiteThreadPoolSize is for setting maximum number of testNGxmls to execute of a testNG object. This count is applicable when a testNG runner executes more than 1 xml.

Both the methods are part of TestNG class object.


问:
Django TemplateDoesNotExist
Ok so I have a project called tvlistings and an app called progguide.

In my tvlistings directory I have the following in these files

settings.py

```<code>TEMPLATE_DIRS = (
    '/home/paul/tvlistings/progguide/templates',
)
</code>```

urls.py

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^progguide/', include('progguide.urls')),
)
</code>```

In my progguide directory I have

urls.py

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('progguide.views',
    (r'^$', 'index'),
    (r'^(?P<prog_id>\d+)/$', 'programme'),
)
</code>```

views.py

```<code>from django.shortcuts import render_to_response
from progguide.models import *

def index(request):
    chan_prog_list = ChannelProgramme.objects.all().order_by('progdate','starttime')[:5]
    return render_to_response('progguide/index.html', {'chan_prog_list': chan_prog_list})
</code>```

And in /home/paul/tvlistings/progguide/templates I have

index.html

```<code>{% if chan_prog_list % }
    <ul>
    {% for prog in chan_prog_list %}
        <li>{{ prog.channelid.channelname}} {{ prog.programmeid.progtitle }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No programmes.</p>
{% endif %}
</code>```

If I try to load http://localhost:8000/progguide I get

TemplateDoesNotExist at /progguide/

progguide/index.html

Request Method:  GET Request URL:
   http://127.0.0.1:8000/progguide/
  Django Version:  1.2.4 Exception Type:
   TemplateDoesNotExist Exception Value:

progguide/index.html

Still very new to this, the above looks ok from what I understand. What am I missing?

答: The string you pass to render_to_response is the relative path to the template, starting from any of the values you have given in TEMPLATE_DIRS. So, given what you have in that setting, you should just use render_to_response('index.html' , ... ).

Title: Django TemplateDoesNotExist

Body:
Ok so I have a project called tvlistings and an app called progguide.

In my tvlistings directory I have the following in these files

settings.py

TEMPLATE_DIRS = (
    '/home/paul/tvlistings/progguide/templates',
)

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^progguide/', include('progguide.urls')),
)

In my progguide directory I have

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('progguide.views',
    (r'^$', 'index'),
    (r'^(?P<prog_id>\d+)/$', 'programme'),
)

views.py

from django.shortcuts import render_to_response
from progguide.models import *

def index(request):
    chan_prog_list = ChannelProgramme.objects.all().order_by('progdate','starttime')[:5]
    return render_to_response('progguide/index.html', {'chan_prog_list': chan_prog_list})

And in /home/paul/tvlistings/progguide/templates I have

index.html

{% if chan_prog_list % }

    {% for prog in chan_prog_list %}

{{ prog.channelid.channelname}} {{ prog.programmeid.progtitle }}

    {% endfor %}

{% else %}

No programmes.

{% endif %}

If I try to load http://localhost:8000/progguide I get

TemplateDoesNotExist at /progguide/

progguide/index.html

Request Method:  GET Request URL:
   http://127.0.0.1:8000/progguide/
  Django Version:  1.2.4 Exception Type:
   TemplateDoesNotExist Exception Value:

progguide/index.html

Still very new to this, the above looks ok from what I understand. What am I missing?


问:
HTML5 camera capture on Android WebView in Cordova Phonegap
I have built a cordova phonegap application as a prototype.

Because it's a prototype I am basically just linking to a mobile webpage doing the following in the index.html:

```<code><script>window.location = 'http://example.com';</script>
</code>```

On example.com one crucial piece of html is this:

```<code><input name="photo" id="upload-image" type="file" accept="image/*" capture="camera" >
</code>```

In the compiled phonegap app which I compile via build.phonegap.com, after downloading and running the .apk file on Android, when clicking on that file control it only opens the local file browser without camera option.

Is there a way to make this work so that it offers to launch the camera or ideally just directly launches the camera?

When I access the mobile site via Chrome from an Android it works as expected, but when running the compiled apk it seems to be using a different browser that doesn't seem to interpret the tag and its attributes as expected.

答:
It is possible

Add crosswalk pluggin (will replace webview)

https://crosswalk-project.org/documentation/cordova.html

And add camera plugin.

Then add this code to onDeviceReady function (Just for gettiing premissions)

```<code>navigator.camera.getPicture(onSuccess, onFail, {
            quality: 50,
            destinationType: Camera.DestinationType.FILE_URI
        });

        function onSuccess(imageURI) {
            var image = document.getElementById('myImage');
            image.src = imageURI;
        }

        function onFail(message) {
            alert('Failed because: ' + message);
        }
</code>```

Now This should open device camera

```<code><input name="photo" id="upload-image" type="file" accept="image/*" capture="camera" >
</code>```

Body:
I have built a cordova phonegap application as a prototype.

Because it's a prototype I am basically just linking to a mobile webpage doing the following in the index.html:

On example.com one crucial piece of html is this:

<input name="photo" id="upload-image" type="file" accept="image/*" capture="camera" >

In the compiled phonegap app which I compile via build.phonegap.com, after downloading and running the .apk file on Android, when clicking on that file control it only opens the local file browser without camera option.

Is there a way to make this work so that it offers to launch the camera or ideally just directly launches the camera?

When I access the mobile site via Chrome from an Android it works as expected, but when running the compiled apk it seems to be using a different browser that doesn't seem to interpret the tag and its attributes as expected.

Body:
It is possible

Add crosswalk pluggin (will replace webview)

https://crosswalk-project.org/documentation/cordova.html

And add camera plugin.

Then add this code to onDeviceReady function (Just for gettiing premissions)

navigator.camera.getPicture(onSuccess, onFail, {
            quality: 50,
            destinationType: Camera.DestinationType.FILE_URI
        });

        function onSuccess(imageURI) {
            var image = document.getElementById('myImage');
            image.src = imageURI;
        }

        function onFail(message) {
            alert('Failed because: ' + message);
        }

Now This should open device camera

<input name="photo" id="upload-image" type="file" accept="image/*" capture="camera" >


问:
is this Laravel Relationship error undefined variable $task
I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file

```<code>@foreach($task->files as $file) //line 14
                <div>
                    <div><i class="fa fa-check-square-o"></i>
                        <span>

                            <a href="{{ $file->file_url }}" target="_blank">{{ $file->file_name }}</a>

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

and My FileController is this

```<code>use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
    {
         $this->validate($request, [
            'file_name'     => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
        ]);

        $filename     = $request->file('file_name')->getRealPath();

        Cloudder::upload($filename, null);
        list($width, $height) = getimagesize($filename);

$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
        $this->saveUploads($request, $fileUrl, $id,$taskId);
</code>```

and route is this

```<code>Route::post('projects/{projects}/tasks/{tasks}/', [
     'uses' => 'FilesController@uploadAttachments',
     'as'   => 'projects.files',
     'middleware' => ['auth']
]);
</code>```

but got this error

```<code>ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)
</code>```

how can fix this problem?

file Model

```<code>use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public function scopeProject($query, $id)
    {
        return $query->where('project_id', $id);
    }

    public function scopeTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    public function task(){
    return $this->belongsTo(Task::class);
}
</code>```

答:
```<code>public function show($project_id,$task_id) {

$project = Project::find($project_id);
$task = Task::find($task_id);

return view('task.show', ['task' => $task,'project' => $project]);

}
</code>```

Body:
I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file

@foreach($task->files as $file) //line 14

                            file_url }}" target="_blank">{{ $file->file_name }}

and My FileController is this

use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
    {
         $this->validate($request, [
            'file_name'     => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
        ]);

        $filename     = $request->file('file_name')->getRealPath();

        Cloudder::upload($filename, null);
        list($width, $height) = getimagesize($filename);

$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
        $this->saveUploads($request, $fileUrl, $id,$taskId);

and route is this

Route::post('projects/{projects}/tasks/{tasks}/', [
     'uses' => 'FilesController@uploadAttachments',
     'as'   => 'projects.files',
     'middleware' => ['auth']
]);

but got this error

ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)

how can fix this problem?

file Model

use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public function scopeProject($query, $id)
    {
        return $query->where('project_id', $id);
    }

    public function scopeTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    public function task(){
    return $this->belongsTo(Task::class);
}


问:
Struts 2 javassist conflict
I m using a legacy project use struts 2.3 with javassist 3.11.0-Ga.

I want to add mockito with powermock in it but powermock need javassist 3.18.1-GA.

So when i run unit test, sometimes i got classFormatError. I find that problem is caused by javassist, i try tonre run my test with -verbose:class and effectively, i see that powermock class use javassist 3.11 instead of 3.18.

I can t upgrade struts2.3 that use javassist 3.11:( and i want to use the last version of powermock/mockito so how does it possible to force eclipse to use javassist 3.18 in test mode only?

Thanks a lot.

答:
You can't exclude javassist from Struts. Web app doesn't even start with exclude.
The only way to do it properly and this is a pain sometimes, is to get the right lib versions for EVERY dependency you have.

Something that is often heavily ignored by project leader, upgrade regularly.

Title: Struts 2 javassist conflict


问:
Nodejs receiving string instead of boolean
I am trying to send http request to node server with boolean value in the object.

I receive in node req.body:

```<code>somekey: "true"
</code>```

instead of

```<code>somekey: true
</code>```

How can it be fixed?

答:
Use body-parser NPM package.

```<code>var bodyParser = require('body-parser');

//You middleware should have this before the handlers.
app.use(bodyParser.json());
</code>```

EDIT:

This is what your AJAX request should look like. You're probably missing the JSON.stringify part for request body or not setting Content-Type: application/json in your request header. This works for me.

```<code>$.ajax({
    url: "https://example.com/hello/login',

    type: 'POST',

    headers: {
        "Content-Type": "application/json"
    },

    data: JSON.stringify({
        somekey: true
    }),

    success: function(result) {
        console.log(result)
    }
});
</code>```

Body:
I am trying to send http request to node server with boolean value in the object.

I receive in node req.body:

somekey: "true"

instead of

somekey: true

How can it be fixed?

Body:
Use body-parser NPM package.

var bodyParser = require('body-parser');

//You middleware should have this before the handlers.
app.use(bodyParser.json());

EDIT:

This is what your AJAX request should look like. You're probably missing the JSON.stringify part for request body or not setting Content-Type: application/json in your request header. This works for me.

$.ajax({
    url: "https://example.com/hello/login',

    type: 'POST',

    headers: {
        "Content-Type": "application/json"
    },

    data: JSON.stringify({
        somekey: true
    }),

    success: function(result) {
        console.log(result)
    }
});


问:
Remove page count from WooCommerce search page title
When navigating to the next page of search results in Woocommerce, the title shows as

Search results: “example” – Page 2

I would like to know how I can customise this so the page number is not shown. Ideally, it would be nice to be displayed as

Search results for Example

I have looked in the files and this title seems to be called using

```<code><?php woocommerce_page_title(); ?>
</code>```

So there's not much there for me to work on.

There are lots of posts on removing the title all together, nothing on how to customise it.

答:
You can use woocommerce_page_title hook to alter the title
  according to your need.

Here is a working code:

```<code>// define the woocommerce_page_title callback
function filter_woocommerce_page_title($page_title)
{
    if (is_search())
    {
        $page_title = 'Search results for ' . ucfirst(get_search_query());
    }
    return $page_title;
}

// add the filter
add_filter('woocommerce_page_title', 'filter_woocommerce_page_title', 10, 1);
</code>```

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin php files.

Hope this helps!

Body:
When navigating to the next page of search results in Woocommerce, the title shows as

Search results: “example” – Page 2

I would like to know how I can customise this so the page number is not shown. Ideally, it would be nice to be displayed as

Search results for Example

I have looked in the files and this title seems to be called using

<?php woocommerce_page_title(); ?>

So there's not much there for me to work on.

There are lots of posts on removing the title all together, nothing on how to customise it.

Body:
You can use woocommerce_page_title hook to alter the title
  according to your need.

Here is a working code:

// define the woocommerce_page_title callback
function filter_woocommerce_page_title($page_title)
{
    if (is_search())
    {
        $page_title = 'Search results for ' . ucfirst(get_search_query());
    }
    return $page_title;
}

// add the filter
add_filter('woocommerce_page_title', 'filter_woocommerce_page_title', 10, 1);

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin php files.

Hope this helps!


问:
How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?
I am working on a music program that requires multiple JavaScript elements to be in sync with another. I’ve been using setInterval, which works really well initially. However, over time the elements gradually become out of sync which is bad in a music program.

I’ve read online that setTimeout is more accurate, and you can have setTimeout loops somehow. However, I have not found a generic version that illustrates how this is possible.

Basically I have some functions like such:

//drums
setInterval(function {
  //code for the drums playing goes here
}, 8000);

//chords
setInterval(function {
  //code for the chords playing goes here
}, 1000);

//bass
setInterval(function {
  //code for the bass playing goes here
}, 500);
```

It works super well, initially, but over the course of about a minute, the sounds become noticeably out of sync as I’ve read happens with setInterval. I’ve read that setTimeout can be more consistently accurate.

Could someone just show me a basic example of using setTimeout to loop something indefinitely? Alternatively, if there is a way to achieve more synchronous results with setInterval or even another function, please let me know.

答:
Use let instead of var in code :</p>

```<code>for(let i=1;i<=5;i++){setTimeout(()=>{console.log(i)},1000);}
</code>```

Body:
I am working on a music program that requires multiple JavaScript elements to be in sync with another. I’ve been using setInterval, which works really well initially. However, over time the elements gradually become out of sync which is bad in a music program.

I’ve read online that setTimeout is more accurate, and you can have setTimeout loops somehow. However, I have not found a generic version that illustrates how this is possible.

Basically I have some functions like such:

//drums
setInterval(function {
  //code for the drums playing goes here
}, 8000);

//chords
setInterval(function {
  //code for the chords playing goes here
}, 1000);

//bass
setInterval(function {
  //code for the bass playing goes here
}, 500);

It works super well, initially, but over the course of about a minute, the sounds become noticeably out of sync as I’ve read happens with setInterval. I’ve read that setTimeout can be more consistently accurate.

Could someone just show me a basic example of using setTimeout to loop something indefinitely? Alternatively, if there is a way to achieve more synchronous results with setInterval or even another function, please let me know.

Body:
Use let instead of var in code :

for(let i=1;i<=5;i++){setTimeout(()=>{console.log(i)},1000);}


问:
LibGDX ,super Mario tutorial
So I am following the Brent Aureli tutorial of super Mario ,and even after pulling his code from git https://github.com/BrentAureli/SuperMario/blob/Mario-Tutorial-26/core/src/com/brentaureli/mariobros/Sprites/Mario.java

My character does not jump ! even though it runs left and right !
so it was brought to my attention that LibGDX was using a new version so i tried

```<code> private TextureRegion marioStand;
    private Animation<TextureRegion> marioRun;
    private Animation<TextureRegion> marioJump;
</code>```

This is the constructor

```<code>Array<TextureRegion> frames = new Array<TextureRegion>();
        //get run animation frames and add them to marioRun Animation
        for(int i = 1; i < 4; i++)
            frames.add(new TextureRegion(screen.getAtlas().findRegion("little_mario"), i * 16, 0, 16, 16));
       marioRun = new Animation(0.1f, frames);

        frames.clear();

        for(int i = 1; i < 4; i++)
            frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), i * 16, 0, 16, 32));
        bigMarioRun = new Animation(0.1f, frames);

        frames.clear();

        //get set animation frames from growing mario
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 240, 0, 16, 32));
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 0, 0, 16, 32));
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 240, 0, 16, 32));
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 0, 0, 16, 32));
        growMario = new Animation(0.2f, frames);
        frames.clear();
        for(int i = 4; i < 6; i++)
            frames.add(new TextureRegion(screen.getAtlas().findRegion("little_mario"), i * 80, 0, 16, 16));
        marioJump = new Animation(0.1f, frames);
        frames.clear();

 public TextureRegion getFrame(float dt){
 case JUMPING:
               // region = marioIsBig ? bigMarioJump :  marioJump;
                region = (TextureRegion) marioJump.getKeyFrame(stateTimer);
                break;
            case RUNNING:
                region = (TextureRegion) (marioIsBig ? bigMarioRun.getKeyFrame(stateTimer, true) : marioRun.getKeyFrame(stateTimer, true));
                break;
</code>```

答:
I checked the original code and cannot find the actual jump mechanics anywhere in Mario.java. I can see if the vertical velocity of mario is other then 0 it should run the jumping animation. So perhaps, if the falling physics are in place and you run off a cliff you will see the jumping animation playing.

So I guess you just need to apply some force to the character. Something along the lines of b2Body.applyForceToCenter(0f,10f,true) or b2Body.setLinearVelocity(0f, 10f);. This could go into the render method when you check for a key press or if you are using a InputProcessor it can go in the keyDown method.

Title: LibGDX ,super Mario tutorial

Body:
So I am following the Brent Aureli tutorial of super Mario ,and even after pulling his code from git https://github.com/BrentAureli/SuperMario/blob/Mario-Tutorial-26/core/src/com/brentaureli/mariobros/Sprites/Mario.java

My character does not jump ! even though it runs left and right !
so it was brought to my attention that LibGDX was using a new version so i tried

 private TextureRegion marioStand;
    private Animation<TextureRegion> marioRun;
    private Animation<TextureRegion> marioJump;

This is the constructor

Array<TextureRegion> frames = new Array<TextureRegion>();
        //get run animation frames and add them to marioRun Animation
        for(int i = 1; i < 4; i++)
            frames.add(new TextureRegion(screen.getAtlas().findRegion("little_mario"), i * 16, 0, 16, 16));
       marioRun = new Animation(0.1f, frames);

        frames.clear();

        for(int i = 1; i < 4; i++)
            frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), i * 16, 0, 16, 32));
        bigMarioRun = new Animation(0.1f, frames);

        frames.clear();

        //get set animation frames from growing mario
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 240, 0, 16, 32));
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 0, 0, 16, 32));
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 240, 0, 16, 32));
        frames.add(new TextureRegion(screen.getAtlas().findRegion("big_mario"), 0, 0, 16, 32));
        growMario = new Animation(0.2f, frames);
        frames.clear();
        for(int i = 4; i < 6; i++)
            frames.add(new TextureRegion(screen.getAtlas().findRegion("little_mario"), i * 80, 0, 16, 16));
        marioJump = new Animation(0.1f, frames);
        frames.clear();

 public TextureRegion getFrame(float dt){
 case JUMPING:
               // region = marioIsBig ? bigMarioJump :  marioJump;
                region = (TextureRegion) marioJump.getKeyFrame(stateTimer);
                break;
            case RUNNING:
                region = (TextureRegion) (marioIsBig ? bigMarioRun.getKeyFrame(stateTimer, true) : marioRun.getKeyFrame(stateTimer, true));
                break;


问:
Why is the path to a shader in my application nil?
When I try to load a GLSL shader from my iPhone application bundle, the path to it is being reported as nil.  This shader is in my Xcode project.

Pictures are be best way to describe this:

答: Might not be copied to your bundle at build time...  Right click on "Shader.vsh" and select "Get Info" - the the "Targets" tab.  Make sure the checkbox for the target you are calling is checked.</p>


问:
C# NEST Elasticsearch custom filter structure (tokenize)
I am trying to rewrite this specific query to C# NEST, but Im stuck on defining filters... Im confused...

```<code>{
   "settings":{
      "analysis":{
         "filter":{
            "lemmagen_filter_sk":{
               "type":"lemmagen",
               "lexicon":"sk"
            },
            "synonym_filter":{
               "type":"synonym",
               "synonyms_path":"synonyms/sk_SK.txt",
               "ignore_case":true
            },
            "stopwords_SK":{
               "type":"stop",
               "stopwords_path":"stop-‐words/stop‐words-slovak.txt",
               "ignore_case":true
            }
         },
        "analyzer":{
            "slovencina_synonym":{
               "type":"custom",
               "tokenizer":"standard",
               "filter":[
                  "stopwords_SK",
                  "lemmagen_filter_sk",
                  "lowercase",
                  "stopwords_SK",
                  "synonym_filter",
                  "asciifolding"
               ]
            },
            "slovencina":{
               "type":"custom",
               "tokenizer":"standard",
               "filter":[
                  "stopwords_SK",
                  "lemmagen_filter_sk",
                  "lowercase",
                  "stopwords_SK",
                  "asciifolding"
               ]
            },
</code>```

I expect to have right client.CreateIndex(...) command with right index settings.
All I have now is this:

```<code>client.CreateIndex(indexName, c => c
    .InitializeUsing(indexConfig)
    .Mappings(m => m
        .Map<T>(mp => mp.AutoMap())));
</code>```

I cannot find any informations how to do this.
I will be gratefull for any kind of help.

EDIT:

```<code>client.CreateIndex(indexName, c => c
                .InitializeUsing(indexConfig)
                .Settings(s => s
                    .Analysis(a => a
                        .TokenFilters(t => t
                            .UserDefined("lemmagen_filter_sk",
                                new LemmagenTokenFilter { Lexicon = "sk" })
                            .Synonym("synonym_filter", ts => ts
                                .SynonymsPath("synonyms/sk_SK.txt")
                                .IgnoreCase(true))
                            .Stop("stopwords_sk", tst => tst
                                .StopWordsPath("stop-words/stop-words-slovak")
                                .IgnoreCase(true))
                         )
                         .Analyzers(aa => aa
                            .Custom("slovencina_synonym", acs => acs
                            .Tokenizer("standard")
                            .Filters("stopwords_SK", "lemmagen_filter_sk", "lowercase", "stopwords_SK", "synonym_filter", "asciifolding")
                            )
                            .Custom("slovencina", acs => acs
                            .Tokenizer("standard")
                            .Filters("stopwords_SK", "lemmagen_filter_sk", "lowercase", "stopwords_SK", "asciifolding")
                            )
                         )
                     )
                 )
                .Mappings(m => m
                    .Map<DealItem>(mp => mp.AutoMap()
                    .Properties(p => p
                        .Text(t => t
                            .Name(n => n.title_dealitem)
                            .Name(n => n.coupon_text1)
                            .Name(n => n.coupon_text2)
                            .Analyzer("slovencina_synonym")
            )
        ))));
</code>```

This is what i have now, but im getting ERROR after trying to use one

```<code>POST dealitems/_analyze
{
  "analyzer": "slovencina",
  "text":     "Janko kúpil nové topánky"
}
</code>```

ERROR:

```<code>{
  "error": {
    "root_cause": [
      {
        "type": "remote_transport_exception",
        "reason": "[myNode][127.0.0.1:9300][indices:admin/analyze[s]]"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "failed to find analyzer [slovencina]"
  },
  "status": 400
}
</code>```

and GET _settings doesn't show any analyzers

RESULT: Problem was in missing files...wrong paths

答:
Indeed, there is no lemmagen token filter available out of the box in NEST. Hopefully, you can easily create your own:

```<code>public class LemmagenTokenFilter : ITokenFilter
{
    public string Version { get; set; }
    public string Type => "lemmagen";
    [JsonProperty("lexicon")]
    public string Lexicon { get; set; }
}

var response = elasticClient.CreateIndex(_defaultIndex,
    d => d.Settings(s => s
        .Analysis(a => a
            .TokenFilters(t => t.UserDefined("lemmagen_filter_sk",
                new LemmagenTokenFilter
                {
                    Lexicon = "sk"
                }))))
                ..
                );
</code>```

Hope that helps.

Body:
I am trying to rewrite this specific query to C# NEST, but Im stuck on defining filters... Im confused...

{
   "settings":{
      "analysis":{
         "filter":{
            "lemmagen_filter_sk":{
               "type":"lemmagen",
               "lexicon":"sk"
            },
            "synonym_filter":{
               "type":"synonym",
               "synonyms_path":"synonyms/sk_SK.txt",
               "ignore_case":true
            },
            "stopwords_SK":{
               "type":"stop",
               "stopwords_path":"stop-‐words/stop‐words-slovak.txt",
               "ignore_case":true
            }
         },
        "analyzer":{
            "slovencina_synonym":{
               "type":"custom",
               "tokenizer":"standard",
               "filter":[
                  "stopwords_SK",
                  "lemmagen_filter_sk",
                  "lowercase",
                  "stopwords_SK",
                  "synonym_filter",
                  "asciifolding"
               ]
            },
            "slovencina":{
               "type":"custom",
               "tokenizer":"standard",
               "filter":[
                  "stopwords_SK",
                  "lemmagen_filter_sk",
                  "lowercase",
                  "stopwords_SK",
                  "asciifolding"
               ]
            },

I expect to have right client.CreateIndex(...) command with right index settings.
All I have now is this:

client.CreateIndex(indexName, c => c
    .InitializeUsing(indexConfig)
    .Mappings(m => m
        .Map<T>(mp => mp.AutoMap())));

I cannot find any informations how to do this.
I will be gratefull for any kind of help.

EDIT:

client.CreateIndex(indexName, c => c
                .InitializeUsing(indexConfig)
                .Settings(s => s
                    .Analysis(a => a
                        .TokenFilters(t => t
                            .UserDefined("lemmagen_filter_sk",
                                new LemmagenTokenFilter { Lexicon = "sk" })
                            .Synonym("synonym_filter", ts => ts
                                .SynonymsPath("synonyms/sk_SK.txt")
                                .IgnoreCase(true))
                            .Stop("stopwords_sk", tst => tst
                                .StopWordsPath("stop-words/stop-words-slovak")
                                .IgnoreCase(true))
                         )
                         .Analyzers(aa => aa
                            .Custom("slovencina_synonym", acs => acs
                            .Tokenizer("standard")
                            .Filters("stopwords_SK", "lemmagen_filter_sk", "lowercase", "stopwords_SK", "synonym_filter", "asciifolding")
                            )
                            .Custom("slovencina", acs => acs
                            .Tokenizer("standard")
                            .Filters("stopwords_SK", "lemmagen_filter_sk", "lowercase", "stopwords_SK", "asciifolding")
                            )
                         )
                     )
                 )
                .Mappings(m => m
                    .Map<DealItem>(mp => mp.AutoMap()
                    .Properties(p => p
                        .Text(t => t
                            .Name(n => n.title_dealitem)
                            .Name(n => n.coupon_text1)
                            .Name(n => n.coupon_text2)
                            .Analyzer("slovencina_synonym")
            )
        ))));

This is what i have now, but im getting ERROR after trying to use one

POST dealitems/_analyze
{
  "analyzer": "slovencina",
  "text":     "Janko kúpil nové topánky"
}

ERROR:

{
  "error": {
    "root_cause": [
      {
        "type": "remote_transport_exception",
        "reason": "[myNode][127.0.0.1:9300][indices:admin/analyze[s]]"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "failed to find analyzer [slovencina]"
  },
  "status": 400
}

and GET _settings doesn't show any analyzers

RESULT: Problem was in missing files...wrong paths

Body:
Indeed, there is no lemmagen token filter available out of the box in NEST. Hopefully, you can easily create your own:

public class LemmagenTokenFilter : ITokenFilter
{
    public string Version { get; set; }
    public string Type => "lemmagen";
    [JsonProperty("lexicon")]
    public string Lexicon { get; set; }
}

var response = elasticClient.CreateIndex(_defaultIndex,
    d => d.Settings(s => s
        .Analysis(a => a
            .TokenFilters(t => t.UserDefined("lemmagen_filter_sk",
                new LemmagenTokenFilter
                {
                    Lexicon = "sk"
                }))))
                ..
                );

Hope that helps.


问:
How do I use a converter in NativeScript?
I'm trying to use a simple converter in {N}. I have read the docs at https://docs.nativescript.org/core-concepts/data-binding#using-converters-in-bindings about 14 times so far but I do not understand the concept because the documentation seem to be very vague. They use a half finished example of a dateConverter, and they do...

```<code>source.set("dateConverter", dateConverter);
source.set("testDate", new Date());
page.bindingContext = source;
</code>```

...without explaining where is the "source" is coming from or how do they set it up? Also, I already have a page.bindingContext assigned so I don't know how do I relate that to the example provided in the docs.

This is my XML file:

```<code><page navigatingTo="onNavigatingTo" backgroundColor="orange">
    <action-bar title="{{ name, name | uppercase }}" class="action-bar" />

    <stack-layout orientation="vertical" verticalAlignment="center">
        <label text="Welcome to Page-B" textAlignment="center" />
    </stack-layout>
</page>
</code>```

I want the title of the actionBar to be uppercased, so I add an uppercase converter (or at least trying to). Here's the corresponding js file:

```<code>exports.onNavigatingTo = function(args) {
    var page = args.object;
    page.bindingContext = page.navigationContext;

    var uppercase = {
        toView: function(value) {
            console.log(`value: ${value}`);
            return value.toUpperCase();
        }
    }
}
</code>```

I get the error: Cannot find function or filter: uppercase

I know I'm missing some sort of binding somewhere, to bind the converter to something else, but I have no idea how to do this. Anyone could provide a small example based on this?

I have seen this similar question Using nativescript converters but that is not helpful because I am also not using Angular (just plain NativeScript/JS) and that post doesn't have a meaningful, concluded answer either.

答:
Ok, I figured it out what was wrong with Nick's answer, and based on that, this code works:</p>

```<code>exports.onNavigatingTo = function(args) {
    var page = args.object;

    var uppercase = {
        toView: function(value) {
            console.log(`value: ${value}`);
            return value.toUpperCase();
        }
    }

    var myViewModel = page.navigationContext;
    myViewModel.uppercase = uppercase;
    page.bindingContext = myViewModel;
}
</code>```

Body:
I'm trying to use a simple converter in {N}. I have read the docs at https://docs.nativescript.org/core-concepts/data-binding#using-converters-in-bindings about 14 times so far but I do not understand the concept because the documentation seem to be very vague. They use a half finished example of a dateConverter, and they do...

source.set("dateConverter", dateConverter);
source.set("testDate", new Date());
page.bindingContext = source;

...without explaining where is the "source" is coming from or how do they set it up? Also, I already have a page.bindingContext assigned so I don't know how do I relate that to the example provided in the docs.

This is my XML file:

<page navigatingTo="onNavigatingTo" backgroundColor="orange">
    <action-bar title="{{ name, name | uppercase }}" class="action-bar" />

    <stack-layout orientation="vertical" verticalAlignment="center">

    </stack-layout>
</page>

I want the title of the actionBar to be uppercased, so I add an uppercase converter (or at least trying to). Here's the corresponding js file:

exports.onNavigatingTo = function(args) {
    var page = args.object;
    page.bindingContext = page.navigationContext;

    var uppercase = {
        toView: function(value) {
            console.log(`value: ${value}`);
            return value.toUpperCase();
        }
    }
}

I get the error: Cannot find function or filter: uppercase

I know I'm missing some sort of binding somewhere, to bind the converter to something else, but I have no idea how to do this. Anyone could provide a small example based on this?

I have seen this similar question Using nativescript converters but that is not helpful because I am also not using Angular (just plain NativeScript/JS) and that post doesn't have a meaningful, concluded answer either.

Body:
Ok, I figured it out what was wrong with Nick's answer, and based on that, this code works:

exports.onNavigatingTo = function(args) {
    var page = args.object;

    var uppercase = {
        toView: function(value) {
            console.log(`value: ${value}`);
            return value.toUpperCase();
        }
    }

    var myViewModel = page.navigationContext;
    myViewModel.uppercase = uppercase;
    page.bindingContext = myViewModel;
}


问:
Bad Request Your browser sent a request that this server could not understand
Although I am by no means an expert on Ubuntu, I have had two servers running for a couple of years with no problems.

Last night, when attempting to access a local website on one of them I got the error:

```<code>**Bad Request**
Your browser sent a request that this server could not understand.
Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.
</code>```

After several hours of frustration and no success, I rebuilt the server.  While Ubuntu was installing I went to the other server and got the exact same error.
The first server has now been rebuilt and it displays the same error.

I have shut down every computer on the network.  Powered down the router and started over.

In addition to the two servers, the network consists of three windows machines and a Ubuntu desktop.

I have tried isolating the machines from the Internet, I have tried both wired and wireless clients.

Going to localhost on the servers displays the Ubuntu Apache Default page.

The only thing that happened about the time the problem started was the Windows decided to shutdown this machine for an update.  I don't see how this could have caused a problem but I have isolated this machine from the network and the problem exists.

I cleared cookies, used five different browsers, and they all report the same error. I'm about out of ideas, and looking for any suggestions.

答: For newer httpd versions do not support Hyphens in the URL in that case you have to add HttpProtocolOptions unsafe to the httpd.conf file, it works fine after that.</p>

Body:
Although I am by no means an expert on Ubuntu, I have had two servers running for a couple of years with no problems.

Last night, when attempting to access a local website on one of them I got the error:

**Bad Request**
Your browser sent a request that this server could not understand.
Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.

After several hours of frustration and no success, I rebuilt the server.  While Ubuntu was installing I went to the other server and got the exact same error.
The first server has now been rebuilt and it displays the same error.

I have shut down every computer on the network.  Powered down the router and started over.

In addition to the two servers, the network consists of three windows machines and a Ubuntu desktop.

I have tried isolating the machines from the Internet, I have tried both wired and wireless clients.

Going to localhost on the servers displays the Ubuntu Apache Default page.

The only thing that happened about the time the problem started was the Windows decided to shutdown this machine for an update.  I don't see how this could have caused a problem but I have isolated this machine from the network and the problem exists.

I cleared cookies, used five different browsers, and they all report the same error. I'm about out of ideas, and looking for any suggestions.