Search Results

Search found 405 results on 17 pages for 'decorator chaining'.

Page 6/17 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Chaining your own method in Ruby on Rails

    - by steven_noble
    In my Rails app, I am used to using syntax like the following in a number of places, including helpers/application_helper.rb: def my_method(x,y) return x+y end I am also used to calling the resulting method from basically anywhere in my app using syntax like this: my_method(2,3) However, I'd like to be able to use syntax like like this: class_from_my_rails_app.my_method(3) How and where do I define my_method so I can use it like this? I'm happy to consult the documentation, but I just don't know what the latter style is called. What do you call it? Many thanks, Steven.

    Read the article

  • chaining and getting the value of an input

    - by cf_PhillipSenn
    This code gets the text that's in a certain column of a table row: var keyA = $(a).children('td').eq(column).text().toUpperCase(); Q: How do I rewrite this to get the value of an input tag that's in the table cell? var keyA = $(a).children('td').eq(column).('input').val().toUpperCase();

    Read the article

  • Design considerations for temporarily transforming a player into an animal in a role playing game

    - by mikedev
    I am working on a role playing game for fun and to practice design patterns. I would like players to be able to transform themselves into different animals. For example, a Druid might be able to shape shift into a cheetah. Right now I'm planning on using the decorator pattern to do this but my question is - how do I make it so that when a druid is in the cheetah form, they can only access skills for the cheetah? In other words, they should not be able to access their normal Druid skills. Using the decorator pattern it appears that even in the cheetah form my druid will be able to access their normal druid skills. class Druid : Character { // many cool druid skills and spells void LightHeal(Character target) { } } abstract class CharacterDecorator : Character { Character DecoratedCharacter; } class CheetahForm : CharacterDecorator { Character DecoratedCharacter; public CheetahForm(Character decoratedCharacter) { DecoratedCharacter= decoratedCharacter; } // many cool cheetah related skills void CheetahRun() { // let player move very fast } } now using the classes Druid myDruid = new Druid(); myDruid.LightHeal(myDruid); // casting light heal here is fine myDruid = new CheetahForm(myDruid); myDruid.LightHeal(myDruid); // casting here should not be allowed Hmmmm...now that I think about it, will myDruid be unable to us the Druid class spells/skills unless the class is down-casted? But even if that's the case, is there a better way to ensure that myDruid at this point is locked out from all Druid related spells/skills until it is cast back to a Druid (since currently it's in CheetahForm)

    Read the article

  • how is FLUENT api different from other API

    - by intern
    i have come across fluent api while studying DSLs. i have searched alot on FLUENT API..the basic conclusion which i could draw out was that fluent api uses method chaining in order to make the code fluent. but i cannot understand that in object oriented languages we can always create an object and can call the methods related to it. then how is FLUENT api different from it? what other features does fluent api add?

    Read the article

  • Python Decorators and inheritance

    - by wheaties
    Help a guy out. Can't seem to get a decorator to work with inheritance. Broke it down to the simplest little example in my scratch workspace. Still can't seem to get it working. class bar(object): def __init__(self): self.val = 4 def setVal(self,x): self.val = x def decor(self, func): def increment(self, x): return func( self, x ) + self.val return increment class foo(bar): def __init__(self): bar.__init__(self) @decor def add(self, x): return x Oops, name "decor" is not defined. Okay, how about @bar.decor? TypeError: unbound method "decor" must be called with a bar instance as first argument (got function instance instead) Ok, how about @self.decor? Name "self" is not defined. Ok, how about @foo.decor?! Name "foo" is not defined. AaaaAAaAaaaarrrrgggg... What am I doing wrong?

    Read the article

  • PHP: Prevent chained method from returning?

    - by Industrial
    Hi, I am having some headaches regarding method chaining for a quite simple PHP class that returns a value, which sometimes need to go through a decryption process: $dataset = new Datacontainer; $key = $dataset->get('key'); $key2 = $dataset->get('key')->decrypt(); The get method is where the return lives. So the call to the decrypt method on the second row isn't going to work in its current state. Can I do something to setup the get method to return only when nothing is chained to it, or what would be the best way to re-factor this code?

    Read the article

  • Named keywords in decorators?

    - by wheaties
    I've been playing around in depth with attempting to write my own version of a memoizing decorator before I go looking at other people's code. It's more of an exercise in fun, honestly. However, in the course of playing around I've found I can't do something I want with decorators. def addValue( func, val ): def add( x ): return func( x ) + val return add @addValue( val=4 ) def computeSomething( x ): #function gets defined If I want to do that I have to do this: def addTwo( func ): return addValue( func, 2 ) @addTwo def computeSomething( x ): #function gets defined Why can't I use keyword arguments with decorators in this manner? What am I doing wrong and can you show me how I should be doing it?

    Read the article

  • Create inherited class from base class

    - by Raj
    public class Car { private string make; private string model; public Car(string make, string model) { this.make = make; this.model = model; } public virtual void Display() { Console.WriteLine("Make: {0}", make); Console.WriteLine("Model: {0}", model); } public string Make { get{return make;} set{make = value;} } public string Model { get{return model;} set{model = value;} } } public class SuperCar:Car { private Car car; private int horsePower; public SuperCar(Car car) { this.car = car; } public int HorsePower { get{return horsePower;} set{horsepower = value;} } public override void Display() { base.Display(); Console.WriteLine("I am a super car"); } When I do something like Car myCar = new Car("Porsche", "911"); SuperCar mySupcar = new SuperCar(myCar); mySupcar.Display(); I only get "I am a supercar" but not the properties of my base class. Should I explicitly assign the properties of my base class in the SuperCar constructor? In fact I'm trying Decorator pattern where I want a class to add behaviour to a base class.

    Read the article

  • Struts2 Sitemesh not working in WAS 6 server

    - by Jithin
    I have a struts2-spring application which works fine in jetty server but when i try migrating it to WAS 6 the decorator(sitemesh) is not getting applied. The server logs shows no error.Is this a known issue ? my web.xml looks like this <filter> <filter-name>action2-cleanup</filter-name> <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> </filter> <filter> <filter-name>sitemesh</filter-name> <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class> </filter> <filter> <filter-name>action2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>action2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>action2-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping>

    Read the article

  • Can a C# method chain be "too long"?

    - by ccornet
    Not in terms of readability, naturally, since you can always arrange the separate methods into separate lines. Rather, is it dangerous, for any reason, to chain an excessively large number of methods together? I use method chaining primarily to save space on declaring individual one-use variables, and traditionally using return methods instead of methods that modify the caller. Except for string methods, those I kinda chain mercilessly. In any case, I worry sometimes about the impact of using exceptionally long method chains all in one line. Let's say I need to update the value of one item based on someone's username. Unfortunately, the shortest method to retrieve the correct user looks something like the following. SPWeb web = GetWorkflowWeb(); SPList list2 = web.Lists["Wars"]; SPListItem item2 = list2.GetItemById(3); SPListItem item3 = item2.GetItemFromLookup("Armies", "Allied Army"); SPUser user2 = item2.GetSPUser("Commander"); SPUser user3 = user2.GetAssociate("Spouse"); string username2 = user3.Name; item1["Contact"] = username2; Everything with a 2 or 3 lasts for only one call, so I might condense it as the following (which also lets me get rid of a would-be-superfluous 1): SPWeb web = GetWorkflowWeb(); item["Contact"] = web.Lists["Armies"] .GetItemById(3) .GetItemFromLookup("Armies", "Allied Army") .GetSPUser("Commander") .GetAssociate("Spouse") .Name; Admittedly, it looks a lot longer when it is all in one line and when you have int.Parse(ddlArmy.SelectedValue.CutBefore(";#", false)) instead of 3. Nevertheless, this is one of the average lengths of these chains, and I can easily foresee some of exceptionally longer counts. Excluding readability, is there anything I should be worried about for these 10+ method chains? Or is there no harm in using really really long method chains?

    Read the article

  • Enum "copy" problem

    - by f0b0s
    Hi all! I have a class, let's call it A. It has a enum (E) and a method Foo(E e), with gets E in the arguments. I want to write a wrapper (decorator) W for A. So it'll have its own method Foo(A::E). But I want to have some kind of encapsulation, so this method should defined as Foo(F f), where F is another enum defined in W, that can be converted to A::E. For example: class A { public: enum E { ONE, TWO, THREE }; void Foo(E e); }; class B { //enum F; // ??? void Foo(F f) { a_.Foo(f); } private: A a_; }; How F should be defined? I don't want to copy value like this: enum F { ONE = A::ONE, TWO = A::TWO, THREE = A::THREE }; because its a potential error in the near feature. Is the typedef definition: typedef A::E F; is the best decision? Is it legal?

    Read the article

  • How do I use ViewScripts on Zend_Form File Elements?

    - by Sonny
    I am using this ViewScript for my standard form elements: <div class="field" id="field_<?php echo $this->element->getId(); ?>"> <?php if (0 < strlen($this->element->getLabel())) : ?> <?php echo $this->formLabel($this->element->getName(), $this->element->getLabel());?> <?php endif; ?> <span class="value"><?php echo $this->{$this->element->helper}( $this->element->getName(), $this->element->getValue(), $this->element->getAttribs() ) ?></span> <?php if (0 < $this->element->getMessages()->length) : ?> <?php echo $this->formErrors($this->element->getMessages()); ?> <?php endif; ?> <?php if (0 < strlen($this->element->getDescription())) : ?> <span class="hint"><?php echo $this->element->getDescription(); ?></span> <?php endif; ?> </div> Trying to use that ViewScript alone results in an error: Exception caught by form: No file decorator found... unable to render file element Looking at this FAQ revealed part of my problem, and I updated my form element decorators like this: 'decorators' => array( array('File'), array('ViewScript', array('viewScript' => 'form/field.phtml')) ) Now it's rendering the file element twice, once within my view script, and extra elements with the file element outside my view script: <input type="hidden" name="MAX_FILE_SIZE" value="8388608" id="MAX_FILE_SIZE" /> <input type="hidden" name="UPLOAD_IDENTIFIER" value="4b5f7335a55ee" id="progress_key" /> <input type="file" name="upload_file" id="upload_file" /> <div class="field" id="field_upload_file"> <label for="upload_file">Upload File</label> <span class="value"><input type="file" name="upload_file" id="upload_file" /></span> </div> Any ideas on how to handle this properly with a ViewScript?

    Read the article

  • Haskell: monadic takeWhile?

    - by Mark Rushakoff
    I have some functions written in C that I call from Haskell. These functions return IO (CInt). Sometimes I want to run all of the functions regardless of what any of them return, and this is easy. For sake of example code, this is the general idea of what's happening currently: Prelude> let f x = print x >> return x Prelude> mapM_ f [0..5] 0 1 2 3 4 5 Prelude> I get my desired side effects, and I don't care about the results. But now I need to stop execution immediately after the first item that doesn't return my desired result. Let's say a return value of 4 or higher requires execution to stop - then what I want to do is this: Prelude> takeWhile (<4) $ mapM f [0..5] Which gives me this error: <interactive:1:22: Couldn't match expected type `[b]' against inferred type `IO a' In the first argument of `mapM', namely `f' In the second argument of `($)', namely `mapM f ([0 .. 5])' In the expression: takeWhile (< 4) $ mapM f ([0 .. 5]) And that makes sense to me - the result is still contained in the IO monad, and I can't just compare two values contained in the IO monad. I know this is precisely the purpose of monads -- chaining results together and discarding operations when a certain condition is met -- but is there an easy way to "wrap up" the IO monad in this case to stop executing the chain upon a condition of my choosing, without writing an instance of MonadPlus? Can I just "unlift" the values from f, for the purposes of the takeWhile? Is this a solution where functors fit? Functors haven't "clicked" with me yet, but I sort of have the impression that this might be a good situation to use them. Update: @sth has the closest answer to what I want - in fact, that's almost exactly what I was going for, but I'd still like to see whether there is a standard solution that isn't explicitly recursive -- this is Haskell, after all! Looking back on how I worded my question, now I can see that I wasn't clear enough about my desired behavior. The f function I used above for an example was merely an example. The real functions are written in C and used exclusively for their side effects. I can't use @Tom's suggestion of mapM_ f (takeWhile (&lt;4) [0..5]) because I have no idea whether any input will really result in success or failure until executed. I don't actually care about the returned list, either -- I just want to call the C functions until either the list is exhausted or the first C function returns a failure code. In C-style pseudocode, my behavior would be: do { result = function_with_side_effects(input_list[index++]); } while (result == success && index < max_index); So again, @sth's answer performs the exact behavior that I want, except that the results may (should?) be discarded. A dropWhileM_ function would be equivalent for my purposes. Why isn't there a function like that or takeWhileM_ in Control.Monad? I see that there was a similar discussion on a mailing list, but it appears that nothing has come of that.

    Read the article

  • ASP.NET MVC Routing Via Method Attributes

    - by TorgoGuy
    In the StackOverflow Podcast #54, Jeff mentions they register their URL routes in the StackOverflow codebase via an attribute above the method that handles the route. Sounds like a good concept (with the caveat that Phil Haack brought up regarding route priorities). Could someone provide some sample to to make this happen? Also, any "best practices" for using this style of routing?

    Read the article

  • Java method missing (ala Ruby) for decorating?

    - by cibercitizen1
    Is there any technique available in Java for intercepting messages (method calls) like the method_missing technique in Ruby? This would allow coding decorators and proxies very easily, like in Ruby: :Client p:Proxy im:Implementation ------- ---------- ----------------- p.foo() -------> method_missing() do_something im.foo() ------------------> do_foo p.bar() --------> method_missing() do_something_more im.bar() -------------------> do_bar (Note: Proxy only has one method: method_missing())

    Read the article

  • JSF 2 Scriptmanager style functionality

    - by CDSO1
    I need to be able to add some javascript to all ajax postback responses (PartialViewContext.isAjaxRequest == true) but I am not succeeding with any implementation I try. I have tried implementing a PhaseListener and adding my script using PartialResponseWriter.insert* to add eval blocks, as well as trying to add the script by creating a script element. (Results in CDATA cannot nest, or just invalid XML) I have tried decorating PartialViewContextFactory to override the PartialViewContext.processPartial and add the script after the wrapped instance has processed it... How should I go about adding sripts to an Ajax response? Something similar to what .NET has with Scriptmanager.registerClientScriptBlock preferably. Thank you

    Read the article

  • how to pass in dynamic data to decorators

    - by steve
    Hi, I am trying to write a base crud controller class that does the following: class BaseCrudController: model = "" field_validation = {} template_dir = "" @expose(self.template_dir) def new(self, *args, **kwargs) .... @validate(self.field_validation, error_handler=new) @expose() def post(self, *args, **kwargs): ... My intent is to have my controllers extend this base class, set the model, field_validation, and template locations, and am ready to go. Unfortunately, decorators (to my understanding), are interpreted when the function is defined. Hence it won't have access to instance's value. Is there a way to pass in dynamic data or values from the sub class? If not, I guess I could use override_template as a workaround to expose and set the template within the controller action. How would I go about validating the form within the controller action? Thanks, Steve

    Read the article

  • should jQuery data be chainable?

    - by pedalpete
    I'm trying to add multiple jQuery data entries to a single element. I suspected that the following would work jQuery('td.person#a'+personId).data('email',thisPerson.email).data('phone',thisPerson.phone); However, I am getting nothing but errors when I do this. jQuery('td.person#a'+personId).data('email',thisPerson.email); jQuery('td.person#a'+personId).data('phone',thisPerson.phone); is there another way to get more than one data entry on an element? Hopefully chained?

    Read the article

  • How can I check if Zend_Form_Elements has no decorators set

    - by jiewmeng
    I find that even if I just declare an element like $this->addElement('textarea', 'txt1'); I find that it already has decorators set Zend_Debug::dump($this->getElement('txt1')->getDecorators()); http://pastebin.com/7Y24g62w I want to test that I didn't set decorators using setDecorators() or using something like $this->addElement('textarea', 'txt1', array( 'decorators' => array(...) )); If I didn't set any decorators then apply default decorators, how can I do that. I want to apply default decorators per element basis, not using Zend_Form#setDisableLoadDefaultDecoraotrs()

    Read the article

  • Multi-argument decorators in 2.6

    - by wheaties
    Generally don't do OO-programming in Python. This project requires it and am running into a bit of trouble. Here's my scratch code for attempting to figure out where it went wrong: class trial(object): def output( func, x ): def ya( self, y ): return func( self, x ) + y return ya def f1( func ): return output( func, 1 ) @f1 def sum1( self, x ): return x which doesn't compile. I've attempted to add the @staticmethod tag to the "output" and "f1" functions but to no avail. Normally I'd do this def output( func, x ): def ya( y ): return func( x ) + y return ya def f1( func ): return output( func, 1 ) @f1 def sum1( x ): return x which does work. So how do I get this going in a class?

    Read the article

  • Combine SQL statement

    - by ninumedia
    I have 3 tables (follows, postings, users) follows has 2 fields - profile_id , following_id postings has 3 fields - post_id, profile_id, content users has 3 fields - profile_id, first_name, last_name I have a follows.profile_id value of 1 that I want to match against. When I run the SQL statement below I get the 1st step in obtaining the correct data. However, I now want to match the postings.profile_id of this resulting set against the users table so each of the names (first and last name) are displayed as well for all the listed postings. Thank you for your help! :) Ex: SELECT * FROM follows JOIN postings ON follows.following_id = postings.profile_id WHERE follows.profile_id = 1

    Read the article

  • dynamically decorating objects in c#

    - by Oren Mazor
    is it possible to easily and dynamically decorate an object? for example, lets say I have a List<PointF>. this list is actually a plot of the sine function. I'd like to go through these points and add a flag to each PointF of whether it's a peak or not. but I don't want to create a new extended SpecialPointF or whatever, that has a boolean property. judge me all you want for being lazy, but laziness is how awesome ideas are born (also bad ideas)

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >