问:
Angular 2 View not displaying data from Webservice
I have a Web Service which is providing some user data (this is Java backend) and I have an Angular component:

```<code>import { Component,state,style,animate,transition, trigger, keyframes,
OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/pluck';

import { IUser } from './user.interface';

@Component({
  moduleId: module.id,
  selector: 'user-cmp',
  templateUrl: 'user.component.html'
})
export class UserComponent {

  user: Observable<IUser>;

  errorMessage: string;

  constructor(private _userService: ActivatedRoute){
    this.user = _userService.data.pluck('user');
  }

}
</code>```

I am using a Resolver:

```<code>import { Resolve } from '@angular/router';
import { Observable } from 'rxjs/Observable'
import { Observer } from 'rxjs/Observer';

import { IUser } from './user.interface';
import { UserService } from './user.service';
import {Injectable} from "@angular/core";

@Injectable()
export class UsersResolver implements Resolve<IUser> {

  constructor (private _userService: UserService) {}

  resolve(): Observable<IUser>{
    return this._userService.getUser();
  }
}
</code>```

Resolver is using a service:

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

import { IUser } from './user.interface';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class UserService {
  private _userUrl = 'http://localhost:8000/rest/users';

  constructor(private _http: Http){

  }

  getUser(): Observable<IUser>{
    return this._http.get(this._userUrl)
      .map((response: Response) => {
        return <IUser> response.json();
      })
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError (error: Response){
    console.error(error);
    return Observable.throw(error.json().error || 'Server Error');
  }
}
</code>```

And finally the View:

```<code><div class="main-content" >
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8">
                <div class="card" [@carduserprofile]>
                    <div class="header">
                        <h4 class="title">Edit User Profile</h4>
                    </div>
                    <div *ngIf="user" class="content">
                        <form>
                            <div class="row">

                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Username</label>
                                        <input type="text" class="form-control" placeholder="Username" value="{{user.username }}">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Email address</label>
                                        <input type="email" class="form-control" placeholder="Email" value="{{user.password}}">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Phone</label>
                                        <input type="text" class="form-control" placeholder="Phone" value="{{user.telephone}}">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label>Type</label>
                                        <input type="text" class="form-control" disabled placeholder="User type" value="{{user.type}}">
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-info btn-fill pull-right">Update Profile</button>
                            <div class="clearfix"></div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

The module looks like this:

```<code>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { MODULE_COMPONENTS, MODULE_ROUTES } from './dashboard.routes';
import { UsersResolver } from './user/user.resolver';

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forChild(MODULE_ROUTES)
    ],
    declarations: [ MODULE_COMPONENTS ],
    providers: [ UsersResolver ]
})

export class DashboardModule{}
</code>```

And also the part of the route is like this:

```<code>{ path: 'user', component: UserComponent, resolve: {user: UsersResolver} },
</code>```

I didn't paste some useless parts of the code, like animations and etc.
My problem is, it prints the data from the webservide using the .do in the service, but it doesn't show nothing in the View. Fields are blank.

I am using *ngIf in case of blank user data from WS.

I have no idea why and also I don't know how to implement some codes to check it in the View.

Any help will be great!
Thanks in advance.

答:
The problem I see is located here:

```<code>constructor(private _userService: ActivatedRoute){
  this.user = _userService.data.pluck('user');
}
</code>```

this.user is an observable so you need to subscribe it to get the value either within the component (with this.user.subscribe(...)) or in the template using the async pipe.

Perhaps you could simply leverage the snapshot for the route:

```<code>constructor(private _userService: ActivatedRoute){
  this.user = _userService.snapshot.data['user'];
}
</code>```

This way the user would be a raw JS object and not an observable. So using the following should be better:

```<code><div *ngIf="user" class="content">
</code>```

Body:
I have a Web Service which is providing some user data (this is Java backend) and I have an Angular component:

import { Component,state,style,animate,transition, trigger, keyframes,
OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/pluck';

import { IUser } from './user.interface';

@Component({
  moduleId: module.id,
  selector: 'user-cmp',
  templateUrl: 'user.component.html'
})
export class UserComponent {

  user: Observable<IUser>;

  errorMessage: string;

  constructor(private _userService: ActivatedRoute){
    this.user = _userService.data.pluck('user');
  }

}

I am using a Resolver:

import { Resolve } from '@angular/router';
import { Observable } from 'rxjs/Observable'
import { Observer } from 'rxjs/Observer';

import { IUser } from './user.interface';
import { UserService } from './user.service';
import {Injectable} from "@angular/core";

@Injectable()
export class UsersResolver implements Resolve<IUser> {

  constructor (private _userService: UserService) {}

  resolve(): Observable<IUser>{
    return this._userService.getUser();
  }
}

Resolver is using a service:

import {Injectable} from "@angular/core";
import { Http, Response } from "@angular/http";

import { IUser } from './user.interface';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class UserService {
  private _userUrl = 'http://localhost:8000/rest/users';

  constructor(private _http: Http){

  }

  getUser(): Observable<IUser>{
    return this._http.get(this._userUrl)
      .map((response: Response) => {
        return <IUser> response.json();
      })
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError (error: Response){
    console.error(error);
    return Observable.throw(error.json().error || 'Server Error');
  }
}

And finally the View:

Edit User Profile

                        <form>

                                        Username
                                        <input type="text" class="form-control" placeholder="Username" value="{{user.username }}">

                                        Email address
                                        <input type="email" class="form-control" placeholder="Email" value="{{user.password}}">

                                        Phone
                                        <input type="text" class="form-control" placeholder="Phone" value="{{user.telephone}}">

                                        Type
                                        <input type="text" class="form-control" disabled placeholder="User type" value="{{user.type}}">

                            <button type="submit" class="btn btn-info btn-fill pull-right">Update Profile</button>

                        </form>

The module looks like this:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { MODULE_COMPONENTS, MODULE_ROUTES } from './dashboard.routes';
import { UsersResolver } from './user/user.resolver';

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forChild(MODULE_ROUTES)
    ],
    declarations: [ MODULE_COMPONENTS ],
    providers: [ UsersResolver ]
})

export class DashboardModule{}

And also the part of the route is like this:

{ path: 'user', component: UserComponent, resolve: {user: UsersResolver} },

I didn't paste some useless parts of the code, like animations and etc.
My problem is, it prints the data from the webservide using the .do in the service, but it doesn't show nothing in the View. Fields are blank.

I am using *ngIf in case of blank user data from WS.

I have no idea why and also I don't know how to implement some codes to check it in the View.

Any help will be great!
Thanks in advance.

Body:
The problem I see is located here:

constructor(private _userService: ActivatedRoute){
  this.user = _userService.data.pluck('user');
}

this.user is an observable so you need to subscribe it to get the value either within the component (with this.user.subscribe(...)) or in the template using the async pipe.

Perhaps you could simply leverage the snapshot for the route:

constructor(private _userService: ActivatedRoute){
  this.user = _userService.snapshot.data['user'];
}

This way the user would be a raw JS object and not an observable. So using the following should be better:

<div *ngIf="user" class="content">


来源: stackexchange

问:
Display problem with Update Panel in ASP.NET
I'll try to explain my problem the best I can, here goes:  I have an update panel on an ASP.NET page and a Panel server control inside it.  I have an rounded corners extender attached to the Panel server control and the extender has a solid background with a solid border.

ok....I haven't found an easy easy to position the update panel itself, so, what I end up doing is trying to position the Panel server control with CSS.  Once I do and I run the project to see the finished product, there is a big gap from where the update panel control starts and where the Panel is positioned.

What I'm wanting to know is:  What's the best way to position an UpdatePanel or regular panel so that gap that I'm talking about doesn't show up??

If anyone needs me to clarify, let me know in the comments and I'll try my best.

答:
I try to keep my UpdatePanels tightly wrapped around the actual content that is needs to have the dynamic effect.

If you only have content within that panel being updated in this fashion, I'd suggest "inverting" things so that your layout is something like:

```<code><Panel>
   <UpdatePanel>
      Pertinent Conent
   </UpdatePanel>
</Panel>
<RoundedCorderExtender />
</code>```

See if that helps resolve your spacing issues.

OwnerDisplayName: Robert Iver

ContentLicense: CC BY-SA 2.5

Body:
I try to keep my UpdatePanels tightly wrapped around the actual content that is needs to have the dynamic effect.

If you only have content within that panel being updated in this fashion, I'd suggest "inverting" things so that your layout is something like:

<Panel>
   <UpdatePanel>
      Pertinent Conent
   </UpdatePanel>
</Panel>
<RoundedCorderExtender />

See if that helps resolve your spacing issues.

OwnerDisplayName: Dillie-O


问:
If i am making a image sharing service website using the standard file upload form what images can i say it supports, other then jpg, png, gif
If i am making a image sharing service website using the standard file upload form what images can i say it supports, other then jpg, png, gif. Is there a list that shows what browsers supports what? I know that jpg png and gif are most common but what are the others. I want to be sure.</p>

答:
I would suggest converting other types of files to those 3

Examples:

jpeg (simple renaming)

bmp

tiff

pcx


问:
Catching Cascading Errors in PowerShell
I'm working with a wrapper script that calls a function which queries some databases inside specified servers and inserts metadata to a specific database on a separate server. I use the $error.count variable to determine if the script was successful or not. I anticipate some permission/extraction errors to happen and want these to be caught and ignored (no increase in the $error.count variable but having a warning written in the job log). I can confirm one permission error is happening and is being properly caught. The $error.count variable is not increased but a warning is printed from the catch showing the database that could not be accessed.

My problem occurs after the extraction/insertion function is finished running. Immediately after this function returns to the wrapper script, I have the $error.count variable print again. This time, it returns a 1 as if the error previously caught cascades into the wrapper script. As I mentioned previously, I do not want this to be included in the error count. I'm not sure how or why the $error.count is increased from this function.

Should I use a different variable to determine if the script "failed" or not? Is there some underlying reason why the $error.count would increase outside of the function that has the error while not increasing after the error is caught? Any guidance on this issue would be appreciated.

Code for reference:
Wrapper function:

```<code>$errorCount = $error.count
    Write-Warning ("$errorCount Before function")
    Extraction/Insertion_Function -serverList $serverList -insertionDB $insertionDB -ErrorAction SilentlyContinue
    $errorCount = $error.count
    Write-Warning ("$errorCount After function")
    } catch {
    Write-Error "Error caught by wrapper: $_"
    }
</code>```

Extraction/Insertion_Function:

```<code>ForEach ($db in $dbList) {
Write-Warning "$errorCount database
.
.
.
    try {
            $totalProperties = Get-ServerDBMetadata -DBConnectionString ($connStr) -DatabaseName $dbName -EA SilentlyContinue
            } catch {
                Write-Warning "Unable to extract metadata from $dbname in $server"
                }
}
</code>```

I then have the error count printing out inside the loop that extracts/inserts the metadata from each database to the insertion database, as well as in the loop for each server that contains the databases:

```<code>WARNING: 0 Before function
WARNING: 0 database
.
.
.
WARNING: 0 database
WARNING: Unable to extract metadata from *database* in *server*
WARNING: 0 database
.
.
.
WARNING: 0 database
**WARNING: 1 After function**
</code>```

The error (permission issue) is caught inside the function but cascades to my wrapper script. I want this particular error to be ignored while NOT ignoring other, more serious errors (like being unable to connect to the server I'm inserting the metadata into) so placing -EA Ignore on the driver function inside the wrapper script is out of the question.

答:
Logging the remaining errors since the last log:</p>

```<code>While ($Global:ErrorCount -lt $Error.Count) {
    $Err = $Error[$Error.Count - ++$Global:ErrorCount]
    $ErrLine = "Error at $($Err.InvocationInfo.ScriptLineNumber),$($Err.InvocationInfo.OffsetInLine): $Err"
    Write-Host $ErrLine -ForegroundColor Red        # Log this
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Catching Cascading Errors in PowerShell

Body:
I'm working with a wrapper script that calls a function which queries some databases inside specified servers and inserts metadata to a specific database on a separate server. I use the $error.count variable to determine if the script was successful or not. I anticipate some permission/extraction errors to happen and want these to be caught and ignored (no increase in the $error.count variable but having a warning written in the job log). I can confirm one permission error is happening and is being properly caught. The $error.count variable is not increased but a warning is printed from the catch showing the database that could not be accessed.

My problem occurs after the extraction/insertion function is finished running. Immediately after this function returns to the wrapper script, I have the $error.count variable print again. This time, it returns a 1 as if the error previously caught cascades into the wrapper script. As I mentioned previously, I do not want this to be included in the error count. I'm not sure how or why the $error.count is increased from this function.

Should I use a different variable to determine if the script "failed" or not? Is there some underlying reason why the $error.count would increase outside of the function that has the error while not increasing after the error is caught? Any guidance on this issue would be appreciated.

Code for reference:
Wrapper function:

$errorCount = $error.count
    Write-Warning ("$errorCount Before function")
    Extraction/Insertion_Function -serverList $serverList -insertionDB $insertionDB -ErrorAction SilentlyContinue
    $errorCount = $error.count
    Write-Warning ("$errorCount After function")
    } catch {
    Write-Error "Error caught by wrapper: $_"
    }

Extraction/Insertion_Function:

ForEach ($db in $dbList) {
Write-Warning "$errorCount database
.
.
.
    try {
            $totalProperties = Get-ServerDBMetadata -DBConnectionString ($connStr) -DatabaseName $dbName -EA SilentlyContinue
            } catch {
                Write-Warning "Unable to extract metadata from $dbname in $server"
                }
}

I then have the error count printing out inside the loop that extracts/inserts the metadata from each database to the insertion database, as well as in the loop for each server that contains the databases:

WARNING: 0 Before function
WARNING: 0 database
.
.
.
WARNING: 0 database
WARNING: Unable to extract metadata from *database* in *server*
WARNING: 0 database
.
.
.
WARNING: 0 database
**WARNING: 1 After function**

The error (permission issue) is caught inside the function but cascades to my wrapper script. I want this particular error to be ignored while NOT ignoring other, more serious errors (like being unable to connect to the server I'm inserting the metadata into) so placing -EA Ignore on the driver function inside the wrapper script is out of the question.

Body:
Logging the remaining errors since the last log:

While ($Global:ErrorCount -lt $Error.Count) {
    $Err = $Error[$Error.Count - ++$Global:ErrorCount]
    $ErrLine = "Error at $($Err.InvocationInfo.ScriptLineNumber),$($Err.InvocationInfo.OffsetInLine): $Err"
    Write-Host $ErrLine -ForegroundColor Red        # Log this
}


问:
.NET Signed XML Prefix
Is there a way to set the prefix on the Signature of a Signed XML Document (SignedXml class in .Net)?

So instead of:

```<code><Signature xmlns="http://www.w3.org/2000/09/xmldsig#>
...
</Signature>
</code>```

I could have the following:

```<code><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#>
...
</ds:Signature>
</code>```

答:
It can be done, but it's necessary to modify the SignedXml class to add the prefix before getting the digest value of the SignedInfo node.

The ComputeSignature method will be modify to add the prefix parameter

```<code>public void ComputeSignature(string prefix){...}
</code>```

When this method is called it calculates the Signature Value by digesting the value of the SignedInfo node, if you get this value without the "ds" prefix and then add the prefix you will get an invalid signature, so you will have to add the prefix BEFORE getting the digest value of the signedinfo node.

This digest value is generated in the method GetC14NDigest, so this method will be modify to add the prefix parameter and to add the prefix BEFORE getting the digest value

```<code>private byte[] GetC14NDigest(HashAlgorithm hash, string prefix)
{
    XmlDocument document = new XmlDocument();
    document.PreserveWhitespace = false;
    XmlElement e = this.SignedInfo.GetXml(); //get the signedinfo nodes
    document.AppendChild(document.ImportNode(e, true));
    Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;
    SetPrefix(prefix, document.DocumentElement); /*Set the prefix before getting the HASH*/
    canonicalizationMethodObject.LoadInput(document);
    return canonicalizationMethodObject.GetDigestedOutput(hash);
}
</code>```

Ok, so now you have the Signature Value of the SignedInfo nodes WITH the "ds" prefix, that being said you still DON'T have the xml with the prefix yet, so if you just call the GetXml method you will get the xml without the prefix and of course because the signature value was calculated considering the ds prefix you will have an invalid signature.
To avoid that and get the xml structure with the prefix you have to modify the GetXml method, add the prefix parameter, and call the SetPrefix method wich will add the "ds" prefix to all the nodes in the Signature Xml

```<code>public XmlElement GetXml(string prefix)
{
    XmlElement e = this.GetXml();
    SetPrefix(prefix, e); //return the xml structure with the prefix
    return e;
}
</code>```

I'll leave here the class with those modifications

CUSTOM CLASS

```<code>internal sealed class CustomSignedXml : SignedXml
{
    XmlElement obj = null;
    public CustomSignedXml (XmlDocument xml)
        : base(xml)
    {
    }

    public CustomSignedXml (XmlElement xmlElement)
        : base(xmlElement)
    {

    }

    public XmlElement GetXml(string prefix)
    {
        XmlElement e = this.GetXml();
        SetPrefix(prefix, e);
        return e;
    }

    public void ComputeSignature(string prefix)
    {
        this.BuildDigestedReferences();
        AsymmetricAlgorithm signingKey = this.SigningKey;
        if (signingKey == null)
        {
            throw new CryptographicException("Cryptography_Xml_LoadKeyFailed");
        }
        if (this.SignedInfo.SignatureMethod == null)
        {
            if (!(signingKey is DSA))
            {
                if (!(signingKey is RSA))
                {
                    throw new CryptographicException("Cryptography_Xml_CreatedKeyFailed");
                }
                if (this.SignedInfo.SignatureMethod == null)
                {
                    this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
                }
            }
            else
            {
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
            }
        }
        SignatureDescription description = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription;
        if (description == null)
        {
            throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated");
        }
        HashAlgorithm hash = description.CreateDigest();
        if (hash == null)
        {
            throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed");
        }
        this.GetC14NDigest(hash, prefix);
        this.m_signature.SignatureValue = description.CreateFormatter(signingKey).CreateSignature(hash);
    }

    private byte[] GetC14NDigest(HashAlgorithm hash, string prefix)
    {

        XmlDocument document = new XmlDocument();
        document.PreserveWhitespace = false;
        XmlElement e = this.SignedInfo.GetXml();
        document.AppendChild(document.ImportNode(e, true));

        Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;
        SetPrefix(prefix, document.DocumentElement); //Set the prefix before getting the HASH
        canonicalizationMethodObject.LoadInput(document);
        return canonicalizationMethodObject.GetDigestedOutput(hash);
    }

    private void BuildDigestedReferences()
    {
        Type t = typeof(SignedXml);
        MethodInfo m = t.GetMethod("BuildDigestedReferences", BindingFlags.NonPublic | BindingFlags.Instance);
        m.Invoke(this, new object[] { });
    }

    private void SetPrefix(string prefix, XmlNode node)
    {
       foreach (XmlNode n in node.ChildNodes)
          SetPrefix(prefix, n);
       node.Prefix = prefix;
    }
}
</code>```

And the way to use it

```<code>CustomSignedXml signedXml = new CustomSignedXml();
.
.//your code
.

//compute the signature with the "ds" prefix

signedXml.ComputeSignature("ds");

//get the xml of the signature with the "ds" prefix

XmlElement xmlDigitalSignature = signedXml.GetXml("ds");
</code>```

OwnerDisplayName: mjmcinto

Title: .NET Signed XML Prefix

Body:
Is there a way to set the prefix on the Signature of a Signed XML Document (SignedXml class in .Net)?

So instead of:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#>
...
</Signature>

I could have the following:

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#>
...
</ds:Signature>

Body:
It can be done, but it's necessary to modify the SignedXml class to add the prefix before getting the digest value of the SignedInfo node.

The ComputeSignature method will be modify to add the prefix parameter

public void ComputeSignature(string prefix){...}

When this method is called it calculates the Signature Value by digesting the value of the SignedInfo node, if you get this value without the "ds" prefix and then add the prefix you will get an invalid signature, so you will have to add the prefix BEFORE getting the digest value of the signedinfo node.

This digest value is generated in the method GetC14NDigest, so this method will be modify to add the prefix parameter and to add the prefix BEFORE getting the digest value

private byte[] GetC14NDigest(HashAlgorithm hash, string prefix)
{
    XmlDocument document = new XmlDocument();
    document.PreserveWhitespace = false;
    XmlElement e = this.SignedInfo.GetXml(); //get the signedinfo nodes
    document.AppendChild(document.ImportNode(e, true));
    Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;
    SetPrefix(prefix, document.DocumentElement); /*Set the prefix before getting the HASH*/
    canonicalizationMethodObject.LoadInput(document);
    return canonicalizationMethodObject.GetDigestedOutput(hash);
}

Ok, so now you have the Signature Value of the SignedInfo nodes WITH the "ds" prefix, that being said you still DON'T have the xml with the prefix yet, so if you just call the GetXml method you will get the xml without the prefix and of course because the signature value was calculated considering the ds prefix you will have an invalid signature.
To avoid that and get the xml structure with the prefix you have to modify the GetXml method, add the prefix parameter, and call the SetPrefix method wich will add the "ds" prefix to all the nodes in the Signature Xml

public XmlElement GetXml(string prefix)
{
    XmlElement e = this.GetXml();
    SetPrefix(prefix, e); //return the xml structure with the prefix
    return e;
}

I'll leave here the class with those modifications

CUSTOM CLASS

internal sealed class CustomSignedXml : SignedXml
{
    XmlElement obj = null;
    public CustomSignedXml (XmlDocument xml)
        : base(xml)
    {
    }

    public CustomSignedXml (XmlElement xmlElement)
        : base(xmlElement)
    {

    }

    public XmlElement GetXml(string prefix)
    {
        XmlElement e = this.GetXml();
        SetPrefix(prefix, e);
        return e;
    }

    public void ComputeSignature(string prefix)
    {
        this.BuildDigestedReferences();
        AsymmetricAlgorithm signingKey = this.SigningKey;
        if (signingKey == null)
        {
            throw new CryptographicException("Cryptography_Xml_LoadKeyFailed");
        }
        if (this.SignedInfo.SignatureMethod == null)
        {
            if (!(signingKey is DSA))
            {
                if (!(signingKey is RSA))
                {
                    throw new CryptographicException("Cryptography_Xml_CreatedKeyFailed");
                }
                if (this.SignedInfo.SignatureMethod == null)
                {
                    this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
                }
            }
            else
            {
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
            }
        }
        SignatureDescription description = CryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription;
        if (description == null)
        {
            throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated");
        }
        HashAlgorithm hash = description.CreateDigest();
        if (hash == null)
        {
            throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed");
        }
        this.GetC14NDigest(hash, prefix);
        this.m_signature.SignatureValue = description.CreateFormatter(signingKey).CreateSignature(hash);
    }

    private byte[] GetC14NDigest(HashAlgorithm hash, string prefix)
    {

        XmlDocument document = new XmlDocument();
        document.PreserveWhitespace = false;
        XmlElement e = this.SignedInfo.GetXml();
        document.AppendChild(document.ImportNode(e, true));

        Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;
        SetPrefix(prefix, document.DocumentElement); //Set the prefix before getting the HASH
        canonicalizationMethodObject.LoadInput(document);
        return canonicalizationMethodObject.GetDigestedOutput(hash);
    }

    private void BuildDigestedReferences()
    {
        Type t = typeof(SignedXml);
        MethodInfo m = t.GetMethod("BuildDigestedReferences", BindingFlags.NonPublic | BindingFlags.Instance);
        m.Invoke(this, new object[] { });
    }

    private void SetPrefix(string prefix, XmlNode node)
    {
       foreach (XmlNode n in node.ChildNodes)
          SetPrefix(prefix, n);
       node.Prefix = prefix;
    }
}

And the way to use it

CustomSignedXml signedXml = new CustomSignedXml();
.
.//your code
.

//compute the signature with the "ds" prefix

signedXml.ComputeSignature("ds");

//get the xml of the signature with the "ds" prefix

XmlElement xmlDigitalSignature = signedXml.GetXml("ds");


问:
How do I alert the user that multiple fields are left blank in an HTML form after clicking submit?
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!

Here is the HTML code:

```<code><form id="contactform" action="">
    <label> Name
        <input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />
    </label>
    <label> Last Name
        <input name="lastname" type="text" id="lastname" maxlength="150" />
    </label>
    <label> Address
        <input name="address" type="text" id="address" maxlength="200" />
    </label>
    <label> Postcode
        <input name="postcode" type="text" id="postcode" maxlength="50" />
    </label>
    <label> City
        <input name="city" type="text" id="city" maxlength="100" />
    </label>
</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />
</code>```

Here is the javascript code:

```<code>function validate() {

    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var address = document.getElementById('address');
    var postcode = document.getElementById('postcode');
    var city = document.getElementById('city');

    if (firstname.value == "") {
        alert("Make sure the first name field is filled");
        return false;
    }

    if (lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
    }
    if (address.value == "") {
        alert("Make sure the address field is filled");
        return false;
    }
    if (postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
    }
    if (city.value == "") {
        alert("Make sure the city field is filled");
        return false;
    }
    return true;
}
</code>```

答:
You can use HTML validation, i.e. the [required] attribute:

<form id="contactform" action="">
 Name
<input required name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus"/>

 Last Name
<input required name="lastname" type="text" id="lastname" maxlength="150">

 Address
<input required name="address" type="text" id="address" maxlength="200">

 Postcode
<input required name="postcode" type="text" id="postcode" maxlength="50">

 City
<input required name="city" type="text" id="city" maxlength="100">

<input type="submit" value="Submit">
<input type="reset" value="Clear">
</form>```

Body:
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!

Here is the HTML code:

<form id="contactform" action="">
     Name
        <input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />

     Last Name
        <input name="lastname" type="text" id="lastname" maxlength="150" />

     Address
        <input name="address" type="text" id="address" maxlength="200" />

     Postcode
        <input name="postcode" type="text" id="postcode" maxlength="50" />

     City
        <input name="city" type="text" id="city" maxlength="100" />

</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />

Here is the javascript code:

function validate() {

    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var address = document.getElementById('address');
    var postcode = document.getElementById('postcode');
    var city = document.getElementById('city');

    if (firstname.value == "") {
        alert("Make sure the first name field is filled");
        return false;
    }

    if (lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
    }
    if (address.value == "") {
        alert("Make sure the address field is filled");
        return false;
    }
    if (postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
    }
    if (city.value == "") {
        alert("Make sure the city field is filled");
        return false;
    }
    return true;
}

Body:
You can use HTML validation, i.e. the [required] attribute:

<form id="contactform" action="">
<label> Name
<input required name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus"/>
</label>
<label> Last Name
<input required name="lastname" type="text" id="lastname" maxlength="150">
</label>
<label> Address
<input required name="address" type="text" id="address" maxlength="200">
</label>
<label> Postcode
<input required name="postcode" type="text" id="postcode" maxlength="50">
</label>
<label> City
<input required name="city" type="text" id="city" maxlength="100">
</label>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</form>


问:
python substring (slicing) compare not always working
```<code>`list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
    "Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
    "Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
    "Tampa Bay","Tennessee","Washington"]
a = "New Orleans at Oakland"
k = a.find("at")
print (k)
for n in range(0,31):
#    b = list1[n]
#    print(b[0:k-1]+"  "+a[0:k-1])
    idx = a.find(list1[n], 0, k-1)
    if idx > 0:
        print(n)
        break
print ("awa team at index" + str(n+1))
for n in range(0,31):
    idx = a.find(list1[n], k+2, len(a))
    if idx > 0:
       print(n)
       break
print ("hom team at index" + str(n+1))`
</code>```

I just started python 2 days ago and I cannot get this to work completely. The program finds the team in the second for loop correctly, but doesn't find the team in the first for loop. I put in the statements that are commented out to see if the strings were somehow truncated, but they are correct. Can anyone tell me what is wrong here?

答:
There's no need to brute force the search. Python has methods that accomplish what you need.</p>

```<code>list1 = ["Arizona", "Atlanta", "Baltimore", "Buffalo", "Carolina", "Chicago",
"Cincinnati", "Cleveland", "Dallas", "Denver", "Detroit", "Green Bay", "Houston",
"Indianapolis", "Jacksonville", "Kansas City", "L.A. Chargers", "L.A. Rams",
"Miami", "Minnesota", "New England", "New Orleans", "NY Giants", "NY Jets",
"Oakland", "Philadelphia", "Pittsburgh", "San Francisco", "Seattle",
"Tampa Bay", "Tennessee", "Washington"]

a = "New Orleans at Oakland"

# Create a list of the teams involved in the game
teams = a.split(" at ")

# Iterate through the teams involved in the game
for team in teams:
    # The index() method returns the lowest index in list that obj appears
    index = list1.index(team)
    # If the the team was found then index is valid
    if index:
        print(index)
        print(list1[index])
</code>```

Body:
`list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
    "Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
    "Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
    "Tampa Bay","Tennessee","Washington"]
a = "New Orleans at Oakland"
k = a.find("at")
print (k)
for n in range(0,31):
#    b = list1[n]
#    print(b[0:k-1]+"  "+a[0:k-1])
    idx = a.find(list1[n], 0, k-1)
    if idx > 0:
        print(n)
        break
print ("awa team at index" + str(n+1))
for n in range(0,31):
    idx = a.find(list1[n], k+2, len(a))
    if idx > 0:
       print(n)
       break
print ("hom team at index" + str(n+1))`

I just started python 2 days ago and I cannot get this to work completely. The program finds the team in the second for loop correctly, but doesn't find the team in the first for loop. I put in the statements that are commented out to see if the strings were somehow truncated, but they are correct. Can anyone tell me what is wrong here?

Body:
There's no need to brute force the search. Python has methods that accomplish what you need.

list1 = ["Arizona", "Atlanta", "Baltimore", "Buffalo", "Carolina", "Chicago",
"Cincinnati", "Cleveland", "Dallas", "Denver", "Detroit", "Green Bay", "Houston",
"Indianapolis", "Jacksonville", "Kansas City", "L.A. Chargers", "L.A. Rams",
"Miami", "Minnesota", "New England", "New Orleans", "NY Giants", "NY Jets",
"Oakland", "Philadelphia", "Pittsburgh", "San Francisco", "Seattle",
"Tampa Bay", "Tennessee", "Washington"]

a = "New Orleans at Oakland"

# Create a list of the teams involved in the game
teams = a.split(" at ")

# Iterate through the teams involved in the game
for team in teams:
    # The index() method returns the lowest index in list that obj appears
    index = list1.index(team)
    # If the the team was found then index is valid
    if index:
        print(index)
        print(list1[index])


问:
How to fetch data from response._body in proper way?
So starting first my nodejs server sends this as a response

"["name1","name2","name3"]"

but my angular 2 code for service is

```<code>return this.http.get(this.config.apiUrl + '/folder').map((response:Response)=> {
       response.json();
     console.log(response); }
</code>```

How do I fetch the array?

If I use response._body there will be an error in npm start stating "._body undefined", so I make it as a comment then after npm start I reverse back, I know it is not proper way. Here is the console.log of above service code

```<code> Response
 headers: Headers
 ok:true
 status:200
 statusText:"OK"
 type:2
 url:"http://localhost:4000/folder"
 _body:"["name1","name2","name3"]"
 __proto__:Body
</code>```

The main problem is to fetch in component in an array

Here, is the code I am trying

```<code>this.photoService.getAllfolder().subscribe(
data => {
  console.log(data);
},
error => {
      console.log(error);
});
</code>```

答:
You are missing a return statement in your mapping. Also if you then want to have the console log, you need to change the order. Your code should therefore look like this:</p>

```<code>return this.http.get(this.config.apiUrl + '/folder')
   .map((response:Response)=> {
     console.log(response);
     return response.json(); // return
   }
</code>```

Body:
So starting first my nodejs server sends this as a response

"["name1","name2","name3"]"

but my angular 2 code for service is

return this.http.get(this.config.apiUrl + '/folder').map((response:Response)=> {
       response.json();
     console.log(response); }

How do I fetch the array?

If I use response._body there will be an error in npm start stating "._body undefined", so I make it as a comment then after npm start I reverse back, I know it is not proper way. Here is the console.log of above service code

 Response
 headers: Headers
 ok:true
 status:200
 statusText:"OK"
 type:2
 url:"http://localhost:4000/folder"
 _body:"["name1","name2","name3"]"
 __proto__:Body

The main problem is to fetch in component in an array

Here, is the code I am trying

this.photoService.getAllfolder().subscribe(
data => {
  console.log(data);
},
error => {
      console.log(error);
});

Body:
You are missing a return statement in your mapping. Also if you then want to have the console log, you need to change the order. Your code should therefore look like this:

return this.http.get(this.config.apiUrl + '/folder')
   .map((response:Response)=> {
     console.log(response);
     return response.json(); // return
   }


问:
Android Shared Preference check value
I'm working on android application that have 2 activities A and B . I have a button in B Activity with event that save the current time of android device, the time save in Shared Preferences:

```<code>long TimeMillis = date.getTime();
editor = sharedpreferences.edit();
editor.putString("TimeMillis", String.valueOf(TimeMillis));
</code>```

I need to check the value of the previous Shared Preferences in A Activity

Note: the Date save on B then check it in A . A come before B.

答:
According to doc you can set a default value, in getString() method, which will be returned if you haven't set anything before.

You can set this value as you wish, then check it in order to understand if your value has been set.

```<code>final String NO_VALUE = "NO_VALUE";

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String mSharedDate = prefs.getString("TimeMillis", NO_VALUE);

if(mSharedDate.equals(NO_VALUE)){
    // No value handling
    return;
}

// do something
</code>```

ContentLicense: CC BY-SA 4.0

Title: Android Shared Preference check value

Body:
I'm working on android application that have 2 activities A and B . I have a button in B Activity with event that save the current time of android device, the time save in Shared Preferences:

long TimeMillis = date.getTime();
editor = sharedpreferences.edit();
editor.putString("TimeMillis", String.valueOf(TimeMillis));

I need to check the value of the previous Shared Preferences in A Activity

Note: the Date save on B then check it in A . A come before B.

Body:
According to doc you can set a default value, in getString() method, which will be returned if you haven't set anything before.

You can set this value as you wish, then check it in order to understand if your value has been set.

final String NO_VALUE = "NO_VALUE";

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String mSharedDate = prefs.getString("TimeMillis", NO_VALUE);

if(mSharedDate.equals(NO_VALUE)){
    // No value handling
    return;
}

// do something


问:
Conditional IF statement inside this.state of the Constructor Reactjs
Im trying to render a conditional if inside a state variable of my constructor.

My original code is like this and it works

```<code>constructor(props, context){
  super(props, context);
}
this.state={
  ... // the rest of my state
  columns: [{
    render:
      row => (
        row.row.exported === 0 ?

        <span className={styles.centered} >
        {
          row.value === true ? <img src={checkedImage} />
              : <img src={uncheckedImage} />
        }
      </span>: ""
    ),
    maxWidth: 60,
    hideFilter: true,
    style: {textAlign:"center"},
  }]
}
</code>```

And i want to do something like this:

```<code>    constructor(props, context){
      super(props, context);

    this.state={
      ... // the rest of my state
      columns:
        render:
          if(this.state.profile.role == 'dba' || this.state.profile.role == 'both'){
            row => (
            row.row.exported === 0 ?
            <span className={styles.centered} >
              {
                row.value === true ? <img src={checkedImage} />
                    : <img src={uncheckedImage} />
              }
            </span>: ""
          }
        ),
        maxWidth: 60,
        hideFilter: true,
        style: {textAlign:"center"},
      }]
    }
  }
</code>```

In my render method im using react-table so it look like this:

Render Method

```<code>render(){
 return(
  <ReactTable columns={this.state.columns} />
 )
}
</code>```

Is it possible or is there any work around to achieve this?

答:
Pull the if statement inside of your callback and give your callback a body. Then you can use the appropriate conditionals.  A quick fix would have a form that looked something a little like this:

```<code>render: (row) => {
  if(this.state.profile.role == 'dba' || this.state.profile.role == 'both'){
    return (
    row.row.exported === 0 ?
    <span className={styles.centered} >
      {
        row.value === true ? <img src={checkedImage} />
            : <img src={uncheckedImage} />
      }
    </span>: ""
  }
),
</code>```

}
Since you have a function body you can use either the ternary operator or if statements for control flow.

Personally, this looks a little messy and the whole definition is deeply nested in an object literal so Id define a function somewhere outside:

```<code>const rowRender = (row) => { ...the code above... }

columns:
        render: (row) => rowRender(row),
        maxWidth: 60,
        hideFilter: true,
        style: {textAlign:"center"},
      }]
</code>```

Body:
Im trying to render a conditional if inside a state variable of my constructor.

My original code is like this and it works

constructor(props, context){
  super(props, context);
}
this.state={
  ... // the rest of my state
  columns: [{
    render:
      row => (
        row.row.exported === 0 ?

        {
          row.value === true ?
              :
        }
      : ""
    ),
    maxWidth: 60,
    hideFilter: true,
    style: {textAlign:"center"},
  }]
}

And i want to do something like this:

    constructor(props, context){
      super(props, context);

    this.state={
      ... // the rest of my state
      columns:
        render:
          if(this.state.profile.role == 'dba' || this.state.profile.role == 'both'){
            row => (
            row.row.exported === 0 ?

              {
                row.value === true ?
                    :
              }
            : ""
          }
        ),
        maxWidth: 60,
        hideFilter: true,
        style: {textAlign:"center"},
      }]
    }
  }

In my render method im using react-table so it look like this:

Render Method

render(){
 return(
  <ReactTable columns={this.state.columns} />
 )
}

Is it possible or is there any work around to achieve this?

Body:
Pull the if statement inside of your callback and give your callback a body. Then you can use the appropriate conditionals.  A quick fix would have a form that looked something a little like this:

render: (row) => {
  if(this.state.profile.role == 'dba' || this.state.profile.role == 'both'){
    return (
    row.row.exported === 0 ?
    <span className={styles.centered} >
      {
        row.value === true ? <img src={checkedImage} />
            : <img src={uncheckedImage} />
      }
    </span>: ""
  }
),

}
Since you have a function body you can use either the ternary operator or if statements for control flow.

Personally, this looks a little messy and the whole definition is deeply nested in an object literal so Id define a function somewhere outside:

const rowRender = (row) => { ...the code above... }

columns:
        render: (row) => rowRender(row),
        maxWidth: 60,
        hideFilter: true,
        style: {textAlign:"center"},
      }]


问:
Use Eval with vice versa mode in VBScript
Normal usage of Eval function is like:

```<code>ValueName2 = Eval("Value" + CStr(CurrentValue) + "Name2")
</code>```

This can return Value[n]Name2 according to CurrentValue.

Then how I tried to use Eval in vice versa mode:

```<code>Eval("Value" + CStr(CurrentValue) + "Name2") = ValueName2
</code>```

So this can always return ValueName2 no matter if original variable (Eg:Value1Name2,,Value100Name2.....).

But, this time when I check values of Value1Name2, it is empty and VB Script also return an error:

Type mismatch: "Eval"

Then how can I use Eval in vice versa mode?

Thanks in Advance.

答:
Eval will always return a value, not a variable reference, so, you can not use Eval to solve the problem.

You can use

```<code>Call Execute( "Value" + CStr(CurrentValue) + "Name2 = ValueName2" )
</code>```

But it is easier and faster to use an array or a dictionary.

Body:
Normal usage of Eval function is like:

ValueName2 = Eval("Value" + CStr(CurrentValue) + "Name2")

This can return Value[n]Name2 according to CurrentValue.

Then how I tried to use Eval in vice versa mode:

Eval("Value" + CStr(CurrentValue) + "Name2") = ValueName2

So this can always return ValueName2 no matter if original variable (Eg:Value1Name2,,Value100Name2.....).

But, this time when I check values of Value1Name2, it is empty and VB Script also return an error:

Type mismatch: "Eval"

Then how can I use Eval in vice versa mode?

Thanks in Advance.

Body:
Eval will always return a value, not a variable reference, so, you can not use Eval to solve the problem.

You can use

Call Execute( "Value" + CStr(CurrentValue) + "Name2 = ValueName2" )

But it is easier and faster to use an array or a dictionary.


问:
How to fix this N+1. Rails. Also, why are N+1 queries so bad?
So I just want to make sure that this is an N+1 query and I want to know how to fix it. ON a high level, where am I losing the most time in an N+1 query? Is it the request over the network to the database url that is costing me the most time? Or is the actual query IN the database that is costing me the most time?

Say we have this:

```<code>products = Product.where(user_id: user.id)  # This is one network database query right?

products.select { |product| !product.restrictions.map(&:state).includes?(user.address.state) }
# restriction is another table. We're trying to filter out products that are restricted to the user's state.
</code>```

Questions

So technically, is this an N+1 query? It is because we're making 1 query to get all products for the user AND another to filter out the restricted products by comparing the product's restrictions by state to the user's state.

So, on a high level, what can I do? Can I eager load the restrictions table in my first query? Or should I just make one trip and do everything in the first query? Are these my two options?

Update

So assume I did Product.includes(:restrictions).where(user_id: user.id), this is all stil oone query right?

Is this also one query if this was all in one method:

```<code>products = Product.where(user_id: user.id)`
products.includes(:restrictions).select do |product|
!product.restrictions.map(&:state_name).include?("CT")
end
</code>```

答:
There are some great articles like this one that go into this in more detail, but the general concept is that any time you're iterating through a list and making queries based on that list then you're performing an N+1 query. You're losing the most time over the network, but also each query comes with a set amount of overhead.

Question 1. Yes this is an N+1 query.

You're making an N+1 query when you return each product and then for each product you return whether it is restricted or not. You can typically recognize them because you are iterating through queries like you do above with products.select { |product| }. This could potentially product hundreds of queries when you could just batch them instead.

In your example, you are returning an array of products and making another request to filter out the list.

Your code currently produces SQL similar to:

```<code>SELECT * FROM products WHERE user_id=1;
</code>```

and then performs another filter where you're checking product restrictions which produces these queries:

```<code>SELECT restrictions FROM products WHERE product_id=1, user_id=1, state="x";
SELECT restrictions FROM products WHERE product_id=2, user_id=1, state="x";
SELECT restrictions FROM products WHERE product_id=3, user_id=1, state="x";
...
</code>```

Question 2. You should just do this all in one query and batch the results. This is psuedocode, but you get the idea:

```<code>products = Product.where(user_id: @user).select(restrictions: state)`
</code>```

Response to your update: That will still create two queries. The method just runs from the top to bottom. The only way to make it only create one query is to use and chain the provided Rails ORM methods which create proxy objects and then create a single query. Read more here: https://stackoverflow.com/a/10747692/1336988

Body:
So I just want to make sure that this is an N+1 query and I want to know how to fix it. ON a high level, where am I losing the most time in an N+1 query? Is it the request over the network to the database url that is costing me the most time? Or is the actual query IN the database that is costing me the most time?

Say we have this:

products = Product.where(user_id: user.id)  # This is one network database query right?

products.select { |product| !product.restrictions.map(&:state).includes?(user.address.state) }
# restriction is another table. We're trying to filter out products that are restricted to the user's state.

Questions

So technically, is this an N+1 query? It is because we're making 1 query to get all products for the user AND another to filter out the restricted products by comparing the product's restrictions by state to the user's state.

So, on a high level, what can I do? Can I eager load the restrictions table in my first query? Or should I just make one trip and do everything in the first query? Are these my two options?

Update

So assume I did Product.includes(:restrictions).where(user_id: user.id), this is all stil oone query right?

Is this also one query if this was all in one method:

products = Product.where(user_id: user.id)`
products.includes(:restrictions).select do |product|
!product.restrictions.map(&:state_name).include?("CT")
end

Body:
There are some great articles like this one that go into this in more detail, but the general concept is that any time you're iterating through a list and making queries based on that list then you're performing an N+1 query. You're losing the most time over the network, but also each query comes with a set amount of overhead.

Question 1. Yes this is an N+1 query.

You're making an N+1 query when you return each product and then for each product you return whether it is restricted or not. You can typically recognize them because you are iterating through queries like you do above with products.select { |product| }. This could potentially product hundreds of queries when you could just batch them instead.

In your example, you are returning an array of products and making another request to filter out the list.

Your code currently produces SQL similar to:

SELECT * FROM products WHERE user_id=1;

and then performs another filter where you're checking product restrictions which produces these queries:

SELECT restrictions FROM products WHERE product_id=1, user_id=1, state="x";
SELECT restrictions FROM products WHERE product_id=2, user_id=1, state="x";
SELECT restrictions FROM products WHERE product_id=3, user_id=1, state="x";
...

Question 2. You should just do this all in one query and batch the results. This is psuedocode, but you get the idea:

products = Product.where(user_id: @user).select(restrictions: state)`

Response to your update: That will still create two queries. The method just runs from the top to bottom. The only way to make it only create one query is to use and chain the provided Rails ORM methods which create proxy objects and then create a single query. Read more here: https://stackoverflow.com/a/10747692/1336988


问:
Generic Interface Casting
I am working on creating a very simplistic OS-like framework (similar to Android) built off of the JVM for educational purposes.

Mostly, I just wanted to learn about ClassLoaders and the endless possibilities of them.  I have the majority of the infrastructure created, but I am questioning whether there may be a better way of handling the generics of the situation that I am in.

A little description of the way my framework operates:

"App" implementations in my framework have the ability to attach extensions, i.e. plugins.  The extension system works by requiring extensions to implement an interface that the App code is aware of, but the App code has no knowledge of the extensions at all, it just knows of the interface.

This is where my use of ClassLoaders comes in.  I use the URLClassLoader to load in all .class files in the $ApplicationRoot/ext directory recursively and test to see if the interface isAssignable( from the loaded classes).

This all works fine and dandy except when I try to further generalize it.  What I want to do is have SDK code that will handle all of this, so that an app would just need to make sure the proper extensions are in the proper folder.

So here is my code right now:

```<code>Set<String> classFiles = new HashSet<>();
gatherAllClassFiles("", classFiles, srcRoot);
gatherAllClassFiles("", classFiles, extRoot);

URLClassLoader ucl = new URLClassLoader(new URL[]{extRoot.toURI().toURL(), srcRoot.toURI().toURL()});

for(String className:classFiles){

    Class<?> clazz = ucl.loadClass(className);
    for(String extension: extensionInterfaceNames){
        Class<?> iface = Class.forName(extension);
        if(iface.isAssignableFrom(clazz)){
            extensions.putIfAbsent(iface, new ArrayList<>());
            extensions.get(iface).add(iface.cast(clazz.newInstance()));
        }
    }
}
</code>```

extensions is declared as follows:

```<code>private Map<Class<?>, List<?>> extensions;
</code>```

I am aware that this implementation of generics is not in the least bit ideal, in fact, in its current state, it won't compile, but I really wanted to stay away from using List<Object>.

What I really would like to be able to do is something like this:

```<code>private Map<Class<?>, List<iface>> extensions;
</code>```

given that iface is the name of the a Class variable holding the class information and not the actual Type, this will not work.

My gut feeling is that I will have to suck it up and use List<Object> and unsafely cast it out, but I was hoping that someone else might have a better suggestion.

答:
A couple of ideas which didn't easily fit in a comment:

What immediately comes to mind is that you could pass a Class to the extension loading routine which each of the loaded classes ought to be a subtype of.

For example:

```<code>public <E> Map<Class<? extends E>, List<E>> loadExtensions
   (Class<E>     extType,
    List<String> extNames) {
    // ...;
}
</code>```

However, this only works if there's some place which does know statically of a class which each of the extensions should be a subtype of. It could be that extension loading would then be delegated to the app implementation. For example, they might end up doing something like:

```<code>class CalculatorApp extends App {
    Map<Class<? extends Calculation>, List<Calculation>> extensions =
        loadExtensions(Calculation.class, ...);
}
</code>```

You could also dump all of the extensions in to e.g. your Map<Class<?>, List<Object>> and then have them be retrievable by type:

```<code>abstract class App {
    private final Map<Class<?>, List<Object>> extensions =
        loadExtensions();

    protected final <E> List<E> findExtensions(Class<E> extType) {
        return extensions.entrySet().stream()
                         .filter(e -> extType.isAssignableFrom(e.getKey()))
                         .flatMap(e -> e.getValue().stream())
                         .map(extType::cast)
                         .collect(Collectors.toList());
    }
}
</code>```

Another way which I don't particularly like but could be worth considering is that the App carries a type parameter for the extension type:

```<code>abstract class App<E> {
    protected final Class<E> extType;
    protected final Map<Class<? extends E>, List<E>> extensions;

    protected App(Class<E> extType) {
        this.extType    = extType;
        this.extensions = loadExtensions(extType);
    }
}
</code>```

Then it gets implemented as:

```<code>class CalculatorApp extends App<Calculation> {
    CalculatorApp() { super(Calculation.class); }
}
</code>```

You could also probably use the getGenericSuperclass().getActualTypeArguments() idiom or TypeToken in this case, instead of passing a class.

A cross between #1 and #3, you could abstract the extensions in to a separate container:

```<code>class Extensions<E> {
    private final Class<E> type;
    private final List<E>  extensions;

    public Extensions(Class<E> type) {
        this.type       = type;
        this.extensions = App.findExtensions(type);
    }
}
</code>```

That would allow an implementation to more easily e.g. use multiple extension types. For the calculator example, maybe they want to have both a Calculation extension and, say, a NumberDisplayFormat extension.

Anyway, it would seem that no matter what you decide to do, somebody needs to know statically what the supertype of their extensions is.

Title: Generic Interface Casting

Body:
I am working on creating a very simplistic OS-like framework (similar to Android) built off of the JVM for educational purposes.

Mostly, I just wanted to learn about ClassLoaders and the endless possibilities of them.  I have the majority of the infrastructure created, but I am questioning whether there may be a better way of handling the generics of the situation that I am in.

A little description of the way my framework operates:

"App" implementations in my framework have the ability to attach extensions, i.e. plugins.  The extension system works by requiring extensions to implement an interface that the App code is aware of, but the App code has no knowledge of the extensions at all, it just knows of the interface.

This is where my use of ClassLoaders comes in.  I use the URLClassLoader to load in all .class files in the $ApplicationRoot/ext directory recursively and test to see if the interface isAssignable( from the loaded classes).

This all works fine and dandy except when I try to further generalize it.  What I want to do is have SDK code that will handle all of this, so that an app would just need to make sure the proper extensions are in the proper folder.

So here is my code right now:

Set<String> classFiles = new HashSet<>();
gatherAllClassFiles("", classFiles, srcRoot);
gatherAllClassFiles("", classFiles, extRoot);

URLClassLoader ucl = new URLClassLoader(new URL[]{extRoot.toURI().toURL(), srcRoot.toURI().toURL()});

for(String className:classFiles){

    Class<?> clazz = ucl.loadClass(className);
    for(String extension: extensionInterfaceNames){
        Class<?> iface = Class.forName(extension);
        if(iface.isAssignableFrom(clazz)){
            extensions.putIfAbsent(iface, new ArrayList<>());
            extensions.get(iface).add(iface.cast(clazz.newInstance()));
        }
    }
}

extensions is declared as follows:

private Map<Class<?>, List<?>> extensions;

I am aware that this implementation of generics is not in the least bit ideal, in fact, in its current state, it won't compile, but I really wanted to stay away from using List<Object>.

What I really would like to be able to do is something like this:

private Map<Class<?>, List<iface>> extensions;

given that iface is the name of the a Class variable holding the class information and not the actual Type, this will not work.

My gut feeling is that I will have to suck it up and use List<Object> and unsafely cast it out, but I was hoping that someone else might have a better suggestion.

Body:
A couple of ideas which didn't easily fit in a comment:

What immediately comes to mind is that you could pass a Class to the extension loading routine which each of the loaded classes ought to be a subtype of.

For example:

public <E> Map<Class<? extends E>, List<E>> loadExtensions
   (Class<E>     extType,
    List<String> extNames) {
    // ...;
}

However, this only works if there's some place which does know statically of a class which each of the extensions should be a subtype of. It could be that extension loading would then be delegated to the app implementation. For example, they might end up doing something like:

class CalculatorApp extends App {
    Map<Class<? extends Calculation>, List<Calculation>> extensions =
        loadExtensions(Calculation.class, ...);
}

You could also dump all of the extensions in to e.g. your Map<Class<?>, List<Object>> and then have them be retrievable by type:

abstract class App {
    private final Map<Class<?>, List<Object>> extensions =
        loadExtensions();

    protected final <E> List<E> findExtensions(Class<E> extType) {
        return extensions.entrySet().stream()
                         .filter(e -> extType.isAssignableFrom(e.getKey()))
                         .flatMap(e -> e.getValue().stream())
                         .map(extType::cast)
                         .collect(Collectors.toList());
    }
}

Another way which I don't particularly like but could be worth considering is that the App carries a type parameter for the extension type:

abstract class App<E> {
    protected final Class<E> extType;
    protected final Map<Class<? extends E>, List<E>> extensions;

    protected App(Class<E> extType) {
        this.extType    = extType;
        this.extensions = loadExtensions(extType);
    }
}

Then it gets implemented as:

class CalculatorApp extends App<Calculation> {
    CalculatorApp() { super(Calculation.class); }
}

You could also probably use the getGenericSuperclass().getActualTypeArguments() idiom or TypeToken in this case, instead of passing a class.

A cross between #1 and #3, you could abstract the extensions in to a separate container:

class Extensions<E> {
    private final Class<E> type;
    private final List<E>  extensions;

    public Extensions(Class<E> type) {
        this.type       = type;
        this.extensions = App.findExtensions(type);
    }
}

That would allow an implementation to more easily e.g. use multiple extension types. For the calculator example, maybe they want to have both a Calculation extension and, say, a NumberDisplayFormat extension.

Anyway, it would seem that no matter what you decide to do, somebody needs to know statically what the supertype of their extensions is.


问:
Simplexml_load_file errors
I'm triying to parse this address in PHP

```<code>$url = 'http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203&term=pizza&format=xml&sort=distance&radius=5&listingcount=10&key=t266jc29dx' ;
$x1 = simplexml_load_file($url);
</code>```

But here's what I keep getting

Warning:
  simplexml_load_file(http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203):
  failed to open stream: HTTP request failed! HTTP/1.1 500 Internal
  Server Error in...

As you can see I'm only getting part of the url parameters.

Can you help?

答:
With some quick searching on how to retrieve XML via cURL this is what I did to retrieve and parse the XML.

The big reason as I mentioned above in a comment is that you can't pass URLs directly into the simple_xml_load_string function with ampersands(&) in them. It's a character in the XML format that represents entities.

```<code><?php

function get_xml_from_url($url){
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

    $xmlstr = curl_exec($ch);
    curl_close($ch);

    return $xmlstr;
}

$url = 'http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203&term=pizza&format=xml&sort=distance&radius=5&listingcount=10&key=t266jc29dx';
$contents = get_xml_from_url($url);

$xml = simplexml_load_string($contents);

echo '```';
print_r($xml);
echo '```';
?>
</code>```

Title: Simplexml_load_file errors

Body:
I'm triying to parse this address in PHP

$url = 'http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203&term=pizza&format=xml&sort=distance&radius=5&listingcount=10&key=t266jc29dx' ;
$x1 = simplexml_load_file($url);

But here's what I keep getting

Warning:
  simplexml_load_file(http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203):
  failed to open stream: HTTP request failed! HTTP/1.1 500 Internal
  Server Error in...

As you can see I'm only getting part of the url parameters.

Can you help?

Body:
With some quick searching on how to retrieve XML via cURL this is what I did to retrieve and parse the XML.

The big reason as I mentioned above in a comment is that you can't pass URLs directly into the simple_xml_load_string function with ampersands(&) in them. It's a character in the XML format that represents entities.

<?php

function get_xml_from_url($url){
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

    $xmlstr = curl_exec($ch);
    curl_close($ch);

    return $xmlstr;
}

$url = 'http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203&term=pizza&format=xml&sort=distance&radius=5&listingcount=10&key=t266jc29dx';
$contents = get_xml_from_url($url);

$xml = simplexml_load_string($contents);

echo '<pre>';
print_r($xml);
echo '</pre>';
?>


问:
hover link info
how can i get the effect that when u point over a link an information is shown in a box which tells u what that link does.

its like when you hover over a link a box explains its action.

Can some1 help me out with a neat sample.

do i need to use the ajax - hovermenuextender for this??

Thanks

答:
It depends on how fancy you want to be. I personally have found jQuery (AKA JavaScript) to answer the call here. qTip is a jQuery library that has some amazing pop-up "bubble" effects. Head over to their website and check out the various things you can do.

If you head to the qTip documentation (particularly this page), you can see how easy it is to replace "normal" link pop-ups with a much better looking tool tip. Code example shown below:

```<code>$('a[title]').qtip({ style: { name: 'cream', tip: true } })
</code>```

Title: hover link info

Body:
It depends on how fancy you want to be. I personally have found jQuery (AKA JavaScript) to answer the call here. qTip is a jQuery library that has some amazing pop-up "bubble" effects. Head over to their website and check out the various things you can do.

If you head to the qTip documentation (particularly this page), you can see how easy it is to replace "normal" link pop-ups with a much better looking tool tip. Code example shown below:

$('a[title]').qtip({ style: { name: 'cream', tip: true } })


问:
dateRestrict in google custom search using Python
I've been trying to use the google custom search.

```<code>from googleapiclient.discovery import build

my_api_key = "MASKXXX"
my_cse_id = "MASKXXXX"

date = "2016-01-01:2016-01-02"

def google_search(search_term, api_key, cse_id, **kwargs):
    service = build("customsearch", "v1", developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, dateRestrict=date, **kwargs).execute()
    return res['items']

results = google_search('crude oil site:www.bloomberg.com/news/articles/', my_api_key, my_cse_id, num=5)
for result in results:
    # pprint.pprint(result)
    print result['title']
    print result['snippet']
</code>```

The above code works, but I want the results to return the articles for a particular date. I am trying to use the option dateRestrict, but it doesn't seem to work. I have tried various formats but none seems to work. What could be the problem? Thanks for the help

答:
I was trying the same thing, and dateRestrict didn't seem to work. The pages that were not in the date range also appeared.
The workaround I found is to use the sort feature. The query will look something like this:

(q='search_term' , cx='search_engine_id', sort = 'date:r:yyyymmdd:yyyymmdd')

The sort feature allows us to sort and filter the date of the results to the time range specified.

Body:
I've been trying to use the google custom search.

from googleapiclient.discovery import build

my_api_key = "MASKXXX"
my_cse_id = "MASKXXXX"

date = "2016-01-01:2016-01-02"

def google_search(search_term, api_key, cse_id, **kwargs):
    service = build("customsearch", "v1", developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, dateRestrict=date, **kwargs).execute()
    return res['items']

results = google_search('crude oil site:www.bloomberg.com/news/articles/', my_api_key, my_cse_id, num=5)
for result in results:
    # pprint.pprint(result)
    print result['title']
    print result['snippet']

The above code works, but I want the results to return the articles for a particular date. I am trying to use the option dateRestrict, but it doesn't seem to work. I have tried various formats but none seems to work. What could be the problem? Thanks for the help


问:
npm install save by default
It happened too many times that I forgot to add --save when installing node modules. Is there a way to append this option by default? So that whenever I type npm install <package> the package is added to dependencies in package.json.

答: From npm5 , npm will save by default . https://github.com/npm/npm/issues/5108</p>

Title: npm install save by default


问:
Android progressBar doesn't set progress after call Retrofit
im trying to simulate a progress of the retrofit's call, so before of execute the call i start the progress in this way:

```<code>public void runSimulateProgress(final CustomDialogLoad d){
    new Thread(new Runnable() {
        @Override
        public void run() {
            if (d != null){
                int progress = 0;
                while (d.getProgress() < 99){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    progress = progress+10;
                    d.setProgress(progress);
                }

            }
        }
    }).start();

}
</code>```

The CustomDialogLoad is a Dialog with a progress and TextView.

So, when the call ends, i want to set progress to 100, but the progressBar doesn't change, i have tried to make any change of progress in a manual way but the progressBar doesn't want to update.

Here's the code of retrofit's call

```<code>dialogProgress.runSimulateProgress(dialogProgress);
final SaveRutaVisitaService saveRutaVisitaService =       restAdapter.create(SaveRutaVisitaService.class);
saveRutaVisitaService.saveRutaVisita(multipartTypedOutput, new        Callback<Response>() {
        @Override
        public void success(Response result, Response response) {
       dialogProgress.setProgress(100)

    }   @Override
        public void failure(RetrofitError retrofitError) {
       dialogProgress.setProgress(100)}
    }
</code>```

I tried to make real progress based on this question

Android Retrofit - onProgressUpdate for showing Progress Notification

but doesn't work to me with multiPart

I appreciate any help

regards

EDIT: i added the "post" to update the progress but still not working

```<code>public void setProgress(final int p){
    mRingProgressBar.post(new Runnable() {
        @Override
        public void run() {
            mRingProgressBar.setProgress(p);
        }
    });

}
</code>```

that method is inside of CustomDialogLoad class

答:
You're attempting to change View from another thread. Check this question How to set text of text view in another thread

Basically, change:

```<code> d.setProgress(progress);
</code>```

to

```<code>d.post(new Runnable() {
    public void run() {
        d.setProgress(progress);
    }
}
</code>```

Body:
im trying to simulate a progress of the retrofit's call, so before of execute the call i start the progress in this way:

public void runSimulateProgress(final CustomDialogLoad d){
    new Thread(new Runnable() {
        @Override
        public void run() {
            if (d != null){
                int progress = 0;
                while (d.getProgress() < 99){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    progress = progress+10;
                    d.setProgress(progress);
                }

            }
        }
    }).start();

}

The CustomDialogLoad is a Dialog with a progress and TextView.

So, when the call ends, i want to set progress to 100, but the progressBar doesn't change, i have tried to make any change of progress in a manual way but the progressBar doesn't want to update.

Here's the code of retrofit's call

dialogProgress.runSimulateProgress(dialogProgress);
final SaveRutaVisitaService saveRutaVisitaService =       restAdapter.create(SaveRutaVisitaService.class);
saveRutaVisitaService.saveRutaVisita(multipartTypedOutput, new        Callback<Response>() {
        @Override
        public void success(Response result, Response response) {
       dialogProgress.setProgress(100)

    }   @Override
        public void failure(RetrofitError retrofitError) {
       dialogProgress.setProgress(100)}
    }

I tried to make real progress based on this question

Android Retrofit - onProgressUpdate for showing Progress Notification

but doesn't work to me with multiPart

I appreciate any help

regards

EDIT: i added the "post" to update the progress but still not working

public void setProgress(final int p){
    mRingProgressBar.post(new Runnable() {
        @Override
        public void run() {
            mRingProgressBar.setProgress(p);
        }
    });

}

that method is inside of CustomDialogLoad class

Body:
You're attempting to change View from another thread. Check this question How to set text of text view in another thread

Basically, change:

 d.setProgress(progress);

to

d.post(new Runnable() {
    public void run() {
        d.setProgress(progress);
    }
}


问:
How do I set the text color of jQuery UI dialog title bars?
I inherited a project from another developer who used jQuery UI.

I've added a few pages that have jQuery UI dialogs and jQuery UI datepickers.

The problem is, the text of the title in the jQuery UI dialog title bar is the same color as the color of the title bar.  In the jQuery UI datepicker, the arrows that the user clicks to change the month on the calendar are the same color as the background there too!

I think this is set somewhere in the jQuery UI CSS.  Can someone please tell me where in the CSS I need to make the adjustment so that the text is visible?

My .ui-widget section is given below and I'm getting gray widgets and text on a gray background:

```<code>.ui-widget { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1.1em/*{fsDefault}*/; }
.ui-widget .ui-widget { font-size: 1em; }
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1em; }
.ui-widget-content { border: 1px solid #aaaaaa/*{borderColorContent}*/; background: #ffffff/*{bgColorContent}*/ url(images/ui-bg_flat_75_ffffff_40x100.png)/*{bgImgUrlContent}*/ 50%/*{bgContentXPos}*/ 50%/*{bgContentYPos}*/ repeat-x/*{bgContentRepeat}*/; color: #222222/*{fcContent}*/; }
.ui-widget-content a { color: #222222/*{fcContent}*/; }
.ui-widget-header { border: 1px solid #aaaaaa/*{borderColorHeader}*/;  background: #cccccc/*{bgColorHeader}*/ url(images/ui-bg_highlight-soft_75_cccccc_1x100.png)/*{bgImgUrlHeader}*/ 50%/*{bgHeaderXPos}*/ 50%/*{bgHeaderYPos}*/ repeat-x/*{bgHeaderRepeat}*/;   color: #222222/*{fcHeader}*/;    font-weight: bold; }
.ui-widget-header a { color: #222222 /*{fcHeader}*/; }
</code>```

UPDATE: I have awarded the points for the answer below.  I discovered that the reason that the widget is invisible is that the jQuery UI image files are missing from the copy of the program I'm working on!

答:
Mine looks like this

```<code>.ui-widget-header { border: 1px solid #aaaaaa;
background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png)
50% 50% repeat-x; color: #222222; font-weight: bold; }
</code>```

I changed color: #222222 to color: red and it changed only the text in the dialog header.

Body:
I inherited a project from another developer who used jQuery UI.

I've added a few pages that have jQuery UI dialogs and jQuery UI datepickers.

The problem is, the text of the title in the jQuery UI dialog title bar is the same color as the color of the title bar.  In the jQuery UI datepicker, the arrows that the user clicks to change the month on the calendar are the same color as the background there too!

I think this is set somewhere in the jQuery UI CSS.  Can someone please tell me where in the CSS I need to make the adjustment so that the text is visible?

My .ui-widget section is given below and I'm getting gray widgets and text on a gray background:

.ui-widget { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1.1em/*{fsDefault}*/; }
.ui-widget .ui-widget { font-size: 1em; }
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1em; }
.ui-widget-content { border: 1px solid #aaaaaa/*{borderColorContent}*/; background: #ffffff/*{bgColorContent}*/ url(images/ui-bg_flat_75_ffffff_40x100.png)/*{bgImgUrlContent}*/ 50%/*{bgContentXPos}*/ 50%/*{bgContentYPos}*/ repeat-x/*{bgContentRepeat}*/; color: #222222/*{fcContent}*/; }
.ui-widget-content a { color: #222222/*{fcContent}*/; }
.ui-widget-header { border: 1px solid #aaaaaa/*{borderColorHeader}*/;  background: #cccccc/*{bgColorHeader}*/ url(images/ui-bg_highlight-soft_75_cccccc_1x100.png)/*{bgImgUrlHeader}*/ 50%/*{bgHeaderXPos}*/ 50%/*{bgHeaderYPos}*/ repeat-x/*{bgHeaderRepeat}*/;   color: #222222/*{fcHeader}*/;    font-weight: bold; }
.ui-widget-header a { color: #222222 /*{fcHeader}*/; }

UPDATE: I have awarded the points for the answer below.  I discovered that the reason that the widget is invisible is that the jQuery UI image files are missing from the copy of the program I'm working on!

Body:
Mine looks like this

.ui-widget-header { border: 1px solid #aaaaaa;
background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png)
50% 50% repeat-x; color: #222222; font-weight: bold; }

I changed color: #222222 to color: red and it changed only the text in the dialog header.


问:
what's different about list_route and detail_route in django-rest-framework?
like title,

what's different about list_route and detail_route in django-rest-framework?

if I want to get 1 in url xxx/books/1/,

how can I write url.py and views.py ?

答:
detail_route, is for an instance. What I mean, method generated with detail route, will be appended after an instance method, i.e. a retrieve.
{prefix}/{lookup}/

Check : django drf router doc

If your model is books and 1 is the id:

```<code>class ParkingViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer

def retrieve(self, request, pk=None):
    # Here pk will be 1.
    queryset = Book.objects.get(pk=pk)
    serializer = BookSerializer(queryset)
    return Response({'msg':"",'data':serializer.data, 'status':'OK'})
</code>```

If xxx is your instance, you should user url_path variable to change default url. Something like this:

```<code>@detail_route(methods=['get'], url_path='(books/?P<num>\d+)')
</code>```

Then in the method, you will have num as a parmeter

urls.py, will be generated with default router:

```<code>from django.conf.urls import url, include
from recharge_card import views
from rest_framework.routers import DefaultRouter

# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'xxx', views.XxxViewSet, base_name="xxx")

urlpatterns = [
    url(r'^api/', include(router.urls)),
]
</code>```

Body:
detail_route, is for an instance. What I mean, method generated with detail route, will be appended after an instance method, i.e. a retrieve.
{prefix}/{lookup}/

Check : django drf router doc

If your model is books and 1 is the id:

class ParkingViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer

def retrieve(self, request, pk=None):
    # Here pk will be 1.
    queryset = Book.objects.get(pk=pk)
    serializer = BookSerializer(queryset)
    return Response({'msg':"",'data':serializer.data, 'status':'OK'})

If xxx is your instance, you should user url_path variable to change default url. Something like this:

@detail_route(methods=['get'], url_path='(books/?P<num>\d+)')

Then in the method, you will have num as a parmeter

urls.py, will be generated with default router:

from django.conf.urls import url, include
from recharge_card import views
from rest_framework.routers import DefaultRouter

# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'xxx', views.XxxViewSet, base_name="xxx")

urlpatterns = [
    url(r'^api/', include(router.urls)),
]


问:
How can I change the progress color dynamically
I need change the color of a progress according with your value. I saw that the code below works

```<code>progress[value^"50"]::-moz-progress-bar{background-color:green}
</code>```

In the code above I can change the color, but in my case I use a tecnology(GWT 2.7) that does not support the operator "^".

I saw too a code like:

```<code>#pb::-moz-progress-bar {background-color: green;}
</code>```

But in my case I should change dinamically the value of background-color.

Tks in advance

答:
I achieve the result using css class bellow

```<code>progress:before  {
    content: attr(data-label);
    color: white;
    vertical-align: 0;

     /*Position text over the progress bar */
     position:absolute;
    text-align:center;
    left:0;
    right:0;
}

progress {
    -webkit-appearance: none;
    background-color: gray;
    position:relative;
    height: 15px;
    width: 255px;
}
.progressBarRed::-moz-progress-bar {
    width: 250px;
    height: 15px;
    border-style: solid;
    border: 1px;
    background-color: red;
}
</code>```

The unique problem that I faced were that the pseudo selector :before does not work in progress element(Firefox). In Chrome work's right.

Body:
I need change the color of a progress according with your value. I saw that the code below works

progress[value^"50"]::-moz-progress-bar{background-color:green}

In the code above I can change the color, but in my case I use a tecnology(GWT 2.7) that does not support the operator "^".

I saw too a code like:

#pb::-moz-progress-bar {background-color: green;}

But in my case I should change dinamically the value of background-color.

Tks in advance

Body:
I achieve the result using css class bellow

progress:before  {
    content: attr(data-label);
    color: white;
    vertical-align: 0;

     /*Position text over the progress bar */
     position:absolute;
    text-align:center;
    left:0;
    right:0;
}

progress {
    -webkit-appearance: none;
    background-color: gray;
    position:relative;
    height: 15px;
    width: 255px;
}
.progressBarRed::-moz-progress-bar {
    width: 250px;
    height: 15px;
    border-style: solid;
    border: 1px;
    background-color: red;
}

The unique problem that I faced were that the pseudo selector :before does not work in progress element(Firefox). In Chrome work's right.


答:
You can create a variable and add the validation messgae to that and display it.A sample

function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');

var text = "Make sure";
var valid = true;

if(firstname.value == "") {
      text+= " the first name  ";
      valid = false;
 }

if(lastname.value == "") {
       text += ( !valid ? '& ' : '')+ " the last name "
      valid = false;

 }
if(address.value == "") {
      text += ( !valid ? '& ' : '')+  " the address ";
      valid = false;

  }
if(postcode.value == "") {
      text += ( !valid ? '& ' : '')+  " the postcode ";
      valid = false;
  }
if(city.value == "") {

       text += ( !valid ? '& ' : '') + " the city ";
      valid = false;

     }

     if(!valid){
        text+= " is Filled";
        alert(text);
        return false;
     }
   return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id = "contactform" action = "">
<label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
<label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type = "submit" value = "Submit" onclick = " return validate()" />
<input type = "reset" value = "Clear" /></code>```

Title: How do I alert the user that multiple fields are left blank in an HTML form after clicking submit?

Body:
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!

Here is the HTML code:

<form id="contactform" action="">
     Name
        <input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />

     Last Name
        <input name="lastname" type="text" id="lastname" maxlength="150" />

     Address
        <input name="address" type="text" id="address" maxlength="200" />

     Postcode
        <input name="postcode" type="text" id="postcode" maxlength="50" />

     City
        <input name="city" type="text" id="city" maxlength="100" />

</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />

Here is the javascript code:

function validate() {

    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var address = document.getElementById('address');
    var postcode = document.getElementById('postcode');
    var city = document.getElementById('city');

    if (firstname.value == "") {
        alert("Make sure the first name field is filled");
        return false;
    }

    if (lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
    }
    if (address.value == "") {
        alert("Make sure the address field is filled");
        return false;
    }
    if (postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
    }
    if (city.value == "") {
        alert("Make sure the city field is filled");
        return false;
    }
    return true;
}

Body:
You can create a variable and add the validation messgae to that and display it.A sample

function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');

var text = "Make sure";
var valid = true;

if(firstname.value == "") {
      text+= " the first name  ";
      valid = false;
 }

if(lastname.value == "") {
       text += ( !valid ? '& ' : '')+ " the last name "
      valid = false;

 }
if(address.value == "") {
      text += ( !valid ? '& ' : '')+  " the address ";
      valid = false;

  }
if(postcode.value == "") {
      text += ( !valid ? '& ' : '')+  " the postcode ";
      valid = false;
  }
if(city.value == "") {

       text += ( !valid ? '& ' : '') + " the city ";
      valid = false;

     }

     if(!valid){
        text+= " is Filled";
        alert(text);
        return false;
     }
   return true;
}

<form id = "contactform" action = "">
<label> Name
<input name = "firstname" type = "text" id = "firstname" maxlength = "50" autofocus = "autofocus"/>
</label>
<label> Last Name
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<label> City
<input name = "city" type = "text" id = "city" maxlength = "100" />
</label>
</form>
<input type = "submit" value = "Submit" onclick = " return validate()" />
<input type = "reset" value = "Clear" />


问:
Python Exception: ValueError: too many values to unpack (expected 2)
im trying to find the mistake in my code.
My IDE (Coderunner on Mac) only says this:

```<code>File "A3.py", line 27, in <module>
ValueError: too many values to unpack (expected 2)
</code>```

I never had this exception. I don't know how to handle it and where the problem is. What I am doing wrong?

This is my code... I commented line 27.

```<code>with open("spd.txt", encoding="utf-8") as f:
    text = f.read()
text = text.replace("\xad", "")

words = []
for word in text.lower().split():
    word = word.strip("‚‘!,.:«»-()'_#-–„“■;+*?")
    if word != "":
        if not word[-1].isalnum():
            print(repr(word))
        words.append(word)

trigrams = {}
for i in range(len(words)-2):
       word = words[i]
       nextword = words[i + 1]
       nextnextword = words[i + 2]
       key = (word, nextword, nextnextword)
       trigrams[key] = trigrams.get(key, 0) + 1

l = list(trigrams.items())
l.sort(key=lambda x: (x[1], x[0]))
l.reverse()

for key, count in trigrams: #This is line 27
    if count < 5:
        break
    word = key[0]
    nextword = key[1]
    nextnextword = key[2]
    print(word, nextword, nextnextword, count)
</code>```

答: You need to do for key, count in trigrams.items(): to iterate over the keys and the values together. Iterating just over the dictionary only yields the keys.

Body:
im trying to find the mistake in my code.
My IDE (Coderunner on Mac) only says this:

File "A3.py", line 27, in <module>
ValueError: too many values to unpack (expected 2)

I never had this exception. I don't know how to handle it and where the problem is. What I am doing wrong?

This is my code... I commented line 27.

with open("spd.txt", encoding="utf-8") as f:
    text = f.read()
text = text.replace("\xad", "")

words = []
for word in text.lower().split():
    word = word.strip("‚‘!,.:«»-()'_#-–„“■;+*?")
    if word != "":
        if not word[-1].isalnum():
            print(repr(word))
        words.append(word)

trigrams = {}
for i in range(len(words)-2):
       word = words[i]
       nextword = words[i + 1]
       nextnextword = words[i + 2]
       key = (word, nextword, nextnextword)
       trigrams[key] = trigrams.get(key, 0) + 1

l = list(trigrams.items())
l.sort(key=lambda x: (x[1], x[0]))
l.reverse()

for key, count in trigrams: #This is line 27
    if count < 5:
        break
    word = key[0]
    nextword = key[1]
    nextnextword = key[2]
    print(word, nextword, nextnextword, count)


问:
How to use awk counting the number of specificed digit in certain column
How can I count the matched value in the certain column?

I have a file:(wm.csv)

I executed the command to get the targeted value in certain column: tail -n +497 wm.csv | awk -F"," '$2=="2" {print $3" "$4}'

then I get the following output data I want:

hit 2
hit 2
hit 2
hit 2
miss
hit 2
hit 2
hit 2
hit 2
hit 2
hit 2
hit 2
incorrect 1
hit 2
hit 2
hit 2

I want to count the number of "2" in second column in order to do simple math like: total digits in column divided by total number of row. Specifically, in this case, it would looks like: 14 (fourteen "2" in second column) / 16(total number of row)

Following is the command I tried but this does not work :
tail -n +497 wm.csv | awk -F"," '$2=="2" {count=0;} { if ($4 == "2") count+=1 } {print $3,$4,$count }'

thanks

答:
taking the posted data as input file</p>

```<code>$ awk '$2==2{c++} END{print NR,c,c/NR}' file

16 14 0.875
</code>```

Body:
taking the posted data as input file

$ awk '$2==2{c++} END{print NR,c,c/NR}' file

16 14 0.875