Search Results

Search found 10055 results on 403 pages for 'self awareness'.

Page 56/403 | < Previous Page | 52 53 54 55 56 57 58 59 60 61 62 63  | Next Page >

  • C# Client to Consume Google App Engine RESTful Webservice (rpc XML)

    - by Ngu Soon Hui
    I think I hit a problem when using C# client to consume Google App Engine Webservice. The Google App Engine code I use is here. This is how the python script on server would look like: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import logging from StringIO import StringIO import traceback import xmlrpclib from xmlrpcserver import XmlRpcServer class Application: def __init__(self): pass def getName(self,meta): return 'example' class XMLRpcHandler(webapp.RequestHandler): rpcserver = None def __init__(self): self.rpcserver = XmlRpcServer() app = Application() self.rpcserver.register_class('app',app) def post(self): request = StringIO(self.request.body) request.seek(0) response = StringIO() try: self.rpcserver.execute(request, response, None) except Exception, e: logging.error('Error executing: '+str(e)) for line in traceback.format_exc().split('\n'): logging.error(line) finally: response.seek(0) rstr = response.read() self.response.headers['Content-type'] = 'text/xml' self.response.headers['Content-length'] = "%d"%len(rstr) self.response.out.write(rstr) application = webapp.WSGIApplication( [('/xmlrpc/', XMLRpcHandler)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() The client side ( in Python) is this: import xmlrpclib s = xmlrpclib.Server('http://localhost:8080/xmlrpc/') print s.app.getName() I have no problem in using Python client to retrieve values from Google App Engine, but I do have difficulties in using a C# client to retrieve the values. The error I got was 404 method not found when I am trying to GetResponse from the web request. This is my code var request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/xmlrpc/app"); request.Method = "GET"; request.ContentLength = 0; request.ContentType = "text/xml"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //404 method not found error here. { } I think it must be that the url is wrong, but I don't know how to get it right. Any idea?

    Read the article

  • Selenium RC: how to capture/handle error?

    - by KenBurnsFan1
    Hi, My test uses Selenium to loop through a CSV list of URLs via an HTTP proxy (working script below). As I watch the script run I can see about 10% of the calls produce "Proxy error: 502" ("Bad_Gateway"); however, the errors are not captured by my catch-all "except Exception" clause -- ie: instead of writing 'error' in the appropriate row of the "output.csv", they get passed to the else clause and produce a short piece of html that starts: "Proxy error: 502 Read from server failed: Unknown error." Also, if I collect all the URLs which returned 502s and re-run the script, they all pass, which leads me to believe that this is a sporadic network path issue. Question: Can the script be made to recognize the the 502 errors, sleep a minute, and then retry the URL instead of moving on to the next URL in the list? The only alternative that I can think of is to apply re.search("Proxy error: 502") after "get_html_source" as a way to catch the bad calls. Then, if the RE matches, put the script to sleep for a minute and then retry 'sel.open(row[0]' on the URL which produced the 502. Any advice would be much appreciated. Thanks! #python 2.6 from selenium import selenium import unittest, time, re, csv, logging class Untitled(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://baseDomain.com") self.selenium.start() self.selenium.set_timeout("60000") def test_untitled(self): sel = self.selenium spamReader = csv.reader(open('ListOfSubDomains.csv', 'rb')) for row in spamReader: try: sel.open(row[0]) except Exception: ofile = open('output.csv', 'ab') ofile.write("error" + '\n') ofile.close() else: time.sleep(5) html = sel.get_html_source() ofile = open('output.csv', 'ab') ofile.write(html.encode('utf-8') + '\n') ofile.close() def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main()

    Read the article

  • Objective-C Simple Inheritance and OO Principles

    - by bleeckerj
    I have a subclass SubClass that inherits from baseclass BaseClass. BaseClass has an initializer, like so: -(id)init { self = [super init]; if(self) { [self commonInit]; } return self; } -(void)commonInit { self.goodStuff = [[NSMutableArray alloc]init]; } SubClass does its initializer, like so: -(id)init { self = [super init]; if(self) { [self commonInit]; } return self; } -(void)commonInit { self.extraGoodStuff = [[NSMutableArray alloc]init]; } Now, I've *never taken a proper Objective-C course, but I'm a programmer more from the Electrical Engineering side, so I make do. I've developed server-side applications mostly in Java though, so I may be seeing the OO world through Java principles. When SubClass is initialized, it calls the BaseClass init and my expectation would be — because inheritance to me implies that characteristics of a BaseClass pass through to SubClass — that the commonInit method in BaseClass would be called during BaseClass init. It is not. I can *sorta understand maybe-possibly-stretch-my-imagination why it wouldn't be. But, then — why wouldn't it be based on the principles of OOP? What does "self" represent if not the instance of the class of the running code? Okay, so — I'm not going to argue that what a well-developed edition of Objective-C is doing is wrong. So, then — what is the pattern I should be using in this case? I want SubClass to have two main bits — the goodStuff that BaseClass has as well as the extraGoodStuff that it deserves as well. Clearly, I've been using the wrong pattern in this type of situation. Am I meant to expose commonInit (which makes me wonder about encapsulation principles — why expose something that, in the Java world at least, would be considered "protected" and something that should only ever be called once for each instance)? I've run into a similar problem in the recent past and tried to muddle through it, but now — I'm really wondering if I've got my principles and concepts all straight in my head. Little help, please.

    Read the article

  • Memory leak for NSDictionary loaded by plist file

    - by Pask
    I have a memory leak problem that just can not understand! Watch this initialization method: - (id)initWithNomeCompositore:(NSString *)nomeCompositore nomeOpera:(NSString *)nomeOpera { if (self = [super init]) { NSString *pathOpere = [[NSBundle mainBundle] pathForResource:kNomeFilePlistOpere ofType:kTipoFilePlist]; NSDictionary *dicOpera = [NSDictionary dictionaryWithDictionary: [[[NSDictionary dictionaryWithContentsOfFile:pathOpere] objectForKey:nomeCompositore] objectForKey:nomeOpera]]; self.nomeCompleto = [[NSString alloc] initWithString:nomeOpera]; self.compositore = [[NSString alloc] initWithString:nomeCompositore]; self.tipologia = [[NSString alloc] initWithString:[dicOpera objectForKey:kKeyTipologia]]; } return self;} Then this little variation (note self.tipologia): - (id)initWithNomeCompositore:(NSString *)nomeCompositore nomeOpera:(NSString *)nomeOpera { if (self = [super init]) { NSString *pathOpere = [[NSBundle mainBundle] pathForResource:kNomeFilePlistOpere ofType:kTipoFilePlist]; NSDictionary *dicOpera = [NSDictionary dictionaryWithDictionary: [[[NSDictionary dictionaryWithContentsOfFile:pathOpere] objectForKey:nomeCompositore] objectForKey:nomeOpera]]; self.nomeCompleto = [[NSString alloc] initWithString:nomeOpera]; self.compositore = [[NSString alloc] initWithString:nomeCompositore]; self.tipologia = [[NSString alloc] initWithString:@"Test"]; } return self;} In the first variant is generated a memory leak, the second is not! And I just can not understand why! The memory leak is evidenced by Instruments, highlighted the line: [NSDictionary dictionaryWithContentsOfFile:pathOpere] This is the dealloc method: - (void)dealloc { [tipologia release]; [compositore release]; [nomeCompleto release]; [super dealloc];}

    Read the article

  • Django upload failing on request data read error

    - by Jake
    Hi All, I've got a Django app that accepts uploads from jQuery uploadify, a jQ plugin that uses flash to upload files and give a progress bar. Files under about 150k work, but bigger files always fail and almost always at around 192k (that's 3 chunks) completed, sometimes at around 160k. The Exception I get is below. exceptions.IOError request data read error File "/usr/lib/python2.4/site-packages/django/core/handlers/wsgi.py", line 171, in _get_post self._load_post_and_files() File "/usr/lib/python2.4/site-packages/django/core/handlers/wsgi.py", line 137, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, self.environ[\'wsgi.input\']) File "/usr/lib/python2.4/site-packages/django/http/__init__.py", line 124, in parse_file_upload return parser.parse() File "/usr/lib/python2.4/site-packages/django/http/multipartparser.py", line 192, in parse for chunk in field_stream: File "/usr/lib/python2.4/site-packages/django/http/multipartparser.py", line 314, in next output = self._producer.next() File "/usr/lib/python2.4/site-packages/django/http/multipartparser.py", line 468, in next for bytes in stream: File "/usr/lib/python2.4/site-packages/django/http/multipartparser.py", line 314, in next output = self._producer.next() File "/usr/lib/python2.4/site-packages/django/http/multipartparser.py", line 375, in next data = self.flo.read(self.chunk_size) File "/usr/lib/python2.4/site-packages/django/http/multipartparser.py", line 405, in read return self._file.read(num_bytes) When running locally on the Django development server, big files work. I've tried setting my FILE_UPLOAD_HANDLERS = ("django.core.files.uploadhandler.TemporaryFileUploadHandler",) in case it was the memory upload handler, but it made no difference. Does anyone know how to fix this?

    Read the article

  • Is it approproate it use django signals withing the same app

    - by Alex Lebedev
    Trying to add email notification to my app in the cleanest way possible. When certain fields of a model change, app should send a notification to a user. Here's my old solution: from django.contrib.auth import User class MyModel(models.Model): user = models.ForeignKey(User) field_a = models.CharField() field_b = models.CharField() def save(self, *args, **kwargs): old = self.__class__.objects.get(pk=self.pk) if self.pk else None super(MyModel, self).save(*args, **kwargs) if old and old.field_b != self.field_b: self.notify("b-changed") # Sevelar more events here # ... def notify(self, event) subj, text = self._prepare_notification(event) send_mail(subj, body, settings.DEFAULT_FROM_EMAIL, [self.user.email], fail_silently=True) This worked fine while I had one or two notification types, but after that just felt wrong to have so much code in my save() method. So, I changed code to signal-based: from django.db.models import signals def remember_old(sender, instance, **kwargs): """pre_save hanlder to save clean copy of original record into `old` attribute """ instance.old = None if instance.pk: try: instance.old = sender.objects.get(pk=instance.pk) except ObjectDoesNotExist: pass def on_mymodel_save(sender, instance, created, **kwargs): old = instance.old if old and old.field_b != instance.field_b: self.notify("b-changed") # Sevelar more events here # ... signals.pre_save.connect(remember_old, sender=MyModel, dispatch_uid="mymodel-remember-old") signals.post_save.connect(on_mymodel_save, sender=MyModel, dispatch_uid="mymodel-on-save") The benefit is that I can separate event handlers into different module, reducing size of models.py and I can enable/disable them individually. The downside is that this solution is more code and signal handlers are separated from model itself and unknowing reader can miss them altogether. So, colleagues, do you think it's worth it?

    Read the article

  • Replace textfields with dropdown select fields

    - by 47
    I have three model classes that look as below: class Model(models.Model): model = models.CharField(max_length=20, blank=False) manufacturer = models.ForeignKey(Manufacturer) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = ''+str(self.manufacturer)+" "+str(self.model) return name class Series(models.Model): series = models.CharField(max_length=20, blank=True, null=True) model = models.ForeignKey(Model) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = str(self.model)+" "+str(self.series) return name class Manufacturer(models.Model): MANUFACTURER_POPULARITY_CHOICES = ( ('1', 'Primary'), ('2', 'Secondary'), ('3', 'Tertiary'), ) manufacturer = models.CharField(max_length=15, blank=False) date_added = models.DateField(default=datetime.today) manufacturer_popularity = models.CharField(max_length=1, choices=MANUFACTURER_POPULARITY_CHOICES) def __unicode__(self): return self.manufacturer I want to have the fields for model series and manufacturer represented as dropdowns instead of text fields. I have customized the model forms as below: class SeriesForm(ModelForm): series = forms.ModelChoiceField(queryset=Series.objects.all()) class Meta: model = Series exclude = ('model', 'date_added',) class ModelForm(ModelForm): model = forms.ModelChoiceField(queryset=Model.objects.all()) class Meta: model = Model exclude = ('manufacturer', 'date_added',) class ManufacturerForm(ModelForm): manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) class Meta: model = Manufacturer exclude = ('date_added',) However, the dropdowns are populated with the unicode in the respective class...how can I further customize this to get the end result I want? Also, how can I populate the forms with the correct data for editing? Currently only SeriesForm is populated. The starting point of all this is from another class whose declaration is as below: class CommonVehicle(models.Model): year = models.ForeignKey(Year) series = models.ForeignKey(Series) .... def __unicode__(self): name = ''+str(self.year)+" "+str(self.series) return name

    Read the article

  • Spaceship objects

    - by Jam
    I'm trying to make a program which creates a spaceship and I'm using the status() method to display the ship's name and fuel values. However, it doesn't seem to be working. I think I may have messed something up with the status() method. I'm also trying to make it so that I can change the fuel values, but I don't want to create a new method to do so. I think I've taken a horrible wrong turn somewhere in there. Help please! class Ship(object): def __init__(self, name="Enterprise", fuel=0): self.name=name self.fuel=fuel print "The spaceship", name, "has arrived!" def status(): print "Name: ", self.name print "Fuel level: ", self.fuel status=staticmethod(status) def main(): ship1=Ship(raw_input("What would you like to name this ship?")) fuel_level=raw_input("How much fuel does this ship have?") if fuel_level<0: self.fuel=0 else: self.fuel(fuel_level) ship2=Ship(raw_input("What would you like to name this ship?")) fuel_level2=raw_input("How much fuel does this ship have?") if fuel_level2<0: self.fuel=0 else: self.fuel(fuel_level2) ship3=Ship(raw_input("What would you like to name this ship?")) fuel_level3=raw_input("How much fuel does this ship have?") if fuel_level3<0: self.fuel=0 else: self.fuel(fuel_level3) Ship.status() main() raw_input("Press enter to exit.")

    Read the article

  • NSTask executed only once

    - by Eimantas
    I'm having trouble executing different NSTask's. Same launchPath, different arguments. I have a class who's instances administer own NSTask objects and depending on arguments those instances were initialized with - dependent NSTask object is being created. I have two initializers: // Method for finished task - (void)taskFinished:(NSNotification *)aNotification { [myTask release]; myTask = nil; [self createTask]; } // Designated initializer - (id) init { self = [super init]; if (self != nil) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskFinished:) name:NSTaskDidTerminateNotification object:nil]; [self createTask]; } return self; } // Convenience initializer - (id)initWithCommand:(NSString *)subCommand { self = [self init]; if (self) { [self setCommand:subCommand]; } return self; } And here 's the createTask method: - (void)createTask { // myTask is a property defined as NSTask* myTask = [[NSTask alloc] init]; [myTask setLaunchPath:@"/usr/bin/executable"]; } Say I have 3 buttons. Each one creates different class instance with different NSTask objects. But problem is that only first one gets executed. The second ones does not even triger "click" event (via target-action). I think it could be cause of launchPath I'm trying to use, 'cause simple /bin/ls works fine. The same command in terminal has 0 return value (i.e. all is fine). Any guides or gotchas are much appreciated.

    Read the article

  • Django forms: how to dynamically create ModelChoiceField labels

    - by Henri
    I would like to create dynamic labels for a forms.ModelChoiceField and I'm wondering how to do that. I have the following form class: class ProfileForm(forms.ModelForm): def __init__(self, data=None, ..., language_code='en', family_name_label='Family name', horoscope_label='Horoscope type', *args, **kwargs): super(ProfileForm, self).__init__(data, *args, **kwargs) self.fields['family_name'].label = family_name_label . . self.fields['horoscope'].label = horoscope_label self.fields['horoscope'].queryset = Horoscope.objects.all() class Meta: model = Profile family_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80', 'class': 'contact_form'})) . . horoscope = forms.ModelChoiceField(queryset = Horoscope.objects.none(), widget=forms.RadioSelect(), empty_label=None) The default labels are defined by the unicode function specified in the Profile definition. However the labels for the radio buttons created by the ModelChoiceField need to be created dynamically. First I thought I could simply override ModelChoiceField as described in the Django documentation. But that creates static labels. It allows you to define any label but once the choice is made, that choice is fixed. So I think I need to adapt add something to init like: class ProfileForm(forms.ModelForm): def __init__(self, data=None, ..., language_code='en', family_name_label='Family name', horoscope_label='Horoscope type', *args, **kwargs): super(ProfileForm, self).__init__(data, *args, **kwargs) self.fields['family_name'].label = family_name_label . . self.fields['horoscope'].label = horoscope_label self.fields['horoscope'].queryset = Horoscope.objects.all() self.fields['horoscope'].<WHAT>??? = ??? Anyone having any idea how to handle this? Any help would be appreciated very much.

    Read the article

  • define a closure as method from class

    - by user272839
    Hi, i'm trying to play with php5.3 and closure. I see here (Listing 7. Closure inside an object : http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html) that it's possible to use $this in the callback function, but it's not. So I try to give $this as use variable : $self = $this; $foo = function() use($self) { //do something with $self } So to use the same example : class Dog { private $_name; protected $_color; public function __construct($name, $color) { $this->_name = $name; $this->_color = $color; } public function greet($greeting) { $self = $this; return function() use ($greeting, $self) { echo "$greeting, I am a {$self->_color} dog named {$self->_name}."; }; } } $dog = new Dog("Rover","red"); $dog->greet("Hello"); Output: Hello, I am a red dog named Rover. First of all this example does not print the string but return the function, but that's not my problem. Secondly I can't access to private or protected, because the callback function is a global function and not in the context from the Dog object. Tha't my problem. It's the same as : function greet($greeting, $object) { echo "$greeting, I am a {$self->_color} dog named {$self->_name}."; } And I want : public function greet($greeting) { echo "$greeting, I am a {$self->_color} dog named {$self->_name}."; } Which is from Dog and not global. I hope that I am clear ...

    Read the article

  • How to provide an inline model field with a queryset choices without losing field value for inline r

    - by Judith Boonstra
    The code displayed below is providing the choices I need for the app field, and the choices I need for the attr field when using Admin. I am having a problem with the attr field on the inline form for already saved records. The attr selected for these saved does show in small print above the field, but not within the field itself. # MODELS: Class Vocab(models.Model): entity = models.Charfield, max_length = 40, unique = True) Class App(models.Model): name = models.ForeignKey(Vocab, related_name = 'vocab_appname', unique = True) app = SelfForeignKey('self, verbose_name = 'parent', blank = True, null = True) attr = models.ManyToManyField(Vocab, related_name = 'vocab_appattr', through ='AppAttr' def parqs(self): a method that provides a queryset consisting of available apps from vocab, excluding self and any apps within the current app's dependent line. def attrqs(self): a method that provides a queryset consisting of available attr from vocab excluding those already selected by current app, 2) those already selected by any apps within the current app's parent line, and 3) those selected by any apps within the current app's dependent line. Class AppAttr(models.Model): app = models.ForeignKey(App) attr = models.ForeignKey(Vocab) # FORMS: from models import AppAttr def appattr_form_callback(instance, field, *args, **kwargs) if field.name = 'attr': if instance: return field.formfield(queryset = instance.attrqs(), *kwargs) return field.formfield(*kwargs) # ADMIN: necessary imports class AppAttrInline(admin.TabularInline): model = AppAttr def get_formset(self, request, obj = None, **kwargs): kwargs['formfield_callback'] = curry(appattr_form_callback, obj) return super(AppAttrInline, self).get_formset(request, obj, **kwargs) class AppForm(forms.ModelForm): class Meta: model = App def __init__(self, *args, **kwargs): super(AppForm, self).__init__(*args, **kwargs) if self.instance.id is None: working = App.objects.all() else: thisrec = App.objects.get(id = self.instance.id) working = thisrec.parqs() self.fields['par'].queryset = working class AppAdmin(admin.ModelAdmin): form = AppForm inlines = [AppAttrInline,] fieldsets = .......... necessary register statements

    Read the article

  • Refreshing a MKMapView when the user location is updated or using default values

    - by koichirose
    I'm trying to refresh my map view and load new data from the server when the device acquires the user location. Here's what I'm doing: - (void)viewDidLoad { CGRect bounds = self.view.bounds; mapView = [[MKMapView alloc] initWithFrame:bounds]; mapView.showsUserLocation=YES; mapView.delegate=self; [self.view insertSubview:mapView atIndex:0]; [self refreshMap]; } - (void)mapView:(MKMapView *)theMapView didUpdateUserLocation:(MKUserLocation *)userLocation { //this is to avoid frequent updates, I just need one position and don't need to continuously track the user's location if (userLocation.location.horizontalAccuracy > self.myUserLocation.location.horizontalAccuracy) { self.myUserLocation = userLocation; CLLocationCoordinate2D centerCoord = { userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude }; [theMapView setCenterCoordinate:centerCoord zoomLevel:10 animated:YES]; [self refreshMap]; } } - (void)refreshMap { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; [self.mapView removeAnnotations:self.mapView.annotations]; //default position NSString *lat = @"45.464161"; NSString *lon = @"9.190336"; if (self.myUserLocation != nil) { lat = [[NSNumber numberWithDouble:myUserLocation.coordinate.latitude] stringValue]; lon = [[NSNumber numberWithDouble:myUserLocation.coordinate.longitude] stringValue]; } NSString *url = [[NSString alloc] initWithFormat:@"http://myserver/geo_search.json?lat=%@&lon=%@", lat, lon]; NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; [url release]; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; } I also have a - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data, to create and add the annotations. Here's what happens: sometimes I get the location after a while, so I already loaded data close to the default location. Then I get the location and it should remove the old annotations and add the new ones, instead I keep seeing the old annotations and the new ones are added anyway (let's say I receive 10 annotations each time, so it means that I have 20 on my map when I should have 10). What am I doing wrong?

    Read the article

  • Rails: updating an association

    - by Sam
    I have a Reservation model which belongs_to a Sharedorder and so a Sharedorder has_many reservations. Give you a little background. I sharedorder has many reservations and each reservation can have an amount. A sharedorder has three status: 1) reserved, 2) confirmed, 3) and purchased. Here is my problem. When a reservation gets added to a sharedorder or an existing reservation's amount is updated I need this to affect the associated sharedoder because the status listed latter should only change when 100% of the reservations have been placed and so on. Here are the things I have tried: . class Reservation < ActiveRecord::Base before_save :sharedorder_reserved_status def sharedorder_reserved_status if self.sharedorder.reserved_percent(reservations_to_be_added) >= 100 && !self.sharedorder.reserved self.sharedorder.update_attribute(:reserved, true) self.sharedorder.update_attribute(:reserved_at, Time.now) end end def reservations_to_be_added if self.new_record? self.amount elsif self.amount_changed? self.amount - self.amount_was else 0 end end end And then in the Sharedorder model: class Sharedorder < ActiveRecord::Base def reserved_percent(amount_change) (((reserved_sum + amount_change).to_f / self.product.twenty_hq_size.to_f)*100).to_i end def reserved_sum if !@reserved_sum reserved_sum = 0 reserved_reservations.collect {|x| reserved_sum += x.amount } reserved_sum else @reserved_sum end end def reserved_reservations @reserved_reservations ||= Reservation.find(:all, :conditions => ['canceled = ? AND sharedorder_id = ?', false, self.id ]) end end I have also tried :touch => true on the reservation model to update the sharedorder put for some reason it doesn't seem to include the latest reservation being added or being updated. So what I'm trying to do is update the status of the sharedorder if a certain percent is reached and I have to send the additional amounts the the sharedorder for it to know to include additional reservations or updates on existing ones. How should I do this?

    Read the article

  • initWithCoder not working as expected?

    - by fuzzygoat
    Does this seem right, the dataFilePath is on disk and contains the right data, but the MSMutable array does not contain any objects after the initWithCoder? I am probably just missing something, but I wanted to quickly check here before moving on. -(id)initWithCoder:(NSCoder *)decoder { self = [super init]; if(self) { [self setReactorCore:[decoder decodeObjectForKey:@"CORE"]]; } return self; } . -(id)init { self = [super init]; if(self) { if([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) { NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]]; NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; NSMutableArray *newCore = [[NSMutableArray alloc] initWithCoder:unArchiver]; [self setReactorCore:newCore]; [newCore release]; [data release]; [unArchiver release]; } else { NSMutableArray *newCore = [[NSMutableArray alloc] init]; [self setReactorCore:newCore]; [newCore release]; } } return self; } gary

    Read the article

  • how to download data which upload to gae ,

    - by zjm1126
    this is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htmlPrefix,get_current_user class MyModel(db.Model): blob = db.BlobProperty() class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_args=None): if not template_args: template_args = {} path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_args)) class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file.encode('utf8')) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.out.write(o) application = webapp.WSGIApplication( [ ('/?', upload), ('/download',download), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main() my index.html is : <form action="/" method="post"> <input type="file" name="file" /> <input type="submit" /> </form> and it show : <__main__.MyModel object at 0x02506830> but ,i don't want to see this , i want to download it , how to change my code to run, thanks

    Read the article

  • In Python, how to make data members visible to subclasses if not known when initializing an object ?

    - by LB
    The title is a bit long, but it should be pretty straightforward for someone well-aware of python. I'm a python newbie. So, maybe i'm doing things in the wrong way. Suppose I have a class TreeNode class TreeNode(Node): def __init__(self, name, id): Node.__init__(self, name, id) self.children = [] and a subclass with a weight: class WeightedNode(TreeNode): def __init__(self,name, id): TreeNode.__init__(self, name, id) self.weight = 0 So far, i think I'm ok. Now, I want to add an object variable called father in TreeNode so that WeightedNode has also this member. The problem is that I don't know when initializing the object who is going to be the father. I set the father afterwards with this method in TreeNode : def set_father(self, father_node): self.father = father_node The problem is then when i'm trying to access self.father in Weighted: print 'Name %s Father %s '%(self.name, self.father.name) I obtain: AttributeError: WeightedNode instance has no attribute 'father' I thought that I could make father visible by doing something in TreeNode.__init__ but i wasn't able to find what. How can i do that ? Thanks.

    Read the article

  • How to make buttons in python/pygame?

    - by user1334014
    I'm making a game in pygame and on the first screen I want there to be buttons that you can press to (i) start the game, (ii) load a new screen with instructions, and (iii) exit the program. I've found this code online for button making, but I don't really understand it (I'm not that good at object oriented programming). If I could get some explanation as to what it's doing that would be great. Also, when I use it and try to open a file on my computer using the file path, I get the error sh: filepath :Permission denied, which I don't know how to solve. #load_image is used in most pygame programs for loading images def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() class Button(pygame.sprite.Sprite): """Class used to create a button, use setCords to set position of topleft corner. Method pressed() returns a boolean and should be called inside the input loop.""" def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('button.png', -1) def setCords(self,x,y): self.rect.topleft = x,y def pressed(self,mouse): if mouse[0] > self.rect.topleft[0]: if mouse[1] > self.rect.topleft[1]: if mouse[0] < self.rect.bottomright[0]: if mouse[1] < self.rect.bottomright[1]: return True else: return False else: return False else: return False else: return False def main(): button = Button() #Button class is created button.setCords(200,200) #Button is displayed at 200,200 while 1: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pos() if button.pressed(mouse): #Button's pressed method is called print ('button hit') if __name__ == '__main__': main() Thank you to anyone who can help me.

    Read the article

  • Django - Problem with models/manager to organise a query...

    - by user296644
    Hi, I have an application to count the number of access to an object for each website in a same database. class SimpleHit(models.Model): """ Hit is the hit counter of a given object """ content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') site = models.ForeignKey(Site) hits_total = models.PositiveIntegerField(default=0, blank=True) [...] class SimpleHitManager(models.Manager): def get_query_set(self): print self.model._meta.fields qset = super(SimpleHitManager, self).get_query_set() qset = qset.filter(hits__site=settings.SITE_ID) return qset class SimpleHitBase(models.Model): hits = generic.GenericRelation(SimpleHit) objects = SimpleHitManager() _hits = None def _db_get_hits(self, only=None): if self._hits == None: try: self._hits = self.hits.get(site=settings.SITE_ID) except SimpleHit.DoesNotExist: self._hits = SimpleHit() return self._hits @property def hits_total(self): return self._db_get_hits().hits_total [...] class Meta: abstract = True And I have a model like: class Model(SimpleHitBase): name = models.CharField(max_length=255) url = models.CharField(max_length=255) rss = models.CharField(max_length=255) creation = AutoNowAddDateTimeField() update = AutoNowDateTimeField() So, my problem is this one: when I call Model.objects.all(), I would like to have one request for the SQL (not two). In this case: one for Model in order to have information and one for the hits in order to have the counter (hits_total). This is because I cannot call directly hits.hits_total (due to SITE_ID?). I have tried select_related, but it seems to do not work... Question: - How can I add column automatically like (SELECT hits.hits_total, model.* FROM [...]) to the queryset? - Or use a functional select_related with my models? I want this model could be plugable on all other existing model. Thank you, Best regards.

    Read the article

  • Mutate an object into an instance of one its subclasses

    - by Gohu
    Hi, Is it possible to mutate an object into an instance of a derived class of the initial's object class? Something like: class Base(): def __init__(self): self.a = 1 def mutate(self): self = Derived() class Derived(Base): def __init__(self): self.b = 2 But that doesn't work. >>> obj = Base() >>> obj.mutate() >>> obj.a 1 >>> obj.b AttributeError... If this isn't possible, how should I do otherwise? My problem is the following: My Base class is like a "summary", and the Derived class is the "whole thing". Of course getting the "whole thing" is a bit expensive so working on summaries as long as it is possible is the point of having these two classes. But you should be able to get it if you want, and then there's no point in having the summary anymore, so every reference to the summary should now be (or contain, at least) the whole thing. I guess I would have to create a class that can hold both, right? class Thing(): def __init__(self): self.summary = Summary() self.whole = None def get_whole_thing(self): self.whole = Whole()

    Read the article

  • What FTP clients securely handle FTP/TLS where the server has a self-signed cert?

    - by billpg
    I'm trying to connect to an FTP server that uses TLS on port 990. Unfortunately, the server uses a self-signed cert. What FTP clients for Windows handle this type of connection securely, such that I can securely verify the cert before continuing with the connection and logging in? (The server admin has supplied me with the expected certificate thumbprint to look for.) As an example of doing it wrongly, Core FTP LE 2.2 presents a dialog with basic information about the cert presented, inviting me to accept-once, accept-always or cancel. The dialog does not include the cert's hash/thumbprint and without that thumprint, I can't verify if the cert I'm being presented is the right one.

    Read the article

  • What are the advantages of OSPF vs nexthop self with iBGP?

    - by Matt Hamilton
    Assuming I have a fairly small network internally, but I have 4 routers each connected out to a different network. The routers are all sat next to each other connected via a switch. Each router uses BGP to speak to the outside networks. There is an iBGP mesh for each router to exchange the routes internally it knows about from each external network. The usual setup is to use OSPF to distribute the connected routes, as the routes via iBGP will still have the next hop set to their original value. What is the advantage of using OSPF in this scenario versus simply using 'set nexthop self' on the routes?

    Read the article

  • PyGTK: dynamic label wrapping

    - by detly
    It's a known bug/issue that a label in GTK will not dynamically resize when the parent changes. It's one of those really annoying small details, and I want to hack around it if possible. I followed the approach at 16 software, but as per the disclaimer you cannot then resize it smaller. So I attempted a trick mentioned in one of the comments (the set_size_request call in the signal callback), but this results in some sort of infinite loop (try it and see). Does anyone have any other ideas? (You can't block the signal just for the duration of the call, since as the print statements seem to indicate, the problem starts after the function is left.) The code is below. You can see what I mean if you run it and try to resize the window larger and then smaller. (If you want to see the original problem, comment out the line after "Connect to the size-allocate signal", run it, and resize the window bigger.) The Glade file ("example.glade"): <?xml version="1.0"?> <glade-interface> <!-- interface-requires gtk+ 2.16 --> <!-- interface-naming-policy project-wide --> <widget class="GtkWindow" id="window1"> <property name="visible">True</property> <signal name="destroy" handler="on_destroy"/> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">In publishing and graphic design, lorem ipsum[p][1][2] is the name given to commonly used placeholder text (filler text) to demonstrate the graphic elements of a document or visual presentation, such as font, typography, and layout. The lorem ipsum text, which is typically a nonsensical list of semi-Latin words, is a hacked version of a Latin text by Cicero, with words/letters omitted and others inserted, but not proper Latin[1][2] (see below: History and discovery). The closest English translation would be "pain itself" (dolorem = pain, grief, misery, suffering; ipsum = itself).</property> <property name="wrap">True</property> </widget> </child> </widget> </glade-interface> The Python code: #!/usr/bin/python import pygtk import gobject import gtk.glade def wrapped_label_hack(gtklabel, allocation): print "In wrapped_label_hack" gtklabel.set_size_request(allocation.width, -1) # If you uncomment this, we get INFINITE LOOPING! # gtklabel.set_size_request(-1, -1) print "Leaving wrapped_label_hack" class ExampleGTK: def __init__(self, filename): self.tree = gtk.glade.XML(filename, "window1", "Example") self.id = "window1" self.tree.signal_autoconnect(self) # Connect to the size-allocate signal self.get_widget("label1").connect("size-allocate", wrapped_label_hack) def on_destroy(self, widget): self.close() def get_widget(self, id): return self.tree.get_widget(id) def close(self): window = self.get_widget(self.id) if window is not None: window.destroy() gtk.main_quit() if __name__ == "__main__": window = ExampleGTK("example.glade") gtk.main()

    Read the article

  • Django : presenting a form very different from the model and with multiple field values in a Django-

    - by sebpiq
    Hi ! I'm currently doing a firewall management application for Django, here's the (simplified) model : class Port(models.Model): number = models.PositiveIntegerField(primary_key=True) application = models.CharField(max_length=16, blank=True) class Rule(models.Model): port = models.ForeignKey(Port) ip_source = models.IPAddressField() ip_mask = models.IntegerField(validators=[MaxValueValidator(32)]) machine = models.ForeignKey("vmm.machine") What I would like to do, however, is to display to the user a form for entering rules, but with a very different organization than the model : Port 80 O Not open O Everywhere O Specific addresses : --------- delete field --------- delete field + add address field Port 443 ... etc Where Not open means that there is no rule for the given port, Everywhere means that there is only ONE rule (0.0.0.0/0) for the given port, and with specific addresses, you can add as many addresses as you want (I did this with JQuery), which will make as many rules. Now I did a version completely "handmade", meaning that I create the forms entirely in my templates, set input names with a prefix, and parse all the POSTed stuff in my view (which is quite painful, and means that there's no point in using a web framework). I also have a class which aggregates the rules together to easily pre-fill the forms with the informations "not open, everywhere, ...". I'm passing a list of those to the template, therefore it acts as an interface between my model and my "handmade" form : class MachinePort(object): def __init__(self, machine, port): self.machine = machine self.port = port @property def fully_open(self): for rule in self.port.rule_set.filter(machine=self.machine): if ipaddr.IPv4Network("%s/%s" % (rule.ip_source, rule.ip_mask)) == ipaddr.IPv4Network("0.0.0.0/0"): return True else : return False @property def partly_open(self): return bool(self.port.rule_set.filter(machine=self.machine)) and not self.fully_open @property def not_open(self): return not self.partly_open and not self.fully_open But all this is rather ugly ! Do anyone of you know if there is a classy way to do this ? In particular with the form... I don't know how to have a form that can have an undefined number of fields, neither how to transform these fields into Rule objects (because all the rule fields would have to be gathered from the form), neither how to save multiple objects... Well I could try to hack into the Form class, but seems like too much work for such a special case. Is there any nice feature I'm missing ?

    Read the article

  • Is there way to find when self signed certificate will expire for Adobe Air application?

    - by tyler
    Hi, I have to release my Adobe Air application but the build process was "setup" by a different developer. (He made a self signed cert and wrote a batch file to call adt for packaging the application). Adobe mentions that such self signed certificates are valid for 5 years. Now I have no idea when that certificate will expire as I don't know when it was created. Also will my installed application stop working on expiry or only new installations will fail ? Thanks.

    Read the article

< Previous Page | 52 53 54 55 56 57 58 59 60 61 62 63  | Next Page >