Search Results

Search found 6519 results on 261 pages for 'nested attributes'.

Page 1/261 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

    - by SeanMcAlinden
    There are a number of ways of implementing a pattern for using custom view model attributes, the following is similar to something I’m using at work which works pretty well. The classes I’m going to create are really simple: 1. Abstract base attribute 2. Custom ModelMetadata provider which will derive from the DataAnnotationsModelMetadataProvider   Base Attribute MetadataAttribute using System; using System.Web.Mvc; namespace Mvc2Templates.Attributes {     /// <summary>     /// Base class for custom MetadataAttributes.     /// </summary>     public abstract class MetadataAttribute : Attribute     {         /// <summary>         /// Method for processing custom attribute data.         /// </summary>         /// <param name="modelMetaData">A ModelMetaData instance.</param>         public abstract void Process(ModelMetadata modelMetaData);     } } As you can see, the class simple has one method – Process. Process accepts the ModelMetaData which will allow any derived custom attributes to set properties on the model meta data and add items to its AdditionalValues collection.   Custom Model Metadata Provider For a quick explanation of the Model Metadata and how it fits in to the MVC 2 framework, it is basically a set of properties that are usually set via attributes placed above properties on a view model, for example the ReadOnly and HiddenInput attributes. When EditorForModel, DisplayForModel or any of the other EditorFor/DisplayFor methods are called, the ModelMetadata information is used to determine how to display the properties. All of the information available within the model metadata is also available through ViewData.ModelMetadata. The following class derives from the DataAnnotationsModelMetadataProvider built into the mvc 2 framework. I’ve overridden the CreateMetadata method in order to process any custom attributes that may have been placed above a property in a view model.   CustomModelMetadataProvider using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Mvc2Templates.Attributes; namespace Mvc2Templates.Providers {     public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider     {         protected override ModelMetadata CreateMetadata(             IEnumerable<Attribute> attributes,             Type containerType,             Func<object> modelAccessor,             Type modelType,             string propertyName)         {             var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);               attributes.OfType<MetadataAttribute>().ToList().ForEach(x => x.Process(modelMetadata));               return modelMetadata;         }     } } As you can see, once the model metadata is created through the base method, a check for any attributes deriving from our new abstract base attribute MetadataAttribute is made, the Process method is then called on any existing custom attributes with the model meta data for the property passed in.   Hooking it up The last thing you need to do to hook it up is set the new CustomModelMetadataProvider as the current ModelMetadataProvider, this is done within the Global.asax Application_Start method. Global.asax protected void Application_Start()         {             AreaRegistration.RegisterAllAreas();               RegisterRoutes(RouteTable.Routes);               ModelMetadataProviders.Current = new CustomModelMetadataProvider();         }   In my next post, I’m going to demonstrate a cool custom attribute that turns a textbox into an ajax driven AutoComplete text box. Hope this is useful. Kind Regards, Sean McAlinden.

    Read the article

  • rails nested attributes

    - by user342798
    I am using rails 3.0.0.beta3 and I am trying to implement form with nested attributes using :accepts_nested_attributes_for. My form is nested to three levels: Survey Question Answer. Survey has_many Questions, and Question has many Answers. Inside the Survey model, there is :accepts_nested_attributes_for :questions and inside the question mode, there is :accepts_nested_attributes_for :answers Everything is working fine except when I add a new answer to an existing question, it doesn't get created. However, if I make changes to the corresponding question while creating the answer, I can successfully create the answer. This example is exactly similar to a railscast: http://railscasts.com/episodes/197-nested-model-form-part-2 but doesn't work in rails3 (at least in my case). Please let me know if there is any issue with nested attributes in Rails 3. Thanks in advance.

    Read the article

  • Proper Use Of HTML Data Attributes

    - by VirtuosiMedia
    I'm writing several JavaScript plugins that are run automatically when the proper HTML markup is detected on the page. For example, when a tabs class is detected, the tabs plugin is loaded dynamically and it automatically applies the tab functionality. Any customization options for the JavaScript plugin are set via HTML5 data attributes, very similar to what Twitter's Bootstrap Framework does. The appeal to the above system is that, once you have it working, you don't have worry about manually instantiating plugins, you just write your HTML markup. This is especially nice if people who don't know JavaScript well (or at all) want to make use of your plugins, which is one of my goals. This setup has been working very well, but for some plugins, I'm finding that I need a more robust set of options. My choices seem to be having an element with many data-attributes or allowing for a single data-options attribute with a JSON options object as a value. Having a lot of attributes seems clunky and repetitive, but going the JSON route makes it slightly more complicated for novices and I'd like to avoid full-blown JavaScript in the attributes if I can. I'm not entirely sure which way is best. Is there a third option that I'm not considering? Are there any recommended best practices for this particular use case?

    Read the article

  • Form is creating already loaded attributes in addition to new attributes, how do I ignore the first?

    - by looloobs
    In my application you: Have an admin user that signs on and that user has a role (separate model), then I use the declarative_authorization plugin to give access to certain areas. That admin user can also register new users in the system, when they do this (using Authlogic) they fill out a nested form that includes that new users' role. So what is happening is the role of the admin user is being loaded by the declarative_authorization and then the nested form using the has_many_nested_attributes is loading that existing role as well as the new role for the new user (users can have many roles). Is there some way I can tell the new User being created to ignore the role assigned to the current_user and only create the role in the form for the new user? I have looked through a lot of different things, but it seems to get more complicated that these are nested attributes. Thanks in advance.

    Read the article

  • undefined method `build_users' with nested models

    - by Cédric
    I've got into trouble with nested attributes. Here is my Account model : class Account < ActiveRecord::Base has_many :products has_many :blogs has_many :openings has_many :users has_one :logo, :class_name => "AccountPicture" has_one :address, :class_name => "AccountAddress" has_and_belongs_to_many :options accepts_nested_attributes_for :logo, :allow_destroy => true accepts_nested_attributes_for :address, :allow_destroy => true accepts_nested_attributes_for :users, :allow_destroy => true end And here is my User model : class User < ActiveRecord::Base belongs_to :account end As you can see, Account accepts nested attributes for logo, address, and users. While testing, i can use nested attributes for logo and address, but not for user. a = Account.new => #<Account id: nil, hostname: nil, subdomain: nil, name: nil, description: nil, base_line: nil, footer: nil, phone_number: nil, mobile_number: nil, email_address: nil, created_at: nil, updated_at: nil> # building the address works fine >> a.build_address => #<AccountAddress id: nil, account_id: nil, country: nil, state: nil, county: nil, city: nil, suburb: nil, zipcode: nil, street: nil, streetno: nil, longitude: nil, latitude: nil, error_code: nil> # building the users fails >> a.build_users NoMethodError: undefined method `build_users' for #<Account:0x7f6862a5f948> from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:260:in `method_missing' from (irb):2 Thus, in my views, when i use the nested forms, i got this error back : User(#69850615730460) expected, got Array(#69850664775200) Any help would be appreciated. Thanks.

    Read the article

  • how to save nested form attributes to database

    - by siulamvictor
    I am not really understand how's the nested attributes work in Rails. I have 2 models, Accounts and Users. Accounts has_many Users. When a new user filled in the form, Rails reported User(#2164802740) expected, got Array(#2148376200) Is that Rails cannot read the nested attributes from the form? How can I fix it? How can I save the data from nested attributes form to database? Thanks all~ Here are the MVCs: Account Model class Account < ActiveRecord::Base has_many :users accepts_nested_attributes_for :users validates_presence_of :company_name, :message => "companyname is required." validates_presence_of :company_website, :message => "website is required." end User Model class User < ActiveRecord::Base belongs_to :account validates_presence_of :user_name, :message => "username too short." validates_presence_of :password, :message => "password too short." end Account Controller class AccountController < ApplicationController def new end def created end def create @account = Account.new(params[:account]) if @account.save redirect_to :action => "created" else flash[:notice] = "error!!!" render :action => "new" end end end Account/new View <h1>Account#new</h1> <% form_for :account, :url => { :action => "create" } do |f| %> <% f.fields_for :users do |ff| %> <p> <%= ff.label :user_name %><br /> <%= ff.text_field :user_name %> </p> <p> <%= ff.label :password %><br /> <%= ff.password_field :password %> </p> <% end %> <p> <%= f.label :company_name %><br /> <%= f.text_field :company_name %> </p> <p> <%= f.label :company_website %><br /> <%= f.text_field :company_website %> </p> <% end %> Account Migration class CreateAccounts < ActiveRecord::Migration def self.up create_table :accounts do |t| t.string :company_name t.string :company_website t.timestamps end end def self.down drop_table :accounts end end User Migration class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :user_name t.string :password t.integer :account_id t.timestamps end end def self.down drop_table :users end end Thanks everyone. :)

    Read the article

  • Is restricting attributes to class or properties doable?

    - by Will Marcouiller
    I have two custom attributes defined like so: internal class SchemaAttribute : Attribute { internal SchemaAttribute(string schema) { Schema = schema; } internal string Schema { get; private set; } } internal class AttributeAttribute : Attribute { internal AttributeAttribute(string attribute) { Attribute = attribute; } internal string Attribute { get; private set; } } I would like to restrict the SchemaAttribute to classes, and the AttributeAttribute to properties. Is this doable?

    Read the article

  • Accepts Nested Attributes For - edit form displays incorrect number of items ( + !map:ActiveSupport:

    - by Brightbyte8
    Hi, I have a teacher profile model which has many subjects (separate model). I want to add subjects to the profile on the same form for creating/editing a profile. I'm using accepts_nested_attributes for and this works fine for creation. However on the edit page I am getting a very strange error - instead of seeing 3 subjects (I added three at create and a look into the console confirms this), I see 12 subjects(!). #Profile model class Profile < ActiveRecord::Base has_many :subjects accepts_nested_attributes_for :subjects end #Subject Model class Subject < ActiveRecord::Base belongs_to :profile end #Profile Controller (only showing deviations from normal RESTFUL setup) def new @profile = Profile.new 3.times do @profile.subjects.build end end #Here's 1 of three parts of the subject output of = debug @profile errors: !ruby/object:ActiveRecord::Errors base: *id004 errors: !map:ActiveSupport::OrderedHash {} subjects: - &id001 !ruby/object:Subject attributes: exam: Either name: "7" created_at: 2010-04-15 10:38:13 updated_at: 2010-04-15 10:38:13 level: Either id: "31" profile_id: "3" attributes_cache: {} # Note that 3 of these attributes are displayed despite me seeing 12 subjects on screen Other info in case it's relevant. Rails: 2.3.5 Ruby 1.8.7 p149 HAML I've never had so much difficulty with a bug before - I've already lost about 8 hours to it. Would really appreciate any help! Thanks to any courageous takers Jack

    Read the article

  • Alternative to Nested Loop For Comparison

    - by KGVT
    I'm currently writing a program that needs to compare each file in an ArrayList of variable size. Right now, the way I'm doing this is through a nested code loop: if(tempList.size()>1){ for(int i=0;i<=tempList.size()-1;i++) //Nested loops. I should feel dirty? for(int j=i+1;j<=tempList.size()-1;j++){ //*Gets sorted. System.out.println(checkBytes(tempList.get(i), tempList.get(j))); } } I've read a few differing opinions on the necessity of nested loops, and I was wondering if anyone had a more efficient alternative. At a glance, each comparison is going to need to be done, either way, so the performance should be fairly steady, but I'm moderately convinced there's a cleaner way to do this. Any pointers?

    Read the article

  • Nested attributes in the index view?

    - by user283179
    How would I show one of many nested objects in the index view class Album < ActiveRecord::Base has_many: photos accepts_nested_attributes_for :photos, :reject_if => proc { |a| a.all? { |k, v| v.blank?} } has_one: cover accepts_nested_attributes_for :cover end class Album Controller < ApplicationController layout "mini" def index @albums = Album.find(:all, :include => [:cover,]).reverse respond_to do |format| format.html # index.html.erb format.xml { render :xml => @albums } end end This is what I have so fare. I just want to show a cover for each album. Any info on this would be a massive help!!

    Read the article

  • has_one | nested attributes -

    - by user283179
    How would I show one of many nested objects in the index view class Album < ActiveRecord::Base has_many: photos accepts_nested_attributes_for :photos, :reject_if => proc { |a| a.all? { |k, v| v.blank?} } has_one: cover accepts_nested_attributes_for :cover end class Album Controller < ApplicationController layout "mini" def index @albums = Album.find(:all, :include => [:cover,]).reverse respond_to do |format| format.html # index.html.erb format.xml { render :xml => @albums } end end This is what I have so fare. I just want to show a cover for each album. Any info on this would be a massive help!!

    Read the article

  • StructureMap with my own attributes in C#

    - by ridecar2
    Hi All, I have an attribute that I have written that has a dependency on the Data Access Layer so I made a constructor that took the DAL class as a parameter (marked with [DefaultConstructor] and another, blank, constructor that is parameterless. When I call a method that depends on the attribute how do I make StructureMap inject the correct type? Thanks Gareth

    Read the article

  • Custom Attributes on Class Members

    - by ccook
    I am using a Custom Attribute to define how a class's members are mapped to properties for posting as a form post (Payment Gateway). I have the custom attribute working just fine, and am able to get the attribute by "name", but would like to get the attribute by the member itself. For example: getFieldName("name"); vs getFieldName(obj.Name); The plan is to write a method to serialize the class with members into a postable string. Here's the test code I have at this point, where ret is a string and PropertyMapping is the custom attribute: foreach (MemberInfo i in (typeof(CustomClass)).GetMember("Name")) { foreach (object at in i.GetCustomAttributes(true)) { PropertyMapping map = at as PropertyMapping; if (map != null) { ret += map.FieldName; } } } Thanks in advance!

    Read the article

  • Nested class or not nested class?

    - by eriks
    I have class A and list of A objects. A has a function f that should be executed every X seconds (for the first instance every 1 second, for the seconds instance every 5 seconds, etc.). I have a scheduler class that is responsible to execute the functions at the correct time. What i thought to do is to create a new class, ATime, that will hold ptr to A instance and the time A::f should be executed. The scheduler will hold a min priority queue of Atime. Do you think it is the correct implementation? Should ATime be a nested class of the scheduler?

    Read the article

  • Updating nested attributes causes duplicate entries

    - by params_noob
    I have a has_many and belongs_to relationship between Job and Address. When I try to update Job and Address in the same form, it updates job but creates a duplicate entry for Address. Am I missing something here? The Edit and Update Actions from Jobs: def edit @job = Job.find(params[:id]) end def update @job = Job.find(params[:id]) if @job.update_attributes(job_params) flash[:success] = "Job Updated" redirect_to current_user else render 'edit' end end The edit form: <h1>Edit Job Information</h1> <div class="row"> <div class="span6 offset3"> <%= form_for(@job) do |f| %> <%= render 'shared/error_messages' %> <%= f.label :recipient %> <%= f.text_field :recipient %> <%= f.label :age %> <%= f.text_field :age %> <%= f.label :gender %> <%= f.text_field :gender %> <%= f.label :ethnicity %> <%= f.text_field :ethnicity %> <%= f.label :height %> <%= f.text_field :height %> <%= f.label :weight %> <%= f.text_field :weight %> <%= f.label :hair %> <%= f.text_field :hair %> <%= f.label :eyes %> <%= f.text_field :eyes %> <%= f.label :other_info %> <%= f.text_field :other_info %> <h3> Address Information </h3> <%= f.fields_for :addresses do |address| %> <%= address.label :label, "Label" %> <%= address.text_field :label %> <%= address.label :addy, "Address" %> <%= address.text_field :addy %> <%= address.label :apt, "Apt/Suite/etc" %> <%= address.text_field :apt %> <%= address.label :city, "City" %> <%= address.text_field :city %> <%= address.label :state, "State" %> <%= address.text_field :state %> <%= address.label :zip, "Zip code" %> <%= address.text_field :zip %> <% end %> <%= f.label :instructions, "Service Instructions" %> <%= f.text_field :instructions %> <%= check_box_tag(:rush) %> <%= label_tag(:rush, "Rush?") %> <%= f.submit "Update Job", class: "btn btn-large btn-primary" %> <% end %> </div> </div>

    Read the article

  • rails search nested set (categories and sub categories)

    - by bob
    Hello, I am using the http://github.com/collectiveidea/awesome_nested_set awesome nested set plugin and currently, if I choose a sub category as my category_id for an item, I can not search by its parent. Category.parent Category.Child I choose Category.child as the category that my item is in. So now my item has category_id of 4 stored in it. If I go to a page in my rails application, lets say teh Category page and I am on the Category.parent's page, I want to show products that have category_id's of all the descendants as well. So ideally i want to have a find method that can take into account the descendants. You can get the descendants of a root by calling root.descendants (a built in plugin method). How would I go about making it so I can query a find that gets the descendants of a root instead of what its doing now which is binging up nothing unless the product had a specific category_id of the Category.parent. I hope I am being clear here. I either need to figure out a way to create a find method or named_scope that can query and return an array of objects that have id's corresponding tot he descendants of a root OR if I have any other options, what are they? I thought about creating a field in my products table like parent_id which can keep track of the parent so i can then create two named scopes one finding the parent stuff and one finding the child stuff and chaining them. I know I can create a named scope for each child and chain them together for multiple children but this seems a very tedious process and also, if you add more children, you would need to specify more named scopes.

    Read the article

  • How Do I Prevent Rails From Treating Updated Nested Attributes Differently From New Nested Attribute

    - by James
    I am using rails3 beta3 and couchdb via couchrest. I am not using active record. I want to add multiple "Sections" to a "Guide" and add and remove sections dynamically via a little javascript. I have looked at all the screencasts by Ryan Bates and they have helped immensely. The only difference is that I want to save all the sections as an array of sections instead of individual sections. Basically like this: "sections" => [{"title" => "Foo1", "content" => "Bar1"}, {"title" => "Foo2", "content" => "Bar2"}] So, basically I need the params hash to look like that when the form is submitted. When I create my form I am doing the following: <%= form_for @guide, :url => { :action => "create" } do |f| %> <%= render :partial => 'section', :collection => @guide.sections %> <%= f.submit "Save" %> <% end %> And my section partial looks like this: <%= fields_for "sections[]", section do |guide_section_form| %> <%= guide_section_form.text_field :section_title %> <%= guide_section_form.text_area :content, :rows => 3 %> <% end %> Ok, so when I create the guide with sections, it is working perfectly as I would like. The params hash is giving me a sections array just like I would want. The problem comes when I want edit guide/sections and save them again because rails is inserting the id of the guide in the id and name of each form field, which is screwing up the params hash on form submission. Just to be clear, here is the raw form output for a new resource: <input type="text" size="30" name="sections[][section_title]" id="sections__section_title"> <textarea rows="3" name="sections[][content]" id="sections__content" cols="40"></textarea> And here is what it looks like when editing an existing resource: <input type="text" value="Foo1" size="30" name="sections[cd2f2759895b5ae6cb7946def0b321f1][section_title]" id="sections_cd2f2759895b5ae6cb7946def0b321f1_section_title"> <textarea rows="3" name="sections[cd2f2759895b5ae6cb7946def0b321f1][content]" id="sections_cd2f2759895b5ae6cb7946def0b321f1_content" cols="40">Bar1</textarea> How do I force rails to always use the new resource behavior and not automatically add the id to the name and value. Do I have to create a custom form builder? Is there some other trick I can do to prevent rails from putting the id of the guide in there? I have tried a bunch of stuff and nothing is working. Thanks in advance!

    Read the article

  • Why should I prepend my custom attributes with "data-"?

    - by Horace Loeb
    So any custom data attribute that I use should start with "data-": <li class="user" data-name="John Resig" data-city="Boston" data-lang="js" data-food="Bacon"> <b>John says:</b> <span>Hello, how are you?</span> </li> Will anything bad happen if I just ignore this? I.e.: <li class="user" name="John Resig" city="Boston" lang="js" food="Bacon"> <b>John says:</b> <span>Hello, how are you?</span> </li> I guess one bad thing is that my custom attributes could conflict with HTML attributes with special meanings (e.g., name), but aside from this, is there a problem with just writing "example_text" instead of "data-example_text"? (It won't validate, but who cares?)

    Read the article

  • documenting class attributes

    - by intuited
    I'm writing a lightweight class whose attributes are intended to be publicly accessible, and only sometimes overridden in specific instantiations. There's no provision in the Python language for creating docstrings for class attributes, or any sort of attributes, for that matter. What is the accepted way, should there be one, to document these attributes? Currently I'm doing this sort of thing: class Albatross(object): """A bird with a flight speed exceeding that of an unladen swallow. Attributes: """ flight_speed = 691 __doc__ += """ flight_speed (691) The maximum speed that such a bird can attain. """ nesting_grounds = "Raymond Luxury-Yacht" __doc__ += """ nesting_grounds ("Raymond Luxury-Yacht") The locale where these birds congregate to reproduce. """ def __init__(**keyargs): """Initialize the Albatross from the keyword arguments.""" self.__dict__.update(keyargs) Although this style doesn't seem to be expressly forbidden in the docstring style guidelines, it's also not mentioned as an option. The advantage here is that it provides a way to document attributes alongside their definitions, while still creating a presentable class docstring, and avoiding having to write comments that reiterate the information from the docstring. I'm still kind of annoyed that I have to actually write the attributes twice; I'm considering using the string representations of the values in the docstring to at least avoid duplication of the default values. Is this a heinous breach of the ad hoc community conventions? Is it okay? Is there a better way? For example, it's possible to create a dictionary containing values and docstrings for the attributes and then add the contents to the class __dict__ and docstring towards the end of the class declaration; this would alleviate the need to type the attribute names and values twice. edit: this last idea is, I think, not actually possible, at least not without dynamically building the class from data, which seems like a really bad idea unless there's some other reason to do that. I'm pretty new to python and still working out the details of coding style, so unrelated critiques are also welcome.

    Read the article

  • C++ non-member functions for nested template classes

    - by beldaz
    I have been writing several class templates that contain nested iterator classes, for which an equality comparison is required. As I believe is fairly typical, the comparison is performed with a non-member (and non-friend) operator== function. In doing so, my compiler (I'm using Mingw32 GCC 4.4 with flags -O3 -g -Wall) fails to find the function and I have run out of possible reasons. In the rather large block of code below there are three classes: a Base class, a Composed class that holds a Base object, and a Nested class identical to the Composed class except that it is nested within an Outer class. Non-member operator== functions are supplied for each. These classes are in templated and untemplated forms (in their own respective namespaces), with the latter equivalent to the former specialised for unsigned integers. In main, two identical objects for each class are compared. For the untemplated case there is no problem, but for the templated case the compiler fails to find operator==. What's going on? #include <iostream> namespace templated { template<typename T> class Base { T t_; public: explicit Base(const T& t) : t_(t) {} bool equal(const Base& x) const { return x.t_==t_; } }; template<typename T> bool operator==(const Base<T> &x, const Base<T> &y) { return x.equal(y); } template<typename T> class Composed { typedef Base<T> Base_; Base_ base_; public: explicit Composed(const T& t) : base_(t) {} bool equal(const Composed& x) const {return x.base_==base_;} }; template<typename T> bool operator==(const Composed<T> &x, const Composed<T> &y) { return x.equal(y); } template<typename T> class Outer { public: class Nested { typedef Base<T> Base_; Base_ base_; public: explicit Nested(const T& t) : base_(t) {} bool equal(const Nested& x) const {return x.base_==base_;} }; }; template<typename T> bool operator==(const typename Outer<T>::Nested &x, const typename Outer<T>::Nested &y) { return x.equal(y); } } // namespace templated namespace untemplated { class Base { unsigned int t_; public: explicit Base(const unsigned int& t) : t_(t) {} bool equal(const Base& x) const { return x.t_==t_; } }; bool operator==(const Base &x, const Base &y) { return x.equal(y); } class Composed { typedef Base Base_; Base_ base_; public: explicit Composed(const unsigned int& t) : base_(t) {} bool equal(const Composed& x) const {return x.base_==base_;} }; bool operator==(const Composed &x, const Composed &y) { return x.equal(y); } class Outer { public: class Nested { typedef Base Base_; Base_ base_; public: explicit Nested(const unsigned int& t) : base_(t) {} bool equal(const Nested& x) const {return x.base_==base_;} }; }; bool operator==(const Outer::Nested &x, const Outer::Nested &y) { return x.equal(y); } } // namespace untemplated int main() { using std::cout; unsigned int testVal=3; { // No templates first typedef untemplated::Base Base_t; Base_t a(testVal); Base_t b(testVal); cout << "a=b=" << testVal << "\n"; cout << "a==b ? " << (a==b ? "TRUE" : "FALSE") << "\n"; typedef untemplated::Composed Composed_t; Composed_t c(testVal); Composed_t d(testVal); cout << "c=d=" << testVal << "\n"; cout << "c==d ? " << (c==d ? "TRUE" : "FALSE") << "\n"; typedef untemplated::Outer::Nested Nested_t; Nested_t e(testVal); Nested_t f(testVal); cout << "e=f=" << testVal << "\n"; cout << "e==f ? " << (e==f ? "TRUE" : "FALSE") << "\n"; } { // Now with templates typedef templated::Base<unsigned int> Base_t; Base_t a(testVal); Base_t b(testVal); cout << "a=b=" << testVal << "\n"; cout << "a==b ? " << (a==b ? "TRUE" : "FALSE") << "\n"; typedef templated::Composed<unsigned int> Composed_t; Composed_t c(testVal); Composed_t d(testVal); cout << "c=d=" << testVal << "\n"; cout << "d==c ? " << (c==d ? "TRUE" : "FALSE") << "\n"; typedef templated::Outer<unsigned int>::Nested Nested_t; Nested_t e(testVal); Nested_t f(testVal); cout << "e=f=" << testVal << "\n"; cout << "e==f ? " << (e==f ? "TRUE" : "FALSE") << "\n"; // Above line causes compiler error: // error: no match for 'operator==' in 'e == f' } cout << std::endl; return 0; }

    Read the article

  • radius traffic accounting - what attributes do I use for traffic (and how)

    - by Mark Regensberg
    we are building a web front end for a internet access token management system that uses radius (freeradius) queried from a captive portal. Reason for building this part is the integration into the accounting and billing platform that operates behind the scenes (all other parts are currently available open source software) The structure is fairly standard, and setting up the basic bits were easy enough (authentication, traffic updates from the captive portal, account expiry date/times) - but I seem to have run out of ability when it comes to limiting an account by traffic consumed. So we can: set up usernames / passwords set expiry dates/times for a given user see the traffic for that user being accurately updated in RADACCT But we can't figure out the correct way/attribute to expire a user when they have consumed X octets of traffic. What attributes are used, or - maybe more accurately - what would be the correct way to use these attributes to limit an account to a certain volume of traffic? Any links to documentation appreciated - freeradius documentation doesn't seem to address the issue directly, or I'm looking in the wrong place... --mark

    Read the article

  • can't delete some files or change their attributes on my FTP server

    - by Revolter
    I've installed a CMS on a shared host running Apache, now when I was deleting the root directory with FTP, some folders left with a "Permission denied" error and I can't change their attributes. the best explanation I've got is that the CMS installer has placed the files and has assigned its ownership to the Apache server instead of my user name. (i don't know it can be done) Ijust haven't use the uninstaller because I've lost my admin password - -" so how to delete those folders ?

    Read the article

  • Is it a bad practice to add extra attributes to html elements?

    - by burak ozdogan
    Hi, Sometimes I add an attribute to some of my controls. Like: <a href id="myLlink" isClimber="True">Chris Sharma</a> I know it is not a valid html. But it helps me in some cases. Is this considered as a bad practice? A friend of mine says that it is ok for Intranet environment but on internet it might not be find friendly by search engines. If it is not a good practice, what are the best practicess? Thanks

    Read the article

  • Subterranean IL: Pseudo custom attributes

    - by Simon Cooper
    Custom attributes were designed to make the .NET framework extensible; if a .NET language needs to store additional metadata on an item that isn't expressible in IL, then an attribute could be applied to the IL item to represent this metadata. For instance, the C# compiler uses DecimalConstantAttribute and DateTimeConstantAttribute to represent compile-time decimal or datetime constants, which aren't allowed in pure IL, and FixedBufferAttribute to represent fixed struct fields. How attributes are compiled Within a .NET assembly are a series of tables containing all the metadata for items within the assembly; for instance, the TypeDef table stores metadata on all the types in the assembly, and MethodDef does the same for all the methods and constructors. Custom attribute information is stored in the CustomAttribute table, which has references to the IL item the attribute is applied to, the constructor used (which implies the type of attribute applied), and a binary blob representing the arguments and name/value pairs used in the attribute application. For example, the following C# class: [Obsolete("Please use MyClass2", true)] public class MyClass { // ... } corresponds to the following IL class definition: .class public MyClass { .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = { string('Please use MyClass2' bool(true) } // ... } and results in the following entry in the CustomAttribute table: TypeDef(MyClass) MemberRef(ObsoleteAttribute::.ctor(string, bool)) blob -> {string('Please use MyClass2' bool(true)} However, there are some attributes that don't compile in this way. Pseudo custom attributes Just like there are some concepts in a language that can't be represented in IL, there are some concepts in IL that can't be represented in a language. This is where pseudo custom attributes come into play. The most obvious of these is SerializableAttribute. Although it looks like an attribute, it doesn't compile to a CustomAttribute table entry; it instead sets the serializable bit directly within the TypeDef entry for the type. This flag is fully expressible within IL; this C#: [Serializable] public class MySerializableClass {} compiles to this IL: .class public serializable MySerializableClass {} For those interested, a full list of pseudo custom attributes is available here. For the rest of this post, I'll be concentrating on the ones that deal with P/Invoke. P/Invoke attributes P/Invoke is built right into the CLR at quite a deep level; there are 2 metadata tables within an assembly dedicated solely to p/invoke interop, and many more that affect it. Furthermore, all the attributes used to specify p/invoke methods in C# or VB have their own keywords and syntax within IL. For example, the following C# method declaration: [DllImport("mscorsn.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.U1)] private static extern bool StrongNameSignatureVerificationEx( [MarshalAs(UnmanagedType.LPWStr)] string wszFilePath, [MarshalAs(UnmanagedType.U1)] bool fForceVerification, [MarshalAs(UnmanagedType.U1)] ref bool pfWasVerified); compiles to the following IL definition: .method private static pinvokeimpl("mscorsn.dll" lasterr winapi) bool marshal(unsigned int8) StrongNameSignatureVerificationEx( string marshal(lpwstr) wszFilePath, bool marshal(unsigned int8) fForceVerification, bool& marshal(unsigned int8) pfWasVerified) cil managed preservesig {} As you can see, all the p/invoke and marshal properties are specified directly in IL, rather than using attributes. And, rather than creating entries in CustomAttribute, a whole bunch of metadata is emitted to represent this information. This single method declaration results in the following metadata being output to the assembly: A MethodDef entry containing basic information on the method Four ParamDef entries for the 3 method parameters and return type An entry in ModuleRef to mscorsn.dll An entry in ImplMap linking ModuleRef and MethodDef, along with the name of the function to import and the pinvoke options (lasterr winapi) Four FieldMarshal entries containing the marshal information for each parameter. Phew! Applying attributes Most of the time, when you apply an attribute to an element, an entry in the CustomAttribute table will be created to represent that application. However, some attributes represent concepts in IL that aren't expressible in the language you're coding in, and can instead result in a single bit change (SerializableAttribute and NonSerializedAttribute), or many extra metadata table entries (the p/invoke attributes) being emitted to the output assembly.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >