Search Results

Search found 68 results on 3 pages for 'keyerror'.

Page 1/3 | 1 2 3  | Next Page >

  • str.format() does not work, keyError

    - by Dor
    The following code raise a keyError exception: addr_list_formatted = [] addr_list_idx = 0 for addr in addr_list: # addr_list is a list addr_list_idx = addr_list_idx + 1 addr_list_formatted.append(""" "{0}" { "gamedir" "str" "address" "{1}" } """.format(addr_list_idx, addr)) Why? Using python 3.1. Thanks.

    Read the article

  • KeyError this says that key(partner) is not in dict ?

    - by Ansh Jain
    I am trying to make an chat application using python and django. I almost complete it and its working fine for 8-10 minutes when two persons are chatting after that certain time it shows an error. here is the traceback : - Traceback (most recent call last): File "\Django_chat\django_chat\chat\views.py", line 55, in receive message = chatSession.getMessage(request.session['partner'],request.session['uid'],afterTime) File "C:\Python26\lib\site-packages\django\contrib\sessions\backends\base.py", line 47, in __getitem__ return self._session[key] KeyError: 'partner' here is the receive module :- def receive(request): message received by this user chatSession = chat() data = request.POST afterTime = data['lastMsgTime'] try: message = chatSession.getMessage(request.session['partner'],request.session['uid'],afterTime) except: #partnerId = virtual_users.objects.get(id=request.session['uid']).partner print('there is an error in receive request') traceback.print_exc(file=open("/myapp.log","a")) msg = serializers.serialize("json", message) return HttpResponse(msg) Please Help me :( thanks Ansh J

    Read the article

  • How to debug python del self.callbacks[s][cid] keyError when the error message does not indicate where in my code the error is

    - by lkloh
    In a python program I am writing, I get an error saying Traceback (most recent call last): File "/Applications/Canopy.app/appdata/canopy-1.4.0.1938.macosx- x86_64/Canopy.app/Contents/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__ return self.func(*args) File "/Users/lkloh/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 413, in button_release_event FigureCanvasBase.button_release_event(self, x, y, num, guiEvent=event) File "/Users/lkloh/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1808, in button_release_event self.callbacks.process(s, event) File "/Users/lkloh/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/cbook.py", line 525, in process del self.callbacks[s][cid] KeyError: 103 Do you have any idea how I can debug this/ what could be wrong? The error message does not point to anywhere in code I have personally written. I get the error message only after I close my GUI window, but I want to fix it even though it does not break the functionality of my code. The error is part of a very big program I am writing, so I cannot post all my code, but below is code I think is relevant: def save(self, event): self.getSaveAxes() self.save_connect() def getSaveAxes(self): saveFigure = figure(figsize=(8,1)) saveFigure.clf() # size of save buttons rect_saveHeaders = [0.04,0.2,0.2,0.6] rect_saveHeadersFilterParams = [0.28,0.2,0.2,0.6] rect_saveHeadersOverride = [0.52,0.2,0.2,0.6] rect_saveQuit = [0.76,0.2,0.2,0.6] #initalize axes saveAxs = {} saveAxs['saveHeaders'] = saveFigure.add_axes(rect_saveHeaders) saveAxs['saveHeadersFilterParams'] = saveFigure.add_axes(rect_saveHeadersFilterParams) saveAxs['saveHeadersOverride'] = saveFigure.add_axes(rect_saveHeadersOverride) saveAxs['saveQuit'] = saveFigure.add_axes(rect_saveQuit) self.saveAxs = saveAxs self.save_connect() self.saveFigure = saveFigure show() def save_connect(self): #set buttons self.bn_saveHeaders = Button(self.saveAxs['saveHeaders'], 'Save\nHeaders\nOnly') self.bn_saveHeadersFilterParams = Button(self.saveAxs['saveHeadersFilterParams'], 'Save Headers &\n Filter Parameters') self.bn_saveHeadersOverride = Button(self.saveAxs['saveHeadersOverride'], 'Save Headers &\nOverride Data') self.bn_saveQuit = Button(self.saveAxs['saveQuit'], 'Quit') #connect buttons to functions they trigger self.cid_saveHeaders = self.bn_saveHeaders.on_clicked(self.save_headers) self.cid_savedHeadersFilterParams = self.bn_saveHeadersFilterParams.on_clicked(self.save_headers_filterParams) self.cid_saveHeadersOverride = self.bn_saveHeadersOverride.on_clicked(self.save_headers_override) self.cid_saveQuit = self.bn_saveQuit.on_clicked(self.save_quit) def save_quit(self, event): self.save_disconnect() close()

    Read the article

  • Getting a KeyError in DB backend of django-digest

    - by rtmie
    I have just started to integrate django_digest into my app. As a start I have added the @httpdigest decorator to one of my views. If I try to connect to it I get a KeyError exception thrown in django_digest/backend/db.py . Depending on which db I configure I get a different KeyError in a different location. I am using Django 1.2.1, with MySql (also tested with sqlite). I am using the default values for all the settings options. As far as I can see I have followed all instructions but am struggling all day with this. I am using the repository versions of django-digest and python-digest. Any steer would be greatly appreciated. Tracebacks for sqlite and mysql below: with sqlite: Traceback (most recent call last): File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/core/servers/basehttp.py", line 674, in __call__ return self.application(environ, start_response) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 248, in __call__ signals.request_finished.send(sender=self.__class__) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/dispatch/dispatcher.py", line 162, in send response = receiver(signal=self, sender=sender, **named) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django_digest-1.8-py2.5.egg/django_digest/backend/db.py", line 16, in close_connection _connection.close() File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 186, in close if self.settings_dict['NAME'] != ":memory:": KeyError: 'NAME' with mysql: Traceback (most recent call last): File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/core/servers/basehttp.py", line 674, in __call__ return self.application(environ, start_response) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 241, in __call__ response = self.get_response(request) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/core/handlers/base.py", line 142, in get_response return self.handle_uncaught_exception(request, resolver, exc_info) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/core/handlers/base.py", line 166, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/core/handlers/base.py", line 80, in get_response response = middleware_method(request) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django_digest-1.8-py2.5.egg/django_digest/middleware.py", line 13, in process_request if (not self._authenticator.authenticate(request) and File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django_digest-1.8-py2.5.egg/django_digest/__init__.py", line 86, in authenticate partial_digest = self._account_storage.get_partial_digest(digest_response.username) File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django_digest-1.8-py2.5.egg/django_digest/backend/db.py", line 97, in get_partial_digest cursor = get_connection().cursor() File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/db/backends/__init__.py", line 75, in cursor cursor = self._cursor() File "/home/robm/projects/gcs/server/gcs2.5/lib/python2.5/site-packages/django/db/backends/mysql/base.py", line 281, in _cursor if settings_dict['USER']: KeyError: 'USER'

    Read the article

  • json KeyError with json.loads

    - by user322775
    my apologies in advance for a python and json nubie question. json seems to be hiccuping on the following statements: {"delete":{"status":{"id":12600579001,"user_id":55389449}}} code snippet: temp = json.loads(line) text = temp['text'] I get the following error output when the above code snippet encounters lines similar to the above json 'dictionary': text = temp['text'] KeyError: 'text' Is it because there is no "text" key in the line or because "delete" is not in the dictionary?

    Read the article

  • app-engine-rest-server to raise KeyError("name %s already used" % model_name)

    - by fx
    I'm playing with the project appengine-rest-server to create the REST webservices for all the existing models. I got a strange error, the first time I query the browser: http://localhost:8080/rest/metadata/user, it gives me the result: <xs:schema> - <xs:element name="user"> - <xs:complexType> - <xs:sequence> <xs:element maxOccurs="1" minOccurs="0" name="key" type="xs:normalizedString"/> <xs:element maxOccurs="1" minOccurs="0" name="surname" type="xs:string"/> <xs:element maxOccurs="1" minOccurs="0" name="firstname" type="xs:string"/> <xs:element maxOccurs="1" minOccurs="0" name="ages" type="xs:long"/> <xs:element maxOccurs="1" minOccurs="0" name="sex" type="xs:boolean"/> <xs:element maxOccurs="1" minOccurs="0" name="updatedDate" type="xs:dateTime"/> <xs:element maxOccurs="1" minOccurs="0" name="createdDate" type="xs:dateTime"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> But refreshing the page, gives me this error: Traceback (most recent call last): File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3185, in _HandleRequest self._Dispatch(dispatcher, self.rfile, outfile, env_dict) File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3128, in _Dispatch base_env_dict=env_dict) File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 515, in Dispatch base_env_dict=base_env_dict) File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2387, in Dispatch self._module_dict) File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2297, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2195, in ExecuteOrImportScript script_module.main() File "/Users/foo/Documents/AppEngine/helloworld/main.py", line 48, in main rest.Dispatcher.add_models({"user": UserModel}) File "/Users/foo/Documents/AppEngine/helloworld/rest/__init__.py", line 845, in add_models cls.add_model(model_name, model_type) File "/Users/foo/Documents/AppEngine/helloworld/rest/__init__.py", line 863, in add_model raise KeyError("name %s already used" % model_name) KeyError: 'name user already used' Can someone give me the explanation on why it happens? Restarting the server, run on the browser again I get the xml result, but refreshing causes the error. Is it a bug in the appengine-rest-server application or it is in my code? My helloworld application is available for download here.

    Read the article

  • I keep Getting KeyError: 'tried' Whenever I Tried to Run Django Dev Server from Remote Machine

    - by Spikie
    I am running django on python2.6.1, and did start the django web server like this manage.py runserver 192.0.0.1:8000 then tried to connect to the django dev web server on http://192.0.0.1:8000/ keep getting this message on the remote computer Traceback (most recent call last): File "C:\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 279, in run self.result = application(self.environ, self.start_response) File "C:\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 651, in call return self.application(environ, start_response) File "C:\Python26\lib\site-packages\django\core\handlers\wsgi.py", line 241, in call response = self.get_response(request) File "C:\Python26\lib\site-packages\django\core\handlers\base.py", line 115, in get_response return debug.technical_404_response(request, e) File "C:\Python26\Lib\site-packages\django\views\debug.py", line 247, in technical_404_response tried = exception.args[0]['tried'] KeyError: 'tried' what i am doing wrong ? it seen to work ok if i run http://192.0.0.1:8000/ on the computer that runs the Django web server and have that ip 192.0.0.1:8000

    Read the article

  • python json_encode throws KeyError exception

    - by MattM
    In a unit test case that I am running, I get a KeyError exception on the 4th json object in the json text below. I went through the sub-objects and found that it was the "cpuid" object that is the offending object, but I am completely at a loss as to what is wrong with the formatting. response = self.app.post( '/machinestats', params=dict(record=self.json_encode([ {"type": "crash", "instance_id": "xxx", "version": "0.2.0", "build_id": "unknown", "crash_text": "Gah!"}, {"type": "machine_info", "machine_info": "I'm awesome.", "version": "0.2.0", "build_id": "unknown", "instance_id": "yyy"}, {"machine_info": "Soup", "crash_text": "boom!", "version": "0.2.0", "build_id": "unknown", "instance_id": "zzz", "type": "crash"}, {"build_id" : "unknown", "cpu_brand" : "intel", "cpu_count" : 4, "cpuid": { "00000000": {"eax" :123,"ebx" :456, "ecx" :789,"edx" :321}, "00000001": {"eax" :123,"ebx" :456, "ecx" :789,"edx" :321}}, "driver_installed" : True, "instance_id" : "yyy", "version" : "0.2.0", "machine_info" : "I'm awesome.", "os_version" : "linux", "physical_memory_mib" : 1024, "product_loaded" : True, "type" : "machine_info", "virtualization_advertised" : True} ])))

    Read the article

  • : in node causing Keyerror in xmlparsing using ElementTree

    - by kguckian
    Hi I'm using ElementTree to parse out an xml feed from Kuler. I'm only beginning in python but am stuck here. The parsing works fine until I attempt to retrieve any nodes containing ':' e.g kuler:swatchHexColor Below is a cut down version of the full feed but same structure: <rss xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:kuler="http://kuler.adobe.com/kuler/API/rss/" xmlns:rss="http://blogs.law.harvard.edu/tech/rss" version="2.0"> <channel> <title>kuler popular themes</title> <item> <title>Theme Title: Fresh Money</title> <description> &lt;img src="http://kuler-api.adobe.com/kuler/themeImages/theme_808366.png" /&gt;&lt;br /&gt; Artist: thesylph005&lt;br /&gt; ThemeID: 808366&lt;br /&gt; Posted: 03/02/2010&lt;br /&gt; Hex: 2F400D, 8CBF26, A8CA65, E8E5B0, 419184 </description> <kuler:themeItem> <kuler:themeID>808366</kuler:themeID> <kuler:themeTitle>Fresh Money</kuler:themeTitle> <kuler:themeImage>http://kuler-api.adobe.com/kuler/themeImages/theme_808366.png</kuler:themeImage> <kuler:themeAuthor> <kuler:authorID>370750</kuler:authorID> <kuler:authorLabel>thesylph005</kuler:authorLabel> </kuler:themeAuthor> <kuler:themeTags/> <kuler:themeRating>4</kuler:themeRating> <kuler:themeDownloadCount>708</kuler:themeDownloadCount> <kuler:themeCreatedAt>20100302</kuler:themeCreatedAt> <kuler:themeEditedAt>20100302</kuler:themeEditedAt> <kuler:themeSwatches> <kuler:swatch> <kuler:swatchHexColor>2F400D</kuler:swatchHexColor> <kuler:swatchColorMode>rgb</kuler:swatchColorMode> <kuler:swatchChannel1>0.183333</kuler:swatchChannel1> <kuler:swatchChannel2>0.25</kuler:swatchChannel2> <kuler:swatchChannel3>0.05</kuler:swatchChannel3> <kuler:swatchChannel4>0.0</kuler:swatchChannel4> <kuler:swatchIndex>0</kuler:swatchIndex> </kuler:swatch> <kuler:swatch> <kuler:swatchHexColor>8CBF26</kuler:swatchHexColor> <kuler:swatchColorMode>rgb</kuler:swatchColorMode> <kuler:swatchChannel1>0.55</kuler:swatchChannel1> <kuler:swatchChannel2>0.75</kuler:swatchChannel2> <kuler:swatchChannel3>0.15</kuler:swatchChannel3> <kuler:swatchChannel4>0.0</kuler:swatchChannel4> <kuler:swatchIndex>1</kuler:swatchIndex> </kuler:swatch> <kuler:swatch> <kuler:swatchHexColor>A8CA65</kuler:swatchHexColor> <kuler:swatchColorMode>rgb</kuler:swatchColorMode> <kuler:swatchChannel1>0.659722</kuler:swatchChannel1> <kuler:swatchChannel2>0.791667</kuler:swatchChannel2> <kuler:swatchChannel3>0.395833</kuler:swatchChannel3> <kuler:swatchChannel4>0.0</kuler:swatchChannel4> <kuler:swatchIndex>2</kuler:swatchIndex> </kuler:swatch> <kuler:swatch> <kuler:swatchHexColor>E8E5B0</kuler:swatchHexColor> <kuler:swatchColorMode>rgb</kuler:swatchColorMode> <kuler:swatchChannel1>0.91</kuler:swatchChannel1> <kuler:swatchChannel2>0.898047</kuler:swatchChannel2> <kuler:swatchChannel3>0.688705</kuler:swatchChannel3> <kuler:swatchChannel4>0.0</kuler:swatchChannel4> <kuler:swatchIndex>3</kuler:swatchIndex> </kuler:swatch> <kuler:swatch> <kuler:swatchHexColor>419184</kuler:swatchHexColor> <kuler:swatchColorMode>rgb</kuler:swatchColorMode> <kuler:swatchChannel1>0.254901</kuler:swatchChannel1> <kuler:swatchChannel2>0.57</kuler:swatchChannel2> <kuler:swatchChannel3>0.519034</kuler:swatchChannel3> <kuler:swatchChannel4>0.0</kuler:swatchChannel4> <kuler:swatchIndex>4</kuler:swatchIndex> </kuler:swatch> </kuler:themeSwatches> Tue, 30 Mar 2010 11:27:12 PST So if I do a findall on say each item's description, I get that back fine. But the minute I try to retrieve anything with a : in the nodename I get Exception Type: KeyError Exception Value: ':' So this works from elementtree.ElementTree import Element, SubElement, dump, parse def xml(): kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey' rss = parse(urllib.urlopen(kulerurl)).getroot() for element in rss.findall('channel/item'): print(element.findtext('description')) dump (rss) but this doesn't def xml(): kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey' rss = parse(urllib.urlopen(kulerurl)).getroot() for element in rss.findall('channel/item/kuler:themeItem'): print(element.findtext('kuler:themeID')) dump (rss) I'm sure it's something simple if anyone could point me to what I'm doing wrong here I'd be most grateful thanks Kieran

    Read the article

  • Python raises a KeyError (for an out of dictionary key) even though the key IS in the dictionary

    - by ignorantslut
    I'm getting a KeyError for an out of dictionary key, even though I know the key IS in fact in the dictionary. Any ideas as to what might be causing this? print G.keys() returns the following: ['24', '25', '20', '21', '22', '23', '1', '3', '2', '5', '4', '7', '6', '9', '8', '11', '10', '13', '12', '15', '14', '17', '16', '19', '18'] but when I try to access a value in the dictionary on the next line of code... for w in G[v]: #note that in this example, v = 17 I get the following error message: KeyError: 17 Any help, tips, or advice are all appreciated. Thanks.

    Read the article

  • Problems with Threading in Python 2.5, KeyError: 51, Help debugging?

    - by vignesh-k
    I have a python script which runs a particular script large number of times (for monte carlo purpose) and the way I have scripted it is that, I queue up the script the desired number of times it should be run then I spawn threads and each thread runs the script once and again when its done. Once the script in a particular thread is finished, the output is written to a file by accessing a lock (so my guess was that only one thread accesses the lock at a given time). Once the lock is released by one thread, the next thread accesses it and adds its output to the previously written file and rewrites it. I am not facing a problem when the number of iterations is small like 10 or 20 but when its large like 50 or 150, python returns a KeyError: 51 telling me element doesn't exist and the error it points out to is within the lock which puzzles me since only one thread should access the lock at once and I do not expect an error. This is the class I use: class errorclass(threading.Thread): def __init__(self, queue): self.__queue=queue threading.Thread.__init__(self) def run(self): while 1: item = self.__queue.get() if item is None: break result = myfunction() lock = threading.RLock() lock.acquire() ADD entries from current thread to entries in file and REWRITE FILE lock.release() queue = Queue.Queue() for i in range(threads): errorclass(queue).start() for i in range(desired iterations): queue.put(i) for i in range(threads): queue.put(None) Python returns with KeyError: 51 for large number of desired iterations during the adding/write file operation after lock access, I am wondering if this is the correct way to use the lock since every thread has a lock operation rather than every thread accessing a shared lock? What would be the way to rectify this?

    Read the article

  • Common Pitfalls in Python

    - by Anurag Uniyal
    Today I was bitten again by "Mutable default arguments" after many years. I usually don't use mutable default arguments unless needed but I think with time I forgot about that, and today in the application I added tocElements=[] in a pdf generation function's argument list and now 'Table of Content' gets longer and longer after each invocation of "generate pdf" :) My question is what other things should I add to my list of things to MUST avoid? Mutable default arguments Import modules always same way e.g. from y import x and import x are different things, they are treated as different modules. Do not use range in place of lists because range() will become an iterator anyway, the following will fail: myIndexList = [0,1,3] isListSorted = myIndexList == range(3) # will fail in 3.0 isListSorted = myIndexList == list(range(3)) # will not same thing can be mistakenly done with xrange: `myIndexList == xrange(3)`. Catching multiple exceptions try: raise KeyError("hmm bug") except KeyError,TypeError: print TypeError It prints "hmm bug", though it is not a bug, it looks like we are catching exceptions of type KeyError,TypeError but instead we are catching KeyError only as variable TypeError, use this instead: try: raise KeyError("hmm bug") except (KeyError,TypeError): print TypeError

    Read the article

  • Python - Things one MUST avoid

    - by Anurag Uniyal
    Today I was bitten again by "Mutable default arguments" after many years. I usually don't use mutable default arguments unless needed but I think with time I forgot about that, and today in the application I added tocElements=[] in a pdf generation function's argument list and now 'Table of Content' gets longer and longer after each invocation of "generate pdf" :) My question is what other things should I add to my list of things to MUST avoid? 1 Mutable default arguments 2 import modules always same way e.g. 'from y import x' and 'import x' are totally different things actually they are treated as different modules see http://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path 3 Do not use range in place of lists because range() will become an iterator anyway, so things like this will fail, so wrap it by list myIndexList = [0,1,3] isListSorted = myIndexList == range(3) # will fail in 3.0 isListSorted = myIndexList == list(range(3)) # will not same thing can be mistakenly done with xrange e.g myIndexList == xrange(3). 4 Catching multiple exceptions try: raise KeyError("hmm bug") except KeyError,TypeError: print TypeError It prints "hmm bug", though it is not a bug, it looks like we are catching exceptions of type KeyError,TypeError but instead we are catching KeyError only as variable TypeError, instead use try: raise KeyError("hmm bug") except (KeyError,TypeError): print TypeError

    Read the article

  • Compound dictionary keys

    - by John Keyes
    I have a particular case where using compound dictionary keys would make a task easier. I have a working solution, but feel it is inelegant. How would you do it? context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['[email protected]', '[email protected]'], 'domain.name': 'virtucon.com' } def getitem(key, context): if hasattr(key, 'upper') and key in context: return context[key] keys = key if hasattr(key, 'pop') else key.split('.') k = keys.pop(0) if keys: try: return getitem(keys, context[k]) except KeyError, e: raise KeyError(key) if hasattr(context, 'count'): k = int(k) return context[k] if __name__ == "__main__": print getitem('database', context) print getitem('database.port', context) print getitem('database.users.0', context) print getitem('admins', context) print getitem('domain.name', context) try: getitem('database.nosuchkey', context) except KeyError, e: print "Error:", e Thanks.

    Read the article

  • Hide fields in Django admin

    - by jwesonga
    I'm tying to hide my slug fields in the admin by setting editable=False but every time I do that I get the following error: KeyError at /admin/website/program/6/ Key 'slug' not found in Form Request Method: GET Request URL: http://localhost:8000/admin/website/program/6/ Exception Type: KeyError Exception Value: Key 'slug' not found in Form Exception Location: c:\Python26\lib\site-packages\django\forms\forms.py in __getitem__, line 105 Python Executable: c:\Python26\python.exe Python Version: 2.6.4 Any idea why this is happening

    Read the article

  • How to implement Priority Queues in Python?

    - by dragosrsupercool
    Sorry for such a silly question but Python docs are confusing.. . Link 1: Queue Implementation http://docs.python.org/library/queue.html It says thats Queue has a contruct for priority queue. But I could not find how to implement it. class Queue.PriorityQueue(maxsize=0) Link 2: Heap Implementation http://docs.python.org/library/heapq.html Here they says that we can implement priority queues indirectly using heapq pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = '<removed-task>' # placeholder for a removed task counter = itertools.count() # unique sequence count def add_task(task, priority=0): 'Add a new task or update the priority of an existing task' if task in entry_finder: remove_task(task) count = next(counter) entry = [priority, count, task] entry_finder[task] = entry heappush(pq, entry) def remove_task(task): 'Mark an existing task as REMOVED. Raise KeyError if not found.' entry = entry_finder.pop(task) entry[-1] = REMOVED def pop_task(): 'Remove and return the lowest priority task. Raise KeyError if empty.' while pq: priority, count, task = heappop(pq) if task is not REMOVED: del entry_finder[task] return task raise KeyError('pop from an empty priority queue' Which is the most efficient priority queue implementation in python? And how to implement it?

    Read the article

  • How would I write the following applescript in Obj-C AppScript? ASTranslate was of no help =(

    - by demonslayer319
    The translation tool isn't able to translate this working code. I copied it out of a working script. set pathToTemp to (POSIX path of ((path to desktop) as string)) -- change jpg to pict tell application "Image Events" try launch set albumArt to open file (pathToTemp & "albumart.jpg") save albumArt as PICT in file (pathToTemp & "albumart.pict") --the first 512 bytes are the PICT header, so it reads from byte 513 --this is to allow the image to be added to an iTunes track later. set albumArt to (read file (pathToTemp & "albumart.pict") from 513 as picture) close end try end tell The code is taking a jpg image, converting it to a PICT file, and then reading the file minus the header (the first 512 bytes). Later in the script, albumArt will be added to an iTunes track. I tried translating the code (minus the comments), but ASTranslate froze for a good 2 minutes before giving me this: Untranslated event 'earsffdr' #import "IEGlue/IEGlue.h" IEApplication *imageEvents = [IEApplication applicationWithName: @"Image Events"]; IELaunchCommand *cmd = [[imageEvents launch] ignoreReply]; id result = [cmd send]; #import "IEGlue/IEGlue.h" IEApplication *imageEvents = [IEApplication applicationWithName: @"Image Events"]; IEReference *ref = [[imageEvents files] byName: @"/Users/Doom/Desktop/albumart.jpg"]; id result = [[ref open] send]; #import "IEGlue/IEGlue.h" IEApplication *imageEvents = [IEApplication applicationWithName: @"Image Events"]; IEReference *ref = [[imageEvents images] byName: @"albumart.jpg"]; IESaveCommand *cmd = [[[ref save] in: [[imageEvents files] byName: @"/Users/Doom/Desktop/albumart.pict"]] as: [IEConstant PICT]]; id result = [cmd send]; 'crdwrread' Traceback (most recent call last): File "objcrenderer.pyc", line 283, in renderCommand KeyError: 'crdwrread' 'cascrgdut' Traceback (most recent call last): File "objcrenderer.pyc", line 283, in renderCommand KeyError: 'cascrgdut' 'crdwrread' Traceback (most recent call last): File "objcrenderer.pyc", line 283, in renderCommand KeyError: 'crdwrread' Untranslated event 'rdwrread' OK I have no clue how to make sense of this. Thanks for any and all help!

    Read the article

  • Simple App Engine Sessions Implementation

    - by raz0r
    Here is a very basic class for handling sessions on App Engine: """Lightweight implementation of cookie-based sessions for Google App Engine. Classes: Session """ import os import random import Cookie from google.appengine.api import memcache _COOKIE_NAME = 'app-sid' _COOKIE_PATH = '/' _SESSION_EXPIRE_TIME = 180 * 60 class Session(object): """Cookie-based session implementation using Memcached.""" def __init__(self): self.sid = None self.key = None self.session = None cookie_str = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(cookie_str) if self.cookie.get(_COOKIE_NAME): self.sid = self.cookie[_COOKIE_NAME].value self.key = 'session-' + self.sid self.session = memcache.get(self.key) if self.session: self._update_memcache() else: self.sid = str(random.random())[5:] + str(random.random())[5:] self.key = 'session-' + self.sid self.session = dict() memcache.add(self.key, self.session, _SESSION_EXPIRE_TIME) self.cookie[_COOKIE_NAME] = self.sid self.cookie[_COOKIE_NAME]['path'] = _COOKIE_PATH print self.cookie def __len__(self): return len(self.session) def __getitem__(self, key): if key in self.session: return self.session[key] raise KeyError(str(key)) def __setitem__(self, key, value): self.session[key] = value self._update_memcache() def __delitem__(self, key): if key in self.session: del self.session[key] self._update_memcache() return None raise KeyError(str(key)) def __contains__(self, item): try: i = self.__getitem__(item) except KeyError: return False return True def _update_memcache(self): memcache.replace(self.key, self.session, _SESSION_EXPIRE_TIME) I would like some advices on how to improve the code for better security. Note: In the production version it will also save a copy of the session in the datastore. Note': I know there are much more complete implementations available online though I would like to learn more about this subject so please don't answer the question with "use that" or "use the other" library.

    Read the article

  • How do I compile a Wikipedia lens and install?

    - by user49523
    I read a tutorial about how to compile and install a Wikipedia lens, but it didn't work. The tutorial sounds easy - i just copied and pasted to the file that was suppose to edit. I have tried some times and here are 2 edits edit 1: import logging import optparse import gettext from gettext import gettext as _ gettext.textdomain('wikipedia') from singlet.lens import SingleScopeLens, IconViewCategory, ListViewCategory from wikipedia import wikipediaconfig import urllib2 import simplejson class WikipediaLens(SingleScopeLens): wiki = "http://en.wikipedia.org" def wikipedia_query(self,search): try: search = search.replace(" ", "|") url = ("%s/w/api.php?action=opensearch&limit=25&format=json&search=%s" % (self.wiki, search)) results = simplejson.loads(urllib2.urlopen(url).read()) print "Searching Wikipedia" return results[1] except (IOError, KeyError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError): print "Error : Unable to search Wikipedia" return [] class Meta: name = 'Wikipedia' description = 'Wikipedia Lens' search_hint = 'Search Wikipedia' icon = 'wikipedia.svg' search_on_blank=True # TODO: Add your categories articles_category = ListViewCategory("Articles", "dialog-information-symbolic") def search(self, search, results): for article in self.wikipedia_query(search): results.append("%s/wiki/%s" % (self.wiki, article), "http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png", self.articles_category, "text/html", article, "Wikipedia Article", "%s/wiki/%s" % (self.wiki, article)) pass edit 2: import urllib2 import simplejson import logging import optparse import gettext from gettext import gettext as _ gettext.textdomain('wikipediaa') from singlet.lens import SingleScopeLens, IconViewCategory, ListViewCategory from wikipediaa import wikipediaaconfig class WikipediaaLens(SingleScopeLens): wiki = "http://en.wikipedia.org" def wikipedia_query(self,search): try: search = search.replace(" ", "|") url = ("%s/w/api.php?action=opensearch&limit=25&format=json&search=%s" % (self.wiki, search)) results = simplejson.loads(urllib2.urlopen(url).read()) print "Searching Wikipedia" return results[1] except (IOError, KeyError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError): print "Error : Unable to search Wikipedia" return [] def search(self, search, results): for article in self.wikipedia_query(search): results.append("%s/wiki/%s" % (self.wiki, article), "http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png", self.articles_category, "text/html", article, "Wikipedia Article", "%s/wiki/%s" % (self.wiki, article)) pass class Meta: name = 'Wikipedia' description = 'Wikipedia Lens' search_hint = 'Search Wikipedia' icon = 'wikipedia.svg' search_on_blank=True # TODO: Add your categories articles_category = ListViewCategory("Articles", "dialog-information-symbolic") def search(self, search, results): # TODO: Add your search results results.append('https://wiki.ubuntu.com/Unity/Lenses/Singlet', 'ubuntu-logo', self.example_category, "text/html", 'Learn More', 'Find out how to write your Unity Lens', 'https://wiki.ubuntu.com/Unity/Lenses/Singlet') pass so .. what can i change in the edit ? (if anybody give me the entire edit file edited i will appreciate)

    Read the article

  • try...else...except syntax error

    - by iform
    I can't understand this... Cannot get this code to run and I've no idea why it is a syntax error. try: newT.read() #existingArtist = newT['Exif.Image.Artist'].value #existingKeywords = newT['Xmp.dc.subject'].value except KeyError: print "KeyError" else: #Program will NOT remove existing values newT.read() if existingArtist != "" : newT['Exif.Image.Artist'] = artistString print existingKeywords keywords = os.path.normpath(relativePath).split(os.sep) print keywords newT['Xmp.dc.subject'] = existingKeywords + keywords newT.write() except: print "Cannot write tags to ",filePath Syntax error occurs on the last "except:". Again...I have no idea why python is throwing a syntax error (spent ~3hrs on this problem).

    Read the article

  • Custom login in Django

    - by alpgs
    Django newbie here. I wrote simplified login form which takes email and password. It works great if both email and password are supplied, but if either is missing i get KeyError exception. According to django documentation this should never happen: By default, each Field class assumes the value is required, so if you pass an empty value -- either None or the empty string ("") -- then clean() will raise a ValidationError exception I tried to write my own validators for fields (clean_email and clean_password), but it doesn't work (ie I get KeyError exception). What am I doing wrong? class LoginForm(forms.Form): email = forms.EmailField(label=_(u'Your email')) password = forms.CharField(widget=forms.PasswordInput, label=_(u'Password')) def clean_email(self): data = self.cleaned_data['email'] if not data: raise forms.ValidationError(_("Please enter email")) return data def clean_password(self): data = self.cleaned_data['password'] if not data: raise forms.ValidationError(_("Please enter your password")) return data def clean(self): try: username = User.objects.get(email__iexact=self.cleaned_data['email']).username except User.DoesNotExist: raise forms.ValidationError(_("No such email registered")) password = self.cleaned_data['password'] self.user = auth.authenticate(username=username, password=password) if self.user is None or not self.user.is_active: raise forms.ValidationError(_("Email or password is incorrect")) return self.cleaned_data

    Read the article

  • python: problem with dictionary get method default value

    - by goutham
    I'm having a new problem here .. CODE 1: try: urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D.get(val['name']))) except KeyError: print "expected parameter not provided - "+val["name"]+" is missing" exit(0) CODE 2: try: urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D[val['name']])) except KeyError: print "expected parameter not provided - "+val["name"]+" is missing" exit(0) see the diffrence in serverInfo_D[val['name']] & serverInfo_D.get(val['name']) code 2 fails but code 1 works the data serverInfo_D:{'user': 'usr', 'pass': 'pass'} data: {'par1': 9995, 'extraparam1': 22} val: {'par1','user','pass','extraparam1'} exception are raised for for data dict .. and all code in for loop which iterates over val

    Read the article

  • String formatting [str.format()] with a dictionary having a key which is a str() of a number

    - by decimus phostle
    Python neophyte here. I was wondering if someone could help with the KeyError I am getting when using a dictionary for string interpolation in str.format. dictionary = {'key1': 'val1', '1': 'val2'} string1 = 'Interpolating {0[key1]}'.format(dictionary) print string1 The above works fine and yields: Interpolating val1 However doing the following: dictionary = {'key1': 'val1', '1': 'val2'} string2 = 'Interpolating {0[1]}'.format(dictionary) print string2 results in: Traceback (most recent call last): File "test.py", line 3, in <module> string2 = 'Interpolating {0[1]}'.format(dictionary) KeyError: 1L So the problem seems to be in the interpretation of the numeric key as a list index, IMHO. Is there any way to work around this? (i.e. convey that this is instead a dictionary key) TIA and apologies if this question has been asked before(couldn't find anything relevant with my search-fu).

    Read the article

  • Trying to grab just absolute links from a webpage using BeautifulSoup

    - by Kevin
    I am reading the contents of a webpage using BeautifulSoup. What I want is to just grab the <a href> that start with http://. I know in beautifulsoup you can search by the attributes. I guess I am just having a syntax issue. I would imagine it would go something like. page = urllib2.urlopen("http://www.linkpages.com") soup = BeautifulSoup(page) for link in soup.findAll('a'): if link['href'].startswith('http://'): print links But that returns: Traceback (most recent call last): File "<stdin>", line 2, in <module> File "C:\Python26\lib\BeautifulSoup.py", line 598, in __getitem__ return self._getAttrMap()[key] KeyError: 'href' Any ideas? Thanks in advance. EDIT This isn't for any site in particular. The script gets the url from the user. So internal link targets would be an issue, that's also why I only want the <'a'> from the pages. If I turn it towards www.reddit.com, it parses the beginning links and it gets to this: <a href="http://www.reddit.com/top/">top</a> <a href="http://www.reddit.com/saved/">saved</a> Traceback (most recent call last): File "<stdin>", line 2, in <module> File "C:\Python26\lib\BeautifulSoup.py", line 598, in __getitem__ return self._getAttrMap()[key] KeyError: 'href'

    Read the article

  • Python, dictionaries, and chi-square contingency table

    - by rohanbk
    I have a file which contains several lines in the following format (word, time that the word occurred in, and frequency of documents containing the given word within the given instance in time): #inputfile <word, time, frequency> apple, 1, 3 banana, 1, 2 apple, 2, 1 banana, 2, 4 orange, 3, 1 I have Python class below that I used to create 2-D dictionaries to store the above file using as the key, and frequency as the value: class Ddict(dict): ''' 2D dictionary class ''' def __init__(self, default=None): self.default = default def __getitem__(self, key): if not self.has_key(key): self[key] = self.default() return dict.__getitem__(self, key) wordtime=Ddict(dict) # Store each inputfile entry with a <word,time> key timeword=Ddict(dict) # Store each inputfile entry with a <time,word> key # Loop over every line of the inputfile for line in open('inputfile'): word,time,count=line.split(',') # If <word,time> already a key, increment count try: wordtime[word][time]+=count # Otherwise, create the key except KeyError: wordtime[word][time]=count # If <time,word> already a key, increment count try: timeword[time][word]+=count # Otherwise, create the key except KeyError: timeword[time][word]=count The question that I have pertains to calculating certain things while iterating over the entries in this 2D dictionary. For each word 'w' at each time 't', calculate: The number of documents with word 'w' within time 't'. (a) The number of documents without word 'w' within time 't'. (b) The number of documents with word 'w' outside time 't'. (c) The number of documents without word 'w' outside time 't'. (d) Each of the items above represents one of the cells of a chi-square contingency table for each word and time. Can all of these be calculated within a single loop or do they need to be done one at a time? Ideally, I would like the output to be what's below, where a,b,c,d are all the items calculated above: print "%s, %s, %s, %s" %(a,b,c,d)

    Read the article

1 2 3  | Next Page >