问:
How to compare current item with the next item in foreach asp.net
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

```<code>foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}
</code>```

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

```<code> <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2016</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }

            <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2017</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }
</code>```

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

答:
Thanks for all. I did it. I did new combined model and used loop for. I think, it's posible variant to answer.

Code model:

```<code>using System.Collections.Generic;

namespace NarkomApp.Models
{
    public class Repairs_RepairsPeriodModel
    {
        public List<REPAIRS> repairsModel { get; set; }
        public List<REPAIRS_PERIOD> repairsPeriodModel { get; set; }
    }
}
</code>```

Code view:

```<code> @for (int i = 0; i < Model.repairsPeriodModel.Count; i++)
            {
                <tr class="line2">
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td style="color: #5f6877;">@Model.repairsPeriodModel[i].vPeriod</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>

                for (int j = 0; j < Model.repairsModel.Count; j++)
                {
                    if (Model.repairsPeriodModel[i].iIdRepairsPeriod == Model.repairsModel[j].fk_iIdRepairsPeriod)
                    {
                        <tr class="line3">
                            <td>@Model.repairsModel[j].vAddress</td>
                            <td>@Model.repairsModel[j].vCreateDate</td>
                            <td>@Model.repairsModel[j].iCountOfFloors</td>
                            <td>@Model.repairsModel[j].iCountOfRooms</td>
                            <td>@Model.repairsModel[j].iAreaOfRooms</td>
                            <td>@Model.repairsModel[j].vLastRepairs</td>
                            <td>@Model.repairsModel[j].vType</td>
                            <td>@Model.repairsModel[j].vBelonging</td>
                            <td>@Model.repairsModel[j].vPlanRepairs</td>
                        </tr>
                    }
                }
            }
</code>```

In the end, I have good table with data:)

Body:
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

                2016

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

                2017

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

Body:
Thanks for all. I did it. I did new combined model and used loop for. I think, it's posible variant to answer.

Code model:

using System.Collections.Generic;

namespace NarkomApp.Models
{
    public class Repairs_RepairsPeriodModel
    {
        public List<REPAIRS> repairsModel { get; set; }
        public List<REPAIRS_PERIOD> repairsPeriodModel { get; set; }
    }
}

Code view:

 @for (int i = 0; i < Model.repairsPeriodModel.Count; i++)
            {
                <tr class="line2">
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td style="color: #5f6877;">@Model.repairsPeriodModel[i].vPeriod</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>

                for (int j = 0; j < Model.repairsModel.Count; j++)
                {
                    if (Model.repairsPeriodModel[i].iIdRepairsPeriod == Model.repairsModel[j].fk_iIdRepairsPeriod)
                    {
                        <tr class="line3">
                            <td>@Model.repairsModel[j].vAddress</td>
                            <td>@Model.repairsModel[j].vCreateDate</td>
                            <td>@Model.repairsModel[j].iCountOfFloors</td>
                            <td>@Model.repairsModel[j].iCountOfRooms</td>
                            <td>@Model.repairsModel[j].iAreaOfRooms</td>
                            <td>@Model.repairsModel[j].vLastRepairs</td>
                            <td>@Model.repairsModel[j].vType</td>
                            <td>@Model.repairsModel[j].vBelonging</td>
                            <td>@Model.repairsModel[j].vPlanRepairs</td>
                        </tr>
                    }
                }
            }

In the end, I have good table with data:)


来源: stackexchange

问:
calling a another function when window size is resized
I have to display Image albums . Till @media element width 700px I can display 3 images per slide , below @media width :700px i need to display 1 image per slide.

For displaying 3 image per slide , I written a function showfilteredImages();

```<code>$scope.imagemaindiv
</code>```

will have all images from backend

```<code>$scope.imagemaindiv = [{
    'img': "image1.png",
    "id": 1
}, {
    'img': "image2.png",
    "id": 2
}, {
    'img': "image3.png",
    "id": 3
}, {
    'img': "image4.png",
    "id": 4
}, {
    'img': "image5.png",
    "id": 5
}, {
    'img': "image6.png",
    "id": 6
}]
$scope._firstImgIndex = 0;
$scope._lastImgIndex = 2;
$scope.showFilteredImages = function() {
    $scope.filteredImages = [];
    for (var i = $scope._firstImgIndex; i <= $scope._lastImgIndex; i++) {
        $scope.filteredImages.push($scope.imagemaindiv[i]);
    }
};
</code>```

答:
Following code might work for you.:).Try for this.</p>

```<code>var data=angular.element($window);
data.bind('resize',function(){

//call your another function here:

});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to display Image albums . Till @media element width 700px I can display 3 images per slide , below @media width :700px i need to display 1 image per slide.

For displaying 3 image per slide , I written a function showfilteredImages();

$scope.imagemaindiv

will have all images from backend

$scope.imagemaindiv = [{
    'img': "image1.png",
    "id": 1
}, {
    'img': "image2.png",
    "id": 2
}, {
    'img': "image3.png",
    "id": 3
}, {
    'img': "image4.png",
    "id": 4
}, {
    'img': "image5.png",
    "id": 5
}, {
    'img': "image6.png",
    "id": 6
}]
$scope._firstImgIndex = 0;
$scope._lastImgIndex = 2;
$scope.showFilteredImages = function() {
    $scope.filteredImages = [];
    for (var i = $scope._firstImgIndex; i <= $scope._lastImgIndex; i++) {
        $scope.filteredImages.push($scope.imagemaindiv[i]);
    }
};

Body:
Following code might work for you.:).Try for this.

var data=angular.element($window);
data.bind('resize',function(){

//call your another function here:

});


问:
Knockout.js: Bind visibility to validationMessage
I am newbie in Knockout.js . I successfully could bind validaionMessage to
 elements. All those
 elements are placed inside a div and that div has special styling for errors. Now, I'd like to show div only when there are some validationMessage available.
How can I do it?

```<code><div class="error-container" >
     <p data-bind="validationMessage: age"></p>
     <p data-bind="validationMessage: sex"></p>
     <p data-bind="validationMessage: name"></p>
</div>
</code>```

PS: I am using version 1.3.0rc .

答:
In KnockoutJS you could do something like this

```<code><!-- ko if: validationMessage -->
<div class="error-container" >
     <p data-bind="validationMessage: age"></p>
     <p data-bind="validationMessage: sex"></p>
     <p data-bind="validationMessage: name"></p>
</div>
<!-- /ko -->
</code>```

If the parametter passed to "ko if" is true, everything inside will be rendered in the view.
The thing is that if I don't know the rest of your code I can't tell what parameter you should pass to the "ko if", but this will give you an idea of how you can achieve what you want.

Body:
I am newbie in Knockout.js . I successfully could bind validaionMessage to
 elements. All those
 elements are placed inside a div and that div has special styling for errors. Now, I'd like to show div only when there are some validationMessage available.
How can I do it?

PS: I am using version 1.3.0rc .

Body:
In KnockoutJS you could do something like this

<!-- ko if: validationMessage -->
<div class="error-container" >
     <p data-bind="validationMessage: age"></p>
     <p data-bind="validationMessage: sex"></p>
     <p data-bind="validationMessage: name"></p>
</div>
<!-- /ko -->

If the parametter passed to "ko if" is true, everything inside will be rendered in the view.
The thing is that if I don't know the rest of your code I can't tell what parameter you should pass to the "ko if", but this will give you an idea of how you can achieve what you want.


问:
Is it possible to restrict the permissions to only allow REST API calls in Bitbucket Server?
I was wondering if it is possible to restrict the credentials of a user to only allow to perform REST API calls (ideally selected ones).

I would like to restrict the user created for Jenkins purposes on to be able to:

trigger the build (using POST commit hook),

update the build status (using Build Status API)

Thanks.

答:
Short answer is - no. There are no specific permission for the REST api.

In details:

A post received hook runs after a push operation. In case of Bitbucket Server it runs also after a merge of a pull request. The documentation says:

The authenticated user must have REPO_WRITE permission for the
  repository that this pull request targets to call this resource.

So, you must give a write access to the user in order to trigger a post-receive hook

According to the documentation:

The authenticated user must have LICENSED permission or higher to call
  this resource.

So you can use a user with minimal permissions


问:
Function Not Working In My Program
My compiler says "too few arguments in the function". I can not figure out what is wrong. Does anyone have any idea on what I am doing wrong?</p>

```<code>#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(int a, int b, int c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}
</code>```

答:
```<code>#include<stdio.h>
#include<math.h>
void  show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(a,b,c);
return ;
}

    void show(int a, int b, int c){
    if(a>c){
        printf("a is the largest number\n");
    } else if(a>b){
        printf("a is smaller than c\n");
    } else if(a<b){
        printf("a is bigger than b\n");
    } else{
        printf("a is the smallest number \n");
    }
 }
</code>```

here is is a complete code please use void in a function because if you use int you need some variable to handle that return variable in this function you don't need int so.try to use return 0 instead of system()

void  show(int a, int b, int c)

int  show(int a, int b, int c)

Title: Function Not Working In My Program

Body:
My compiler says "too few arguments in the function". I can not figure out what is wrong. Does anyone have any idea on what I am doing wrong?

#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(int a, int b, int c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}

Body:
#include<stdio.h>
#include<math.h>
void  show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(a,b,c);
return ;
}

    void show(int a, int b, int c){
    if(a>c){
        printf("a is the largest number\n");
    } else if(a>b){
        printf("a is smaller than c\n");
    } else if(a<b){
        printf("a is bigger than b\n");
    } else{
        printf("a is the smallest number \n");
    }
 }

here is is a complete code please use void in a function because if you use int you need some variable to handle that return variable in this function you don't need int so.try to use return 0 instead of system()

void  show(int a, int b, int c)

int  show(int a, int b, int c)


问:
Button added to custom section header view disappears when row is deleted
Just came across some very strange behavior in my app. I've recreated the problem in a simplest-case scenario:

```<code>NSMutableArray *data;

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [[NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil] retain];
}

- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
    header.backgroundColor = [UIColor lightGrayColor];
    [header addSubview:self.button];
    return header;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
    cell.textLabel.text = [data objectAtIndex:indexPath.row];
    return cell;
}

- (void)dealloc {
    [super dealloc];
}
</code>```

Every time I delete a row; the button in my header disappears! This happens no matter what type of rowAnimation I use. If I scroll the table up so that the header scrolls off; the button returns when the header returns. The button is created in the xib file.

I can work around it in one of 2 ways:

Reloading the tableView data after the delete; with a delay so that the deletion animation completes first.

Creating the button in viewForHeaderInSection instead of in the interfaceBuilder.

I'd really like to understand what's going on here. Where is the button going? I've confirmed that viewForHeaderInSection is called when I delete a row.

Edit I tried changing it so that the button is created in viewForHeader, instead of in the xib, but it's causing other strange issues... when I create or delete the button, I am setting certain properties such as the title and enabled depending on how many items there are in the table. When I delete the last row in the table, I don't see the update in text and enabled status until I scroll the button off the screen and back on again.

答:
Well I at least managed to get around my issue... I made an iVar and property for the view that I create in viewForheaderAtSection, and then I only create a new view if I don't have one already. Otherwise I just return the header I already had; something like this:

```<code>- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    if (!self.myHeader){
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
        header.backgroundColor = [UIColor lightGrayColor];
        [header addSubview:self.button];
        self.myHeader = header;
        [header release];
    }
    return self.myHeader;
}
</code>```

This works, but it would still be great to understand what exactly is going on. As far as I can tell, viewForHeaderInSection is being called by the system, but then the instance of the view that I return in that method is not actually being used / shown; at least not until I do something that causes the view to redraw...

ContentLicense: CC BY-SA 2.5

Body:
Just came across some very strange behavior in my app. I've recreated the problem in a simplest-case scenario:

NSMutableArray *data;

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [[NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil] retain];
}

- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
    header.backgroundColor = [UIColor lightGrayColor];
    [header addSubview:self.button];
    return header;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
    cell.textLabel.text = [data objectAtIndex:indexPath.row];
    return cell;
}

- (void)dealloc {
    [super dealloc];
}

Every time I delete a row; the button in my header disappears! This happens no matter what type of rowAnimation I use. If I scroll the table up so that the header scrolls off; the button returns when the header returns. The button is created in the xib file.

I can work around it in one of 2 ways:

Reloading the tableView data after the delete; with a delay so that the deletion animation completes first.

Creating the button in viewForHeaderInSection instead of in the interfaceBuilder.

I'd really like to understand what's going on here. Where is the button going? I've confirmed that viewForHeaderInSection is called when I delete a row.

Edit I tried changing it so that the button is created in viewForHeader, instead of in the xib, but it's causing other strange issues... when I create or delete the button, I am setting certain properties such as the title and enabled depending on how many items there are in the table. When I delete the last row in the table, I don't see the update in text and enabled status until I scroll the button off the screen and back on again.

Body:
Well I at least managed to get around my issue... I made an iVar and property for the view that I create in viewForheaderAtSection, and then I only create a new view if I don't have one already. Otherwise I just return the header I already had; something like this:

- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    if (!self.myHeader){
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
        header.backgroundColor = [UIColor lightGrayColor];
        [header addSubview:self.button];
        self.myHeader = header;
        [header release];
    }
    return self.myHeader;
}

This works, but it would still be great to understand what exactly is going on. As far as I can tell, viewForHeaderInSection is being called by the system, but then the instance of the view that I return in that method is not actually being used / shown; at least not until I do something that causes the view to redraw...


问:
Ionic 2: Loading screen does not get dismissed
I have an application made with Ionic 2, The work flow is like this

Case A . When user is using app for the first time

User Logs in (loading is shown)

When successfully logged in loading window is hidden and user is forwarded to Dashboard page.

In dashboard page items are loaded via ajax request.

Case B. When user is already logged in before

The first screen is Dashboard and items are loaded via ajax request.

Problem

In case A, when user logs in and forwarded to DashboardPage, the loading screen doesn't gets dismissed. Sometimes it gets dismissed but most of the time it doesnot? Is this an ionic bug or am I doing something wrong??

Here is my DashboardPage

```<code>//imports here

export class DashboardPage {
    public loadingmsg: any;
    public ajaxRequest: any;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private webservice: WebService,
        private loadingCtrl: LoadingController
    )
    {
        this.loadDashboardContents();
    }

    loadDashboardContents(){
        //other codes
        this.loadingmsg = this.loadingCtrl.create({
            content:"Loading contents, please wait..."
        });

        this.loadingmsg.present();

        this.ajaxRequest = this.webservice.getDashboardContents(params).subscribe(data => {
            this.loadingmsg.dismiss().then(()=>{
                //other codes to save retrieved data to localstorage.
            });
        });
    }
}
</code>```

UPDATE
The login method from login page

```<code>loginUser(){
    this.loading=this.loadingctrl.create({
            content:"Logging in, please wait..."
     });

     this.loading.present();

     this.ajaxRequest = this.webservice.loginUser(params).subscribe(data => {
        this.loading.dismiss();
        if(data.status =="ok"){
            this.navctrl.push(DashboardPage).then(()=>{
                const index = this.viewCtrl.index;
                this.navctrl.remove(index);
            });
        }else{
            //show error alert
        }
     }, err =>{
        this.loading.dismiss();
     });

}
</code>```

My Ionic and cordova version information

```<code>Ionic Framework: 3.5.0
Ionic App Scripts: 1.3.9
Angular Core: 4.1.3
Angular Compiler CLI: 4.1.3
Node: 6.10.3
OS Platform: Windows 10
Cordova Version: 6.5.0
</code>```

答:
I am currently using loading in my project and it works well in all case. To ensure loading will always dismiss you need to add some code:

1. duration, dismissOnPageChange

```<code>let loading = this.loadingCtrl.create({
   content: "",
   duration: 5000, //ms
   dismissOnPageChange: true
})
</code>```

2. dissmis when ajax call success or error:

```<code>.subscribe(success=>{
  //some code
  loading.dismiss();
},error=>{
  //some code
  loading.dismiss();
})
</code>```

Body:
I have an application made with Ionic 2, The work flow is like this

Case A . When user is using app for the first time

User Logs in (loading is shown)

When successfully logged in loading window is hidden and user is forwarded to Dashboard page.

In dashboard page items are loaded via ajax request.

Case B. When user is already logged in before

The first screen is Dashboard and items are loaded via ajax request.

Problem

In case A, when user logs in and forwarded to DashboardPage, the loading screen doesn't gets dismissed. Sometimes it gets dismissed but most of the time it doesnot? Is this an ionic bug or am I doing something wrong??

Here is my DashboardPage

//imports here

export class DashboardPage {
    public loadingmsg: any;
    public ajaxRequest: any;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private webservice: WebService,
        private loadingCtrl: LoadingController
    )
    {
        this.loadDashboardContents();
    }

    loadDashboardContents(){
        //other codes
        this.loadingmsg = this.loadingCtrl.create({
            content:"Loading contents, please wait..."
        });

        this.loadingmsg.present();

        this.ajaxRequest = this.webservice.getDashboardContents(params).subscribe(data => {
            this.loadingmsg.dismiss().then(()=>{
                //other codes to save retrieved data to localstorage.
            });
        });
    }
}

UPDATE
The login method from login page

loginUser(){
    this.loading=this.loadingctrl.create({
            content:"Logging in, please wait..."
     });

     this.loading.present();

     this.ajaxRequest = this.webservice.loginUser(params).subscribe(data => {
        this.loading.dismiss();
        if(data.status =="ok"){
            this.navctrl.push(DashboardPage).then(()=>{
                const index = this.viewCtrl.index;
                this.navctrl.remove(index);
            });
        }else{
            //show error alert
        }
     }, err =>{
        this.loading.dismiss();
     });

}

My Ionic and cordova version information

Ionic Framework: 3.5.0
Ionic App Scripts: 1.3.9
Angular Core: 4.1.3
Angular Compiler CLI: 4.1.3
Node: 6.10.3
OS Platform: Windows 10
Cordova Version: 6.5.0

Body:
I am currently using loading in my project and it works well in all case. To ensure loading will always dismiss you need to add some code:

1. duration, dismissOnPageChange

let loading = this.loadingCtrl.create({
   content: "",
   duration: 5000, //ms
   dismissOnPageChange: true
})

2. dissmis when ajax call success or error:

.subscribe(success=>{
  //some code
  loading.dismiss();
},error=>{
  //some code
  loading.dismiss();
})


问:
Crystal Report showing blank page
I am new to Crystal report, using a tutorial i have created a report in VS.2012 and Crystal Report "CRforVS_13_0_5". When i run this report, it shows nothing but a bank page. Even the toolbar of "Crystal Report Viewer" is not shown.

I have searched a lot on google and in Stackoverflow, but none of the solutions given helped me with this.

The steps i have followed to create this report is as below:

Created a DataSet.

Added a Crystal Report into my web project.

Added a new Form "Default.aspx" into my project and added a button into it.

Typed below code in on click event of the code.

My code:

```<code>protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection CN;
    String MyConnectionString = "";
    MyConnectionString = "data source=.; initial catalog=Test; user id=sa; password=Abc1234";

    CN = new SqlConnection(MyConnectionString);
    CN.Open();

    string SQL = null;
    SQL = "SELECT * FROM UserInformation ORDER BY Username";

    SqlDataAdapter myDA = new SqlDataAdapter(SQL,CN);
    CN.Close();

    DatasetEmp DS = new DatasetEmp();
    myDA.Fill(DS,"UserInformation");

    ReportDocument myRPT = new ReportDocument();
    myRPT.Load(Server.MapPath("~/CrystalReportEmp.rpt"));
    myRPT.SetDataSource(DS);

    CrystalReportViewer1.ReportSource = myRPT;
}
</code>```

After i run the code, it shows nothing.
like below picture.

答: You need to place aspnet_client files in application folder. If issue not resolved you need to check console errors in browser with press key F12 then you can place the Crystal Report files in specified folder in application.

Title: Crystal Report showing blank page

Body:
I am new to Crystal report, using a tutorial i have created a report in VS.2012 and Crystal Report "CRforVS_13_0_5". When i run this report, it shows nothing but a bank page. Even the toolbar of "Crystal Report Viewer" is not shown.

I have searched a lot on google and in Stackoverflow, but none of the solutions given helped me with this.

The steps i have followed to create this report is as below:

Created a DataSet.

Added a Crystal Report into my web project.

Added a new Form "Default.aspx" into my project and added a button into it.

Typed below code in on click event of the code.

My code:

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection CN;
    String MyConnectionString = "";
    MyConnectionString = "data source=.; initial catalog=Test; user id=sa; password=Abc1234";

    CN = new SqlConnection(MyConnectionString);
    CN.Open();

    string SQL = null;
    SQL = "SELECT * FROM UserInformation ORDER BY Username";

    SqlDataAdapter myDA = new SqlDataAdapter(SQL,CN);
    CN.Close();

    DatasetEmp DS = new DatasetEmp();
    myDA.Fill(DS,"UserInformation");

    ReportDocument myRPT = new ReportDocument();
    myRPT.Load(Server.MapPath("~/CrystalReportEmp.rpt"));
    myRPT.SetDataSource(DS);

    CrystalReportViewer1.ReportSource = myRPT;
}

After i run the code, it shows nothing.
like below picture.


问:
How to get updated data after editing through post request in angular 2
I have searched a lot on this but cannot understand how to get updated data from database. I am learning angular 2 and my situation is that I am fetching the data from table named branches using php in angular 2. Here is my Service in angular 2 project

```<code>import { Injectable } from '@angular/core';
import {Http, Headers, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import "rxjs/add/observable/throw";
import { Observable } from "rxjs/Observable";

@Injectable()
export class BranchesService {

  constructor(private _http: Http){}
  _errorHandler(error: Response){
    console.error(error);
    return Observable.throw(error || "Internal server error");
  }

  getBranches(limit, offset){
    console.log("I am called");
    return this._http.get("http://localhost/churchDb/api/v1/branches/"+limit+"/"+offset)
                .map((response: Response) => response.json())
                .catch(this._errorHandler);
  }

  updateBranch(value){
    let headers = new Headers();
    headers.append("Content-Type","application/json; charset=utf-8");
    return this._http.post("http://localhost/churchDb/api/v1/update-branch", value , headers )
      .map((response: Response) =>
        response.json()
      )
      .catch(this._errorHandler);
  }

}
</code>```

And in my branches Component I am subscribing to getBranches in branches service

```<code>branches=[];
ngOnInit() {
    this.branches=[];
    this.sub=this._branchesService.getBranches(this.limit,this.offset)
      .subscribe(
        (resBranchesData)=> {
          this.errorMsg=resBranchesData.message;
          this.branches=resBranchesData.data;
          console.log("Updated : " + JSON.stringify(resBranchesData));
        },
        (resBranchesError)=>{
          console.log(resBranchesError)
        }
      );
  }
</code>```

And displaying branches in my View

```<code><table class="table table-bordered">
      <thead>
        <tr>
          <th>#</th>
          <th>First Name</th>
          <th>Address</th>
          <th>City</th>
          <th>Actions</th>
          <!--<th>Username</th>-->
        </tr>
      </thead>
      <tbody *ngFor="let branch of branches" style="text-align: left">
        <tr>
          <td>{{ branch.id }}</td>
          <td>{{ branch.name }}</td>
          <td>{{ branch.address }}</td>

          <div *ngFor="let city of cities">
            <td *ngIf="city.id == branch.city" style="border:none">
              {{ city.name }}
            </td>
          </div>
          <td><button class="btn btn-default" (click)="edit(branch)" >edit</button><button class="btn btn-danger" (click)="openModal()" style="margin-left: 10px">delete</button></td>
        </tr>
      </tbody>
    </table>
</code>```

On clicking edit I display a pre-filed form in modal in the same view

```<code><modal [animation]="animation" [keyboard]="keyboard" [backdrop]="backdrop" [cssClass]="cssClass" #modal>
  <form #branchEditForm="ngForm"  (ngSubmit)="updateBranch(branchEditForm.value)">
    <modal-header [show-close]="true">
      <h4 class="modal-title">Add Church Branch</h4>
    </modal-header>
    <modal-body>
      <div class="form-group">
        <input type="hidden" class="form-control" required name="id" id="id" ngModel="{{branch.id}}">
        <label>Church Name</label>
        <input type="text" class="form-control" required name="name" id="name" ngModel="{{branch.name}}">
      </div>
      <div class="form-group">
        <label>Address</label>
        <input type="text" class="form-control" required name="address" id="address" ngModel="{{branch.address}}">
      </div>
      <div class="form-group">
        <label>Address</label>
        <select class="form-control" name="city" ngModel="{{branch.city}}">
            <option *ngFor="let city of cities" value="{{city.id}}" [attr.selected]="city.id == branch.city ? '' : selected" >{{city.name}}</option>
        </select>
      </div>

    </modal-body>
    <modal-footer>
      <button type="button" class="btn btn-default" data-dismiss="modal" (click)="modal.dismiss()">Cancel</button>
      <!--<button type="button" class="btn btn-primary" [disabled]="!modalForm.valid" (click)="validationModal.close()">Update</button>-->
      <input type="submit" class="btn btn-primary" [disabled]="!branchEditForm.valid" value="Update" />
    </modal-footer>
  </form>
</modal>
</code>```

Upon submitting the form in branches Component

```<code>updateBranch(value:any){
    console.log(value);
    this._branchesService.updateBranch(value)
      .subscribe(
        (response)=>{
          if(response.code == "200"){
            this.modal.close();
            this._router.navigate(['branches']);
          }else{
            // this.showFlag=true;
            // this.loadingFlag=false;
            // this.error=response.message;
          }
        },
        (error) =>{ this.error=error }
      )
  }
</code>```

The above function successfully updates the data in database table but I cant get the updated data in branches Service.
I see the updated data only after clearing the cache of my browser.
I have also tried navigating from a different component with no luck.
I have also figured if the url in post request is changed, it gets me updated data.
What am I doing wrong? I am new to angular 2 and cannot figure the reason. Any help is much appreciated.

答:
There are two ways to achieve this.

Method 1: Return updated records in your updateBranch service.

This means, in your server-side api call, return the updated list from the database, so that every time you call your update service, the updated list is returned:

```<code>this._branchesService.updateBranch(value)
    .subscribe(
        (response) => {
            this.modal.close();
            //this will only work if your server return the updated list.
            this.branches=response.data;
        })
</code>```

Suggestion: You do not need to check the response.code anywhere in your service or component, if you are using observables. Angular2 automatically wraps any response status code in between 200 to 300 as error, and you can handle them at .error()

Method 2: use .flatMap() to get the updated list, right after update.

In the event you have no control over the API implementation, aka they can't give you the response directly in the update service, then you will need to manually call getBranches again right after the update.

So what you can do is you use a .flatMap(). flatMap will wait for the previous Observables to finish executing, and then proceed to execute the next one (think .then() in promise):

```<code>updateBranch(value: any) {
    this._branchesService.updateBranch(value)
        .flatMap((response) => {
                if (response.code == "200") {
                    this.modal.close();
                    return this._branchesServcice.getBranches(this.limit, this.offset);
                } else {
                    // this.showFlag=true;
                    // this.loadingFlag=false;
                    // this.error=response.message;
                    //return Observable.empty if fails
                    return Observable.empty();
                }
            }
        )
        .subscribe((resBranchesData)=>{
            //do whatever you want after retrieving the branches
        })

}
</code>```

Body:
I have searched a lot on this but cannot understand how to get updated data from database. I am learning angular 2 and my situation is that I am fetching the data from table named branches using php in angular 2. Here is my Service in angular 2 project

import { Injectable } from '@angular/core';
import {Http, Headers, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import "rxjs/add/observable/throw";
import { Observable } from "rxjs/Observable";

@Injectable()
export class BranchesService {

  constructor(private _http: Http){}
  _errorHandler(error: Response){
    console.error(error);
    return Observable.throw(error || "Internal server error");
  }

  getBranches(limit, offset){
    console.log("I am called");
    return this._http.get("http://localhost/churchDb/api/v1/branches/"+limit+"/"+offset)
                .map((response: Response) => response.json())
                .catch(this._errorHandler);
  }

  updateBranch(value){
    let headers = new Headers();
    headers.append("Content-Type","application/json; charset=utf-8");
    return this._http.post("http://localhost/churchDb/api/v1/update-branch", value , headers )
      .map((response: Response) =>
        response.json()
      )
      .catch(this._errorHandler);
  }

}

And in my branches Component I am subscribing to getBranches in branches service

branches=[];
ngOnInit() {
    this.branches=[];
    this.sub=this._branchesService.getBranches(this.limit,this.offset)
      .subscribe(
        (resBranchesData)=> {
          this.errorMsg=resBranchesData.message;
          this.branches=resBranchesData.data;
          console.log("Updated : " + JSON.stringify(resBranchesData));
        },
        (resBranchesError)=>{
          console.log(resBranchesError)
        }
      );
  }

And displaying branches in my View

          #
          First Name
          Address
          City
          Actions

          {{ branch.id }}
          {{ branch.name }}
          {{ branch.address }}

              {{ city.name }}

          <button class="btn btn-default" (click)="edit(branch)" >edit</button><button class="btn btn-danger" (click)="openModal()" style="margin-left: 10px">delete</button>

On clicking edit I display a pre-filed form in modal in the same view

<modal [animation]="animation" [keyboard]="keyboard" [backdrop]="backdrop" [cssClass]="cssClass" #modal>
  <form #branchEditForm="ngForm"  (ngSubmit)="updateBranch(branchEditForm.value)">
    <modal-header [show-close]="true">

Add Church Branch

    </modal-header>
    <modal-body>

        <input type="hidden" class="form-control" required name="id" id="id" ngModel="{{branch.id}}">
        Church Name
        <input type="text" class="form-control" required name="name" id="name" ngModel="{{branch.name}}">

        Address
        <input type="text" class="form-control" required name="address" id="address" ngModel="{{branch.address}}">

        Address
        <select class="form-control" name="city" ngModel="{{branch.city}}">
            <option *ngFor="let city of cities" value="{{city.id}}" [attr.selected]="city.id == branch.city ? '' : selected" >{{city.name}}</option>
        </select>

    </modal-body>
    <modal-footer>
      <button type="button" class="btn btn-default" data-dismiss="modal" (click)="modal.dismiss()">Cancel</button>

      <input type="submit" class="btn btn-primary" [disabled]="!branchEditForm.valid" value="Update" />
    </modal-footer>
  </form>
</modal>

Upon submitting the form in branches Component

updateBranch(value:any){
    console.log(value);
    this._branchesService.updateBranch(value)
      .subscribe(
        (response)=>{
          if(response.code == "200"){
            this.modal.close();
            this._router.navigate(['branches']);
          }else{
            // this.showFlag=true;
            // this.loadingFlag=false;
            // this.error=response.message;
          }
        },
        (error) =>{ this.error=error }
      )
  }

The above function successfully updates the data in database table but I cant get the updated data in branches Service.
I see the updated data only after clearing the cache of my browser.
I have also tried navigating from a different component with no luck.
I have also figured if the url in post request is changed, it gets me updated data.
What am I doing wrong? I am new to angular 2 and cannot figure the reason. Any help is much appreciated.

Body:
There are two ways to achieve this.

Method 1: Return updated records in your updateBranch service.

This means, in your server-side api call, return the updated list from the database, so that every time you call your update service, the updated list is returned:

this._branchesService.updateBranch(value)
    .subscribe(
        (response) => {
            this.modal.close();
            //this will only work if your server return the updated list.
            this.branches=response.data;
        })

Suggestion: You do not need to check the response.code anywhere in your service or component, if you are using observables. Angular2 automatically wraps any response status code in between 200 to 300 as error, and you can handle them at .error()

Method 2: use .flatMap() to get the updated list, right after update.

In the event you have no control over the API implementation, aka they can't give you the response directly in the update service, then you will need to manually call getBranches again right after the update.

So what you can do is you use a .flatMap(). flatMap will wait for the previous Observables to finish executing, and then proceed to execute the next one (think .then() in promise):

updateBranch(value: any) {
    this._branchesService.updateBranch(value)
        .flatMap((response) => {
                if (response.code == "200") {
                    this.modal.close();
                    return this._branchesServcice.getBranches(this.limit, this.offset);
                } else {
                    // this.showFlag=true;
                    // this.loadingFlag=false;
                    // this.error=response.message;
                    //return Observable.empty if fails
                    return Observable.empty();
                }
            }
        )
        .subscribe((resBranchesData)=>{
            //do whatever you want after retrieving the branches
        })

}


问:
Can I write a test without any assert in it?
I'd like to know if it is "ok" to write a test without any "assert" in it. So the test would fail only when an exception / error has occured.

Eg: like a test which has a simple select query, to ensure that the database configuration is right. So when I change some db-configuration, I re-run this test and check if the configuration is right. ?

Thanks!

答: the purpose of the test is to check if "X" has an "expected something", in order to check that "expected something" is correct to assert, to expect or to verify. This is why most frameworks implements those methods in a way or another</p>


问:
Open file by URL
I have FileOpener class for open documents by URL:

```<code>public class FileOpener {

    private FileOpener() {
    }

    private static String url;
    private static Uri uri;
    private static Intent intent;

    public static void open(Context context, FileDTO fileDTO) {
        fileDTO.setUrl("https://calibre-ebook.com/downloads/demos/demo.docx");
        setupBase(fileDTO);
        checkFileTypeByUrl();

        try {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void checkFileTypeByUrl() {

    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
    intent.setDataAndType(uri, mimeType);
    }

    private static void setupBase(FileDTO fileDTO) {
        url = fileDTO.getUrl();
        uri = Uri.parse(url);
        intent = new Intent(Intent.ACTION_VIEW, uri);
    }
}
</code>```

In activity/fragment it's look like this:

```<code>    @Override
    public void openOrDownloadFile(FileDTO file) {
        FileOpener.open(getContext(), file);
    }
</code>```

It's work fine for PDF/Txt documents, but for MsWord/MsExcel/MsPowerPoint have ActivityNotFoundException (I have word/excel/powerpoint on my device, which opening from other applications without problem)

Stacktrace:

W/System.err: android.content.ActivityNotFoundException: No Activity
  found to handle Intent { act=android.intent.action.VIEW
  dat=https://calibre-ebook.com/downloads/demos/demo.docx
  typ=application/vnd.openxmlformats-officedocument.wordprocessingml.document
  flg=0x4000000 }

What could be the problem?

答:
try this using web view you can load your file from url</p>

```<code>WebView webview = (WebView)findViewById(R.id.containWebView);
webview.setWebViewClient(new AppWebViewClients());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.loadUrl("http://docs.google.com/gview?embedded=true&url="
            + "YOUR_DOC_URL_HERE");

 public class AppWebViewClients extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
    view.loadUrl(url);
    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    // TODO Auto-generated method stub
    super.onPageFinished(view, url);

}
}
</code>```

Title: Open file by URL

Body:
I have FileOpener class for open documents by URL:

public class FileOpener {

    private FileOpener() {
    }

    private static String url;
    private static Uri uri;
    private static Intent intent;

    public static void open(Context context, FileDTO fileDTO) {
        fileDTO.setUrl("https://calibre-ebook.com/downloads/demos/demo.docx");
        setupBase(fileDTO);
        checkFileTypeByUrl();

        try {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void checkFileTypeByUrl() {

    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
    intent.setDataAndType(uri, mimeType);
    }

    private static void setupBase(FileDTO fileDTO) {
        url = fileDTO.getUrl();
        uri = Uri.parse(url);
        intent = new Intent(Intent.ACTION_VIEW, uri);
    }
}

In activity/fragment it's look like this:

    @Override
    public void openOrDownloadFile(FileDTO file) {
        FileOpener.open(getContext(), file);
    }

It's work fine for PDF/Txt documents, but for MsWord/MsExcel/MsPowerPoint have ActivityNotFoundException (I have word/excel/powerpoint on my device, which opening from other applications without problem)

Stacktrace:

W/System.err: android.content.ActivityNotFoundException: No Activity
  found to handle Intent { act=android.intent.action.VIEW
  dat=https://calibre-ebook.com/downloads/demos/demo.docx
  typ=application/vnd.openxmlformats-officedocument.wordprocessingml.document
  flg=0x4000000 }

What could be the problem?

Body:
try this using web view you can load your file from url

WebView webview = (WebView)findViewById(R.id.containWebView);
webview.setWebViewClient(new AppWebViewClients());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.loadUrl("http://docs.google.com/gview?embedded=true&url="
            + "YOUR_DOC_URL_HERE");

 public class AppWebViewClients extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
    view.loadUrl(url);
    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    // TODO Auto-generated method stub
    super.onPageFinished(view, url);

}
}


问:
Predicate inside a Where<> query not hit?
I need to call the method for each item in the list. So, I have used Where<> query as follows,

```<code>List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});
</code>```

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

答:
The CheckName() method is not executed because of Deferred execution of Linq. The actual statement is not executed till you actually access it. So in your case, for the CheckName(), you should do something like:

```<code>var name = list.Where(n =>
{
    return CheckName(n);
}).ToList();
</code>```

Body:
I need to call the method for each item in the list. So, I have used Where<> query as follows,

List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

Body:
The CheckName() method is not executed because of Deferred execution of Linq. The actual statement is not executed till you actually access it. So in your case, for the CheckName(), you should do something like:

var name = list.Where(n =>
{
    return CheckName(n);
}).ToList();


问:
Ajax File download Issue
I am downloading a dynamic file in my application, simulating ajax using iframes. What I am doing is, when the download request is made, I will create a dynamic invisible iframe, and set the src of  my iframe as the download url.I am able to successfully download the file, but the requirement is to show a download indicator once the download starts and that should finish as soon as the download dialog comes up.I provided call back after iframe creation to show the download indicator, which is successfully working, and provided another method on the 'onload' of the iframe, expecting it will be invoked, when the download dialog comes up. But unfortunately, that is not working, and because of that even after the download completes, my progress indicator is still there. I am not able to remove that. Then I came to realize that the since the content type of the response is not html, it will be served by a separate process, which leads to the download dialog and because of that my onload method is never getting called. Please let me know a solution for this.</p>

答:
You should start a timer in the client when the download request is made which tests the state of the iframe at a specified interval:</p>

```<code>if ( ( iframe.document && iframe.document.readyState == 'complete' )
    || iframe.contentDocument )
{
    stopTimer();
    closePopupDialog();
}
</code>```

Title: Ajax File download Issue

Body:
You should start a timer in the client when the download request is made which tests the state of the iframe at a specified interval:

if ( ( iframe.document && iframe.document.readyState == 'complete' )
    || iframe.contentDocument )
{
    stopTimer();
    closePopupDialog();
}


问:
Share common components between two react native applications
I have an existing react native application with certain custom components I made. Now I'm trying to make a new application and use some of those components, so there's no need to copy/paste when changes occur. Let's name these applications app1 and app2.

Here's what I tried:

keeping the file structure
app1 =>
src,
node_modules,
ios, etc

app2 =>
   src,
   node_modules,
   ios, etc

shared_folder =>
   components,
   node_modules

that didn't work because the shared_folder needed node_modules to import react, react-native, etc. Npm complained of all the duplicate node modules it was looking at

Then I tried the structure

app_folder =>
      node_modules,
      app1,
      app2,
      shared_folder

That didn't work because when running npm start, it didn't know which index.ios.js to look for. Also, xcode for both app1 and app2 projects kept complaining about finding certain react files.

My question is, what's the best way to structure these 2 applications so I can share certain components between them?

答: not sure i understand your exact scenario but usually shared components that make sense for more than one project should go in their own module (you could create private scoped npm packages).  assuming there's some logic that groups them together</p>


问:
How to get a zip of the npm mysql package that is installed globally?
I am a beginner and i am currently making a chat bot using amazon lambda and i need to upload that npm-mysql package as a zip in AWS lambda, so that i can use it.So how to create a zip of this npm-mysql package that is installed globally in my system and where can i find the npm-mysql package in my system for zipping it? </p>

答:
Dont install the package globally.
A good practice is to create your own package.json and then zip up your code + the node modules.
What this would look like is something like this:

```<code><project-folder>
   |
   |--index.js (Your code)
   |--package.json (this has details including the packages your use)
   |--node_modules
          |-- This contains all the modules you need
</code>```

Once you have this structure you can just zip this up and upload to lambda.A
You can create the package.json file using npm init and filling in the details.
For dependencies do a npm install <dep_name> --save will start adding these deps to package.json.

Body:
Dont install the package globally.
A good practice is to create your own package.json and then zip up your code + the node modules.
What this would look like is something like this:

<project-folder>
   |
   |--index.js (Your code)
   |--package.json (this has details including the packages your use)
   |--node_modules
          |-- This contains all the modules you need

Once you have this structure you can just zip this up and upload to lambda.A
You can create the package.json file using npm init and filling in the details.
For dependencies do a npm install <dep_name> --save will start adding these deps to package.json.


问:
Excel Equivalent of SQL query "SELECT A.one, B.two FROM A INNER JOIN B ON A.three = B.three"
How do you do SQL "select join on" in excel?
Say I want col one from table A, col two from table B and they both have col three.

I would do:

```<code>SELECT A.one, B.two
FROM A
INNER JOIN B ON
A.three = B.three
</code>```

But instead of tables I have a few tabs in a Excel sheet. How do I do the equivalent of above query in Excel?

答:
Assuming your sheets are as follows:

Sheet1

Sheet2

In Cell A2 of Sheet3 enter the formula

```<code>=IFERROR(INDEX(Sheet1!$A$2:$A$8,MATCH(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),Sheet1!$C$2:$C$8,0)),"")
</code>```

and in Cell B2 of Sheet3 enter the following formula

```<code>=IFERROR(INDEX(Sheet2!$B$2:$B$8,MATCH(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),Sheet1!$C$2:$C$8,0)),"")
</code>```

Both the above formula are array formula so commit it by pressing Ctrl+Shift+Enter. Drag/Copy down as required. See image for reference.

-----------------------------------------------------------------------------------------------------------------------

If you also want to display third column of first two sheets in Sheet3 (which is ID in my sample sheet) then enter following formula in Cell A2

```<code>=IFERROR(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),"")
</code>```

This is also an array formula. In Cell B2 enter

```<code>=IFERROR(INDEX(Sheet1!$A$2:$A$8,MATCH(A2,Sheet1!$C$2:$C$8,0)),"")
</code>```

And in Cell C2 enter

```<code>=IFERROR(INDEX(Sheet2!$B$2:$B$8,MATCH(A2,Sheet2!$C$2:$C$8,0)),"")
</code>```

Drag/Copy down as required. See image below.

Got this from @ScottCraner's answer here.

There's another way of achieving this without using using formula and VBA. See if this helps.

Body:
How do you do SQL "select join on" in excel?
Say I want col one from table A, col two from table B and they both have col three.

I would do:

SELECT A.one, B.two
FROM A
INNER JOIN B ON
A.three = B.three

But instead of tables I have a few tabs in a Excel sheet. How do I do the equivalent of above query in Excel?

Body:
Assuming your sheets are as follows:

Sheet1

Sheet2

In Cell A2 of Sheet3 enter the formula

=IFERROR(INDEX(Sheet1!$A$2:$A$8,MATCH(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),Sheet1!$C$2:$C$8,0)),"")

and in Cell B2 of Sheet3 enter the following formula

=IFERROR(INDEX(Sheet2!$B$2:$B$8,MATCH(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),Sheet1!$C$2:$C$8,0)),"")

Both the above formula are array formula so commit it by pressing Ctrl+Shift+Enter. Drag/Copy down as required. See image for reference.

-----------------------------------------------------------------------------------------------------------------------

If you also want to display third column of first two sheets in Sheet3 (which is ID in my sample sheet) then enter following formula in Cell A2

=IFERROR(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),"")

This is also an array formula. In Cell B2 enter

=IFERROR(INDEX(Sheet1!$A$2:$A$8,MATCH(A2,Sheet1!$C$2:$C$8,0)),"")

And in Cell C2 enter

=IFERROR(INDEX(Sheet2!$B$2:$B$8,MATCH(A2,Sheet2!$C$2:$C$8,0)),"")

Drag/Copy down as required. See image below.

Got this from @ScottCraner's answer here.

There's another way of achieving this without using using formula and VBA. See if this helps.


问:
lxml does not work when no doctype is available?
I'm trying to parse a XML with etree,

```<code>import re
from lxml   import etree
from pprint import pprint

doc = etree.parse('123.xml')
print doc.xpath('//jdbc-driver-params/url')
</code>```

But no matter what xpath query I use, it doc.xpath always return an empty list

Any ideas? Attached xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<jdbc-data-source xmlns="http://xmlns.oracle.com/weblogic/jdbc-data-source">
  <name>jdbc/db_ejemplo</name>
  <jdbc-driver-params>
    <url>jdbc:mysql://localhost:3306/db_ejemplo</url>
    <driver-name>com.mysql.jdbc.Driver</driver-name>
    <properties>
      <property>
        <name>user</name>
        <value>root</value>
      </property>
      <property>
        <name>password</name>
        <value>Qwer1234</value>
      </property>
    </properties>
  </jdbc-driver-params>
  <jdbc-data-source-params>
    <jndi-name>jdbc/db_ejemplo</jndi-name>
  </jdbc-data-source-params>
</jdbc-data-source>
</code>```

答:
It looks like the namespace is causing the issue:

```<code>doc.xpath(
    '//ns:jdbc-data-source/ns:jdbc-driver-params/ns:url',
    namespaces={
        'ns':'http://xmlns.oracle.com/weblogic/jdbc-data-source'
    }
 )
</code>```

yields:

```<code>[<Element {http://xmlns.oracle.com/weblogic/jdbc-data-source}url at 0x1049877a0>]
</code>```

Body:
I'm trying to parse a XML with etree,

import re
from lxml   import etree
from pprint import pprint

doc = etree.parse('123.xml')
print doc.xpath('//jdbc-driver-params/url')

But no matter what xpath query I use, it doc.xpath always return an empty list

Any ideas? Attached xml

<?xml version="1.0" encoding="UTF-8"?>
<jdbc-data-source xmlns="http://xmlns.oracle.com/weblogic/jdbc-data-source">
  <name>jdbc/db_ejemplo</name>
  <jdbc-driver-params>
    <url>jdbc:mysql://localhost:3306/db_ejemplo</url>
    <driver-name>com.mysql.jdbc.Driver</driver-name>
    <properties>
      <property>
        <name>user</name>
        <value>root</value>
      </property>
      <property>
        <name>password</name>
        <value>Qwer1234</value>
      </property>
    </properties>
  </jdbc-driver-params>
  <jdbc-data-source-params>
    <jndi-name>jdbc/db_ejemplo</jndi-name>
  </jdbc-data-source-params>
</jdbc-data-source>

Body:
It looks like the namespace is causing the issue:

doc.xpath(
    '//ns:jdbc-data-source/ns:jdbc-driver-params/ns:url',
    namespaces={
        'ns':'http://xmlns.oracle.com/weblogic/jdbc-data-source'
    }
 )

yields:

[<Element {http://xmlns.oracle.com/weblogic/jdbc-data-source}url at 0x1049877a0>]


问:
Remove duplicates in the list using linq
I have a class Items with properties (Id, Name, Code, Price).

The List of Items is populated with duplicated items.

For ex.:

```<code>1         Item1       IT00001        $100
2         Item2       IT00002        $200
3         Item3       IT00003        $150
1         Item1       IT00001        $100
3         Item3       IT00003        $150
</code>```

How to remove the duplicates in the list using linq?

答:
When you don't want to write IEqualityComparer you can try something like following. </p>

```<code> class Program
{

    private static void Main(string[] args)
    {

        var items = new List<Item>();
        items.Add(new Item {Id = 1, Name = "Item1"});
        items.Add(new Item {Id = 2, Name = "Item2"});
        items.Add(new Item {Id = 3, Name = "Item3"});

        //Duplicate item
        items.Add(new Item {Id = 4, Name = "Item4"});
        //Duplicate item
        items.Add(new Item {Id = 2, Name = "Item2"});

        items.Add(new Item {Id = 3, Name = "Item3"});

        var res = items.Select(i => new {i.Id, i.Name})
            .Distinct().Select(x => new Item {Id = x.Id, Name = x.Name}).ToList();

        // now res contains distinct records
    }

}

public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }
}
</code>```

Body:
I have a class Items with properties (Id, Name, Code, Price).

The List of Items is populated with duplicated items.

For ex.:

1         Item1       IT00001        $100
2         Item2       IT00002        $200
3         Item3       IT00003        $150
1         Item1       IT00001        $100
3         Item3       IT00003        $150

How to remove the duplicates in the list using linq?

Body:
When you don't want to write IEqualityComparer you can try something like following.

 class Program
{

    private static void Main(string[] args)
    {

        var items = new List<Item>();
        items.Add(new Item {Id = 1, Name = "Item1"});
        items.Add(new Item {Id = 2, Name = "Item2"});
        items.Add(new Item {Id = 3, Name = "Item3"});

        //Duplicate item
        items.Add(new Item {Id = 4, Name = "Item4"});
        //Duplicate item
        items.Add(new Item {Id = 2, Name = "Item2"});

        items.Add(new Item {Id = 3, Name = "Item3"});

        var res = items.Select(i => new {i.Id, i.Name})
            .Distinct().Select(x => new Item {Id = x.Id, Name = x.Name}).ToList();

        // now res contains distinct records
    }

}

public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }
}


问:
How to display javascript alert without reset form
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

```<code>if($pwd != $pwd2) {
    echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
</code>```

I also tried the one below but still the same thing happened:

```<code>if($pwd != $pwd2) {
    ?>
    <script type="text/javascript">
        alert("Password does not match!");
    </script>
    <?php
}
</code>```

答:
If you want other input fields not to be empty after submission you should try this using php.
Let's say your input field is username.

```<code>$username = $_POST['username'];
<input type="text" name="username"  value="<?php echo htmlentities($username); ?>">
</code>```

When you use this, after you clicked ok and get the alert, your username field will not be empty. The value you entered will appear in the text field.

Body:
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

if($pwd != $pwd2) {
    echo("");
}

I also tried the one below but still the same thing happened:

if($pwd != $pwd2) {
    ?>

    <?php
}

Body:
If you want other input fields not to be empty after submission you should try this using php.
Let's say your input field is username.

$username = $_POST['username'];
<input type="text" name="username"  value="<?php echo htmlentities($username); ?>">

When you use this, after you clicked ok and get the alert, your username field will not be empty. The value you entered will appear in the text field.


答:
If you need to call a method for each item in a list then you should use a simple for loop:

```<code>foreach var name in list
  CheckName(name);
</code>```

Just because LINQ is available, doesn't mean it should be used everywhere there is a collection. It is important to write code that makes sense and is self commenting and using it here has simultaneously introduced a flaw into your logic and made your code harder to read, understand and maintain. It's the wrong tool for the stated purpose

Doubtless you have additional requirements not stated here, like "I want to check every name in a list and make sure that none are null". You can and possibly should use linq for this but it looks more like

```<code>bool allNamesOK = list.All(n => n != null);
</code>```

This code is compact and reads well; we can clearly see the intention (though I wouldn't call the list "list" - "names" would better)

Title: Predicate inside a Where<> query not hit?

Body:
If you need to call a method for each item in a list then you should use a simple for loop:

foreach var name in list
  CheckName(name);

Just because LINQ is available, doesn't mean it should be used everywhere there is a collection. It is important to write code that makes sense and is self commenting and using it here has simultaneously introduced a flaw into your logic and made your code harder to read, understand and maintain. It's the wrong tool for the stated purpose

Doubtless you have additional requirements not stated here, like "I want to check every name in a list and make sure that none are null". You can and possibly should use linq for this but it looks more like

bool allNamesOK = list.All(n => n != null);

This code is compact and reads well; we can clearly see the intention (though I wouldn't call the list "list" - "names" would better)


问:
Echo arrays with regular text
How would I write this so I'm only using one echo? </p>

```<code>echo "<div class='post'>";
echo $row['title'];
echo "</div>";
</code>```

<p>I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank. </p>

答:
echo '
' . $row['title'] . '
';

The . operator concatenates strings. Also, I believe HTML wants you to use double quotes for class="post" (although perhaps it doesn't care?).

Title: Echo arrays with regular text

Body:
How would I write this so I'm only using one echo?

echo "
";
echo $row['title'];
echo "
";

I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank.

Body:
echo '<div class="post">' . $row['title'] . '</div>';

The . operator concatenates strings. Also, I believe HTML wants you to use double quotes for class="post" (although perhaps it doesn't care?).


问:
TFS - undo merge after get latest
I did a search on this issue and found a lot posts and questions but none seems to target my situation.

I had pending changes and i did "Get Latest", i got the conflicts window and wanted to resolve them, so i did a merge as i wanted to keep both my changes and the server's new code. but i forgot to check the block of codes and i just clicked merge (did not  checked in yet!).  i had a conflict on one of the cproj files and now i lost some .cs files as well.

I think i lost both versions of code and i want to go back and do that merge all over again and do it right, but i don't have a time machine! :)

Any help would be appreciated.

答:
You basically did an... let's say "Auto Merge". The only help you have is to view the changeset/history of that exact file.
Unless you shelved some changes, there is no way to get both .cs files back.

Title: TFS - undo merge after get latest


答:
If you see an example of ACTION_VIEW intent filter for the app to open files:

```<code><intent-filter android:label="app">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https"
          android:host="www.example.com">
</intent-filter>
</code>```

You can see that there is a android:scheme="https", which means that this app will accept ACTION_VIEW only with Uris having https scheme.

In your case the word app has only file scheme, and won't handle http or https Uris.

So first you have to download the file, and only after that open it as local file.

Title: Open file by URL

Body:
I have FileOpener class for open documents by URL:

public class FileOpener {

    private FileOpener() {
    }

    private static String url;
    private static Uri uri;
    private static Intent intent;

    public static void open(Context context, FileDTO fileDTO) {
        fileDTO.setUrl("https://calibre-ebook.com/downloads/demos/demo.docx");
        setupBase(fileDTO);
        checkFileTypeByUrl();

        try {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void checkFileTypeByUrl() {

    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
    intent.setDataAndType(uri, mimeType);
    }

    private static void setupBase(FileDTO fileDTO) {
        url = fileDTO.getUrl();
        uri = Uri.parse(url);
        intent = new Intent(Intent.ACTION_VIEW, uri);
    }
}

In activity/fragment it's look like this:

    @Override
    public void openOrDownloadFile(FileDTO file) {
        FileOpener.open(getContext(), file);
    }

It's work fine for PDF/Txt documents, but for MsWord/MsExcel/MsPowerPoint have ActivityNotFoundException (I have word/excel/powerpoint on my device, which opening from other applications without problem)

Stacktrace:

W/System.err: android.content.ActivityNotFoundException: No Activity
  found to handle Intent { act=android.intent.action.VIEW
  dat=https://calibre-ebook.com/downloads/demos/demo.docx
  typ=application/vnd.openxmlformats-officedocument.wordprocessingml.document
  flg=0x4000000 }

What could be the problem?

Body:
If you see an example of ACTION_VIEW intent filter for the app to open files:

<intent-filter android:label="app">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https"
          android:host="www.example.com">
</intent-filter>

You can see that there is a android:scheme="https", which means that this app will accept ACTION_VIEW only with Uris having https scheme.

In your case the word app has only file scheme, and won't handle http or https Uris.

So first you have to download the file, and only after that open it as local file.


问:
textBox embedded in a ListBox initial focus
I want to set the focus to the first ListBox item that is a textbox. I want to be able to write in it immedatelly without the necesity to click it or press any key. I try this but doesn't work:</p>

```<code>        private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listBox1.Items.Add(new TextBox() { });
        (listBox1.Items[0] as TextBox).Focus();

    }
</code>```

答:
In case any body else has this issue. An UIElement has to be fully loaded before you can focus it. therefor this can be made very simple:</p>

```<code>private void Window_Loaded(object sender, RoutedEventArgs e)
{
    listBox1.Items.Add(new TextBox() { });
    var txBox = listBox1.Items[0] as TextBox;
    txBox.Loaded += (txbSender, args) => (txbSender as TextBox)?.Focus();
}
</code>```

Body:
I want to set the focus to the first ListBox item that is a textbox. I want to be able to write in it immedatelly without the necesity to click it or press any key. I try this but doesn't work:

        private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listBox1.Items.Add(new TextBox() { });
        (listBox1.Items[0] as TextBox).Focus();

    }

Body:
In case any body else has this issue. An UIElement has to be fully loaded before you can focus it. therefor this can be made very simple:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    listBox1.Items.Add(new TextBox() { });
    var txBox = listBox1.Items[0] as TextBox;
    txBox.Loaded += (txbSender, args) => (txbSender as TextBox)?.Focus();
}


问:
calling a another function when window size is resized
I have to display Image albums . Till @media element width 700px I can display 3 images per slide , below @media width :700px i need to display 1 image per slide.

For displaying 3 image per slide , I written a function showfilteredImages();

```<code>$scope.imagemaindiv
</code>```

will have all images from backend

```<code>$scope.imagemaindiv = [{
    'img': "image1.png",
    "id": 1
}, {
    'img': "image2.png",
    "id": 2
}, {
    'img': "image3.png",
    "id": 3
}, {
    'img': "image4.png",
    "id": 4
}, {
    'img': "image5.png",
    "id": 5
}, {
    'img': "image6.png",
    "id": 6
}]
$scope._firstImgIndex = 0;
$scope._lastImgIndex = 2;
$scope.showFilteredImages = function() {
    $scope.filteredImages = [];
    for (var i = $scope._firstImgIndex; i <= $scope._lastImgIndex; i++) {
        $scope.filteredImages.push($scope.imagemaindiv[i]);
    }
};
</code>```

答:
try this code

```<code><!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />

    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <my-directive></my-directive>
  </body>

</html>
</code>```

app.js

```<code>'use strict';

var app = angular.module('app', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){
       alert();
         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);
</code>```

Body:
I have to display Image albums . Till @media element width 700px I can display 3 images per slide , below @media width :700px i need to display 1 image per slide.

For displaying 3 image per slide , I written a function showfilteredImages();

$scope.imagemaindiv

will have all images from backend

$scope.imagemaindiv = [{
    'img': "image1.png",
    "id": 1
}, {
    'img': "image2.png",
    "id": 2
}, {
    'img': "image3.png",
    "id": 3
}, {
    'img': "image4.png",
    "id": 4
}, {
    'img': "image5.png",
    "id": 5
}, {
    'img': "image6.png",
    "id": 6
}]
$scope._firstImgIndex = 0;
$scope._lastImgIndex = 2;
$scope.showFilteredImages = function() {
    $scope.filteredImages = [];
    for (var i = $scope._firstImgIndex; i <= $scope._lastImgIndex; i++) {
        $scope.filteredImages.push($scope.imagemaindiv[i]);
    }
};

Body:
try this code

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />

    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <my-directive></my-directive>
  </body>

</html>

app.js

'use strict';

var app = angular.module('app', []);

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){
       alert();
         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);


问:
WEKA's "Class has to be nominal if cost matrix given" error
I am trying to classify a data with 51 features with the command

DecisionTable -X 1 -S "weka.attributeSelection.GreedyStepwise -T -1.79 -N -1 -num-slots 1"

but I am getting the error

What does this error mean about nominal class for cost matrix?

答:
Its hard to tell you the exact reason without seeing your data.
But "class has to be nominal" tells you that you need a nominal label.

example for binary label   : {0,1}

example for nominal label  : {very, small, middle, big, very big}

example for continous label: real numbers

you need to classify your data nominal (or binary) with the given costmatrix


问:
Possible to load ASCX with jQuery.load() function?
Is it possible without encapsulating these controls in aspx files? The Register tag makes me think that it is not.</p>

答:
One possible way would be to have a generic aspx stub page that acts as a host to the ascx in the normal web forms way make a callback to the that page using JQuery's $.ajax() method with some arguments to denote what ascx control you want to load.

Then on your stub / host page, override the render method and render the control directly to the output stream using response.output.write. The callback handler on the client will catch the output and then it can be inserted into the DOM in the normal way or using using the version of $.load() that allows the specification of a DOM element.

hope this helps.

OwnerDisplayName: Emre


问:
Need java code in importing a text file comparing a set of strings
I have a set strings (string1,string2,string3,string4) and i want to search this in a text file (input.txt) using java coding, i have tried using below command but it is not working, please help.</p>

```<code>package string;
import java.io.File; //Required for input file
import java.io.FileNotFoundException; //Required for exceptioenter code heren throw
import java.util.Scanner; //required for scanner

public class strng {

public static void main(String[] args) throws FileNotFoundException // throws clause added
{

//ask the the for the string to be searched
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please enter part of the string: ");
    String searchString = keyboard.next().toLowerCase();

 // open the data file
    File file = new File("APPD_01_15_16_01.txt");
 // create a scanner from the file
    Scanner inputFile = new Scanner (file);

    // While there is another line to read.
    while(inputFile.hasNext())
    {
        // read the lines
         //Read string

        //Check if user input is a match and if true print out info.

        if(searchString.contains("samplemachine")
        {
            System.out.println("Yup!");
        }
        else
        {
            System.out.println("Fail!");
        }
    }

    // be polite and close the file
    inputFile.close();

}

}
</code>```

答: Your code is not doing what you are saying you want to do. If your requirement  is to is to search from the set of string then why are you comparing with the input taken from user?</p>

Body:
I have a set strings (string1,string2,string3,string4) and i want to search this in a text file (input.txt) using java coding, i have tried using below command but it is not working, please help.

package string;
import java.io.File; //Required for input file
import java.io.FileNotFoundException; //Required for exceptioenter code heren throw
import java.util.Scanner; //required for scanner

public class strng {

public static void main(String[] args) throws FileNotFoundException // throws clause added
{

//ask the the for the string to be searched
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please enter part of the string: ");
    String searchString = keyboard.next().toLowerCase();

 // open the data file
    File file = new File("APPD_01_15_16_01.txt");
 // create a scanner from the file
    Scanner inputFile = new Scanner (file);

    // While there is another line to read.
    while(inputFile.hasNext())
    {
        // read the lines
         //Read string

        //Check if user input is a match and if true print out info.

        if(searchString.contains("samplemachine")
        {
            System.out.println("Yup!");
        }
        else
        {
            System.out.println("Fail!");
        }
    }

    // be polite and close the file
    inputFile.close();

}

}


问:
Correct JSON string format for the body request in a WebRequest Activity inside of a Orchard Workflow?
I'm trying to make a POST in a WebRequest Activity, but the body is always empty if I select JSON format:

I have tried escaping and unescaping characters, with and without quotes and spaces, etc:

```<code>{\"value\": [{\"@search.action\": \"delete\",\"id\": \"abc-008\"}]}
</code>```

And

```<code>{value:[{@search.action: delete,id: abc-008}]}
</code>```

But formValues is always empty:

```<code>var formValues = activityContext.GetState<string>("FormValues") ?? "";
</code>```

The request works fine if I select Key/Value as the format but I need Json.

Edit: Should add that I tried the valid Json format (JsonLint) plus the examples I gave, with and without spaces and using ' instead of " but it's still empty.

答:
Both of the given Json formats are not valid. Did you tried simple format?

{     "value": [{         "@search.action": "delete",         "id": "abc - 008"   }] }

Body:
I'm trying to make a POST in a WebRequest Activity, but the body is always empty if I select JSON format:

I have tried escaping and unescaping characters, with and without quotes and spaces, etc:

{\"value\": [{\"@search.action\": \"delete\",\"id\": \"abc-008\"}]}

And

{value:[{@search.action: delete,id: abc-008}]}

But formValues is always empty:

var formValues = activityContext.GetState<string>("FormValues") ?? "";

The request works fine if I select Key/Value as the format but I need Json.

Edit: Should add that I tried the valid Json format (JsonLint) plus the examples I gave, with and without spaces and using ' instead of " but it's still empty.


问:
How to use a RestTemplate xml file in MockClientHttpRequest/Response
I am trying to stub a response that is coming back from a web server to my application, in order to be able to carry out component tests on my application.
I have a RestTemplate XML that I would like my requestFactory to consume to create responses based on the XML. Example of the XML is below.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rates-file xmlns="http://www.example.com/schema/rates-file">
    <timestamp>2017-06-30T14:20:21.768+10:00</timestamp>
    <daily-rates-updated>true</daily-rates-updated>
    <number-of-records>96</number-of-records>
    <rate>
        <transaction-type>transaction</transaction-type>
        <product-code>product</product-code>
        <code>code</code>
        <description>description</description>
        <rate>2.6154</rate>
    </rate>

    <number-of-records>96</number-of-records>
    <rate>
        <transaction-type>transaction2</transaction-type>
        <product-code>product2</product-code>
        <code>code2</code>
        <description>description2</description>
        <rate>2.6154</rate>
    </rate>
  ...
</code>```

For this purpose I am using MockClientHttpRequest and MockClientHttpResponse (part of spring-test).
How do I have the MockClientHttpRequest consume this XML and consequently produce my responses?

EDIT: Just to clarify this is the part of code I am trying to direct to my XML:

```<code>public RatesFile fetchRatesFile() {
...
try {
...
    **ratesFile = restTemplate.postForObject(exampleUrl, variables, RatesFile.class);**
...
}

return ratesFile;
</code>```

}

Instead of overriding postForObject method, I would like to write a RequestFactory that responds to the HttpMethod.POST request by using the XML.

答:
I'd not mess with the RestTemplate, simply due to the fact that I'd not be testing the Prod code in that case. What I'd do is override exampleUrl in my test, and then stand up an endpoint that responds to that. Here's how:

If using Spring Boot, simply use the properties attribute on @SpringBootTest to set  exampleUrl=http://localhost:8080/test. Also throw in @DirtiesContext in that case. Otherwise, create an application.properties in the src/test/resources directory and put the property in that.

Now either you can create a @RestController in the test package that has a method mapped to /test, OR

Use a mock Web server that you can configure to return canned response. The 2 most popular ones are WireMock and MockServer

Using either #2 or #3, you receive the HTTP request and can return whatever response you want to based on that.

Body:
I am trying to stub a response that is coming back from a web server to my application, in order to be able to carry out component tests on my application.
I have a RestTemplate XML that I would like my requestFactory to consume to create responses based on the XML. Example of the XML is below.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rates-file xmlns="http://www.example.com/schema/rates-file">
    <timestamp>2017-06-30T14:20:21.768+10:00</timestamp>
    <daily-rates-updated>true</daily-rates-updated>
    <number-of-records>96</number-of-records>
    <rate>
        <transaction-type>transaction</transaction-type>
        <product-code>product</product-code>
        code
        <description>description</description>
        <rate>2.6154</rate>
    </rate>

    <number-of-records>96</number-of-records>
    <rate>
        <transaction-type>transaction2</transaction-type>
        <product-code>product2</product-code>
        code2
        <description>description2</description>
        <rate>2.6154</rate>
    </rate>
  ...

For this purpose I am using MockClientHttpRequest and MockClientHttpResponse (part of spring-test).
How do I have the MockClientHttpRequest consume this XML and consequently produce my responses?

EDIT: Just to clarify this is the part of code I am trying to direct to my XML:

public RatesFile fetchRatesFile() {
...
try {
...
    **ratesFile = restTemplate.postForObject(exampleUrl, variables, RatesFile.class);**
...
}

return ratesFile;

}

Instead of overriding postForObject method, I would like to write a RequestFactory that responds to the HttpMethod.POST request by using the XML.


问:
JOGL Depth Buffering Not Working
I have been using JOGL for a few days now and this is now becoming a major road block.  I can not get shapes to draw in the correct z-order, instead, they are drawn in the order they are given to OpenGL.

I have spent the last few hours researching this and the general resolutions (and my reactions) seem to be the following:

Make sure your frustum is correct

I have double checked the frustum, it seems correct

I have switched to gluLookAt instead of a custom built frustum

I have switched to glOrthof just to make sure it is not perspective that is the problem.

I have not even set ANY view at all, instead working in the -1, 1 range that seems to be default

Make sure the following calls are in the init:

gl.glEnable(GL.GL_DEPTH_TEST);

gl.glDepthFunc(GL.GL_LEQUAL);

Make sure you are clearing the depth buffer on each redraw

gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

I have provided the very basic sample of a program below where this problem is occurring.  If you have JOGL and run it, you will see the red triangle at Z-position -0.5f ALWAYS on top while the triangles rotate around each other.  If you swap the two triangle vertex calls, the green triangle will then always be on top.

This has been an immense headache for me so any insight will be helpful, either from JOGL or OpenGL in general, but I can't seem to see what is wrong.

Also note that for brevity I removed the proper code to destroy the window.

```<code>import java.awt.Frame;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;

import com.jogamp.opengl.util.Animator;

public class JOGLTest implements GLEventListener
{
    static GLU glu = new GLU();
    static GLCanvas canvas = new GLCanvas();
    static Frame frame = new Frame("JOGL test");
    static Animator animator = new Animator(canvas);

    float rot = 0.0f;

    public void display(GLAutoDrawable glDrawable)
    {
        final GL2 gl = glDrawable.getGL().getGL2();

        rot++;

        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

        gl.glLoadIdentity();

        gl.glRotatef(rot, 0.0f, 1.0f, 0.0f);

        gl.glBegin(GL.GL_TRIANGLES);

        gl.glColor3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(-1.0f, -1.0f, 0.0f);
        gl.glVertex3f(1.0f, -1.0f, 0.0f);

        gl.glColor3f(1.0f, 0.0f, 0.0f);
        gl.glVertex3f(-1.0f, 1.0f, -0.5f);
        gl.glVertex3f(1.0f, 1.0f, -0.5f);
        gl.glVertex3f(0.0f, 0.0f, -0.5f);

        gl.glEnd();
    }

    public void dispose(GLAutoDrawable arg0)
    {

    }

    public void init(GLAutoDrawable glDrawable)
    {
        GL2 gl = glDrawable.getGL().getGL2();
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        gl.glClearDepth(1.0f);
        gl.glEnable(GL.GL_DEPTH_TEST);
        gl.glDepthFunc(GL.GL_LEQUAL);
    }

    public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
            int arg4)
    {

    }

    public static void main(String[] args)
    {
        canvas.addGLEventListener(new JOGLTest());
        frame.add(canvas);
        frame.setSize(640, 480);
        frame.setVisible(true);

        animator.start();
        canvas.requestFocus();
    }
}
</code>```

答:
Just stumbled across your question... are you using an Intel graphics card and an 'older' (pre-24th November) version of JOGL, by any chance? If so, the following may be helpful (ignore the mention of win7 64-bit; the problem described is more general and was solved in that instance in subsequent JOGL releases):
http://jogamp.762907.n3.nabble.com/Depth-buffer-not-working-on-Win7-64b-td1737435.html</p>

Title: JOGL Depth Buffering Not Working

Body:
I have been using JOGL for a few days now and this is now becoming a major road block.  I can not get shapes to draw in the correct z-order, instead, they are drawn in the order they are given to OpenGL.

I have spent the last few hours researching this and the general resolutions (and my reactions) seem to be the following:

Make sure your frustum is correct

I have double checked the frustum, it seems correct

I have switched to gluLookAt instead of a custom built frustum

I have switched to glOrthof just to make sure it is not perspective that is the problem.

I have not even set ANY view at all, instead working in the -1, 1 range that seems to be default

Make sure the following calls are in the init:

gl.glEnable(GL.GL_DEPTH_TEST);

gl.glDepthFunc(GL.GL_LEQUAL);

Make sure you are clearing the depth buffer on each redraw

gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

I have provided the very basic sample of a program below where this problem is occurring.  If you have JOGL and run it, you will see the red triangle at Z-position -0.5f ALWAYS on top while the triangles rotate around each other.  If you swap the two triangle vertex calls, the green triangle will then always be on top.

This has been an immense headache for me so any insight will be helpful, either from JOGL or OpenGL in general, but I can't seem to see what is wrong.

Also note that for brevity I removed the proper code to destroy the window.

import java.awt.Frame;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;

import com.jogamp.opengl.util.Animator;

public class JOGLTest implements GLEventListener
{
    static GLU glu = new GLU();
    static GLCanvas canvas = new GLCanvas();
    static Frame frame = new Frame("JOGL test");
    static Animator animator = new Animator(canvas);

    float rot = 0.0f;

    public void display(GLAutoDrawable glDrawable)
    {
        final GL2 gl = glDrawable.getGL().getGL2();

        rot++;

        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

        gl.glLoadIdentity();

        gl.glRotatef(rot, 0.0f, 1.0f, 0.0f);

        gl.glBegin(GL.GL_TRIANGLES);

        gl.glColor3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(-1.0f, -1.0f, 0.0f);
        gl.glVertex3f(1.0f, -1.0f, 0.0f);

        gl.glColor3f(1.0f, 0.0f, 0.0f);
        gl.glVertex3f(-1.0f, 1.0f, -0.5f);
        gl.glVertex3f(1.0f, 1.0f, -0.5f);
        gl.glVertex3f(0.0f, 0.0f, -0.5f);

        gl.glEnd();
    }

    public void dispose(GLAutoDrawable arg0)
    {

    }

    public void init(GLAutoDrawable glDrawable)
    {
        GL2 gl = glDrawable.getGL().getGL2();
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        gl.glClearDepth(1.0f);
        gl.glEnable(GL.GL_DEPTH_TEST);
        gl.glDepthFunc(GL.GL_LEQUAL);
    }

    public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
            int arg4)
    {

    }

    public static void main(String[] args)
    {
        canvas.addGLEventListener(new JOGLTest());
        frame.add(canvas);
        frame.setSize(640, 480);
        frame.setVisible(true);

        animator.start();
        canvas.requestFocus();
    }
}