问:
Preventing classes from being instantiated on the stack or as data member
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

```<code>// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };
</code>```

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

```<code>typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };
</code>```

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

```<code>class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));
</code>```

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

```<code>Module m(RingAlertPtr(&m_myRingAlert,[](void *){});
</code>```

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?

答:
I believe the usual solution to make the constructor(s) protected and only allow creation through static (or free friend functions) returning shared_ptr<>. Since the constructor is protected, non-friend code cannot create instances, whether that code tries to construct the instance on the stack or, in a constructor, as a member.

You have to ensure that child classes also make their constructors protected, of course.

Body:
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

Module m(RingAlertPtr(&m_myRingAlert,[](void *){});

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?


来源: stackexchange

问:
In CSS is there any need for backup fonts when applying custom fonts to a webpage?
In CSS why is a backup font recommended if I am uploading a custom font for use with the webpage?

I thought the backup fonts were only needed in case the client doesn't have the 1st/2nd/3rd..etc choice installed.

For example if you have this code:

@font-face {
    font-family: MyCustomFont;
    src: url('../fonts/MyCustomFont.ttf');
}
```

<p>Why is this necessary?</p>

<pre class="lang-css prettyprint-override"><code>body {
    font-family: MyCustomFont, Arial, Helvetica, sans-serif;
}
</code>```

答:
DaveRandom, these would be the only nested while loops involved in the business of computing.

I figured out a way to integrate Google Fonts without any of the problems usually found when 3rd party fonts are used.

First off, we know our Google Fonts files are in the .woff format and may not work in all browsers.

Second, if a Google Cloud or some other molest prevents the download of the font file from our server due to cache restrictions or other network limits we know this pseudo-state of connectivity will likely support the .woff fonts from Google Fonts.

To the credit of Google we may be able to load our images in some other way so why not try a Google Fonts version of our end product.. so here is why not:

In order to insure the font remains the same when adding Google Fonts I recommend not removing the self-hosted fonts unless a verified plaintiff requests you do so for rights ownership reasons.

Instead of removing self-hosted fonts which are the true key to real cross-browser compatibility, create a same-font entry in CSS that specifies it's font title as 3rd party such as: 'ArialVanityGoogleFonts'.
Use the browser's built-in font fallback .csv and include the fonts as follows: ArialVanity, ArialVanityGoogleFonts, Arial

ContentLicense: CC BY-SA 3.0

Body:
In CSS why is a backup font recommended if I am uploading a custom font for use with the webpage?

I thought the backup fonts were only needed in case the client doesn't have the 1st/2nd/3rd..etc choice installed.

For example if you have this code:

@font-face {
    font-family: MyCustomFont;
    src: url('../fonts/MyCustomFont.ttf');
}

Why is this necessary?

body {
    font-family: MyCustomFont, Arial, Helvetica, sans-serif;
}

ContentLicense: CC BY-SA 4.0


问:
How to use aurelia-validate with a object properties to validate?
I'm using aurelia-validate and my validation works fine if I use variables, but I need it to validate properties of an object rather than a variable:

Here's what works:

```<code>  import {Validation} from 'aurelia-validation';
  import {ensure} from 'aurelia-validation';
  import {ItemService} from './service';

  export class EditItem {
    static inject() {
      return [Validation, ItemService];
    }

    @ensure(function(it){
      it.isNotEmpty()
        .hasLengthBetween(3,10);
    })
      name = '';

    @ensure(function(it){
      it.isNotEmpty()
        .hasMinLength(10)
        .matches(/^https?:\/\/.{3,}$/) //looks like a url
        .matches(/^\S*$/); //no spaces
    })
      url = '';

    constructor(validation, service) {
      this.validation = validation.on(this);
      this.service = service;
    }

    activate(params){
      return this.service.getItem(params.id).then(res => {
        console.log(res);
        this.name = res.content.name; //populate
        this.url = res.content.url;
      });
    }

    update() {
      this.validation.validate().then(
        () => {
          var data = {
            name: this.name,
            url: this.url
          };

          this.service.updateItem(data).then(res => {
            this.message = "Thank you!";
          })
        }
      );
    }
  }
</code>```

Here's what I'm trying to do (but doesn't work)...also I'm not sure if it's better to keep the properties on the class or have a property called this.item which contains the properties (this is the typical angular way):

```<code>  import {Validation} from 'aurelia-validation';
  import {ensure} from 'aurelia-validation';
  import {ItemService} from './service';

  export class EditItem {
    static inject() {
      return [Validation, ItemService];
    }

    @ensure(function(it){
      it.isNotEmpty()
        .hasLengthBetween(3,10);
    })
      this.item.name; //no assignment here should happen

    @ensure(function(it){
      it.isNotEmpty()
        .hasMinLength(10)
        .matches(/^https?:\/\/.{3,}$/) //looks like a url
        .matches(/^\S*$/); //no spaces
    })
      this.item.url; //no assignment?

    constructor(validation, service) {
      this.validation = validation.on(this);
      this.service = service;
      this.item = null;
    }

    activate(params){
      return this.service.getItem(params.id).then(res => {
        console.log(res);
        this.item = res.content; //populate with object from api call
      });
    }

    update() {
      this.validation.validate().then(
        () => {
          var data = {
            name: this.item.name,
            url: this.item.url
          };

          this.service.updateItem(data).then(res => {
            this.message = "Thank you!";
          })
        }
      );
    }
  }
</code>```

Can someone give me some guidance here on how to use a validator against an existing object (for an edit page)?

答:
Use the .on method of the validator to apply your rules to object properties.

The example below is called after I retrieve an object named stock, it validates that the quantity is not empty and is numeric only.  Hope this helps...

```<code>let stock = {
  name: 'some name'
  minimumQuantity: '1'
};

applyRules() {
  ValidationRules
    .ensure((m: EditStock) => m.minimumQuantity)
    .displayName("Minimum Quantity")
    .required()
    .withMessage(`\${$displayName} cannot be blank.`)
    .matches( /^[0-9]*$/)
    .withMessage(`\${$displayName} must be numeric only.`)

  .on(this.stock);
}
</code>```

Body:
I'm using aurelia-validate and my validation works fine if I use variables, but I need it to validate properties of an object rather than a variable:

Here's what works:

  import {Validation} from 'aurelia-validation';
  import {ensure} from 'aurelia-validation';
  import {ItemService} from './service';

  export class EditItem {
    static inject() {
      return [Validation, ItemService];
    }

    @ensure(function(it){
      it.isNotEmpty()
        .hasLengthBetween(3,10);
    })
      name = '';

    @ensure(function(it){
      it.isNotEmpty()
        .hasMinLength(10)
        .matches(/^https?:\/\/.{3,}$/) //looks like a url
        .matches(/^\S*$/); //no spaces
    })
      url = '';

    constructor(validation, service) {
      this.validation = validation.on(this);
      this.service = service;
    }

    activate(params){
      return this.service.getItem(params.id).then(res => {
        console.log(res);
        this.name = res.content.name; //populate
        this.url = res.content.url;
      });
    }

    update() {
      this.validation.validate().then(
        () => {
          var data = {
            name: this.name,
            url: this.url
          };

          this.service.updateItem(data).then(res => {
            this.message = "Thank you!";
          })
        }
      );
    }
  }

Here's what I'm trying to do (but doesn't work)...also I'm not sure if it's better to keep the properties on the class or have a property called this.item which contains the properties (this is the typical angular way):

  import {Validation} from 'aurelia-validation';
  import {ensure} from 'aurelia-validation';
  import {ItemService} from './service';

  export class EditItem {
    static inject() {
      return [Validation, ItemService];
    }

    @ensure(function(it){
      it.isNotEmpty()
        .hasLengthBetween(3,10);
    })
      this.item.name; //no assignment here should happen

    @ensure(function(it){
      it.isNotEmpty()
        .hasMinLength(10)
        .matches(/^https?:\/\/.{3,}$/) //looks like a url
        .matches(/^\S*$/); //no spaces
    })
      this.item.url; //no assignment?

    constructor(validation, service) {
      this.validation = validation.on(this);
      this.service = service;
      this.item = null;
    }

    activate(params){
      return this.service.getItem(params.id).then(res => {
        console.log(res);
        this.item = res.content; //populate with object from api call
      });
    }

    update() {
      this.validation.validate().then(
        () => {
          var data = {
            name: this.item.name,
            url: this.item.url
          };

          this.service.updateItem(data).then(res => {
            this.message = "Thank you!";
          })
        }
      );
    }
  }

Can someone give me some guidance here on how to use a validator against an existing object (for an edit page)?

Body:
Use the .on method of the validator to apply your rules to object properties.

The example below is called after I retrieve an object named stock, it validates that the quantity is not empty and is numeric only.  Hope this helps...

let stock = {
  name: 'some name'
  minimumQuantity: '1'
};

applyRules() {
  ValidationRules
    .ensure((m: EditStock) => m.minimumQuantity)
    .displayName("Minimum Quantity")
    .required()
    .withMessage(`\${$displayName} cannot be blank.`)
    .matches( /^[0-9]*$/)
    .withMessage(`\${$displayName} must be numeric only.`)

  .on(this.stock);
}


问:
Define Column type in xml file to use as Crystal report data source
I use this XML file as data source for my crystal report.

```<code><Person>
    <name></Name>
    <Family></Family>
    <BirthDate type="datetime"></BirthDate>
</Person>
</code>```

But when I use this as data source and crystal report engine generates my report columns according to given XML , I see that the BirthDate field is a string. I can not change its type , and I think maybe there is a problem with my XML format

Is there any body to help me?!
Thanks

答:
Probably too late, but I hope this helps those looking for an answer now.
Instead of using a xml, use a xsd. Following your example, it'd be like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Person" nillable="true" type="Person" />
  <xs:complexType name="Person">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="Family" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="BirthDate" type="xs:dateTime" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>
</code>```

Crystal Report will identify the type of the birthdate correctly.

Body:
I use this XML file as data source for my crystal report.

<Person>
    <name></Name>
    <Family></Family>
    <BirthDate type="datetime"></BirthDate>
</Person>

But when I use this as data source and crystal report engine generates my report columns according to given XML , I see that the BirthDate field is a string. I can not change its type , and I think maybe there is a problem with my XML format

Is there any body to help me?!
Thanks

Body:
Probably too late, but I hope this helps those looking for an answer now.
Instead of using a xml, use a xsd. Following your example, it'd be like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Person" nillable="true" type="Person" />
  <xs:complexType name="Person">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="Family" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="BirthDate" type="xs:dateTime" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Crystal Report will identify the type of the birthdate correctly.


问:
Django templates {% regroup %} : handle the case when grouper value is None
Currently working on a e-commerce project (with django-oscar), I have an issue regarding products display on the basket template.

I use the {% regroup %} tag because I have several types of products : standalone, parent or children. Each basket line corresponds to a product, and if several of them are children sharing the same parent product, I want them to be regrouped under their common parent. However, I want standalone products to stand on their own.

My queryset is the following :

```<code>in_stock_lines = request.basket \
    .all_lines() \
    .order_by('product__parent', 'date_created') \
    .filter(attached_to=None, product__product_class__name='Produit standard', is_customized=False)
</code>```

In basket.html:

```<code>{% regroup in_stock_lines by product.parent as parent_list %}
    {% for parent in parent_list %}
        {% if parent.grouper %}
            {% include "basket/partials/_basket_non_customized_product.html" %}
        {% else %}
            {% include "basket/partials/_basket_non_customized_standalone_product.html" %}
        {% endif %}
    {% endfor %}
</code>```

The thing is that I don't want the regroup to act in the {% else %} part, because they are standalone products and are not supposed to be regrouped. But as their product.parent, i.e. the grouper is None, they are.

Is there way to prevent the {% regroup %} to act for a certain grouper value ? I could make two distinct queries in my views.py to separate standalone products from the others, and not include their template in the {% regroup %}, but I would like to avoid to make two queries if it can be.

Any help appreciated ! This is my first question on Stackoverflow, sorry if I miss some basic rules about the way I ask it.

答:
I don't think that is something you can do in the template directly. Django deliberately limits the 'tools' available in its template language to discourage putting too much logic in the templates.

Whilst you could do the work in views.py, as what you're doing is quite presentational, I would suggest a custom template tag (more specifically an inclusion tag) is probably what you want.

You should be able to avoid multiple queries as the grouping logic is quite simple. I'd suggest looking at collections.defaultdict for simple grouping.

Body:
Currently working on a e-commerce project (with django-oscar), I have an issue regarding products display on the basket template.

I use the {% regroup %} tag because I have several types of products : standalone, parent or children. Each basket line corresponds to a product, and if several of them are children sharing the same parent product, I want them to be regrouped under their common parent. However, I want standalone products to stand on their own.

My queryset is the following :

in_stock_lines = request.basket \
    .all_lines() \
    .order_by('product__parent', 'date_created') \
    .filter(attached_to=None, product__product_class__name='Produit standard', is_customized=False)

In basket.html:

{% regroup in_stock_lines by product.parent as parent_list %}
    {% for parent in parent_list %}
        {% if parent.grouper %}
            {% include "basket/partials/_basket_non_customized_product.html" %}
        {% else %}
            {% include "basket/partials/_basket_non_customized_standalone_product.html" %}
        {% endif %}
    {% endfor %}

The thing is that I don't want the regroup to act in the {% else %} part, because they are standalone products and are not supposed to be regrouped. But as their product.parent, i.e. the grouper is None, they are.

Is there way to prevent the {% regroup %} to act for a certain grouper value ? I could make two distinct queries in my views.py to separate standalone products from the others, and not include their template in the {% regroup %}, but I would like to avoid to make two queries if it can be.

Any help appreciated ! This is my first question on Stackoverflow, sorry if I miss some basic rules about the way I ask it.


问:
Issue while performing the Get-Object Operation in S3 using AWSCLI
I am trying to perform Get-Object operation in AWS. To achieve this, I have followed the below link:

http://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html

By following this, I have tried executing the below command from my CLI:

aws s3api get-object --bucket test-bucket-1 --key test-object sample.zip

where,

test-bucket-1 is the name of my bucket,
test-object is the name of my object,
sample.zip is the zip file where I want the contents to be downloaded to.

By doing this, I get the following error:

An error occurred (Invalid Token) when calling the GetObject operation: The provided token is malformed or otherwise invalid.

The user by whom I am performing this action has the following policy attached:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
</code>```

}

Am I passing any parameter wrong? Please let me know.

答:
Even you set the region when you ran aws configure, you will need to set it again with this command (set the region of bucket ) :

```<code>aws s3api get-object --bucket test-bucket-1 --key test-object sample.zip --region <BUCKET-REGION>
</code>```

It seems weird , but I encountered similar issue before, and the resolution is what I explained.

Of course, the answer assumes you have the right permissions (policy) to access the bucket since you are saying you have Admin access.

Body:
I am trying to perform Get-Object operation in AWS. To achieve this, I have followed the below link:

http://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html

By following this, I have tried executing the below command from my CLI:

aws s3api get-object --bucket test-bucket-1 --key test-object sample.zip

where,

test-bucket-1 is the name of my bucket,
test-object is the name of my object,
sample.zip is the zip file where I want the contents to be downloaded to.

By doing this, I get the following error:

An error occurred (Invalid Token) when calling the GetObject operation: The provided token is malformed or otherwise invalid.

The user by whom I am performing this action has the following policy attached:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]

}

Am I passing any parameter wrong? Please let me know.

Body:
Even you set the region when you ran aws configure, you will need to set it again with this command (set the region of bucket ) :

aws s3api get-object --bucket test-bucket-1 --key test-object sample.zip --region <BUCKET-REGION>

It seems weird , but I encountered similar issue before, and the resolution is what I explained.

Of course, the answer assumes you have the right permissions (policy) to access the bucket since you are saying you have Admin access.


问:
how to extract one element from nested list as vector - R twitteR package
I have a nested list of 'twitteR' user objects, whereby the 1st level of the list is a given user-id, e.g. 000000000, and the second level is a number of attributes for that entry, e.g. description or name. There are n list elements, and for each of these elements, the exact same variables/attributes exist.

What I want to do, is to extract one particular attribute/variable for every 1st order element of the list and save it to a character vector.

I can do this with a for loop, but this takes forever, and I'd really like for it to be more efficient, as I want to extract these variables for a huge amount of similar lists.

So, this is what the data i have looks like at the moment, let's assume my list is called list:

```<code>> list$`00000000`$description
[1] "bla bla bla bla"
> list$`00000001`$description
[1] "blub blub blub"
> list$`00000002`$description
[1] "pim pim pim"
</code>```

and this is what i'd like to have

```<code>> description
[1] "bla bla bla bla" "blub blub blub" "pim pim pim"
> class(description)
[1] "character"
</code>```

Is there a way of elegantly doing this in as few lines as possible, without the need for a for-loop?
Thanks in advance!

答:
Using the rlist library, you can use functions like select or filter on lists:

```<code>library(rlist)
# Sample data
twitterers <- list("0" = list(descr = "bla", other = 11), "1" = list(descr = "blu", other = 20))
# list.select returns a list, so you unlist it and convert it to a vector to have the desired output
as.vector(unlist(list.select(twitterers, descr)))
</code>```

Result:

```<code>[1] "bla" "blu"
</code>```

Body:
I have a nested list of 'twitteR' user objects, whereby the 1st level of the list is a given user-id, e.g. 000000000, and the second level is a number of attributes for that entry, e.g. description or name. There are n list elements, and for each of these elements, the exact same variables/attributes exist.

What I want to do, is to extract one particular attribute/variable for every 1st order element of the list and save it to a character vector.

I can do this with a for loop, but this takes forever, and I'd really like for it to be more efficient, as I want to extract these variables for a huge amount of similar lists.

So, this is what the data i have looks like at the moment, let's assume my list is called list:

> list$`00000000`$description
[1] "bla bla bla bla"
> list$`00000001`$description
[1] "blub blub blub"
> list$`00000002`$description
[1] "pim pim pim"

and this is what i'd like to have

> description
[1] "bla bla bla bla" "blub blub blub" "pim pim pim"
> class(description)
[1] "character"

Is there a way of elegantly doing this in as few lines as possible, without the need for a for-loop?
Thanks in advance!

Body:
Using the rlist library, you can use functions like select or filter on lists:

library(rlist)
# Sample data
twitterers <- list("0" = list(descr = "bla", other = 11), "1" = list(descr = "blu", other = 20))
# list.select returns a list, so you unlist it and convert it to a vector to have the desired output
as.vector(unlist(list.select(twitterers, descr)))

Result:

[1] "bla" "blu"


问:
How can I grab the Swift REPL compiler errors in JSON format
I'm looking to grab Swift compiler errors from the Swift REPL in a readable format such as JSON or XML

The best I can do is read it in as a String via standard in/out pipes. I have tried nearly every argument/option with swiftc with no luck.

I read that I can write Python scripts that extend LLDB but I wouldn't know where to start.

Currently the format reads in as:

```<code>/Users/joeblow/Desktop/pre-compiled.swift:1:38: error: cannot convert value of type 'Int' to specified type 'String'
var age = 10; var name: String = 12;
                                 ^~
</code>```

But I'm interested moreso in something like this:

```<code>{
  path: "/Users/joeblow/Desktop/compiled.swift",
  line: 1,
  position: 38,
  error: "cannot convert value of type 'Int' to specified type 'String'"
}
</code>```

I do not want to use Regex/String manipulation.

答:
The swift compiler accepts the -parseable-output flag, which produces a structured output including the errors.  For instance, if wrong.swift has the contents of your example, I see:

```<code> > swiftc -g -Onone -parseable-output wrong.swift
1149
{
  "kind": "began",
  "name": "compile",
  "command": "\/Applications\/Xcode.app\/Contents\/Developer\/Toolchains\/XcodeDefault.xctoolchain\/usr\/bin\/swift -frontend -c -primary-file wrong.swift -target x86_64-apple-macosx10.9 -enable-objc-interop -sdk \/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/MacOSX.platform\/Developer\/SDKs\/MacOSX10.13.sdk -g -emit-module-doc-path \/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftdoc -color-diagnostics -Onone -module-name wrong -emit-module-path \/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftmodule -o \/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.o",
  "inputs": [
    "wrong.swift"
  ],
  "outputs": [
    {
      "type": "object",
      "path": "\/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.o"
    },
    {
      "type": "swiftmodule",
      "path": "\/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftmodule"
    },
    {
      "type": "swiftdoc",
      "path": "\/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftdoc"
    }
  ],
  "pid": 33440
}
306
{
  "kind": "finished",
  "name": "compile",
  "pid": 33440,
  "output": "\u001B[1mwrong.swift:1:21: \u001B[0;1;31merror: \u001B[0m\u001B[1mcannot convert value of type 'Int' to specified type 'String'\n\u001B[0mvar name : String = 12\n\u001B[0;1;32m                    ^~\n\u001B[0m",
  "exit-status": 1
}
</code>```

However, while the REPL uses a swift compiler instance for parsing your expressions, it doesn't have a way to accept and pass "extra flags" to that compiler, so at present I don't think there's any way to get the REPL to emit errors in this form.

If you're interested in this capability then please file an enhancement request with the swift.org JIRA.  If you are adventurous, you could even try adding it yourself.  You would have to get the swift driver to pass this option to lldb, and then get lldb to parse and pass it to its compiler.  Probably also have to extract only the errors from the output or it would be too noisy.

Body:
I'm looking to grab Swift compiler errors from the Swift REPL in a readable format such as JSON or XML

The best I can do is read it in as a String via standard in/out pipes. I have tried nearly every argument/option with swiftc with no luck.

I read that I can write Python scripts that extend LLDB but I wouldn't know where to start.

Currently the format reads in as:

/Users/joeblow/Desktop/pre-compiled.swift:1:38: error: cannot convert value of type 'Int' to specified type 'String'
var age = 10; var name: String = 12;
                                 ^~

But I'm interested moreso in something like this:

{
  path: "/Users/joeblow/Desktop/compiled.swift",
  line: 1,
  position: 38,
  error: "cannot convert value of type 'Int' to specified type 'String'"
}

I do not want to use Regex/String manipulation.

Body:
The swift compiler accepts the -parseable-output flag, which produces a structured output including the errors.  For instance, if wrong.swift has the contents of your example, I see:

 > swiftc -g -Onone -parseable-output wrong.swift
1149
{
  "kind": "began",
  "name": "compile",
  "command": "\/Applications\/Xcode.app\/Contents\/Developer\/Toolchains\/XcodeDefault.xctoolchain\/usr\/bin\/swift -frontend -c -primary-file wrong.swift -target x86_64-apple-macosx10.9 -enable-objc-interop -sdk \/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/MacOSX.platform\/Developer\/SDKs\/MacOSX10.13.sdk -g -emit-module-doc-path \/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftdoc -color-diagnostics -Onone -module-name wrong -emit-module-path \/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftmodule -o \/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.o",
  "inputs": [
    "wrong.swift"
  ],
  "outputs": [
    {
      "type": "object",
      "path": "\/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.o"
    },
    {
      "type": "swiftmodule",
      "path": "\/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftmodule"
    },
    {
      "type": "swiftdoc",
      "path": "\/var\/folders\/zc\/dp8ptx_10pg8m6pnwpbnjms00000gp\/T\/wrong-bc5f07.swiftdoc"
    }
  ],
  "pid": 33440
}
306
{
  "kind": "finished",
  "name": "compile",
  "pid": 33440,
  "output": "\u001B[1mwrong.swift:1:21: \u001B[0;1;31merror: \u001B[0m\u001B[1mcannot convert value of type 'Int' to specified type 'String'\n\u001B[0mvar name : String = 12\n\u001B[0;1;32m                    ^~\n\u001B[0m",
  "exit-status": 1
}

However, while the REPL uses a swift compiler instance for parsing your expressions, it doesn't have a way to accept and pass "extra flags" to that compiler, so at present I don't think there's any way to get the REPL to emit errors in this form.

If you're interested in this capability then please file an enhancement request with the swift.org JIRA.  If you are adventurous, you could even try adding it yourself.  You would have to get the swift driver to pass this option to lldb, and then get lldb to parse and pass it to its compiler.  Probably also have to extract only the errors from the output or it would be too noisy.


问:
VBA Select Multiple Tabs in Spreadsheet using code
I have a spreadsheet with 3 tabs. I need the following code to select the first two tabs. I almost have it but the Sheets(Array(c)).Select portion returns an error. Essentially i need the last section to return as Sheets(Array("Sheet1", "Sheet2")).Select

```<code>Sub HideUnhide2()
Dim a As String
Dim b As Double
Dim c As String
Application.Calculation = xlManual
        For I = 1 To 100
            If Range("d5") <> "Entity:" Then Exit For
            'Start
            c = c & ", " & Chr(34) & ActiveSheet.Name & Chr(34)

            'End
            b = b + 1

            ActiveSheet.Next.Select
        Next I
    '   End If
           c = Right(c, Len(c) - 2)
           MsgBox c
           Sheets(Array(c)).Select

Application.Calculation = xlAutomatic
MsgBox "Total tabs updated = " & b

End Sub
</code>```

Any help is appreciated.

答:
How about this?</p>

```<code>Sub SelectTabs()

    Dim numSheets As Integer
    numSheets = 5
    Dim aSheets() As String
    ReDim aSheets(numSheets - 1)

    For i = 0 To numSheets - 1
        aSheets(i) = ActiveWorkbook.Worksheets(i + 1).Name
    Next i

    ActiveWorkbook.Worksheets(aSheets()).Select

End Sub
</code>```

Body:
I have a spreadsheet with 3 tabs. I need the following code to select the first two tabs. I almost have it but the Sheets(Array(c)).Select portion returns an error. Essentially i need the last section to return as Sheets(Array("Sheet1", "Sheet2")).Select

Sub HideUnhide2()
Dim a As String
Dim b As Double
Dim c As String
Application.Calculation = xlManual
        For I = 1 To 100
            If Range("d5") <> "Entity:" Then Exit For
            'Start
            c = c & ", " & Chr(34) & ActiveSheet.Name & Chr(34)

            'End
            b = b + 1

            ActiveSheet.Next.Select
        Next I
    '   End If
           c = Right(c, Len(c) - 2)
           MsgBox c
           Sheets(Array(c)).Select

Application.Calculation = xlAutomatic
MsgBox "Total tabs updated = " & b

End Sub

Any help is appreciated.

Body:
How about this?

Sub SelectTabs()

    Dim numSheets As Integer
    numSheets = 5
    Dim aSheets() As String
    ReDim aSheets(numSheets - 1)

    For i = 0 To numSheets - 1
        aSheets(i) = ActiveWorkbook.Worksheets(i + 1).Name
    Next i

    ActiveWorkbook.Worksheets(aSheets()).Select

End Sub


问:
Inserting module with controller in function AngularJS
why if I insert angular module with controller into function, angularjs stop working?</p>

```<code>(function() {
      var app = angular.module("app", []);

      app.controller("c1", function($scope){

          $scope.name = "Hello World!";

      });
 });
</code>```

答:
You neglected the code of the IIFE (parenthesis at the end: () ).

Below there is a snippet with your sample corrected.

(function() {
  var app = angular.module("app", []);

  app.controller("c1", function($scope){

  $scope.name = "Hello World!";

  });
})(); //<< -- here!! See the closing ()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="c1">
{{name}}
</div></code>```

You can read more about IIFE here:

What is the (function() { } )() construct in JavaScript?

https://en.wikipedia.org/wiki/Immediately-invoked_function_expression

Body:
why if I insert angular module with controller into function, angularjs stop working?

(function() {
      var app = angular.module("app", []);

      app.controller("c1", function($scope){

          $scope.name = "Hello World!";

      });
 });

Body:
You neglected the code of the IIFE (parenthesis at the end: () ).

Below there is a snippet with your sample corrected.

(function() {
  var app = angular.module("app", []);

  app.controller("c1", function($scope){

  $scope.name = "Hello World!";

  });
})(); //<< -- here!! See the closing ()

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="c1">
{{name}}
</div>

You can read more about IIFE here:

What is the (function() { } )() construct in JavaScript?

https://en.wikipedia.org/wiki/Immediately-invoked_function_expression


问:
two or more range inputs sharing one (the same) Max value in HTML
To give you an image of what I am trying to do, know that browser strategy real time games page when you can recruit units using an range input (or ui slider)? Something like this...
 I am trying to make some range inputs that should share the same max value (which is given dynamically by an ajax call). For example if I have value 10, when I change first range at value 3, rests of ranges will have max value 7 now. If I change value to second range at 2, rests will have now max 5...
I should simplify this for the moment with only 3 ranges (but will be more, like 14).

```<code><input type="range" id="wpike" min="0" max="" value="0"><button>V</button>
<input type="range" id="waxe" min="0" max="" value="0"><button>V</button>
<input type="range" id="wsword" min="0" max="" value="0"><button>V</button>
</code>```

Variable $rangemax will be given in ajax call and put in every range input max value... I tried to make an onchange event using ranges class, but that will trigger it over the actual range changed (minimizing its max value irremediable).

```<code>$('.ceva').on('change input', function () {
    var $rangemax = // $rangemax - wpike val - waxe val - wsword val(orientative)
        $('ceva').attr('max', $rangemax);
});
</code>```

I can do an onchange function for each id separately like: when I change its value, change atrr max for every id (excluding changed id)... But this will result huge code, considering i should have like 14 ranges...
Or I can have an invisible input... When page is loaded, I fill its value with $rangemax. Ranges will have max Then $(ceva).on(change - insert in the input value ($rangemax-waxe.val()-wpike.val()-so on... Then set max attr of $(ceva) as insert element value?  Would be more elegant...but..not enought?:D

答:
I solved it, was so simple...just math...sorry for my incompetence, I will let this here, maybe someone would find it useful.

```<code><input type="range" class="ceva" id="a" min="0" max="10" value="0">
<input type="range" class="ceva" id="b" min="0" max="10" value="0">
<input type="range" class="ceva" id="c" min="0" max="10" value="0">

 $(".ceva").on("change", function(){
 var maxi = 10;
 var a = $("#a").val();
 var b = $("#b").val();
 var c = $("#c").val();
 $('#a').attr("max" , (maxi - b - c));
 $('#b').attr("max" , (maxi - a - c));
 $('#c').attr("max" , (maxi - a - b));
 });
</code>```

Now I have to work on part where I have 3 resources and different costs for every soldier.

Body:
To give you an image of what I am trying to do, know that browser strategy real time games page when you can recruit units using an range input (or ui slider)? Something like this...
 I am trying to make some range inputs that should share the same max value (which is given dynamically by an ajax call). For example if I have value 10, when I change first range at value 3, rests of ranges will have max value 7 now. If I change value to second range at 2, rests will have now max 5...
I should simplify this for the moment with only 3 ranges (but will be more, like 14).

<input type="range" id="wpike" min="0" max="" value="0"><button>V</button>
<input type="range" id="waxe" min="0" max="" value="0"><button>V</button>
<input type="range" id="wsword" min="0" max="" value="0"><button>V</button>

Variable $rangemax will be given in ajax call and put in every range input max value... I tried to make an onchange event using ranges class, but that will trigger it over the actual range changed (minimizing its max value irremediable).

$('.ceva').on('change input', function () {
    var $rangemax = // $rangemax - wpike val - waxe val - wsword val(orientative)
        $('ceva').attr('max', $rangemax);
});

I can do an onchange function for each id separately like: when I change its value, change atrr max for every id (excluding changed id)... But this will result huge code, considering i should have like 14 ranges...
Or I can have an invisible input... When page is loaded, I fill its value with $rangemax. Ranges will have max Then $(ceva).on(change - insert in the input value ($rangemax-waxe.val()-wpike.val()-so on... Then set max attr of $(ceva) as insert element value?  Would be more elegant...but..not enought?:D

Body:
I solved it, was so simple...just math...sorry for my incompetence, I will let this here, maybe someone would find it useful.

<input type="range" class="ceva" id="a" min="0" max="10" value="0">
<input type="range" class="ceva" id="b" min="0" max="10" value="0">
<input type="range" class="ceva" id="c" min="0" max="10" value="0">

 $(".ceva").on("change", function(){
 var maxi = 10;
 var a = $("#a").val();
 var b = $("#b").val();
 var c = $("#c").val();
 $('#a').attr("max" , (maxi - b - c));
 $('#b').attr("max" , (maxi - a - c));
 $('#c').attr("max" , (maxi - a - b));
 });

Now I have to work on part where I have 3 resources and different costs for every soldier.


问:
For Loop in Array (Java) Index Out of Bounds
I'm having a hard time using an array in a for loop that is supposed to cube numbers 1-9 in descending order. I keep getting an out of bounds error and the cubed values are completely off. I would greatly appreciate an explanation as to where I am going wrong with thinking about arrays. I believe the issue is with my index, but I'm struggling to explain why.

```<code>System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
    System.out.println();
    // Create array
    int[] values = new int[11];
    int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to count in descending order
    for (int counter = 9; counter < moreValues.length; counter--)
    {
        cubedNumber = Math.pow(counter,3);
        System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
    }
</code>```

Output

答:
Your main bug is the loop termination condition counter < moreValues.length, which if you're counting down will always be true.

Instead, check for the index being at or above zero:

```<code>for (int counter = 9; counter >= 0; counter--)
</code>```

Your other bug is you're cubing the index, not the number pointed to by the index, so code this instead;

```<code>cubedNumber = Math.pow(moreValues[counter], 3);
</code>```

To reduce confusion, you're better using an industry standard name for the loop variable, like i or where the loop variable is being used as an index to an array, index is often used and can improve code clarity.

Body:
I'm having a hard time using an array in a for loop that is supposed to cube numbers 1-9 in descending order. I keep getting an out of bounds error and the cubed values are completely off. I would greatly appreciate an explanation as to where I am going wrong with thinking about arrays. I believe the issue is with my index, but I'm struggling to explain why.

System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
    System.out.println();
    // Create array
    int[] values = new int[11];
    int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to count in descending order
    for (int counter = 9; counter < moreValues.length; counter--)
    {
        cubedNumber = Math.pow(counter,3);
        System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
    }

Output

Body:
Your main bug is the loop termination condition counter < moreValues.length, which if you're counting down will always be true.

Instead, check for the index being at or above zero:

for (int counter = 9; counter >= 0; counter--)

Your other bug is you're cubing the index, not the number pointed to by the index, so code this instead;

cubedNumber = Math.pow(moreValues[counter], 3);

To reduce confusion, you're better using an industry standard name for the loop variable, like i or where the loop variable is being used as an index to an array, index is often used and can improve code clarity.


问:
adding object dynamically in live a-frame camera view

I am trying to place an image in a-frame camera view.  please share an example.

答:
A quick way to do this is to add an invisible "marker" as a child of the camera, and use its position as the spawn point when adding an object.

HTML

```<code><a-scene>
  <a-camera>
    <a-entity id="marker" position="0 0 -5"></a-entity>
  </a-camera>
  <a-cylinder id="floor" height="0.1" radius="10" color="green"></a-cylinder>
</a-scene>
</code>```

JS

```<code>var sceneEl = document.querySelector('a-scene');
var markerEl = document.querySelector('#marker');

// Add boxe when spacebar is pressed.
document.addEventListener('keyup', function (e) {
  if (e.keyCode !== 32) return;

  var newEl = document.createElement('a-box');
  newEl.setAttribute('color', 'red');
  sceneEl.appendChild(newEl);
  var position = markerEl.object3D.getWorldPosition();
  position.y = 0.5;
  newEl.setAttribute('position', position);
});
</code>```

Codepen: https://codepen.io/donmccurdy/pen/QOOXbK?editors=1010

Body:
A quick way to do this is to add an invisible "marker" as a child of the camera, and use its position as the spawn point when adding an object.

HTML

<a-scene>
  <a-camera>
    <a-entity id="marker" position="0 0 -5"></a-entity>
  </a-camera>
  <a-cylinder id="floor" height="0.1" radius="10" color="green"></a-cylinder>
</a-scene>

JS

var sceneEl = document.querySelector('a-scene');
var markerEl = document.querySelector('#marker');

// Add boxe when spacebar is pressed.
document.addEventListener('keyup', function (e) {
  if (e.keyCode !== 32) return;

  var newEl = document.createElement('a-box');
  newEl.setAttribute('color', 'red');
  sceneEl.appendChild(newEl);
  var position = markerEl.object3D.getWorldPosition();
  position.y = 0.5;
  newEl.setAttribute('position', position);
});

Codepen: https://codepen.io/donmccurdy/pen/QOOXbK?editors=1010


问:
Manually change colour of one factor level in ggplot2 stacked barplot
I'm giving a presentation, and would like to highlight the rate of occurrence of one of my factor levels on a slide by retaining the colour of this particular factor level, whilst greying out the other factor levels across other variables.

Using the Arthritis data set in the vcd library as an example:

```<code>library(vcd)
ggplot(Arthritis, aes(x = Sex, fill = Improved)) + geom_bar(position = "fill")
</code>```

When, for example, I’m telling the audience about the marked improvement in the males, can I have a version of the plot which retains the colour of marked improvement in males, but greys out everything else? Preferably by using different shades of grey to keep the boundaries?

答:
Consider this example:

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

ggplot(Arthritis)+
  geom_bar(aes(x = Sex, group = Improved), fill = c("red", "blue", "green", "yellow", "grey50", "black"), position = "fill")
</code>```

To change the specified field, while others keep the default ggplot colors:

```<code>ggplot(Arthritis)+
  geom_bar(aes(x = Sex,
               group = Improved),
           fill = c(rev(hue_pal()(3)),
                    "black",
                    hue_pal()(3)[2:1]),
            position = "fill")
</code>```

or to grey out the rest with shades

```<code>ggplot(Arthritis)+
  geom_bar(aes(x = Sex,
               group = Improved),
           fill = c(paste0("grey", 7:9*10),
                    hue_pal()(3)[3],
                    paste0("grey", 8:9*10)),
           position = "fill")
</code>```

to keep the legend just plot the above over your initial layer:

```<code>ggplot(Arthritis)+
  geom_bar(aes(x = Sex, fill = Improved),  position = "fill")+
  geom_bar(aes(x = Sex,
               group = Improved),
           fill = c(paste0("grey", 7:9*10),
                    hue_pal()(3)[3],
                    paste0("grey", 8:9*10)),
           position = "fill")
</code>```

Body:
I'm giving a presentation, and would like to highlight the rate of occurrence of one of my factor levels on a slide by retaining the colour of this particular factor level, whilst greying out the other factor levels across other variables.

Using the Arthritis data set in the vcd library as an example:

library(vcd)
ggplot(Arthritis, aes(x = Sex, fill = Improved)) + geom_bar(position = "fill")

When, for example, I’m telling the audience about the marked improvement in the males, can I have a version of the plot which retains the colour of marked improvement in males, but greys out everything else? Preferably by using different shades of grey to keep the boundaries?

Body:
Consider this example:

library(scales)
library(ggplot2)

ggplot(Arthritis)+
  geom_bar(aes(x = Sex, group = Improved), fill = c("red", "blue", "green", "yellow", "grey50", "black"), position = "fill")

To change the specified field, while others keep the default ggplot colors:

ggplot(Arthritis)+
  geom_bar(aes(x = Sex,
               group = Improved),
           fill = c(rev(hue_pal()(3)),
                    "black",
                    hue_pal()(3)[2:1]),
            position = "fill")

or to grey out the rest with shades

ggplot(Arthritis)+
  geom_bar(aes(x = Sex,
               group = Improved),
           fill = c(paste0("grey", 7:9*10),
                    hue_pal()(3)[3],
                    paste0("grey", 8:9*10)),
           position = "fill")

to keep the legend just plot the above over your initial layer:

ggplot(Arthritis)+
  geom_bar(aes(x = Sex, fill = Improved),  position = "fill")+
  geom_bar(aes(x = Sex,
               group = Improved),
           fill = c(paste0("grey", 7:9*10),
                    hue_pal()(3)[3],
                    paste0("grey", 8:9*10)),
           position = "fill")


答:
This is fundamentally flawed- what if I want my main class to inherit and provide that callback? You're artificially limiting it for no real advantage. Use a std::function instead.

```<code>class Module {
public:
    Module (std::function<void()> ringAlert) : Alert(ringAlert) {}
    void dosomething() {
        if (something) alert();
    }
private:
    std::function<void()> alert;
};
</code>```

The Standard function type is exceedingly flexible and very good to use.

You could also provide for a custom destruction function.

```<code>class Module {
public:
    Module(interface* ptr, std::function<void(interface*)> destructor)
        :pointer(ptr), destruct(destructor) {
    }
    ~Module() {
        if (destruct)
            destruct(pointer);
    }
    void doSomething() {
        if (condition)
            pointer->ring();
    }
private:
    interface* pointer;
    std::function<void(interface*)> destruct;
};
</code>```

If I alloc on the stack, I pass an empty function object. If I allocate on the heap, I pass a quick destruction lambda.

ContentLicense: CC BY-SA 2.5

Title: Preventing classes from being instantiated on the stack or as data member

Body:
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

Module m(RingAlertPtr(&m_myRingAlert,[](void *){});

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?

Body:
This is fundamentally flawed- what if I want my main class to inherit and provide that callback? You're artificially limiting it for no real advantage. Use a std::function instead.

class Module {
public:
    Module (std::function<void()> ringAlert) : Alert(ringAlert) {}
    void dosomething() {
        if (something) alert();
    }
private:
    std::function<void()> alert;
};

The Standard function type is exceedingly flexible and very good to use.

You could also provide for a custom destruction function.

class Module {
public:
    Module(interface* ptr, std::function<void(interface*)> destructor)
        :pointer(ptr), destruct(destructor) {
    }
    ~Module() {
        if (destruct)
            destruct(pointer);
    }
    void doSomething() {
        if (condition)
            pointer->ring();
    }
private:
    interface* pointer;
    std::function<void(interface*)> destruct;
};

If I alloc on the stack, I pass an empty function object. If I allocate on the heap, I pass a quick destruction lambda.


问:
Create a concatenated string from json object in Python
From a json file, I have extracted the following:

```<code>[u'001', u'002', u'003', u'004', u'005', u'006', u'007', u'009', u'041',
u'043', u'050', u'099', u'983']
</code>```

But, what I need is to create a string like this (this will be part of a SQL statement)

```<code>str = """not in ('001','002','003','004','005','006','007','009','041','043','050','099','983')"""
</code>```

I am new to this. Do you have any clues for me?
This will be done in Python.

Thank you in advance!

答:
str.join wrapped in a str.format does the job. First & last quotes and parenthesis are handled by format, whereas middle quotes & commas are handled by str.join

```<code>s = [u'001', u'002', u'003', u'004', u'005', u'006', u'007', u'009', u'041',
u'043', u'050', u'099', u'983']

print("not in ('{}')".format("','".join(s)))
</code>```

result:

```<code>not in ('001','002','003','004','005','006','007','009','041','043','050','099','983')
</code>```

note that str(tuple(s)) generates the same single quoted string, but I don't like relying on the representation of python objects.

Body:
From a json file, I have extracted the following:

[u'001', u'002', u'003', u'004', u'005', u'006', u'007', u'009', u'041',
u'043', u'050', u'099', u'983']

But, what I need is to create a string like this (this will be part of a SQL statement)

str = """not in ('001','002','003','004','005','006','007','009','041','043','050','099','983')"""

I am new to this. Do you have any clues for me?
This will be done in Python.

Thank you in advance!

Body:
str.join wrapped in a str.format does the job. First & last quotes and parenthesis are handled by format, whereas middle quotes & commas are handled by str.join

s = [u'001', u'002', u'003', u'004', u'005', u'006', u'007', u'009', u'041',
u'043', u'050', u'099', u'983']

print("not in ('{}')".format("','".join(s)))

result:

not in ('001','002','003','004','005','006','007','009','041','043','050','099','983')

note that str(tuple(s)) generates the same single quoted string, but I don't like relying on the representation of python objects.


问:
C# Linq Query from a list to select only records which have same id from another list
I am having a list of object. I would like to select item from the list and perform foreach operation on the selected items.And then Get the Data which have that Site.

C# Linq Query from a list to select only records which have same id from another list

Model

List of Sites

```<code>public class Site
{
    public string Name{ get; set; }
    public int SiteNo{ get; set; }
}

public class StudentSite
{
    public string Username{ get; set; }
    public string { get; set; }
    public IList<Site> SiteNo { get; set; }
    public DateTime? DateReceived { get; set; }
    public string firstname { get; set; }
    public string DataEntryUser { get; set; }
    public DateTime? CreatedDate { get; set; }
    public int? Count { get; set; }
}

var user = repository.Get(userid);  //it return me the list of sites 10 sites

results_temp12 = (from workstation in _entitiesCTRS2.AidsM.OrderBy(c => c.Lab_ID )
                 where user.User_InvSites.ToList().
                 ForEach(c => c.Inv_Site.SITE_NO
                    .Where( w=> workstation.Site_Number == c.Inv_Site.SITE_NO)
                    .ToList())
                    select new
                    StudentSite
                    {
                        firstname = workstation.First_Name,
                        CreatedDate = workstation.Entered_dt,
                        scanid = workstation.Scan_ID,
                        labid = workstation.Lab_ID,
                        SiteNo = workstation.Site_Number,
                        DateReceived = workstation.Date_Received,
                        DataEntryUser = workstation.Entered_By
                    }).ToList();
</code>```

答:
It's maddeningly unclear on what you want.  But two possibilities I get from your question:</p>

```<code>// Inner join: Only returns foos where foo.Id exists in bars
var results = from foo in foos
              join bar in bars on foo.Id equals bar.Id
              select foo;

// Gets all foos if it contains at least one element found in another list
var results = from foo in foos
              where foo.Sites.Select(f => f.Id).Any(s => bars.Any(b => s == b.Id))
              select foo;
</code>```

Body:
I am having a list of object. I would like to select item from the list and perform foreach operation on the selected items.And then Get the Data which have that Site.

C# Linq Query from a list to select only records which have same id from another list

Model

List of Sites

public class Site
{
    public string Name{ get; set; }
    public int SiteNo{ get; set; }
}

public class StudentSite
{
    public string Username{ get; set; }
    public string { get; set; }
    public IList<Site> SiteNo { get; set; }
    public DateTime? DateReceived { get; set; }
    public string firstname { get; set; }
    public string DataEntryUser { get; set; }
    public DateTime? CreatedDate { get; set; }
    public int? Count { get; set; }
}

var user = repository.Get(userid);  //it return me the list of sites 10 sites

results_temp12 = (from workstation in _entitiesCTRS2.AidsM.OrderBy(c => c.Lab_ID )
                 where user.User_InvSites.ToList().
                 ForEach(c => c.Inv_Site.SITE_NO
                    .Where( w=> workstation.Site_Number == c.Inv_Site.SITE_NO)
                    .ToList())
                    select new
                    StudentSite
                    {
                        firstname = workstation.First_Name,
                        CreatedDate = workstation.Entered_dt,
                        scanid = workstation.Scan_ID,
                        labid = workstation.Lab_ID,
                        SiteNo = workstation.Site_Number,
                        DateReceived = workstation.Date_Received,
                        DataEntryUser = workstation.Entered_By
                    }).ToList();

Body:
It's maddeningly unclear on what you want.  But two possibilities I get from your question:

// Inner join: Only returns foos where foo.Id exists in bars
var results = from foo in foos
              join bar in bars on foo.Id equals bar.Id
              select foo;

// Gets all foos if it contains at least one element found in another list
var results = from foo in foos
              where foo.Sites.Select(f => f.Id).Any(s => bars.Any(b => s == b.Id))
              select foo;


问:
Codeigniter Query: Mysql query convert into codeigniter query format
Please help me How to convert this query into codeigniter query format</p>

```<code>SELECT *
FROM `table1`
LEFT JOIN `table2`
    ON table1.permission_key = table2.permission_key AND
       (table2.role_id is null || table2.role_id="1")
WHERE
    table1.section  ='abc' AND
    table1.sub_section = 'xzy';
</code>```

答:
you can type your query as plain sql statement and pass it to codeiginter function $this->db->query();

```<code>$query = "SELECT * FROM table1 JOIN table2 ON table1.permission_key = table2.permission_key AND AND
       (table2.role_id is null || table2.role_id='1')
       WHERE table1.section  ='abc' AND table1.sub_section = 'xzy'";
$this->db->query($query);
$this->db->get();
</code>```

Body:
Please help me How to convert this query into codeigniter query format

SELECT *
FROM `table1`
LEFT JOIN `table2`
    ON table1.permission_key = table2.permission_key AND
       (table2.role_id is null || table2.role_id="1")
WHERE
    table1.section  ='abc' AND
    table1.sub_section = 'xzy';

Body:
you can type your query as plain sql statement and pass it to codeiginter function $this->db->query();

$query = "SELECT * FROM table1 JOIN table2 ON table1.permission_key = table2.permission_key AND AND
       (table2.role_id is null || table2.role_id='1')
       WHERE table1.section  ='abc' AND table1.sub_section = 'xzy'";
$this->db->query($query);
$this->db->get();


问:
ContentPresenter Resources not applied when added as LogicalChild
My custom control is derived from ContentControl and has an additional dependency property 'AdditionalContent' of type FrameworkElement.

This property is bound to a ContentPresenter in style that has custom style resources:

```<code><ContentPresenter ContentSource="AdditionalContent">
  <ContentPresenter.Resources>
    <Style TargetType="{x:Type Button}">
      ... some setters ...
    </Style>
  </ContentPresenter.Resources>
</ContentPresenter>
</code>```

As I learned from other questions here, I have to add this object as logical child of my control by calling AddLogicalChild(AdditionalContent) and overriding LogicalChildren property.

Now, if I use my control like this

```<code><MyControl>
  <MyControl.AdditionalContent>
    <Button .../>
  </MyControl.AdditionalContent>
</MyControl>
</code>```

The style for Button is not applied. And that's the correct behaviour, because of style inheritance (see this answer). So I have to apply the style in the place where I define the AdditionalContent. So far so good.

But strange behaviour: when I leave out adding the object as logical child, the styles are applied.

Why does this happen? And is there a proper way to provide styles for all contents inside AdditionalContent similar to define Toolbar styles?

答:
It's hard to tell since you have left out much of the button definition, but try setting the style of the button to a dynamic resource with the button type as the resource key.

```<code><Button Style="{DynamicResource {x:Type Button}}"/>
</code>```

When adding a default style with no resource key like you have done, the implicit key is the data type.

By setting the style to a dynamic resource you are indicating that the resource could change during runtime, which is the case when you are inserting it into the tree at runtime like you are doing.

Body:
My custom control is derived from ContentControl and has an additional dependency property 'AdditionalContent' of type FrameworkElement.

This property is bound to a ContentPresenter in style that has custom style resources:

<ContentPresenter ContentSource="AdditionalContent">
  <ContentPresenter.Resources>

  </ContentPresenter.Resources>
</ContentPresenter>

As I learned from other questions here, I have to add this object as logical child of my control by calling AddLogicalChild(AdditionalContent) and overriding LogicalChildren property.

Now, if I use my control like this

<MyControl>
  <MyControl.AdditionalContent>
    <Button .../>
  </MyControl.AdditionalContent>
</MyControl>

The style for Button is not applied. And that's the correct behaviour, because of style inheritance (see this answer). So I have to apply the style in the place where I define the AdditionalContent. So far so good.

But strange behaviour: when I leave out adding the object as logical child, the styles are applied.

Why does this happen? And is there a proper way to provide styles for all contents inside AdditionalContent similar to define Toolbar styles?

Body:
It's hard to tell since you have left out much of the button definition, but try setting the style of the button to a dynamic resource with the button type as the resource key.

<Button Style="{DynamicResource {x:Type Button}}"/>

When adding a default style with no resource key like you have done, the implicit key is the data type.

By setting the style to a dynamic resource you are indicating that the resource could change during runtime, which is the case when you are inserting it into the tree at runtime like you are doing.


问:
How to pass the manifest to player after processing?
Once the manifest is obtained by using host.processManifest , necessary changes can be made. How can one pass the manifest to the player after this?

答: Your function needs to return the manifest as a string value.</p>


问:
blink-matching-paren not working in readline prompt
I am making a program with an interactive prompt using the readline library. I would like for the prompt to support matching parenthesis highlighting so I have set blink-matching-paren in ~/.initrc with

```<code>set blink-matching-paren on
</code>```

however when I use the interactive prompt, there is no matching parenthesis blinking. I am using the #include directives shown here:

```<code>#include <readline/readline.h>
#include <readline/history.h>
</code>```

and reading from standard input like so:

```<code>char* line = readline(my_prompt);
</code>```

The linked documentation suggests that this would be sufficient, yet I am not observing the desired behavior.

Thanks for the help.

答: Ensure that you are really calling the correct readline function, as indeed what you have done should be sufficient. Check that you are linking the correct library with the -lreadline compiler flag. Perhaps you are mistakenly linking a similar library (such as GNU Readline) which also has a readline function and are calling the readline from that library instead.

Body:
I am making a program with an interactive prompt using the readline library. I would like for the prompt to support matching parenthesis highlighting so I have set blink-matching-paren in ~/.initrc with

set blink-matching-paren on

however when I use the interactive prompt, there is no matching parenthesis blinking. I am using the #include directives shown here:

#include <readline/readline.h>
#include <readline/history.h>

and reading from standard input like so:

char* line = readline(my_prompt);

The linked documentation suggests that this would be sufficient, yet I am not observing the desired behavior.

Thanks for the help.


问:
Vista 64-bit Development Caveats
I'm migrating my development workstation from 32-bit Vista to 64-bit Vista.

The production platform is 32-bit Windows Server and SQL Server 2008.

Does anyone know of any issues with migrating the code base?

EDIT:

the system consists of web forms, c# code, stored procedures.

there is also ajax.net, ssrs, ssis, and dynamic reports/graphs from dundas.

however, i think other users might appreciate any lessons learned or feedback in general regarding this move.

FINDINGS:

As of Jan 24, 2009

Checkpoint VPN does not support Vista 64 (actually it seems that very few do)

Cropper utility required special download and rebuild to work on Vista 64 (Cropper looks very nice, but it lacks scrollable window capture)

The lack of support for Vista 64 made it not worth while for me.  I wish someone would have mentioned the lack of VPN support, but there is currently no vpn vendor that supports 64 bit clients....  So be forwarned - as of 1/28/2009 - using Vista 64 is not a good option for those of us who need vpn.

答:
I have come across one issue with Vista 64:

Program Files

Program files may be stored in Program Files x86 or in Program Files you may have to code around this if any of your code makes assumptions about where programs are stored - even if you have done the right thing and used environment variables, as there are 2 locations there are now 2 different environment variables. You need to know which of these your app will be installed in, which will be different if you target any CPU from if you target x86.

OwnerDisplayName: mson

Title: Vista 64-bit Development Caveats

LastEditorDisplayName: mson

OwnerDisplayName: Sam Meldrum


问:
MS Access VBA Ranged Dates with BETWEEN or single entry with in Text Boxes
I'm looking for some assistance on this  Look up code I managed to put together.

```<code>If Me.txtStartDate > "" And Me.txtEndDate > "" Then
varWhere = varWhere & "[CompletionDate] BETWEEN #" & Me.txtStartDate & "# AND #" & Me.txtEndDate & "#"

ElseIf Me.txtStartDate > "" And Me.txtEndDate Is Nothing Then
varWhere = varWhere & "[CompletionDate] = """" & Me.txtStartDate & " * "" And ""

ElseIf Me.txtStartDate Is Nothing And Me.txtEndDate > "" Then
MsgBox "Please Input a Start Date", vbOKOnly, Error

End If
</code>```

I feel like the code itself is self explanatory of my goals. However I'm wanting to allow the user to input into Me.txtStartDate & Me.txtEndDate giving the range. Also, Allowing the user to just input into Me.txtStartDate for a single date.  I have attempted combining the two Along with a message box if they input into end date alone.

Its not working for me, I can get either or working.

My Question is "How do I combine these three statements, so they work in a conditional statement way?"

Anything helps.

答:
I'm not sure what you're trying to do.  I like to use datepickers.

```<code>Private Sub Form_Open(Cancel As Integer)
Me.DTPickerStart.DefaultValue = "Date()"
Me.DTPickerEnd.DefaultValue = "Date()"
</code>```

Then I'd do something like this.

```<code>If (Nz(Me.Me.txtStartDate.Value) = "") Then
        MsgBox "Please select a Start Date.", vbCritical + vbOKOnly, "Error"
ElseIf (Nz(Me.txtEndDate.Value) = "") Then
    MsgBox "Please select a End Date.", vbCritical + vbOKOnly, "Error"
Else
    DoCmd.OpenReport "XYZRpt", acViewPreview
    Or you could do..
    DoCmd.OpenQuery "Passthroughquery"  that links to an SQL procedure.  I'm not
    sure what you're trying to do though.
End If
</code>```

Body:
I'm looking for some assistance on this  Look up code I managed to put together.

If Me.txtStartDate > "" And Me.txtEndDate > "" Then
varWhere = varWhere & "[CompletionDate] BETWEEN #" & Me.txtStartDate & "# AND #" & Me.txtEndDate & "#"

ElseIf Me.txtStartDate > "" And Me.txtEndDate Is Nothing Then
varWhere = varWhere & "[CompletionDate] = """" & Me.txtStartDate & " * "" And ""

ElseIf Me.txtStartDate Is Nothing And Me.txtEndDate > "" Then
MsgBox "Please Input a Start Date", vbOKOnly, Error

End If

I feel like the code itself is self explanatory of my goals. However I'm wanting to allow the user to input into Me.txtStartDate & Me.txtEndDate giving the range. Also, Allowing the user to just input into Me.txtStartDate for a single date.  I have attempted combining the two Along with a message box if they input into end date alone.

Its not working for me, I can get either or working.

My Question is "How do I combine these three statements, so they work in a conditional statement way?"

Anything helps.

Body:
I'm not sure what you're trying to do.  I like to use datepickers.

Private Sub Form_Open(Cancel As Integer)
Me.DTPickerStart.DefaultValue = "Date()"
Me.DTPickerEnd.DefaultValue = "Date()"

Then I'd do something like this.

If (Nz(Me.Me.txtStartDate.Value) = "") Then
        MsgBox "Please select a Start Date.", vbCritical + vbOKOnly, "Error"
ElseIf (Nz(Me.txtEndDate.Value) = "") Then
    MsgBox "Please select a End Date.", vbCritical + vbOKOnly, "Error"
Else
    DoCmd.OpenReport "XYZRpt", acViewPreview
    Or you could do..
    DoCmd.OpenQuery "Passthroughquery"  that links to an SQL procedure.  I'm not
    sure what you're trying to do though.
End If


问:
Generate a report using DFSORT
I have a task to write a JCL job invoking ICETOOL/DFSORT to generate a report. The report takes a VSAM KSDS as input and generates a list of bank branches.

Each record in the BRANCHES KSDS is of the form

• 4-byte binary unsigned integer representing a 6-digit decimal branch sortcode (e.g. 420101)

• 1-byte EBCDIC flag: ◦ EBCDIC 'A' means the branch is owned by ZeusBank and all its accounts are held in the ACCOUNTS KSDS

◦ EBCDIC 'B' means the branch is not owned by ZeusBank so we do not hold its account information in the ACCOUNTS KSDS

• 32-byte EBCDIC character branch name (e.g. “ZEUSBANK FOOFORD BAR STREET” or “OTHERBANK QUUXHAM BAZ ROAD”), blank padded on the right.

The report should look like this

I'm pretty new to JCL so please forgive if the question is simple. Thanks.

答:
You can try this:</p>

```<code>//STEPSORT EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTIN DD DSN=DATASETNAME
//SORTOUT DD SYSOUT=*
//SYSIN DD *
SORT FIELDS=(5,1,CH,A)
OUTFIL HEADER2=(1:C'LIST OF WHATEVER BANK',4/,
1:C'SORTCODE',10:C'FLAG',15:C'BRANCH',/,
1:C'--------',10:C'----',15:C'------'),
BUILD=(1:1,4,BI,TO=ZD,LENGTH=6,10:5,1,15:6,32)
/*
</code>```

Title: Generate a report using DFSORT

Body:
You can try this:

//STEPSORT EXEC PGM=SORT
//SYSOUT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SORTIN DD DSN=DATASETNAME
//SORTOUT DD SYSOUT=*
//SYSIN DD *
SORT FIELDS=(5,1,CH,A)
OUTFIL HEADER2=(1:C'LIST OF WHATEVER BANK',4/,
1:C'SORTCODE',10:C'FLAG',15:C'BRANCH',/,
1:C'--------',10:C'----',15:C'------'),
BUILD=(1:1,4,BI,TO=ZD,LENGTH=6,10:5,1,15:6,32)
/*


问:
Best Icon size for displaying in the tray
I am working on a Delphi program which will display an icon on the "tray". I am doing it "the hard way" (using the Shell_NotifyIcon api, etc and not a component, for reasons outside the point here). It's working fine but sometimes it seems like the icon is a little "blurry" in some systems. Now, I have experimented using 16x16 bmp, 32x32, etc. It seems like the system scales it down to the needed size, but the results are different depending on the OS version (or perhaps something else as well)....

Have any of you any experience about the best size and color depth of a BMP to be extracted and displayed on the tray using Shell_NotifyIcon from a ListImage?

答:
A single *.ico file is recommended for app icons. *.ico file can store different sizes of icons like 16, 32, 256 etc. You can convert different image files to ico format online here.

For tray icon 16x16 or 32x32 ico would fit.

Official msdn guide for icons: icons in Windows


问:
PHP: javascript alert, with value from sql query, into IF condition
With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.

```<code>$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);

$rowcount=mysqli_num_rows($result);

$message = "Records found: " . $rowcount . "<br /><br />";

if ($rowcount > 1) {

echo '<script language="javascript">';
echo 'alert' .$message;

foreach($result as $val){

$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;

echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
echo '</script>';
}
</code>```

Recording counts are done correctly, but I can not make the popup appear in any way.

答:
try this. Hope this help you.</p>

```<code> $sql = "SELECT * FROM pt_locations WHERE country = ('country') AND
location = ('location')";
$result = $conn->query($sql);

$rowcount=mysqli_num_rows($result);

$message = "Records found: " . $rowcount;

if ($rowcount > 1) {

echo '<script language="javascript">';
echo 'alert("'.$message.'")';
 echo '</script>';

while($val=mysqli_fetch_assoc($result)){

$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;

echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
}
</code>```

Body:
With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.

$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);

$rowcount=mysqli_num_rows($result);

$message = "Records found: " . $rowcount . "

";

if ($rowcount > 1) {

echo '';
}

Recording counts are done correctly, but I can not make the popup appear in any way.

Body:
try this. Hope this help you.

 $sql = "SELECT * FROM pt_locations WHERE country = ('country') AND
location = ('location')";
$result = $conn->query($sql);

$rowcount=mysqli_num_rows($result);

$message = "Records found: " . $rowcount;

if ($rowcount > 1) {

echo '<script language="javascript">';
echo 'alert("'.$message.'")';
 echo '</script>';

while($val=mysqli_fetch_assoc($result)){

$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;

echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
}


答:
Try:</p>

```<code>for (int counter = moreValues.length; counter >= 1; counter--)
{
    cubedNumber = Math.pow(counter,3);
    System.out.println(moreValues[counter-1] + " cubed is " + cubedNumber);
}
</code>```

Title: For Loop in Array (Java) Index Out of Bounds

Body:
I'm having a hard time using an array in a for loop that is supposed to cube numbers 1-9 in descending order. I keep getting an out of bounds error and the cubed values are completely off. I would greatly appreciate an explanation as to where I am going wrong with thinking about arrays. I believe the issue is with my index, but I'm struggling to explain why.

System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
    System.out.println();
    // Create array
    int[] values = new int[11];
    int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // Create variable to store cubed numbers
    double cubedNumber = 0;
    // Create for loop to count in descending order
    for (int counter = 9; counter < moreValues.length; counter--)
    {
        cubedNumber = Math.pow(counter,3);
        System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
    }

Output

Body:
Try:

for (int counter = moreValues.length; counter >= 1; counter--)
{
    cubedNumber = Math.pow(counter,3);
    System.out.println(moreValues[counter-1] + " cubed is " + cubedNumber);
}


问:
How to debug NASM Assembly that produces segfault before hitting _start
I have the following assmebly (NASM) code I am writing that sets the mouse pointer to the location 100,100:

```<code>section .text
    global _start:

_start:
    mov eax, 4
    mov ecx, 100
    mov edx, 100
    int 33h

    mov eax, 1
    int 0x80
</code>```

I compile it with the following make file:

```<code>DEPS = Mouse.asm

Mouse: $(DEPS)
    nasm -f elf $(DEPS)
    ld -m elf_i386 -s -o Mouse Mouse.o
</code>```

Then I open it up in GDB using $sudo gdb Mouse.  Then I input "break _start" and press "r" to run.  When I do that I get the following output:

"Starting program: /home/tyler/ASM/Mouse/Mouse

Program received signal SIGSEGV, Segmentation fault.
0x0804806f in ?? ()
"

It looks to me that it never even hits the breakpoint at _start so I don't know what I could be doing wrong.  How can I go about debugging this?

答:
Update: modern GDB has a starti command that makes this hack obsolete.  Stopping at the first machine code instruction in GDB

TL:DR: the reason b _start doesn't find that symbol to set the breakpoint is that you stripped symbols when linking.  (So that's why it's "pending" on loading of dynamic libs, but in this case there aren't any.)

To sort of answer the question you asked (rather than the problem you actually have), use @Ped7g's suggestion to "abuse" GDB's error-handling to get it to stop before the first instruction without knowing the right address:

b *0 sets a breakpoint at address zero (which is impossible).

r runs the program, at which point GDB tries to actually set the breakpoint.  It fails, and stops before any instructions are executed.

d 1 deletes the invalid breakpoint

si (or stepi) will single step from there.

This is a useful trick for debugging a program that has no symbols, even if it's dynamically linked using ASLR (gcc -pie) so you can't get the real ELF entry-point address using readelf -a.

What you did:

Then I input "break _start" and press "r" to run.

When I do that after building with the same commands you used, I get

```<code>Reading symbols from ./Mouse...(no debugging symbols found)...done.
(gdb) b _start
No symbol table is loaded.  Use the "file" command.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (_start) pending.
</code>```

I had to type y or n before I could enter r to run the program.

So I don't actually have a breakpoint at the instruction labeled _start: in the asm source.  All I have is a pending breakpoint that will be set somewhere if I give GDB a symbol table.  (It is possible to strip debug symbols into a separate file, so this gdb behaviour makes sense.  But it unfortunately confused you in this case. :/)

Your binary is stripped because you built with ld -s.  This is the opposite of what you want for debugging.  Use nasm -g -Fdwarf to use the modern dwarf debug-info format instead of STABS for even better symbol info.

```<code>(gdb) r
Starting program: /home/peter/src/SO/Mouse

Program received signal SIGSEGV, Segmentation fault.
0x0804806f in ?? ()
</code>```

The instruction at 0x0804806f is your int 33h.

It's not segfaulting before _start, it just didn't stop because you never actually set a breakpoint.  In a statically-linked binary, the first instruction to run in user-space is the one at your ELF entry point.  (In a dynamically linked binary, the ELF interpreter runs first and eventually jumps to your _start, or whatever you called your entry point.)

Use layout reg to show registers and disassembly.  Use set disassembly-flavor intel to get GNU's MASM-like syntax which is close enough to NASM to read when you know what it's supposed to be.  Put these in your ~/.gdbinit.  See also the bottom of the x86 tag wiki for more debugging tips with gdb and strace.

As commenters have pointed out, there's no way your program can run natively under Linux.  Linux doesn't natively support the BIOS int 33h ABI, only its own system-call ABI.  What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64.  This is why int 33h segfaults.

If you want to write MS-DOS or PC-BIOS code, use an emulator like BOCHS (which has a built-in debugger that will let you single-step anything, even a bootloader).

Body:
I have the following assmebly (NASM) code I am writing that sets the mouse pointer to the location 100,100:

section .text
    global _start:

_start:
    mov eax, 4
    mov ecx, 100
    mov edx, 100
    int 33h

    mov eax, 1
    int 0x80

I compile it with the following make file:

DEPS = Mouse.asm

Mouse: $(DEPS)
    nasm -f elf $(DEPS)
    ld -m elf_i386 -s -o Mouse Mouse.o

Then I open it up in GDB using $sudo gdb Mouse.  Then I input "break _start" and press "r" to run.  When I do that I get the following output:

"Starting program: /home/tyler/ASM/Mouse/Mouse

Program received signal SIGSEGV, Segmentation fault.
0x0804806f in ?? ()
"

It looks to me that it never even hits the breakpoint at _start so I don't know what I could be doing wrong.  How can I go about debugging this?

Body:
Update: modern GDB has a starti command that makes this hack obsolete.  Stopping at the first machine code instruction in GDB

TL:DR: the reason b _start doesn't find that symbol to set the breakpoint is that you stripped symbols when linking.  (So that's why it's "pending" on loading of dynamic libs, but in this case there aren't any.)

To sort of answer the question you asked (rather than the problem you actually have), use @Ped7g's suggestion to "abuse" GDB's error-handling to get it to stop before the first instruction without knowing the right address:

b *0 sets a breakpoint at address zero (which is impossible).

r runs the program, at which point GDB tries to actually set the breakpoint.  It fails, and stops before any instructions are executed.

d 1 deletes the invalid breakpoint

si (or stepi) will single step from there.

This is a useful trick for debugging a program that has no symbols, even if it's dynamically linked using ASLR (gcc -pie) so you can't get the real ELF entry-point address using readelf -a.

What you did:

Then I input "break _start" and press "r" to run.

When I do that after building with the same commands you used, I get

Reading symbols from ./Mouse...(no debugging symbols found)...done.
(gdb) b _start
No symbol table is loaded.  Use the "file" command.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (_start) pending.

I had to type y or n before I could enter r to run the program.

So I don't actually have a breakpoint at the instruction labeled _start: in the asm source.  All I have is a pending breakpoint that will be set somewhere if I give GDB a symbol table.  (It is possible to strip debug symbols into a separate file, so this gdb behaviour makes sense.  But it unfortunately confused you in this case. :/)

Your binary is stripped because you built with ld -s.  This is the opposite of what you want for debugging.  Use nasm -g -Fdwarf to use the modern dwarf debug-info format instead of STABS for even better symbol info.

(gdb) r
Starting program: /home/peter/src/SO/Mouse

Program received signal SIGSEGV, Segmentation fault.
0x0804806f in ?? ()

The instruction at 0x0804806f is your int 33h.

It's not segfaulting before _start, it just didn't stop because you never actually set a breakpoint.  In a statically-linked binary, the first instruction to run in user-space is the one at your ELF entry point.  (In a dynamically linked binary, the ELF interpreter runs first and eventually jumps to your _start, or whatever you called your entry point.)

Use layout reg to show registers and disassembly.  Use set disassembly-flavor intel to get GNU's MASM-like syntax which is close enough to NASM to read when you know what it's supposed to be.  Put these in your ~/.gdbinit.  See also the bottom of the x86 tag wiki for more debugging tips with gdb and strace.

As commenters have pointed out, there's no way your program can run natively under Linux.  Linux doesn't natively support the BIOS int 33h ABI, only its own system-call ABI.  What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64.  This is why int 33h segfaults.

If you want to write MS-DOS or PC-BIOS code, use an emulator like BOCHS (which has a built-in debugger that will let you single-step anything, even a bootloader).


问:
HTML5 Flyout Content Blocks?
Someone had to ask it, I've been drooling over it since Microsoft launched http://www.beautyoftheweb.com/

How in the world are they doing that?

You know what I mean, the flying, re-arranging content blocks. I know they are doing the site redirecting using the /#/ URL as a placeholder and then just appending the rest as a link, but I've scoured their source for hours and just cannot for the life of me figure out how they are doing the flying content blocks.

Obviously I cannot copy the source code, but I would love to figure this out - even if I can't use it in production, it's so fascinating to see what we can do without flash that years ago we would have done ONLY in flash, and it would have been clunky at that.

Anyone have any ideas?

答: I think they are using Jquery along with a number of other javascript frameworks. They are listed at the bottom of the source file.</p>

Title: HTML5 Flyout Content Blocks?