Search Results

Search found 107 results on 5 pages for 'decorators'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | 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

  • Threaded Django task doesn't automatically handle transactions or db connections?

    - by Gabriel Hurley
    I've got Django set up to run some recurring tasks in their own threads, and I noticed that they were always leaving behind unfinished database connection processes (pgsql "Idle In Transaction"). I looked through the Postgres logs and found that the transactions weren't being completed (no ROLLBACK). I tried using the various transaction decorators on my functions, no luck. I switched to manual transaction management and did the rollback manually, that worked, but still left the processes as "Idle". So then I called connection.close(), and all is well. But I'm left wondering, why doesn't Django's typical transaction and connection management work for these threaded tasks that are being spawned from the main Django thread?

    Read the article

  • ASP.NET 3.5 Stateless Session Managment and connection pooling?

    - by Norm
    I am designing an ASP.NET (3.5) web application that connects to a Rocket Software UniVerse database. I am in the planning stages right now and need some help in being pointed in the right direction. I am brand new to ASP and C#. I am shooting for a RESTful design and a MVC pattern. Rocket provides a .NET library called UniObjects.NET which handles everything for connecting and retrieving information from the database. What would be the best way to in general to log my users into the database, then use that session via connection pooling? I see that in 3.5 there is the ASP.NET Routing Infrastructure and that looks promising am I in the right direction on this? Also does C# support decorators like Python and Java?

    Read the article

  • In a C++ template, is it allowed to return an object with spesific type parameters?

    - by nieldw
    When I've got a template with certain type parameters, is it allowed for a function to return an object of this same template, but with different types? In other words, is the following allowed? template<class edgeDecor, class vertexDecor, bool dir> Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const { /* Construct new Graph with apropriate decorators */ Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>(); /* ... */ return span; }; If this is not allowed, how can I accomplish the same kind of thing?

    Read the article

  • How can I write to the previous line in a log file using Python's Logging module?

    - by turvyc
    Hi all, long-time lurker here, finally emerging from the woodwork. Essentially, what I'm trying to do is have my logger write data like this to the logfile: Connecting to database . . . Done. I'd like the 'Connecting to database . . . ' to be written when the function is called, and the 'Done' written after the function has successfully executed. I'm using Python 2.6 and the logging module. Also, I'd really like to avoid using decorators for this. Any help would be most appreciated!

    Read the article

  • In a C++ template, is it allowed to return an object with specific type parameters?

    - by nieldw
    When I've got a template with certain type parameters, is it allowed for a function to return an object of this same template, but with different types? In other words, is the following allowed? template<class edgeDecor, class vertexDecor, bool dir> Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const { /* Construct new Graph with apropriate decorators */ Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>(); /* ... */ return span; }; If this is not allowed, how can I accomplish the same kind of thing?

    Read the article

  • Zend_Form setMultiFile()

    - by Cristian
    Hello everyone, i got a question related to the setMultiFile method of zend_form. I already got a form like this: $foto->setLabel('Foto:'); $foto->addValidator('IsImage', true); $foto->addValidator('Count', true, 12); $foto->addValidator('Extension', true, 'gif,png,jpg'); $foto->setDestination(PUBLIC_PATH.'/upload/img/'); $foto->addFilter('Rename', array( 'target' => PUBLIC_PATH.'/upload/img/', 'overwrite' => true )); $foto->addDecorators(array( array('Description',array('tag'=>'','escape'=>false)) )); And it's everything working...but now i need to iterate each element to set a description and decorators...any suggestions ? Thanks to everyone that will reply to this, i'm drivin crazy with that..

    Read the article

  • Adding nodes to MAAS server

    - by Yasith Tharindu
    I was able to install MAAS server using ubuntu 12.04. Then boot up nodes from he PXE. Then installed maas-precise-x86-64-commissioning through pxe. Now the installation is done. but im unable to commission with the MAAS server. It does not show it as a node and neither im unable to add it manually and end up with following error. Also what is the default username password for maas-precise-x86-64-commissioning. Im unable to login. This error when adding node manually. ERROR 2012-11-20 08:32:54,500 maas.maasserver ################################ Exception: timed out ################################ ERROR 2012-11-20 08:32:54,501 maas.maasserver Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/dist-packages/django/views/decorators/vary.py", line 22, in inner_func response = func(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/piston/resource.py", line 166, in call result = self.error_handler(e, request, meth, em_format) File "/usr/lib/python2.7/dist-packages/piston/resource.py", line 164, in call result = meth(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/maasserver/api.py", line 251, in dispatcher self, request, request.method, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/maasserver/api.py", line 193, in perform_api_operation return method(handler, request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/maasserver/api.py", line 493, in new node = create_node(request) File "/usr/lib/python2.7/dist-packages/maasserver/api.py", line 418, in create_node return form.save() File "/usr/lib/python2.7/dist-packages/maasserver/forms.py", line 234, in save node = super(NodeWithMACAddressesForm, self).save() File "/usr/lib/python2.7/dist-packages/django/forms/models.py", line 363, in save fail_message, commit, construct=False) File "/usr/lib/python2.7/dist-packages/django/forms/models.py", line 85, in save_instance instance.save() File "/usr/lib/python2.7/dist-packages/maasserver/models.py", line 114, in save return super(CommonInfo, self).save(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py", line 460, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py", line 570, in save_base created=(not record_exists), raw=raw, using=using) File "/usr/lib/python2.7/dist-packages/django/dispatch/dispatcher.py", line 172, in send response = receiver(signal=self, sender=sender, **named) File "/usr/lib/python2.7/dist-packages/maasserver/provisioning.py", line 485, in provision_post_save_Node profile, power_type, preseed_data) File "/usr/lib/python2.7/dist-packages/maasserver/provisioning.py", line 245, in call result = self.method(*args) 259,1 93% result = self.method(*args) File "/usr/lib/python2.7/xmlrpclib.py", line 1224, in call return self._send(self._name, args) File "/usr/lib/python2.7/xmlrpclib.py", line 1578, in _request verbose=self._verbose File "/usr/lib/python2.7/xmlrpclib.py", line 1264, in request return self.single_request(host, handler, request_body, verbose) File "/usr/lib/python2.7/xmlrpclib.py", line 1294, in single_request response = h.getresponse(buffering=True) File "/usr/lib/python2.7/httplib.py", line 1030, in getresponse response.begin() File "/usr/lib/python2.7/httplib.py", line 407, in begin version, status, reason = self._read_status() File "/usr/lib/python2.7/httplib.py", line 365, in _read_status line = self.fp.readline() File "/usr/lib/python2.7/socket.py", line 447, in readline data = self._sock.recv(self._rbufsize) timeout: timed out

    Read the article

  • Updating an Entity through a Service

    - by GeorgeK
    I'm separating my software into three main layers (maybe tiers would be a better term): Presentation ('Views') Business logic ('Services' and 'Repositories') Data access ('Entities' (e.g. ActiveRecords)) What do I have now? In Presentation, I use read-only access to Entities, returned from Repositories or Services, to display data. $banks = $banksRegistryService->getBanksRepository()->getBanksByCity( $city ); $banksViewModel = new PaginatedList( $banks ); // some way to display banks; // example, not real code I find this approach quite efficient in terms of performance and code maintanability and still safe as long as all write operations (create, update, delete) are preformed through a Service: namespace Service\BankRegistry; use Service\AbstractDatabaseService; use Service\IBankRegistryService; use Model\BankRegistry\Bank; class Service extends AbstractDatabaseService implements IBankRegistryService { /** * Registers a new Bank * * @param string $name Bank's name * @param string $bik Bank's Identification Code * @param string $correspondent_account Bank's correspondent account * * @return Bank */ public function registerBank( $name, $bik, $correspondent_account ) { $bank = new Bank(); $bank -> setName( $name ) -> setBik( $bik ) -> setCorrespondentAccount( $correspondent_account ); if( null === $this->getBanksRepository()->getDefaultBank() ) $this->setDefaultBank( $bank ); $this->getEntityManager()->persist( $bank ); return $bank; } /** * Makes the $bank system's default bank * * @param Bank $bank * @return IBankRegistryService */ public function setDefaultBank( Bank $bank ) { $default_bank = $this->getBanksRepository()->getDefaultBank(); if( null !== $default_bank ) $default_bank->setDefault( false ); $bank->setDefault( true ); return $this; } } Where am I stuck? I'm struggling about how to update certain fields in Bank Entity. Bad solution #1: Making a series of setters in Service for each setter in Bank; - seems to be quite reduntant, increases Service interface complexity and proportionally decreases it's simplicity - something to avoid if you care about code maitainability. I try to follow KISS and DRY principles. Bad solution #2: Modifying Bank directly through it's native setters; - really bad. If you'll ever need to move modification into the Service, it will be pain. Business logic should remain in Business logic layer. Plus, there are plans on logging all of the actions and maybe even involve user permissions (perhaps, through decorators) in future, so all modifications should be made only through the Service. Possible good solution: Creating an updateBank( Bank $bank, $array_of_fields_to_update) method; - makes the interface as simple as possible, but there is a problem: one should not try to manually set isDefault flag on a Bank, this operation should be performed through setDefaultBank method. It gets even worse when you have relations that you don't want to be directly modified. Of course, you can just limit the fields that can be modified by this method, but how do you tell method's user what they can and cannot modify? Exceptions?

    Read the article

  • How to declare dependent style names with UiBinder

    - by Eduard Wirch
    I have a simple UiBinder widget containing a TextArea: <!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent"> <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <g:TextArea visibleLines="3" /> </ui:UiBinder> I want to control the background color of this textarea for writeable and read only states. GWT uses the "-readonly" style name decorator to achieve this. So I try this: <!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent"> <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <ui:style> .textBoxStyle { background-color:yellow; } .textBoxStyle-readonly { background-color:lightgray; } </ui:style> <g:TextArea styleName="{style.textBoxStyle}" visibleLines="3" /> </ui:UiBinder> Obviously this won't work because style names are obfuscated for CssResources resulting in something like this: .G1x26wpeN { background-color:yellow } .G1x26wpeO { background-color: lightgray; } The result HTML for writeable textarea looks like this: <textarea tabindex="0" class="G1x26wpeN" rows="3"/> The read only textarea looks like this: <textarea tabindex="0" class="G1x26wpeN G1x26wpeN-readonly" readonly="" rows="3"/> How do I declare the style so GWT will obfuscate the primary part but not the "-readonly" decdorator? I know that I can disable the obfuscation for the entire style name. But I'd like to keep the obfuscation while making use of the decorators.

    Read the article

  • sitemesh vs jsp-config (<include-prelude>)

    - by Nrj
    Please help clarifying : In web.xml I have the following <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <el-ignored>false</el-ignored> <page-encoding>utf-8</page-encoding> <include-prelude>/jstlTaglibs.jspf</include-prelude> </jsp-property-group> </jsp-config> Also in decorators.xml I have <decorator name="footer" page="footer.jsp"> <pattern>*.action</pattern> </decorator> which is used via sitemesh.xml. The footer.jsp which says ... <decorator:body /> <@include .. "footer.jsp"/> So what I gather is, both of the codes above in a sense inject some jspf. Please help highlighting the differences and benefits of both the approaches. Also which one is more used across industry ?

    Read the article

  • Login URL using authentication information in Django

    - by fuSi0N
    I'm working on a platform for online labs registration for my university. Login View [project views.py] from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib import auth def index(request): return render_to_response('index.html', {}, context_instance = RequestContext(request)) def login(request): if request.method == "POST": post = request.POST.copy() if post.has_key('username') and post.has_key('password'): usr = post['username'] pwd = post['password'] user = auth.authenticate(username=usr, password=pwd) if user is not None and user.is_active: auth.login(request, user) if user.get_profile().is_teacher: return HttpResponseRedirect('/teachers/'+user.username+'/') else: return HttpResponseRedirect('/students/'+user.username+'/') else: return render_to_response('index.html', {'msg': 'You don\'t belong here.'}, context_instance = RequestContext(request) return render_to_response('login.html', {}, context_instance = RequestContext(request)) def logout(request): auth.logout(request) return render_to_response('index.html', {}, context_instance = RequestContext(request)) URLS #========== PROJECT URLS ==========# urlpatterns = patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }), (r'^admin/', include(admin.site.urls)), (r'^teachers/', include('diogenis.teachers.urls')), (r'^students/', include('diogenis.students.urls')), (r'^login/', login), (r'^logout/', logout), (r'^$', index), ) #========== TEACHERS APP URLS ==========# urlpatterns = patterns('', (r'^(?P<username>\w{0,50})/', labs), ) The login view basically checks whether the logged in user is_teacher [UserProfile attribute via get_profile()] and redirects the user to his profile. Labs View [teachers app views.py] from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.models import User from accounts.models import * from labs.models import * def user_is_teacher(user): return user.is_authenticated() and user.get_profile().is_teacher @user_passes_test(user_is_teacher, login_url="/login/") def labs(request, username): q1 = User.objects.get(username=username) q2 = u'%s %s' % (q1.last_name, q1.first_name) q2 = Teacher.objects.get(name=q2) results = TeacherToLab.objects.filter(teacher=q2) return render_to_response('teachers/labs.html', {'results': results}, context_instance = RequestContext(request)) I'm using @user_passes_test decorator for checking whether the authenticated user has the permission to use this view [labs view]. The problem I'm having with the current logic is that once Django authenticates a teacher user he has access to all teachers profiles basically by typing the teachers username in the url. Once a teacher finds a co-worker's username he has direct access to his data. Any suggestions would be much appreciated.

    Read the article

  • Tracking Down a Stack Overflow in My Linq Query

    - by Lazarus
    I've written the following Linq query: IQueryable<ISOCountry> entries = (from e in competitorRepository.Competitors join c in countries on e.countryID equals c.isoCountryCode where !e.Deleted orderby c.isoCountryCode select new ISOCountry() { isoCountryCode = e.countryID, Name = c.Name }).Distinct(); The objective is to retrieve a list of the countries represented by the competitors found in the system. 'countries' is an array of ISOCountry objects explicitly created and returned as an IQueryable (ISOCountry is an object of just two strings, isoCountryCode and Name). Competitors is an IQueryable which is bound to a database table through Linq2SQL though I created the objects from scratch and used the Linq data mapping decorators. For some reason this query causes a stack overflow when the system tries to execute it. I've no idea why, I've tried trimming the Distinct, returning an anonymous type of the two strings, using 'select c', all result in the overflow. The e.CountryID value is populated from a dropdown that was in itself populated from the IQueryable so I know the values are appropriate but even if not I wouldn't expect a stack overflow. Can anyone explain why the overflow is occurring or give good speculation as to why it might be happening? EDIT As requested, code for ISOCountry: public class ISOCountry { public string isoCountryCode { get; set; } public string Name { get; set; } }

    Read the article

  • python-social-auth AuthCanceled exception

    - by vero4ka
    I'm using python-social-auth in my Django application for authentication via Facebook. But when a user tries to login and when it's been refirected to Facebook app page clicks on "Cancel" button, appears the following exception: ERROR 2014-01-03 15:32:15,308 base :: Internal Server Error: /complete/facebook/ Traceback (most recent call last): File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view return view_func(*args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 45, in wrapper return func(request, backend, *args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/views.py", line 21, in complete redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/actions.py", line 54, in do_complete *args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/strategies/base.py", line 62, in complete return self.backend.auth_complete(*args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 63, in auth_complete self.process_error(self.data) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 56, in process_error super(FacebookOAuth2, self).process_error(data) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/oauth.py", line 312, in process_error raise AuthCanceled(self, data.get('error_description', '')) AuthCanceled: Authentication process canceled Is the any way to catch it Django?

    Read the article

  • Matplotlib canvas drawing

    - by Morgoth
    Let's say I define a few functions to do certain matplotlib actions, such as def dostuff(ax): ax.scatter([0.],[0.]) Now if I launch ipython, I can load these functions and start a new figure: In [1]: import matplotlib.pyplot as mpl In [2]: fig = mpl.figure() In [3]: ax = fig.add_subplot(1,1,1) In [4]: run functions # run the file with the above defined function If I now call dostuff, then the figure does not refresh: In [6]: dostuff(ax) I have to then explicitly run: In [7]: fig.canvas.draw() To get the canvas to draw. Now I can modify dostuff to be def dostuff(ax): ax.scatter([0.],[0.]) ax.get_figure().canvas.draw() This re-draws the canvas automatically. But now, say that I have the following code: def dostuff1(ax): ax.scatter([0.],[0.]) ax.get_figure().canvas.draw() def dostuff2(ax): ax.scatter([1.],[1.]) ax.get_figure().canvas.draw() def doboth(ax): dostuff1(ax) dostuff2(ax) ax.get_figure().canvas.draw() I can call each of these functions, and the canvas will be redrawn, but in the case of doboth(), it will get redrawn multiple times. My question is: how could I code this, such that the canvas.draw() only gets called once? In the above example it won't change much, but in more complex cases with tens of functions that can be called individually or grouped, the repeated drawing is much more obvious, and it would be nice to be able to avoid it. I thought of using decorators, but it doesn't look as though it would be simple. Any ideas?

    Read the article

  • How to use Struts2-jQuery Plugin with sitemesh

    - by fayway
    Hi I have this error when I try to include the tag (http://code.google.com/p/struts2-jquery/wiki/HeadTag) in a sitemesh decorator main.jsp (decorator) <%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sj" uri="/struts-jquery-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>My Project- <decorator:title /></title> <sj:head compressed="false" jqueryui="true"></sj:head> </head> <body> <!-- head --> .... Tomcat Error exception java.lang.RuntimeException: org.apache.jasper.JasperException: An exception occurred processing JSP page /decorators/main.jsp at line 11 8: <head> 9: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 10: <title>My Project- <decorator:title /></title> 11: <sj:head compressed="false" jqueryui="true"></sj:head> 12: </head> 13: <body> 14: <!-- head --> Stacktrace: com.opensymphony.sitemesh.webapp.decorator.BaseWebAppDecorator.render(BaseWebAppDecorator.java:39) com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:84) Please any idea ? Thanks in advance

    Read the article

  • Graph limitations - Should I use Decorator?

    - by Nick Wiggill
    I have a functional AdjacencyListGraph class that adheres to a defined interface GraphStructure. In order to layer limitations on this (eg. acyclic, non-null, unique vertex data etc.), I can see two possible routes, each making use of the GraphStructure interface: Create a single class ("ControlledGraph") that has a set of bitflags specifying various possible limitations. Handle all limitations in this class. Update the class if new limitation requirements become apparent. Use the decorator pattern (DI, essentially) to create a separate class implementation for each individual limitation that a client class may wish to use. The benefit here is that we are adhering to the Single Responsibility Principle. I would lean toward the latter, but by Jove!, I hate the decorator Pattern. It is the epitome of clutter, IMO. Truthfully it all depends on how many decorators might be applied in the worst case -- in mine so far, the count is seven (the number of discrete limitations I've recognised at this stage). The other problem with decorator is that I'm going to have to do interface method wrapping in every... single... decorator class. Bah. Which would you go for, if either? Or, if you can suggest some more elegant solution, that would be welcome. EDIT: It occurs to me that using the proposed ControlledGraph class with the strategy pattern may help here... some sort of template method / functors setup, with individual bits applying separate controls in the various graph-canonical interface methods. Or am I losing the plot?

    Read the article

  • UnicodeDecodeError on attempt to save file through django default filebased backend

    - by Ivan Kuznetsov
    When i attempt to add a file with russian symbols in name to the model instance through default instance.file_field.save method, i get an UnicodeDecodeError (ascii decoding error, not in range (128) from the storage backend (stacktrace ended on os.exist). If i write this file through default python file open/write all goes right. All filenames in utf-8. I get this error only on testing Gentoo, on my Ubuntu workstation all works fine. class Article(models.Model): file = models.FileField(null=True, blank=True, max_length = 300, upload_to='articles_files/%Y/%m/%d/') Traceback: File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 24. return view_func(request, *args, **kwargs) File "/var/www/localhost/help/wiki/views.py" in edit_article 338. new_article.file.save(fp, fi, save=True) File "/usr/lib/python2.6/site-packages/django/db/models/fields/files.py" in save 92. self.name = self.storage.save(name, content) File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in save 47. name = self.get_available_name(name) File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in get_available_name 73. while self.exists(name): File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in exists 196. return os.path.exists(self.path(name)) File "/usr/lib/python2.6/genericpath.py" in exists 18. st = os.stat(path) Exception Type: UnicodeEncodeError at /edit/ Exception Value: ('ascii', u'/var/www/localhost/help/i/articles_files/2010/03/17/\u041f\u0440\u0438\u0432\u0435\u0442', 52, 58, 'ordinal not in range(128)')

    Read the article

  • How can I add a plugin to the registry while using a Zend_Form?

    - by Mallika Iyer
    I have a zend form that I'm initializing as follows: $form = new Form_XYZ(); I have a display group in that form, which I'm calling like this: $form->addDisplayGroup($generalSettingsGroup, 'general', array( 'legend' => 'General', 'disableDefaultDecorators' => true, 'decorators' => array( 'FormElements', 'FieldSet', array('HtmlTag', array('tag' => 'div', 'class' => 'general') ) ) ) ); I get this error : ArrayObject Object ( [exception] => Zend_Loader_PluginLoader_Exception Object ( [message:protected] => Plugin by name 'FieldSet' was not found in the registry; used paths:Zend_Form_Decorator_: Zend/Form/Decorator/ [string:private] => [code:protected] => 0 [file:protected] => /usr/share/pear/PEAR/Zend/Loader/PluginLoader.php [line:protected] => 406 [trace:private] => Array ................... How can I add the FieldSet plugin to the registry? I'm using the default Zend_Form Fieldset decorator.

    Read the article

  • What makes this "declarator invalid"? C++

    - by nieldw
    I have Vertex template in vertex.h. From my graph.h: 20 template<class edgeDecor, class vertexDecor, bool dir> 21 class Vertex; which I use in my Graph template. I've used the Vertex template successfully throughout my Graph, return pointers to Vertices, etc. Now for the first time I am trying to declare and instantiate a Vertex object, and gcc is telling me that my 'declarator' is 'invalid'. How can this be? 81 template<class edgeDecor, class vertexDecor, bool dir> 82 Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const 83 { 84 /* Construct new Graph with apropriate decorators */ 85 Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>(); 86 span.E.reserve(this->E.size()); 87 88 typename Vertex<edgeDecor,int,dir> v = new Vertex(INT_MAX); 89 span.V = new vector<Vertex<edgeDecor,int,dir> >(this->V.size,v); 90 }; And gcc is saying: graph.h: In member function ‘Graph<edgeDecor, int, dir> Graph<edgeDecor, vertexDecor, dir>::Dijkstra(Vertex<edgeDecor, vertexDecor, dir>, bool) const’: graph.h:88: error: invalid declarator before ‘v’ graph.h:89: error: ‘v’ was not declared in this scope I know this is probably another noob question, but I'll appreciate any help.

    Read the article

  • associated array elements in zend form

    - by ToonMariner
    Hi, Been trying to find a solution for this for a while with not much luck... Need to render a form with an array of checkboxes each having an associated textbox. given an array of array('Dave'=23,'Pete'=12,'Si'=43); the resulting mark-up should yield: <div> <label><input type="checkbox" name="user_id[]" id="user_id-1" value="23" />Dave</label> <label for="job-1">Job:</label><input type="text" name="job[]" id="job-1" /> </div> <div> <label><input type="checkbox" name="user_id[]" id="user_id-2" value="12" />Pete</label> <label for="job-2">Job:</label><input type="text" name="job[]" id="job-2" /> </div> <div> <label><input type="checkbox" name="user_id[]" id="user_id-3" value="43" />Si</label> <label for="job-3">Job:</label><input type="text" name="job[]" id="job-3" /> </div> Complete zend noob so any help appreciuated (including decorators etc.) Thanks peeps

    Read the article

  • How can I adjust the position of a label for a zend form Radio element?

    - by murze
    Hi, with this piece of code $feOnline = New Zend_Form_Element_Radio('online'); $feOnline->setValue($article->online) ->addMultiOptions(array(0=>'offline', 1=>'online')) ->setLabel('Online'); this html is generated <dd id="online-element"> <label for="online-0"> <input type="radio" checked="checked" value="0" id="online-0" name="online">offline </label><br> <label for="online-1"><input type="radio" value="1" id="online-1" name="online">online </label> </dd> However I don't want the input-tag inside the label-tag. No need for the "" either... What decorators must I add to get this output? <dd id="online-element"> <input type="radio" checked="checked" value="0" id="online-0" name="online"><label for="online-0">offline</label> <input type="radio" value="1" id="online-1" name="online"><label for="online-1">online</label> </dd>

    Read the article

  • Celery / Django Single Tasks being run multiple times

    - by felix001
    I'm facing an issue where I'm placing a task into the queue and it is being run multiple times. From the celery logs I can see that the same worker is running the task ... [2014-06-06 15:12:20,731: INFO/MainProcess] Received task: input.tasks.add_queue [2014-06-06 15:12:20,750: INFO/Worker-2] starting runner.. [2014-06-06 15:12:20,759: INFO/Worker-2] collection started [2014-06-06 15:13:32,828: INFO/Worker-2] collection complete [2014-06-06 15:13:32,836: INFO/Worker-2] generation of steps complete [2014-06-06 15:13:32,836: INFO/Worker-2] update created [2014-06-06 15:13:33,655: INFO/Worker-2] email sent [2014-06-06 15:13:33,656: INFO/Worker-2] update created [2014-06-06 15:13:34,420: INFO/Worker-2] email sent [2014-06-06 15:13:34,421: INFO/Worker-2] FINISH - Success However when I view the actual logs of the application it is showing 5-6 log lines for each step (??). Im using Django 1.6 with RabbitMQ. The method for placing into the queue is via placing a delay on a function. This function (task decorator is added( then calls a class which is run. Has anyone any idea on the best way to troubleshoot this ? Edit : As requested heres the code, views.py In my view im sending my data to the queue via ... from input.tasks import add_queue_project add_queue_project.delay(data) tasks.py from celery.decorators import task @task() def add_queue_project(data): """ run project """ logger = logging_setup(app="project") logger.info("starting project runner..") f = project_runner(data) f.main() class project_runner(): """ main project runner """ def __init__(self,data): self.data = data self.logger = logging_setup(app="project") def self.main(self): .... Code settings.py THIRD_PARTY_APPS = ( 'south', # Database migration helpers: 'crispy_forms', # Form layouts 'rest_framework', 'djcelery', ) import djcelery djcelery.setup_loader() BROKER_HOST = "127.0.0.1" BROKER_PORT = 5672 # default RabbitMQ listening port BROKER_USER = "test" BROKER_PASSWORD = "test" BROKER_VHOST = "test" CELERY_BACKEND = "amqp" # telling Celery to report the results back to RabbitMQ CELERY_RESULT_DBURI = "" CELERY_IMPORTS = ("input.tasks", ) celeryd The line im running is to start celery, python2.7 manage.py celeryd -l info Thanks,

    Read the article

  • Why does Celery work in Python shell, but not in my Django views? (import problem)

    - by TIMEX
    I installed Celery (latest stable version.) I have a directory called /home/myuser/fable/jobs. Inside this directory, I have a file called tasks.py: from celery.decorators import task from celery.task import Task class Submitter(Task): def run(self, post, **kwargs): return "Yes, it works!!!!!!" Inside this directory, I also have a file called celeryconfig.py: BROKER_HOST = "localhost" BROKER_PORT = 5672 BROKER_USER = "abc" BROKER_PASSWORD = "xyz" BROKER_VHOST = "fablemq" CELERY_RESULT_BACKEND = "amqp" CELERY_IMPORTS = ("tasks", ) In my /etc/profile, I have these set as my PYTHONPATH: PYTHONPATH=/home/myuser/fable:/home/myuser/fable/jobs So I run my Celery worker using the console ($ celeryd --loglevel=INFO), and I try it out. I open the Python console and import the tasks. Then, I run the Submitter. >>> import fable.jobs.tasks as tasks >>> s = tasks.Submitter() >>> s.delay("abc") <AsyncResult: d70d9732-fb07-4cca-82be-d7912124a987> Everything works, as you can see in my console [2011-01-09 17:30:05,766: INFO/MainProcess] Task tasks.Submitter[d70d9732-fb07-4cca-82be-d7912124a987] succeeded in 0.0398268699646s: But when I go into my Django's views.py and run the exact 3 lines of code as above, I get this: [2011-01-09 17:25:20,298: ERROR/MainProcess] Unknown task ignored: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported.": {'retries': 0, 'task': 'fable.jobs.tasks.Submitter', 'args': ('abc',), 'expires': None, 'eta': None, 'kwargs': {}, 'id': 'eb5c65b4-f352-45c6-96f1-05d3a5329d53'} Traceback (most recent call last): File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/listener.py", line 321, in receive_message eventer=self.event_dispatcher) File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 299, in from_message eta=eta, expires=expires) File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/worker/job.py", line 243, in __init__ self.task = tasks[self.task_name] File "/home/myuser/mysite-env/lib/python2.6/site-packages/celery/registry.py", line 63, in __getitem__ raise self.NotRegistered(str(exc)) NotRegistered: "Task of kind 'fable.jobs.tasks.Submitter' is not registered, please make sure it's imported." It's weird, because the celeryd client does show that it's registered, when I launch it. [2011-01-09 17:38:27,446: WARNING/MainProcess] Configuration -> . broker -> amqp://GOGOme@localhost:5672/fablemq . queues -> . celery -> exchange:celery (direct) binding:celery . concurrency -> 1 . loader -> celery.loaders.default.Loader . logfile -> [stderr]@INFO . events -> OFF . beat -> OFF . tasks -> . tasks.Decayer . tasks.Submitter Can someone help?

    Read the article

  • How to use multiple flatpages models in a django app?

    - by the_drow
    I have multiple models that can be converted to flatpages but have to have some extra information (For example I have an about us page but I also have a blog). However I understand that there must be only one flatpages model since the middleware only returns the flatpages instance and does not resolve the child models. What do I have to do? EDIT: It seems I need to change the views. Here's the current code: from django.contrib.flatpages.models import FlatPage from django.template import loader, RequestContext from django.shortcuts import get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.core.xheaders import populate_xheaders from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_protect DEFAULT_TEMPLATE = 'flatpages/default.html' # This view is called from FlatpageFallbackMiddleware.process_response # when a 404 is raised, which often means CsrfViewMiddleware.process_view # has not been called even if CsrfViewMiddleware is installed. So we need # to use @csrf_protect, in case the template needs {% csrf_token %}. # However, we can't just wrap this view; if no matching flatpage exists, # or a redirect is required for authentication, the 404 needs to be returned # without any CSRF checks. Therefore, we only # CSRF protect the internal implementation. def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url # Here instead of getting the flat page it needs to find if it has a page with a child model. f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) return render_flatpage(request, f) @csrf_protect def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) # Here I need to be able to configure what I am passing in the context c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >