问:
Handle aggregate promise of EachPromise (each_limit) in Guzzle

The task

Suppose we have an API POST endpoint which returns answer like this:

```<code>{
  "data": [1,2,3],
  "total_rows": 20
}
</code>```

Which means that we received data partially, only the first page of 3 entries. The total entries count is 20, which means we want to call other pages using some offset in request. The total count (and possibly offset) is therefore only known after the first call is completed, while other calls do not depend on each other and can be done simultaneously.

The Toolset

It's PHP and for this task Guzzle 6 is used with Promises/A+. Additionally, Guzzle offers EachPromise class, which receives an iterable of multiple promises and a config hash to setup processing. As per PhpDoc block of that class constructor:

Configuration hash can include the following key value pairs:

fulfilled: (callable) Invoked when a promise fulfills. The function   is invoked with three arguments: the fulfillment value, the index

  position from the iterable list of the promise, and the aggregate

  promise that manages all of the promises. The aggregate promise may

  be resolved from within the callback to short-circuit the promise.

rejected: (callable) Invoked when a promise is rejected. The   function is invoked with three arguments: the rejection reason, the

  index position from the iterable list of the promise, and the

  aggregate promise that manages all of the promises. The aggregate

  promise may be resolved from within the callback to short-circuit

  the promise.

concurrency: (integer) Pass this configuration option to limit the   allowed number of outstanding concurrently executing promises,

  creating a capped pool of promises. There is no limit by default.

The code

$paginatedResult = $this->client->sendAsync($this->createRequest($requestBody))
    ->then(function (ResponseInterface $response) use ($requestBody) {
            return $this->deserializeToPaginatedResult(
                $response,
                $requestBody->paginatedResultClass()
            );
        }
    )->wait();

$pageGenerator = function () use ($paginatedResult, $requestBody) {
    $perPageCount = count($paginatedResult->getItems());
    $totalItems = $paginatedResult->getTotalCount();

    for ($currentOffset = $perPageCount; $currentOffset <= $totalItems; $currentOffset += $perPageCount) {
        $newRequestBody = clone $requestBody;
        $newRequestBody->setOffset($currentOffset);

        yield $this->client->sendAsync($this->createRequest($newRequestBody));
    }
};

$aggregatedResult = (new EachPromise(
    $pageGenerator(), [
        'concurrency' => 4,
        'fulfilled' => function ($promiseResult, $promiseIndex, $promiseAggregate) use ($requestBody) {
            $paginatedResult = $this->deserializeToPaginatedResult(
                $promiseResult,
                $requestBody->paginatedResultClass()
            );

            return $paginatedResult->getItems();
        },
    ]
))->promise()
    ->then(
        function ($promisedAggregatedResult) {
            var_dump($promisedAggregatedResult);
        }
    )
    ->wait();

var_dump($aggregatedResult);
```

The problem

In the config hash the fulfilled callback receives 3 objects, as documentation states. The $promiseResult can be properly handled and $paginatedResult->getItems() actually returns an array of items in requested page, but I cannot aggregate those items. The $aggregatedResult is null, and the $promisedAggregatedResult inside the last thened fulfillment callback is also null.

The question

How should one properly use Guzzle's EachPromise (and it's helper functions each and each_limit) to aggregate results of all the promises passed to it?

答:
The reason

As per EachPromise class description:

Represents a promise that iterates over many promises and invokes
side-effect functions in the process.

So those config hash callables are just side-effect functions which might or might not short-circuit resolve the aggregate promise. And that's exactly is the reason why fulfillment function neither affected the $promiseAggregate, nor ended up in last then fulfillment callable argument $promisedAggregatedResult.

The hint on proper usage can be found in \GuzzleHttp\Promise\all and \GuzzleHttp\Promise\some functions. The key idea is to use external aggregate by reference in those side-effect fulfilled/rejected callbacks. If the aggregate promise is never resolved inside those side-effect function, then it resolves to null, which is then passed on in the next then fulfillment callback. Again, one should use aggregate by reference in the fulfillment callable just to return it as promise fulfillment value.

The actual code solution

$paginatedResult = $this->client->sendAsync($this->createRequest($requestBody))
    ->then(function (ResponseInterface $response) use ($requestBody) {
            return $this->deserializeToPaginatedResult(
                $response,
                $requestBody->paginatedResultClass()
            );
        }
    )->wait();

$pageGenerator = function () use ($paginatedResult, $requestBody) {
    $perPageCount = count($paginatedResult->getItems());
    $totalItems = $paginatedResult->getTotalCount();

    for ($currentOffset = $perPageCount; $currentOffset <= $totalItems; $currentOffset += $perPageCount) {
        $newRequestBody = clone $requestBody;
        $newRequestBody->setOffset($currentOffset);

        yield $this->client->sendAsync($this->createRequest($newRequestBody));
    }
};
$items = $paginatedResult->getItems();

return each_limit(
    $pageGenerator(),
    4,
    function ($promiseResult) use (&$items, $requestBody) {
        $paginatedResult = $this->deserializeToPaginatedResult(
            $promiseResult,
            $requestBody->paginatedResultClass()
        );
        $items = array_merge($items, $paginatedResult->getItems());
    },
    function ($reason, $idx, PromiseInterface $aggregate) {
        $aggregate->reject($reason);
    })->then(function () use (&$items) {
        ksort($items);
        return $items;
    });
```

Body:
The task

Suppose we have an API POST endpoint which returns answer like this:

{
  "data": [1,2,3],
  "total_rows": 20
}

Which means that we received data partially, only the first page of 3 entries. The total entries count is 20, which means we want to call other pages using some offset in request. The total count (and possibly offset) is therefore only known after the first call is completed, while other calls do not depend on each other and can be done simultaneously.

The Toolset

It's PHP and for this task Guzzle 6 is used with Promises/A+. Additionally, Guzzle offers EachPromise class, which receives an iterable of multiple promises and a config hash to setup processing. As per PhpDoc block of that class constructor:

Configuration hash can include the following key value pairs:

fulfilled: (callable) Invoked when a promise fulfills. The function   is invoked with three arguments: the fulfillment value, the index

  position from the iterable list of the promise, and the aggregate

  promise that manages all of the promises. The aggregate promise may

  be resolved from within the callback to short-circuit the promise.

rejected: (callable) Invoked when a promise is rejected. The   function is invoked with three arguments: the rejection reason, the

  index position from the iterable list of the promise, and the

  aggregate promise that manages all of the promises. The aggregate

  promise may be resolved from within the callback to short-circuit

  the promise.

concurrency: (integer) Pass this configuration option to limit the   allowed number of outstanding concurrently executing promises,

  creating a capped pool of promises. There is no limit by default.

The code

$paginatedResult = $this->client->sendAsync($this->createRequest($requestBody))
    ->then(function (ResponseInterface $response) use ($requestBody) {
            return $this->deserializeToPaginatedResult(
                $response,
                $requestBody->paginatedResultClass()
            );
        }
    )->wait();

$pageGenerator = function () use ($paginatedResult, $requestBody) {
    $perPageCount = count($paginatedResult->getItems());
    $totalItems = $paginatedResult->getTotalCount();

    for ($currentOffset = $perPageCount; $currentOffset <= $totalItems; $currentOffset += $perPageCount) {
        $newRequestBody = clone $requestBody;
        $newRequestBody->setOffset($currentOffset);

        yield $this->client->sendAsync($this->createRequest($newRequestBody));
    }
};

$aggregatedResult = (new EachPromise(
    $pageGenerator(), [
        'concurrency' => 4,
        'fulfilled' => function ($promiseResult, $promiseIndex, $promiseAggregate) use ($requestBody) {
            $paginatedResult = $this->deserializeToPaginatedResult(
                $promiseResult,
                $requestBody->paginatedResultClass()
            );

            return $paginatedResult->getItems();
        },
    ]
))->promise()
    ->then(
        function ($promisedAggregatedResult) {
            var_dump($promisedAggregatedResult);
        }
    )
    ->wait();

var_dump($aggregatedResult);

The problem

In the config hash the fulfilled callback receives 3 objects, as documentation states. The $promiseResult can be properly handled and $paginatedResult->getItems() actually returns an array of items in requested page, but I cannot aggregate those items. The $aggregatedResult is null, and the $promisedAggregatedResult inside the last thened fulfillment callback is also null.

The question

How should one properly use Guzzle's EachPromise (and it's helper functions each and each_limit) to aggregate results of all the promises passed to it?


来源: stackexchange

问:
PHP regex pattern match recursive
I have this in a function which is supposed to replace any sequence of parentheses with what is enclosed in it like (abc) becomes abc any where it appears even recursively because parens can be nested.

```<code>$return =   preg_replace_callback(
    '|(\((.+)\))+|',
    function ($matches) {
        return $matches[2];
    },
    $s
);
</code>```

when the above regex is fed this string "a(bcdefghijkl(mno)p)q" as input it returns "ap)onm(lkjihgfedcbq". This shows the regex is matched once. What can I do to make it continue to match even inside already made matches and produce this `abcdefghijklmnopq'"

答:
Try this one,

```<code>  preg_match('/\((?:[^\(\)]*+|(?0))*\)/', $str )
</code>```

https://regex101.com/r/NsQSla/1

It will match everything inside of the ( ) as long as they are matched pairs.

Example

```<code>(abc) (abc (abc))
</code>```

will have the following matches

```<code>Match 1
   Full match   0-5 `(abc)`
Match 2
   Full match   6-17    `(abc (abc))`
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP regex pattern match recursive

Body:
I have this in a function which is supposed to replace any sequence of parentheses with what is enclosed in it like (abc) becomes abc any where it appears even recursively because parens can be nested.

$return =   preg_replace_callback(
    '|(\((.+)\))+|',
    function ($matches) {
        return $matches[2];
    },
    $s
);

when the above regex is fed this string "a(bcdefghijkl(mno)p)q" as input it returns "ap)onm(lkjihgfedcbq". This shows the regex is matched once. What can I do to make it continue to match even inside already made matches and produce this `abcdefghijklmnopq'"

Body:
Try this one,

  preg_match('/\((?:[^\(\)]*+|(?0))*\)/', $str )

https://regex101.com/r/NsQSla/1

It will match everything inside of the ( ) as long as they are matched pairs.

Example

(abc) (abc (abc))

will have the following matches

Match 1
   Full match   0-5 `(abc)`
Match 2
   Full match   6-17    `(abc (abc))`


问:
How to find and return a column index in VBA?
I am creating a VBA code to clear some data from multiple excel files. The problem is that the positions of the headers are not fixed and the columns slip away when I put together the files.
I have to find the column index based on header name and assign them to variables.

I declared the range of the header to a variable.
How can I return the column index to a variable?
I have never done this before that is why I am asking you guys.
At my first attempt I was thinking something like this:

```<code>Set findrng = sourceWS.Range(Cells(1, 1), Cells(1, 100))
index1 = findrng.Find("COUNTRY")
</code>```

index1 should store an integer like 1 or 21 ...

Any help would be appreciated.

答:
Ah sorry guys I just found it. It was simple as hell...</p>

```<code>ind1 = findrng.Find("COUNTRY").Column
</code>```

Body:
I am creating a VBA code to clear some data from multiple excel files. The problem is that the positions of the headers are not fixed and the columns slip away when I put together the files.
I have to find the column index based on header name and assign them to variables.

I declared the range of the header to a variable.
How can I return the column index to a variable?
I have never done this before that is why I am asking you guys.
At my first attempt I was thinking something like this:

Set findrng = sourceWS.Range(Cells(1, 1), Cells(1, 100))
index1 = findrng.Find("COUNTRY")

index1 should store an integer like 1 or 21 ...

Any help would be appreciated.

Body:
Ah sorry guys I just found it. It was simple as hell...

ind1 = findrng.Find("COUNTRY").Column


问:
long and int same size in eclipse?
Don't know if this is an eclipse specific problem but whenever I declare a long and try to put a value > 2^32 in it complains about "the literal XXXXXX of type int is out of range"

I've tried casting is directly to long but is doesnt seem to have any effect. What am I missing here?

答:
Try creating long constant: 123456789123l (note letter l in the end)

```<code>long l = 123456789123; // error, constant `123456789123` has type int

long l1 = 123456789123l; // will work
long l2 = 123456789123L; // will work too
</code>```

ContentLicense: CC BY-SA 2.5

Title: long and int same size in eclipse?

Body:
Try creating long constant: 123456789123l (note letter l in the end)

long l = 123456789123; // error, constant `123456789123` has type int

long l1 = 123456789123l; // will work
long l2 = 123456789123L; // will work too


问:
Compose a method name with a variable
I have this code in a Mojolicious template:

```<code>my $lang = 'de'; # de, en, ...
% $col = 'internet' . '_' . $lang;
%== markdown($rs->$col); # outputs correctly the content of the column internet_de
</code>```

Is there a way to combine the lines 2 and 3 into something like:

```<code>%== markdown($rs->'internet' . '_' . $lang); # syntax error at template ..., near "->'internet'"
</code>```

答:
Use a ref-deref. This is analogue to the baby cart.</p>

```<code>$rs->${\"internet_$lang"}
$rs->${\('internet_' . $lang)}
</code>```

Title: Compose a method name with a variable

Body:
I have this code in a Mojolicious template:

my $lang = 'de'; # de, en, ...
% $col = 'internet' . '_' . $lang;
%== markdown($rs->$col); # outputs correctly the content of the column internet_de

Is there a way to combine the lines 2 and 3 into something like:

%== markdown($rs->'internet' . '_' . $lang); # syntax error at template ..., near "->'internet'"

Body:
Use a ref-deref. This is analogue to the baby cart.

$rs->${\"internet_$lang"}
$rs->${\('internet_' . $lang)}


问:
Charjs 2 with reactjs
I am totally new to reactjs library. I found this library very interesting and want to implement in my chart-analyzing project(which is Java based spring project). Basically I want to implement it conventional way, do not want to install npm or any package manager. I have two files:

File: index.html

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.31.0/react-bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-chartjs-2/2.1.0/react-chartjs-2.min.js"></script>
    <script type="text/babel" src="chart.js"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
</code>```

File: chart.js

```<code>var MyComponent = React.createClass({
    render: function(){
      return <Line data={chartData} optionis={chartOptions} width="90%" height="70%" />
    }
});
ReactDOM.render(<MyComponent />, document.getElementById("root"));
</code>```

I think, it should work, but I get error:
Uncaught ReferenceError: Line is not defined

Note: I do NOT want to use npm manager. So, answers with npm, or using javascript require or import are not applicable to my requirement.

答:
You HAVE TO import the chartJS library (or in ES5 its var Line = require('Line')).

Thats the reason the console said Line is not defined.

Title: Charjs 2 with reactjs

Body:
I am totally new to reactjs library. I found this library very interesting and want to implement in my chart-analyzing project(which is Java based spring project). Basically I want to implement it conventional way, do not want to install npm or any package manager. I have two files:

File: index.html

    <!DOCTYPE html>

File: chart.js

var MyComponent = React.createClass({
    render: function(){
      return <Line data={chartData} optionis={chartOptions} width="90%" height="70%" />
    }
});
ReactDOM.render(<MyComponent />, document.getElementById("root"));

I think, it should work, but I get error:
Uncaught ReferenceError: Line is not defined

Note: I do NOT want to use npm manager. So, answers with npm, or using javascript require or import are not applicable to my requirement.


问:
WPF - DisplayMemberPath of nested property
I've a combobox with ItemsSource property bound to my ICollectionView of City type.

In turn, City contains an Address property which contains AddressNameString.

I would be able to set as DispalyMemberPath AddressNameString property, however it seems impossible to achieve.

Isn't it? Is there some workaround?

答:
Setting the DisplayMemberPath to a nested property path should work:

```<code>DisplayMemberPath="Address.AddressNameString"
</code>```

You could also use the ItemTemplate property instead of the DisplayMemberPath property:

```<code><ComboBox ItemsSource="{Binding Cities}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Address.AddressNameString}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

Make sure that the property is public and that you haven't misspelled the property name in your XAML.

Body:
Setting the DisplayMemberPath to a nested property path should work:

DisplayMemberPath="Address.AddressNameString"

You could also use the ItemTemplate property instead of the DisplayMemberPath property:

<ComboBox ItemsSource="{Binding Cities}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Address.AddressNameString}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Make sure that the property is public and that you haven't misspelled the property name in your XAML.


答:
I am confused to what you are asking.

Is your problem that you would like to be able to search your first row for headers, and retrieve a specific column based on the header?

```<code>thisRow = 1

searchCol = Sheet1.Cells(thisRow, 1).EntireRow.Find(What:="someString", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
</code>```

? Then you can access that column with the .column accessor.

Title: How to find and return a column index in VBA?

Body:
I am confused to what you are asking.

Is your problem that you would like to be able to search your first row for headers, and retrieve a specific column based on the header?

thisRow = 1

searchCol = Sheet1.Cells(thisRow, 1).EntireRow.Find(What:="someString", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

? Then you can access that column with the .column accessor.


问:
Angular - get synchronously from Promise
I want to print history of products. I have an id of product in ActivatedRoute.params. In ngOnInit method I have to get all history of product and assign to variable. Then I want to map product to productHistory, because I want to have last version with history toghether. But the problem is with getting history. Method to getting history return Promise and I cannot get length of productsHistory when I use this property and I get undefined. How can I get this property after loading from service?

I want to execute method after execution getHistory().

My code:

ProductService.ts:

```<code>import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

// rest imports

@Injectable()
export class ProductService {

    // URL to web api
    private projectsUrl = 'http://localhost:8080/products';

    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http) {}

    getHistory(id: number): Promise<ProductHistory[]> {
        const url = `${this.projectsUrl}/projectId/${id}`;
        return this.http.get(url)
            .toPromise()
            .then(response => response.json() as ProductHistory[])
            .catch(this.handleError);
    }

    handleError() {
        //...
        // implementation is irrelevant
    }
}
</code>```

ProductHistoryComponent.ts:

```<code>import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { ProductService } from './product.service';

import { ProductHistory } from './product-history';
import { Product } from './model/product';

import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'product-history',
    templateUrl: './product-history.component.html',
    styleUrls: [ './product-history.component.css' ]
})
export class ProductHistoryComponent implements OnInit {

    auditProducts: ProductHistory[] = new Array<ProductHistory[]>();
    selectedProduct: ProductHistory;

    constructor(
        private route: ActivatedRoute,
        private location: Location,
        private productService: ProductService
    ) {}

    ngOnInit(): void {
        let id: number = this.route.snapshot.params['id'];

        this.productService.getHistory(id)
            .then(history => this.historyProducts = history);

        this.productService.getProduct(id)
            .then(product => {
                let lastVersion: ProductHistory = this.createLastVersion(product);
                this.auditProducts.push(lastVersion);
            });
    }

    onSelect(ProductHistory: ProductHistory): void {
        this.selectedProduct = ProductHistory;
        this.compare(this.selectedProduct);
    }

    goBack(): void {
        this.location.back();
    }

    compare(history: ProductHistory): void {
        let previous: ProductHistory;
        if (history.changeNumber != null && history.changeNumber > 1) {
            previous = this.historyProducts[history.changeNumber - 2];
            if (typeof previous != 'undefined') {
                this.setPreviousDiffsFalse(previous);
                if (previous.name !== history.name) {
                    history.nameDiff = true;
                }
                if (previous.price !== history.price) {
                    history.priceDiff = true;
                }
            }
        }
    }

    createLastVersion(product: Product): ProductHistory {
        let lastVersionProduct: ProductHistory = new ProductHistory();
        lastVersionProduct.id = this.historyProducts.length + 1;
        lastVersionProduct.name = product.name;
        lastVersionProduct.price = product.price;
        lastVersionProduct.changeNumber = this.historyProducts[this.historyProducts.length - 1].changeNumber + 1;
        return lastVersionProduct;
    }

    setPreviousDiffsFalse(previous: ProductHistory): void {
        previous.nameDiff = false;
        previous.priceDiff = false;
    }

}
</code>```

答:
I would suggest using observables instead of promises ... but to answer your question, you just need to perform the second request after the first is received. Something like this:

```<code>ngOnInit(): void {
    let id: number = this.route.snapshot.params['id'];

    this.productService.getHistory(id)
        .then(history => {
               this.historyProducts = history);

               this.productService.getProduct(id)
                     .then(product => {
                         let lastVersion: ProductHistory = this.createLastVersion(product);
                         this.auditProducts.push(lastVersion);
        });
     }
}
</code>```

I just moved the second request within the then of the first request. NOTE: I did not syntax check this.

Body:
I want to print history of products. I have an id of product in ActivatedRoute.params. In ngOnInit method I have to get all history of product and assign to variable. Then I want to map product to productHistory, because I want to have last version with history toghether. But the problem is with getting history. Method to getting history return Promise and I cannot get length of productsHistory when I use this property and I get undefined. How can I get this property after loading from service?

I want to execute method after execution getHistory().

My code:

ProductService.ts:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

// rest imports

@Injectable()
export class ProductService {

    // URL to web api
    private projectsUrl = 'http://localhost:8080/products';

    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http) {}

    getHistory(id: number): Promise<ProductHistory[]> {
        const url = `${this.projectsUrl}/projectId/${id}`;
        return this.http.get(url)
            .toPromise()
            .then(response => response.json() as ProductHistory[])
            .catch(this.handleError);
    }

    handleError() {
        //...
        // implementation is irrelevant
    }
}

ProductHistoryComponent.ts:

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { ProductService } from './product.service';

import { ProductHistory } from './product-history';
import { Product } from './model/product';

import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'product-history',
    templateUrl: './product-history.component.html',
    styleUrls: [ './product-history.component.css' ]
})
export class ProductHistoryComponent implements OnInit {

    auditProducts: ProductHistory[] = new Array<ProductHistory[]>();
    selectedProduct: ProductHistory;

    constructor(
        private route: ActivatedRoute,
        private location: Location,
        private productService: ProductService
    ) {}

    ngOnInit(): void {
        let id: number = this.route.snapshot.params['id'];

        this.productService.getHistory(id)
            .then(history => this.historyProducts = history);

        this.productService.getProduct(id)
            .then(product => {
                let lastVersion: ProductHistory = this.createLastVersion(product);
                this.auditProducts.push(lastVersion);
            });
    }

    onSelect(ProductHistory: ProductHistory): void {
        this.selectedProduct = ProductHistory;
        this.compare(this.selectedProduct);
    }

    goBack(): void {
        this.location.back();
    }

    compare(history: ProductHistory): void {
        let previous: ProductHistory;
        if (history.changeNumber != null && history.changeNumber > 1) {
            previous = this.historyProducts[history.changeNumber - 2];
            if (typeof previous != 'undefined') {
                this.setPreviousDiffsFalse(previous);
                if (previous.name !== history.name) {
                    history.nameDiff = true;
                }
                if (previous.price !== history.price) {
                    history.priceDiff = true;
                }
            }
        }
    }

    createLastVersion(product: Product): ProductHistory {
        let lastVersionProduct: ProductHistory = new ProductHistory();
        lastVersionProduct.id = this.historyProducts.length + 1;
        lastVersionProduct.name = product.name;
        lastVersionProduct.price = product.price;
        lastVersionProduct.changeNumber = this.historyProducts[this.historyProducts.length - 1].changeNumber + 1;
        return lastVersionProduct;
    }

    setPreviousDiffsFalse(previous: ProductHistory): void {
        previous.nameDiff = false;
        previous.priceDiff = false;
    }

}

Body:
I would suggest using observables instead of promises ... but to answer your question, you just need to perform the second request after the first is received. Something like this:

ngOnInit(): void {
    let id: number = this.route.snapshot.params['id'];

    this.productService.getHistory(id)
        .then(history => {
               this.historyProducts = history);

               this.productService.getProduct(id)
                     .then(product => {
                         let lastVersion: ProductHistory = this.createLastVersion(product);
                         this.auditProducts.push(lastVersion);
        });
     }
}

I just moved the second request within the then of the first request. NOTE: I did not syntax check this.


问:
find a specific element in nested XML File Spark scala
I want to select a spaecific element :
select("File.columns.column._name")

```<code> |-- File: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _Description: string (nullable = true)
 |    |    |-- _RowTag: string (nullable = true)
 |    |    |-- _name: string (nullable = true)
 |    |    |-- _type: string (nullable = true)
 |    |    |-- columns: struct (nullable = true)
 |    |    |    |-- column: array (nullable = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- _Hive_Final_Table: string (nullable = true)
 |    |    |    |    |    |-- _Hive_Final_column: string (nullable = true)
 |    |    |    |    |    |-- _Hive_Table1: string (nullable = true)
 |    |    |    |    |    |-- _Hive_column1: string (nullable = true)
 |    |    |    |    |    |-- _Path: string (nullable = true)
 |    |    |    |    |    |-- _Type: string (nullable = true)
 |    |    |    |    |    |-- _VALUE: string (nullable = true)
 |    |    |    |    |    |-- _name: string (nullable = true)
</code>```

I got this error :

Exception in thread "main" org.apache.spark.sql.AnalysisException:
  cannot resolve 'File.columns.column[_name]' due to data type mismatch:
  argument 2 requires integral type, however, '_name' is of string
  type.;
          at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)
          at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:65)
          at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:57)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$transformUp$1.apply(TreeNode.scala:335)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$transformUp$1.apply(TreeNode.scala:335)
          at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:69)
          at org.apache.spark.sql.catalyst.trees.TreeNode.transformUp(TreeNode.scala:334)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$5.apply(TreeNode.scala:332)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$5.apply(TreeNode.scala:332)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$4.apply(TreeNode.scala:281)
          at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
          at scala.collection.Iterator$class.foreach(Iterator.scala:727)
          at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
          at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
          at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
          at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
          at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
          at scala.collection.AbstractIterator.to(Iterator.scala:1157)
          at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
          at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
          at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
          at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
          at org.apache.spark.sql.catalyst.trees.TreeNode.transformChildren(TreeNode.scala:321)
          at org.apache.spark.sql.catalyst.trees.TreeNode.transformUp(TreeNode.scala:332)
          at org.apache.spark.sql.catalyst.plans.QueryPlan.transformExpressionUp$1(QueryPlan.scala:108)
          at org.apache.spark.sql.catalyst.plans.QueryPlan.org$apache$spark$sql$catalyst$plans$QueryPlan$$recursiveTransform$2(QueryPlan.scala:118)

Can you help me please ?

答:
Looking at your schema you can do the following to select _name from the nested structs from dataframe

```<code>import org.apache.spark.sql.functions._
df.select(col("File.columns.column")(0)(0)("_name").as("_name"))
</code>```

Body:
I want to select a spaecific element :
select("File.columns.column._name")

 |-- File: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _Description: string (nullable = true)
 |    |    |-- _RowTag: string (nullable = true)
 |    |    |-- _name: string (nullable = true)
 |    |    |-- _type: string (nullable = true)
 |    |    |-- columns: struct (nullable = true)
 |    |    |    |-- column: array (nullable = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- _Hive_Final_Table: string (nullable = true)
 |    |    |    |    |    |-- _Hive_Final_column: string (nullable = true)
 |    |    |    |    |    |-- _Hive_Table1: string (nullable = true)
 |    |    |    |    |    |-- _Hive_column1: string (nullable = true)
 |    |    |    |    |    |-- _Path: string (nullable = true)
 |    |    |    |    |    |-- _Type: string (nullable = true)
 |    |    |    |    |    |-- _VALUE: string (nullable = true)
 |    |    |    |    |    |-- _name: string (nullable = true)

I got this error :

Exception in thread "main" org.apache.spark.sql.AnalysisException:
  cannot resolve 'File.columns.column[_name]' due to data type mismatch:
  argument 2 requires integral type, however, '_name' is of string
  type.;
          at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)
          at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:65)
          at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$2.applyOrElse(CheckAnalysis.scala:57)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$transformUp$1.apply(TreeNode.scala:335)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$transformUp$1.apply(TreeNode.scala:335)
          at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:69)
          at org.apache.spark.sql.catalyst.trees.TreeNode.transformUp(TreeNode.scala:334)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$5.apply(TreeNode.scala:332)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$5.apply(TreeNode.scala:332)
          at org.apache.spark.sql.catalyst.trees.TreeNode$$anonfun$4.apply(TreeNode.scala:281)
          at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
          at scala.collection.Iterator$class.foreach(Iterator.scala:727)
          at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
          at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
          at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
          at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
          at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
          at scala.collection.AbstractIterator.to(Iterator.scala:1157)
          at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
          at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
          at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
          at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
          at org.apache.spark.sql.catalyst.trees.TreeNode.transformChildren(TreeNode.scala:321)
          at org.apache.spark.sql.catalyst.trees.TreeNode.transformUp(TreeNode.scala:332)
          at org.apache.spark.sql.catalyst.plans.QueryPlan.transformExpressionUp$1(QueryPlan.scala:108)
          at org.apache.spark.sql.catalyst.plans.QueryPlan.org$apache$spark$sql$catalyst$plans$QueryPlan$$recursiveTransform$2(QueryPlan.scala:118)

Can you help me please ?

Body:
Looking at your schema you can do the following to select _name from the nested structs from dataframe

import org.apache.spark.sql.functions._
df.select(col("File.columns.column")(0)(0)("_name").as("_name"))


问:
Load javascript state from rendered elements
Just wanted to know is there any javascript framework or lib that could load part of initial state from existing DOM elements.

Could reactjs or vuejs do things like this?

So to be perfectly clear i want to render page on server and mark some elements to be part of the model. The idea is to be able to render html with some important data so search engines could get it without js. Regular use would have exactly the same page but once js kicks in, I want it to get data from marked fields and add to current state.

i.e.

```<code><h1 x-marker="pageTitle">Page Title</h1>
<h2>{{ subtitle }}</h2>

var state = {
    subtitle: 'This is subtitle',
}
</code>```

search engine sees this:

```<code><h1>Page Title</h1>
<h2>{{subtitle}}</h2>
</code>```

regular user sees this:

```<code><h1>Page Title</h1>
<h2>This is subtitle</h2>
</code>```

BUT state should be

```<code>var state = {
    pageTitle: 'Page Title',
    subtitle: 'This is subtitle',
}
</code>```

So I want it to initially pull data from x-marker and after that maintain state of that element.

I could implement this kind of thing myself, just wanted to check does something like this already exists.

答:
I'd advise strongly against the method you proposed and look into how to do server side rendering for your React apps.

There's something about server rendering in the React docs:
https://facebook.github.io/react/docs/react-dom-server.html#rendertostring

Next.js is a good framework to help you with this
https://github.com/zeit/next.js

Body:
Just wanted to know is there any javascript framework or lib that could load part of initial state from existing DOM elements.

Could reactjs or vuejs do things like this?

So to be perfectly clear i want to render page on server and mark some elements to be part of the model. The idea is to be able to render html with some important data so search engines could get it without js. Regular use would have exactly the same page but once js kicks in, I want it to get data from marked fields and add to current state.

i.e.

Page Title

{{ subtitle }}

var state = {
    subtitle: 'This is subtitle',
}

search engine sees this:

Page Title

{{subtitle}}

regular user sees this:

Page Title

This is subtitle

BUT state should be

var state = {
    pageTitle: 'Page Title',
    subtitle: 'This is subtitle',
}

So I want it to initially pull data from x-marker and after that maintain state of that element.

I could implement this kind of thing myself, just wanted to check does something like this already exists.


问:
Change pentaho dashboards jquery version
I have biserver-ce version 6.0.1.0, and it comes with jquery 1.9.1.

I want to update it to jquery version 3.2.1 (latest), but pentaho doesn't simply add the file, it generates it somehow.

All I could find it was that it keeps the file in this directory:

\pentaho-solutions\system\common-ui\resources\web\jquery-1.9.1.js

Tried to replace it with the new version, didn't work.

Then I searched for every jquery file in the server folder:

```<code>\pentaho-solutions\system\pentaho-cdf\js\compressed\lib
\pentaho-solutions\system\pentaho-cdf\js\lib
\tomcat\webapps\pentaho\mantle\browser\lib
\pentaho-solutions\system\saiku\ui\js
\pentaho-solutions\system\common-ui\resources\web
\pentaho-solutions\system\pentaho-cdf\js-legacy\lib
</code>```

Replace them all, but $.fn.jQuery still says "1.9.1".

答: You require to rebuild biserver-ce (and projects it depends on) with corrected dependencies. Because pentaho modified and rebuild depended js on build time.</p>

Body:
I have biserver-ce version 6.0.1.0, and it comes with jquery 1.9.1.

I want to update it to jquery version 3.2.1 (latest), but pentaho doesn't simply add the file, it generates it somehow.

All I could find it was that it keeps the file in this directory:

\pentaho-solutions\system\common-ui\resources\web\jquery-1.9.1.js

Tried to replace it with the new version, didn't work.

Then I searched for every jquery file in the server folder:

\pentaho-solutions\system\pentaho-cdf\js\compressed\lib
\pentaho-solutions\system\pentaho-cdf\js\lib
\tomcat\webapps\pentaho\mantle\browser\lib
\pentaho-solutions\system\saiku\ui\js
\pentaho-solutions\system\common-ui\resources\web
\pentaho-solutions\system\pentaho-cdf\js-legacy\lib

Replace them all, but $.fn.jQuery still says "1.9.1".


问:
Datatables backend not working
I have staging and live environment for my project. On staging env my code is working fine, but on live it's not working. (both servers have php 5.6 running)

My problem is that Datatables Editor backend script is returning blank white page without errors. I have tested that if I have small amount of records in DB ( like 5-10 records ), it's loading everything right.

Backend script:

```<code><?php

include( "../classes/datatables/DataTables.php" );

// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Options,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'translate' )
    ->fields(
        Field::inst( 'id' ),
        Field::inst( 'alias' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'lv' ),
        Field::inst( 'ru' ),
        Field::inst( 'en' ),
        Field::inst( 'translated' )
        ->setFormatter( function ( $val, $data, $opts ) {
                return ! $val ? 0 : 1;
            } )
    )
    ->process( $_POST )
    ->json();
</code>```

am I missing any php library I don't know, what could be a problem?

答:
OMG! Took 2 days and found solution, needed to add "charset=utf8" to dsn!</p>

```<code>$sql_details = array(
"type" => "Mysql",  // Database type: "Mysql", "Postgres", "Sqlserver", "Sqlite" or "Oracle"
"user" => DB_LOGIN,       // Database user name
"pass" => DB_PASS,       // Database password
"host" => DB_HOST,       // Database host
"port" => 3306,       // Database connection port (can be left empty for default)
"db"   => DB_DB,       // Database name
"dsn"  => "charset=utf8"        // PHP DSN extra information. Set as `charset=utf8` if you are using MySQL
);
</code>```

Title: Datatables backend not working

Body:
I have staging and live environment for my project. On staging env my code is working fine, but on live it's not working. (both servers have php 5.6 running)

My problem is that Datatables Editor backend script is returning blank white page without errors. I have tested that if I have small amount of records in DB ( like 5-10 records ), it's loading everything right.

Backend script:

<?php

include( "../classes/datatables/DataTables.php" );

// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Options,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'translate' )
    ->fields(
        Field::inst( 'id' ),
        Field::inst( 'alias' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'lv' ),
        Field::inst( 'ru' ),
        Field::inst( 'en' ),
        Field::inst( 'translated' )
        ->setFormatter( function ( $val, $data, $opts ) {
                return ! $val ? 0 : 1;
            } )
    )
    ->process( $_POST )
    ->json();

am I missing any php library I don't know, what could be a problem?

Body:
OMG! Took 2 days and found solution, needed to add "charset=utf8" to dsn!

$sql_details = array(
"type" => "Mysql",  // Database type: "Mysql", "Postgres", "Sqlserver", "Sqlite" or "Oracle"
"user" => DB_LOGIN,       // Database user name
"pass" => DB_PASS,       // Database password
"host" => DB_HOST,       // Database host
"port" => 3306,       // Database connection port (can be left empty for default)
"db"   => DB_DB,       // Database name
"dsn"  => "charset=utf8"        // PHP DSN extra information. Set as `charset=utf8` if you are using MySQL
);


问:
Bulk insert does not insert all the rows from the log file without giving any error
i'm using the following code

```<code>create TABLE #temp1(
 [date] [varchar](500) NULL,
 [time] [varchar](500) NULL,
 [s-ip] [varchar](500) NULL,
 [cs-method] [varchar](500) NULL,
 [cs-uri-stem] [varchar](max) NULL,
 [cs-uri-query] [varchar](max) NULL,
 [s-port] [varchar](500) NULL,
 [cs-username] [varchar](500) NULL,
 [c-ip] [varchar](500) NULL,
 [cs(User-Agent)] [varchar](2048) NULL,
 [cs(Referer)] [varchar](max) NULL,
 [sc-status] [varchar](max) NULL,
 [sc-substatus] [varchar](500) NULL,
 [sc-win32-status] [varchar](500) NULL,
 [time-taken] [varchar](500) NULL
 )

BULK INSERT #temp1 FROM 'C:\iislogs\u_ex150108.log'
  WITH (
           FIRSTROW  = 5,

          FIELDTERMINATOR = ' ',
           ROWTERMINATOR = '\n',
           MAXERRORS = 10000
        )
</code>```

and the file that, i'm using has 1521000 lines but i am getting only  1305226 in #temp1

Please help
Thanks in advance

答:
Recently I had an issue inserting rows with bulk insert, I added a rowcount condition till the stored procedure has to run.</p>

```<code>select @tablerowcount = count(*) from tbl1
while @tablerowcount = 0
begin
  exec sp_custombulkinsert
end
</code>```

Body:
i'm using the following code

create TABLE #temp1(
 [date] [varchar](500) NULL,
 [time] [varchar](500) NULL,
 [s-ip] [varchar](500) NULL,
 [cs-method] [varchar](500) NULL,
 [cs-uri-stem] [varchar](max) NULL,
 [cs-uri-query] [varchar](max) NULL,
 [s-port] [varchar](500) NULL,
 [cs-username] [varchar](500) NULL,
 [c-ip] [varchar](500) NULL,
 [cs(User-Agent)] [varchar](2048) NULL,
 [cs(Referer)] [varchar](max) NULL,
 [sc-status] [varchar](max) NULL,
 [sc-substatus] [varchar](500) NULL,
 [sc-win32-status] [varchar](500) NULL,
 [time-taken] [varchar](500) NULL
 )

BULK INSERT #temp1 FROM 'C:\iislogs\u_ex150108.log'
  WITH (
           FIRSTROW  = 5,

          FIELDTERMINATOR = ' ',
           ROWTERMINATOR = '\n',
           MAXERRORS = 10000
        )

and the file that, i'm using has 1521000 lines but i am getting only  1305226 in #temp1

Please help
Thanks in advance

Body:
Recently I had an issue inserting rows with bulk insert, I added a rowcount condition till the stored procedure has to run.

select @tablerowcount = count(*) from tbl1
while @tablerowcount = 0
begin
  exec sp_custombulkinsert
end


问:
How to use predict within xyplot / panel function?
I plot and fit data via

```<code>> xyplot(Amplification~Voltage,
        data = before_database[before_database$Serial_number==912009913,],
        grid = TRUE,
        main = "SN = 912009913",
        panel = function(x, y) {
            panel.xyplot(x, y)
            fit<-lm(y ~ poly(x,2))
            panel.lines(x, fitted(fit), col.line="black")
        })
</code>```

before_database is my data frame ( before_database ) and via Serial_number I choose a grouped subset of the data frame. Hence, Amplification is against Voltage.

Now I have two questions: How do I get related values out of the lm fit ? At the moment I'm not quite sure which I need so I ask in general.
And, additionally, how do I get the corresponding value at a certain point out of the fit? E.g. I need the Voltage at Amplification = 150 (there is no data point). Fitted() should do it but I don't get along with it..

Here is the plot:

Thank you!

PS: I know the plot is not representing the data :) This is finally my task to find the best plot.

edit: According to the discussion I want to fit the model at first outside of the xyplot because of getting used to it. Therefore I have now:

```<code>before_database.frame<- read.table("APD_data.txt",
                                  header = TRUE,
                                  sep = "",
                                  dec="."
                                 )

test.frame<- before_database.frame[before_database.frame$Serial_number==912009913, ]

test.fit<- lm(Amplification ~ poly(Voltage,2), data=test.frame)

xyplot(
      Amplification ~ Voltage,
      data = test.frame,
      grid = TRUE,
      main = "SN = 91200913",
      panel = function(x,y)
      {
          panel.xyplot(x,y)
          panel.lines(x, fitted(test.fit),
          col.line="black")
      }
      )

test.fit$coefficients[1]

new.df<- data.frame(Amplification=150)
predict(test.fit, new.df)
</code>```

When applying "predict" I receive:

```<code>"Error in poly(Voltage, 2, coefs = list(alpha = c(247.536114864865, 174.327996600877 : object 'Voltage' not found"
</code>```

I guess the frame "new.df" needs the variable voltage? But how do I provide it without a value?

答:
To predict your response variable at a new value of the predictor variable(s) use the predict function rather than the fitted function.  You give it your model along with a new data frame that has the values of the predictor (x) variable(s) that you want to predict at.

Not sure what else you want to extract or what you want to do with it.  Running the command:

```<code>methods(class='lm')
</code>```

will show you the functions that can be used on the results of an lm object, skimming the help files (then reading the interesting ones in depth) may help you find the information you are looking for.

Body:
I plot and fit data via

> xyplot(Amplification~Voltage,
        data = before_database[before_database$Serial_number==912009913,],
        grid = TRUE,
        main = "SN = 912009913",
        panel = function(x, y) {
            panel.xyplot(x, y)
            fit<-lm(y ~ poly(x,2))
            panel.lines(x, fitted(fit), col.line="black")
        })

before_database is my data frame ( before_database ) and via Serial_number I choose a grouped subset of the data frame. Hence, Amplification is against Voltage.

Now I have two questions: How do I get related values out of the lm fit ? At the moment I'm not quite sure which I need so I ask in general.
And, additionally, how do I get the corresponding value at a certain point out of the fit? E.g. I need the Voltage at Amplification = 150 (there is no data point). Fitted() should do it but I don't get along with it..

Here is the plot:

Thank you!

PS: I know the plot is not representing the data :) This is finally my task to find the best plot.

edit: According to the discussion I want to fit the model at first outside of the xyplot because of getting used to it. Therefore I have now:

before_database.frame<- read.table("APD_data.txt",
                                  header = TRUE,
                                  sep = "",
                                  dec="."
                                 )

test.frame<- before_database.frame[before_database.frame$Serial_number==912009913, ]

test.fit<- lm(Amplification ~ poly(Voltage,2), data=test.frame)

xyplot(
      Amplification ~ Voltage,
      data = test.frame,
      grid = TRUE,
      main = "SN = 91200913",
      panel = function(x,y)
      {
          panel.xyplot(x,y)
          panel.lines(x, fitted(test.fit),
          col.line="black")
      }
      )

test.fit$coefficients[1]

new.df<- data.frame(Amplification=150)
predict(test.fit, new.df)

When applying "predict" I receive:

"Error in poly(Voltage, 2, coefs = list(alpha = c(247.536114864865, 174.327996600877 : object 'Voltage' not found"

I guess the frame "new.df" needs the variable voltage? But how do I provide it without a value?

Body:
To predict your response variable at a new value of the predictor variable(s) use the predict function rather than the fitted function.  You give it your model along with a new data frame that has the values of the predictor (x) variable(s) that you want to predict at.

Not sure what else you want to extract or what you want to do with it.  Running the command:

methods(class='lm')

will show you the functions that can be used on the results of an lm object, skimming the help files (then reading the interesting ones in depth) may help you find the information you are looking for.


问:
Easy way to integrate branches into trunk
I'm running Subversion version 1.4.3 (r23084) + tortoise, and my problem is integrating an branch into trunk. Tortoise's merge didnt work, i got to do this from console.

Its always a hard work to do because of many issues, so i've been thinking about some changes.
Will a subversion update (its on 1.6 now) resolve my problem?
Or its better to change everything and start all over again with GIT ?

tnx!

答:
From my experience, this is always rather hard with SVN. Not impossible, but a lot of legwork.

You may try to use git-svn; maybe it will make merges easier while saving you the trouble to change the rest of the workflow.


问:
Python pip install exact version if two versions, one generic and one local, exist
We have set up a local python package server for your internal python packages and serve also some packages which are hard to compile on windows. As numpy is one of these packages, there exist now two versions of numpy on our server:

numpy-1.13.0-cp35-none-win32.whl

numpy-1.13.0+mkl-cp35-cp35m-win32.whl

How can I instruct pip to install a specific version of these two? Running pip install numpy will pick the package with "mkl", but for some projects I want numpy without "mkl".

Edit:

The only way which works is the full URL to the package, which seems a little bit verbose.

答:
From what I can remember, it's just a matter of writing the package's entire name.

If you need a guide:
https://pip.pypa.io/en/stable/reference/pip_install/#examples


问:
How can I std::sqrt(boost::lambda::placeholder1_type)?
How do I std::sqrt() on a boost::lambda::placeholder1_type?

The following program compiles and executes fine. Somehow, it manages to convert boost::lambda::_1 to a double and multiply it with 5.0.

```<code>#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <cmath>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      std::cout << boost::lambda::_1 * 5.0 << " "
  );
}
</code>```

However, if I replace the std::cout line with

```<code>std::cout << std::sqrt(boost::lambda::_1) << " "
</code>```

the compiler (g++) says

no known conversion for argument 1 from
  ‘boost::lambda::placeholder1_type {aka const
  boost::lambda::lambda_functor >}’ to
  ‘double’

So, how can I take the square root from boost::lambda::_1 in this std::for_each loop?

答:
Do it the C++11 way:</p>

```<code>#include <iostream>
#include <cmath>
#include <array>
#include <algorithm>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      [] (const auto&v ) { std::cout << sqrt(v) * 5.0 << " "; }
  );
}
</code>```

Body:
How do I std::sqrt() on a boost::lambda::placeholder1_type?

The following program compiles and executes fine. Somehow, it manages to convert boost::lambda::_1 to a double and multiply it with 5.0.

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <cmath>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      std::cout << boost::lambda::_1 * 5.0 << " "
  );
}

However, if I replace the std::cout line with

std::cout << std::sqrt(boost::lambda::_1) << " "

the compiler (g++) says

no known conversion for argument 1 from
  ‘boost::lambda::placeholder1_type {aka const
  boost::lambda::lambda_functor >}’ to
  ‘double’

So, how can I take the square root from boost::lambda::_1 in this std::for_each loop?

Body:
Do it the C++11 way:

#include <iostream>
#include <cmath>
#include <array>
#include <algorithm>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      [] (const auto&v ) { std::cout << sqrt(v) * 5.0 << " "; }
  );
}


问:
Count Entries in Column Ignoring Duplicates
I have a table which handles timesheets. One column is for weekending dates, next column is name and third is hours worked.

```<code>W/E         Name        Hours

25/05/2017  J. Smith    37.5
18/05/2017  J. Smith    37.5
25/07/2017  J. Smith    37.5
25/07/2017  D. Bloggs   20
25/07/2017  D. Bloggs   10
25/07/2017  D. Bloggs   7.5
</code>```

I need to find how many unique timesheets I have. So based on the above, I have 3 timesheets from J Smith but only 1 timesheet from D Bloggs, albeit split into 3. So my total unique timesheets is 4.

Can anyone recommend a good way, formula or function that would get this done without deleting or editing my data manually?

答:
Try,

```<code>=SUMPRODUCT(1/COUNTIFS(A2:A7, A2:A7, B2:B7, B2:B7))
</code>```

If your data contains blank rows, change the numerator of the division to not accept blanks and add blanks to the denominator; the latter to avoid a #DIV/0! error.

```<code>=SUMPRODUCT((A2:A8<>"")/(COUNTIFS(A2:A8, A2:A8, B2:B8, B2:B8)+(A2:A8="")))
</code>```

If there is a blank then the numerator will be zero and the denominator will not. Any fraction with zero as the numerator is zero so it doesn't matter what the denominator is as long as it is non-zero.

Body:
I have a table which handles timesheets. One column is for weekending dates, next column is name and third is hours worked.

W/E         Name        Hours

25/05/2017  J. Smith    37.5
18/05/2017  J. Smith    37.5
25/07/2017  J. Smith    37.5
25/07/2017  D. Bloggs   20
25/07/2017  D. Bloggs   10
25/07/2017  D. Bloggs   7.5

I need to find how many unique timesheets I have. So based on the above, I have 3 timesheets from J Smith but only 1 timesheet from D Bloggs, albeit split into 3. So my total unique timesheets is 4.

Can anyone recommend a good way, formula or function that would get this done without deleting or editing my data manually?

Body:
Try,

=SUMPRODUCT(1/COUNTIFS(A2:A7, A2:A7, B2:B7, B2:B7))

If your data contains blank rows, change the numerator of the division to not accept blanks and add blanks to the denominator; the latter to avoid a #DIV/0! error.

=SUMPRODUCT((A2:A8<>"")/(COUNTIFS(A2:A8, A2:A8, B2:B8, B2:B8)+(A2:A8="")))

If there is a blank then the numerator will be zero and the denominator will not. Any fraction with zero as the numerator is zero so it doesn't matter what the denominator is as long as it is non-zero.


问:
Angular: Formatting numbers with commas
Title very much sums up my needs.

```<code>123456789 => 123,456,789
12345 => 12,345
</code>```

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.

答:
function printNo() {
  document.getElementById('text').innerHTML =
  Number(1234355).toLocaleString('en-GB');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
 <html>
    <head></head>

     <body onload="printNo()">
      <h1 id="text"></h1>

     </body>
</html></code>```

Reference link

Title: Angular: Formatting numbers with commas

Body:
Title very much sums up my needs.

123456789 => 123,456,789
12345 => 12,345

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.

Body:
function printNo() {
  document.getElementById('text').innerHTML =
  Number(1234355).toLocaleString('en-GB');
}

 <!DOCTYPE html>
 <html>
    <head></head>

     <body onload="printNo()">
      <h1 id="text"></h1>

     </body>
</html>

Reference link

ContentLicense: CC BY-SA 4.0


问:
Child/Parent inheritance/casting and Generic type
If I simply define the base class and inherited class this way

```<code>abstract class Base
{
}

class Inherited : Base
{
}
</code>```

I am free to use Base a = new Inherited(); without any error.

But if I have complicated base class with generic, for example see the code below:

```<code>abstract class AnotherBase<TDetailType> where TDetailType : AnotherDetail
{
    public List<TDetailType> Children { get; set; }
}

abstract class AnotherDetail
{
}
</code>```

And I have inherited classes

```<code>class AnotherInherited : AnotherBase<AnotherInheritedDetail>
{
}

class AnotherInheritedDetail : AnotherDetail
{
}
</code>```

Obviously I could not use the similar syntax any more AnotherBase<AnotherDetail> b = new AnotherInherited(); because the compiler provides the error message

Severity  Code    Description Project File    Line    Suppression State
  Error CS0029  Cannot implicitly convert type
  'ConsoleApplication3.AnotherInherited' to
  'ConsoleApplication3.AnotherBase'  ConsoleApplication3 c:\temp\ConsoleApplication3\ConsoleApplication3\Program.cs  15  Active

Any suggestion how can I still use the base class to represent inherited classes under such circumstance?

答:
Of course this would not work.

Your class AnotherInherited inherits from AnotherBase<AnotherInheritedDetail> and not AnotherBase<AnotherDetail>. This might seem wierd to you, but you are inheriting one class by another and not the generics aswell.

You may use the generics interchangable while working with the object, but the class-definition states only this one inheritance.

At least that is my understanding.

Body:
If I simply define the base class and inherited class this way

abstract class Base
{
}

class Inherited : Base
{
}

I am free to use Base a = new Inherited(); without any error.

But if I have complicated base class with generic, for example see the code below:

abstract class AnotherBase<TDetailType> where TDetailType : AnotherDetail
{
    public List<TDetailType> Children { get; set; }
}

abstract class AnotherDetail
{
}

And I have inherited classes

class AnotherInherited : AnotherBase<AnotherInheritedDetail>
{
}

class AnotherInheritedDetail : AnotherDetail
{
}

Obviously I could not use the similar syntax any more AnotherBase<AnotherDetail> b = new AnotherInherited(); because the compiler provides the error message

Severity  Code    Description Project File    Line    Suppression State
  Error CS0029  Cannot implicitly convert type
  'ConsoleApplication3.AnotherInherited' to
  'ConsoleApplication3.AnotherBase'  ConsoleApplication3 c:\temp\ConsoleApplication3\ConsoleApplication3\Program.cs  15  Active

Any suggestion how can I still use the base class to represent inherited classes under such circumstance?


问:
How to find all instances of a procedure (or function) in SQL Server 2005/2008
I modified a procedure and it now takes a greater number of parameters. How can I find every place that the procedure is called so I can update the number of arguments the proc is passed?

I tried this:

```<code>select * from syscomments where text like '%MODIFIED-PROCEDURE-NAME%'
</code>```

but I'm still finding other places the proc is called that this query did not return.

答: Get yourself Red-Gate SQL Search - it's great, it's FREE and it just works. It can be used to do exactly what you're looking for! Go grab it - it's worth its weight in gold!

Body:
I modified a procedure and it now takes a greater number of parameters. How can I find every place that the procedure is called so I can update the number of arguments the proc is passed?

I tried this:

select * from syscomments where text like '%MODIFIED-PROCEDURE-NAME%'

but I'm still finding other places the proc is called that this query did not return.


问:
Replace a subset of a data frame with dplyr join operations
Suppose that I gave a treatment to some column values of a data frame like this:

```<code>  id animal weight   height ...
  1    dog     23.0
  2    cat     NA
  3   duck     1.2
  4  fairy     0.2
  5  snake     BAD

df <- data.frame(id = seq(1:5),
             animal = c("dog", "cat", "duck", "fairy", "snake"),
             weight = c("23", NA, "1.2", "0.2",  "BAD"))
</code>```

Suppose that the treatment require to work in a separately table, and gave as the result, the following data frame that is a subset of the original:

```<code>  id animal weight
  2    cat    2.2
  5  snake    1.3

sub_df <- data.frame(id = c(2, 5),
             animal = c("cat", "snake"),
             weight = c("2.2", "1.3"))
</code>```

Now I want to put all together again, so I use an operation like this:

```<code>> df %>%
   anti_join(sub_df, by = c("id", "animal")) %>%
   bind_rows(sub_df)

 id animal weight
 4  fairy    0.2
 1    dog   23.0
 3   duck    1.2
 2    cat    2.2
 5  snake    1.3
</code>```

Exist some way to do this directly with join operations?

In the case that the subset is just the key column and the variable subject to give a treatment (id, animal weigth) and not the total variables of the original data frame (id, animal, weight, height), how could assemble the subset with the original set?

答:
Remove the na's first, then simply stack the tibbles:</p>

```<code> bind_rows(filter(df,!is.na(weight)),sub_df)
</code>```

Body:
Suppose that I gave a treatment to some column values of a data frame like this:

  id animal weight   height ...
  1    dog     23.0
  2    cat     NA
  3   duck     1.2
  4  fairy     0.2
  5  snake     BAD

df <- data.frame(id = seq(1:5),
             animal = c("dog", "cat", "duck", "fairy", "snake"),
             weight = c("23", NA, "1.2", "0.2",  "BAD"))

Suppose that the treatment require to work in a separately table, and gave as the result, the following data frame that is a subset of the original:

  id animal weight
  2    cat    2.2
  5  snake    1.3

sub_df <- data.frame(id = c(2, 5),
             animal = c("cat", "snake"),
             weight = c("2.2", "1.3"))

Now I want to put all together again, so I use an operation like this:

> df %>%
   anti_join(sub_df, by = c("id", "animal")) %>%
   bind_rows(sub_df)

 id animal weight
 4  fairy    0.2
 1    dog   23.0
 3   duck    1.2
 2    cat    2.2
 5  snake    1.3

Exist some way to do this directly with join operations?

In the case that the subset is just the key column and the variable subject to give a treatment (id, animal weigth) and not the total variables of the original data frame (id, animal, weight, height), how could assemble the subset with the original set?

Body:
Remove the na's first, then simply stack the tibbles:

 bind_rows(filter(df,!is.na(weight)),sub_df)


问:
Use group seperator(GS) in hive external table as delimiter
I am using the following query to create an external table with group seperator(GS) as delimiter

```<code>CREATE EXTERNAL TABLE IF NOT EXISTS icephase2Demo.GS_TEST1
(
RandomString1 String,
RandomString2 String
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\35'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION '/DataSourcing/DV_POC/GS_TEST/';
</code>```

Then I am loading data from the file

```<code>load data inpath '/DataSourcing/DV_POC/groupseperatorOutput.dat' into table icephase2Demo.GS_TEST1;
</code>```

The following is the input in my file

but when i issue select command in hive , I am getting the values concatenated

```<code>hive> select * from GS_TEST1;
</code>```

nAUrLJdXYKFw       NULL

I9X24g8mqIMQ       NULL

\35 is the octal value of group seperator. its ascii value is 29.
I understand that the delimiter '\35' is not picked by hive.

Please suggest a work around for this problem

答: use \29 (decimal), \035 (octal) or \u001D (hex)

Body:
I am using the following query to create an external table with group seperator(GS) as delimiter

CREATE EXTERNAL TABLE IF NOT EXISTS icephase2Demo.GS_TEST1
(
RandomString1 String,
RandomString2 String
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\35'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION '/DataSourcing/DV_POC/GS_TEST/';

Then I am loading data from the file

load data inpath '/DataSourcing/DV_POC/groupseperatorOutput.dat' into table icephase2Demo.GS_TEST1;

The following is the input in my file

but when i issue select command in hive , I am getting the values concatenated

hive> select * from GS_TEST1;

nAUrLJdXYKFw       NULL

I9X24g8mqIMQ       NULL

\35 is the octal value of group seperator. its ascii value is 29.
I understand that the delimiter '\35' is not picked by hive.

Please suggest a work around for this problem


问:
Difficulties with displaying post information on seperate page
I am making a website that you can post things on and the posts show up on your feed, sort of like instagram. Everything works as far as retrieving the posts from the database and displaying them all on one page using a forEach loop. There is a button that says "more details", and when clicked on it brings you to a separate page with just that post on it.
The problem is that when I try to go to the page, nothing shows up. There are no errors shown either, and the other header info shows.

```<code>app.get("/posts/:author/:id", function(req, res){
    Post.findAll({
        where: {
            id: req.params.id,
            author: req.params.author
        }
    }).then(function(foundPost){
        var renderPost = foundPost;
        res.render("show", {post: renderPost});
    });
});
</code>```

That is the code for the get request of the page.^

```<code><% include ./partials/header %>

<h1><%= post.author%></h1>
<h1><%= post.body%></h1>
<h1><%= post.title%></h1>

hi

<% include ./partials/footer %>
</code>```

That is the code for the actual show page.
The "hi" displays along with 3 empty h1's when you use inspect.

答:
I am assuming the findAll method returns an Array, so in order to get the post object, you should do:

```<code>var renderPost = foundPost[0];
</code>```

Body:
I am making a website that you can post things on and the posts show up on your feed, sort of like instagram. Everything works as far as retrieving the posts from the database and displaying them all on one page using a forEach loop. There is a button that says "more details", and when clicked on it brings you to a separate page with just that post on it.
The problem is that when I try to go to the page, nothing shows up. There are no errors shown either, and the other header info shows.

app.get("/posts/:author/:id", function(req, res){
    Post.findAll({
        where: {
            id: req.params.id,
            author: req.params.author
        }
    }).then(function(foundPost){
        var renderPost = foundPost;
        res.render("show", {post: renderPost});
    });
});

That is the code for the get request of the page.^

<% include ./partials/header %>

<%= post.author%>

<%= post.body%>

<%= post.title%>

hi

<% include ./partials/footer %>

That is the code for the actual show page.
The "hi" displays along with 3 empty h1's when you use inspect.

Body:
I am assuming the findAll method returns an Array, so in order to get the post object, you should do:

var renderPost = foundPost[0];


问:
How do you change the formated font color of a cell using VBA?
I would like to select rows in my excel sheet based on a criteria and then edit the format of other cells in the same row.

I know that I can select rows using autofilters (column n equals ""):

```<code>Sub beautify()

Dim rng As Range
Set rng = ActiveSheet.Range("F60:AJ3272")
rng.AutoFilter Field:=4, Field:=4, Criteria1:=""

End Sub
</code>```

Now how do I change the font of column F of the lines that I have selected to white.

答:
I made slight modifications to your code and it worked:</p>

```<code>Sub beautify()

Dim i As Long

For i = 1 To 50
 If Cells(i, 9).Value = "" Then
  ActiveSheet.Range(Cells(i, 10), Cells(i, 31)).Font.Color = vbBlack
  ActiveSheet.Range(Cells(i, 8), Cells(i, 8)).Font.Color = vbWhite
 End If

Next i

End Sub
</code>```

Body:
I would like to select rows in my excel sheet based on a criteria and then edit the format of other cells in the same row.

I know that I can select rows using autofilters (column n equals ""):

Sub beautify()

Dim rng As Range
Set rng = ActiveSheet.Range("F60:AJ3272")
rng.AutoFilter Field:=4, Field:=4, Criteria1:=""

End Sub

Now how do I change the font of column F of the lines that I have selected to white.

Body:
I made slight modifications to your code and it worked:

Sub beautify()

Dim i As Long

For i = 1 To 50
 If Cells(i, 9).Value = "" Then
  ActiveSheet.Range(Cells(i, 10), Cells(i, 31)).Font.Color = vbBlack
  ActiveSheet.Range(Cells(i, 8), Cells(i, 8)).Font.Color = vbWhite
 End If

Next i

End Sub


问:
How to consume WCF method with "DataSet" return type in Silverlight
10+ Methods in my WCF webservice returns an object of type DataSet

```<code> public System.Data.DataSet ReturnData()
        {
            DataSet dataSet = new DataSet();
            //do some work on the dataset
            return dataSet;
        }
</code>```

I want to consume this WCF webservice in my silverlight application.

Problem: DataSet is not resolved as System.Data.dll does not appear in the Silverlight application's add reference section.

Is there a workaround or a solution?

答:
Take a look on DataSet for Silverlight Applications

But I advise you to write this into classes

Edit:
To show you how you can use instead of the classe, I give you an example

```<code>  public class Person
    {
        private int gID;
        private String gFirstName="";
        private String gLastName = "";

        public int ID
        {
            get
            {
                return gID;
            }
            set
            {
                gID = value;
            }
        }

        public String FirstName
        {
            get
            {
                return gFirstName;
            }
            set
            {
                gFirstName= value;
            }
        }

        public String LastName
        {
            get
            {
                return gLastName;
            }
            set
            {
                gLastName = value;
            }
        }
    }
</code>```

.

```<code>   public class Persons
    {
        private List<Person> gListOfPerson;

        public List<Person> All
        {
            get
            {
                if (gListOfPerson == null)
                {
                    gListOfPerson= new List<Person>();
                }
                return gListOfPerson;
            }
            set
            {
                gListOfPerson=value;
            }
        }

    }
</code>```

.

```<code>public Persons ReturnData()
{
                 DataSet  vDS = new DataSet();
                 //get data from SQL Server or what ever in a DataSet...

                foreach(System.Data.DataTable t in vDS.Tables)
                {
                    Persons  vPersons = new Persons();
                    foreach(System.Data.DataRow dr in t.Rows)
                    {
                        Person vPerson = new Person();
                        int vtryInt;
                        int.TryParse(dr["ID"].ToString(), out vtryInt);
                        vPerson.ID = vtryInt;
                        vPerson.FirstName = dr["FirstName"].toString();
                        vPerson.LastName = dr["LastName"].toString();

                        vPersons.All.Add(vPerson);
                    }

                    return vPersons ;
 }
</code>```

Body:
10+ Methods in my WCF webservice returns an object of type DataSet

 public System.Data.DataSet ReturnData()
        {
            DataSet dataSet = new DataSet();
            //do some work on the dataset
            return dataSet;
        }

I want to consume this WCF webservice in my silverlight application.

Problem: DataSet is not resolved as System.Data.dll does not appear in the Silverlight application's add reference section.

Is there a workaround or a solution?

Body:
Take a look on DataSet for Silverlight Applications

But I advise you to write this into classes

Edit:
To show you how you can use instead of the classe, I give you an example

  public class Person
    {
        private int gID;
        private String gFirstName="";
        private String gLastName = "";

        public int ID
        {
            get
            {
                return gID;
            }
            set
            {
                gID = value;
            }
        }

        public String FirstName
        {
            get
            {
                return gFirstName;
            }
            set
            {
                gFirstName= value;
            }
        }

        public String LastName
        {
            get
            {
                return gLastName;
            }
            set
            {
                gLastName = value;
            }
        }
    }

.

   public class Persons
    {
        private List<Person> gListOfPerson;

        public List<Person> All
        {
            get
            {
                if (gListOfPerson == null)
                {
                    gListOfPerson= new List<Person>();
                }
                return gListOfPerson;
            }
            set
            {
                gListOfPerson=value;
            }
        }

    }

.

public Persons ReturnData()
{
                 DataSet  vDS = new DataSet();
                 //get data from SQL Server or what ever in a DataSet...

                foreach(System.Data.DataTable t in vDS.Tables)
                {
                    Persons  vPersons = new Persons();
                    foreach(System.Data.DataRow dr in t.Rows)
                    {
                        Person vPerson = new Person();
                        int vtryInt;
                        int.TryParse(dr["ID"].ToString(), out vtryInt);
                        vPerson.ID = vtryInt;
                        vPerson.FirstName = dr["FirstName"].toString();
                        vPerson.LastName = dr["LastName"].toString();

                        vPersons.All.Add(vPerson);
                    }

                    return vPersons ;
 }


问:
How to add two strings as numbers together in mongoDB
my guestMin and guestMax are both strings, and I want to add them together and put the sum into guestSum.

I tried this:

```<code>$project:{
    "_id" : 1,
    "name" : 1,
    "guestsMin" : 1,
    "guestsMax" : 1,
    "guestSum" : parseInt("guestsMin") + parseInt("guestsMax"),
    "gmapsdata" : 1
}
</code>```

this does not show the guestSum at all

```<code>$project:{
    "_id" : 1,
    "name" : 1,
    "guestsMin" : 1,
    "guestsMax" : 1,
    "guestSum" : { $add: [ parseInt("guestsMin"), parseInt("guestsMax") ] },
    "gmapsdata" : 1
}
</code>```

this gives "guestSum": null,

```<code>    "guestSum" : { $add: [ parseInt("$guestsMin"), parseInt("$guestsMax") ] },
</code>```

this gives "guestSum": null,

```<code>    "guestSum" : { $multiply: [ parseInt("$guestsMin"), parseInt("$guestsMax") ] },
</code>```

this gives "guestSum": null,

```<code>    "guestSum" : { $multiply: [ parseInt("property.guestsMin"), parseInt("property.guestsMax") ] },
</code>```

this gives "guestSum": null,

Im running out of ideas, anyone?

答:
The solution was this:

```<code>"guestSort" : { $multiply: [ "$guestsMin", "$guestsMax"] },
</code>```

"property.guestsMin" did not work

"guestsMin" did not work

"$property.guestsMin" did not work

but... "$guestsMin" worked

Body:
my guestMin and guestMax are both strings, and I want to add them together and put the sum into guestSum.

I tried this:

$project:{
    "_id" : 1,
    "name" : 1,
    "guestsMin" : 1,
    "guestsMax" : 1,
    "guestSum" : parseInt("guestsMin") + parseInt("guestsMax"),
    "gmapsdata" : 1
}

this does not show the guestSum at all

$project:{
    "_id" : 1,
    "name" : 1,
    "guestsMin" : 1,
    "guestsMax" : 1,
    "guestSum" : { $add: [ parseInt("guestsMin"), parseInt("guestsMax") ] },
    "gmapsdata" : 1
}

this gives "guestSum": null,

    "guestSum" : { $add: [ parseInt("$guestsMin"), parseInt("$guestsMax") ] },

this gives "guestSum": null,

    "guestSum" : { $multiply: [ parseInt("$guestsMin"), parseInt("$guestsMax") ] },

this gives "guestSum": null,

    "guestSum" : { $multiply: [ parseInt("property.guestsMin"), parseInt("property.guestsMax") ] },

this gives "guestSum": null,

Im running out of ideas, anyone?

Body:
The solution was this:

"guestSort" : { $multiply: [ "$guestsMin", "$guestsMax"] },

"property.guestsMin" did not work

"guestsMin" did not work

"$property.guestsMin" did not work

but... "$guestsMin" worked


问:
Creating an ec2 windows instance with Ami using Aws cli adding ami-roles, tags and EBS
I am running the following command

```<code>aws ec2 run-instances --image-id ${Ami_id} --count 1 --instance-type t2.micro --iam-instance-profile Name="bot_syndication_cloudwatch" --key-name my-key\
--security-group-ids sg-27b53b5c,sg-7ddd5306 --subnet-id subnet-96e0d6e0 \
--tag-specifications ResourceType=instance,Tags=[{Key=Name,Value=Stage-Content-Syndication},{Key=Environment,Value=Stage},{Key=Platform,Value=Windows}]\
--block-device-mappings "[{\"DeviceName\":\"/dev/sdj\",\"NoDevice\":\"\"}]" \
</code>```

and I am getting this error

```<code>sg-7ddd5306, --tag-specifications, ResourceType=instance,Tags=[{Key=Name,Value=Stage-Content-Syndication},{Key=Environment,Value=Stage},{Key=Platform,Value=Windows}]--block-device-mappings, [{"DeviceName":"/dev/sdj","NoDevice":""}], sg-27b53b5c
Build step 'Execute shell' marked build as failure
</code>```

答:
The issue is with this parameter --security-group-ids sg-27b53b5c,sg-7ddd5306

If you have multiple security groups to assign on your ec2 instance, you need to separate with space such as

```<code>--security-group-ids sg-27b53b5c sg-7ddd5306
</code>```

Body:
I am running the following command

aws ec2 run-instances --image-id ${Ami_id} --count 1 --instance-type t2.micro --iam-instance-profile Name="bot_syndication_cloudwatch" --key-name my-key\
--security-group-ids sg-27b53b5c,sg-7ddd5306 --subnet-id subnet-96e0d6e0 \
--tag-specifications ResourceType=instance,Tags=[{Key=Name,Value=Stage-Content-Syndication},{Key=Environment,Value=Stage},{Key=Platform,Value=Windows}]\
--block-device-mappings "[{\"DeviceName\":\"/dev/sdj\",\"NoDevice\":\"\"}]" \

and I am getting this error

sg-7ddd5306, --tag-specifications, ResourceType=instance,Tags=[{Key=Name,Value=Stage-Content-Syndication},{Key=Environment,Value=Stage},{Key=Platform,Value=Windows}]--block-device-mappings, [{"DeviceName":"/dev/sdj","NoDevice":""}], sg-27b53b5c
Build step 'Execute shell' marked build as failure

Body:
The issue is with this parameter --security-group-ids sg-27b53b5c,sg-7ddd5306

If you have multiple security groups to assign on your ec2 instance, you need to separate with space such as

--security-group-ids sg-27b53b5c sg-7ddd5306


问:
Angularjs checkbox checked onload but gives undefined when unchecked first time inside nested ng-repeat
I am using AngularJS, Ionic (v 1) frameworks. On load of the mobile app screen, the checkboxes are to displayed as checked & then user may check or uncheck the checkboxes. The checkboxes are checked on load fine, however, when first time user unchecks a checkbox then the checkbox status value is undefined even though the checkbox is seen to be unchecked. After this when it is checked then it works fine whereby either the checkbox value is true or false depending upon if user checked it or unchecked it. Below if the html section of the code that is displaying the nested ng-repeat and checkboxes displayed. Also, there are multiple checkboxes that can be displayed and that is why second ng-repeat is used to load all the values for the checkboxes. Below the HTML code is the Javascript functions in controllers.

The togglegroup & isgroupshown functions are used to show or hide the checkboxes when the user clicks on the icon next to Extras.

HTML

```<code><form name="list" class="list">
<div ng-repeat="(i, item) in menu_items track by $index">
<div class="item item-divider">
{{item.p_name}}
</div>
<select ng-show="item.Customizable == 1" ng-model="data.cmbIngredient[i]">
<option selected="selected" value="">Select the size</option>
<option ng-repeat="x in item.ProductSizes" value="{{x}}">
{{x.ProductName}}: €{{x.ProductPrice | number:2}}
</option>
</select>
<div>
{{item.p_description}}
</div>
<!-- if the Extras value equates to 1 then the checkbox is displayed-->
<div ng-show="item.Extras == 1">
<i ng-click="toggleGroup(item)" class="icon balanced icon" ng-class="isGroupShown(item) ? 'ion-minus' : 'ion-plus-round'"></i> Extras
<label ng-repeat="(j, ext) in item.ExtraDetails track by $index" class="checkbox" ng-show="isGroupShown(item)">

<input type="checkbox" ng-checked="1" ng-change="AddExtras(data.data[j].chkextras[i],item.p_id)" ng-model="data.data[j].chkextras[i]"> {{ext.CIngredientName}}

</label>
</div>
</div>
</form>
</code>```

Controller functions

```<code>$scope.AddExtras=function(extraStatus,pid){
if(extraStatus == true){
    //pass it to service
}
else if (extraStatus == false){
    //pass it to a service
}
};
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};
</code>```

答:
If you read the docs for ng-checked you can clearly read what causes the issue:

Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.

Conclusion: you should either use ng-checked or ng-model and not mix both.

Body:
I am using AngularJS, Ionic (v 1) frameworks. On load of the mobile app screen, the checkboxes are to displayed as checked & then user may check or uncheck the checkboxes. The checkboxes are checked on load fine, however, when first time user unchecks a checkbox then the checkbox status value is undefined even though the checkbox is seen to be unchecked. After this when it is checked then it works fine whereby either the checkbox value is true or false depending upon if user checked it or unchecked it. Below if the html section of the code that is displaying the nested ng-repeat and checkboxes displayed. Also, there are multiple checkboxes that can be displayed and that is why second ng-repeat is used to load all the values for the checkboxes. Below the HTML code is the Javascript functions in controllers.

The togglegroup & isgroupshown functions are used to show or hide the checkboxes when the user clicks on the icon next to Extras.

HTML

<form name="list" class="list">

{{item.p_name}}

<select ng-show="item.Customizable == 1" ng-model="data.cmbIngredient[i]">
<option selected="selected" value="">Select the size</option>
<option ng-repeat="x in item.ProductSizes" value="{{x}}">
{{x.ProductName}}: €{{x.ProductPrice | number:2}}
</option>
</select>

{{item.p_description}}

 Extras

<input type="checkbox" ng-checked="1" ng-change="AddExtras(data.data[j].chkextras[i],item.p_id)" ng-model="data.data[j].chkextras[i]"> {{ext.CIngredientName}}

</form>

Controller functions

$scope.AddExtras=function(extraStatus,pid){
if(extraStatus == true){
    //pass it to service
}
else if (extraStatus == false){
    //pass it to a service
}
};
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};


问:
What is the best way to design a HTTP request when somewhat complex parameters are needed?
I have some web services that I am writing and I am trying to be as RESTful as possible.  I am hosting these web services using a HTTPHandler running inside of IIS/ASP.NET/SharePoint.

Most of my services expect a HTTP GET.  I have two of these that are simply returning some data (i.e., a query) and will be Idempotent, but the parameters may be somewhat complex.  Both of them could include characters in the parameters of the service that are not allowed for at least the PATH portion of the URL.

Using IIS, ASP.NET, and SharePoint I have found that the following characters in the URL path don't even make it to my HttpHandler even if Url encoded (the request blows up and I don't have any easy control over this):

% (%25)

& (%26)

* (%2a, but didn't Url encode)

+ (%2b)

: (%3a)

< (%3c)

(%3e)

The following characters made it to my HttpHandler, but the UriTemplate could not handle them properly even if Url encoded:

(%23)

. (%2e, but didn't Url encode; UriTemplate removed the "." if is is the last character before a /)

? (%3f)

/ (%2f - UriTemplate fails for obvious reasons even if UrlEncoded)

\ (%5c)

So, I've been somewhat thorough, but I need to test these url encoded characters in the query string.  It appears that this will work for the most part there.

In one of my services, the special characters that are a parameter are semantically part of a query/filter (actually search terms for a search service), but in another they are not really part of a query/filter so ideally they are part of the path and not the query string.

My question is, what option is best?  Here are some I know of:

Use HTTP GET and query string.  Anything that may use special characters should be on the query string and Url Encoded.  This is where I am leaning, but I am concerned about extremely long query strings (IE has a 2083 limit)

Use HTTP GET and base64 encoding within path.  Use a Modified Base64 for URL for any parameters that might use special characters and keep them as part of the path if preferred.  I have tried this and it works, but it is kind of ugly.  Still a concern about extremely long query strings.

Use HTTP POST and message body.  Anything that may use special characters should be in the body of the request.  Seems like a decent solution, but posts are understood to not be Idempotent and (I thought) are generally meant for changes (whereas no change is occurring here).

Use HTTP GET and message body.  Anything that may use special characters should be in the body of the request.  This seems like a bad idea according to SO: HTTP GET with request body and Roy Fielding.

Use a combination of #3 and either #1 or #2 above depending on how large the request can be.

Other???

Note that in some cases I may be able to change things around to prevent special characters (and I may do that), but I won't be able to do this in all cases.

Regarding URI length, RFC2616 Sec3.2.1 says the following:

The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

```<code>  Note: Servers ought to be cautious about depending on URI lengths
  above 255 bytes, because some older client or proxy
  implementations might not properly support these lengths.
</code>```

In addition the Maximum URL length is 2,083 characters in Internet Explorer.

Related: How to pass complex queries in REST?

答:
If the query is too big to go in the URI, turn your query into a resource (like a saved search).
I worked on a restful API for a hotel's booking system; the search query had too many params (preferences, rooming list...etc) so I turned it into a resource that I POST to the server. The server then replies with a URI uniquely identifing the search which body is the posted query + its results:

```<code>POST http://hotels.xyz/searches
body <search><query>...</query></search>
</code>```

Response

```<code>201 Created - Location: http://hotels.xyz/searches/someID
Body <search><query>...</query><results>...</results></search>
</code>```

Body:
I have some web services that I am writing and I am trying to be as RESTful as possible.  I am hosting these web services using a HTTPHandler running inside of IIS/ASP.NET/SharePoint.

Most of my services expect a HTTP GET.  I have two of these that are simply returning some data (i.e., a query) and will be Idempotent, but the parameters may be somewhat complex.  Both of them could include characters in the parameters of the service that are not allowed for at least the PATH portion of the URL.

Using IIS, ASP.NET, and SharePoint I have found that the following characters in the URL path don't even make it to my HttpHandler even if Url encoded (the request blows up and I don't have any easy control over this):

% (%25)

& (%26)

* (%2a, but didn't Url encode)

+ (%2b)

: (%3a)

< (%3c)

(%3e)

The following characters made it to my HttpHandler, but the UriTemplate could not handle them properly even if Url encoded:

(%23)

. (%2e, but didn't Url encode; UriTemplate removed the "." if is is the last character before a /)

? (%3f)

/ (%2f - UriTemplate fails for obvious reasons even if UrlEncoded)

\ (%5c)

So, I've been somewhat thorough, but I need to test these url encoded characters in the query string.  It appears that this will work for the most part there.

In one of my services, the special characters that are a parameter are semantically part of a query/filter (actually search terms for a search service), but in another they are not really part of a query/filter so ideally they are part of the path and not the query string.

My question is, what option is best?  Here are some I know of:

Use HTTP GET and query string.  Anything that may use special characters should be on the query string and Url Encoded.  This is where I am leaning, but I am concerned about extremely long query strings (IE has a 2083 limit)

Use HTTP GET and base64 encoding within path.  Use a Modified Base64 for URL for any parameters that might use special characters and keep them as part of the path if preferred.  I have tried this and it works, but it is kind of ugly.  Still a concern about extremely long query strings.

Use HTTP POST and message body.  Anything that may use special characters should be in the body of the request.  Seems like a decent solution, but posts are understood to not be Idempotent and (I thought) are generally meant for changes (whereas no change is occurring here).

Use HTTP GET and message body.  Anything that may use special characters should be in the body of the request.  This seems like a bad idea according to SO: HTTP GET with request body and Roy Fielding.

Use a combination of #3 and either #1 or #2 above depending on how large the request can be.

Other???

Note that in some cases I may be able to change things around to prevent special characters (and I may do that), but I won't be able to do this in all cases.

Regarding URI length, RFC2616 Sec3.2.1 says the following:

The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

  Note: Servers ought to be cautious about depending on URI lengths
  above 255 bytes, because some older client or proxy
  implementations might not properly support these lengths.

In addition the Maximum URL length is 2,083 characters in Internet Explorer.

Related: How to pass complex queries in REST?

Body:
If the query is too big to go in the URI, turn your query into a resource (like a saved search).
I worked on a restful API for a hotel's booking system; the search query had too many params (preferences, rooming list...etc) so I turned it into a resource that I POST to the server. The server then replies with a URI uniquely identifing the search which body is the posted query + its results:

POST http://hotels.xyz/searches
body <search><query>...</query></search>

Response

201 Created - Location: http://hotels.xyz/searches/someID
Body <search><query>...</query><results>...</results></search>