问:
Ionic Cordova App Not Installing on Android
I'm fairly certain the issue persists on all Android devices. However I can be wrong.

I get through the build process with no errors. I find the APK file in the proper folder but when I upload it via USB (not through CLI adb) to my Android (Galaxy S7 edge) it says "App not Installed" after having it go through trying to Install. I am not sure this has anything to do with the processor on my phone as I ran into a similar issue when installing apps made with RPG Maker MV. Right now I'm just (re)trying my hand on Android dev using ionic / Cordova rather than standard Java based Android development.

Note:
I already have debug mode / unknown sources checked.
The app itself works fine in web browser testing.

So main question:
How do I get it to install?

Side question:
Is there a way to tell ionic what version of Android I want to build for?
(I have a few of the SDKs installed)

答:
OP's Feedback

```<code>cordova run android --device
</code>```

Original Answer

You need to create a debug version of apk using below CLI command.

```<code>ionic run android --device
</code>```

Plug a device to the PC using USB

Copy the android-debug.apk file to the device(apk path:.. \platforms\android\build\outputs\apk)

After that, You have to enable below setting on your Android device.

settings --> general tab --> security --> unknown sources (enabled
  this)

After that just double-clicked the android-debug.apk from the location which you have copied.Then your app will be installed on your device.

Body:
OP's Feedback

cordova run android --device

Original Answer

You need to create a debug version of apk using below CLI command.

ionic run android --device

Plug a device to the PC using USB

Copy the android-debug.apk file to the device(apk path:.. \platforms\android\build\outputs\apk)

After that, You have to enable below setting on your Android device.

settings --> general tab --> security --> unknown sources (enabled
  this)

After that just double-clicked the android-debug.apk from the location which you have copied.Then your app will be installed on your device.


来源: stackexchange

问:
Rails API post in request spec should pass params but getting empty
To start, in my request spec sites.spec.rb I have this test:

```<code>describe "POST /v1/sites" do

    let(:valid_attributes) { { url: "www.example.com", site_code: "123456" } }

    context 'when the request is valid' do
      before { post v1_sites_path, params: valid_attributes }

      it 'creates a site' do
        expect(json['url']).to eq("www.example.com")
        expect(json['site_code']).to eq("123456")
      end

      it 'returns status code 201' do
        expect(response).to have_http_status(201)
      end
    end
</code>```

I then get a failing test for "creates a site"...

```<code>1) Sites POST /v1/sites when the request is valid creates a site
     Failure/Error: expect(json['url']).to eq("www.example.com")

       expected: "www.example.com"
            got: ["can't be blank"]

       (compared using ==)
     # ./spec/requests/sites_spec.rb:61:in `block (4 levels) in <top (required)>'
     # ./spec/rails_helper.rb:84:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:83:in `block (2 levels) in <top (required)>'
</code>```

Now this technically makes sense because my Site model has validates :url, :site_code, presence: true. So the test is failing because the post is not passing the params correctly.

Lastly, here is the controller:

```<code>module Api::V1
  class SitesController < BaseApiController
    before_action :set_site, only: [:show, :update, :destroy]

    # GET /sites
    def index
      @sites = Site.all

      render json: @sites
    end

    # GET /sites/1
    def show
      render json: @site
    end

    # POST /sites
    def create
      @site = Site.new(site_params)

      if @site.save
        render json: @site, status: :created, location: @site
      else
        render json: @site.errors, status: :unprocessable_entity
      end
    end

    # PATCH/PUT /sites/1
    def update
      if @site.update(site_params)
        render json: @site
      else
        render json: @site.errors, status: :unprocessable_entity
      end
    end

    # DELETE /sites/1
    def destroy
      @site.destroy
    end

    private
      # Use callbacks to share common setup or constraints between actions.
      def set_site
        @site = Site.find(params[:id])
      end

      # Only allow a trusted parameter "white list" through.
      def site_params
        # params.require(:data).require(:attributes).permit(:url, :side_code, :user_id)
        # params.require(:site).permit(:url, :side_code, :user_id)
        params.fetch(:site, {}).permit(:url, :side_code)
      end
  end
end
</code>```

I am speculating that the way I am passing parameters to the post for Rails API is perhaps not formatted or correctly or something else entirely. I did play with the params in the test block trying data: { attributes: valid_attributes } with no luck.

Any thoughts or suggestions are greatly appreciated!

答:
This problem was indeed due to format of the parameters I was passing to POST request in the test block. I tested the POST via the command line and watched the rails server to see how the params were coming through. They looked like this:

```<code>Parameters: {"site_code"=>"123456", "url"=>"www.updated.com", "subdomain"=>"api", "id"=>"2", "site"=>{"site_code"=>"123456", "url"=>"www.updated.com"}}
</code>```

Then in my sites_spec.rb, I copied this format for the valid params of the post request:

```<code>let(:valid_attributes) { { "site"=>{"url"=>"www.example.com", "user_id"=>user_id, "site_code"=>"123456"} } }
</code>```

This works. The JSON format of the params needed to be formatted in the test block the same way they would be if it was real JSON request.

ContentLicense: CC BY-SA 3.0

Body:
To start, in my request spec sites.spec.rb I have this test:

describe "POST /v1/sites" do

    let(:valid_attributes) { { url: "www.example.com", site_code: "123456" } }

    context 'when the request is valid' do
      before { post v1_sites_path, params: valid_attributes }

      it 'creates a site' do
        expect(json['url']).to eq("www.example.com")
        expect(json['site_code']).to eq("123456")
      end

      it 'returns status code 201' do
        expect(response).to have_http_status(201)
      end
    end

I then get a failing test for "creates a site"...

1) Sites POST /v1/sites when the request is valid creates a site
     Failure/Error: expect(json['url']).to eq("www.example.com")

       expected: "www.example.com"
            got: ["can't be blank"]

       (compared using ==)
     # ./spec/requests/sites_spec.rb:61:in `block (4 levels) in <top (required)>'
     # ./spec/rails_helper.rb:84:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:83:in `block (2 levels) in <top (required)>'

Now this technically makes sense because my Site model has validates :url, :site_code, presence: true. So the test is failing because the post is not passing the params correctly.

Lastly, here is the controller:

module Api::V1
  class SitesController < BaseApiController
    before_action :set_site, only: [:show, :update, :destroy]

    # GET /sites
    def index
      @sites = Site.all

      render json: @sites
    end

    # GET /sites/1
    def show
      render json: @site
    end

    # POST /sites
    def create
      @site = Site.new(site_params)

      if @site.save
        render json: @site, status: :created, location: @site
      else
        render json: @site.errors, status: :unprocessable_entity
      end
    end

    # PATCH/PUT /sites/1
    def update
      if @site.update(site_params)
        render json: @site
      else
        render json: @site.errors, status: :unprocessable_entity
      end
    end

    # DELETE /sites/1
    def destroy
      @site.destroy
    end

    private
      # Use callbacks to share common setup or constraints between actions.
      def set_site
        @site = Site.find(params[:id])
      end

      # Only allow a trusted parameter "white list" through.
      def site_params
        # params.require(:data).require(:attributes).permit(:url, :side_code, :user_id)
        # params.require(:site).permit(:url, :side_code, :user_id)
        params.fetch(:site, {}).permit(:url, :side_code)
      end
  end
end

I am speculating that the way I am passing parameters to the post for Rails API is perhaps not formatted or correctly or something else entirely. I did play with the params in the test block trying data: { attributes: valid_attributes } with no luck.

Any thoughts or suggestions are greatly appreciated!

Body:
This problem was indeed due to format of the parameters I was passing to POST request in the test block. I tested the POST via the command line and watched the rails server to see how the params were coming through. They looked like this:

Parameters: {"site_code"=>"123456", "url"=>"www.updated.com", "subdomain"=>"api", "id"=>"2", "site"=>{"site_code"=>"123456", "url"=>"www.updated.com"}}

Then in my sites_spec.rb, I copied this format for the valid params of the post request:

let(:valid_attributes) { { "site"=>{"url"=>"www.example.com", "user_id"=>user_id, "site_code"=>"123456"} } }

This works. The JSON format of the params needed to be formatted in the test block the same way they would be if it was real JSON request.


问:
GCD Returning Incorrect Results in UITableView
I have a list of about 8,500 items that load in a UITableView and there should be only about 200 items in which product.isnewitem is true. For every 'new' item, an image (newicon.png) is supposed to load indicating that it is a new item; however, when I start scrolling down on the table view, newicon shows up on over 50% of the items. All the items are loaded via Realm.

The check for new items is done in:

```<code>if product.isnewitem {
        cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
    }
</code>```

Here is the entire cellForRowAtIndexPath method:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let paths = NSSearchPathForDirectoriesInDomains(documentsDirectory, userDomainMask, true)

    let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as? OrderFormViewCell
        ?? UITableViewCell(style: .subtitle, reuseIdentifier: "ProductCell") as! OrderFormViewCell

    let realm = try! Realm()
    let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
    let product = allProducts[indexPath.row]

    cell.productDescriptionLabel.text = product.basedescription

    queue.async {
        let realm = try! Realm()

        let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
        let product = allProducts[indexPath.row]

        if product.isnewitem {
            cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
        }

        if let dirPath = paths.first {
            let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("T\(product.itemno.replacingOccurrences(of: "-", with: "")).png")

            if let image = UIImage(contentsOfFile: imageURL.path) {
                cell.productImageView.image = image
            }
            else {
                cell.productImageView.image = #imageLiteral(resourceName: "image-coming-soon.png")
            }
        }

    }

    return cell
}
</code>```

答:
I can’t understand why you use this code

```<code>let realm = try! Realm()
let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
let product = allProducts[indexPath.row]
</code>```

two times in your cellForRowAtIndexPath and one in a queue, I think you must move this code to your viewController viewDidLoad, or viewWillAppear and then use the products from a local array declared on your viewController

```<code>var allProducts : Results<Product>?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let realm = try! Realm()
    self.allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
}
</code>```

and in your cellForRowAtIndexPath you should have something like this

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let paths = NSSearchPathForDirectoriesInDomains(documentsDirectory, userDomainMask, true)

let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as? OrderFormViewCell
    ?? UITableViewCell(style: .subtitle, reuseIdentifier: "ProductCell") as! OrderFormViewCell

let product = self.allProducts[indexPath.row]
cell.productDescriptionLabel.text = product.basedescription
if product.isnewitem {
        cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
    }
else {
        cell.newIconImageView.image = nil
    }

    if let dirPath = paths.first {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("T\(product.itemno.replacingOccurrences(of: "-", with: "")).png")

        if let image = UIImage(contentsOfFile: imageURL.path) {
            cell.productImageView.image = image
        }
        else {
            cell.productImageView.image = #imageLiteral(resourceName: "image-coming-soon.png")
        }
    }

return cell
}
</code>```

I hope this helps you

Body:
I have a list of about 8,500 items that load in a UITableView and there should be only about 200 items in which product.isnewitem is true. For every 'new' item, an image (newicon.png) is supposed to load indicating that it is a new item; however, when I start scrolling down on the table view, newicon shows up on over 50% of the items. All the items are loaded via Realm.

The check for new items is done in:

if product.isnewitem {
        cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
    }

Here is the entire cellForRowAtIndexPath method:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let paths = NSSearchPathForDirectoriesInDomains(documentsDirectory, userDomainMask, true)

    let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as? OrderFormViewCell
        ?? UITableViewCell(style: .subtitle, reuseIdentifier: "ProductCell") as! OrderFormViewCell

    let realm = try! Realm()
    let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
    let product = allProducts[indexPath.row]

    cell.productDescriptionLabel.text = product.basedescription

    queue.async {
        let realm = try! Realm()

        let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
        let product = allProducts[indexPath.row]

        if product.isnewitem {
            cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
        }

        if let dirPath = paths.first {
            let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("T\(product.itemno.replacingOccurrences(of: "-", with: "")).png")

            if let image = UIImage(contentsOfFile: imageURL.path) {
                cell.productImageView.image = image
            }
            else {
                cell.productImageView.image = #imageLiteral(resourceName: "image-coming-soon.png")
            }
        }

    }

    return cell
}

Body:
I can’t understand why you use this code

let realm = try! Realm()
let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
let product = allProducts[indexPath.row]

two times in your cellForRowAtIndexPath and one in a queue, I think you must move this code to your viewController viewDidLoad, or viewWillAppear and then use the products from a local array declared on your viewController

var allProducts : Results<Product>?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let realm = try! Realm()
    self.allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
}

and in your cellForRowAtIndexPath you should have something like this

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let paths = NSSearchPathForDirectoriesInDomains(documentsDirectory, userDomainMask, true)

let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as? OrderFormViewCell
    ?? UITableViewCell(style: .subtitle, reuseIdentifier: "ProductCell") as! OrderFormViewCell

let product = self.allProducts[indexPath.row]
cell.productDescriptionLabel.text = product.basedescription
if product.isnewitem {
        cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
    }
else {
        cell.newIconImageView.image = nil
    }

    if let dirPath = paths.first {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("T\(product.itemno.replacingOccurrences(of: "-", with: "")).png")

        if let image = UIImage(contentsOfFile: imageURL.path) {
            cell.productImageView.image = image
        }
        else {
            cell.productImageView.image = #imageLiteral(resourceName: "image-coming-soon.png")
        }
    }

return cell
}

I hope this helps you


问:
Issue with String to Date conversion after Timezone parsing
I am trying to convert a date to a specified timezone and return the converted date. But the code always returns the unconverted date. Can any help with the same.

```<code>public static Date testUserSpecifiedConv(String toTimezone, Date inputDate) {
        System.out.println(inputDate);
        Date convertedDate = null;
        String inputDateStr ;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone(toTimezone));

        inputDateStr = df.format(inputDate);

        System.out.println("Formatted Date In String Format: " + inputDateStr);
        //Now trying to convert it back to date
        try {
            convertedDate = df.parse(inputDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return convertedDate;
    }

    public static void main(String args[]) {
        System.out.println("Formatted Date In Date Format: "+testUserSpecifiedConv("EST", new Date()));
    }
</code>```

Output is

```<code>Fri Mar 31 15:58:50 IST 2017
Formatted Date In String Format: 03/31/2017 05:28:50
Formatted Date In Date Format: Fri Mar 31 15:58:50 IST 2017
</code>```

The formatted date in string and date format in output is different.

答:
java.time

The Answer by JDC has the right idea.

I will show how to use the modern java.time classes that supplant the troublesome old legacy date-time classe (Date, Calendar, etc.) that should be avoided.

Firstly, your two arguments.

Pass ZoneId objects around rather than mere strings. Doing so provides type-safety, ensures valid values, and makes your code more self-documenting.

Date is outmoded, convert to Instant and pass that instead.

For time zone, specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "America/Montreal" );
</code>```

For the Date, convert to its equivalent in java.time, Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). Like Date, an Instant is always in UTC.

To convert between legacy classes and java.time classes, look to new methods added to the old classes.

```<code>Instant instant = myJavaUtilDate.toInstant();
</code>```

Assign a ZoneId to generate a ZonedDateTime object.

```<code>ZonedDateTime zdt = instant.atZone( z );
</code>```

Generate a string representing that value using a DateTimeFormatter. Do not conflate a date-time object with a string representation of its value.

```<code>DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" , Locale.US );
String output = zdt.format( f );
</code>```

Body:
I am trying to convert a date to a specified timezone and return the converted date. But the code always returns the unconverted date. Can any help with the same.

public static Date testUserSpecifiedConv(String toTimezone, Date inputDate) {
        System.out.println(inputDate);
        Date convertedDate = null;
        String inputDateStr ;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone(toTimezone));

        inputDateStr = df.format(inputDate);

        System.out.println("Formatted Date In String Format: " + inputDateStr);
        //Now trying to convert it back to date
        try {
            convertedDate = df.parse(inputDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return convertedDate;
    }

    public static void main(String args[]) {
        System.out.println("Formatted Date In Date Format: "+testUserSpecifiedConv("EST", new Date()));
    }

Output is

Fri Mar 31 15:58:50 IST 2017
Formatted Date In String Format: 03/31/2017 05:28:50
Formatted Date In Date Format: Fri Mar 31 15:58:50 IST 2017

The formatted date in string and date format in output is different.

Body:
java.time

The Answer by JDC has the right idea.

I will show how to use the modern java.time classes that supplant the troublesome old legacy date-time classe (Date, Calendar, etc.) that should be avoided.

Firstly, your two arguments.

Pass ZoneId objects around rather than mere strings. Doing so provides type-safety, ensures valid values, and makes your code more self-documenting.

Date is outmoded, convert to Instant and pass that instead.

For time zone, specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );

For the Date, convert to its equivalent in java.time, Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). Like Date, an Instant is always in UTC.

To convert between legacy classes and java.time classes, look to new methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant();

Assign a ZoneId to generate a ZonedDateTime object.

ZonedDateTime zdt = instant.atZone( z );

Generate a string representing that value using a DateTimeFormatter. Do not conflate a date-time object with a string representation of its value.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" , Locale.US );
String output = zdt.format( f );


问:
How Angular2 Http request can return body as binary?
I have a url that return the html content with charset=iso-8859-7 which means angulars http request convert the data to utf8 by default and i am unable to encode them back in iso-8859-7 properly. After a lot of searching i found out that many people had the same issue and most of the answers were to change the charset in the server, something that i'm unable to do as the server doesn't belong to me.

So the question is how can HTTP request return binary so i can encode them to iso-8859-7 string?

EDIT - SOLUTION:

What i finally did was to to use TextDecoder and {responseType: ResponseContentType.ArrayBuffer} at RequestOptions. Here is an example to help anyone who is trying to parse html pages and decode them into the right encoding. Hope to help all the guys who tried this in a project which is using Angular2 like Ionic2.

```<code>public parser() {
    // Set content type
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded;'});
    // Create a request option, with withCredentials for sending previous stored cookies
    let options = new RequestOptions({
      withCredentials: true,
      headers: headers,
      responseType: ResponseContentType.ArrayBuffer
    });

    return this.http.get('https://blablablablabla', options) // ...using get request
      .map((res: any) => {

        var string = new TextDecoder('iso-8859-7').decode(res._body);

        var parser = new DOMParser();
        var htmlDoc = parser.parseFromString(string, "text/html");

        console.log(string)

        ..... blabla blabla doing some stuff here .....
      })
      .catch((error: any) => Observable.throw(error || 'Server error'));
}
</code>```

答:
Include the RequestOptionsArgs when you send request.

Specify the field responseType : ResponseContentType inside RequestOptionsArgs. (Either ResponseContentType.ArrayBuffer or ResponseContentType.Blob)

Use TextDecoder or something similar to decode the result.

See the docs:

https://angular.io/api/http/Http

https://angular.io/api/http/RequestOptions

https://angular.io/api/http/ResponseContentType

Body:
I have a url that return the html content with charset=iso-8859-7 which means angulars http request convert the data to utf8 by default and i am unable to encode them back in iso-8859-7 properly. After a lot of searching i found out that many people had the same issue and most of the answers were to change the charset in the server, something that i'm unable to do as the server doesn't belong to me.

So the question is how can HTTP request return binary so i can encode them to iso-8859-7 string?

EDIT - SOLUTION:

What i finally did was to to use TextDecoder and {responseType: ResponseContentType.ArrayBuffer} at RequestOptions. Here is an example to help anyone who is trying to parse html pages and decode them into the right encoding. Hope to help all the guys who tried this in a project which is using Angular2 like Ionic2.

public parser() {
    // Set content type
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded;'});
    // Create a request option, with withCredentials for sending previous stored cookies
    let options = new RequestOptions({
      withCredentials: true,
      headers: headers,
      responseType: ResponseContentType.ArrayBuffer
    });

    return this.http.get('https://blablablablabla', options) // ...using get request
      .map((res: any) => {

        var string = new TextDecoder('iso-8859-7').decode(res._body);

        var parser = new DOMParser();
        var htmlDoc = parser.parseFromString(string, "text/html");

        console.log(string)

        ..... blabla blabla doing some stuff here .....
      })
      .catch((error: any) => Observable.throw(error || 'Server error'));
}


问:
Avoid execution goes on in a .each loop
I've got a code like this one to see whether some radio buttons have been checked or not. I'm using .each function of jquery to show an alert when I find a group of radio buttons with the same name value and none of them have been checked. When I find one I want to fire an alert and return false, but after the alert is shown the execution of the .each stops but the lines after .each function are executed (I mean true value is executed).

```<code>$(":radio").each(function(){
    var name = $(this).attr('name');
    var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
    var notAnswered = numAnswered == 0;
    if(notAnswered){
        alert("Must answer all questions");
        return false;
    }
});
console.log('still goes here even when alert is fired');
return true;
</code>```

How can I avoid this situation?

Thanks.

答:
You can use that same notAnswered variable (or another, whatever floats your boat) at a higher scope, like this:

```<code>var notAnswered;
$(":radio").each(function(){
    notAnswered = $(":radio[name="+this.name+"]:checked").length == 0;
    if(notAnswered){
        alert("Must answer all questions");
        return false;
    }
});
if(notAnswered) return false;
console.log("will only fire if there's an answer");
return true;
</code>```

The other changes above are just slimming down the code, you can get away with far fewer selector engine invocations :)

ContentLicense: CC BY-SA 2.5

Title: Avoid execution goes on in a .each loop

Body:
I've got a code like this one to see whether some radio buttons have been checked or not. I'm using .each function of jquery to show an alert when I find a group of radio buttons with the same name value and none of them have been checked. When I find one I want to fire an alert and return false, but after the alert is shown the execution of the .each stops but the lines after .each function are executed (I mean true value is executed).

$(":radio").each(function(){
    var name = $(this).attr('name');
    var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
    var notAnswered = numAnswered == 0;
    if(notAnswered){
        alert("Must answer all questions");
        return false;
    }
});
console.log('still goes here even when alert is fired');
return true;

How can I avoid this situation?

Thanks.

Body:
You can use that same notAnswered variable (or another, whatever floats your boat) at a higher scope, like this:

var notAnswered;
$(":radio").each(function(){
    notAnswered = $(":radio[name="+this.name+"]:checked").length == 0;
    if(notAnswered){
        alert("Must answer all questions");
        return false;
    }
});
if(notAnswered) return false;
console.log("will only fire if there's an answer");
return true;

The other changes above are just slimming down the code, you can get away with far fewer selector engine invocations :)


问:
How to stop reading input and analyze data in C
I need to create a code in C that reads in a list of pairs of numbers with the first number being the product number (between 1 and and the total number of products as determined by the input) and the second number being the rating from 1-10 and stores it in a 2D array. The rows of the array starting at 1 are product numbers and columns 1-10 are ratings. Column 11 is total number of stars and column 12 is total number of ratings. I have to use scanf to read in the values, and when scan()!=2, the loops should stop and the report generated.

The report should list for each product the number of ratings for each value (i.e. 2 ratings of 5 stars, 17 ratings of 10 stars, etc.) as well as the average rating.

I think I have the logic correct and my code compiles but it keeps returning error when I try to generate a report. Any clues what the problem might be?

This is the code I have so far:

```<code>int productStar[][13] = {0};
int i = 0;
int product = 0;
int stars = 0;
int howMany = 0;
int ratings = 0;
float avg = 0;
int sum = 0;

printf("How many unique products?\n");
scanf("%d", &howMany);

printf("Please enter product # and stars\n");

while(1)
{
    scanf("%d %d", &product, &stars); /* Reads in two values; first is product number, second is rating */

    if (scanf("%d %d", &product, &stars) != 2) /* kills the loop */
    {
        printf("Hi from the inside\n");
        break;
    }

    productStar[product][stars] += 1; /* adds tally to specific product rating */

    productStar[product][11] += stars; /* increments total number of stars; used later to find avg */

    productStar[product][12] += 1; /* increments how many ratings */

}

for (int product = 0; product <= howMany; ++product)
{
 for (int stars = 0; stars <= 10; ++stars)
    {
       avg = productStar[product][11]/productStar[product][12];

        printf("Product %d Information:\n", product);
        printf("1 star: %d\n", productStar[product][1]);
        printf("2 star: %d\n", productStar[product][2]);
        printf("3 star: %d\n", productStar[product][3]);
        printf("4 star: %d\n", productStar[product][4]);
        printf("5 star: %d\n", productStar[product][5]);
        printf("6 star: %d\n", productStar[product][6]);
        printf("7 star: %d\n", productStar[product][7]);
        printf("8 star: %d\n", productStar[product][8]);
        printf("9 star: %d\n", productStar[product][9]);
        printf("10 star: %d\n", productStar[product][10]);
        printf("Average rating: %2.2f out of 10 (%d ratings total).\n", avg, ratings);
        printf("--------------------\n");
    }
}

for (product = 0; product <= howMany; ++product)
{
    sum += productStar[product][12];
    /* Sum of all ratings */
}

printf("%d product ratings evaluated in all.\n\n", sum);

return 0;
</code>```

}

答:
You're reading from standard input twice in a row which I don't think you want to do. Perhaps try changing the second scanf inside of you input reading loop to a statement that checks to see if product and stars are not empty strings:

```<code>  while(1) {
        scanf("%d %d", &product, &stars); /* Reads in two values; first is product number, second is rating */

        if (product == '\0' || stars == '\0') /* kills the loop */
        {
            // Break out of input loop and process data.
            break;
        }
  }

  // Processing code.
</code>```

Also, it's a good idea to check for division by zero:

```<code>if (productStar[product][12] != 0) {
    avg = productStar[product][11]/productStar[product][12];
}
</code>```

After I made those changes your code worked perfectly :)

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

int productStar[][13] = {0};
int i = 0;
int product = 0;
int stars = 0;
int howMany = 0;
int ratings = 0;
float avg = 0;
int sum = 0;

int main(void) {
  printf("How many unique products?\n");
  scanf("%d", &howMany);

  printf("Please enter product # and stars\n");

  while(1)
  {

      scanf("%d %d", &product, &stars); /* Reads in two values; first is product number, second is rating */

      if (product == '\0' || stars == '\0') /* kills the loop */
      {
          break;
      }

      productStar[product][stars] += 1; /* adds tally to specific product rating */

      productStar[product][11] += stars; /* increments total number of stars; used later to find avg */

      productStar[product][12] += 1; /* increments how many ratings */

  }

  for (int product = 0; product <= howMany; ++product)
  {
   for (int stars = 0; stars <= 10; ++stars)
      {
        if (productStar[product][12] != 0) {
           avg = productStar[product][11]/productStar[product][12];
        }

          printf("Product %d Information:\n", product);
          printf("1 star: %d\n", productStar[product][1]);
          printf("2 star: %d\n", productStar[product][2]);
          printf("3 star: %d\n", productStar[product][3]);
          printf("4 star: %d\n", productStar[product][4]);
          printf("5 star: %d\n", productStar[product][5]);
          printf("6 star: %d\n", productStar[product][6]);
          printf("7 star: %d\n", productStar[product][7]);
          printf("8 star: %d\n", productStar[product][8]);
          printf("9 star: %d\n", productStar[product][9]);
          printf("10 star: %d\n", productStar[product][10]);
          printf("Average rating: %2.2f out of 10 (%d ratings total).\n", avg, ratings);
          printf("--------------------\n");
      }
  }

  for (product = 0; product <= howMany; ++product)
  {
      sum += productStar[product][12];
      /* Sum of all ratings */
  }

  printf("%d product ratings evaluated in all.\n\n", sum);

  return 0;
}
</code>```

Body:
I need to create a code in C that reads in a list of pairs of numbers with the first number being the product number (between 1 and and the total number of products as determined by the input) and the second number being the rating from 1-10 and stores it in a 2D array. The rows of the array starting at 1 are product numbers and columns 1-10 are ratings. Column 11 is total number of stars and column 12 is total number of ratings. I have to use scanf to read in the values, and when scan()!=2, the loops should stop and the report generated.

The report should list for each product the number of ratings for each value (i.e. 2 ratings of 5 stars, 17 ratings of 10 stars, etc.) as well as the average rating.

I think I have the logic correct and my code compiles but it keeps returning error when I try to generate a report. Any clues what the problem might be?

This is the code I have so far:

int productStar[][13] = {0};
int i = 0;
int product = 0;
int stars = 0;
int howMany = 0;
int ratings = 0;
float avg = 0;
int sum = 0;

printf("How many unique products?\n");
scanf("%d", &howMany);

printf("Please enter product # and stars\n");

while(1)
{
    scanf("%d %d", &product, &stars); /* Reads in two values; first is product number, second is rating */

    if (scanf("%d %d", &product, &stars) != 2) /* kills the loop */
    {
        printf("Hi from the inside\n");
        break;
    }

    productStar[product][stars] += 1; /* adds tally to specific product rating */

    productStar[product][11] += stars; /* increments total number of stars; used later to find avg */

    productStar[product][12] += 1; /* increments how many ratings */

}

for (int product = 0; product <= howMany; ++product)
{
 for (int stars = 0; stars <= 10; ++stars)
    {
       avg = productStar[product][11]/productStar[product][12];

        printf("Product %d Information:\n", product);
        printf("1 star: %d\n", productStar[product][1]);
        printf("2 star: %d\n", productStar[product][2]);
        printf("3 star: %d\n", productStar[product][3]);
        printf("4 star: %d\n", productStar[product][4]);
        printf("5 star: %d\n", productStar[product][5]);
        printf("6 star: %d\n", productStar[product][6]);
        printf("7 star: %d\n", productStar[product][7]);
        printf("8 star: %d\n", productStar[product][8]);
        printf("9 star: %d\n", productStar[product][9]);
        printf("10 star: %d\n", productStar[product][10]);
        printf("Average rating: %2.2f out of 10 (%d ratings total).\n", avg, ratings);
        printf("--------------------\n");
    }
}

for (product = 0; product <= howMany; ++product)
{
    sum += productStar[product][12];
    /* Sum of all ratings */
}

printf("%d product ratings evaluated in all.\n\n", sum);

return 0;

}

Body:
You're reading from standard input twice in a row which I don't think you want to do. Perhaps try changing the second scanf inside of you input reading loop to a statement that checks to see if product and stars are not empty strings:

  while(1) {
        scanf("%d %d", &product, &stars); /* Reads in two values; first is product number, second is rating */

        if (product == '\0' || stars == '\0') /* kills the loop */
        {
            // Break out of input loop and process data.
            break;
        }
  }

  // Processing code.

Also, it's a good idea to check for division by zero:

if (productStar[product][12] != 0) {
    avg = productStar[product][11]/productStar[product][12];
}

After I made those changes your code worked perfectly :)

#include <stdio.h>

int productStar[][13] = {0};
int i = 0;
int product = 0;
int stars = 0;
int howMany = 0;
int ratings = 0;
float avg = 0;
int sum = 0;

int main(void) {
  printf("How many unique products?\n");
  scanf("%d", &howMany);

  printf("Please enter product # and stars\n");

  while(1)
  {

      scanf("%d %d", &product, &stars); /* Reads in two values; first is product number, second is rating */

      if (product == '\0' || stars == '\0') /* kills the loop */
      {
          break;
      }

      productStar[product][stars] += 1; /* adds tally to specific product rating */

      productStar[product][11] += stars; /* increments total number of stars; used later to find avg */

      productStar[product][12] += 1; /* increments how many ratings */

  }

  for (int product = 0; product <= howMany; ++product)
  {
   for (int stars = 0; stars <= 10; ++stars)
      {
        if (productStar[product][12] != 0) {
           avg = productStar[product][11]/productStar[product][12];
        }

          printf("Product %d Information:\n", product);
          printf("1 star: %d\n", productStar[product][1]);
          printf("2 star: %d\n", productStar[product][2]);
          printf("3 star: %d\n", productStar[product][3]);
          printf("4 star: %d\n", productStar[product][4]);
          printf("5 star: %d\n", productStar[product][5]);
          printf("6 star: %d\n", productStar[product][6]);
          printf("7 star: %d\n", productStar[product][7]);
          printf("8 star: %d\n", productStar[product][8]);
          printf("9 star: %d\n", productStar[product][9]);
          printf("10 star: %d\n", productStar[product][10]);
          printf("Average rating: %2.2f out of 10 (%d ratings total).\n", avg, ratings);
          printf("--------------------\n");
      }
  }

  for (product = 0; product <= howMany; ++product)
  {
      sum += productStar[product][12];
      /* Sum of all ratings */
  }

  printf("%d product ratings evaluated in all.\n\n", sum);

  return 0;
}


问:
How do I order the x-axis categories of a graph according to y-axis values while maintaining the x-axis category names?
Thanks in advance to anyone who can help me with this. I am making a geom_point graph of chlorophyll concentrations in several lakes (these lakes occur in two different watersheds, which is why I have split them into two facets). I would like these points to be ordered by chlorophyll concentration, from lowest to highest concentration (note: I have flipped the y axis). I have done this, but the problem is, when I order the lakes by chlorophyll concentration, I have to graph "site_order" on the x-axis rather than "site_name." You can see from the hashed-out lines of code that I have tried two different methods for graphing the site_names on the x-axis:

1) I have tried assigning site_name levels to site_order, but this does not work. It produces a graph with lake names for the x-axis categories, but the lakes are not associated with the correct data! I'm not sure how levels() assigns site_name to site_order, but it doesn't do it correctly... (see fig. 1).

2)I have tried labeling the x axis with site_name using scale_x_discrete, but this results in a graph without any labels for x-axis categories (see fig. 2).

My code and a sample dataset are below. If anyone can troubleshoot either of my approaches, or suggest a different approach, I would GREATLY appreciate it!

Here's my sample dataset:

```<code>                      Watershed site_order         site_name Morph Chla_percent
1  Six Mile Creek & Schutz Lake         19        Wassermann  Deep   248.571429
2  Six Mile Creek & Schutz Lake         12            Church  Deep    21.428571
3  Six Mile Creek & Schutz Lake          1     Kelser's Pond  Deep  -100.000000
4  Six Mile Creek & Schutz Lake          7           Steiger  Deep    -6.428571
5  Six Mile Creek & Schutz Lake          5            Zumbra  Deep   -40.000000
6  Six Mile Creek & Schutz Lake          4             Stone  Deep   -57.142857
7  Six Mile Creek & Schutz Lake         16       East Auburn  Deep   107.857143
8  Six Mile Creek & Schutz Lake          9       West Auburn  Deep     0.000000
9  Six Mile Creek & Schutz Lake         18            Turbid  Deep   185.714286
10 Six Mile Creek & Schutz Lake         15            Schutz  Deep    84.285714
11              Minnehaha Creek         11           Brownie  Deep    20.285714
12              Minnehaha Creek          2           Calhoun  Deep   -70.714286
13              Minnehaha Creek          6             Cedar  Deep   -33.571429
14              Minnehaha Creek          3           Harriet  Deep   -67.142857
15              Minnehaha Creek          8          Hiawatha  Deep    -1.428571
16              Minnehaha Creek         13 Lake of the Isles  Deep    74.285714
17              Minnehaha Creek         10           Nokomis  Deep    13.571429
18              Minnehaha Creek         17       Powderhorn   Deep   160.714286
19              Minnehaha Creek         14              Taft  Deep    83.571429
</code>```

Here's my code:

```<code>#Import, fix up, and subset data
Data = read.csv("Lakes_data_for_R.csv",
            stringsAsFactors=FALSE)
colnames(Data)[1] <- "Watershed"
Data <- Data[grep("Deep", Data$Morph),]

#Create site_order column (and if possible, assign levels of site_name to site_order)
Data$site_order <- rank(Data$Chla_percent)
#Data$site_order <- as.factor(Data$site_order)
#levels(Data$site_order) <- Data$site_name

#Load ggplot
library(ggplot2)

#Make plot
ggplot() +
  geom_point(data = Data, aes(x = site_order, y = Chla_percent), size = 5, color = "blue") +
  ylab ("Chlorophyll a (% difference from Poor threshold)") + xlab("") +
  facet_grid(~Watershed, scale = "free", space = "free") +
  scale_y_reverse() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, color = "black"),
    axis.text.y = element_text(color = "black"),
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor = element_blank(),
    axis.line.x = element_line(color = "black"),
    axis.line.y = element_line(color = "black"),
    panel.background = element_rect(fill = "white"),
    legend.key=element_blank(),
    legend.title = element_blank(),
    text = element_text(size=18),
    panel.spacing = unit(2, "lines"))
#+scale_x_discrete(labels = Data$site_name)
</code>```

Here's Figure 1:

Here's Figure 2:

答:
The easiest way to reorder these categories is by reordering the factor site_name.  Here is a minimum working example followed by code that should work for your example:

```<code>library(ggplot2)
library(dplyr)

myData <- iris %>% group_by(Species) %>% summarise(MeanSL =mean(Sepal.Length))
typeof(myData$Species)
ggplot(data=myData,aes(x=Species, y=MeanSL)) + geom_point()
myData$Species<- factor(myData$Species, levels=myData$Species[order(- myData$MeanSL)], ordered=TRUE)
ggplot(data=myData,aes(x=Species, y=MeanSL)) + geom_point()
</code>```

In your case this should do the trick:

```<code>Data$site_name <-factor(Data$site_name, levels=Data$site_name[order(- Data$Chla_percent)], ordered=TRUE)

ggplot() +
  geom_point(data = Data, aes(x = site_name, y = Chla_percent), size = 5, color = "blue") +
  ylab ("Chlorophyll a (% difference from Poor threshold)") + xlab("") +
  facet_grid(~Watershed, scale = "free", space = "free") +
  scale_y_reverse() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, color = "black"),
        axis.text.y = element_text(color = "black"),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line.x = element_line(color = "black"),
        axis.line.y = element_line(color = "black"),
        panel.background = element_rect(fill = "white"),
        legend.key=element_blank(),
        legend.title = element_blank(),
        text = element_text(size=18),
        panel.spacing = unit(2, "lines"))
</code>```

Body:
Thanks in advance to anyone who can help me with this. I am making a geom_point graph of chlorophyll concentrations in several lakes (these lakes occur in two different watersheds, which is why I have split them into two facets). I would like these points to be ordered by chlorophyll concentration, from lowest to highest concentration (note: I have flipped the y axis). I have done this, but the problem is, when I order the lakes by chlorophyll concentration, I have to graph "site_order" on the x-axis rather than "site_name." You can see from the hashed-out lines of code that I have tried two different methods for graphing the site_names on the x-axis:

1) I have tried assigning site_name levels to site_order, but this does not work. It produces a graph with lake names for the x-axis categories, but the lakes are not associated with the correct data! I'm not sure how levels() assigns site_name to site_order, but it doesn't do it correctly... (see fig. 1).

2)I have tried labeling the x axis with site_name using scale_x_discrete, but this results in a graph without any labels for x-axis categories (see fig. 2).

My code and a sample dataset are below. If anyone can troubleshoot either of my approaches, or suggest a different approach, I would GREATLY appreciate it!

Here's my sample dataset:

                      Watershed site_order         site_name Morph Chla_percent
1  Six Mile Creek & Schutz Lake         19        Wassermann  Deep   248.571429
2  Six Mile Creek & Schutz Lake         12            Church  Deep    21.428571
3  Six Mile Creek & Schutz Lake          1     Kelser's Pond  Deep  -100.000000
4  Six Mile Creek & Schutz Lake          7           Steiger  Deep    -6.428571
5  Six Mile Creek & Schutz Lake          5            Zumbra  Deep   -40.000000
6  Six Mile Creek & Schutz Lake          4             Stone  Deep   -57.142857
7  Six Mile Creek & Schutz Lake         16       East Auburn  Deep   107.857143
8  Six Mile Creek & Schutz Lake          9       West Auburn  Deep     0.000000
9  Six Mile Creek & Schutz Lake         18            Turbid  Deep   185.714286
10 Six Mile Creek & Schutz Lake         15            Schutz  Deep    84.285714
11              Minnehaha Creek         11           Brownie  Deep    20.285714
12              Minnehaha Creek          2           Calhoun  Deep   -70.714286
13              Minnehaha Creek          6             Cedar  Deep   -33.571429
14              Minnehaha Creek          3           Harriet  Deep   -67.142857
15              Minnehaha Creek          8          Hiawatha  Deep    -1.428571
16              Minnehaha Creek         13 Lake of the Isles  Deep    74.285714
17              Minnehaha Creek         10           Nokomis  Deep    13.571429
18              Minnehaha Creek         17       Powderhorn   Deep   160.714286
19              Minnehaha Creek         14              Taft  Deep    83.571429

Here's my code:

#Import, fix up, and subset data
Data = read.csv("Lakes_data_for_R.csv",
            stringsAsFactors=FALSE)
colnames(Data)[1] <- "Watershed"
Data <- Data[grep("Deep", Data$Morph),]

#Create site_order column (and if possible, assign levels of site_name to site_order)
Data$site_order <- rank(Data$Chla_percent)
#Data$site_order <- as.factor(Data$site_order)
#levels(Data$site_order) <- Data$site_name

#Load ggplot
library(ggplot2)

#Make plot
ggplot() +
  geom_point(data = Data, aes(x = site_order, y = Chla_percent), size = 5, color = "blue") +
  ylab ("Chlorophyll a (% difference from Poor threshold)") + xlab("") +
  facet_grid(~Watershed, scale = "free", space = "free") +
  scale_y_reverse() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, color = "black"),
    axis.text.y = element_text(color = "black"),
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor = element_blank(),
    axis.line.x = element_line(color = "black"),
    axis.line.y = element_line(color = "black"),
    panel.background = element_rect(fill = "white"),
    legend.key=element_blank(),
    legend.title = element_blank(),
    text = element_text(size=18),
    panel.spacing = unit(2, "lines"))
#+scale_x_discrete(labels = Data$site_name)

Here's Figure 1:

Here's Figure 2:

Body:
The easiest way to reorder these categories is by reordering the factor site_name.  Here is a minimum working example followed by code that should work for your example:

library(ggplot2)
library(dplyr)

myData <- iris %>% group_by(Species) %>% summarise(MeanSL =mean(Sepal.Length))
typeof(myData$Species)
ggplot(data=myData,aes(x=Species, y=MeanSL)) + geom_point()
myData$Species<- factor(myData$Species, levels=myData$Species[order(- myData$MeanSL)], ordered=TRUE)
ggplot(data=myData,aes(x=Species, y=MeanSL)) + geom_point()

In your case this should do the trick:

Data$site_name <-factor(Data$site_name, levels=Data$site_name[order(- Data$Chla_percent)], ordered=TRUE)

ggplot() +
  geom_point(data = Data, aes(x = site_name, y = Chla_percent), size = 5, color = "blue") +
  ylab ("Chlorophyll a (% difference from Poor threshold)") + xlab("") +
  facet_grid(~Watershed, scale = "free", space = "free") +
  scale_y_reverse() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, color = "black"),
        axis.text.y = element_text(color = "black"),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line.x = element_line(color = "black"),
        axis.line.y = element_line(color = "black"),
        panel.background = element_rect(fill = "white"),
        legend.key=element_blank(),
        legend.title = element_blank(),
        text = element_text(size=18),
        panel.spacing = unit(2, "lines"))


问:
JSON post doesn't work
I have this code :

```<code>[WebMethod]
public List<string> pubss(string gn)
    {
        List<string> onepub = new List<string>();
        iam_dbEntities db = new iam_dbEntities();
        var message = from i in db.Public_MessageSet where
        i.RoomSet.Room_Name == gn select i;
        foreach(var s in message)
        {
            onepub.Add(s.Sender.ToString());
        }
        return onepub;
    }
</code>```

and this Jquery Code :

```<code>$('#addRoom').click(function () {
 $.ajax({
            type: "POST",
            url: "WebService.asmx/pubss",
            data: "gn=Programmers",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                alert(JSON.toString(data));
            }
    });
});
</code>```

When I click the button I expect some alerts contains information about
the senders but nothing showed, not a single alert.

答:
Try with the following modified code</p>

```<code>$.ajax({
            type: "POST",
            url: "WebService.asmx/pubss",
            data: "{gn:'Programmers'}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                alert(JSON.toString(data));
            }
    });
</code>```

Title: JSON post doesn't work

Body:
I have this code :

[WebMethod]
public List<string> pubss(string gn)
    {
        List<string> onepub = new List<string>();
        iam_dbEntities db = new iam_dbEntities();
        var message = from i in db.Public_MessageSet where
        i.RoomSet.Room_Name == gn select i;
        foreach(var s in message)
        {
            onepub.Add(s.Sender.ToString());
        }
        return onepub;
    }

and this Jquery Code :

$('#addRoom').click(function () {
 $.ajax({
            type: "POST",
            url: "WebService.asmx/pubss",
            data: "gn=Programmers",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                alert(JSON.toString(data));
            }
    });
});

When I click the button I expect some alerts contains information about
the senders but nothing showed, not a single alert.

Body:
Try with the following modified code

$.ajax({
            type: "POST",
            url: "WebService.asmx/pubss",
            data: "{gn:'Programmers'}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                alert(JSON.toString(data));
            }
    });


问:
Wordpress image links 404
Im migrating a wordpress site for the first time. I can get the site to load here: http://www.foureyescomic.com/ by updating the config file and the database table like this:

But now I'm getting images with broken links like this:

答:
You need to update wp_posts table in database. Here is a workaround.

If you the original address is up yet, it is more convenient to use a plugin for migration. Here is a good one.

Title: Wordpress image links 404


问:
What notation to use when accessing an adjacency list?
I'm attempting to do a DFS search on a certain graph, here I have attempted to write down the following code (I'm aware that there are many errors/warnings and mistakes I have made but this is only a start and I need some help).

```<code>int visited[];
static int last=-1;
int record_of_visit[];

void print_dfs(Graph* graph, int source_id)
{
    //printf("not yet implemented: put code for part 1 here\n");
    visited[source_id]=1;
    record_of_visit[++last]=source_id;
    int i;
    for (i=0;i<20;i++)
    {
        if (graph[source_id][i]==1)
        {
            if(visited[i] == 0)
                print_dfs(graph,i);
        }
    }
}
</code>```

The graph.c file implementing the adjacency list can be found here.

The graph.h file can be found here.

Here I am trying to access the graph which is an already built adjacency list, but the compiler would give me error when I run this program indicating that
on if (graph[source_id][i]==1)

subscripted value is neither array nor pointer

What am I doing wrong here? Also any tips or suggestions on what to improve in my still raw DFS implementation would be appreciated!

答: You can access elements of a struct by a "dot", i.e. you can acces n from the first graph in your array by graph[0].n

Body:
I'm attempting to do a DFS search on a certain graph, here I have attempted to write down the following code (I'm aware that there are many errors/warnings and mistakes I have made but this is only a start and I need some help).

int visited[];
static int last=-1;
int record_of_visit[];

void print_dfs(Graph* graph, int source_id)
{
    //printf("not yet implemented: put code for part 1 here\n");
    visited[source_id]=1;
    record_of_visit[++last]=source_id;
    int i;
    for (i=0;i<20;i++)
    {
        if (graph[source_id][i]==1)
        {
            if(visited[i] == 0)
                print_dfs(graph,i);
        }
    }
}

The graph.c file implementing the adjacency list can be found here.

The graph.h file can be found here.

Here I am trying to access the graph which is an already built adjacency list, but the compiler would give me error when I run this program indicating that
on if (graph[source_id][i]==1)

subscripted value is neither array nor pointer

What am I doing wrong here? Also any tips or suggestions on what to improve in my still raw DFS implementation would be appreciated!


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: When DBase II allowed me to print records to a text file AND stick exactly the right typesetting codes pretty much where I wanted -- before them, inside them, behind them, around them. I can still feel the chill on the back of my neck. WOW a whole whole typesetting system right here in my tiny computer! Warm up the 300 baud modem and send this file straight to an 8-inch disk and run it through a Compugraphic. Yards of beautifully shiny photo-type paper with all the letters in the right place. I do not deserve this happiness ...</p>

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: John Turnbull


问:
How to set a value to display for bound properties in WPF design mode?
My bound contents are showed as empty string in the UI design-mode. I want to display some faked value for those contents but I don't know how to.

Please share if you know how to. Thank you!

答:
An easy way to get Design-time-data in Visual Studio 2010 is to use a design-datacontext. Short example with a Window and a ViewModel, For DataContext, the d:DataContext will be used in Design-mode and the StaticResource will be used in runtime. You can also use a separate ViewModel for design but in this example I will use the same ViewModel for both.

```<code><Window ...
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:DesignTimeData"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance local:MyViewModel,
                        IsDesignTimeCreatable=True}">
    <Window.Resources>
        <local:MyViewModel x:Key="MyViewModel" />
    </Window.Resources>
    <Window.DataContext>
        <StaticResource ResourceKey="MyViewModel"/>
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{Binding MyText}"
                 Width="75"
                 Height="25"
                 Margin="6"/>
    </StackPanel>
</Window>
</code>```

And in the ViewModels property MyText we check if we're in design mode and in that case we return something else.

```<code>public class MyViewModel : INotifyPropertyChanged
{
    public MyViewModel()
    {
        MyText = "Runtime-Text";
    }

    private string m_myText;
    public string MyText
    {
        get
        {
            // Or you can use
            // DesignerProperties.GetIsInDesignMode(this)
            if (Designer.IsDesignMode)
            {
                return "Design-Text";
            }
            return m_myText;
        }
        set
        {
            m_myText = value;
            OnPropertyChanged("MyText");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

Designer.cs, which is found here, looks like this

```<code>public static class Designer
{
    private static readonly bool isDesignMode;
    public static bool IsDesignMode
    {
        get { return isDesignMode; }
    }
    static Designer()
    {
        DependencyProperty prop =
            DesignerProperties.IsInDesignModeProperty;
        isDesignMode =
            (bool)DependencyPropertyDescriptor.
                FromProperty(prop, typeof(FrameworkElement))
                      .Metadata.DefaultValue;
    }
}
</code>```

Body:
An easy way to get Design-time-data in Visual Studio 2010 is to use a design-datacontext. Short example with a Window and a ViewModel, For DataContext, the d:DataContext will be used in Design-mode and the StaticResource will be used in runtime. You can also use a separate ViewModel for design but in this example I will use the same ViewModel for both.

<Window ...
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:DesignTimeData"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance local:MyViewModel,
                        IsDesignTimeCreatable=True}">
    <Window.Resources>
        <local:MyViewModel x:Key="MyViewModel" />
    </Window.Resources>
    <Window.DataContext>
        <StaticResource ResourceKey="MyViewModel"/>
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{Binding MyText}"
                 Width="75"
                 Height="25"
                 Margin="6"/>
    </StackPanel>
</Window>

And in the ViewModels property MyText we check if we're in design mode and in that case we return something else.

public class MyViewModel : INotifyPropertyChanged
{
    public MyViewModel()
    {
        MyText = "Runtime-Text";
    }

    private string m_myText;
    public string MyText
    {
        get
        {
            // Or you can use
            // DesignerProperties.GetIsInDesignMode(this)
            if (Designer.IsDesignMode)
            {
                return "Design-Text";
            }
            return m_myText;
        }
        set
        {
            m_myText = value;
            OnPropertyChanged("MyText");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Designer.cs, which is found here, looks like this

public static class Designer
{
    private static readonly bool isDesignMode;
    public static bool IsDesignMode
    {
        get { return isDesignMode; }
    }
    static Designer()
    {
        DependencyProperty prop =
            DesignerProperties.IsInDesignModeProperty;
        isDesignMode =
            (bool)DependencyPropertyDescriptor.
                FromProperty(prop, typeof(FrameworkElement))
                      .Metadata.DefaultValue;
    }
}


问:
How to stop an animation onBackPressed?
In my MainActivity I have 2 animations (FAB and a TAB title) and I would like to stop them onBackPressed.

```<code>@Bind(R.id.fab_text) Button mFAB;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_drawer);

    Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.fab_scale_up_down);
    animation.setRepeatCount(Animation.INFINITE);
    animation.setAnimationListener(new SimpleAnimationListener() {
        private long offset;
        private long startTime;

        @Override
        public void onAnimationStart(Animation animation) {
            startTime = System.currentTimeMillis();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            final long now = System.currentTimeMillis();
            Timber.i("onAnimationRepeatFAB: elapeed seconds: %d", (now - startTime) / 1000);
            if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                animation.setRepeatCount(0);
            } else {
                offset++;
                animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
            }
        }
    });
    mFAB.startAnimation(animation);
</code>```

About the FAB it's easy.

```<code>public void onBackPressed() {
    mFAB.clearAnimation();
</code>```

But how do I stop the other animation defined like this? I don't know how to access the animation of the TAB below.

```<code>private void populateViewPager(List<Tab> tabs) {
    // clear all listeners before populating new tabs
    mTabLayout.setOnTabSelectedListener(null);
    mViewPager.clearOnPageChangeListeners();

    if (mPagerAdapter == null) {
        mPagerAdapter = new TabsPagerAdapter(this, getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
    }

    // populate tabs
    mPagerAdapter.setTabs(tabs);
    if (mPagerAdapter.getCount() > DEFAULT_TAB_POSITION)
        mViewPager.setCurrentItem(DEFAULT_TAB_POSITION);
    mTabLayout.setupWithViewPager(mViewPager);

    // set animation on corresponding tabs
    List<Tab> pagerTabs = mPagerAdapter.getTabs();
    for (int i = 0; i < pagerTabs.size(); i++) {
        Tab pagerTab = pagerTabs.get(i);
        if (pagerTab.isAnimated()) {
            Timber.i("Animating tab: %s", pagerTab.getId());
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                // set custom view in order to get it back then
                tab.setCustomView(R.layout.partial_tab_view);

                // set animation on the custom view
                Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);
                animation.setRepeatCount(Animation.INFINITE);
                animation.setAnimationListener(new SimpleAnimationListener() {
                    private long offset;
                    private long startTime;

                    @Override
                    public void onAnimationStart(Animation animation) {
                        startTime = System.currentTimeMillis();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        final long now = System.currentTimeMillis();
                        Timber.i("onAnimationRepeat: elapeed seconds: %d", (now - startTime) / 1000);
                        if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                            animation.setRepeatCount(0);
                        } else {
                            offset++;
                            animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
                        }
                    }
                });
                //noinspection ConstantConditions
                tab.getCustomView().setAnimation(animation);
            } else {
                Timber.w("tab!=null");
            }
        }
    }
}
</code>```

答:
Declare an Animation object as a global variable. Use cancel() method to cancel the animation.

Try this:

```<code>// Animation
Animation animation;

............
..............

private void populateViewPager(List<Tab> tabs) {
    .................
    ..............................

    animation = AnimationUtils.loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);

    ..............
    .....................
}

@Override
public void onBackPressed() {

    animation.cancel();
    super.onBackPressed();
}
</code>```

Title: How to stop an animation onBackPressed?

Body:
In my MainActivity I have 2 animations (FAB and a TAB title) and I would like to stop them onBackPressed.

@Bind(R.id.fab_text) Button mFAB;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_drawer);

    Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.fab_scale_up_down);
    animation.setRepeatCount(Animation.INFINITE);
    animation.setAnimationListener(new SimpleAnimationListener() {
        private long offset;
        private long startTime;

        @Override
        public void onAnimationStart(Animation animation) {
            startTime = System.currentTimeMillis();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            final long now = System.currentTimeMillis();
            Timber.i("onAnimationRepeatFAB: elapeed seconds: %d", (now - startTime) / 1000);
            if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                animation.setRepeatCount(0);
            } else {
                offset++;
                animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
            }
        }
    });
    mFAB.startAnimation(animation);

About the FAB it's easy.

public void onBackPressed() {
    mFAB.clearAnimation();

But how do I stop the other animation defined like this? I don't know how to access the animation of the TAB below.

private void populateViewPager(List<Tab> tabs) {
    // clear all listeners before populating new tabs
    mTabLayout.setOnTabSelectedListener(null);
    mViewPager.clearOnPageChangeListeners();

    if (mPagerAdapter == null) {
        mPagerAdapter = new TabsPagerAdapter(this, getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
    }

    // populate tabs
    mPagerAdapter.setTabs(tabs);
    if (mPagerAdapter.getCount() > DEFAULT_TAB_POSITION)
        mViewPager.setCurrentItem(DEFAULT_TAB_POSITION);
    mTabLayout.setupWithViewPager(mViewPager);

    // set animation on corresponding tabs
    List<Tab> pagerTabs = mPagerAdapter.getTabs();
    for (int i = 0; i < pagerTabs.size(); i++) {
        Tab pagerTab = pagerTabs.get(i);
        if (pagerTab.isAnimated()) {
            Timber.i("Animating tab: %s", pagerTab.getId());
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                // set custom view in order to get it back then
                tab.setCustomView(R.layout.partial_tab_view);

                // set animation on the custom view
                Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);
                animation.setRepeatCount(Animation.INFINITE);
                animation.setAnimationListener(new SimpleAnimationListener() {
                    private long offset;
                    private long startTime;

                    @Override
                    public void onAnimationStart(Animation animation) {
                        startTime = System.currentTimeMillis();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        final long now = System.currentTimeMillis();
                        Timber.i("onAnimationRepeat: elapeed seconds: %d", (now - startTime) / 1000);
                        if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                            animation.setRepeatCount(0);
                        } else {
                            offset++;
                            animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
                        }
                    }
                });
                //noinspection ConstantConditions
                tab.getCustomView().setAnimation(animation);
            } else {
                Timber.w("tab!=null");
            }
        }
    }
}

Body:
Declare an Animation object as a global variable. Use cancel() method to cancel the animation.

Try this:

// Animation
Animation animation;

............
..............

private void populateViewPager(List<Tab> tabs) {
    .................
    ..............................

    animation = AnimationUtils.loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);

    ..............
    .....................
}

@Override
public void onBackPressed() {

    animation.cancel();
    super.onBackPressed();
}


答:
```<code>var myreturnvalue = true;
$(":radio").each(function(){
    var name = $(this).attr('name');
    var numAnswered = $(":radio").filter('[name='+name+']').filter(":checked").length;
    var notAnswered = numAnswered == 0;
    if(notAnswered){
        alert("Must answer all questions");
        myreturnvalue = false;
        return false;
    }
});
console.log('still goes here even when alert is fired');
return myreturnvalue;
</code>```

Title: Avoid execution goes on in a .each loop


问:
Fatal error: Class 'Magento_Db_Adapter_Pdo_Mysql' not found in /home/xxxx/public_html/xx/xx/includes/src/__default.php on line 29313
i just did all these solution but failed to get solution

777 permission to your magento folder.

chmod 775 lib/Magento/Db/Adapter/Pdo/Mysql.php

答:
I think it's compilation issue.

Disable Magento compiler via SSH

```<code>php -f shell/compiler.php clear
php -f shell/compiler.php disable
</code>```

Then clear cache, if works then compile again

Body:
I think it's compilation issue.

Disable Magento compiler via SSH

php -f shell/compiler.php clear
php -f shell/compiler.php disable

Then clear cache, if works then compile again


问:
Downside of green threads: host kernel thread blocks
I am currently studying operating system and I have difficulties understanding some parts about Implementing Multi-Threaded Processes.

To be specific, the textbook explains that we can implement user-level threads by the system called Per-Processor Kernel Threads. The detailed explanation about this system is below:

When the application starts up, the user-level thread library creates one kernel thread for each processor on the host machine. As long as there is no other activity on the system, the kernel will assign each of these threads a processor. Each kernel thread executes the user-level scheduler in parallel: pull the next thread off the user-level ready list, and run it. Because thread scheduling decisions occur at user level, they can be flexible and application specific.

However, next, it also mentions there are some downsides of this system, which is similar to that of green threads. Some downsides mentioned are below

Any time a user-level thread calls into the kernel, its host kernel thread blocks. This prevents the thread library from running a different user-level thread on that processor in the meantime.

Any time the kernel time-slices a kernel thread, the user-level thread it was running is also suspended. Thi library cannot resume that thread until the kernel thread resumes.

I cannot totally understand both of them.
Here are my questions.

If a user-level thread calls into the kernel, why host kernel thread blocks in this system?

What does kernel time-slices a kernel thread mean?

If kernel time-slices a kernel thread, why user-level thread running is suspended?

Thanks.

答:
What you are describing is sometimes referred to as the many-to-many model in textbooks with the added constraint that the number of kernel threads are limited to the number of processors.

I do not know of ANY operating system that implements threads this way. (If someone out there know of some non-academic Operating system that does threading this way, please enlighten me.) Such a system would be ridiculously convoluted to implement.

There is no real advantage whatsoever to user threads. Sadly, most Operating Systems textbooks are best used a cat box liner. Many insist on describing theoretical (but impracticable) advantages of user threads that simply do not exist in the real world. What is being described is running user threads on top of kernel threads.

This statement is just laughable:

Because thread scheduling decisions occur at user level, they can be flexible and application specific.

a) You are still going to have the [implicitly] inflexible kernel thread underneath.

b) The operating system's implementation of kernel threads would have to be completely inept if one could get better performance with user threads in this manner.

This is total BS:

Any time a user-level thread calls into the kernel, its host kernel thread blocks. This prevents the thread library from running a different user-level thread on that processor in the meantime.

a) There are non-blocking kernel calls.

b) Calling I/O system services in SOME retrograde operating systems blocks user threads. This is not true in all operating systems.

To your specific questions:

If a user-level thread calls into the kernel, why host kernel thread blocks in this system?

See above. It only happens for some system calls in some poorly designed operating systems.

What does kernel time-slices a kernel thread mean?

Yes, that's poor English. In thread scheduling a process is may be given a fixed amount of time ("time slice" or "quantum") that it can execute before the scheduler kicks in to see if another thread should be given a turn to execute. If you have a thread that does long calculations without doing I/O, this time limit prevents that thread from hogging the system.

Why this is a specific drawback of this thread model is beyond me. The same thing happens in pure kernel threads. Or pure user threads.

Sadly, what you have here is a book that is taking simple concepts and making them overly complicated. You have my sympathies.


问:
Transition duration not working for bootstraps thumbnail:hover
I have made the entire thumbnail a link and have specified in the CSS for it to have a transition duration of 0.3s. Unfortunately it does not work. I have tried numerous things, but have not seemed to figured it out.

This is the relevant HTML code:

```<code><div class="row">
    <div class="col-sm-12 col-md-3 col-lg-3"> <a href="https://www.cars.com">
            <div class="thumbnail">
                <img src="car.jpg" alt="Car">
            </div>
        </a>
    </div>
</div>
</code>```

This is the relevant CSS code:

```<code>.thumbnail{
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
    transition-duration: 1s;
}
</code>```

Does anyone know why this is happening / how to fix this? Any help is greatly appreciated.

答:
You are missing the transition property. You need to specify what css property you are trying to animate. It can be all or in this case box-shadow. It should be something like this:

```<code>.thumbnail{
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
    transition-duration: 1s;
    transition-property: box-shadow;

}
</code>```

You can check a working example here:
https://jsbin.com/qosusugige

Good documentation about CSS transitions in MDN.

Body:
I have made the entire thumbnail a link and have specified in the CSS for it to have a transition duration of 0.3s. Unfortunately it does not work. I have tried numerous things, but have not seemed to figured it out.

This is the relevant HTML code:

This is the relevant CSS code:

.thumbnail{
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
    transition-duration: 1s;
}

Does anyone know why this is happening / how to fix this? Any help is greatly appreciated.

Body:
You are missing the transition property. You need to specify what css property you are trying to animate. It can be all or in this case box-shadow. It should be something like this:

.thumbnail{
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
    transition-duration: 1s;
    transition-property: box-shadow;

}

You can check a working example here:
https://jsbin.com/qosusugige

Good documentation about CSS transitions in MDN.


问:
Class Not Found: Empty Test Suite in IntelliJ
I'm just starting the computer science program at my college, and I'm having some issues with IntelliJ. When I try to run unit tests, I get the message

```<code>Process finished with exit code 1
Class not found: "edu.macalester.comp124.hw0.AreaTest"Empty test suite.
</code>```

I also see a message entitled "No tests were found" on the left side of my screen. My test code is here:

```<code>package edu.macalester.comp124.hw0;

import org.junit.Test;
import static org.junit.Assert.*;

public class AreaTest {

    @Test
    public void testSquare() {
    assertEquals(Area.getSquareArea(3.0), 9.0, 0.001);
    }

    @Test
    public void testCircle() {
    assertEquals(Area.getCircleArea(3.0), 28.2743, 0.001);
    }
}
</code>```

And my project code is here:

```<code>package edu.macalester.comp124.hw0;

import java.lang.Math;
public class Area {

/**
 * Calculates the area of a square.
 * @param sideLength The length of the side of a square
 * @return The area
 */
public static double getSquareArea(double sideLength) {
    // Has been replaced by correct formula
    return sideLength * sideLength;
}

/**
 * Calculates the area of a circle.
 * @param radius The radius of the circle
 * @return The area
 */
public static double getCircleArea(double radius) {
    // Replaced by correct value
    return radius * 2 * Math.PI;
}

}
</code>```

How can I get my tests to work?  I'm using the most recent version of IntelliJ IDEA CE.

答:
Does your test require an Android device (emulator or hardware)?

If so, it's called an "instrumented test" and resides in "module-name/src/androidTest/java/".

If not, it's called a "local unit test" and resides in "module-name/src/test/java"

https://developer.android.com/training/testing/start/index.html

I got the same error because I had written a local unit test, but it was placed in the folder for instrumented tests. Moving the local unit test to the "src/test/java" folder fixed it for me.

ContentLicense: CC BY-SA 4.0

Body:
I'm just starting the computer science program at my college, and I'm having some issues with IntelliJ. When I try to run unit tests, I get the message

Process finished with exit code 1
Class not found: "edu.macalester.comp124.hw0.AreaTest"Empty test suite.

I also see a message entitled "No tests were found" on the left side of my screen. My test code is here:

package edu.macalester.comp124.hw0;

import org.junit.Test;
import static org.junit.Assert.*;

public class AreaTest {

    @Test
    public void testSquare() {
    assertEquals(Area.getSquareArea(3.0), 9.0, 0.001);
    }

    @Test
    public void testCircle() {
    assertEquals(Area.getCircleArea(3.0), 28.2743, 0.001);
    }
}

And my project code is here:

package edu.macalester.comp124.hw0;

import java.lang.Math;
public class Area {

/**
 * Calculates the area of a square.
 * @param sideLength The length of the side of a square
 * @return The area
 */
public static double getSquareArea(double sideLength) {
    // Has been replaced by correct formula
    return sideLength * sideLength;
}

/**
 * Calculates the area of a circle.
 * @param radius The radius of the circle
 * @return The area
 */
public static double getCircleArea(double radius) {
    // Replaced by correct value
    return radius * 2 * Math.PI;
}

}

How can I get my tests to work?  I'm using the most recent version of IntelliJ IDEA CE.


问:
ASP NET SQL - select * from where author
I'm having a problem showing equal results from SQL database

```<code>"select * from Log where Author=" + User.Identity.Name
</code>```

That's the current command I've tried, but can't get it working.

while this works:

```<code>"select * from Log where Author='markus'"
</code>```

Thanks for any help.

答:
You can also use string.Format method for this kind of situations.
Try the following.</p>

```<code>string query=string.Format("select * from Log where Author='{0}'",User.Identity.Name)
</code>```

Body:
I'm having a problem showing equal results from SQL database

"select * from Log where Author=" + User.Identity.Name

That's the current command I've tried, but can't get it working.

while this works:

"select * from Log where Author='markus'"

Thanks for any help.

Body:
You can also use string.Format method for this kind of situations.
Try the following.

string query=string.Format("select * from Log where Author='{0}'",User.Identity.Name)


问:
ddd - value objects to cover every property
Implementing an integration with a 3rd party system which exports products and imports orders from a web site.

There is some ddd work already done in the design and to continue it i would like.

Should every single property on the order and products be covered with a value object?

This would mean around 100 classes to cover all possible properties which seems excessive:

ProductSku

ProductName

ProductDescription

ProductPrice

etc...

答:
Should every single property on the order and products be covered with a value object?

They already are.  The real question is whether you are going to leave that covering implicit, or make it explicit.

This would mean around 100 classes to cover all possible properties which seems excessive:

Oh, it has the potential to get much more tangled than that.  ProductPrice, for example, encloses a concept of Money (which it has in common with ComputedTax and RoundedTax), which includes an Amount and a CurrencyCode to denote units).

You may want to give serious consideration to choosing a language in which creating hundreds of different value classes doesn't feel excessive.

See also:

https://fsharpforfunandprofit.com/posts/designing-with-types-making-illegal-states-unrepresentable/

http://blog.ploeh.dk/2016/11/28/easy-domain-modelling-with-types/


答:
Not only is a transition property missing but somewhere in that bootstrap css stylsheet is preventing transition from being effected use !important

```<code>.thumbnail{
  transition:box-shadow 0.3s !important;
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
}
</code>```

Snippet below

.thumbnail{
  transition:box-shadow 0.3s !important;
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="row">
    <div class="col-sm-12 col-md-3 col-lg-3">
            <div class="thumbnail">
                <img src="car.jpg" alt="Car">
            </div>

    </div>
</div></code>```

Title: Transition duration not working for bootstraps thumbnail:hover

Body:
Not only is a transition property missing but somewhere in that bootstrap css stylsheet is preventing transition from being effected use !important

.thumbnail{
  transition:box-shadow 0.3s !important;
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
}

Snippet below

.thumbnail{
  transition:box-shadow 0.3s !important;
    transition-duration: 1s;
}

.thumbnail:hover{
    box-shadow: 5px 5px 5px red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="row">
    <div class="col-sm-12 col-md-3 col-lg-3"> <a href="https://www.cars.com">
            <div class="thumbnail">
                <img src="car.jpg" alt="Car">
            </div>
        </a>
    </div>
</div>


问:
textfield not shown with proper size
I am new to Java and am trying to run this code. What could be error in the following code—my JTextField, txtfld, is shown just as a line instead of as a full text box?

```<code>public class calculator
{
    public static void main(String s[])
    {
        JFrame j=new JFrame();
        j.setSize(400,600);

        JPanel p1=new JPanel();
        JPanel p2=new JPanel();
        p1.setSize(400, 100);
        p2.setSize(400, 500);
        p1.setLocation(0, 0);
        p2.setLocation(0, 100);

        p2.setLayout(new GridLayout(4,4));
        j.add(p1);
        j.add(p2);

        JTextField txtfld=new JTextField();
        txtfld.setSize(390, 92);
        txtfld.setLocation(5, 2);
        //txtfld.setVisible(true);
        p1.add(txtfld);

        j.setVisible(true);

    }
}
</code>```

答:
```<code>JTextField txtfld=new JTextField();
</code>```

You need to give a hint to the layout manager what the size should be.

So you should use something like:

```<code>JTextField txtfld=new JTextField(10);
</code>```

Now the preferred size will be such that 10 "W" characters can be displayed in the text field before scrolling is required.

You should also pack() the frame before making it visible:

```<code>j.pack();
j.setVisible();
</code>```

This will allow the frame to display all the components at their preferred sizes.

Also, get rid of all the setSize() and setLocation() statements. It is the job of the layout manager to set the size and location. Those values will be recalculated by the layout manager.

```<code>j.add(p1);
j.add(p2);
</code>```

The default layout manager for a frame is a BorderLayout. So the above code will cause p2 to replace p1 on the frame.

Basically your entire code is wrong.

Start by reading the section from the Swing tutorial on How to Use Layout Managers for more information and working examples to get you started. Maybe start with the BorderLayout example, since this is the default layout of the frame you need to understand how it works first.

Title: textfield not shown with proper size

Body:
I am new to Java and am trying to run this code. What could be error in the following code—my JTextField, txtfld, is shown just as a line instead of as a full text box?

public class calculator
{
    public static void main(String s[])
    {
        JFrame j=new JFrame();
        j.setSize(400,600);

        JPanel p1=new JPanel();
        JPanel p2=new JPanel();
        p1.setSize(400, 100);
        p2.setSize(400, 500);
        p1.setLocation(0, 0);
        p2.setLocation(0, 100);

        p2.setLayout(new GridLayout(4,4));
        j.add(p1);
        j.add(p2);

        JTextField txtfld=new JTextField();
        txtfld.setSize(390, 92);
        txtfld.setLocation(5, 2);
        //txtfld.setVisible(true);
        p1.add(txtfld);

        j.setVisible(true);

    }
}

Body:
JTextField txtfld=new JTextField();

You need to give a hint to the layout manager what the size should be.

So you should use something like:

JTextField txtfld=new JTextField(10);

Now the preferred size will be such that 10 "W" characters can be displayed in the text field before scrolling is required.

You should also pack() the frame before making it visible:

j.pack();
j.setVisible();

This will allow the frame to display all the components at their preferred sizes.

Also, get rid of all the setSize() and setLocation() statements. It is the job of the layout manager to set the size and location. Those values will be recalculated by the layout manager.

j.add(p1);
j.add(p2);

The default layout manager for a frame is a BorderLayout. So the above code will cause p2 to replace p1 on the frame.

Basically your entire code is wrong.

Start by reading the section from the Swing tutorial on How to Use Layout Managers for more information and working examples to get you started. Maybe start with the BorderLayout example, since this is the default layout of the frame you need to understand how it works first.


问:
How to store array values in a MySQL database
I don't know how to store my array data in database, I only know fetching and displaying data. Any suggestion or discrimination is ok to me because i didn't get the logic and im a noob and newbie

```<code>    <?php
    $cart_statement = "SELECT * FROM user_cart WHERE email = '$email'";
    $cart_res = mysqli_query($con,$cart_statement);
    $storeArray = Array();
    $cart_num = mysqli_num_rows($cart_res);
    while ($cart_row = mysqli_fetch_array($cart_res)) {
        echo $storeArray[] =  $cart_row['product_name'].",";
    }
    ?>
</code>```

mysql table user_cart

|- - - - - - |- - - - - - - - - - - -|

|  cart_id   | product_name  |

| - - - - - -|- - - - - - - - - - - -|

|- - -1 - - |- - -Laptop1 - - - |

|- - -2 - - |- - -Laptop2 - - - |

|- - - - - - |- - - - - - - - - - - -|

output i want is Laptop1,Laptop2

store in tbl_orders

|- - - - - - - |- - - - - - - - - - - - - - - |

|  order_id   | - - - products - - - - -  |

| - - - - - - -|- - - - - - - - - - - - - - - |

|- - -1 - - - |- Laptop1, Laptop2  - |

|- - - - - -  - |- - - - - - - - - - - - - - - |

sorry i dont know how to make tables here

答:
I'm not sure I understand your question. Are you asking how to insert data from an array into multiple rows of your table? For that, you just need to create multiple INSERT queries, one for each array element, and execute them with the proper data bound to them. It's easiest to iterate through the array for this.

For example:

```<code>foreach ($cart_row as $value) {
    $stmt = "INSERT INTO user_cart(ProductName, Qty, Price) VALUES (?, ?, ?)";
    $stmt = mysqli_stmt_prepare($con, $stmt);
    mysqli_stmt_bind_param($stmt, "sii", $value["product_name"], $value["quantity"], $value["price"]);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}
</code>```

Body:
I don't know how to store my array data in database, I only know fetching and displaying data. Any suggestion or discrimination is ok to me because i didn't get the logic and im a noob and newbie

    <?php
    $cart_statement = "SELECT * FROM user_cart WHERE email = '$email'";
    $cart_res = mysqli_query($con,$cart_statement);
    $storeArray = Array();
    $cart_num = mysqli_num_rows($cart_res);
    while ($cart_row = mysqli_fetch_array($cart_res)) {
        echo $storeArray[] =  $cart_row['product_name'].",";
    }
    ?>

mysql table user_cart

|- - - - - - |- - - - - - - - - - - -|

|  cart_id   | product_name  |

| - - - - - -|- - - - - - - - - - - -|

|- - -1 - - |- - -Laptop1 - - - |

|- - -2 - - |- - -Laptop2 - - - |

|- - - - - - |- - - - - - - - - - - -|

output i want is Laptop1,Laptop2

store in tbl_orders

|- - - - - - - |- - - - - - - - - - - - - - - |

|  order_id   | - - - products - - - - -  |

| - - - - - - -|- - - - - - - - - - - - - - - |

|- - -1 - - - |- Laptop1, Laptop2  - |

|- - - - - -  - |- - - - - - - - - - - - - - - |

sorry i dont know how to make tables here

Body:
I'm not sure I understand your question. Are you asking how to insert data from an array into multiple rows of your table? For that, you just need to create multiple INSERT queries, one for each array element, and execute them with the proper data bound to them. It's easiest to iterate through the array for this.

For example:

foreach ($cart_row as $value) {
    $stmt = "INSERT INTO user_cart(ProductName, Qty, Price) VALUES (?, ?, ?)";
    $stmt = mysqli_stmt_prepare($con, $stmt);
    mysqli_stmt_bind_param($stmt, "sii", $value["product_name"], $value["quantity"], $value["price"]);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}


问:
JS google map modify listener from another class
I'm in the middle of converting my google map from ionic-native to JS. I'm trying to modify my map's click listener from another class. Howevever I'm getting property issues.

```<code>this.maps.init(); //Initialize map

this.maps.map.addListener('click', function(pos){

   this.maps.addMarker(pos.latLng.lat(), pos.latLng.lng());//error here

});
</code>```

I'm getting the error

```<code>Cannot read property 'addMarker' of undefined
</code>```

help please

答:
You just need to use arrow functions like this:

```<code>this.maps.init(); //Initialize map

this.maps.map.addListener('click', (pos) => {

   this.maps.addMarker(pos.latLng.lat(), pos.latLng.lng());//error here

});
</code>```

By using arrow functions, the this property is not overwritten and still references the component instance.

Body:
I'm in the middle of converting my google map from ionic-native to JS. I'm trying to modify my map's click listener from another class. Howevever I'm getting property issues.

this.maps.init(); //Initialize map

this.maps.map.addListener('click', function(pos){

   this.maps.addMarker(pos.latLng.lat(), pos.latLng.lng());//error here

});

I'm getting the error

Cannot read property 'addMarker' of undefined

help please

Body:
You just need to use arrow functions like this:

this.maps.init(); //Initialize map

this.maps.map.addListener('click', (pos) => {

   this.maps.addMarker(pos.latLng.lat(), pos.latLng.lng());//error here

});

By using arrow functions, the this property is not overwritten and still references the component instance.