问:
VSTS Build Failure - error MSB4184: The expression """.ArtifactsStagingDirectory" cannot be evaluated
I have a solution with multiple projects (1 WebApi project, 2 MVC projects, and bunch of class libraries).

I am following this article on using Octopus Deploy to package up individual projects and push them to the Octopus server when the projects are contained in a single solution.

The build solution tasks has me changing the arguments from:

```<code>/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(BuildConfiguration)"
</code>```

to

```<code>/p:OutDir=$(Build.ArtifactsStagingDirectory) /p:GenerateProjectSpecficOutputFolder=true
</code>```

on the surface this makes sense - publish everything to a single directory and create a separate folder for each project.

However changing this - creates and error on build:

d:\a\1\s\Test.Models\Test.Models.csproj" (default target) (5) ->
  (ImplicitlyExpandDesignTimeFacades target) ->    C:\Program Files
  (x86)\MSBuild\14.0\bin\Microsoft.NetFramework.CurrentVersion.targets(107,74):
  error MSB4184: The expression """.ArtifactsStagingDirectory" cannot be
  evaluated. Method 'System.String.ArtifactsStagingDirectory' not found.
  [d:\a\1\s\Test.Models\P4P.Models.csproj]

This is a separate class library that is failing.  The solution is building one of the web applications and another class library before reaching this failure.

答: The variable $(Build.ArtifactsStagingDirectory) you specified is not a predefined variable. There is a redundant string "s" in it. The right one should be: $(Build.ArtifactStagingDirectory).

Body:
I have a solution with multiple projects (1 WebApi project, 2 MVC projects, and bunch of class libraries).

I am following this article on using Octopus Deploy to package up individual projects and push them to the Octopus server when the projects are contained in a single solution.

The build solution tasks has me changing the arguments from:

/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(BuildConfiguration)"

to

/p:OutDir=$(Build.ArtifactsStagingDirectory) /p:GenerateProjectSpecficOutputFolder=true

on the surface this makes sense - publish everything to a single directory and create a separate folder for each project.

However changing this - creates and error on build:

d:\a\1\s\Test.Models\Test.Models.csproj" (default target) (5) ->
  (ImplicitlyExpandDesignTimeFacades target) ->    C:\Program Files
  (x86)\MSBuild\14.0\bin\Microsoft.NetFramework.CurrentVersion.targets(107,74):
  error MSB4184: The expression """.ArtifactsStagingDirectory" cannot be
  evaluated. Method 'System.String.ArtifactsStagingDirectory' not found.
  [d:\a\1\s\Test.Models\P4P.Models.csproj]

This is a separate class library that is failing.  The solution is building one of the web applications and another class library before reaching this failure.


来源: stackexchange

问:
Error, Reference.push failed: first argument contains undefined in property
I'm new with firebase database and I'm currently trying to push data into my firebase database, but got an error like this Error: Reference.push failed: first argument contains undefined in property 'Product.prdName'

//insert data function in service.ts
insertProduct(Product: Product) {
  this.productList.push({
    prdName: Product.prdName,
    prdCat: Product.prdCat,
    prdSup: Product.prdSup,
  });
}

//onsubmit function in component.ts
productList: Product[];

constructor(private productService: ProductService) {}

onSubmit(form: NgForm) {
  if (form.value.$key == null) {
    this.productService.insertProduct(form.value);
  } else {
    this.productService.updateProduct(form.value);
  }
  this.resetForm(form);
}

//class.ts
export class Product {
  $key: string;
  prdName: string;
  prdCat: string; //category
  prdSup: string; //supplier
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--form snipped-->

<form #productForm="ngForm" (ngSubmit)="onSubmit(productForm)">
  <input type="hidden" name="$key" #$key="ngModel" [(ngModel)]="productService.selectedProduct.$key">

  <div class="form-group">
    <label>Product Name</label>
    <input class="form-control" name="name" #name="ngModel" [(ngModel)]="productService.selectedProduct.prdName" placeholder="Full Name">
  </div>

  <div class="form-group">
    <button type="submit" class="btn btn-primary" (onclick)="">Submit</button>
  </div>
</form></code>```

Can somebody help me, please?

please let me know if more snippets are needed. Thanks in advance.

答:
You are passing onSubmit(productForm) , so you will get output like

```<code>{
  $key : value of productService.selectedProduct.$key
  name : value of productService.selectedProduct.prdName
}
</code>```

What you can do is

EITHER CHANGE

Value of name property of input to same as Product class like name='name' to name='prdName'

OR

```<code>this.productService.insertProduct(form.value);
</code>```

to

```<code>this.productService.insertProduct(this.productService.selectedProduct);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new with firebase database and I'm currently trying to push data into my firebase database, but got an error like this Error: Reference.push failed: first argument contains undefined in property 'Product.prdName'

//insert data function in service.ts
insertProduct(Product: Product) {
  this.productList.push({
    prdName: Product.prdName,
    prdCat: Product.prdCat,
    prdSup: Product.prdSup,
  });
}

//onsubmit function in component.ts
productList: Product[];

constructor(private productService: ProductService) {}

onSubmit(form: NgForm) {
  if (form.value.$key == null) {
    this.productService.insertProduct(form.value);
  } else {
    this.productService.updateProduct(form.value);
  }
  this.resetForm(form);
}

//class.ts
export class Product {
  $key: string;
  prdName: string;
  prdCat: string; //category
  prdSup: string; //supplier
}

<form #productForm="ngForm" (ngSubmit)="onSubmit(productForm)">
  <input type="hidden" name="$key" #$key="ngModel" [(ngModel)]="productService.selectedProduct.$key">

    Product Name
    <input class="form-control" name="name" #name="ngModel" [(ngModel)]="productService.selectedProduct.prdName" placeholder="Full Name">

    <button type="submit" class="btn btn-primary" (onclick)="">Submit</button>

</form>

Can somebody help me, please?

please let me know if more snippets are needed. Thanks in advance.

Body:
You are passing onSubmit(productForm) , so you will get output like

{
  $key : value of productService.selectedProduct.$key
  name : value of productService.selectedProduct.prdName
}

What you can do is

EITHER CHANGE

Value of name property of input to same as Product class like name='name' to name='prdName'

OR

this.productService.insertProduct(form.value);

to

this.productService.insertProduct(this.productService.selectedProduct);


问:
Ionic Runtime Error ( A network error)
Hello I have this problem and i don't know how to solve it.
A network error (such as timeout, interrupted connection or unreachable host) has occurred. I read Install cordova-plugin-whitelist might fix the problem but the same error still occurs. Any ideas on how to fix it ?

答: i had to enable the sign in method from the firebase console under authentication. </p>

Title: Ionic Runtime Error ( A network error)


问:
Efficient algorithm for comparing elements in the same list
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

```<code>public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}
</code>```

答:
if you just want to check whether there is a clash, Then you can try

```<code>Set<BaseBallGame> baseBallGameSet = new HashSet<BaseBallGame>(games_list);
if(baseBallGameSet.size < games_list.size)
  // Clash exists.
</code>```

You can consider this as an optimization before what @thebenman has suggested.

Body:
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}

Body:
if you just want to check whether there is a clash, Then you can try

Set<BaseBallGame> baseBallGameSet = new HashSet<BaseBallGame>(games_list);
if(baseBallGameSet.size < games_list.size)
  // Clash exists.

You can consider this as an optimization before what @thebenman has suggested.


问:
JavaFX Panel inside Panel auto resizing
I have a JavaFX application which has only one FXML file. In this file I have one AnchorPane which has a StackPane inside it. Here is the screenshot:

When I start this application, I want to resize StackPane automatically with the AnchorPane. Thus; StackPane will get the current avaliable width and height automatically. At the moment when I resize the application, AnchorPane is being resized automatically but StackPane stays as his fixed size.

How can I resize the StackPane automatically and make it fully stretched inside its parent panel?

My Code

Main.java

```<code>package app;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

  public static void main(String[] args) {
      Application.launch(args);
  }

  @Override
  public void start(Stage stage) throws Exception {
      Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
      Scene scene = new Scene(root,800,600);
      scene.getStylesheets().add(this.getClass().getResource("/app/style1.css").toExternalForm());
      stage.setScene(scene);
      stage.show();
  }
}
</code>```

MainController.java

```<code>package app;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;

public class MainController implements Initializable {

   @FXML
   private AnchorPane anchorPane;
   @FXML
   private StackPane stackPane;

   @Override
   public void initialize(URL url, ResourceBundle rb) {
     stackPane.setPrefSize(anchorPane.getPrefWidth(), anchorPane.getPrefHeight()); //didn't work
   }
}
</code>```

Main.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="anchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
    <StackPane fx:id="stackPane" ></StackPane>
</AnchorPane>
</code>```

style1.css

```<code>#anchorPane {
    -fx-border-width: 2px;
    -fx-border-color: chartreuse;
}
#stackPane {
    -fx-border-width: 2px;
    -fx-border-color: red;

    /* didn't work */
   -fx-hgap: 100%;
   -fx-vgap: 100%;
}
</code>```

答:
No need to cede.

just select pane ,right click then select Fit to parent.

It will automatically resize pane to anchor pane size.

Title: JavaFX Panel inside Panel auto resizing

Body:
I have a JavaFX application which has only one FXML file. In this file I have one AnchorPane which has a StackPane inside it. Here is the screenshot:

When I start this application, I want to resize StackPane automatically with the AnchorPane. Thus; StackPane will get the current avaliable width and height automatically. At the moment when I resize the application, AnchorPane is being resized automatically but StackPane stays as his fixed size.

How can I resize the StackPane automatically and make it fully stretched inside its parent panel?

My Code

Main.java

package app;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

  public static void main(String[] args) {
      Application.launch(args);
  }

  @Override
  public void start(Stage stage) throws Exception {
      Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
      Scene scene = new Scene(root,800,600);
      scene.getStylesheets().add(this.getClass().getResource("/app/style1.css").toExternalForm());
      stage.setScene(scene);
      stage.show();
  }
}

MainController.java

package app;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;

public class MainController implements Initializable {

   @FXML
   private AnchorPane anchorPane;
   @FXML
   private StackPane stackPane;

   @Override
   public void initialize(URL url, ResourceBundle rb) {
     stackPane.setPrefSize(anchorPane.getPrefWidth(), anchorPane.getPrefHeight()); //didn't work
   }
}

Main.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="anchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
    <StackPane fx:id="stackPane" ></StackPane>
</AnchorPane>

style1.css

#anchorPane {
    -fx-border-width: 2px;
    -fx-border-color: chartreuse;
}
#stackPane {
    -fx-border-width: 2px;
    -fx-border-color: red;

    /* didn't work */
   -fx-hgap: 100%;
   -fx-vgap: 100%;
}


问:
Scrapy behavior changes when download delay is set
Here is my scrapy spider

```<code>class Spider(scrapy.Spider):
    name = "name"
    start_urls = ["https://www.aurl"]

    def parse(self, response):
        links_page_urls = response.css("a.dynamic-linkset::attr(href)").extract()
        for url in contract_page_urls:
            yield response.follow(url, callback=self.parse_list_page)

        next_data_cursor = response.css("li.next").css("a::attr(href)").extract_first()
        if next_data_cursor:
            self.log("going to next page - {}".format(next_data_cursor))
            yield response.follow(next_data_cursor, callback=self.parse)

    def parse_list_page(self, response):
        list =  response.css("div.row div.list-group a.list-group-item").css("a::attr(href)").extract()
        for url in list:
            self.log("url - {}".format(url))
            yield scrapy.Request(url=self.base_url + url, callback=self.parse_page)

    def parse_page(self, response):
        #Lots of code for parsing elements from a page
        # build an item and return it
</code>```

My observations is that on my own machine at home and with no download delay set, the actual pages are visited in rapid succession and saved to mongo. When I move this code to an EC2 instance and set the download delay to 60, what I now notice is that the web pages aren't visited for scraping and instead the first page is visited, a next data token is scraped and it's visited. Then I see a lot of print outs related to scraping the list pages rather than each individual page.

The desired behavior is to visit the initial URL, get the page list, and then visit each page and scrape it, then move onto the next data cursor and repeat this process.

答:
You could try to set a much lower DOWNLOAD_DELAY (probably= 2) and also set CONCURRENT_REQUESTS = 1 assigning a higher priority to the requests from the page list, something like:

```<code>yield response.follow(url, callback=self.parse_list_page, priority=1)
</code>```

Body:
Here is my scrapy spider

class Spider(scrapy.Spider):
    name = "name"
    start_urls = ["https://www.aurl"]

    def parse(self, response):
        links_page_urls = response.css("a.dynamic-linkset::attr(href)").extract()
        for url in contract_page_urls:
            yield response.follow(url, callback=self.parse_list_page)

        next_data_cursor = response.css("li.next").css("a::attr(href)").extract_first()
        if next_data_cursor:
            self.log("going to next page - {}".format(next_data_cursor))
            yield response.follow(next_data_cursor, callback=self.parse)

    def parse_list_page(self, response):
        list =  response.css("div.row div.list-group a.list-group-item").css("a::attr(href)").extract()
        for url in list:
            self.log("url - {}".format(url))
            yield scrapy.Request(url=self.base_url + url, callback=self.parse_page)

    def parse_page(self, response):
        #Lots of code for parsing elements from a page
        # build an item and return it

My observations is that on my own machine at home and with no download delay set, the actual pages are visited in rapid succession and saved to mongo. When I move this code to an EC2 instance and set the download delay to 60, what I now notice is that the web pages aren't visited for scraping and instead the first page is visited, a next data token is scraped and it's visited. Then I see a lot of print outs related to scraping the list pages rather than each individual page.

The desired behavior is to visit the initial URL, get the page list, and then visit each page and scrape it, then move onto the next data cursor and repeat this process.

Body:
You could try to set a much lower DOWNLOAD_DELAY (probably= 2) and also set CONCURRENT_REQUESTS = 1 assigning a higher priority to the requests from the page list, something like:

yield response.follow(url, callback=self.parse_list_page, priority=1)


问:
Angular 4 routes with submodules
I'm trying to use Core UI Angular seed.

here're my routing files:
app/app.routing.js

```<code>import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

// Import Containers
import {
    FullLayoutComponent,
    SimpleLayoutComponent
} from './containers';

export const routes:Routes = [
    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full',
    },
    {
        path: '',
        component: FullLayoutComponent,
        data: {
            title: 'Home'
        },
        children: [
            {
                path: 'dashboard',
                loadChildren: './views/dashboard/dashboard.module#DashboardModule'
            },
            {
                path: 'clients',
                loadChildren: './views/clients/clients.module#ClientsModule'
            },
        ]
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {
}
</code>```

app/views/clients/clients.routing.ts

```<code>import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {ClientsComponent} from './clients.component';

const routes:Routes = [
    {
        path: '',
        component: ClientsComponent,
        data: {
            title: 'Clients'
        },
        children: [
            {
                path: 'organizations',
                loadChildren: './organizations/organizations.module#OrganizationsModule'
            },
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class ClientsRoutingModule {
}
</code>```

app\views\clients\organizations\organizations.routing.ts

```<code>import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    {
        path: '',
        component: IndexComponent,
        data: {
            title: 'Organizations'
        },
        children: [
            {
                path: 'create',
                component: CreateComponent,
                data: {
                    title: 'Add organization'
                }
            }
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}
</code>```

So, while navigating:

http://localhost:4200/#/dashboard - and renders dashboard
http://localhost:4200/#/clients/organizations - renders clients IndexComponent

but

http://localhost:4200/#/clients/organizations - also renders clients IndexComponent
http://localhost:4200/#/clients/organizations/create - also renders clients IndexComponent

Breadcrumbs render in correct way.

ClientsModule

```<code>import {NgModule} from '@angular/core';

import {ClientsComponent} from './clients.component';
import {ClientsRoutingModule} from './clients.routing';

@NgModule({
    imports: [
        ClientsRoutingModule,
    ],
    declarations: [
        ClientsComponent,
    ]
})
export class ClientsModule {
}
</code>```

OrganizationsModule

```<code>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {OrganizationsRoutingModule} from './organizations.routing';

import {ListComponent} from './components/list.component';

import {IndexComponent} from './index.component';
import {ViewComponent} from './view.component';
import {CreateComponent} from './create.component';

@NgModule({
    imports: [
        CommonModule,
        OrganizationsRoutingModule,
    ],
    declarations: [
        ListComponent,
        IndexComponent,
        CreateComponent,
        ViewComponent
    ]
})
export class OrganizationsModule {
}
</code>```

答:
Your routine definition is wrong, It should be as follow,
app\views\clients\organizations\organizations.routing.ts</p>

```<code>import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    { path: 'create', component: CreateComponent, data: { title: 'Add organization' }},
    {
        path: '',
        children: [
           { path: '', component: IndexComponent},
           { path: ':id', component: ViewComponent } //if you want to show detail view by id
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}
</code>```

Title: Angular 4 routes with submodules

Body:
I'm trying to use Core UI Angular seed.

here're my routing files:
app/app.routing.js

import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

// Import Containers
import {
    FullLayoutComponent,
    SimpleLayoutComponent
} from './containers';

export const routes:Routes = [
    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full',
    },
    {
        path: '',
        component: FullLayoutComponent,
        data: {
            title: 'Home'
        },
        children: [
            {
                path: 'dashboard',
                loadChildren: './views/dashboard/dashboard.module#DashboardModule'
            },
            {
                path: 'clients',
                loadChildren: './views/clients/clients.module#ClientsModule'
            },
        ]
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {
}

app/views/clients/clients.routing.ts

import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {ClientsComponent} from './clients.component';

const routes:Routes = [
    {
        path: '',
        component: ClientsComponent,
        data: {
            title: 'Clients'
        },
        children: [
            {
                path: 'organizations',
                loadChildren: './organizations/organizations.module#OrganizationsModule'
            },
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class ClientsRoutingModule {
}

app\views\clients\organizations\organizations.routing.ts

import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    {
        path: '',
        component: IndexComponent,
        data: {
            title: 'Organizations'
        },
        children: [
            {
                path: 'create',
                component: CreateComponent,
                data: {
                    title: 'Add organization'
                }
            }
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}

So, while navigating:

http://localhost:4200/#/dashboard - and renders dashboard
http://localhost:4200/#/clients/organizations - renders clients IndexComponent

but

http://localhost:4200/#/clients/organizations - also renders clients IndexComponent
http://localhost:4200/#/clients/organizations/create - also renders clients IndexComponent

Breadcrumbs render in correct way.

ClientsModule

import {NgModule} from '@angular/core';

import {ClientsComponent} from './clients.component';
import {ClientsRoutingModule} from './clients.routing';

@NgModule({
    imports: [
        ClientsRoutingModule,
    ],
    declarations: [
        ClientsComponent,
    ]
})
export class ClientsModule {
}

OrganizationsModule

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {OrganizationsRoutingModule} from './organizations.routing';

import {ListComponent} from './components/list.component';

import {IndexComponent} from './index.component';
import {ViewComponent} from './view.component';
import {CreateComponent} from './create.component';

@NgModule({
    imports: [
        CommonModule,
        OrganizationsRoutingModule,
    ],
    declarations: [
        ListComponent,
        IndexComponent,
        CreateComponent,
        ViewComponent
    ]
})
export class OrganizationsModule {
}

Body:
Your routine definition is wrong, It should be as follow,
app\views\clients\organizations\organizations.routing.ts

import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    { path: 'create', component: CreateComponent, data: { title: 'Add organization' }},
    {
        path: '',
        children: [
           { path: '', component: IndexComponent},
           { path: ':id', component: ViewComponent } //if you want to show detail view by id
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}


问:
Software for taking notes on programming
What type of software is good for taking notes on programming?  For example, if I want to jot down different methods/functions that are useful for different things.  Ideally, the software would have  syntax highlighting.

The software would need to support Mac OS X.  I will most probably be using this for Objective-C/iPhone development and Ruby on Rails development.

I want something that can shift between ordinary text and coding syntax.  For example if I was to type:

In order to create a rectangle in Objective-C with a name square use: (CGRect *) square...........

I would like the objective-C code to have syntax highlighting but not the rest of the text.

Thanks!

P.S. I use textmate generally for coding.

答:
I like notepad 2
http://www.flos-freeware.ch/notepad2.html</p>

ContentLicense: CC BY-SA 2.5


问:
Android Studio Freezes at Gradle Build
I just installed Android Studio on Windows 10, and tried to create my first App ("Hello World") from the Studio website. The program gets stuck (but computer remains responsive) at the "Gradle Build" step. I saw another post on this topic, referring to firewall issues, but no resolution. I turned off my firewall, but the problem persisted. Also, I looked on Task Manager and the Android Studio task was using 83% of memory (>480MB). Many thanks in advance if any ideas! Screenshot:

答: Close other applications, as we can see 83% memory equals 480 megabyte on your computer. Try freeing memory by closing other applications. Also list what is your RAM size?</p>

Title: Android Studio Freezes at Gradle Build


问:
Get notification when a user wants to add data to the database
I'm about to begin working on a recipe Android app for my college final project, and I want users to be able to add recipes to the database. However, I don't want the data to be added right away, but I'd like to receive a notification whenever someone wants to add a recipe, so I can confirm it myself. I'm using back{4}app by the way.

How can I do such a thing in a not-so-complicated way? I was thinking to create an admin account for myself in the app itself, but is there any way to send the notifications to said account? I also want to be able to confirm recipe addition with a simple "Confirm" button from within the app, so will this require me to create an additional class for pending recipes? Will I need an admin account in any case?

答:
all this can be achieve by using cloud code.

```<code>Parse.cloud.define("addRecipe", function(request, response) {
    const query = new Parse.Query("recipe");
    query.set("name", "name");
    query.save({
         success function(result) {
              response(result);
              //call push notification function from client or from cloud code when the error is nil
         },
         error: function(result, error) {
          response(error);
          }
    });
});
</code>```

this is an example of push notifications using cloud code.
push notification are not allow anymore from the client due to secure reason.
you should be subscribe to this channel

```<code>Parse.Cloud.define("pushsample", function (request, response) {
    Parse.Push.send({
        channels: ["channelName"],
        data: {
            title: "Hello!",
            message: "Hello from the Cloud Code",
        }
   }, {
        success: function () {
            // Push was successful
            response.sucess("push sent");
        },
        error: function (error) {
        // Push was unsucessful
        response.sucess("error with push: " + error);
        },
        useMasterKey: true
   });
});
</code>```

you should also implement some logic to your app in order to display recipes confirm by admin.

```<code>var recipe = Parse.Object.extend("recipe");
var query = new Parse.Query(recipe);
query.equalTo("confirm", true);
query.find({
  success: function(results) {
    //it will display recipes confirmed
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  });
</code>```

you should also setup a admin system in your app or a website

Body:
all this can be achieve by using cloud code.

Parse.cloud.define("addRecipe", function(request, response) {
    const query = new Parse.Query("recipe");
    query.set("name", "name");
    query.save({
         success function(result) {
              response(result);
              //call push notification function from client or from cloud code when the error is nil
         },
         error: function(result, error) {
          response(error);
          }
    });
});

this is an example of push notifications using cloud code.
push notification are not allow anymore from the client due to secure reason.
you should be subscribe to this channel

Parse.Cloud.define("pushsample", function (request, response) {
    Parse.Push.send({
        channels: ["channelName"],
        data: {
            title: "Hello!",
            message: "Hello from the Cloud Code",
        }
   }, {
        success: function () {
            // Push was successful
            response.sucess("push sent");
        },
        error: function (error) {
        // Push was unsucessful
        response.sucess("error with push: " + error);
        },
        useMasterKey: true
   });
});

you should also implement some logic to your app in order to display recipes confirm by admin.

var recipe = Parse.Object.extend("recipe");
var query = new Parse.Query(recipe);
query.equalTo("confirm", true);
query.find({
  success: function(results) {
    //it will display recipes confirmed
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  });

you should also setup a admin system in your app or a website


问:
Why I'm getting java.security.InvalidKey Exception?
I'm trying decrypt whatup db file (which I copied to my PC, and run from my PC, under linux).

The initialize vector and key are:

```<code>private byte[] key = { (byte) 141, 75, 21, 92, (byte) 201, (byte) 255,
        (byte) 129, (byte) 229, (byte) 203, (byte) 246, (byte) 250, 120,
        25, 54, 106, 62, (byte) 198, 33, (byte) 166, 86, 65, 108,
        (byte) 215, (byte) 147 };

private final byte[] iv = { 0x1E, 0x39, (byte) 0xF3, 0x69, (byte) 0xE9, 0xD,
        (byte) 0xB3, 0x3A, (byte) 0xA7, 0x3B, 0x44, 0x2B, (byte) 0xBB,
        (byte) 0xB6, (byte) 0xB0, (byte) 0xB9 };
</code>```

And when I'm running this code:

```<code>  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  SecretKeySpec secret = new SecretKeySpec(key, "AES");
  IvParameterSpec vector = new IvParameterSpec(iv);
  cipher.init(Cipher.DECRYPT_MODE, secret, vector);
</code>```

I'm getting exception on the init function:
"java.security.InvalidKeyException: Illegal key size"

I used this post:

Get all messages from Whatsapp

What is wrong ?

答: I guess The JDK key size which does not allow you to encrypt with key whose size is more than 128 bits.</p>

Body:
I'm trying decrypt whatup db file (which I copied to my PC, and run from my PC, under linux).

The initialize vector and key are:

private byte[] key = { (byte) 141, 75, 21, 92, (byte) 201, (byte) 255,
        (byte) 129, (byte) 229, (byte) 203, (byte) 246, (byte) 250, 120,
        25, 54, 106, 62, (byte) 198, 33, (byte) 166, 86, 65, 108,
        (byte) 215, (byte) 147 };

private final byte[] iv = { 0x1E, 0x39, (byte) 0xF3, 0x69, (byte) 0xE9, 0xD,
        (byte) 0xB3, 0x3A, (byte) 0xA7, 0x3B, 0x44, 0x2B, (byte) 0xBB,
        (byte) 0xB6, (byte) 0xB0, (byte) 0xB9 };

And when I'm running this code:

  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  SecretKeySpec secret = new SecretKeySpec(key, "AES");
  IvParameterSpec vector = new IvParameterSpec(iv);
  cipher.init(Cipher.DECRYPT_MODE, secret, vector);

I'm getting exception on the init function:
"java.security.InvalidKeyException: Illegal key size"

I used this post:

Get all messages from Whatsapp

What is wrong ?


问:
Getting Webpack 2 to support IE8
I want to use Webpack 2 in a large project which must still support IE8.

I've installed babel-preset-env so I can easily deprecate any IE < 11 in future, one by one, once each of the browsers becomes unsupported by this project.

According to the babel-preset-env readme "If you are targeting IE 8 and Chrome 55 [babel-preset-env] will include all plugins required by IE 8 since you would need to support both still."

As I understand it, I also need to install babel-polyfill mostly for its IE5 shim, but also for its polyfills for ES6 and 7 features that I may wish to use.

However having installed these things, my code still falls over on IE8 (in Browserstack) at the point where Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); is first run. A function I thought was getting 'fixed' by the shims.

Is it not getting shimmed properly? Have I missed out a step?

答:
I had the same problem before and here is what I did to solve.

In es6 features,

a class can define a property with get and set to encapsulate a field.

but it is not woroking on IE8.

because the defineProperty method is not supported see the docs,

so we changed the whole code pattern to like below

```<code>let val1;

class className {

    methodName() {
        this.val2 = 'test';
        //code here
    }

    getVal1() {
        return val1;
    }

    setVal1(_val1) {
        val1 = _val1;
    }

    getVal2() {
        return this.val2;
    }

    setVal2(_val2) {
        this.val2 = _val2;
    }
}

module.exports = className;
</code>```

and I recommend that adding 'es3ify' see the link,github es3ify to your webpack build for IE7/8

Title: Getting Webpack 2 to support IE8

Body:
I had the same problem before and here is what I did to solve.

In es6 features,

a class can define a property with get and set to encapsulate a field.

but it is not woroking on IE8.

because the defineProperty method is not supported see the docs,

so we changed the whole code pattern to like below

let val1;

class className {

    methodName() {
        this.val2 = 'test';
        //code here
    }

    getVal1() {
        return val1;
    }

    setVal1(_val1) {
        val1 = _val1;
    }

    getVal2() {
        return this.val2;
    }

    setVal2(_val2) {
        this.val2 = _val2;
    }
}

module.exports = className;

and I recommend that adding 'es3ify' see the link,github es3ify to your webpack build for IE7/8


问:
Apache drops Authorize header regardless of .htaccess rules resulting 401 on Laravel api request
My code works perfectly fine while I am using it on my local and I can get the user info with postman and I have no issues getting the access token from server or localhost but using the access token for retrieving data from my real server always returns { message: unauthenticated } with status 401

The reason I found out is that Apache Drops the Authorize Header ! I have tried to fix it with adding these to my .htaccess but they don't do any help

my Apache vr is 2.4.29

this is my .htaccess file:

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

</IfModule>
</code>```

Someone please help me with this... :(

答:
It seems the important thing I didn't know was that in first: some shared hosting websites don't allow you to access or modify the apache config file, and second: in the config file its needed to change the AllowOverride from None to All

```<code>AllowOverride All
</code>```

I switched from a WH4S shared host to a Dreamhosting VPS and everything is working just as it should have been.

Body:
My code works perfectly fine while I am using it on my local and I can get the user info with postman and I have no issues getting the access token from server or localhost but using the access token for retrieving data from my real server always returns { message: unauthenticated } with status 401

The reason I found out is that Apache Drops the Authorize Header ! I have tried to fix it with adding these to my .htaccess but they don't do any help

my Apache vr is 2.4.29

this is my .htaccess file:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

</IfModule>

Someone please help me with this... :(

Body:
It seems the important thing I didn't know was that in first: some shared hosting websites don't allow you to access or modify the apache config file, and second: in the config file its needed to change the AllowOverride from None to All

AllowOverride All

I switched from a WH4S shared host to a Dreamhosting VPS and everything is working just as it should have been.


问:
Continuous Speech Recognition on browser like "ok google" or "hey siri"
I am doing a POC and my requirement is that I want to implement the feature like OK google or Hey Siri on browser.

I am using the Chrome Browser's Web speech api. The things I noticed that I can't continuous the recognition as it terminates automatically after a certain period of time and I know its relevant because of security concern. I just does another hack like when the SpeechReognition terminates then on its end event I further start the SpeechRecogntion but it is not the best way to implement such a solution because suppose if I am using the 2 instances of same application on the different browser tab then It doesn't work or may be I am using another application in my browser that uses the speech recognition then both the application doesn't behave the same as expected. I am looking for a best approach to solve this problem.

Thanks in advance.

答:
Since your problem is that you can't run the SpeechRecognition continuously for long periods of time, one way would be to start the SpeechRecognition only when you get some input in the mic.

This way only when there is some input, you will start the SR, looking for your magic_word.

If the magic_word is found, then you will be able to use the SR normally for your other tasks.

This can be detected by the WebAudioAPI, which is not tied by this time restriction SR suffers from. You can feed it by an LocalMediaStream from MediaDevices.getUserMedia.

For more info, on below script, you can see this answer.

Here is how you could attach it to a SpeechRecognition:

const magic_word = ##YOUR_MAGIC_WORD##;

// initialize our SpeechRecognition object
let recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.continuous = true;

// detect the magic word
recognition.onresult = e => {
    // extract all the transcripts
    var transcripts  = [].concat.apply([], [...e.results]
      .map(res => [...res]
        .map(alt => alt.transcript)
      )
    );
  if(transcripts.some(t => t.indexOf(magic_word) > -1)){
    //do something awesome, like starting your own command listeners
  }
  else{
    // didn't understood...
  }
}
// called when we detect silence
function stopSpeech(){
    recognition.stop();
}
// called when we detect sound
function startSpeech(){
    try{ // calling it twice will throw...
      recognition.start();
  }
  catch(e){}
}
// request a LocalMediaStream
navigator.mediaDevices.getUserMedia({audio:true})
// add our listeners
.then(stream => detectSilence(stream, stopSpeech, startSpeech))
.catch(e => log(e.message));

function detectSilence(
  stream,
  onSoundEnd = _=>{},
  onSoundStart = _=>{},
  silence_delay = 500,
  min_decibels = -80
  ) {
  const ctx = new AudioContext();
  const analyser = ctx.createAnalyser();
  const streamNode = ctx.createMediaStreamSource(stream);
  streamNode.connect(analyser);
  analyser.minDecibels = min_decibels;

  const data = new Uint8Array(analyser.frequencyBinCount); // will hold our data
  let silence_start = performance.now();
  let triggered = false; // trigger only once per silence event

  function loop(time) {
    requestAnimationFrame(loop); // we'll loop every 60th of a second to check
    analyser.getByteFrequencyData(data); // get current data
    if (data.some(v => v)) { // if there is data above the given db limit
      if(triggered){
        triggered = false;
        onSoundStart();
        }
      silence_start = time; // set it to now
    }
    if (!triggered && time - silence_start > silence_delay) {
      onSoundEnd();
      triggered = true;
    }
  }
  loop();
}
```

As a plunker, since neither StackSnippets nor jsfiddle's iframes will allow gUM in two versions...

Body:
Since your problem is that you can't run the SpeechRecognition continuously for long periods of time, one way would be to start the SpeechRecognition only when you get some input in the mic.

This way only when there is some input, you will start the SR, looking for your magic_word.

If the magic_word is found, then you will be able to use the SR normally for your other tasks.

This can be detected by the WebAudioAPI, which is not tied by this time restriction SR suffers from. You can feed it by an LocalMediaStream from MediaDevices.getUserMedia.

For more info, on below script, you can see this answer.

Here is how you could attach it to a SpeechRecognition:

const magic_word = ##YOUR_MAGIC_WORD##;

// initialize our SpeechRecognition object
let recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.continuous = true;

// detect the magic word
recognition.onresult = e => {
    // extract all the transcripts
    var transcripts  = [].concat.apply([], [...e.results]
      .map(res => [...res]
        .map(alt => alt.transcript)
      )
    );
  if(transcripts.some(t => t.indexOf(magic_word) > -1)){
    //do something awesome, like starting your own command listeners
  }
  else{
    // didn't understood...
  }
}
// called when we detect silence
function stopSpeech(){
    recognition.stop();
}
// called when we detect sound
function startSpeech(){
    try{ // calling it twice will throw...
      recognition.start();
  }
  catch(e){}
}
// request a LocalMediaStream
navigator.mediaDevices.getUserMedia({audio:true})
// add our listeners
.then(stream => detectSilence(stream, stopSpeech, startSpeech))
.catch(e => log(e.message));

function detectSilence(
  stream,
  onSoundEnd = _=>{},
  onSoundStart = _=>{},
  silence_delay = 500,
  min_decibels = -80
  ) {
  const ctx = new AudioContext();
  const analyser = ctx.createAnalyser();
  const streamNode = ctx.createMediaStreamSource(stream);
  streamNode.connect(analyser);
  analyser.minDecibels = min_decibels;

  const data = new Uint8Array(analyser.frequencyBinCount); // will hold our data
  let silence_start = performance.now();
  let triggered = false; // trigger only once per silence event

  function loop(time) {
    requestAnimationFrame(loop); // we'll loop every 60th of a second to check
    analyser.getByteFrequencyData(data); // get current data
    if (data.some(v => v)) { // if there is data above the given db limit
      if(triggered){
        triggered = false;
        onSoundStart();
        }
      silence_start = time; // set it to now
    }
    if (!triggered && time - silence_start > silence_delay) {
      onSoundEnd();
      triggered = true;
    }
  }
  loop();
}

As a plunker, since neither StackSnippets nor jsfiddle's iframes will allow gUM in two versions...


问:
How do I pass libsass configuration variables into a flask_assets bundle?
My goal is to set LIBSASS_STYLE="expanded" via flask_assets.Bundle. The webassets libsass documentation says I can do it, but doesn't say how.

My base app controller looks like the following.

```<code>from flask import Flask, render_template
from flask_assets import Environment, Bundle

app = Flask(__name__)

# ... Typical flask controller stuff

if __name__ == "__main__":
    assets = Environment(app)

    css = Bundle(
        'sass/*.scss',         # input scss files
        filters='libsass',     # to be compiled by libsass
        output='css/style.css' # and outputed to style.css
    )

    assets.register("asset_css", css)

    app.run(debug=True)
</code>```

This outputs a valid css file (which is great) but not in the format that I desire since I simply have no idea where I can slip any libsass options.

Any help on this issue is greatly welcome. Thanks!

答:
You need to instantiate libsass filter explicitly to pass options to it</p>

```<code>from flask_assets import Bundle
from webassets.filter import get_filter

libsass = get_filter(
    'libsass',
    as_output=True,
    style='compressed',
)

css = Bundle(
    'sass/*.scss',
    filters=(libsass),
    output='css/style.css'
)
</code>```

Body:
My goal is to set LIBSASS_STYLE="expanded" via flask_assets.Bundle. The webassets libsass documentation says I can do it, but doesn't say how.

My base app controller looks like the following.

from flask import Flask, render_template
from flask_assets import Environment, Bundle

app = Flask(__name__)

# ... Typical flask controller stuff

if __name__ == "__main__":
    assets = Environment(app)

    css = Bundle(
        'sass/*.scss',         # input scss files
        filters='libsass',     # to be compiled by libsass
        output='css/style.css' # and outputed to style.css
    )

    assets.register("asset_css", css)

    app.run(debug=True)

This outputs a valid css file (which is great) but not in the format that I desire since I simply have no idea where I can slip any libsass options.

Any help on this issue is greatly welcome. Thanks!

Body:
You need to instantiate libsass filter explicitly to pass options to it

from flask_assets import Bundle
from webassets.filter import get_filter

libsass = get_filter(
    'libsass',
    as_output=True,
    style='compressed',
)

css = Bundle(
    'sass/*.scss',
    filters=(libsass),
    output='css/style.css'
)


问:
thymeleaf th:each not looping
my web is read data from database and show it on table but not working as it should be.

my controller

```<code>public String printWelcome(ModelMap model) {
    model.addAttribute("message", "Hello world!");
    List<User> users = userDAO.getAllUser();
    model.addAttribute("users", users);
    return "hello";
}
</code>```

my view

```<code><!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
    <h1>${message}</h1>
    <h1>${users.get(0).username}</h1>
    <h1>${users.get(1).passw}</h1>
    <table>
        <thead>
        <tr>
            <th>name</th>
            <th>password</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="user : ${users}">
            <td th:text="${user.username}"/>
            <td th:text="${user.passw}"/>
        </tr>
        </tbody>
    </table>
</body>
</html>
</code>```

hello word is appear. also list content of username of first data and password on second data are also appear good. but the table contain loop data is not show up instead showing object on html code

```<code><tr th:each="user : [com.pckg.model.User@414e9cef, com.pckg.model.User@72d57b3c, com.pckg.model.User@2640e7f3, com.pckg.model.User@35ef8cf9, com.pckg.model.User@f3c74f, com.pckg.model.User@592640f6, com.pckg.model.User@78f84b5e, com.pckg.model.User@313998fc]">
    <td th:text=""></td>
    <td th:text=""></td>
</tr>
</code>```

答:
You have a problem configuring Thymeleaf inside your project, the 'th' tag in the source file should be converted to HTML after parsing, but the generated HTML still showing the original tags.

Check the InternalResourceViewResolver

Title: thymeleaf th:each not looping

Body:
my web is read data from database and show it on table but not working as it should be.

my controller

public String printWelcome(ModelMap model) {
    model.addAttribute("message", "Hello world!");
    List<User> users = userDAO.getAllUser();
    model.addAttribute("users", users);
    return "hello";
}

my view

<!DOCTYPE HTML>

${message}

${users.get(0).username}

${users.get(1).passw}

            name
            password

hello word is appear. also list content of username of first data and password on second data are also appear good. but the table contain loop data is not show up instead showing object on html code


问:
Truncation in python
How can we truncate (not round) the cube root of a given number after the 10th decimal place in python?

For Example:

If number is 8 the required output is 2.0000000000 and for 33076161 it is 321.0000000000

答:
What about this code .. I have created it for my personal use. although it is so simple, it is working well.    </p>

```<code>def truncation_machine(original,edge):
'''
Function of the function :) :
    it performs truncation operation on long decimal numbers.
Input:
    a) the number that needs to undergo truncation.
    b) the no. of decimals that we want to KEEP.
Output:
    A clean truncated number.
Example: original=1.123456789
         edge=4
         output=1.1234
'''
import math
g=original*(10**edge)
h=math.trunc(g)
T=h/(10**edge)
print('The original number ('+str(original)+') underwent a '+str(edge)+'-digit truncation to be in the form: '+str(T))
return T
</code>```

Title: Truncation in python

Body:
What about this code .. I have created it for my personal use. although it is so simple, it is working well.

def truncation_machine(original,edge):
'''
Function of the function :) :
    it performs truncation operation on long decimal numbers.
Input:
    a) the number that needs to undergo truncation.
    b) the no. of decimals that we want to KEEP.
Output:
    A clean truncated number.
Example: original=1.123456789
         edge=4
         output=1.1234
'''
import math
g=original*(10**edge)
h=math.trunc(g)
T=h/(10**edge)
print('The original number ('+str(original)+') underwent a '+str(edge)+'-digit truncation to be in the form: '+str(T))
return T


问:
Filter by One to many relation child data

I want to filter by the leadtransactions data (date)

Here i used the transaction details date in leadtransation table.i want to filter by particular date in my leadtransation.Kindly help me with the working sample or the particular code which am gonna write in DAO method.

```<code>@Entity
@Table(name = "lead_master")
public class Lead {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "lead_id", nullable = false, unique = true)
private int lead_id;

@Column(name = "first_name", nullable = false)
private String first_name;

@Column(name = "last_name")
private String last_name;

@Column(name = "company_name")
private String company_name;

@Column(name = "website")
private String website;

@Column(name = "email")
private String email;

@Column(name = "phone_number")
private String phone_number;

@Column(name = "job_type", nullable = false)
private String job_type;

@Column(name = "date", nullable = false)
private Date date;

@Column(name = "time_stamp", nullable = false)
private Date time_stamp;

@Column(name = "status", nullable = false)
private int status;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "lead_tx_relation", joinColumns = @JoinColumn(name = "lead_id"), inverseJoinColumns = @JoinColumn(name = "lead_tx_id"))
private Set<LeadTranscrations> LeadTranscrations;
</code>```

答:
I suppose that in LeadTranscrations class you have transDate as column attribute

for this

```<code>private Set<LeadTranscrations> leadTranscrations;
</code>```

you can use query method for this

```<code>List<Lead> findByLeadTranscrationsTransDate(Date transDate);
</code>```

you can also add order by

```<code>List<Lead> findByLeadTranscrationsTransDateOrderByTransDateAsc(Date transDate);
</code>```

Body:
I want to filter by the leadtransactions data (date)

Here i used the transaction details date in leadtransation table.i want to filter by particular date in my leadtransation.Kindly help me with the working sample or the particular code which am gonna write in DAO method.

@Entity
@Table(name = "lead_master")
public class Lead {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "lead_id", nullable = false, unique = true)
private int lead_id;

@Column(name = "first_name", nullable = false)
private String first_name;

@Column(name = "last_name")
private String last_name;

@Column(name = "company_name")
private String company_name;

@Column(name = "website")
private String website;

@Column(name = "email")
private String email;

@Column(name = "phone_number")
private String phone_number;

@Column(name = "job_type", nullable = false)
private String job_type;

@Column(name = "date", nullable = false)
private Date date;

@Column(name = "time_stamp", nullable = false)
private Date time_stamp;

@Column(name = "status", nullable = false)
private int status;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "lead_tx_relation", joinColumns = @JoinColumn(name = "lead_id"), inverseJoinColumns = @JoinColumn(name = "lead_tx_id"))
private Set<LeadTranscrations> LeadTranscrations;

Body:
I suppose that in LeadTranscrations class you have transDate as column attribute

for this

private Set<LeadTranscrations> leadTranscrations;

you can use query method for this

List<Lead> findByLeadTranscrationsTransDate(Date transDate);

you can also add order by

List<Lead> findByLeadTranscrationsTransDateOrderByTransDateAsc(Date transDate);


答: It is possibly downloading the dependencies. Make sure you have a proper internet connection for gradle to download the dependeicies. If you are behind a proxy server configure the proxy in gradle.properties file before opening the project.</p>

Title: Android Studio Freezes at Gradle Build

Body: I just installed Android Studio on Windows 10, and tried to create my first App ("Hello World") from the Studio website. The program gets stuck (but computer remains responsive) at the "Gradle Build" step. I saw another post on this topic, referring to firewall issues, but no resolution. I turned off my firewall, but the problem persisted. Also, I looked on Task Manager and the Android Studio task was using 83% of memory (>480MB). Many thanks in advance if any ideas! Screenshot:


答: For a pc, if you want a fairly simple notepad like app with syntax highlighting, I'd pick TextPad... You can associate syntax files and "customize" as needed.  For a mac I'd pick BBEdit...</p>

Title: Software for taking notes on programming

Body:
What type of software is good for taking notes on programming?  For example, if I want to jot down different methods/functions that are useful for different things.  Ideally, the software would have  syntax highlighting.

The software would need to support Mac OS X.  I will most probably be using this for Objective-C/iPhone development and Ruby on Rails development.

I want something that can shift between ordinary text and coding syntax.  For example if I was to type:

In order to create a rectangle in Objective-C with a name square use: (CGRect *) square...........

I would like the objective-C code to have syntax highlighting but not the rest of the text.

Thanks!

P.S. I use textmate generally for coding.


问:
generate csr with entry type: trustedCertEntry
I got two question regarding the Java keytool. Can I generate csr for trustedCertEntry?

I also executed this command:

```<code>keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr
</code>```

for a trustedCertEntry but I get error:

```<code>keytool error: java.lang.Exception: Alias <mydomain> has no key
</code>```

which means a trustedCertEntry cannot generate csr? Or I need to have something, or a key to generate csr file?

答:
I need to have something, or a key to generate csr file?

Correct. You need a keypair. You can't generate a CSR from somebody else's certificate. Otherwise the whole X.509 system would be insecure.

Body:
I got two question regarding the Java keytool. Can I generate csr for trustedCertEntry?

I also executed this command:

keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr

for a trustedCertEntry but I get error:

keytool error: java.lang.Exception: Alias <mydomain> has no key

which means a trustedCertEntry cannot generate csr? Or I need to have something, or a key to generate csr file?


问:
Can't get the html render conditionally?
I have a strange incident in getting the html page rendering conditionally with asp.net core 2.0

```<code>    <head>
        @{
                var user = await _userManager.FindByNameAsync(User.Identity.Name);
         }
    </head>
    <body>
     @if (user != null)
     {
       <a href="/user/edit/?username=@user.UserName" class="dropdown-toggle">
       <span class="hidden-xs">@user.FullName</span>
                                   </a>
     }
   </body>
</code>```

For this layout, it gives errors: "The name 'user' does not exist in the current context It used to work fine in .net core 1.1 and classic asp.net.

However, if I do like this, then it works fine. So strange.

```<code><body>
@{
    var user = await _userManager.FindByNameAsync(User.Identity.Name);
   if (user != null)
    {
      <a href="/user/edit/?username=@user.UserName" class="dropdown-toggle">
       <span class="hidden-xs">@user.FullName</span>
                               </a>
     }
 }
</code>```

答:
It seems you can't declare variables inside "head" tag. I tried the following and it worked just fine:</p>

```<code>@{
    var user = await _userManager.FindByNameAsync(User.Identity.Name);
}
<head>
    ...
</head>
<body>
@if (user != null)
{
    <a href="/user/edit/?username=@user.UserName" class="dropdown-toggle">
        <span class="hidden-xs">@user.FullName</span>
    </a>
}
</body>
</code>```

Body:
I have a strange incident in getting the html page rendering conditionally with asp.net core 2.0

        @{
                var user = await _userManager.FindByNameAsync(User.Identity.Name);
         }

     @if (user != null)
     {

       @user.FullName

     }

For this layout, it gives errors: "The name 'user' does not exist in the current context It used to work fine in .net core 1.1 and classic asp.net.

However, if I do like this, then it works fine. So strange.

@{
    var user = await _userManager.FindByNameAsync(User.Identity.Name);
   if (user != null)
    {

       @user.FullName

     }
 }

Body:
It seems you can't declare variables inside "head" tag. I tried the following and it worked just fine:

@{
    var user = await _userManager.FindByNameAsync(User.Identity.Name);
}
<head>
    ...
</head>
<body>
@if (user != null)
{
    <a href="/user/edit/?username=@user.UserName" class="dropdown-toggle">
        <span class="hidden-xs">@user.FullName</span>
    </a>
}
</body>


问:
How to convert binary file into readable format on linux server
I am trying to convert binary file into readable format but unable to do so, please suggest how it could be achieved.</p>

```<code>$ file test.docx
test.docx: Microsoft Word 2007+
$ file -i test.docx
test.docx: application/msword; charset=binary
$

>>> raw = codecs.open('test.docx', encoding='ascii').readlines()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 694, in readlines
    return self.reader.readlines(sizehint)
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 603, in readlines
    data = self.read()
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 492, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 18: ordinal not in range(128)
</code>```

答:
Try the below code, Working with Binary Data</p>

```<code>with open("test_file.docx", "rb") as binary_file:
# Read the whole file at once
data = binary_file.read()
print(data)

# Seek position and read N bytes
binary_file.seek(0)  # Go to beginning
couple_bytes = binary_file.read(2)
print(couple_bytes)
</code>```

Body:
I am trying to convert binary file into readable format but unable to do so, please suggest how it could be achieved.

$ file test.docx
test.docx: Microsoft Word 2007+
$ file -i test.docx
test.docx: application/msword; charset=binary
$

>>> raw = codecs.open('test.docx', encoding='ascii').readlines()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 694, in readlines
    return self.reader.readlines(sizehint)
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 603, in readlines
    data = self.read()
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 492, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 18: ordinal not in range(128)

Body:
Try the below code, Working with Binary Data

with open("test_file.docx", "rb") as binary_file:
# Read the whole file at once
data = binary_file.read()
print(data)

# Seek position and read N bytes
binary_file.seek(0)  # Go to beginning
couple_bytes = binary_file.read(2)
print(couple_bytes)


问:
Pandas not able to access non-indexed column
I'm trying to create a churn model using the data from Kaggle. When I try and do a train_test_split I get a KeyError: "['temin' 'tdchar'] not in index" Does anyone know if I really need to index the columns to access the data?
Below is my code:

```<code>import pandas as pd
from sklearn.cross_validation import train_test_split
df_churn = pd.read_csv("https://storage.googleapis.com/kaggle-competitions-data/kaggle/6716/churn_train.txt?GoogleAccessId=competitions-data@kaggle-161607.iam.gserviceaccount.com&Expires=1510894749&Signature=TjX%2ByvtIpVtVls5YK48iS%2Fpu4ajHGARwNsLNVz5SVEO8SBz9SPZVkdR0vHj4nRbJY3LxDHXXP3jsRdIoljaExRy1oZ%2Fadk2q08besx8RZdHlhv7wEd1r6Djqe9ybfMusgL42%2BQvEg4FuIKf3Ayzuxz%2BXaN1rIZZkRMgcj7XFpL3ao6ITgI3XjfM%2FrYs5CIGS2r75Az6YWe5PjFhzjGb23ndYo%2Ftzh02QcDwZ6122f3sAwY045tWcY4NZNOA7EiAt7l12wifiI1NytB5Q2cid9YFUhIx5mSVOqXaXr6NCbj62VpVTq9Ic76w5UT9tu%2FsFjTS7WN5hQY625IT3yAxoFg%3D%3D")

X_train, y_train, X_test, y_test = train_test_split(df_churn[["temin","tdchar"]],df_churn[["label"]],test_size=.3)
</code>```

I get the following error message:

```<code>KeyError: "['temin' 'tdchar'] not in index"
</code>```

答:
Your column names have whitespaces in them:

```<code>df_churn.columns

Index(['st', ' acclen', ' arcode', ' phnum', ' intplan', ' voice',
       'nummailmes', ' tdmin', ' tdcal', ' tdchar', ' temin', ' tecal',
       ' tecahr', ' tnmin', ' tn cal', ' tnchar', ' timin', ' tical',
       ' tichar ncsc', ' label'],
      dtype='object')
</code>```

So, strip them:

```<code>df_churn.columns = df_churn.columns.str.strip()
</code>```

This works now!

```<code>X = df_churn[["temin", "tdchar"]]
y = df_churn[["label"]]
X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=.3)
</code>```

Body:
I'm trying to create a churn model using the data from Kaggle. When I try and do a train_test_split I get a KeyError: "['temin' 'tdchar'] not in index" Does anyone know if I really need to index the columns to access the data?
Below is my code:

import pandas as pd
from sklearn.cross_validation import train_test_split
df_churn = pd.read_csv("https://storage.googleapis.com/kaggle-competitions-data/kaggle/6716/churn_train.txt?GoogleAccessId=competitions-data@kaggle-161607.iam.gserviceaccount.com&Expires=1510894749&Signature=TjX%2ByvtIpVtVls5YK48iS%2Fpu4ajHGARwNsLNVz5SVEO8SBz9SPZVkdR0vHj4nRbJY3LxDHXXP3jsRdIoljaExRy1oZ%2Fadk2q08besx8RZdHlhv7wEd1r6Djqe9ybfMusgL42%2BQvEg4FuIKf3Ayzuxz%2BXaN1rIZZkRMgcj7XFpL3ao6ITgI3XjfM%2FrYs5CIGS2r75Az6YWe5PjFhzjGb23ndYo%2Ftzh02QcDwZ6122f3sAwY045tWcY4NZNOA7EiAt7l12wifiI1NytB5Q2cid9YFUhIx5mSVOqXaXr6NCbj62VpVTq9Ic76w5UT9tu%2FsFjTS7WN5hQY625IT3yAxoFg%3D%3D")

X_train, y_train, X_test, y_test = train_test_split(df_churn[["temin","tdchar"]],df_churn[["label"]],test_size=.3)

I get the following error message:

KeyError: "['temin' 'tdchar'] not in index"

Body:
Your column names have whitespaces in them:

df_churn.columns

Index(['st', ' acclen', ' arcode', ' phnum', ' intplan', ' voice',
       'nummailmes', ' tdmin', ' tdcal', ' tdchar', ' temin', ' tecal',
       ' tecahr', ' tnmin', ' tn cal', ' tnchar', ' timin', ' tical',
       ' tichar ncsc', ' label'],
      dtype='object')

So, strip them:

df_churn.columns = df_churn.columns.str.strip()

This works now!

X = df_churn[["temin", "tdchar"]]
y = df_churn[["label"]]
X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=.3)


问:
AVCaptureVideoPreviewLayer orientation - need landscape
My app is landscape only. I'm presenting the AVCaptureVideoPreviewLayer like this:

```<code>self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
[self.previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
[self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
NSLog(@"previewView: %@", self.previewView);
CALayer *rootLayer = [self.previewView layer];
[rootLayer setMasksToBounds:YES];
[self.previewLayer setFrame:[rootLayer bounds]];
    NSLog(@"previewlayer: %f, %f, %f, %f", self.previewLayer.frame.origin.x, self.previewLayer.frame.origin.y, self.previewLayer.frame.size.width, self.previewLayer.frame.size.height);
[rootLayer addSublayer:self.previewLayer];
[session startRunning];
</code>```

self.previewView has a frame of (0,0,568,320), which is correct. self.previewLayer logs a frame of (0,0,568,320), which is theoretically correct. However, the camera display appears as a portrait rectangle in the middle of the landscape screen, and the orientation of the camera preview image is wrong by 90 degrees. What am I doing wrong? I need the camera preview layer to appear in the full screen, in landscape mode, and the image should be orientated correctly.

答:
Works with Swift 4, Xcode 9:

```<code>  override func viewWillTransition(to size: CGSize,
                                   with coordinator: UIViewControllerTransitionCoordinator)
  {
    super.viewWillTransition(to: size, with: coordinator)
    guard
    let conn = self.previewLayer?.connection,
      conn.isVideoOrientationSupported
      else { return }
    let deviceOrientation = UIDevice.current.orientation
    switch deviceOrientation {
    case .portrait: conn.videoOrientation = .portrait
    case .landscapeRight: conn.videoOrientation = .landscapeLeft
    case .landscapeLeft: conn.videoOrientation = .landscapeRight
    case .portraitUpsideDown: conn.videoOrientation = .portraitUpsideDown
    default: conn.videoOrientation = .portrait
    }
  }
</code>```

One subtlety to notice here is that UIDeviceOrientation.landscapeRight goes with AVCaptureVideoOrientation.landscapeLeft.

The other landscape case is similarly mismatched. This is deliberate, and accommodates an unfortunate mismatch between UIKit and AVFoundation. If you match the cases up by matching the names, it won't work, and your video will be upside down in landscape configurations.

ContentLicense: CC BY-SA 4.0

Body:
My app is landscape only. I'm presenting the AVCaptureVideoPreviewLayer like this:

self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
[self.previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
[self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
NSLog(@"previewView: %@", self.previewView);
CALayer *rootLayer = [self.previewView layer];
[rootLayer setMasksToBounds:YES];
[self.previewLayer setFrame:[rootLayer bounds]];
    NSLog(@"previewlayer: %f, %f, %f, %f", self.previewLayer.frame.origin.x, self.previewLayer.frame.origin.y, self.previewLayer.frame.size.width, self.previewLayer.frame.size.height);
[rootLayer addSublayer:self.previewLayer];
[session startRunning];

self.previewView has a frame of (0,0,568,320), which is correct. self.previewLayer logs a frame of (0,0,568,320), which is theoretically correct. However, the camera display appears as a portrait rectangle in the middle of the landscape screen, and the orientation of the camera preview image is wrong by 90 degrees. What am I doing wrong? I need the camera preview layer to appear in the full screen, in landscape mode, and the image should be orientated correctly.

Body:
Works with Swift 4, Xcode 9:

  override func viewWillTransition(to size: CGSize,
                                   with coordinator: UIViewControllerTransitionCoordinator)
  {
    super.viewWillTransition(to: size, with: coordinator)
    guard
    let conn = self.previewLayer?.connection,
      conn.isVideoOrientationSupported
      else { return }
    let deviceOrientation = UIDevice.current.orientation
    switch deviceOrientation {
    case .portrait: conn.videoOrientation = .portrait
    case .landscapeRight: conn.videoOrientation = .landscapeLeft
    case .landscapeLeft: conn.videoOrientation = .landscapeRight
    case .portraitUpsideDown: conn.videoOrientation = .portraitUpsideDown
    default: conn.videoOrientation = .portrait
    }
  }

One subtlety to notice here is that UIDeviceOrientation.landscapeRight goes with AVCaptureVideoOrientation.landscapeLeft.

The other landscape case is similarly mismatched. This is deliberate, and accommodates an unfortunate mismatch between UIKit and AVFoundation. If you match the cases up by matching the names, it won't work, and your video will be upside down in landscape configurations.


问:
Confused with homebrew version mysql and official mysql preferences pane on mac
I downloaded mysql for my Mac from official website 'mysql.com', then launched it on my server using preferences pane and as well as from command line using

sudo /usr/local/etc/mysql/support-files/mysql.server start

Its working good, but during my development process i want to change the sql_mode,because i am getting below error

sql_mode=only_full_group_by

Many of them said to change sql mode config in /usr/mysql/my.cnf, but unfortunately i don't see that directory on my mac, So i installed Homebrew version mysql ,this also not working.

My Problem is where I can find my.cnf file on my mac? now i am not using homebrew version of mysql, I'm using official mysql downloaded from mysql.com/downloads.

答: Run mysql --help it will show you the config file that is being loaded.


问:
Visual studio 2010 connects all databases in Server Explorer when opening a solution
Basicly, I think the title of the post here says it all.

I am working with Visual Studio 2010 Ultimate 10.0.30319.1 RTMRel.
EDIT: I am running Windows 7 x64.

Everytime I open a solution it tries to connect to all databases present in Server Explorer. My problem is that some of them are not always available over internet so I must wait for the timeout. Anyone as ever experienced the same problem ?

I am usign the PRO version at home and it does not do it.

I disabled every plugin into Visual Studio and now I am stuck with this problem.

Finally, even Google did not help me so this is why I am trying here.

Thanks a lot.

答:
here's my connect bug for a similar issue. Please upvote if you encounter this lameness.
https://connect.microsoft.com/VisualStudio/feedback/details/636679/visual-studio-2010-sp1-beta-tries-to-open-db-connections-when-opening-project-properties</p>


问:
Aurigma PACKAGE UPLOAD ERROR - ERROR CODE 6
We are testing the trail package on QA server and we encountered the following issue.please help us to fix this issue

we tried  uploading the folder of 2GB using HTML5 uploader, it is working in Chrome but in Mozilla Firefox v54 it is getting failed. we tried uploading 2Gb folder for 4 times but in all 4 times it failed. so we enabled the aurigma debug mode and then uploaded the 2GB folder it showed package uploader error.

[htmluploader_trace] [WARNING] Package upload error
      { errorCode: 6, errorMessage: "Internal Server Error [500]", responseText: "" }

In apache error log it showed

PHP Fatal error:  Uncaught exception 'Exception' with message 'Upload
  request is invalid.' in
  /home/application/libraries/aurigma/ImageUploaderFlashPHP/UploadSession.class.php:142\nStack
  trace:\n#0
  /home/application/libraries/aurigma/ImageUploaderFlashPHP/UploadSession.class.php(32):
  UploadSession->validateRequest()\n#1
  /home/application/libraries/aurigma/ImageUploaderFlashPHP/UploadHandler.class.php(135):
  UploadSession->processRequest()\n#2
  /home/application/libraries/aurigma/ImageUploaderFlashPHP/UploadHandler.class.php(186):
  UploadHandler->processRequest()\n#3
  /home/application/libraries/aurigma/Aurigmabackend.php(10):
  UploadHandler->saveFiles('/mnt/uploads/di...')\n#4
  /home/application/controllers/create.php(565):
  Aurigmabackend->initialize('/uploads/di...')\n#5 [internal function]:
  create->htmlflashupload()\n#6 /home/system/core/CodeIgniter.php(359):
  call_user_func_array(Array, Array)\n#7 /home/index.php(203):
  require_once('/home/...')\n#8 in
  /home/application/libraries/aurigma/ImageUploaderFlashPHP/UploadSession.class.php
  on line 142.

We further investigated the error in html5 uploader in Firefox. we added the log in the backend and checked the post parameters that are been sent from client. we found that some of the post parameters were missing for a file that failed to upload.

Missing post parameters were RequestCount, PackageComplete and RequestComplete but these parameters are their in the post parameters in the browsers.

答:
Error code 6 is - goog.net.ErrorCode.HTTP_ERROR, The Http response
returned a non-successful http status code (500)

Https status 500 -
is a server error.

Upload request is invalid - Aurigma Uploader
request consists of some required fields such as
packageGuid,requestComplete,packageCount.

Your request is
   incomplete and don't have all required fields. Check constructor of UploadSession.php. Check $_POST and $post objects

If you can't find error yourself, you may ask a help from Aurigma support team.


问:
check if arraylist is NOT empty java
I know the isEmpty() method used to check if an arraylist is empty, but I am trying to check if an arraylist is not empty. I tried to look online but I didn't find any useful information on how to do this. My code is like "while ArrayList is not empty then run code).</p>

答:
Alternatively, you can also check whether the array is null by the length/size of the arraylist. </p>

```<code>while(arrayListName.size() > 0 ){
//execute code
}
</code>```

Title: check if arraylist is NOT empty java

Body:
Alternatively, you can also check whether the array is null by the length/size of the arraylist.

while(arrayListName.size() > 0 ){
//execute code
}


问:
HTML mobile redirect only working on page refresh
I have a website that I want to redirect on a particular page for mobile users, so the following is currently in the header of the relevant page

```<code><script type="text/javascript">
if (screen.width<640) {
window.location="mobilePage";
}
</script>
</code>```

If I click from the main navigation, this does nothing. However, I refresh the page, it works. Part of the trouble is that I've used a website builder, on account of not being any good at graphic design and not wanting to have to keep up with new phones / versions of things. That means a lot of code is hidden from me, which makes it phenomenally harder to debug. I've tried forcing it to reload once, but no dice.

Does anyone have any insight as to why this is happening, and more importantly if there's anything I can do? It would be much appreciated!

(PS Not sure if the website is helpful to elucidate my struggle, but the page in question is here.)

答:
Instead of depending on the screen width, try using regex code and navigator. For Example,

```<code>  if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 window.location="mobilePage";
}
</code>```

Hope this works

Body:
I have a website that I want to redirect on a particular page for mobile users, so the following is currently in the header of the relevant page

If I click from the main navigation, this does nothing. However, I refresh the page, it works. Part of the trouble is that I've used a website builder, on account of not being any good at graphic design and not wanting to have to keep up with new phones / versions of things. That means a lot of code is hidden from me, which makes it phenomenally harder to debug. I've tried forcing it to reload once, but no dice.

Does anyone have any insight as to why this is happening, and more importantly if there's anything I can do? It would be much appreciated!

(PS Not sure if the website is helpful to elucidate my struggle, but the page in question is here.)

Body:
Instead of depending on the screen width, try using regex code and navigator. For Example,

  if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 window.location="mobilePage";
}

Hope this works


问:
ng2-file-upload ASP.NET Core MVC - Chunk Upload Progress
I'm using the ng2-file-upload package hitting an ASP.NET Core backend.

https://github.com/valor-software/ng2-file-upload

Using the base example, trying to test a large file upload ~50MB.

The file eventually uploads, but no progress/chunk action is happening. It basically uploads all at once after sitting a while.

What do I need to change to get progress/chunk upload?

ng2 component:

```<code>import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';

@Component({
    selector: 'fileupload',
    templateUrl: './fileupload.component.html'
})
export class FileUploadComponent implements OnInit {

    public uploader: FileUploader = new FileUploader({ url: '/api/purchaseorder/upload' });

    ngOnInit() {

        this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {

            console.log("ImageUpload:uploaded:", item, status);
        };
    }

    public hasBaseDropZoneOver: boolean = false;
    public hasAnotherDropZoneOver: boolean = false;

    public fileOverBase(e: any): void {
        this.hasBaseDropZoneOver = e;
    }

    public fileOverAnother(e: any): void {
        this.hasAnotherDropZoneOver = e;
    }
}
</code>```

asp.net mvc controller/action:

```<code>    public ActionResult Upload(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            return NoContent();
        }

        // handle file here

        return Ok();
    }
</code>```

答:
When you ask for IFormFile to be passed into the action as a parameter, it will need to load the entire file before the action can be processed. Instead pull the IFormFile from the current request like so:</p>

```<code>public ActionResult Upload()
{
    foreach (IFormFile file in Request.Form.Files)
    {
        if (file == null || file.Length == 0)
        {
            return NoContent();
        }

        // handle file here
        var stream = file.OpenReadStream();
    {

    return Ok();
}
</code>```

Body:
I'm using the ng2-file-upload package hitting an ASP.NET Core backend.

https://github.com/valor-software/ng2-file-upload

Using the base example, trying to test a large file upload ~50MB.

The file eventually uploads, but no progress/chunk action is happening. It basically uploads all at once after sitting a while.

What do I need to change to get progress/chunk upload?

ng2 component:

import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';

@Component({
    selector: 'fileupload',
    templateUrl: './fileupload.component.html'
})
export class FileUploadComponent implements OnInit {

    public uploader: FileUploader = new FileUploader({ url: '/api/purchaseorder/upload' });

    ngOnInit() {

        this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {

            console.log("ImageUpload:uploaded:", item, status);
        };
    }

    public hasBaseDropZoneOver: boolean = false;
    public hasAnotherDropZoneOver: boolean = false;

    public fileOverBase(e: any): void {
        this.hasBaseDropZoneOver = e;
    }

    public fileOverAnother(e: any): void {
        this.hasAnotherDropZoneOver = e;
    }
}

asp.net mvc controller/action:

    public ActionResult Upload(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            return NoContent();
        }

        // handle file here

        return Ok();
    }

Body:
When you ask for IFormFile to be passed into the action as a parameter, it will need to load the entire file before the action can be processed. Instead pull the IFormFile from the current request like so:

public ActionResult Upload()
{
    foreach (IFormFile file in Request.Form.Files)
    {
        if (file == null || file.Length == 0)
        {
            return NoContent();
        }

        // handle file here
        var stream = file.OpenReadStream();
    {

    return Ok();
}


问:
Magento order mail are not going to customer?
My magento site stoped sending the order mail to customer, i have checked several answer, but nothing works for me.
I tried to send mail with php mail funtion, its working but mail going to spam also. Is this may be a reason?</p>

答:
If mails are going to spam, then there may be chances of mis configuration in server, alternatively you can install the below extension & configure in backend , than mails will go to inbox....

https://github.com/aschroder/Magento-SMTP-Pro-Email-Extension

http://www.aschroder.com/product/smtppro-magento-smtp-email/


问:
javascript code to get the html tag information and store in a variable in js code
I have an html page with content and a button. When clicked on the getData button, a javascript function is called where I have to store each html tag information to a variable.

Demo : https://plnkr.co/edit/wuIsu1qhcrYeoxtkrGxC?p=preview

js code:

```<code>function getData(){
        var $divs = $('.div1')
        alert($divs);   //[object Object] is printed
      //var p_tags;
      //var ul_tags;
    }
</code>```

html code:

```<code> <div>
        <button onClick="getData()">GetData</button>

   <div class="div1">
<p>The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly) </p>

<p><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">This article is about the Internet encyclopedia. For Wikipedia's home page, see </span><a href="https://en.wikipedia.org/wiki/Main_Page" title="Main Page" style="color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia's Main Page</a><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">. For Wikipedia's visitor introduction, see </span><a href="https://en.wikipedia.org/wiki/Wikipedia:About" title="Wikipedia:About" style="color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia's About Page</a><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">. For other uses, see </span><a href="https://en.wikipedia.org/wiki/Wikipedia_(disambiguation)" class="mw-disambig" title="Wikipedia (disambiguation)" style="text-decoration-line: underline; color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia </a></p>
<ul><li>one</li><li>two</li></ul>
  </div></div>
</code>```

答:
Use text() method to get tag information

```<code>function getData(){
    var $divs = $('.div1').text();

    var p_tags = $('.div1 p').text();
    var ul_tags = $('.div1 ul').text();
}
</code>```

In Case you want full HTMl then use html() method.

Body:
I have an html page with content and a button. When clicked on the getData button, a javascript function is called where I have to store each html tag information to a variable.

Demo : https://plnkr.co/edit/wuIsu1qhcrYeoxtkrGxC?p=preview

js code:

function getData(){
        var $divs = $('.div1')
        alert($divs);   //[object Object] is printed
      //var p_tags;
      //var ul_tags;
    }

html code:

        <button onClick="getData()">GetData</button>

The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly)

This article is about the Internet encyclopedia. For Wikipedia's home page, see Wikipedia's Main Page. For Wikipedia's visitor introduction, see Wikipedia's About Page. For other uses, see Wikipedia

one

two

Body:
Use text() method to get tag information

function getData(){
    var $divs = $('.div1').text();

    var p_tags = $('.div1 p').text();
    var ul_tags = $('.div1 ul').text();
}

In Case you want full HTMl then use html() method.


问:
Software for taking notes on programming
What type of software is good for taking notes on programming?  For example, if I want to jot down different methods/functions that are useful for different things.  Ideally, the software would have  syntax highlighting.

The software would need to support Mac OS X.  I will most probably be using this for Objective-C/iPhone development and Ruby on Rails development.

I want something that can shift between ordinary text and coding syntax.  For example if I was to type:

In order to create a rectangle in Objective-C with a name square use: (CGRect *) square...........

I would like the objective-C code to have syntax highlighting but not the rest of the text.

Thanks!

P.S. I use textmate generally for coding.

Body: Try Evernote. http://www.evernote.com/


问:
Angular4 importing local js file indicates 404 not found
I set up a new project using "ng new xxx",
 just add one line in index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>Bbb</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

```

Then put the JS file in the same dir as index.html

the same dir

But when I run "ng server", the browser always show: 404

the js file not found

Does anyone know why? Thanks in advance.

答:
If you want to create a new folder i.e. "data". Then you will have to add "data" in "assets" array of angular-cli.json file. See below JSON data :-

```<code>    "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "data",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": ["data/sample.js"],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
</code>```

After that don't forget to restart the server. Otherwise you will get 404 error.

Body:
I set up a new project using "ng new xxx",
 just add one line in index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>Bbb</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

Then put the JS file in the same dir as index.html

the same dir

But when I run "ng server", the browser always show: 404

the js file not found

Does anyone know why? Thanks in advance.

Body:
If you want to create a new folder i.e. "data". Then you will have to add "data" in "assets" array of angular-cli.json file. See below JSON data :-

    "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "data",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": ["data/sample.js"],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],

After that don't forget to restart the server. Otherwise you will get 404 error.


问:
Change SearchView TextSize
I have the following SearchView implementation in the xml, the text entry has been cut from the top as shown in the below image. No matter what textSize I am putting, nothing changes.

```<code><LinearLayout
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="32dp"
   android:gravity="center_vertical"
   android:layout_marginTop="10dp">
     <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="12sp"/>
</LinearLayout>
</code>```

答:
```<code>sv= (SearchView) findViewById(R.id.search_view);
TextView searchText = (TextView)
sv.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
</code>```

Title: Change SearchView TextSize

Body:
I have the following SearchView implementation in the xml, the text entry has been cut from the top as shown in the below image. No matter what textSize I am putting, nothing changes.

<LinearLayout
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="32dp"
   android:gravity="center_vertical"
   android:layout_marginTop="10dp">
     <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="12sp"/>
</LinearLayout>


答:
What you try to output via alert is a jQuery object. Browser alert cannot show the details of objects — instead [object Object] is printed.

However, if you try console.log($divs), you can see the details of the jQuery object, on which you can execute various methods to manipulate DOM.

For example, you can get the inner HTML of the selected
s like this:

```<code>console.log($divs.html())
</code>```

Title: javascript code to get the html tag information and store in a variable in js code

Body:
What you try to output via alert is a jQuery object. Browser alert cannot show the details of objects — instead [object Object] is printed.

However, if you try console.log($divs), you can see the details of the jQuery object, on which you can execute various methods to manipulate DOM.

For example, you can get the inner HTML of the selected <div>s like this:

console.log($divs.html())