问:
How to add new value for SKU price in Magento?
I am new in Magento , I created my code to remove the special offer
and to add new price for SKU.

I could remove the special offer but I could not add the new price for SKUs. How can this be done?

My code is as follows:

```<code>$productIds[][] = array('DF-12''200','DF-98''300','DF-87''400');

$products = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToSelect('*') // <- careful with this
    ->addAttributeToFilter(
        'sku', array('in' => $productIds[0])
    )
    ->load();

foreach ($products as $_product){
    $product = Mage::getModel('catalog/product')->load($_product->getId());
    $product->setprice($productIds[1])
    $product->setOffertext('');
    $product->setSpecialFromDate('');
    $product->setSpecialToDate('');
    $product->setSpecialPrice('');
    $product->save();
}
</code>```

答:
I'm not quite sure how you're forming the array containing your products' SKU and prices, it seems off to me. But since I can only speculate on that part with the given information, an example of how I'd programmatically update smaller product collections might be of more help. This snippet works for me in a backend model:

```<code>// array('sku' => price )
$productPricesBySku = array('DF-1234' => 180.00, 'DF-1235' => 99.95);

$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('price')             // optional
    ->addAttributeToSelect('special_from_date') // optional
    ->addAttributeToSelect('special_to_date')   // optional
    ->addAttributeToFilter('sku', array('in'=>array_keys($productPricesBySku)));

foreach($collection as $_product){

    if(!($price=$productPricesBySku[$_product->getSku()])) continue;
    // no need to load the product again
    // just set the data directly on our collection-item and save it
    $_product->setPrice((float)$price)
        ->setSpecialFromDate('')
        ->setSpecialToDate('')
        ->setSpecialPrice('')
        ->save();

}
</code>```

(To prevent memory exhaustion on large collections you should use the Mage_Core_Model_Resource_Iterator rather than foreach-loops. You can read up on that here for instance.)

Body:
I am new in Magento , I created my code to remove the special offer
and to add new price for SKU.

I could remove the special offer but I could not add the new price for SKUs. How can this be done?

My code is as follows:

$productIds[][] = array('DF-12''200','DF-98''300','DF-87''400');

$products = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToSelect('*') // <- careful with this
    ->addAttributeToFilter(
        'sku', array('in' => $productIds[0])
    )
    ->load();

foreach ($products as $_product){
    $product = Mage::getModel('catalog/product')->load($_product->getId());
    $product->setprice($productIds[1])
    $product->setOffertext('');
    $product->setSpecialFromDate('');
    $product->setSpecialToDate('');
    $product->setSpecialPrice('');
    $product->save();
}

Body:
I'm not quite sure how you're forming the array containing your products' SKU and prices, it seems off to me. But since I can only speculate on that part with the given information, an example of how I'd programmatically update smaller product collections might be of more help. This snippet works for me in a backend model:

// array('sku' => price )
$productPricesBySku = array('DF-1234' => 180.00, 'DF-1235' => 99.95);

$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('price')             // optional
    ->addAttributeToSelect('special_from_date') // optional
    ->addAttributeToSelect('special_to_date')   // optional
    ->addAttributeToFilter('sku', array('in'=>array_keys($productPricesBySku)));

foreach($collection as $_product){

    if(!($price=$productPricesBySku[$_product->getSku()])) continue;
    // no need to load the product again
    // just set the data directly on our collection-item and save it
    $_product->setPrice((float)$price)
        ->setSpecialFromDate('')
        ->setSpecialToDate('')
        ->setSpecialPrice('')
        ->save();

}

(To prevent memory exhaustion on large collections you should use the Mage_Core_Model_Resource_Iterator rather than foreach-loops. You can read up on that here for instance.)


来源: stackexchange

问:
some issue with using atom sync-settings tool
With the risk of me misunderstanding something, I can't get my packages to sync. I went through the following scenario:

I install new packages on Machine 1 and upload the settings through the "Sync Backup" command in atom. I can see that the new packages are listed in the packages.json file in the gist.
On Machine

I restore the settings and can indeed see settings being restored, like keymaps. However I don't get my new packages. I have restarted and reloaded Atom without luck.
Are there any extra steps I need to take to get the new packages on Machine 2?

答: You can try atom-package-sync. It is a package that I created a couple weeks ago. It works a little bit like the synchronization of Google Chrome, you just login and it syncs your packages and settings automatically across all your Atom instances. It is based on package-sync but I find it easier to use.

ContentLicense: CC BY-SA 3.0


问:
fscanf always returns 0(CLOSED)
I am a beginner in C programming, and I am trying to write a simple code to read a text file and write its content into an array, then print it on console. However, I always get 0.0000, and I could not solve the problem.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

int numOfLines(FILE *fp1);
void printarr(float arr[], int size);
float *filetoArr(FILE *fp, int arrsize);

int main(int argc, const char *argv[]) {
    char *fileName1 = argv[1];
    FILE *fp1 = fopen(fileName1, "r");
    printf("File name: %s", fileName1);
    int size = numOfLines(fp1);
    printf("Number of lines in the file: %d\n", size);
    float *arr = filetoArr(fp1, size);
    printarr(arr, size);
    free(arr);
    fclose(fp1);
}

void printarr(float *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%f ", *(arr + i));
    }
}

float *filetoArr(FILE *fp, int arrsize) {
    int size = arrsize;
    float *arr = (float *)malloc(sizeof(float) * size);
    for (int i = 0; i < size; i++) {
        fscanf(fp, "%f\n", (arr+i));
    }
    return (arr);
}

int numOfLines(FILE *fp1) {
    int numberOfLines = 0;
    char c;
    do {
        c = getc(fp1);
        if (c == '\n') {
            numberOfLines++;
        }
    } while (c != EOF);
    return numberOfLines;
}
</code>```

答:
your numOfLines goes to the end of the file.

You have to rewind(fp1) to reset your file handle to position 0, or fscanf hits the end of the file, and doesn't read anything (check return code from fscanf: it should be 1 I bet you're getting 0 all the time)

Title: fscanf always returns 0(CLOSED)

Body:
I am a beginner in C programming, and I am trying to write a simple code to read a text file and write its content into an array, then print it on console. However, I always get 0.0000, and I could not solve the problem.

#include <stdio.h>
#include <stdlib.h>

int numOfLines(FILE *fp1);
void printarr(float arr[], int size);
float *filetoArr(FILE *fp, int arrsize);

int main(int argc, const char *argv[]) {
    char *fileName1 = argv[1];
    FILE *fp1 = fopen(fileName1, "r");
    printf("File name: %s", fileName1);
    int size = numOfLines(fp1);
    printf("Number of lines in the file: %d\n", size);
    float *arr = filetoArr(fp1, size);
    printarr(arr, size);
    free(arr);
    fclose(fp1);
}

void printarr(float *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%f ", *(arr + i));
    }
}

float *filetoArr(FILE *fp, int arrsize) {
    int size = arrsize;
    float *arr = (float *)malloc(sizeof(float) * size);
    for (int i = 0; i < size; i++) {
        fscanf(fp, "%f\n", (arr+i));
    }
    return (arr);
}

int numOfLines(FILE *fp1) {
    int numberOfLines = 0;
    char c;
    do {
        c = getc(fp1);
        if (c == '\n') {
            numberOfLines++;
        }
    } while (c != EOF);
    return numberOfLines;
}


问:
Add a spinning wheel while application is searching database
I have an application that searches in a database for some information.

Since the database is quite big, it sometimes takes a lot of time before the application returns the results to the interface.

I want to add some sort of spinning wheel to inform the user that the application is still searching the database and did not freeze. Once the results are returned, the wheel should disappear.

Any idea how to do this or is there a good tutorial explaining how to do this?

答:
Have you considered changing the mouse pointer to the hourglass as this would be extremely simple to implement:

```<code>Me.Cursor = Cursors.WaitCursor

...Do your DB calls here...

Me.Cursor = Cursors.Default
</code>```

However, I would agree that display a 'spinning wheel' is probably a little more user friendly and definately a lot more obvious.  So, first get hold of an animated gif that suits your needs.  Then create a form that has a picture box containing the image.

Once you have that you can show the form to the user and in the background do the DB work, once this has completed close the form.

Another alternative would be to use a rolling progress bar instead, so when it reaches 100% it cycles around again and keeps going until you close it.

EDIT:

One thing that I forgot to mention is that you will have to handle exception conditions.  Lets say you set the cursor to wait, then an error occurs.  The exception may bypass the code that resets everything.  This leaves the user with a changed cursor and no means of changing it.

When I have done this kind of thing I have typically created a disposable WaitCursor class and then used something like this:

```<code>Using myWaitCursor As WaitCursor = New WaitCursor
...do something...
End Using
</code>```

In the Dispose of the WaitCursor class you set the cursor back to default.  The same would apply if you went down the route of using a form with an image or progress bar.

ContentLicense: CC BY-SA 2.5

Body:
Have you considered changing the mouse pointer to the hourglass as this would be extremely simple to implement:

Me.Cursor = Cursors.WaitCursor

...Do your DB calls here...

Me.Cursor = Cursors.Default

However, I would agree that display a 'spinning wheel' is probably a little more user friendly and definately a lot more obvious.  So, first get hold of an animated gif that suits your needs.  Then create a form that has a picture box containing the image.

Once you have that you can show the form to the user and in the background do the DB work, once this has completed close the form.

Another alternative would be to use a rolling progress bar instead, so when it reaches 100% it cycles around again and keeps going until you close it.

EDIT:

One thing that I forgot to mention is that you will have to handle exception conditions.  Lets say you set the cursor to wait, then an error occurs.  The exception may bypass the code that resets everything.  This leaves the user with a changed cursor and no means of changing it.

When I have done this kind of thing I have typically created a disposable WaitCursor class and then used something like this:

Using myWaitCursor As WaitCursor = New WaitCursor
...do something...
End Using

In the Dispose of the WaitCursor class you set the cursor back to default.  The same would apply if you went down the route of using a form with an image or progress bar.


问:
gSOAP Serialized XML to String
Anyway I can print the serialized xml message (using gsoap).

For example:

```<code>soap_serialize_ns1__Response(soap, &ns2__UpdatedResponse);
</code>```

I would like to be able to see what the serialized (xml) looks like.

Anyone know how?

答:
Anyway I can print the serialized xml message (using gsoap).

I would like to be able to see what the serialized (xml) looks like.

To "print" a serialized object to a string in XML you have two options, depending whether you are coding in C or in C++.

When coding in C do the following:

```<code>struct soap *soap = soap_new();
...
const char *str = NULL;
soap->os = &str; // assign a string to write output to
soap_write_ns1__Response(soap, &response);
soap->os = NULL; // no longer writing to the string
printf("The XML is:%s\n", str);
...
soap_end(soap); // warning: this deletes str with XML too!
str = NULL;     // so make it NULL as good practice
soap_free(soap);
</code>```

When coding in C++ do the following:

```<code>soap *soap = soap_new();
...
std::stringstream ss;
soap->os = &ss; // assign a stringstream to write output to
soap_write_ns1__Response(soap, &response);
soap->os = NULL; // no longer writing to the stream
std::cout << "The XML is:\n" << ss.str();
...
soap_destroy(soap);
soap_end(soap);
soap_free(soap);
</code>```

See gSOAP XML databindgs on their web site for details.

Title: gSOAP Serialized XML to String

Body:
Anyway I can print the serialized xml message (using gsoap).

For example:

soap_serialize_ns1__Response(soap, &ns2__UpdatedResponse);

I would like to be able to see what the serialized (xml) looks like.

Anyone know how?

Body:
Anyway I can print the serialized xml message (using gsoap).

I would like to be able to see what the serialized (xml) looks like.

To "print" a serialized object to a string in XML you have two options, depending whether you are coding in C or in C++.

When coding in C do the following:

struct soap *soap = soap_new();
...
const char *str = NULL;
soap->os = &str; // assign a string to write output to
soap_write_ns1__Response(soap, &response);
soap->os = NULL; // no longer writing to the string
printf("The XML is:%s\n", str);
...
soap_end(soap); // warning: this deletes str with XML too!
str = NULL;     // so make it NULL as good practice
soap_free(soap);

When coding in C++ do the following:

soap *soap = soap_new();
...
std::stringstream ss;
soap->os = &ss; // assign a stringstream to write output to
soap_write_ns1__Response(soap, &response);
soap->os = NULL; // no longer writing to the stream
std::cout << "The XML is:\n" << ss.str();
...
soap_destroy(soap);
soap_end(soap);
soap_free(soap);

See gSOAP XML databindgs on their web site for details.


问:
Static const declaration, constexpr definition of variable, valid c++?
Example:
In header file:

```<code>class Foo
{
     static const int IntArray[];
};
</code>```

In source file:

```<code>constexpr int Foo::IntArray[] = { 1, 2, 3, 4 };
</code>```

This compiles on g++ and allows me to put the initializer list in the source file in stead of the header. (if it were constexpr in the header the compiler requires immediate initialization in the header). While still allowing the array to be used in constexpr evaluations...

Is this valid, portable C++ ?

答:
I doubt it's compliant. The declaration and definition are required to be identical AFAIK.

It's certainly not portable. Although gcc, clang and microsoft cl 2017 accept it,

ICC reports:

```<code><source>(6): error: member "Foo::IntArray" (declared at line 3) was previously not declared constexpr
  constexpr int Foo::IntArray[] = { 1, 2, 3, 4 };
  ^
compilation aborted for <source> (code 2)
Compiler exited with result code 2
</code>```

Body:
Example:
In header file:

class Foo
{
     static const int IntArray[];
};

In source file:

constexpr int Foo::IntArray[] = { 1, 2, 3, 4 };

This compiles on g++ and allows me to put the initializer list in the source file in stead of the header. (if it were constexpr in the header the compiler requires immediate initialization in the header). While still allowing the array to be used in constexpr evaluations...

Is this valid, portable C++ ?

Body:
I doubt it's compliant. The declaration and definition are required to be identical AFAIK.

It's certainly not portable. Although gcc, clang and microsoft cl 2017 accept it,

ICC reports:

<source>(6): error: member "Foo::IntArray" (declared at line 3) was previously not declared constexpr
  constexpr int Foo::IntArray[] = { 1, 2, 3, 4 };
  ^
compilation aborted for <source> (code 2)
Compiler exited with result code 2


问:
Program won't start through bat file
I have a program called program.exe

It's located in the folder:

```<code>C:\Program Files\Comp\Soft\program.exe
</code>```

I want to start it through a bat file but failed to do so.

Everything works when I do this in cmd:

```<code>cmd> cd C:\Program Files\Comp\Soft\
cmd> program.exe
// program is running
</code>```

I tried to do it in a bat file using these combinations:

```<code>Start "" "C:\Program Files\Comp\Soft\program.exe"
Start /d "" "C:\Program Files\Comp\Soft" "program.exe"
Start /d /w "" "C:\Program Files\Comp\Soft" "program.exe"
</code>```

But failed everytime.

What's wrong with my file?

答:
Try this</p>

```<code>cd "c:\Program Files\Comp\Soft"
start "" program.exe
</code>```

Title: Program won't start through bat file

Body:
I have a program called program.exe

It's located in the folder:

C:\Program Files\Comp\Soft\program.exe

I want to start it through a bat file but failed to do so.

Everything works when I do this in cmd:

cmd> cd C:\Program Files\Comp\Soft\
cmd> program.exe
// program is running

I tried to do it in a bat file using these combinations:

Start "" "C:\Program Files\Comp\Soft\program.exe"
Start /d "" "C:\Program Files\Comp\Soft" "program.exe"
Start /d /w "" "C:\Program Files\Comp\Soft" "program.exe"

But failed everytime.

What's wrong with my file?

Body:
Try this

cd "c:\Program Files\Comp\Soft"
start "" program.exe


问:
Swift: Can't insert NSObject into Array as it wants a [String] instead
I have a model object called Hashtag. This simply contains a optional String variable called hashtagName. I fetch the data from my Firebase Database and append the hashtags to my fashionHashtags, which is a [Hashtag]. The issue I have is that I want to append that to my other categoriesArray by using the insertElementAtIndexPath function. I cannot do this as it wants an array of Strings and not an array of Hashtag. When I autocorrect it, it replaces it with fashionHashtags as! [String] but that creates another error. How do I fix this so it allows me to do so? I would like to stick to the Model Object way of doing things. Thank you guys. An answer would be highly appreciated. Code is below:

```<code>class Hashtag: NSObject {

    vvar hashtagName: String?
}

private let reuseIdentifier = "Cell"

class HashtagView: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var catagoriesArray: [String] = ["FASHION", "FOOD", "HOBBIES", "MUSIC"]

    var fashionHashtags = [Hashtag]()
    var foodHashtags = [Hashtag]()
    var hobbiesHashtags = [Hashtag]()
    var musicHashtags = [Hashtag]()

    var hashtagsArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.hashtagsArray.removeAll()

        self.navigationController?.navigationBar.tintColor = .white
        navigationItem.title = "Hashtag"

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Finished", style: .plain, target: self, action: #selector(finishSelectingHashtags))

        self.collectionView?.backgroundColor = .white
        self.collectionView?.register(HashtagCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView?.contentInset = UIEdgeInsetsMake(10, 0, 0, 0)

        handleFetchFashionHashtags()
    }

    func insertElementAtIndexPath(element: [String], index: Int) {
        catagoriesArray.insert(contentsOf: element, at: index)
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if indexPath.item == 0 {
            insertElementAtIndexPath(element: fashionHashtags, index: indexPath.item + 1)

            self.collectionView?.performBatchUpdates(
                {
                    self.collectionView?.reloadSections(NSIndexSet(index: 0) as IndexSet)
            }, completion: { (finished:Bool) -> Void in

            })
        }

    }
</code>```

答:
Based upon my understanding, there could be a couple of different approaches.  Here would be the approach of looping through the array of Hashtag objects and appending the hashtagName string property to the categoriesArray of strings.

```<code>    for hashTagItem in fashionHashtags {
        if let hashTag = hashTagItem.hashtagName {
             // Appends to categoriesArray as a string
             categoriesArray.append(hashTag)
        }
    }
</code>```

Another approach would be to build a set of strings and then insert it as it makes sense.

```<code>    var hashTagString: [Strings] = []
    for hashTagItem in fashionHashtags {
        if let hashTag = hashTagItem.hashtagName {
             hashTagStrings.append(hashTag)
        }
    }
    // Insert or add the hash tag strings as it makes sense
    categoriesArray += hashTagStrings  // Add all at once if it makes sense
</code>```

Body:
I have a model object called Hashtag. This simply contains a optional String variable called hashtagName. I fetch the data from my Firebase Database and append the hashtags to my fashionHashtags, which is a [Hashtag]. The issue I have is that I want to append that to my other categoriesArray by using the insertElementAtIndexPath function. I cannot do this as it wants an array of Strings and not an array of Hashtag. When I autocorrect it, it replaces it with fashionHashtags as! [String] but that creates another error. How do I fix this so it allows me to do so? I would like to stick to the Model Object way of doing things. Thank you guys. An answer would be highly appreciated. Code is below:

class Hashtag: NSObject {

    vvar hashtagName: String?
}

private let reuseIdentifier = "Cell"

class HashtagView: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var catagoriesArray: [String] = ["FASHION", "FOOD", "HOBBIES", "MUSIC"]

    var fashionHashtags = [Hashtag]()
    var foodHashtags = [Hashtag]()
    var hobbiesHashtags = [Hashtag]()
    var musicHashtags = [Hashtag]()

    var hashtagsArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.hashtagsArray.removeAll()

        self.navigationController?.navigationBar.tintColor = .white
        navigationItem.title = "Hashtag"

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Finished", style: .plain, target: self, action: #selector(finishSelectingHashtags))

        self.collectionView?.backgroundColor = .white
        self.collectionView?.register(HashtagCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView?.contentInset = UIEdgeInsetsMake(10, 0, 0, 0)

        handleFetchFashionHashtags()
    }

    func insertElementAtIndexPath(element: [String], index: Int) {
        catagoriesArray.insert(contentsOf: element, at: index)
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if indexPath.item == 0 {
            insertElementAtIndexPath(element: fashionHashtags, index: indexPath.item + 1)

            self.collectionView?.performBatchUpdates(
                {
                    self.collectionView?.reloadSections(NSIndexSet(index: 0) as IndexSet)
            }, completion: { (finished:Bool) -> Void in

            })
        }

    }

Body:
Based upon my understanding, there could be a couple of different approaches.  Here would be the approach of looping through the array of Hashtag objects and appending the hashtagName string property to the categoriesArray of strings.

    for hashTagItem in fashionHashtags {
        if let hashTag = hashTagItem.hashtagName {
             // Appends to categoriesArray as a string
             categoriesArray.append(hashTag)
        }
    }

Another approach would be to build a set of strings and then insert it as it makes sense.

    var hashTagString: [Strings] = []
    for hashTagItem in fashionHashtags {
        if let hashTag = hashTagItem.hashtagName {
             hashTagStrings.append(hashTag)
        }
    }
    // Insert or add the hash tag strings as it makes sense
    categoriesArray += hashTagStrings  // Add all at once if it makes sense


问:
Firefox, CSS display: table / table-cell and height
Im displaying several content in div and span elements in a table like style.

```<code><div class="row">
  <div class="item">
    <div class="item-col-glyphicon">
      <span class="glyphicon glyphicon-remove item-glyphicon"></span>
    </div>
    <div class="item-col1">
      <span class="item-col1-a">a</span>
      <span class="item-col1-b">b</span>
    </div>
    <div class="separator"></div>
    <div class="details">
      <span style="display:block">Line 1</span>
      <span style="display:block">Line 2</span>
    </div>
  </div>
</div>
</code>```

The glyphicon-remove should be vertically centered, which works fine in Chrome and IE 11 but not Firefox 52.

The expected result looks like this:

The Firefox result looks like this:

What am I doing wrong here?
I created a fiddle.

答:
the 0.7em on the class item-glyphicon was not required for mozilla. so i made that rule chrome specific. Heres the link to working fiddle, https://jsfiddle.net/x1uydngo/9/</p>

```<code>@media screen and (-webkit-min-device-pixel-ratio:0)
{
.item-glyphicon{top:0.7em;}
}
</code>```

Body:
Im displaying several content in div and span elements in a table like style.

      a
      b

      Line 1
      Line 2

The glyphicon-remove should be vertically centered, which works fine in Chrome and IE 11 but not Firefox 52.

The expected result looks like this:

The Firefox result looks like this:

What am I doing wrong here?
I created a fiddle.

Body:
the 0.7em on the class item-glyphicon was not required for mozilla. so i made that rule chrome specific. Heres the link to working fiddle, https://jsfiddle.net/x1uydngo/9/

@media screen and (-webkit-min-device-pixel-ratio:0)
{
.item-glyphicon{top:0.7em;}
}


问:
emacs formatting problems
How can I configure it so that when I create and edit files in emacs the formatting looks the same in editors such as Geany or gedit,, it seems that the indentation is never preserved correctly.</p>

答: This is probably related to tab ('\t', 0x9) characters.  To forbid emacs from adding tab characters, customize indent-tabs-mode to nil.  (C-h v indent-tabs-mode).  To replace all tabs in existing files with spaces (and keep it looking as it currently does in emacs), use M-x untabify (acts on the current region).

Title: emacs formatting problems


问:
Reporting Services Line Breaks When Exported Not In HTML
In Reportings Serivces 2005..I have a matrix control with a the below expression in one of the cells. The problem is that all these lines are running together when viewed from the report viewer. It does, however, export in the correct format (pdf, excel). This is a little issue but its drving me nuts. I use the same technique on other reports and they display as expected.

Expression:

```<code>=Fields!FullName.Value + " (" + Fields!Id.Value.ToString() + ") "
+ chr(10) + chr(13)
+ "dob " + Format(Fields!DateOfBirth.Value, "MM/dd/yyyy")
+ chr(10) + chr(13)
+ "Days Enrolled: " + Fields!OriginalDaysEnrolled.Value.ToString()
+ chr(10) + chr(13)
+ "45 Day: " + Fields!ItemStringFor45Day.Value
+ chr(10) + chr(13)
+ "90 Day: " + Fields!NinetyDay.Value.ToString()
+ chr(10) + chr(13)
+ "Current: " + Fields!CurrentDescription.Value
+ chr(10) + chr(13)
+ "Open Follow Ups: " + Fields!FollowUpCount.Value.ToString()
</code>```

Web Appearance (IE7, haven't checked others)

Doe, Johnny (123456) dob 03/30/2009 Days Enrolled: 98 45 Day: V H Deca Dev 90 Day: 18 Month Current: 18 Month Open Follow Ups: 1

Exported Appearance (as expected and as Web should look)

Doe, Johnny (123456)

  dob 03/30/2009

  Days Enrolled: 98

  45 Day: V H Deca Dev

  90 Day: 18 Month

  Current: 18 Month

  Open Follow Ups: 1

答:
White space is just white space to HTML; it condenses all the white space to a single space for presentation (including your chr(10) + chr(13)). In order for a line break, you either have to use a
 tag or surround your line break values with ``````.

If you save the following as a ".html" file, you'll see that all characters will be displayed on the same line.

```<code><html>
    <body>
        This is
        my          test
        for
        line breaks!
    </body>
</html>
</code>```

However, this will yield the line breaks you want.

```<code><html>
    <body>
        ```
            This is
            my          test
            for
            line breaks!
        ```
    </body>
</html>
</code>```

Easiest thing for you to do though is to replace your chr(10) + chr(13) with
. PDF and Excel will still respect the tag as a line break. If
 doesn't work, try
 - I can't remember if Reporting Services encodes its output or not.

Body:
In Reportings Serivces 2005..I have a matrix control with a the below expression in one of the cells. The problem is that all these lines are running together when viewed from the report viewer. It does, however, export in the correct format (pdf, excel). This is a little issue but its drving me nuts. I use the same technique on other reports and they display as expected.

Expression:

=Fields!FullName.Value + " (" + Fields!Id.Value.ToString() + ") "
+ chr(10) + chr(13)
+ "dob " + Format(Fields!DateOfBirth.Value, "MM/dd/yyyy")
+ chr(10) + chr(13)
+ "Days Enrolled: " + Fields!OriginalDaysEnrolled.Value.ToString()
+ chr(10) + chr(13)
+ "45 Day: " + Fields!ItemStringFor45Day.Value
+ chr(10) + chr(13)
+ "90 Day: " + Fields!NinetyDay.Value.ToString()
+ chr(10) + chr(13)
+ "Current: " + Fields!CurrentDescription.Value
+ chr(10) + chr(13)
+ "Open Follow Ups: " + Fields!FollowUpCount.Value.ToString()

Web Appearance (IE7, haven't checked others)

Doe, Johnny (123456) dob 03/30/2009 Days Enrolled: 98 45 Day: V H Deca Dev 90 Day: 18 Month Current: 18 Month Open Follow Ups: 1

Exported Appearance (as expected and as Web should look)

Doe, Johnny (123456)

  dob 03/30/2009

  Days Enrolled: 98

  45 Day: V H Deca Dev

  90 Day: 18 Month

  Current: 18 Month

  Open Follow Ups: 1

Body:
White space is just white space to HTML; it condenses all the white space to a single space for presentation (including your chr(10) + chr(13)). In order for a line break, you either have to use a <br /> tag or surround your line break values with <pre></pre>.

If you save the following as a ".html" file, you'll see that all characters will be displayed on the same line.

<html>
    <body>
        This is
        my          test
        for
        line breaks!
    </body>
</html>

However, this will yield the line breaks you want.

<html>
    <body>
        <pre>
            This is
            my          test
            for
            line breaks!
        </pre>
    </body>
</html>

Easiest thing for you to do though is to replace your chr(10) + chr(13) with <br />. PDF and Excel will still respect the tag as a line break. If <br /> doesn't work, try &lt;br /&gt; - I can't remember if Reporting Services encodes its output or not.


问:
Rendering Dynamic Select Options
I have a form that is currently using jQuery to:

Do a series of ajax requests

Dynamically change select options based on the returned data.

I thought this would be something nice to reimplement in vue.js as a learning experience. But I am running into a snag with what is the best way to add dynamic options to a <select>.

This link in the docs (http://012.vuejs.org/guide/forms.html#Dynamic_Select_Options) looks like exactly what I need but I am having issues replicating it in my code below. Any ideas what I could be doing wrong? Any tips are appreciated!

```<code><script src="https://unpkg.com/vue"></script>

<script type="text/x-template" id="add-match-template">
    <select v-model="selected_game" options="games"></select>
</script>

<div id="add_match_form">
    <add-match-form></add-match-form>
</div>

<script type="text/javascript">
    Vue.component('add-match-form', {
        template: '#add-match-template',
        data: function() {
            return {
                games: [
                    {'value': 1, 'text': 'Game 1'},
                    {'value': 4, 'text': 'Game 4'}
                ],
                selected_game: null
            }
        }
    })

    new Vue({
        el: "#add_match_form"
    })
</script>
</code>```

答:
In Vue 2, you no longer bind options that way. Here is the current documentation.

```<code>Vue.component('add-match-form', {
  template: '#add-match-template',
  data: function() {
    return {
      games: [
        {'value': 1, 'text': 'Game 1'},
        {'value': 4, 'text': 'Game 4'}
      ],
      selected_game: null
    }
  }
})

new Vue({
  el: "#add_match_form"
})
</code>```

Template:

```<code><div id="add_match_form">
    <add-match-form></add-match-form>
</div>

<template id="add-match-template">
  <select v-model="selected_game">
    <option v-for="game in games" :value="game.value">{{game.text}}</option>
  </select>
</template>
</code>```

Working Example

console.clear()

Vue.component('add-match-form', {
  template: '#add-match-template',
  data: function() {
    return {
      games: [
        {'value': 1, 'text': 'Game 1'},
        {'value': 4, 'text': 'Game 4'}
      ],
      selected_game: null
    }
  }
})

new Vue({
  el: "#add_match_form"
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="add_match_form">
    <add-match-form></add-match-form>
</div>

<template id="add-match-template">
  <select v-model="selected_game">
    <option v-for="game in games" :value="game.value">{{game.text}}</option>
  </select>
</template></code>```

ContentLicense: CC BY-SA 4.0

Title: Rendering Dynamic Select Options

Body:
I have a form that is currently using jQuery to:

Do a series of ajax requests

Dynamically change select options based on the returned data.

I thought this would be something nice to reimplement in vue.js as a learning experience. But I am running into a snag with what is the best way to add dynamic options to a <select>.

This link in the docs (http://012.vuejs.org/guide/forms.html#Dynamic_Select_Options) looks like exactly what I need but I am having issues replicating it in my code below. Any ideas what I could be doing wrong? Any tips are appreciated!

    <add-match-form></add-match-form>

Body:
In Vue 2, you no longer bind options that way. Here is the current documentation.

Vue.component('add-match-form', {
  template: '#add-match-template',
  data: function() {
    return {
      games: [
        {'value': 1, 'text': 'Game 1'},
        {'value': 4, 'text': 'Game 4'}
      ],
      selected_game: null
    }
  }
})

new Vue({
  el: "#add_match_form"
})

Template:

<div id="add_match_form">
    <add-match-form></add-match-form>
</div>

<template id="add-match-template">
  <select v-model="selected_game">
    <option v-for="game in games" :value="game.value">{{game.text}}</option>
  </select>
</template>

Working Example

console.clear()

Vue.component('add-match-form', {
  template: '#add-match-template',
  data: function() {
    return {
      games: [
        {'value': 1, 'text': 'Game 1'},
        {'value': 4, 'text': 'Game 4'}
      ],
      selected_game: null
    }
  }
})

new Vue({
  el: "#add_match_form"
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="add_match_form">
    <add-match-form></add-match-form>
</div>

<template id="add-match-template">
  <select v-model="selected_game">
    <option v-for="game in games" :value="game.value">{{game.text}}</option>
  </select>
</template>


问:
Spyder: refresh existing plot window instead of opening a new one
I want to show plots in a separate window. Currently I have the IPython graphics backend set to "automatic".

When I re-run the code (or plot another figure), Spyder opens a new plot window. Is it possible to refresh the figure in the window that is already opened instead of opening a new one?

答:
The GUI window that opens when you call plt.show() is bound to a figure. You cannot change the figure inside it. (Well, to be precise, there might be an option of obtaining a handle from the operating system and manipulating its content, but I assume this is not worth the effort.)

Re-running the code actually means that you produce a new figure since the code does not know that it's been run before.

So, exchanging the figure or reusing the window to plot a different figure is not possible.

What is possible however is to use the figure and manipulate the figure while it's open. This is done via plt.ion(). After calling this command in IPython you can adapt the figure, e.g. adding new lines to it etc.

See this example:

At  IN [6] the window opens and when IN [7] is executed, the figure stays open and the content changes.


问:
how to show bar chart for every product
I'm trying to print a bar chart for every product to show a summary of data but the bar chart is showing only once with different values at y-axis.

How can I show the data for each product on a bar chart?

Review.js

```<code>angular.module('App.review',[]).directive('review', function($cookieStore){
return{
     restrict:'E',
     controller:function($scope, $window, $http){
             var ctx = document.getElementById("myChart");
             var myChart = new Chart(ctx, {
                 type: 'horizontalBar',
                 data: {
                     labels: ["Rating", "Blue", "Yellow", "Green", "Purple", "O"],
                     datasets: [{
                         label: '# of Votes',
                         data: $scope.data,
                         backgroundColor: [
                             'rgba(255, 99, 132, 0.2)',
                             'rgba(54, 162, 235, 0.2)',
                             'rgba(255, 206, 86, 0.2)',
                             'rgba(75, 192, 192, 0.2)',
                             'rgba(153, 102, 255, 0.2)',
                             'rgba(255, 159, 64, 0.2)'
                         ],
                         borderColor: [
                             'rgba(255,99,132,1)',
                             'rgba(54, 162, 235, 1)',
                             'rgba(255, 206, 86, 1)',
                             'rgba(75, 192, 192, 1)',
                             'rgba(153, 102, 255, 1)',
                             'rgba(255, 159, 64, 1)'
                         ],
                         borderWidth: 1
                     }]
                 },
                 options: {
                     scales: {
                         xAxes: [{
                             display: false,
                             stacked: false,
                             ticks: {
                                    min: 0,
                                    max: 10
                                }
                         }]
                     }
                 }
             });
            },
     templateUrl:'scripts/directives/ReviewDirective/review.html',
     transclude:false
}
 });
</code>```

review.html

```<code><div style="width:100%; border:solid green;">
 <canvas  id="myChart" width="100" height="100vh"></canvas>
</div>
</code>```

product.html

```<code><td ng-controller="ReviewsCtrl" >
              <div data-ng-repeat="r in dataList" >
                <div data-ng-if=" r.id == item.productId">
                  <div data-ng-init="data =r.data" >
                    {{data=r.data}}
                    <review></review>
                  </div>
                </div>
              </div>
            </td>
</code>```

答:
Check this code

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

    app.directive('review', function () {
        return {
            restrict: 'E',
            scope: {
                data: "=data"
            },
            link: function ($scope, element, attrs) {
                var ctx = element[0].querySelector('#myChart');
                var myChart = new Chart(ctx, {
                    type: 'horizontalBar',
                    data: {
                        labels: ["Rating", "Blue", "Yellow", "Green", "Purple", "O"],
                        datasets: [{
                            label: '# of Votes',
                            data: $scope.data,
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.2)',
                                'rgba(54, 162, 235, 0.2)',
                                'rgba(255, 206, 86, 0.2)',
                                'rgba(75, 192, 192, 0.2)',
                                'rgba(153, 102, 255, 0.2)',
                                'rgba(255, 159, 64, 0.2)'
                            ],
                            borderColor: [
                                'rgba(255,99,132,1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            xAxes: [{
                                display: false,
                                stacked: false,
                                ticks: {
                                    min: 0,
                                    max: 10
                                }
                            }]
                        }
                    }
                });
            },
            templateUrl: 'review.html',
            transclude: false
        }
    });
    app.controller('ReviewsCtrl', function ($scope) {
        $scope.dataList = [{
            productId: 1,
            productName: 'One',
            data: [1, 2, 3, 4, 5]
        }, {
            productId: 2,
            productName: 'Two',
            data: [6, 7, 8, 1, 1]
        }];
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.6/angular.min.js"></script>
<div ng-app="App.review">
 <table>
  <tr>
   <td ng-controller="ReviewsCtrl">
    <div data-ng-repeat="r in dataList">
     {{r.productName}}
     <review data="r.data"></review>
    </div>
   </td>
  </tr>
 </table>

 <script type="text/ng-template" id="review.html">
  <div style="width: 100%; border: solid green;">
   <canvas id="myChart" width="100" height="100vh"></canvas>
  </div>
 </script>
</div></code>```

Title: how to show bar chart for every product

Body:
I'm trying to print a bar chart for every product to show a summary of data but the bar chart is showing only once with different values at y-axis.

How can I show the data for each product on a bar chart?

Review.js

angular.module('App.review',[]).directive('review', function($cookieStore){
return{
     restrict:'E',
     controller:function($scope, $window, $http){
             var ctx = document.getElementById("myChart");
             var myChart = new Chart(ctx, {
                 type: 'horizontalBar',
                 data: {
                     labels: ["Rating", "Blue", "Yellow", "Green", "Purple", "O"],
                     datasets: [{
                         label: '# of Votes',
                         data: $scope.data,
                         backgroundColor: [
                             'rgba(255, 99, 132, 0.2)',
                             'rgba(54, 162, 235, 0.2)',
                             'rgba(255, 206, 86, 0.2)',
                             'rgba(75, 192, 192, 0.2)',
                             'rgba(153, 102, 255, 0.2)',
                             'rgba(255, 159, 64, 0.2)'
                         ],
                         borderColor: [
                             'rgba(255,99,132,1)',
                             'rgba(54, 162, 235, 1)',
                             'rgba(255, 206, 86, 1)',
                             'rgba(75, 192, 192, 1)',
                             'rgba(153, 102, 255, 1)',
                             'rgba(255, 159, 64, 1)'
                         ],
                         borderWidth: 1
                     }]
                 },
                 options: {
                     scales: {
                         xAxes: [{
                             display: false,
                             stacked: false,
                             ticks: {
                                    min: 0,
                                    max: 10
                                }
                         }]
                     }
                 }
             });
            },
     templateUrl:'scripts/directives/ReviewDirective/review.html',
     transclude:false
}
 });

review.html

 <canvas  id="myChart" width="100" height="100vh"></canvas>

product.html

                    {{data=r.data}}
                    <review></review>

Body:
Check this code

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

    app.directive('review', function () {
        return {
            restrict: 'E',
            scope: {
                data: "=data"
            },
            link: function ($scope, element, attrs) {
                var ctx = element[0].querySelector('#myChart');
                var myChart = new Chart(ctx, {
                    type: 'horizontalBar',
                    data: {
                        labels: ["Rating", "Blue", "Yellow", "Green", "Purple", "O"],
                        datasets: [{
                            label: '# of Votes',
                            data: $scope.data,
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.2)',
                                'rgba(54, 162, 235, 0.2)',
                                'rgba(255, 206, 86, 0.2)',
                                'rgba(75, 192, 192, 0.2)',
                                'rgba(153, 102, 255, 0.2)',
                                'rgba(255, 159, 64, 0.2)'
                            ],
                            borderColor: [
                                'rgba(255,99,132,1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            xAxes: [{
                                display: false,
                                stacked: false,
                                ticks: {
                                    min: 0,
                                    max: 10
                                }
                            }]
                        }
                    }
                });
            },
            templateUrl: 'review.html',
            transclude: false
        }
    });
    app.controller('ReviewsCtrl', function ($scope) {
        $scope.dataList = [{
            productId: 1,
            productName: 'One',
            data: [1, 2, 3, 4, 5]
        }, {
            productId: 2,
            productName: 'Two',
            data: [6, 7, 8, 1, 1]
        }];
    });

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.6/angular.min.js"></script>
<div ng-app="App.review">
 <table>
  <tr>
   <td ng-controller="ReviewsCtrl">
    <div data-ng-repeat="r in dataList">
     {{r.productName}}
     <review data="r.data"></review>
    </div>
   </td>
  </tr>
 </table>

 <script type="text/ng-template" id="review.html">
  <div style="width: 100%; border: solid green;">
   <canvas id="myChart" width="100" height="100vh"></canvas>
  </div>
 </script>
</div>


问:
Python staticmethod and dependency injection
Can someone help me with a good explanation on why a staticmethod on python is useful for dependency injection?

I was seeing this great video https://www.youtube.com/watch?v=E_kZDvwofHY and on 45m45s Thomas Wouters claim that staticmethods are useful for DI, but I can't grasp why.

...

After start to writing this post, and made some tests I think I got it.
An example:

```<code>class GreetPrint(object):

    def pp(self, param):
        print("Hello", param)

class User(object):

    def __init__(self, param):
        self.param = param

    def print_user(self):
        self.output(self.param)

    @staticmethod
    def output(msg):
        return print_dependency.pp(msg)

print_dependency = GreetPrint()

a = User("Guido")
a.print_user()
</code>```

This is a better approach (at least in Python) than injecting through the constructor?

答:
Dependency injection is where the client provides something the caller needs on to the caller.

In you're example it looks like the dependency being configured is the output method, in this case GreetPrint

In the example provided there is a tight coupling between the User and the output method GreetPrint.  Imagine if we were required to change the way User was outputted.  There is a tight coupling to the print dependency floating in global scope.  Different outputters could be applied to users through inheritance but then a large inheritance graph begins to develop and the benefits of dependency injection and composition are lost.

In this case the client isn't providing the User with the output method, the user only has a single output method GreetPrint, and it cannot be configured by the client.

The way you have it setup now looks considerably harder to work with than injecting the outputter into the constructor.

Dependency injection can be established by programming to an interface which removes the coupling of the target on its dependency.  I feel like the dependency in this case the the output method.

Should the user be responsible for outputting itself?  Or should the user be acted upon by the out putter?  Are there other types of objects besides users the program has to output?

Body:
Can someone help me with a good explanation on why a staticmethod on python is useful for dependency injection?

I was seeing this great video https://www.youtube.com/watch?v=E_kZDvwofHY and on 45m45s Thomas Wouters claim that staticmethods are useful for DI, but I can't grasp why.

...

After start to writing this post, and made some tests I think I got it.
An example:

class GreetPrint(object):

    def pp(self, param):
        print("Hello", param)

class User(object):

    def __init__(self, param):
        self.param = param

    def print_user(self):
        self.output(self.param)

    @staticmethod
    def output(msg):
        return print_dependency.pp(msg)

print_dependency = GreetPrint()

a = User("Guido")
a.print_user()

This is a better approach (at least in Python) than injecting through the constructor?


问:
How to display object attributes based on user choice?
I am new to java object oriented programming and need help with a problem!

I created a variety of DVD objects and want to let the user choose an option, then display several attributes of the chosen DVD. However, I don't want to have to create 8 different cases for all the possible movie options. Is there a way to call on a method with a variable that corresponds to each DVD ID (which is the first variable I assigned)?

I tried creating an array list but it gives me an error

Any help is much appreciated!

```<code>    List<DVD> list = new ArrayList<DVD>(){
    DVD dvd1 = new DVD(1, "Movie 1");
    DVD dvd2 = new DVD(2, "Movie 2");
    DVD dvd3 = new DVD(3, "Movie 3");
    DVD dvd4 = new DVD(4, "Movie 4");
    DVD dvd5 = new DVD(5, "Movie 5");
    DVD dvd6 = new DVD(6, "Movie 6");
    DVD dvd7 = new DVD(7, "Movie 7");

        System.out.println("Enter your movie choice");
        int movieChoice = sc.nextInt();

        System.out.println(list.get(movieChoice).getDVDName());
</code>```

答:
Use reflections to look for fields by names. Let's say wanted hash set contains names of fields needed to be processed.

```<code>Set<String> wanted = new HashSet<>();
    Stream.of(DVD.class.getDeclaredFields()).filter(field -> wanted.contains(field.getName())).forEach(field ->
            {
                boolean accesBuffer = field.isAccessible();
                field.setAccessible(true);
                //Do Something With the Field - get value, store in HashMap, etc.
                field.setAccessible(accesBuffer);
            }
    );
</code>```

Body:
I am new to java object oriented programming and need help with a problem!

I created a variety of DVD objects and want to let the user choose an option, then display several attributes of the chosen DVD. However, I don't want to have to create 8 different cases for all the possible movie options. Is there a way to call on a method with a variable that corresponds to each DVD ID (which is the first variable I assigned)?

I tried creating an array list but it gives me an error

Any help is much appreciated!

    List<DVD> list = new ArrayList<DVD>(){
    DVD dvd1 = new DVD(1, "Movie 1");
    DVD dvd2 = new DVD(2, "Movie 2");
    DVD dvd3 = new DVD(3, "Movie 3");
    DVD dvd4 = new DVD(4, "Movie 4");
    DVD dvd5 = new DVD(5, "Movie 5");
    DVD dvd6 = new DVD(6, "Movie 6");
    DVD dvd7 = new DVD(7, "Movie 7");

        System.out.println("Enter your movie choice");
        int movieChoice = sc.nextInt();

        System.out.println(list.get(movieChoice).getDVDName());

Body:
Use reflections to look for fields by names. Let's say wanted hash set contains names of fields needed to be processed.

Set<String> wanted = new HashSet<>();
    Stream.of(DVD.class.getDeclaredFields()).filter(field -> wanted.contains(field.getName())).forEach(field ->
            {
                boolean accesBuffer = field.isAccessible();
                field.setAccessible(true);
                //Do Something With the Field - get value, store in HashMap, etc.
                field.setAccessible(accesBuffer);
            }
    );


问:
How to remove components created with Angular-CLI
I am working on angular2 for my new project, newly with this technology. I have set-up my project with angular CLI (Reference site https://github.com/angular/angular-cli).
I have created 4 components using command ng generate component my-new-component
For testing purpose, created one component app-testing, need to remove that component from my project. Else need to rename for that component. I have tried several like. ng destroy component app-testing but showing error The destroy command is not supported by Angular-CLI., Please help me with solution.
Thanks in advance.

答: I tried ng remove component Comp_Name also ng distroy component but it is not yet supported by angular so the best option for now is to manually remove it from the folder structure.</p>


问:
Getting Spring/Jackson to intelligently deserialize model subclasses
Given a model hierarchy like so:

```<code>// WARNING: This is pseudo-code for giving an example!
public abstract class BaseVehicle {
    private String make;
    private String model;

    // Constructors, getters & setters down here
}

public class Motorcycle extends BaseVehicle {
    private int numCylinders;

    // Constructors, getters & setters down here
}

public class Car extends BaseVehicle {
    // ...etc.
}
</code>```

And given the following payload class (that will be sent to a Spring controller):

```<code>public class Payload {
    @JsonIgnore
    @JsonProperty(value = "orgId")
    private String orgId;

    @JsonIgnore
    @JsonProperty(value = "isInitialized")
    private Boolean isInitialized;

    @JsonIgnore
    @JsonProperty(value = "vehicle")
    private BaseVehicle vehicle;

    // Constructors, getters & setters down here
}
</code>```

I'm wondering if its possible to have the Spring controller (using Jackson for JSON serialization) configured to only expect a BaseVehicle instance in the Payload it receives, but to dynamically infer which BaseVehicle subclass was actually sent:

```<code>@RequestMapping(value='/payload', method=RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody MyAppResponse onPayload(@RequestBody Payload payload) {
    logger.info("Received a payload with a vehicle of type: " + payload.getVehicle().getClass().getName());
}
</code>```

So that if I happen to send a Payload JSON that contains a Motorcycle as its vehicle field, then when that logger.info(...) statement fires, the code sees the vehicle is a Motorcycle (and ditto for any other BaseVehicle subclass)?

Is this possible, if so, how?

答:
However I'd greatly prefer a solution that allows the JSON to remain as-is.

As I mentioned in my comment above, you could analyze the payload vehicle JSON object tree in order to make a little analysis trying to detect the payload element type.

@JsonDeserialize(using = BaseVehicleJsonDeserializer.class)
abstract class BaseVehicle {

    @JsonProperty
    private String make;

    @JsonProperty
    private String model;

}

@JsonDeserialize(as = Car.class)
final class Car
        extends BaseVehicle {
}

@JsonDeserialize(as = Motorcycle.class)
final class Motorcycle
        extends BaseVehicle {

    @JsonProperty
    private int numCylinders;

}
```

<p>The trick here is the <code>@JsonDeserialize</code> annotation. The <code>BaseVehicleJsonDeserializer</code> can be implemented as follows:</p>

<pre class="lang-java prettyprint-override"><code>final class BaseVehicleJsonDeserializer
        extends JsonDeserializer<BaseVehicle> {

    @Override
    public BaseVehicle deserialize(final JsonParser parser, final DeserializationContext context)
            throws IOException {
        final TreeNode treeNode = parser.readValueAsTree();
        final Class<? extends BaseVehicle> baseVehicleClass = Stream.of(treeNode)
                // Check if the tree node is ObjectNode
                .filter(tn -> tn instanceof ObjectNode)
                // And cast
                .map(tn -> (ObjectNode) tn)
                // Now "bind" the object node with if the object node can be supported by the resolver
                .flatMap(objectNode -> Stream.of(BaseVehicleTypeResolver.cachedBaseVehicleTypeResolvers).filter(resolver -> resolver.matches(objectNode)))
                // If found, just get the detected vehicle class
                .map(BaseVehicleTypeResolver::getBaseVehicleClass)
                // Take the first resolver only
                .findFirst()
                // Or throw a JSON parsing exception
                .orElseThrow(() -> new JsonParseException(parser, "Cannot parse: " + treeNode));
        // Convert the JSON tree to the resolved class instance
        final ObjectMapper objectMapper = (ObjectMapper) parser.getCodec();
        return objectMapper.treeToValue(treeNode, baseVehicleClass);
    }

    // Known strategies here
    private enum BaseVehicleTypeResolver {

        CAR_RESOLVER {
            @Override
            protected Class<? extends BaseVehicle> getBaseVehicleClass() {
                return Car.class;
            }

            @Override
            protected boolean matches(final ObjectNode objectNode) {
                return !objectNode.has("numCylinders");
            }
        },

        MOTORCYCLE_RESOLVER {
            @Override
            protected Class<? extends BaseVehicle> getBaseVehicleClass() {
                return Motorcycle.class;
            }

            @Override
            protected boolean matches(final ObjectNode objectNode) {
                return objectNode.has("numCylinders");
            }
        };

        // Enum.values() returns array clones every time it's invoked
        private static final BaseVehicleTypeResolver[] cachedBaseVehicleTypeResolvers = BaseVehicleTypeResolver.values();

        protected abstract Class<? extends BaseVehicle> getBaseVehicleClass();

        protected abstract boolean matches(ObjectNode objectNode);

    }

}
</code>```

As you can see, such an approach is more or less fragile and sophisticated, but it tries to make some analysis. Now, how it can be used:

final ObjectMapper mapper = new ObjectMapper();
Stream.of(
        "{\"orgId\":\"foo\",\"isInitialized\":true,\"vehicle\":{\"make\":\"foo\",\"model\":\"foo\"}}",
        "{\"orgId\":\"bar\",\"isInitialized\":true,\"vehicle\":{\"make\":\"bar\",\"model\":\"bar\",\"numCylinders\":4}}"
)
        .map(json -> {
            try {
                return mapper.readValue(json, Payload.class);
            } catch ( final IOException ex ) {
                throw new RuntimeException(ex);
            }
        })
        .map(Payload::getVehicle)
        .map(BaseVehicle::getClass)
        .forEach(System.out::println);
```

Output:

class q43138817.Car

  class q43138817.Motorcycle

Body:
Given a model hierarchy like so:

// WARNING: This is pseudo-code for giving an example!
public abstract class BaseVehicle {
    private String make;
    private String model;

    // Constructors, getters & setters down here
}

public class Motorcycle extends BaseVehicle {
    private int numCylinders;

    // Constructors, getters & setters down here
}

public class Car extends BaseVehicle {
    // ...etc.
}

And given the following payload class (that will be sent to a Spring controller):

public class Payload {
    @JsonIgnore
    @JsonProperty(value = "orgId")
    private String orgId;

    @JsonIgnore
    @JsonProperty(value = "isInitialized")
    private Boolean isInitialized;

    @JsonIgnore
    @JsonProperty(value = "vehicle")
    private BaseVehicle vehicle;

    // Constructors, getters & setters down here
}

I'm wondering if its possible to have the Spring controller (using Jackson for JSON serialization) configured to only expect a BaseVehicle instance in the Payload it receives, but to dynamically infer which BaseVehicle subclass was actually sent:

@RequestMapping(value='/payload', method=RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody MyAppResponse onPayload(@RequestBody Payload payload) {
    logger.info("Received a payload with a vehicle of type: " + payload.getVehicle().getClass().getName());
}

So that if I happen to send a Payload JSON that contains a Motorcycle as its vehicle field, then when that logger.info(...) statement fires, the code sees the vehicle is a Motorcycle (and ditto for any other BaseVehicle subclass)?

Is this possible, if so, how?

Body:
However I'd greatly prefer a solution that allows the JSON to remain as-is.

As I mentioned in my comment above, you could analyze the payload vehicle JSON object tree in order to make a little analysis trying to detect the payload element type.

@JsonDeserialize(using = BaseVehicleJsonDeserializer.class)
abstract class BaseVehicle {

    @JsonProperty
    private String make;

    @JsonProperty
    private String model;

}

@JsonDeserialize(as = Car.class)
final class Car
        extends BaseVehicle {
}

@JsonDeserialize(as = Motorcycle.class)
final class Motorcycle
        extends BaseVehicle {

    @JsonProperty
    private int numCylinders;

}

The trick here is the @JsonDeserialize annotation. The BaseVehicleJsonDeserializer can be implemented as follows:

final class BaseVehicleJsonDeserializer
        extends JsonDeserializer<BaseVehicle> {

    @Override
    public BaseVehicle deserialize(final JsonParser parser, final DeserializationContext context)
            throws IOException {
        final TreeNode treeNode = parser.readValueAsTree();
        final Class<? extends BaseVehicle> baseVehicleClass = Stream.of(treeNode)
                // Check if the tree node is ObjectNode
                .filter(tn -> tn instanceof ObjectNode)
                // And cast
                .map(tn -> (ObjectNode) tn)
                // Now "bind" the object node with if the object node can be supported by the resolver
                .flatMap(objectNode -> Stream.of(BaseVehicleTypeResolver.cachedBaseVehicleTypeResolvers).filter(resolver -> resolver.matches(objectNode)))
                // If found, just get the detected vehicle class
                .map(BaseVehicleTypeResolver::getBaseVehicleClass)
                // Take the first resolver only
                .findFirst()
                // Or throw a JSON parsing exception
                .orElseThrow(() -> new JsonParseException(parser, "Cannot parse: " + treeNode));
        // Convert the JSON tree to the resolved class instance
        final ObjectMapper objectMapper = (ObjectMapper) parser.getCodec();
        return objectMapper.treeToValue(treeNode, baseVehicleClass);
    }

    // Known strategies here
    private enum BaseVehicleTypeResolver {

        CAR_RESOLVER {
            @Override
            protected Class<? extends BaseVehicle> getBaseVehicleClass() {
                return Car.class;
            }

            @Override
            protected boolean matches(final ObjectNode objectNode) {
                return !objectNode.has("numCylinders");
            }
        },

        MOTORCYCLE_RESOLVER {
            @Override
            protected Class<? extends BaseVehicle> getBaseVehicleClass() {
                return Motorcycle.class;
            }

            @Override
            protected boolean matches(final ObjectNode objectNode) {
                return objectNode.has("numCylinders");
            }
        };

        // Enum.values() returns array clones every time it's invoked
        private static final BaseVehicleTypeResolver[] cachedBaseVehicleTypeResolvers = BaseVehicleTypeResolver.values();

        protected abstract Class<? extends BaseVehicle> getBaseVehicleClass();

        protected abstract boolean matches(ObjectNode objectNode);

    }

}

As you can see, such an approach is more or less fragile and sophisticated, but it tries to make some analysis. Now, how it can be used:

final ObjectMapper mapper = new ObjectMapper();
Stream.of(
        "{\"orgId\":\"foo\",\"isInitialized\":true,\"vehicle\":{\"make\":\"foo\",\"model\":\"foo\"}}",
        "{\"orgId\":\"bar\",\"isInitialized\":true,\"vehicle\":{\"make\":\"bar\",\"model\":\"bar\",\"numCylinders\":4}}"
)
        .map(json -> {
            try {
                return mapper.readValue(json, Payload.class);
            } catch ( final IOException ex ) {
                throw new RuntimeException(ex);
            }
        })
        .map(Payload::getVehicle)
        .map(BaseVehicle::getClass)
        .forEach(System.out::println);

Output:

class q43138817.Car

  class q43138817.Motorcycle


问:
Sound plays in PhoneGap when testing with phonegap app, but not when built with PhoneGap Build
I am working on my first android app where you hit a button and it plays a .wav sound, it works great when I run the phonegap server app to test it but then when I package it as an .APK with phonegap build and install it on my phone, it does not play the .wav sounds.</p>

```<code>$('.sound1').on('touchstart', function () {

var thissound = new Audio();
thissound.src = $(this).attr('key');
thissound.play();
});
</code>```

答:
The changes I made were instead of new audio(); I did new Media(); and after reading Playing Local Sound In Phonegap I found out it may have had something to do with the path needing to be an absolute local path, it works in the real packaged app now. I also discovered you need too use media.release(); because of the finite number of times you can play a sound.</p>

```<code>$('.sound1').on('touchstart', function () {
    var path = window.location.pathname;
    path = path.substr( path, path.length - 10 );
    var finalpath = 'file://' + path;
    var key = $(this).attr('key');
    var thissound = new Media( finalpath + key, function onSuccess() {
    // release the media resource once finished playing
    thissound.release();
    } );
    thissound.play();
});
</code>```

Body:
I am working on my first android app where you hit a button and it plays a .wav sound, it works great when I run the phonegap server app to test it but then when I package it as an .APK with phonegap build and install it on my phone, it does not play the .wav sounds.

$('.sound1').on('touchstart', function () {

var thissound = new Audio();
thissound.src = $(this).attr('key');
thissound.play();
});

Body:
The changes I made were instead of new audio(); I did new Media(); and after reading Playing Local Sound In Phonegap I found out it may have had something to do with the path needing to be an absolute local path, it works in the real packaged app now. I also discovered you need too use media.release(); because of the finite number of times you can play a sound.

$('.sound1').on('touchstart', function () {
    var path = window.location.pathname;
    path = path.substr( path, path.length - 10 );
    var finalpath = 'file://' + path;
    var key = $(this).attr('key');
    var thissound = new Media( finalpath + key, function onSuccess() {
    // release the media resource once finished playing
    thissound.release();
    } );
    thissound.play();
});


问:
Why when I run Django server it fails?
Bottom line: when I run 'python manage.py runserver 8000' I get an exception.

Steps that I did:

This is a newly installed Windows 10, so I have installed Python3 and added all parameters to Path

Run 'pip install Django' and this is what I got:

Then I wanted to run Django server and run 'python manage.py runserver 8000'. Instead of running the server, here is what I got:

I know I have missed something, but can't figure out what. What am I missing here?

Thanks!

答:
INSTALLED_APPS is a list of apps that Django should load. You still have to install the app yourself, in this case:

```<code>pip install django-paypal
</code>```

Title: Why when I run Django server it fails?

Body:
INSTALLED_APPS is a list of apps that Django should load. You still have to install the app yourself, in this case:

pip install django-paypal


问:
Update pivot tables with filters using VBA
So far I haven't used VBA with pivot tables. Now I would like to update (refresh) 2 pivot tables and set the filter for the calendar week to the last full week.

My questions / problems here are:

1) Do I actually need the .ClearAllFilters lines or can I set the filter also without it ?

2) Can I check before setting the filter if the corresponding item (e.g. the week number 13) exists in my table ? Otherwise I would try to filter for something that doesn't exist (yet).

3) Do I write the code for this the right way or is there a shorter / better way for this ? E.g. I wasn't sure if With within With would makes sense here.

My code:

```<code>Dim varLastSunday As Date, varWeekNumber As Integer

varLastSunday = Date - Weekday(Date, vbUseSystemDayOfWeek)
varWeekNumber = CLng(Format(varLastSunday, "ww"))

Application.ScreenUpdating = False
With Worksheets(4)
    .Range("StartColumns").EntireColumn.Hidden = False
    .PivotTables("PivotTable9").PivotCache.Refresh
    .PivotTables("PivotTable9").PivotFields("WEEK_NUMBER").ClearAllFilters
    .PivotTables("PivotTable9").PivotFields("WEEK_NUMBER").CurrentPage = varWeekNumber
    .PivotTables("PivotTable10").PivotCache.Refresh
    .PivotTables("PivotTable10").PivotFields("week").ClearAllFilters
    .PivotTables("PivotTable10").PivotFields("week").CurrentPage = varWeekNumber
End With
Application.ScreenUpdating = True
</code>```

答:
Because you are dealing with a PageField (i.e. a field that is in the Filters pane and that has "Select Multiple Items" unchecked) then no, I don't believe you need to clear filters. But my advice...just leave it in there...it won't hurt.

Easier simply to put some kind of error handling in your code to pick up any errors if the item doesn't exist. If you simply want to ignore any error, put an On Error Resume Next statement at the top of your block of code. Alternately you may want to advise the user that the PivotTable has not been filtered. If you clarify what you want to do, I'll post a code snippet.

Note that if both these pivottables share the same datasource, you don't need to refresh both caches, because they share a cache. If that's the case, then just get rid of the 2nd Refresh line.

Can you clarify why you are hiding the column? Does it get unhidden later? Is it likely to be unhidden whenever you run this code?

If this is all your code is doing, then I probably wouldn't bother turning off screenupdating. But again, it doesn't really matter.

Body:
So far I haven't used VBA with pivot tables. Now I would like to update (refresh) 2 pivot tables and set the filter for the calendar week to the last full week.

My questions / problems here are:

1) Do I actually need the .ClearAllFilters lines or can I set the filter also without it ?

2) Can I check before setting the filter if the corresponding item (e.g. the week number 13) exists in my table ? Otherwise I would try to filter for something that doesn't exist (yet).

3) Do I write the code for this the right way or is there a shorter / better way for this ? E.g. I wasn't sure if With within With would makes sense here.

My code:

Dim varLastSunday As Date, varWeekNumber As Integer

varLastSunday = Date - Weekday(Date, vbUseSystemDayOfWeek)
varWeekNumber = CLng(Format(varLastSunday, "ww"))

Application.ScreenUpdating = False
With Worksheets(4)
    .Range("StartColumns").EntireColumn.Hidden = False
    .PivotTables("PivotTable9").PivotCache.Refresh
    .PivotTables("PivotTable9").PivotFields("WEEK_NUMBER").ClearAllFilters
    .PivotTables("PivotTable9").PivotFields("WEEK_NUMBER").CurrentPage = varWeekNumber
    .PivotTables("PivotTable10").PivotCache.Refresh
    .PivotTables("PivotTable10").PivotFields("week").ClearAllFilters
    .PivotTables("PivotTable10").PivotFields("week").CurrentPage = varWeekNumber
End With
Application.ScreenUpdating = True


问:
Angular2 - Change template of dynamic component / reload module
I have a dynamic component which receives its template in runtime and is compiled on the fly with the compileModuleAndAllComponentsSync method of Compiler from '@angular/core'.

Here is the code I use to get the componentFactory of the runtime component (please see the Plunker for complete code, all the interesting stuff is in runtime-content.component.ts)

```<code>private createComponentFactorySync(compiler: Compiler, metadata: Component): ComponentFactory<any> {
    let decoratedCmp = Component(metadata)(RuntimeComponent);

    @NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
    class RuntimeComponentModule { }

    let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);

    return module.componentFactories.find(f => f.componentType === decoratedCmp);
}
</code>```

It all works fine and the dynamic template is working fine the first time it is compiled. For my use case however I need to be able to change the template and recompile several times. But the second time I try to compile I get the error

"Type RuntimeComponent is part of the declarations of 2 modules: RuntimeComponentModule and RuntimeComponentModule!"

This of course makes sense since it does compile into another module of the same type. So my idea has been to try to unload the previously created module but cannot find any way to do that.

Anyone have an idea to acheive what I'm trying to do? Maybe by unloading the module or perhaps in another way. I have provided a working plunker to show the problem. Press the 'compile' button which will compile the dynamic template which will work fine (pressing the 'Inc' button increases the value). Pressing compile a second time will raise the error described above and the component stops working.

Plunker

答:
Another solution would be to declare a new class for each new component and don't re-use the same RuntimeComponent each time.

```<code>protected createNewComponent(tmpl: string) {

    @Component({
        selector: `runtime-component-dynamic`,
        template: tmpl
    })
    class RuntimeComponent {
        name: string = 'Tim Jelly';
        value: number = 42;

        incValue() {
            this.value++;
        }
    }

    return RuntimeComponent;
}
</code>```

See Plunker

Body:
I have a dynamic component which receives its template in runtime and is compiled on the fly with the compileModuleAndAllComponentsSync method of Compiler from '@angular/core'.

Here is the code I use to get the componentFactory of the runtime component (please see the Plunker for complete code, all the interesting stuff is in runtime-content.component.ts)

private createComponentFactorySync(compiler: Compiler, metadata: Component): ComponentFactory<any> {
    let decoratedCmp = Component(metadata)(RuntimeComponent);

    @NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
    class RuntimeComponentModule { }

    let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);

    return module.componentFactories.find(f => f.componentType === decoratedCmp);
}

It all works fine and the dynamic template is working fine the first time it is compiled. For my use case however I need to be able to change the template and recompile several times. But the second time I try to compile I get the error

"Type RuntimeComponent is part of the declarations of 2 modules: RuntimeComponentModule and RuntimeComponentModule!"

This of course makes sense since it does compile into another module of the same type. So my idea has been to try to unload the previously created module but cannot find any way to do that.

Anyone have an idea to acheive what I'm trying to do? Maybe by unloading the module or perhaps in another way. I have provided a working plunker to show the problem. Press the 'compile' button which will compile the dynamic template which will work fine (pressing the 'Inc' button increases the value). Pressing compile a second time will raise the error described above and the component stops working.

Plunker

Body:
Another solution would be to declare a new class for each new component and don't re-use the same RuntimeComponent each time.

protected createNewComponent(tmpl: string) {

    @Component({
        selector: `runtime-component-dynamic`,
        template: tmpl
    })
    class RuntimeComponent {
        name: string = 'Tim Jelly';
        value: number = 42;

        incValue() {
            this.value++;
        }
    }

    return RuntimeComponent;
}

See Plunker


问:
Perfectly safe static/runtime numeric casts
I'm looking for a C++ feature/code, which I feel is very basic and demanded for generic programming: an ability to tell if some value of given numeric type (integer or float) is exactly representable by another given numeric type.

Long story short, I have a number of template classes, which operate on arbitrary numeric types and they have to interoperate properly. For instance, a memory stream may work with 32bit size type, but file stream has 64bit size type and passing data between them may result in overflow. Another example is geometry classes, one parametrized to work with 64bit floats, another parametrized to work with 64bit integers: passing data between them may result both in rounding errors (integer can't represent fractions) and overflow (integer has bigger value range than same-sized float).

So I wonder if should do my own implementation, or a solution is readily available (unfortunately, I can't use heavyweight libraries like Boost)?

Update: while typing my question, I decided to roll out my own implementation:

```<code>#include <limits>
#include <array>

enum class NumberClass {
    UNKNOWN, INTEGER, FLOAT
};

template <typename T> struct NumberClassResolver {
    static const NumberClass value = std::numeric_limits<T>::is_integer ? NumberClass::INTEGER : (std::numeric_limits<T>::is_iec559 ? NumberClass::FLOAT : NumberClass::UNKNOWN);
};

template <typename From, typename To> struct StaticIntegerCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)) || ((std::numeric_limits<From>::is_signed == std::numeric_limits<To>::is_signed) && (sizeof(From) <= sizeof(To)));
};
template <typename From, typename To> struct StaticFloatCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)); // NOTE Here we rely on the fact, that floats are IEEE-754 compliant and bigger ones has both bigger significand and exponent
};

template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct StaticNumberCastCheckHelper;
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static const bool value = StaticIntegerCastCheck<From, To>::value;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static const bool value = sizeof(To) > sizeof(From); // NOTE Here we rely on assumption, that sizes are POTs and significand part of a float never takes up less that half of it's size
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static const bool value = false;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static const bool value = StaticFloatCastCheck<From, To>::value;
};

template <typename From, typename To> struct StaticNumberCastCheck {
    static const bool value = StaticNumberCastCheckHelper<NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::value;
};

template <bool isFromSigned, bool isToSigned, typename From, typename To> struct RuntimeIntegerCastCheckHelper {
    static bool check(From value) {
        return (value >= std::numeric_limits<To>::min()) && (value <= std::numeric_limits<To>::max()); // NOTE Compiler must eliminate comparisson to zero for unsigned types
    }
};

template <bool isStaticallySafeCastable, NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper {
    static bool check(From value) {
        return false;
    }
};
template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper<true, FromClass, ToClass, From, To> {
    static bool check(From value) {
        return true;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        return RuntimeIntegerCastCheckHelper<std::numeric_limits<From>::is_signed, std::numeric_limits<To>::is_signed, From, To>::check(value);
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};

template <typename From, typename To> struct RuntimeNumberCastCheck {
    static bool check(From value) {
        return RuntimeNumberCastCheckHelper<StaticNumberCastCheck<From, To>::value, NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::check(value);
    }
};
</code>```

Intended usage:

```<code>StaticNumberCastCheck<uint8_t, float>::value; // can we safely cast all 8-bit unsigned integers to float?
RuntimeNumberCastCheck<float, uint8_t>::check(42); // can we safely cast 42 from float to 8-bit unsigned integer?
</code>```

It's based on some broad assumptions, so I also would be glad to hear if I'm missing something here (false positives, optimizations, etc).

答:
This information can be found in the documentation of the std::numeric_traits template, which gives you each integer or floating point type's minimum and maximum values (and whether the given numerical type is integer or floating point).

Generally, an integer type obviously can't express every floating value, so your first order of business would be to check is_exact. That'll square away comparions between integer and floating point types. Then, you can compare min() and max(), to see if the given numeric type covers the range of another numeric type.

Body:
I'm looking for a C++ feature/code, which I feel is very basic and demanded for generic programming: an ability to tell if some value of given numeric type (integer or float) is exactly representable by another given numeric type.

Long story short, I have a number of template classes, which operate on arbitrary numeric types and they have to interoperate properly. For instance, a memory stream may work with 32bit size type, but file stream has 64bit size type and passing data between them may result in overflow. Another example is geometry classes, one parametrized to work with 64bit floats, another parametrized to work with 64bit integers: passing data between them may result both in rounding errors (integer can't represent fractions) and overflow (integer has bigger value range than same-sized float).

So I wonder if should do my own implementation, or a solution is readily available (unfortunately, I can't use heavyweight libraries like Boost)?

Update: while typing my question, I decided to roll out my own implementation:

#include <limits>
#include <array>

enum class NumberClass {
    UNKNOWN, INTEGER, FLOAT
};

template <typename T> struct NumberClassResolver {
    static const NumberClass value = std::numeric_limits<T>::is_integer ? NumberClass::INTEGER : (std::numeric_limits<T>::is_iec559 ? NumberClass::FLOAT : NumberClass::UNKNOWN);
};

template <typename From, typename To> struct StaticIntegerCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)) || ((std::numeric_limits<From>::is_signed == std::numeric_limits<To>::is_signed) && (sizeof(From) <= sizeof(To)));
};
template <typename From, typename To> struct StaticFloatCastCheck {
    static const bool value = std::is_same<From, To>::value || (sizeof(From) < sizeof(To)); // NOTE Here we rely on the fact, that floats are IEEE-754 compliant and bigger ones has both bigger significand and exponent
};

template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct StaticNumberCastCheckHelper;
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static const bool value = StaticIntegerCastCheck<From, To>::value;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static const bool value = sizeof(To) > sizeof(From); // NOTE Here we rely on assumption, that sizes are POTs and significand part of a float never takes up less that half of it's size
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static const bool value = false;
};
template <typename From, typename To> struct StaticNumberCastCheckHelper<NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static const bool value = StaticFloatCastCheck<From, To>::value;
};

template <typename From, typename To> struct StaticNumberCastCheck {
    static const bool value = StaticNumberCastCheckHelper<NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::value;
};

template <bool isFromSigned, bool isToSigned, typename From, typename To> struct RuntimeIntegerCastCheckHelper {
    static bool check(From value) {
        return (value >= std::numeric_limits<To>::min()) && (value <= std::numeric_limits<To>::max()); // NOTE Compiler must eliminate comparisson to zero for unsigned types
    }
};

template <bool isStaticallySafeCastable, NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper {
    static bool check(From value) {
        return false;
    }
};
template <NumberClass FromClass, NumberClass ToClass, typename From, typename To> struct RuntimeNumberCastCheckHelper<true, FromClass, ToClass, From, To> {
    static bool check(From value) {
        return true;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        return RuntimeIntegerCastCheckHelper<std::numeric_limits<From>::is_signed, std::numeric_limits<To>::is_signed, From, To>::check(value);
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::INTEGER, NumberClass::FLOAT, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};
template <typename From, typename To> struct RuntimeNumberCastCheckHelper<false, NumberClass::FLOAT, NumberClass::INTEGER, From, To> {
    static bool check(From value) {
        To toValue = static_cast<To>(value);
        From fromValue = static_cast<From>(toValue);
        return value == fromValue;
    }
};

template <typename From, typename To> struct RuntimeNumberCastCheck {
    static bool check(From value) {
        return RuntimeNumberCastCheckHelper<StaticNumberCastCheck<From, To>::value, NumberClassResolver<From>::value, NumberClassResolver<To>::value, From, To>::check(value);
    }
};

Intended usage:

StaticNumberCastCheck<uint8_t, float>::value; // can we safely cast all 8-bit unsigned integers to float?
RuntimeNumberCastCheck<float, uint8_t>::check(42); // can we safely cast 42 from float to 8-bit unsigned integer?

It's based on some broad assumptions, so I also would be glad to hear if I'm missing something here (false positives, optimizations, etc).