Search Results

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

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

  • Adding a decorator that converts strings to lowercase in Python

    - by user2905382
    So I am new to learning decorators and I have gone through countless tutorials and while I understand and can mostly follow all of the examples, I think the best way to learn, would be to implement a decorator myself. So I am going to use this example below. I realize a decorator is not at all necessary to do this, but for the sake of learning, I would like to add a decorator that filters the strings like dog name and breed and turns them into lowercase. Any ideas or pointers in the right direction would be appreciated. class Dogs: totalDogs = 0 dogList=[] def __init__(self, breed, color, age): self.breed=breed self.color=color self.age=age Dogs.dogList.append(self.breed) Dogs.totalDogs += 1 def displayDogs(self): print "breed: ", self.breed print "color: ",self.color print "age: ",self.age print "list of breeds:", Dogs.dogList print "total dogs: ", Dogs.totalDogs def somedecorator(*args): #now what terrier=Dogs("TeRrIer", "white", 5) terrier.displayDogs() retriever=Dogs("goldenRETRIEVER", "brown", 10) retriever.displayDogs()

    Read the article

  • Can I use the decorator pattern to wrap a method body?

    - by mgroves
    I have a bunch of methods with varying signatures. These methods interact with a fragile data connection, so we often use a helper class to perform retries/reconnects, etc. Like so: MyHelper.PerformCall( () => { doStuffWithData(parameters...) }); And this works fine, but it can make the code a little cluttery. What I would prefer to do is decorate the methods that interact with the data connection like so: [InteractsWithData] protected string doStuffWithData(parameters...) { // do stuff... } And then essentially, whenever doStuffWithData is called, the body of that method would be passed in as an Action to MyHelper.PerformCall(). How do I do this?

    Read the article

  • Freeware Local Proxy for Proxy Chaining with HTTPAUTH

    - by pepoluan
    I am looking for a freeware local proxy to perform proxy-chaining with HTTPAUTH. To explain my situation: In my workplace I am forced to keep switching between several internet-connected apps, and thus everytime I have to type in the credentials (or, at least, click on 'OK' to send my previously-saved credential). To make matters more annoying, the proxy login times out every 30 minutes, requiring me to lather-rinse-repeat the whole annoyance. I'd like to just point them all to a locally installed proxy which will on its own perform the required HTTPAUTH against the corporate proxy. I've tried Cntlm, but it always fail to authenticate (and according to this thread, that is due to the proxy using HTTPAUTH which is not supported by Cntlm) Any suggestions? ETA: I found Polipo, but it's kinda wonky on Windows. Especially if I visit a new URL, and the DNS server is a bit slow, then Polipo will simply drop/refuse the connection. And I have to put my password in plaintext. If there's a better suggestion, I'm all ears.

    Read the article

  • Is this a good or bad way to use constructor chaining? (... to allow for testing).

    - by panamack
    My motivation for chaining my class constructors here is so that I have a default constructor for mainstream use by my application and a second that allows me to inject a mock and a stub. It just seems a bit ugly 'new'-ing things in the ":this(...)" call and counter-intuitive calling a parametrized constructor from a default constructor , I wondered what other people would do here? (FYI - SystemWrapper) using SystemWrapper; public class MyDirectoryWorker{ // SystemWrapper interface allows for stub of sealed .Net class. private IDirectoryInfoWrap dirInf; private FileSystemWatcher watcher; public MyDirectoryWorker() : this( new DirectoryInfoWrap(new DirectoryInfo(MyDirPath)), new FileSystemWatcher()) { } public MyDirectoryWorker(IDirectoryInfoWrap dirInf, FileSystemWatcher watcher) { this.dirInf = dirInf; if(!dirInf.Exists){ dirInf.Create(); } this.watcher = watcher; watcher.Path = dirInf.FullName; watcher.NotifyFilter = NotifyFilters.FileName; watcher.Created += new FileSystemEventHandler(watcher_Created); watcher.Deleted += new FileSystemEventHandler(watcher_Deleted); watcher.Renamed += new RenamedEventHandler(watcher_Renamed); watcher.EnableRaisingEvents = true; } public static string MyDirPath{get{return Settings.Default.MyDefaultDirPath;}} // etc... }

    Read the article

  • ZendX Jquery Decorator

    - by iJD
    How use partial decorator in Jquery Element I use this code for Form Element: $title = new Zend_Form_Element_Text('title'); $title->setRequired(true) ->setAttrib('class', 'inputbox') ->setLabel('Title'); $title->viewScript = 'RegElement.phtml'; $title->setDecorators( array( array('ViewScript', array('class' => 'RegElement')) ) ); But when i use Jquery Element i dont know how implement it: $datePicker = new ZendX_JQuery_Form_Element_DatePicker( "datePicker1", array("label" => "Date:") ); $datePicker->viewScript = 'RegElement.phtml'; $datePicker->setDecorators( array( array('ViewScript', array('class' => 'RegElement')) ) ); //views/scripts/RegElement.phtml <li class="row <?php echo $this->class ?>"> <div class="cont-error"> <?php echo $this->formErrors($this->element->getMessages()); ?> </div> <div class="rowfields"> <?php echo $this->formLabel($this->element->getName(), $this->element->getLabel()) ?> <?php echo $this->{$this->element->helper}( $this->element->getName(), $this->element->getValue(), $this->element->getAttribs() ) ?> </div> <div class="hint"><?php echo $this->element->getDescription() ?></div> </li> And display this error: Warning: Exception caught by form: Cannot render jQuery form element without at least one decorator implementing the 'ZendX_JQuery_Form_Decorator_UiWidgetElementMarker' interface. I need display datePicker with same format. but idk how implement this interface. thx for your help.

    Read the article

  • When should a method of a class return the same instance after modifying itself?

    - by modiX
    I have a class that has three methods A(), B() and C(). Those methods modify the own instance. While the methods have to return an instance when the instance is a separate copy (just as Clone()), I got a free choice to return void or the same instance (return this;) when modifying the same instance in the method and not returning any other value. When deciding for returning the same modified instance, I can do neat method chains like obj.A().B().C();. Would this be the only reason for doing so? Is it even okay to modify the own instance and return it, too? Or should it only return a copy and leave the original object as before? Because when returning the same modified instance the user would maybe admit the returned value is a copy, otherwise it would not be returned? If it's okay, what's the best way to clarify such things on the method?

    Read the article

  • Decorator pattern in C++

    - by AlgoMan
    Can someone give me an example of Decorator pattern in C++ ? I have come across the Java version of it. But C++ i have found it difficult to understand the examples that are given.

    Read the article

  • Optimizing a memoization decorator not increase call stack

    - by Tyler Crompton
    I have a very, very basic memoization decorator that I need to optimize below: def memoize(function): memos = {} def wrapper(*args): try: return memos[args] except KeyError: pass result = function(*args) memos[args] = result return result return wrapper The goal is to make this so that it doesn't add on to the call stack. It actually doubles it right now. I realize that I can embed this on a function by function basis, but that is not desired as I would like a global solution for memoizing. Any ideas?

    Read the article

  • Decorator Module Standard

    - by Kyle Terry
    I was wondering if it's frowned upon to use the decorator module that comes with python. Should I be creating decorators using the original means or is it considered okay practice to use the module?

    Read the article

  • Auto-register class methods using decorator

    - by adamk
    I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties). Example code: class my_class(object): @register(prop1,prop2) def my_method( arg1,arg2 ): # method code here... @register(prop3,prop4) def my_other_method( arg1,arg2 ): # method code here... I want that when loading is done, somewhere there will be a dict containing: { "my_class.my_method" : ( prop1, prop2 ) "my_class.my_other_method" : ( prop3, prop4 ) } Is this possible?

    Read the article

  • Daisy-chaining network switches with multiple cables

    - by user72153
    This might just be the dumbest question you'll ever read, but I digress. Say I have two 100Mbps Ethernet switches with 2 computers on each, connected together by a single cable. This way, the two PCs on each switch share the 100Mbps bandwidth with the others. If I added another cable between the 2 switches, would there be 200Mbps throughput available between the switches? Or am I completely off my rocker? Thanks for the help.

    Read the article

  • OpenVPN Chaining

    - by noderunner
    I'm trying to set up an OpenVPN "chain", similar to what is described here. I have two separate networks, A and B. Each network has an OpenVPN server using a standard "road warrior" or "client/server" approach. A client can connect to either one for access to the hosts/services on that respective network. But server A and B are also connected to each other. The servers on each network have a "site-to-site" connection between the two. What I'm trying to accomplish, is the ability to connect to network A as a client, and then make connections with hosts on network B. I'm using tun/routing for all of the VPN connections. The "chain" looks something like this: [Client] --- [Server A] --- [Server A] --- [Server B] --- [Server B] --- [Host B] (tun0) (tun0) (tun1) (tun0) (eth0) (eth0) The whole idea is that server A should route traffic destined to network B through the "site-to-site" VPN set up on tun1 when a client from tun0 tries to connect. I did this simply by setting up two connection profiles on server A. One profile is a standard server config running on tun0, defining a virtual client network, IP address pool, pushing routes, etc. The other is a client connection to Server B running on tun1. With ip_forwarding enabled, I then simply added a "push route" to the clients advertising a route to network B. On server A, this seems to work when I look at tcpdump output. If I connect as a client, and then ping a host on network B, I can see the traffic getting passed from tun0 to tun1 on Server A: tcpdump -nSi tun1 icmp The weird thing is that I don't see Server B receiving that traffic through the tunnel. It's as if Server A is sending it through the site-to-site connection like it should, but server B is completely ignoring it. When I look for the traffic on Server B, it simply isn't there. A ping from Server A -- Host B works fine. But a ping from a client connected to Server A to host B does not. I'm wondering if Server B is ignoring the traffic because the source IP does not match the client IP pool that it hands out to clients? Does anyone know if I need to do something on Server B in order for it to see the traffic? This is a complicated problem to explain, so thanks if you stuck with me this far.

    Read the article

  • zend_form ViewScript decorator / passing arguments

    - by timpone
    I have a form that is extend from Zend_Form. I am placing the form into a ViewScript decorator like this: $this->setDecorators(array(array('ViewScript', array('viewScript' => 'game/forms/game-management.phtml')))); I'd like to pass in a variable to this ViewScript but am not sure how this could be done. Since the partial renders out as a Zend_View (allowing $this-app_store_icon for rendering), it seems like there should be a way to pass variables to be rendered. I tried the following but to no avail. $this->setDecorators(array(array('ViewScript', array('viewScript' => 'game/forms/game-management.phtml'),array('app_store_picon'=>$current_app_store_picon)))); Any help on how to get this done would be appreciated. thanks

    Read the article

  • python decorator to modify variable in current scope

    - by AlexH
    Goal: Make a decorator which can modify the scope that it is used in. If it worked: class Blah(): # or perhaps class Blah(ParentClassWhichMakesThisPossible) def one(self): pass @decorated def two(self): pass Blah.decorated ["two"] Why? I essentially want to write classes which can maintain specific dictionaries of methods, so that I can retrieve lists of available methods of different types on a per class basis. errr..... I want to do this: class RuleClass(ParentClass): @rule def blah(self): pass @rule def kapow(self): pass def shazam(self): class OtherRuleClass(ParentClass): @rule def foo(self): pass def bar(self): pass RuleClass.rules.keys() ["blah", "kapow"] OtherRuleClass.rules.keys() ["foo"]

    Read the article

  • python decorator to add function to list in current scope

    - by AlexH
    Goal: Make a decorator which can modify the scope that it is used in. If it worked: class Blah(): # or perhaps class Blah(ParentClassWhichMakesThisPossible) def one(self): pass @decorated def two(self): pass Blah.decorated ["two"] Why? I essentially want to write classes which can maintain specific dictionaries of methods, so that I can retrieve lists of available methods of different types on a per class basis. errr..... I want to do this: class RuleClass(ParentClass): @rule def blah(self): pass @rule def kapow(self): pass def shazam(self): class OtherRuleClass(ParentClass): @rule def foo(self): pass def bar(self): pass RuleClass.rules.keys() ["blah", "kapow"] OtherRuleClass.rules.keys() ["foo"]

    Read the article

  • What we call this kind of chaining in C#

    - by Thinking
    Can you please tell me what kind of construct in C# is this. Code Golf: Numeric equivalent of an Excel column name C.WriteLine(C.ReadLine() .Reverse() .Select((c, i) => (c - 64) * System.Math.Pow(26, i)) .Sum()); Though I am new to C# (only two months exp so far), but since the time I have joined a C# team, I have never seen this kind of chaining. It really attracted me and I want to learn more about it. Please give some insight about this.

    Read the article

  • Constructors and method chaining in JavaScript

    - by Sethen Maleno
    I am trying to make method chaining work in conjunction with my constructors, but I am not exactly sure how to go about it. Here is my code thus far: function Points(one, two, three) { this.one = one; this.two = two; this.three = three; } Points.prototype = { add: function() { return this.result = this.one + this.two + this.three; }, multiply: function() { return this.result * 30; } } var some = new Points(1, 1, 1); console.log(some.add().multiply()); I am trying to call the multiply method on the return value of the add method. I know there is something obvious that I am not doing, but I am just not sure what it is. Any thoughts?

    Read the article

  • Singleton Pattern combine with a Decorator

    - by Mike
    Attached is a classic Decorator pattern. My question is how would you modify the below code so that you can wrap zero or one of each topping on to the Pizza Right now I can have a Pepporini - Sausage -- Pepporini -- Pizza class driving the total cost up to $10, charging twice for Pepporini. I don't think I want to use the Chain of Responsibility pattern as order does not matter and not all toppings are used? Thank you namespace PizzaDecorator { public interface IPizza { double CalculateCost(); } public class Pizza: IPizza { public Pizza() { } public double CalculateCost() { return 8.00; } } public abstract class Topping : IPizza { protected IPizza _pizzaItem; public Topping(IPizza pizzaItem) { this._pizzaItem = pizzaItem; } public abstract double CalculateCost(); } public class Pepporini : Topping { public Pepporini(IPizza pizzaItem) : base(pizzaItem) { } public override double CalculateCost() { return this._pizzaItem.CalculateCost() + 0.50; } } public class Sausage : Topping { public Sausage(IPizza pizzaItem) : base(pizzaItem) { } public override double CalculateCost() { return this._pizzaItem.CalculateCost() + 1.00; } } public class Onions : Topping { public Onions(IPizza pizzaItem) : base(pizzaItem) { } public override double CalculateCost() { return this._pizzaItem.CalculateCost() + .25; } } }

    Read the article

  • Castle, sharing a transient component between a decorator and a decorated component

    - by Marius
    Consider the following example: public interface ITask { void Execute(); } public class LoggingTaskRunner : ITask { private readonly ITask _taskToDecorate; private readonly MessageBuffer _messageBuffer; public LoggingTaskRunner(ITask taskToDecorate, MessageBuffer messageBuffer) { _taskToDecorate = taskToDecorate; _messageBuffer = messageBuffer; } public void Execute() { _taskToDecorate.Execute(); Log(_messageBuffer); } private void Log(MessageBuffer messageBuffer) {} } public class TaskRunner : ITask { public TaskRunner(MessageBuffer messageBuffer) { } public void Execute() { } } public class MessageBuffer { } public class Configuration { public void Configure() { IWindsorContainer container = null; container.Register( Component.For<MessageBuffer>() .LifeStyle.Transient); container.Register( Component.For<ITask>() .ImplementedBy<LoggingTaskRunner>() .ServiceOverrides(ServiceOverride.ForKey("taskToDecorate").Eq("task.to.decorate"))); container.Register( Component.For<ITask>() .ImplementedBy<TaskRunner>() .Named("task.to.decorate")); } } How can I make Windsor instantiate the "shared" transient component so that both "Decorator" and "Decorated" gets the same instance? Edit: since the design is being critiqued I am posting something closer to what is being done in the app. Maybe someone can suggest a better solution (if sharing the transient resource between a logger and the true task is considered a bad design)

    Read the article

  • decorator pattern

    - by vbNewbie
    I have a program that converts currency using a specific design pattern. I now need to take my converted result and using the decorator pattern allow the result to be converted to 3 different formats: 1 - exponential notation, rounded to 2 decimal points. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Converter { public partial class Form1 : Form { // Setup Chain of Responsibility Handler h1 = new USDHandler(); Handler h2 = new CADHandler(); Handler h3 = new AUDHandler(); public string reqCurName; public int reqAmt; public string results; public string requestID; public Form1() { InitializeComponent(); h1.SetSuccessor(h2); h2.SetSuccessor(h3); } // "Handler" private void button1_Click_1(object sender, EventArgs e) { reqCurName = txtInput.Text; reqAmt = Convert.ToInt32(txtAmt.Text.ToString()); results = h1.HandleRequest(reqCurName, reqAmt); if (results != "") { lblResult.Text = results; lblResult.Visible = true; } } abstract class Handler { protected Handler successor; public string retrn; public void SetSuccessor(Handler successor) { this.successor = successor; } public abstract string HandleRequest(string requestID, int reqAmt); } // "USD Handler" class USDHandler : Handler { public override string HandleRequest(string requestID, int reqAmt) { if (requestID == "USD") { retrn = "Request handled by " + this.GetType().Name + " \nConversion from Euro to USD is " + reqAmt/0.630479; return (retrn); } else if (successor != null) { retrn = successor.HandleRequest(requestID, reqAmt); } return (retrn); } } // "CAD Handler" class CADHandler : Handler { public override string HandleRequest(string requestID, int reqAmt) { if (requestID == "CAD") { retrn = "Request handled by " + this.GetType().Name + " \nConversion from Euro to CAD is " + reqAmt /0.617971; return (retrn); } else if (successor != null) { retrn = successor.HandleRequest(requestID, reqAmt); } return (retrn); } } // "AUD Handler" class AUDHandler : Handler { public override string HandleRequest(string requestID, int reqAmt) { if (requestID == "AUD") { requestID = "Request handled by " + this.GetType().Name + " \nConversion from Euro to AUD is " + reqAmt / 0.585386; return (requestID); } else if (successor != null) { retrn = successor.HandleRequest(requestID, reqAmt); } return (requestID); } } } }

    Read the article

  • hash table with chaining method program freezing

    - by Justin Carrey
    I am implementing hash table in C using linked list chaining method. The program compiles but when inserting a string in hash table, the program freezes and gets stuck. The program is below: struct llist{ char *s; struct llist *next; }; struct llist *a[100]; void hinsert(char *str){ int strint, hashinp; strint = 0; hashinp = 0; while(*str){ strint = strint+(*str); } hashinp = (strint%100); if(a[hashinp] == NULL){ struct llist *node; node = (struct llist *)malloc(sizeof(struct llist)); node->s = str; node->next = NULL; a[hashinp] = node; } else{ struct llist *node, *ptr; node = (struct llist *)malloc(sizeof(struct llist)); node->s = str; node->next = NULL; ptr = a[hashinp]; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = node; } } void hsearch(char *strsrch){ int strint1, hashinp1; strint1 = 0; hashinp1 = 0; while(*strsrch){ strint1 = strint1+(*strsrch); } hashinp1 = (strint1%100); struct llist *ptr1; ptr1 = a[hashinp1]; while(ptr1 != NULL){ if(ptr1->s == strsrch){ cout << "Element Found\n"; break; } else{ ptr1 = ptr1->next; } } if(ptr1 == NULL){ cout << "Element Not Found\n"; } } hinsert() is to insert elements into hash and hsearch is to search an element in the hash. Hash function is written inside hinsert() itself. In the main(), what i am initializing all the elements in a[] to be NULL like this: for(int i = 0;i < 100; i++){ a[i] = NULL; } Help is very much appreciated. Thanks !

    Read the article

  • confused about python decorators

    - by nbv4
    I have a class that has an output() method which returns a matplotlib Figure instance. I have a decorator I wrote that takes that fig instance and turns it into a Django response object. My decorator looks like this: class plot_svg(object): def __init__(self, view): self.view = view def __call__(self, *args, **kwargs): print args, kwargs fig = self.view(*args, **kwargs) canvas=FigureCanvas(fig) response=HttpResponse(content_type='image/svg+xml') canvas.print_svg(response) return response and this is how it was being used: def as_avg(self): return plot_svg(self.output)() The only reason I has it that way instead of using the "@" syntax is because when I do it with the "@": @plot_svg def as_svg(self): return self.output() I get this error: as_svg() takes exactly 1 argument (0 given) I'm trying to 'fix' this by putting it in the "@" syntax but I can't figure out how to get it working. I'm thinking it has something to do with self not getting passed where it's supposed to...

    Read the article

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