Search Results

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

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

  • Decorator Pattern - Multiple wrappers or quantity property?

    - by Jiminizer
    I'm making use of the decorator pattern for one of the first times, as part of a Uni project. As far as I can see, the pattern seems to be meant more for adding functionality in a modular manner, however we've been taught it with uses such as a coffee or pizza maker, where the object has modular components that are added - changing properties rather than behaviour. I'm trying to make the most of both uses, however I've come up with a question. In the example in the book we're using (Head First Design Patterns), the pattern is used in a coffee shop creating different coffees. So, for example, milk, froth, sugar, sprinkles are all decorators. How would you implement a system that used the same decorator multiple times (for example, a coffee with two sugars)? Would you rewrap the coffee, or give sugar a quantity property? Or (as i'm starting to suspect) would this never be an issue as the pattern isn't designed to be used this way?

    Read the article

  • When using method chaining, do I reuse the object or create one?

    - by MainMa
    When using method chaining like: var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create(); there may be two approaches: Reuse the same object, like this: public Car PaintedIn(Color color) { this.Color = color; return this; } Create a new object of type Car at every step, like this: public Car PaintedIn(Color color) { var car = new Car(this); // Clone the current object. car.Color = color; // Assign the values to the clone, not the original object. return car; } Is the first one wrong or it's rather a personal choice of the developer? I believe that he first approach may quickly cause the intuitive/misleading code. Example: // Create a car with neither color, nor model. var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor); // Create several cars based on the neutral car. var yellowCar = mercedes.PaintedIn(Color.Yellow).Create(); var specificModel = mercedes.OfModel(99).Create(); // Would `specificModel` car be yellow or of neutral color? How would you guess that if // `yellowCar` were in a separate method called somewhere else in code? Any thoughts?

    Read the article

  • Adding a class to the $tag surrounding a <label> in a Zend_Form with the Label decorator

    - by Roderik
    I'm trying to get the following html out of Zend_Form <div class="group wat-cf"> <div class="left"> <label class="label right">Username</label> </div> <div class="right"> <input type="text" class="text_field"> </div> </div> Using the following code: $username->setAttrib("class", "text_field") ->setDecorators(array( 'ViewHelper', 'Description', 'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'div', 'class' => 'right')), array('Label', array('tag' => 'div', 'class' => 'label right')), array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class' => 'group wat-cf')) )); I can get the next fragment <div class="group wat-cf"> <div id="username-label"> <label for="username" class="label right required">Username:</label> </div> <div class="right"> <input type="text" name="username" id="username" value="" class="text_field"> </div> </div> so apart from some extra id's and required classes i don't mind, i need to get a class "left" on div id="username-label" Now adding class to the Label line, gets the class added on the element. I also don't see and option to do this in the Label decorator code itself. So i need a custom Label decorator, or is there some other way i'm missing?

    Read the article

  • Can Eclipse generate method-chaining setters

    - by Chris R
    I'd like to generate method-chaining setters (setters that return the object being set), like so: public MyObject setField (Object value) { this.field = value; return this; } This makes it easier to do one-liner instantiations, which I find easier to read: myMethod (new MyObject ().setField (someValue).setOtherField (someOtherValue)); Can Eclipse's templates be modified to do this? I've changed the content to include return this; but the signature is not changed.

    Read the article

  • access django session from a decorator

    - by ed1t
    I have a decorator that I use for my views @valid_session from django.http import Http404 def valid_session(the_func): """ function to check if the user has a valid session """ def _decorated(*args, **kwargs): if ## check if username is in the request.session: raise Http404('not logged in.') else: return the_func(*args, **kwargs) return _decorated I would like to access my session in my decoartor. When user is logged in, I put the username in my session.

    Read the article

  • Python class decorator and maximum recursion depth exceeded

    - by Michal Lula
    I try define class decorator. I have problem with __init__ method in decorated class. If __init__ method invokes super the RuntimeError maximum recursion depth exceeded is raised. Code example: def decorate(cls): class NewClass(cls): pass return NewClass @decorate class Foo(object): def __init__(self, *args, **kwargs): super(Foo, self).__init__(*args, **kwargs) What I doing wrong? Thanks, Michal

    Read the article

  • How to assure applying order of function decorators in Python?

    - by Satoru.Logic
    Some decorators should only be used in the outermost layer. A decorator that augments the original function and add a configure parameter is one example. from functools import wraps def special_case(f): @wraps(f) def _(a, b, config_x=False): if config_x: print "Special case here" return return f(a, b) How can I avoid decorators like this getting decorated by another decorator? EDIT It is really disgusting to let everyone trying to apply a new decorator worry about the application order. So, is it possible to avoid this kind of situation? Is it possible to add a config option without introducing a new parameter?

    Read the article

  • Decorator not calling the decorated instance - alternative design needed

    - by Daniel Hilgarth
    Assume I have a simple interface for translating text (sample code in C#): public interface ITranslationService { string GetTranslation(string key, CultureInfo targetLanguage); // some other methods... } A first simple implementation of this interface already exists and simply goes to the database for every method call. Assuming a UI that is being translated at start up this results in one database call per control. To improve this, I want to add the following behavior: As soon as a request for one language comes in, fetch all translations from this language and cache them. All translation requests are served from the cache. I thought about implementing this new behavior as a decorator, because all other methods of that interface implemented by the decorater would simple delegate to the decorated instance. However, the implementation of GetTranslation wouldn't use GetTranslation of the decorated instance at all to get all translations of a certain language. It would fire its own query against the database. This breaks the decorator pattern, because every functionality provided by the decorated instance is simply skipped. This becomes a real problem if there are other decorators involved. My understanding is that a Decorator should be additive. In this case however, the decorator is replacing the behavior of the decorated instance. I can't really think of a nice solution for this - how would you solve it? Everything is allowed, even a complete re-design of ITranslationService itself.

    Read the article

  • How to implement exception chaining in PHP

    - by Josef Sábl
    Constructor for PHP's exception has third parameter, documentation says: $previous: The previous exception used for the exception chaining. But I can't make it work. My code looks like this: try { throw new Exception('Exception 1', 1001); } catch (Exception $ex) { throw new Exception('Exception 2', 1002, $ex); } I expect Exception 2 to be thrown and I expect that it will have Exception 1 attached. But all I get is: Fatal error: Wrong parameters for Exception([string $exception [, long $code ]]) in ... What am I doing wrong?

    Read the article

  • Inside a decorator-class, access instance of the class which contains the decorated method

    - by ifischer
    I have the following decorator, which saves a configuration file after a method decorated with @saveconfig is called: class saveconfig(object): def __init__(self, f): self.f = f def __call__(self, *args): self.f(object, *args) # Here i want to access "cfg" defined in pbtools print "Saving configuration" I'm using this decorator inside the following class. After the method createkvm is called, the configuration object self.cfg should be saved inside the decorator: class pbtools() def __init__(self): self.configfile = open("pbt.properties", 'r+') # This variable should be available inside my decorator self.cfg = ConfigObj(infile = self.configfile) @saveconfig def createkvm(self): print "creating kvm" My problem is that i need to access the object variable self.cfg inside the decorator saveconfig. A first naive approach was to add a parameter to the decorator which holds the object, like @saveconfig(self), but this doesn't work. How can I access object variables of the method host inside the decorator? Do i have to define the decorator inside the same class to get access?

    Read the article

  • C++ input chaining in C#

    - by Monty
    I am trying to learn C# coming from C++. I am writing just some basic console stuff to get a feel for it and was wondering if it is possible to do simple chaining of inputs in C#. For example in C++: cout<<"Enter two numbers: "; cin >> int1 >> int2; You could then just input 3 5 and hit enter and the values will be fine. In C# however I have to split it up(as far as I can tell) like this: Console.Write("Enter the first number: "; int1 = (char)Console.Read(); Console.Writeline(""); Console.Write("Enter the second number: "; int2 = (char)Console.Read(); Maybe I am just missing something.

    Read the article

  • Decorator for determining HTTP response from a view

    - by polera
    I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far: from django.shortcuts import render_to_response from django.http import HttpResponse from django.template.loader import render_to_string def raw_response(template): def wrap(view): def response(request,*args,**kwargs): if request.method == "GET": try: if request.GET['raw'] == "1": render = HttpResponse(render_to_string(template,{}),content_type="text/plain") return render except Exception: render = render_to_response(template,{}) return render return response return wrap Currently, the {} is there just as a place holder. Ultimately, I'd like to be able to pass a dict like this: @raw_response('my_template_name.html') def view_name(request): render({"x":42}) Any assistance is appreciated.

    Read the article

  • C++ method chaining including class constructor

    - by jena
    Hello, I'm trying to implement method chaining in C++, which turns out to be quite easy if the constructor call of a class is a separate statement, e.g: Foo foo; foo.bar().baz(); But as soon as the constructor call becomes part of the method chain, the compiler complains about expecting ";" in place of "." immediately after the constructor call: Foo foo().bar().baz(); I'm wondering now if this is actually possible in C++. Here is my test class: class Foo { public: Foo() { } Foo& bar() { return *this; } Foo& baz() { return *this; } }; I also found an example for "fluent interfaces" in C++ (http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B) which seems to be exactly what I'm searching for. However, I get the same compiler error for that code. Thanks in advance for any hint. Best, Jean

    Read the article

  • Help with authorization and redirection decorator in python (pylons)

    - by ensnare
    I'm trying to write a simple decorator to check the authentication of a user, and to redirect to the login page if s/he is not authenticated: def authenticate(f): try: if user['authenticated'] is True: return f except: redirect_to(controller='login', action='index') class IndexController(BaseController): @authenticate def index(self): return render('/index.mako' ) But this approach doesn't work. When a user is authenticated, everything is fine. But when the user is not authenticated, redirect_to() doesn't work and I am given this error: HTTPFound: 302 Found Content-Type: text/html; charset=UTF-8 Content-Length: 0 location: /login Thank for your help!

    Read the article

  • Django: Staff Decorator

    - by Mark
    I'm trying to write a "staff only" decorator for Django, but I can't seem to get it to work: def staff_only(error='Only staff may view this page.'): def _dec(view_func): def _view(request, *args, **kwargs): u = request.user if u.is_authenticated() and u.is_staff: return view_func(request, *args, **kwargs) messages.error(request, error) return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('home'))) _view.__name__ = view_func.__name__ _view.__dict__ = view_func.__dict__ _view.__doc__ = view_func.__doc__ return _view return _dec Trying to follow lead from here. I'm getting: 'WSGIRequest' object has no attribute '__name__' But if I take those 3 lines out, I just get a useless "Internal Server Error". What am I doing wrong here?

    Read the article

  • Is it an example of decorator pattern?

    - by Supereme
    Hi, I've an example please tell me whether it is Decorator pattern or not? public abstract class ComputerComponent { String description ="Unknown Type"; public String getDescription() { return description; } public abstract double getCost(); } public abstract class AccessoryDecorator { ComputerComponent comp; public abstract String getDescription(); } public class PIIIConcreteComp extends ComputerComponent { public PIIIConcreteComp() { description=“Pentium III”; } public double getCost() { return 19950.00; } public class floppyConcreteDeco extends AccessoryDecorator { public floppyConcreteDeco(ComputerComponent comp) this.comp=comp; } public String getDescription() { return comp.getDescription() +”, floppy 1.44 mb”; } public double getCost() { return 250+comp.getCost(); } } public class ComponentAssembly { public static void createComponent() { ComputerComponent comp = new PIIConcreteComp(); // create a PIII computer object ComputerComponent deco1= new floppyConcreteDeco(comp); // decorate it with a floppy //ComputerComponent deco2= newCDRomConcreteDeco(deco1); ComputerComponent deco2= new floppyConcreteDeco(deco1); // decorate with a CDRom or with one more floppy System.out.println( deco2.getdescription() +” “+ deco2.getCost(); } } Thank you.

    Read the article

  • Entity Framework Decorator Pattern

    - by Anthony Compton
    In my line of business we have Products. These products can be modified by a user by adding Modifications to them. Modifications can do things such as alter the price and alter properties of the Product. This, to me, seems to fit the Decorator pattern perfectly. Now, envision a database in which Products exist in one table and Modifications exist in another table and the database is hooked up to my app through the Entity Framework. How would I go about getting the Product objects and the Modification objects to implement the same interface so that I could use them interchangeably? For instance, the kind of things I would like to be able to do: Given a Modification object, call .GetNumThings(), which would then return the number of things in the original object, plus or minus the number of things added by the modification. This question may be stemming from a pretty serious lack of exposure to the nitty-gritty of EF (all of my experience so far has been pretty straight-forward LOB Silverlight apps), and if that's the case, please feel free to tell me to RTFM. Thanks in advance!

    Read the article

  • Can I call sitemesh struts tags from a decorator in freemarker?

    - by fool4jesus
    I know if you are using JSPs, you can call struts tags defined the normal way from a decorator, like this: <html> <body> <decorator:body /> </body> </html> but in the examples I always see using freemarker decorators, they will instead say: <html> <body> ${body} </body> </html> Is this the only way to include the pieces of the page from the decorator, or is it possible to use the same taglibs? To test it, I put sitemesh-decorator.tld into WEB-INF/lib and tried just using <@decorator.body /> but no joy there. I think I'm missing something here, but I'm not sure what it is.

    Read the article

  • trouble chaining proxies

    - by proxy error
    trouble chaining proxies hows it going? i am having trouble chaining proxies. i open terminal, run nano /etc/proxychains.conf i add the list like this [ProxyList] add proxy here ... meanwile defaults set to "tor" socks4 127.0.0.1 9050 socks5 59.21.114.99 5577 i open a new tab, run proxychains firefox all i get is this ProxyChains-3.1 (http://proxychains.sf.net) firefox opens but when i google my ip address it is not what it says in the list pleaqse help

    Read the article

  • Copy call signature to decorator

    - by Morgoth
    If I do the following def mydecorator(f): def wrapper(*args, **kwargs): f(*args, **kwargs) wrapper.__doc__ = f.__doc__ wrapper.__name__ = f.__name__ return wrapper @mydecorator def myfunction(a,b,c): '''My docstring''' pass And then type help myfunction, I get: Help on function myfunction in module __main__: myfunction(*args, **kwargs) My docstring So the name and docstring are correctly copied over. Is there a way to also copy over the actual call signature, in this case (a, b, c)?

    Read the article

  • Routing in Php and decorator pattern

    - by Joey Salac Hipolito
    I do not know if I am using the term 'routing' correctly, but here is the situation: I created an .htaccess file to 'process' (dunno if my term is right) the url of my application, like this : RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)$ index.php?url=$1 [QSA,L] Now I have this : http://appname/controller/method/parameter http://appname/$url[0]/$url[1]/$url[2] What I did is: setup a default controller, in case it is not specified in the url setup a Controller wrapper I did it like this $target = new $url[0]() $controller = new Controller($target) The problem with that one is that I can't use the methods in the object I passed in the constructor of the Controller: I resolved it like this : class Controller { protected $target; protected $view; public function __construct($target, $view) { $this->target = $target; $this->view = $view; } public function __call($method, $arguments) { if (method_exists($this->target, $method)) { return call_user_func_array(array($this->target, $method), $arguments); } } } This is working fine, the problem occurs in the index where I did the routing, here it is if(isset($url[2])){ if(method_exists($controller, $url[1])){ $controller->$url[1]($url[2]) } } else { if(method_exists($controller, $url[1])){ $controller->$url[1]() } } where $controller = new Controller($target) The problem is that the method doesn't exist, although I can use it directly without checking if method exist, how can I resolve this?

    Read the article

  • PHP OOP: Method Chaining

    - by Isis
    I have the following code, <?php class Templater { static $params = array(); public static function assign($name, $value) { self::$params[] = array($name => $value); } public static function draw() { self::$params; } } $test = Templater::assign('key', 'value'); $test = Templater::draw(); print_r($test); How can I alter this script so I could use this? $test = Templater::assign('key', 'value')->assign('key2', 'value2')->draw(); print_r($test);

    Read the article

  • Zend Framework decorator subform add a class tag to DD wrapper tag

    - by Samuele
    I have this form: class Request_Form_Prova extends Zend_Form { public function init() { $this->setMethod('post'); $SubForm_Step = new Zend_Form_SubForm(); $SubForm_Step->setAttrib('class','Step'); $this->addSubform($SubForm_Step, 'Chicco'); $PrivacyCheck = $SubForm_Step->createElement('CheckBox', 'PrivacyCheck'); $PrivacyCheck->setLabel('I have read and I agre bla bla...') ->setRequired(true) ->setUncheckedValue(''); $PrivacyCheck->getDecorator('Label')->setOption('class', 'inline'); $SubForm_Step->addElement($PrivacyCheck); $SubForm_Step->addElement('submit', 'submit', array( 'ignore' => true, 'label' => 'OK', )); } } That generate this HTML: <form enctype="application/x-www-form-urlencoded" method="post" action=""> <dl class="zend_form"> <dt id="Chicco-label">&nbsp;</dt> <dd id="Chicco-element"> <fieldset id="fieldset-Chicco" class="Step"> <dl> <dt id="Chicco-PrivacyCheck-label"><label for="Chicco-PrivacyCheck" class="inline required">I have read and I agre bla bla...</label></dt> <dd id="Chicco-PrivacyCheck-element"> <input type="hidden" name="Chicco[PrivacyCheck]" value=""><input type="checkbox" name="Chicco[PrivacyCheck]" id="Chicco-PrivacyCheck" value="1"> </dd> <dt id="submit-label">&nbsp;</dt> <dd id="submit-element"> <input type="submit" name="Chicco[submit]" id="Chicco-submit" value="OK"> </dd> </dl> </fieldset> </dd> </dl> </form> How can I add a class="Test" to the <dd id="Chicco-element"> elemnt? In order to have it like that: <dd id="Chicco-element" class="Test"> I thought something like that but it don't work: $SubForm_Step->getDecorator('DdWrapper')->setOption('class', 'Test'); OR $SubForm_Step->getDecorator('DtDdWrapper')->setOption('class', 'Test'); How can I do it? And last question: How can I wrap that DD and DT element of a SubForm in another DL element? Like that: ( second line ) <dl class="zend_form"> <dl> <dt id="Chicco-label">&nbsp;</dt> <dd id="Chicco-element"> <fieldset id="fieldset-Chicco" class="Step"> <dl> .......

    Read the article

  • jQuery:Problem in Chaining the events.

    - by Shyju
    I have the following javascript function which will load data from a server page to the div This is working fine with the FadeIn/FadeOut effects function ShowModels(manuId) { var div = $("#rightcol"); div.fadeOut('slow',function() { div.load("../Lib/handlers/ModelLookup.aspx?mode=bymanu&mid="+manuId, { symbol: $("#txtSymbol" ).val() }, function() { $(this).fadeIn(); }); }); } Now i want to Show a Loading Message till the div loads the contents from the server page I tried this.But its not working.Can any one help me to debug this ? Thanks in advance function ShowModels(manuId) { var div = $("#rightcol"); var strLoadingMsg="<img src='loading.gif'/><h3>Loading...</h3>"; div.fadeOut('slow',function() { div.load(strLoadingMsg,function(){ div.load("../Lib/handlers/ModelLookup.aspx?mode=bymanu&mid="+manuId, { symbol: $("#txtSymbol" ).val() }, function() { $(this).fadeIn(); }); }); }); } My ultimate requirement is to FadeOut the current content.Show the Loading message.Show the Data coming from server with a FadeIn effect

    Read the article

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