Search Results

Search found 97 results on 4 pages for 'pil'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • Python Threading

    - by anteater7171
    I'm trying to make a simple program that continually displays and updates a label that displays the CPU usage, while having other unrelated things going on. I've done enough research to know that threading is likely going to be involved. However, I'm having trouble applying what I've seen in simple examples of threading to what I'm trying to do. What I currently have going: import Tkinter import psutil,time from PIL import Image, ImageTk class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.labelVariable = Tkinter.StringVar() self.label = Tkinter.Label(self,textvariable=self.labelVariable) self.label.pack() self.button = Tkinter.Button(self,text='button',command=self.A) self.button.pack() def A (self): G = str(round(psutil.cpu_percent(), 1)) + '%' print G self.labelVariable.set(G) def B (self): print "hello" if __name__ == "__main__": app = simpleapp_tk(None) app.mainloop() In the above code I'm basically trying to get command A continually running, while allowing command B to be done when the users presses the button.

    Read the article

  • Google App Engine says "Must authenticate first." while trying to deploy any app

    - by Oleksandr Bolotov
    Google App Engine says "Must authenticate first." while trying to deploy any app: me@myhost /opt/google_appengine $ python appcfg.py update ~/sda2/workspace/lyapapam/ Application: lyapapam; version: 1. Server: appengine.google.com. Scanning files on local disk. Scanned 500 files. Scanned 1000 files. Initiating update. Email: <my_email_was_here>@gmail.com Password for <my_email_was_here>@gmail.com: Error 401: --- begin server output --- Must authenticate first. --- end server output --- We are getting this message with any appliation and under any developer account avialable to us That's what we have installed: App Engine SDK - 1.3.2 PIL - 1.1.7 Python - 2.5.5 pip - 0.6.3 ssl - 1.15 wsgiref - 0.1.2 How can I fix it? Is it well known problem?

    Read the article

  • python convert 12 bit image encoded in a string to 8 bit png

    - by ks
    I have a string that is read from a usb apogee camera that is a 12-bit grayscale image with the 12-bits each occupying the lowest 12 bits of 16-bits words. I want to create a 8-bit png from this string by ignoring the lowest 4 bits. I can convert it to a 16-bit image where the highest 4 bits are always zero using PIL with import Image imageStr is the image string imageSize is the image size img=Image.fromstring("I", imageSize, imageStr, "raw", "I;16", 0,1) img.save("MyImage.png", "PNG") Anyway I can do something similar to create a 8-bit image without completely unpacking the string doing arithmetic and making a new string?

    Read the article

  • sharing a folder between linux and windows over the internet

    - by valya
    Hello Currently my job is to make websites with Django. I use many things like virtualenv, PIL, etc. The problem is, I can't stand Linux on my desktop. I like it on servers, It's greate to use it over the SSH. But for desktop? No way. But for the development Linux is quite essential. Of course almost everything is ported to Windows, but it's not as simple to use as in Linux. For example, Windows shell is awful in comparison with Linux. So I've tried Cygwin, but it's too damn slow. Every time django dev server reloads, it tooks almost 20-30 seconds. In comparison, then using "native" python on Windows or Linux, it reloads instantly. Even worse, Cygwin makes all my system very slow. I've been thinking about it and have thought up a way to go. I can share a folder with my application with some Linux box. The devserver and everything will run on that box, while I'll be happy editing files and running the browser on my Windows 7. SSH shell is much quickier and handy than Cygwin. Currently there are no Linux boxes in my home network (except for my android phone :) but I have several VDS boxes with Debian. So, how do I share a Windows folder with VDS box? I can't rely on my desktop IP but I can rely on the VDS's one. I need sharing to be as quick as possible (well, 2-3 seconds ping is OK) and "native" for both systems, so I could use a folder like a normal folder in both Windows and Linux.

    Read the article

  • Faking a Linux environment without chroot

    - by Pascal
    For a university project I want to test a C++11 program on a 32-core machine. Unfortunately the machine has Ubuntu 12.04 with GCC 4.6 installed (we need GCC 4.7 because of some C++11 threading features). In such an environment I would normally run a chroot with a custom linux (say a debootstrap with Ubuntu 12.10). Since we don't get root access on the machine we can't use chroot. So far I have prepared a run-time environment using debootstrap for our code, I compiled it in the debootstrap environemnt. Then copied it onto the server (using rsync). In order to run our C++ code I set the LD_LIBRARY_PATH to export LD_LIBRARY_PATH=~/debootstrap/usr/lib/:~/debootstrap/lib64/:~/debootstrap/usr/lib/x86_64-linux-gnu/:~/debootstrap/lib/x86_64-linux-gnu/:$LD_LIBRARY_PATH and so far our code seems to run. I'm however stuck with our python code. It doesn't seem to be sufficient to set the paths manually. export PYTHONPATH=~/debootstrap/usr/lib/python2.7/dist-packages:~/debootstrap/usr/lib/python2.7:~/debootstrap/usr/lib/python2.7/plat-linux2:~/debootstrap/usr/lib/python2.7/lib-tk:~/debootstrap/usr/lib/python2.7/lib-dynload:~/debootstrap/usr/local/lib/python2.7/dist-packages:~/debootstrap/usr/lib/pymodules/python2.7:~/debootstrap/usr/lib/python2.7/dist-packages/PIL:~/debootstrap/usr/lib/python2.7/dist-packages/gtk-2.0:~/debootstrap/usr/lib/python2.7 Executing our script results in ImportError: No module named _path Is there an easier way to accomplish a "fake"-chroot than just overriding and creating environment variables? Note I need python since we created a custom C++-Python module in order to run our tests. Maybe I should create two questions from this.

    Read the article

  • Fastest image iteration in Python

    - by Greg
    I am creating a simple green screen app with Python 2.7.4 but am getting quite slow results. I am currently using PIL 1.1.7 to load and iterate the images and saw huge speed-ups changing from the old getpixel() to the newer load() and pixel access object indexing. However the following loop still takes around 2.5 seconds to run for an image of around 720p resolution: def colorclose(Cb_p, Cr_p, Cb_key, Cr_key, tola, tolb): temp = math.sqrt((Cb_key-Cb_p)**2+(Cr_key-Cr_p)**2) if temp < tola: return 0.0 else: if temp < tolb: return (temp-tola)/(tolb-tola) else: return 1.0 .... for x in range(width): for y in range(height): Y, cb, cr = fg_cbcr_list[x, y] mask = colorclose(cb, cr, cb_key, cr_key, tola, tolb) mask = 1 - mask bgr, bgg, bgb = bg_list[x,y] fgr, fgg, fgb = fg_list[x,y] pixels[x,y] = ( (int)(fgr - mask*key_color[0] + mask*bgr), (int)(fgg - mask*key_color[1] + mask*bgg), (int)(fgb - mask*key_color[2] + mask*bgb)) Am I doing anything hugely inefficient here which makes it run so slow? I have seen similar, simpler examples where the loop is replaced by a boolean matrix for instance, but for this case I can't see a way to replace the loop. The pixels[x,y] assignment seems to take the most amount of time but not knowing Python very well I am unsure of a more efficient way to do this. Any help would be appreciated.

    Read the article

  • Using Sendkeys in python to press {F12} results in other keys pressed?

    - by ThantiK
    import time from ctypes import * import win32gui import win32com.client as comclt X = 119 Y = 53 def PILColorToRGB(pil_color): """ convert a PIL-compatible integer into an (r, g, b) tuple """ hexstr = '%06x' % pil_color # reverse byte order r, g, b = hexstr[4:], hexstr[2:4], hexstr[:2] r, g, b = [int(n, 16) for n in (r, g, b)] return (r, g, b) wsh = comclt.Dispatch("WScript.Shell") w = win32gui user = windll.LoadLibrary("c:\\windows\\system32\\user32.dll") h = user.GetDC(0) gdi = windll.LoadLibrary("c:\\windows\\system32\\gdi32.dll") while True: FG = w.GetWindowText(w.GetForegroundWindow()) #FG = Foreground window title. if FG == "World of Warcraft": rgb = (PILColorToRGB(gdi.GetPixel(h,X,Y))) #X, Y time.sleep(0.333) #don't check too often. if (rgb[0] >= 130): #While Pixel (X, Y) is Red... #print "%d %d %d" % (rgb[0], rgb[1], rgb[2]) #Debug wsh.SendKeys("{F12}") #Send a key. time.sleep(0.7) #Add some extra down-time if we send the key. else: time.sleep(5) Basically all this code does is read a pixel on the screen, and send a key (F12) if the pixel is red. But when using this code I regularly get some phantom key-code being pressed. The application I'm using this on is obviously world of warcraft, and I have checked that all keybinds are standard keybinds. However randomly it seems I get either an up arrow, or a w pressed, which moves my character forward whenever this code executes (F12 is bound to a macro, unbound from any movement. If I press f12 with a hardware event, it does not exhibit this behavior. What in the world could be going on here?

    Read the article

  • Resizing image algorithm in python

    - by hippocampus
    So, I'm learning my self python by this tutorial and I'm stuck with exercise number 13 which says: Write a function to uniformly shrink or enlarge an image. Your function should take an image along with a scaling factor. To shrink the image the scale factor should be between 0 and 1 to enlarge the image the scaling factor should be greater than 1. This is not meant as a question about PIL, but to ask which algorithm to use so I can code it myself. I've found some similar questions like this, but I dunno how to translate this into python. Any help would be appreciated. I've come to this: import image win = image.ImageWin() img = image.Image("cy.png") factor = 2 W = img.getWidth() H = img.getHeight() newW = int(W*factor) newH = int(H*factor) newImage = image.EmptyImage(newW, newH) for col in range(newW): for row in range(newH): p = img.getPixel(col,row) newImage.setPixel(col*factor,row*factor,p) newImage.draw(win) win.exitonclick() I should do this in a function, but this doesn't matter right now. Arguments for function would be (image, factor). You can try it on OP tutorial in ActiveCode. It makes a stretched image with empty columns :.

    Read the article

  • sorl-thumbnail unit tests fail by 1 pixel (!)

    - by stevejalim
    Hi I'm using sorl-thumbnail in a Django 1.2 (currently 1.2 RC) project and getting a surprising failure of four of sorl's built-in unit tests. Essentially, the resized images are all 1px shorter than the unit tests expect them to be. See below for details I'm developing on OSX 10.5.8 (not Snow Leopard) with Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) and PIL 1.1.6. Any thoughts what might be up? Cheers Steve ====================================================================== FAIL: test_extension (sorl.thumbnail.tests.fields.FieldTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/fields.py", line 66, in test_extension self.verify_thumbnail((50, 37), thumb, expected_filename) File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/base.py", line 92, in verify_thumbnail self.assertEqual(image.size, expected_size) AssertionError: (50, 38) != (50, 37) ====================================================================== FAIL: test_thumbnail (sorl.thumbnail.tests.fields.ImageWithThumbnailsFieldTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/fields.py", line 111, in test_thumbnail self.verify_thumbnail((50, 37), thumb, expected_filename) File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/base.py", line 92, in verify_thumbnail self.assertEqual(image.size, expected_size) AssertionError: (50, 38) != (50, 37) ====================================================================== FAIL: testTag (sorl.thumbnail.tests.templatetags.ThumbnailTagTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/templatetags.py", line 118, in testTag self.verify_thumbnail((90, 67), expected_filename=expected_fn) File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/base.py", line 92, in verify_thumbnail self.assertEqual(image.size, expected_size) AssertionError: (90, 68) != (90, 67)

    Read the article

  • Python optimization problem?

    - by user342079
    Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter part): import math, array import numpy as np from PIL import Image size = (800,800) width, height = size s1x = width * 1./8 s1y = height * 1./8 s2x = width * 7./8 s2y = height * 7./8 r,g,b = (255,255,255) arr = np.zeros((width,height,3)) hy = math.hypot print 'computing distances (%s by %s)'%size, for i in xrange(width): if i%(width/10)==0: print i, if i%20==0: print '.', for j in xrange(height): d1 = hy(i-s1x,j-s1y) d2 = hy(i-s2x,j-s2y) arr[i][j] = abs(d1-d2) print '' arr2 = np.zeros((width,height,3),dtype="uint8") for ld in [200,116,100,84,68,52,36,20,8,4,2]: print 'now computing image for ld = '+str(ld) arr2 *= 0 arr2 += abs(arr%ld-ld/2)*(r,g,b)/(ld/2) print 'saving image...' ar2img = Image.fromarray(arr2) ar2img.save('ld'+str(ld).rjust(4,'0')+'.png') print 'saved as ld'+str(ld).rjust(4,'0')+'.png' I have managed to optimize most of it, but there's still a huge performance gap in the part with the 2 for-s, and I can't seem to think of a way to bypass that using common array operations... I'm open to suggestions :D

    Read the article

  • Pymedia video encoding failed

    - by user1474837
    I am using Python 2.5 with Windows XP. I am trying to make a list of pygame images into a video file using this function. I found the function on the internet and edited it. It worked at first, than it stopped working. This is what it printed out: Making video... Formating 114 Frames... starting loop making encoder Frame 1 process 1 Frame 1 process 2 Frame 1 process 2.5 This is the error: Traceback (most recent call last): File "ScreenCapture.py", line 202, in <module> makeVideoUpdated(record_files, video_file) File "ScreenCapture.py", line 151, in makeVideoUpdated d = enc.encode(da) pymedia.video.vcodec.VCodecError: Failed to encode frame( error code is 0 ) This is my code: def makeVideoUpdated(files, outFile, outCodec='mpeg1video', info1=0.1): fw = open(outFile, 'wb') if (fw == None) : print "Cannot open file " + outFile return if outCodec == 'mpeg1video' : bitrate= 2700000 else: bitrate= 9800000 start = time.time() enc = None frame = 1 print "Formating "+str(len(files))+" Frames..." print "starting loop" for img in files: if enc == None: print "making encoder" params= {'type': 0, 'gop_size': 12, 'frame_rate_base': 125, 'max_b_frames': 90, 'height': img.get_height(), 'width': img.get_width(), 'frame_rate': 90, 'deinterlace': 0, 'bitrate': bitrate, 'id': vcodec.getCodecID(outCodec) } enc = vcodec.Encoder(params) # Create VFrame print "Frame "+str(frame)+" process 1" bmpFrame= vcodec.VFrame(vcodec.formats.PIX_FMT_RGB24, img.get_size(), # Covert image to 24bit RGB (pygame.image.tostring(img, "RGB"), None, None) ) print "Frame "+str(frame)+" process 2" # Convert to YUV, then codec da = bmpFrame.convert(vcodec.formats.PIX_FMT_YUV420P) print "Frame "+str(frame)+" process 2.5" d = enc.encode(da) #THIS IS WHERE IT STOPS print "Frame "+str(frame)+" process 3" fw.write(d.data) print "Frame "+str(frame)+" process 4" frame += 1 print "savng file" fw.close() Could somebody tell me why I have this error and possibly how to fix it? The files argument is a list of pygame images, outFile is a path, outCodec is default, and info1 is not used anymore. UPDATE 1 This is the code I used to make that list of pygame images. from PIL import ImageGrab import time, pygame pygame.init() f = [] #This is the list that contains the images fps = 1 for n in range(1, 100): info = ImageGrab.grab() size = info.size mode = info.mode data = info.tostring() info = pygame.image.fromstring(data, size, mode) f.append(info) time.sleep(fps)

    Read the article

  • Image Gurus: Optimize my Python PNG transparency function

    - by ozone
    I need to replace all the white(ish) pixels in a PNG image with alpha transparency. I'm using Python in AppEngine and so do not have access to libraries like PIL, imagemagick etc. AppEngine does have an image library, but is pitched mainly at image resizing. I found the excellent little pyPNG module and managed to knock up a little function that does what I need: make_transparent.py pseudo-code for the main loop would be something like: for each pixel: if pixel looks "quite white": set pixel values to transparent otherwise: keep existing pixel values and (assuming 8bit values) "quite white" would be: where each r,g,b value is greater than "240" AND each r,g,b value is within "20" of each other This is the first time I've worked with raw pixel data in this way, and although works, it also performs extremely poorly. It seems like there must be a more efficient way of processing the data without iterating over each pixel in this manner? (Matrices?) I was hoping someone with more experience in dealing with these things might be able to point out some of my more obvious mistakes/improvements in my algorithm. Thanks!

    Read the article

  • Could not import Django settings into Google App Engine

    - by gkelsall
    Hello all you Google App Engine experts, I have used Django a little before but am new to Google App Engine and am trying to use it's development web server with Django for the first time. I don't know if this is relevent but I previously had Django 1.1 and Python 2.6 on my Windows XP and even though I have uninstalled Python 2.6 there is still a folder and entries in the registry. I have followed the instructions from Google but when I browse to the GAE developemnt web server it cannot find my settings (details below). Any hints gratefully received. Regards Geoff C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo %PATH% C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS \system32\WindowsPowerShell\v1.0;;C:\Python25;C:\Python25\Lib\site- packages\django\bin;C:\Documents and Settings\GeoffK\My Documents\ing \ingsite;C:\Program Files\Google\google_appengine\ C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>echo %PYTHONPATH% C:\Documents and Settings\GeoffK\My Documents\ing\ingsite C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>C:\Documents and Settings\GeoffK\My Documents\ing\ingsite>dev_appserver.py -- debug_imports ingiliz\ INFO 2009-08-04 07:29:45,328 appengine_rpc.py:157] Server: appengine.google. com INFO 2009-08-04 07:29:45,358 appcfg.py:322] Checking for updates to the SDK. INFO 2009-08-04 07:29:45,578 appcfg.py:336] The SDK is up to date. WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not read data store data from c:\docume~1\geoffk\locals~1\temp \dev_appserver.datastore WARNING 2009-08-04 07:29:45,578 datastore_file_stub.py:404] Could not read data store data from c:\docume~1\geoffk\locals~1\temp \dev_appserver.datastore.history WARNING 2009-08-04 07:29:45,608 dev_appserver.py:3296] Could not initialize ima ges API; you are likely missing the Python "PIL" module. ImportError: No module named _imaging INFO 2009-08-04 07:29:45,625 dev_appserver_main.py:465] Running application ingiliz on port 8080: http://localhost:8080 ..... Now attempting to browse if need more detail here I can post ..... if not settings.DATABASE_ENGINE: File "C:\Python25\lib\site-packages\django\conf\__init__.py", line 28, in __ge tattr__ self._import_settings() File "C:\Python25\lib\site-packages\django\conf\__init__.py", line 59, in _imp ort_settings self._target = Settings(settings_module) File "C:\Python25\lib\site-packages\django\conf\__init__.py", line 94, in __in it__ raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'settings' (Is it on sys.path? Does it ha ve syntax errors?): No module named settings INFO 2009-08-04 07:31:02,187 dev_appserver.py:2982] "GET / HTTP/ 1.1" 500 -

    Read the article

  • Error after installing Django (supposed PATH or PYTHONPATH "error")

    - by illuminated
    Hi all, I guess this is a PATH/PYTHONPATH error, but my attempts failed so far to make django working. System is Ubuntu 10.04, 64bit: mx:~/webapps$ cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=10.04 DISTRIB_CODENAME=lucid DISTRIB_DESCRIPTION="Ubuntu 10.04 LTS" Python version: 2.6.5: @mx:~/webapps$ python -V Python 2.6.5 When I run django-admin.py, the following happens: mx:~/webapps$ django-admin.py Traceback (most recent call last): File "/usr/local/bin/django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core Similar when I import django in python shell: mx:~/webapps$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named django >>> quit() More details: mx:~/webapps$ python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" /usr/lib/python2.6/dist-packages Within python shell: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.path ['', '/usr/lib/python2.6/dist-packages/django', '/usr/local/lib/python2.6/dist-packages/django/bin', '/usr/local/lib/python2.6/dist-packages/django', '/home/petra/webapps', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/pymodules/python2.6'] django-admin.py can be found here: mx:~/webapps$ locate django-admin.py ~/install/sources/Django-1.2.1/build/lib.linux-i686-2.6/django/bin/django-admin.py ~/install/sources/Django-1.2.1/build/scripts-2.6/django-admin.py ~/install/sources/Django-1.2.1/django/bin/django-admin.py /usr/local/bin/django-admin.py /usr/local/lib/python2.6/dist-packages/django/bin/django-admin.py /usr/local/lib/python2.6/dist-packages/django/bin/django-admin.pyc and in the end this doesn't help: export PYTHONPATH="/usr/lib/python2.6/dist-packages/django:$PYTHONPATH" nor this: export PYTHONPATH="/usr/local/lib/python2.6/dist-packages/django:$PYTHONPATH" How to solve this !? Thanks all in advance! :)

    Read the article

  • How do I print out objects in an array in python?

    - by Jonathan
    I'm writing a code which performs a k-means clustering on a set of data. I'm actually using the code from a book called collective intelligence by O'Reilly. Everything works, but in his code he uses the command line and i want to write everything in notepad++. As a reference his line is >>>kclust=clusters.kcluster(data,k=10) >>>[rownames[r] for r in k[0]] Here is my code: from PIL import Image,ImageDraw def readfile(filename): lines=[line for line in file(filename)] # First line is the column titles colnames=lines[0].strip( ).split('\t')[1:] rownames=[] data=[] for line in lines[1:]: p=line.strip( ).split('\t') # First column in each row is the rowname rownames.append(p[0]) # The data for this row is the remainder of the row data.append([float(x) for x in p[1:]]) return rownames,colnames,data from math import sqrt def pearson(v1,v2): # Simple sums sum1=sum(v1) sum2=sum(v2) # Sums of the squares sum1Sq=sum([pow(v,2) for v in v1]) sum2Sq=sum([pow(v,2) for v in v2]) # Sum of the products pSum=sum([v1[i]*v2[i] for i in range(len(v1))]) # Calculate r (Pearson score) num=pSum-(sum1*sum2/len(v1)) den=sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1))) if den==0: return 0 return 1.0-num/den class bicluster: def __init__(self,vec,left=None,right=None,distance=0.0,id=None): self.left=left self.right=right self.vec=vec self.id=id self.distance=distance def hcluster(rows,distance=pearson): distances={} currentclustid=-1 # Clusters are initially just the rows clust=[bicluster(rows[i],id=i) for i in range(len(rows))] while len(clust)>1: lowestpair=(0,1) closest=distance(clust[0].vec,clust[1].vec) # loop through every pair looking for the smallest distance for i in range(len(clust)): for j in range(i+1,len(clust)): # distances is the cache of distance calculations if (clust[i].id,clust[j].id) not in distances: distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec) #print 'i' #print i #print #print 'j' #print j #print d=distances[(clust[i].id,clust[j].id)] if d<closest: closest=d lowestpair=(i,j) # calculate the average of the two clusters mergevec=[ (clust[lowestpair[0]].vec[i]+clust[lowestpair[1]].vec[i])/2.0 for i in range(len(clust[0].vec))] # create the new cluster newcluster=bicluster(mergevec,left=clust[lowestpair[0]], right=clust[lowestpair[1]], distance=closest,id=currentclustid) # cluster ids that weren't in the original set are negative currentclustid-=1 del clust[lowestpair[1]] del clust[lowestpair[0]] clust.append(newcluster) return clust[0] def kcluster(rows,distance=pearson,k=4): # Determine the minimum and maximum values for each point ranges=[(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))] # Create k randomly placed centroids clusters=[[random.random( )*(ranges[i][1]-ranges[i][0])+ranges[i][0] for i in range(len(rows[0]))] for j in range(k)] lastmatches=None for t in range(100): print 'Iteration %d' % t bestmatches=[[] for i in range(k)] # Find which centroid is the closest for each row for j in range(len(rows)): row=rows[j] bestmatch=0 for i in range(k): d=distance(clusters[i],row) if d<distance(clusters[bestmatch],row): bestmatch=i bestmatches[bestmatch].append(j) # If the results are the same as last time, this is complete if bestmatches==lastmatches: break lastmatches=bestmatches # Move the centroids to the average of their members for i in range(k): avgs=[0.0]*len(rows[0]) if len(bestmatches[i])>0: for rowid in bestmatches[i]: for m in range(len(rows[rowid])): avgs[m]+=rows[rowid][m] for j in range(len(avgs)): avgs[j]/=len(bestmatches[i]) clusters[i]=avgs return bestmatches

    Read the article

  • Django - I got TemplateSyntaxError when I try open the admin page. (http://DOMAIN_NAME/admin)

    - by user140827
    I use grappelly plugin. When I try open the admin page (/admin) I got TemplateSyntaxError. It says 'get_generic_relation_list' is invalid block tag. TemplateSyntaxError at /admin/ Invalid block tag: 'get_generic_relation_list', expected 'endblock' Request Method: GET Request URL: http://DOMAIN_NAME/admin/ Django Version: 1.4 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag: 'get_generic_relation_list', expected 'endblock' Exception Location: /opt/python27/django/1.4/lib/python2.7/site-packages/django/template/base.py in invalid_block_tag, line 320 Python Executable: /opt/python27/django/1.4/bin/python Python Version: 2.7.0 Python Path: ['/home/vhosts/DOMAIN_NAME/httpdocs/media', '/home/vhosts/DOMAIN_NAME/private/new_malinnikov/lib', '/home/vhosts/DOMAIN_NAME/httpdocs/', '/home/vhosts/DOMAIN_NAME/private/new_malinnikov', '/home/vhosts/DOMAIN_NAME/private/new_malinnikov', '/home/vhosts/DOMAIN_NAME/private', '/opt/python27/django/1.4', '/home/vhosts/DOMAIN_NAME/httpdocs', '/opt/python27/django/1.4/lib/python2.7/site-packages/setuptools-0.6c12dev_r88846-py2.7.egg', '/opt/python27/django/1.4/lib/python2.7/site-packages/pip-0.8.1-py2.7.egg', '/opt/python27/django/1.4/lib/python27.zip', '/opt/python27/django/1.4/lib/python2.7', '/opt/python27/django/1.4/lib/python2.7/plat-linux2', '/opt/python27/django/1.4/lib/python2.7/lib-tk', '/opt/python27/django/1.4/lib/python2.7/lib-old', '/opt/python27/django/1.4/lib/python2.7/lib-dynload', '/opt/python27/lib/python2.7', '/opt/python27/lib/python2.7/plat-linux2', '/opt/python27/lib/python2.7/lib-tk', '/opt/python27/django/1.4/lib/python2.7/site-packages', '/opt/python27/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/opt/python27/lib/python2.7/site-packages/flup-1.0.3.dev_20100525-py2.7.egg', '/opt/python27/lib/python2.7/site-packages/virtualenv-1.5.1-py2.7.egg', '/opt/python27/lib/python2.7/site-packages/SQLAlchemy-0.6.4-py2.7.egg', '/opt/python27/lib/python2.7/site-packages/SQLObject-0.14.1-py2.7.egg', '/opt/python27/lib/python2.7/site-packages/FormEncode-1.2.3dev-py2.7.egg', '/opt/python27/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-linux-x86_64.egg', '/opt/python27/lib/python2.7/site-packages/psycopg2-2.2.2-py2.7-linux-x86_64.egg', '/opt/python27/lib/python2.7/site-packages/pysqlite-2.6.0-py2.7-linux-x86_64.egg', '/opt/python27/lib/python2.7/site-packages', '/opt/python27/lib/python2.7/site-packages/PIL'] Server time: ???, 7 ??? 2012 04:19:42 +0700 Error during template rendering In template /home/vhosts/DOMAIN_NAME/httpdocs/templates/grappelli/admin/base.html, error at line 28 Invalid block tag: 'get_generic_relation_list', expected 'endblock' 18 <!--[if lt IE 8]> 19 <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script> 20 <![endif]--> 21 {% block javascripts %} 22 <script type="text/javascript" src="{% admin_media_prefix %}jquery/jquery-1.3.2.min.js"></script> 23 <script type="text/javascript" src="{% admin_media_prefix %}js/admin/Bookmarks.js"></script> 24 <script type="text/javascript"> 25 // Admin URL 26 var ADMIN_URL = "{% get_admin_url %}"; 27 // Generic Relations 28 {% get_generic_relation_list %} 29 // Get Bookmarks 30 $(document).ready(function(){ 31 $.ajax({ 32 type: "GET", 33 url: '{% url grp_bookmark_get %}', 34 data: "path=" + escape(window.location.pathname + window.location.search), 35 dataType: "html", 36 success: function(data){ 37 $('ul#bookmarks').replaceWith(data); 38 }

    Read the article

  • getting Cannot identify image file when trying to create thumbnail in django

    - by Mo J. Mughrabi
    Am trying to create a thumbnail in django, am trying to build a custom class specifically to be used for generating thumbnails. As following from StringIO import StringIO from PIL import Image class Thumbnail(object): source = '' size = (50, 50) output = '' def __init__(self): pass @staticmethod def load(src): self = Thumbnail() self.source = src return self def generate(self, size=(50, 50)): if not isinstance(size, tuple): raise Exception('Thumbnail class: The size parameter must be an instance of a tuple.') self.size = size # resize properties box = self.size factor = 1 fit = True image = Image.open(self.source) # Convert to RGB if necessary if image.mode not in ('L', 'RGB'): image = image.convert('RGB') while image.size[0]/factor > 2*box[0] and image.size[1]*2/factor > 2*box[1]: factor *=2 if factor > 1: image.thumbnail((image.size[0]/factor, image.size[1]/factor), Image.NEAREST) #calculate the cropping box and get the cropped part if fit: x1 = y1 = 0 x2, y2 = image.size wRatio = 1.0 * x2/box[0] hRatio = 1.0 * y2/box[1] if hRatio > wRatio: y1 = int(y2/2-box[1]*wRatio/2) y2 = int(y2/2+box[1]*wRatio/2) else: x1 = int(x2/2-box[0]*hRatio/2) x2 = int(x2/2+box[0]*hRatio/2) image = image.crop((x1,y1,x2,y2)) #Resize the image with best quality algorithm ANTI-ALIAS image.thumbnail(box, Image.ANTIALIAS) # save image to memory temp_handle = StringIO() image.save(temp_handle, 'png') temp_handle.seek(0) self.output = temp_handle return self def get_output(self): return self.output.read() the purpose of the class is so i can use it inside different locations to generate thumbnails on the fly. The class works perfectly, I've tested it directly under a view.. I've implemented the thumbnail class inside the save method of the forms to resize the original images on saving. in my design, I have two fields for thumbnails. I was able to generate one thumbnail, if I try to generate two it crashes and I've been stuck for hours not sure whats the problem. Here is my model class Image(models.Model): article = models.ForeignKey(Article) title = models.CharField(max_length=100, null=True, blank=True) src = models.ImageField(upload_to='publication/image/') r128 = models.ImageField(upload_to='publication/image/128/', blank=True, null=True) r200 = models.ImageField(upload_to='publication/image/200/', blank=True, null=True) uploaded_at = models.DateTimeField(auto_now=True) Here is my forms class ImageForm(models.ModelForm): """ """ class Meta: model = Image fields = ('src',) def save(self, commit=True): instance = super(ImageForm, self).save(commit=True) file = Thumbnail.load(instance.src) instance.r128 = SimpleUploadedFile( instance.src.name, file.generate((128, 128)).get_output(), content_type='image/png' ) instance.r200 = SimpleUploadedFile( instance.src.name, file.generate((200, 200)).get_output(), content_type='image/png' ) if commit: instance.save() return instance the strange part is, when i remove the line which contains instance.r200 in the form save. It works fine, and it does the thumbnail and stores it successfully. Once I add the second thumbnail it fails.. Any ideas what am doing wrong here? Thanks Update: I tried earlier doing the following but I still got the same error class ImageForm(models.ModelForm): """ """ class Meta: model = Image fields = ('src',) def save(self, commit=True): instance = super(ImageForm, self).save(commit=True) instance.r128 = SimpleUploadedFile( instance.src.name, Thumbnail.load(instance.src).generate((128, 128)).get_output(), content_type='image/png' ) instance.r200 = SimpleUploadedFile( instance.src.name, Thumbnail.load(instance.src).generate((200, 200)).get_output(), content_type='image/png' ) if commit: instance.save() return instance

    Read the article

  • sys.path() and PYTHONPATH issues

    - by Justin
    I've been learning Python, I'm working in 2.7.3, and I'm trying to understand import statements. The documentation says that when you attempt to import a module, the interpreter will first search for one of the built-in modules. What is meant by a built-in module? Then, the documentation says that the interpreter searches in the directories listed by sys.path, and that sys.path is initialized from these sources: the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). the installation-dependent default. Here is a sample output of a sys.path command from my computer using python in command-line mode: (I deleted a few so that it wouldn't be huge) ['', '/usr/lib/python2.7', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] Now, I'm assuming that the '' path refers to the directory containing the 'script', and so I figured the rest of them would be coming from my PYTHONPATH environmental variable. However, when I go to the terminal and type env, PYTHONPATH doesn't exist as an environmental variable. I also tried import os then os.environ, but I get the same output. Do I really not have a PYTHONPATH environmental variable? I don't believe I ever specifically defined a PYTHONPATH environmental variable, but I assumed that when I installed new packages they automatically altered that environment variable. If I don't have a PYTHONPATH, how is my sys.path getting populated? If I download new packages, how does Python know where to look for them if I don't have this PYTHONPATH variable? How do environment variables work? From what I understand, environment variables are specific to the process for which they are set, however, if I open multiple terminal windows and run env, they all display a number of identical variables, for example, PATH. I know there file locations for persistent environment variables, for example /etc/environment, which contains my PATH variable. Is it possible to tell where a persistent environment variable is stored? What is the recommended location for storing new persistent environment variables? How do environment variables actually work with say, the Python interpreter? The Python interpreter looks for PYTHONPATH, but how does it work at the nitty-gritty level?

    Read the article

  • installed openstack using devstack install shell script but getting 500 error when i try opening dashboard

    - by Arvind
    I followed the instructions at http://devstack.org/guides/single-machine.html to install OpenStack. I first installed Ubuntu on my Windows 7 PC using the officially supported Windows installer for Ubuntu 12.04 LTS. And after that I followed the instructions at above page to install OpenStack. As per instructions, I should be able to access the dashboard aka Horizon, at http://192.168.1.4/ (thats the IP of the PC on which I installed Ubuntu-OpenStack). However I am getting a 500 error web page when I open that. How do I resolve this error? I want to set up a dev environment for OpenStack. For your ref, the whole error message is given now-- FilterError at / /usr/bin/env: node: No such file or directory Request Method: GET Request URL: http://192.168.1.4/ Django Version: 1.4.2 Exception Type: FilterError Exception Value: /usr/bin/env: node: No such file or directory Exception Location: /usr/local/lib/python2.7/dist-packages/compressor/filters/base.py in input, line 133 Python Executable: /usr/bin/python Python Version: 2.7.3 Python Path: ['/opt/stack/horizon/openstack_dashboard/wsgi/../..', '/opt/stack/python-keystoneclient', '/opt/stack/python-novaclient', '/opt/stack/python-openstackclient', '/opt/stack/keystone', '/opt/stack/glance', '/opt/stack/python-glanceclient/setuptools_git-0.4.2-py2.7.egg', '/opt/stack/python-glanceclient', '/opt/stack/nova', '/opt/stack/horizon', '/opt/stack/cinder', '/opt/stack/python-cinderclient', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol', '/opt/stack/horizon/openstack_dashboard'] Server time: Sat, 27 Oct 2012 08:43:29 +0000 Error during template rendering In template /opt/stack/horizon/openstack_dashboard/templates/_stylesheets.html, error at line 3 /usr/bin/env: node: No such file or directory 1 {% load compress %} 2 3 {% compress css %} 4 <link href='{{ STATIC_URL }}dashboard/less/horizon.less' type='text/less' media='screen' rel='stylesheet' /> 5 {% endcompress %} 6 7 <link rel="shortcut icon" href="{{ STATIC_URL }}dashboard/img/favicon.ico"/> 8 Also, the traceback is now given below-- Environment: Request Method: GET Request URL: http://192.168.1.4/ Django Version: 1.4.2 Python Version: 2.7.3 Installed Applications: ('openstack_dashboard', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'compressor', 'horizon', 'openstack_dashboard.dashboards.project', 'openstack_dashboard.dashboards.admin', 'openstack_dashboard.dashboards.settings', 'openstack_auth') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'horizon.middleware.HorizonMiddleware', 'django.middleware.doc.XViewMiddleware', 'django.middleware.locale.LocaleMiddleware') Template error: In template /opt/stack/horizon/openstack_dashboard/templates/_stylesheets.html, error at line 3 /usr/bin/env: node: No such file or directory 1 : {% load compress %} 2 : 3 : {% compress css %} 4 : <link href='{{ STATIC_URL }}dashboard/less/horizon.less' type='text/less' media='screen' rel='stylesheet' /> 5 : {% endcompress %} 6 : 7 : <link rel="shortcut icon" href="{{ STATIC_URL }}dashboard/img/favicon.ico"/> 8 : Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/vary.py" in inner_func 36. response = func(*args, **kwargs) File "/opt/stack/horizon/openstack_dashboard/wsgi/../../openstack_dashboard/views.py" in splash 38. return shortcuts.render(request, 'splash.html', {'form': form}) File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render 44. return HttpResponse(loader.render_to_string(*args, **kwargs), File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string 176. return t.render(context_instance) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 140. return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render 134. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 823. bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 74. return node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render 155. return self.render_template(self.template, context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render_template 137. output = template.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 140. return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render 134. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render 823. bit = self.render_node(node, context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 74. return node.render(context) File "/usr/local/lib/python2.7/dist-packages/compressor/templatetags/compress.py" in render 147. return self.render_compressed(context, self.kind, self.mode, forced=forced) File "/usr/local/lib/python2.7/dist-packages/compressor/templatetags/compress.py" in render_compressed 107. rendered_output = self.render_output(compressor, mode, forced=forced) File "/usr/local/lib/python2.7/dist-packages/compressor/templatetags/compress.py" in render_output 119. return compressor.output(mode, forced=forced) File "/usr/local/lib/python2.7/dist-packages/compressor/css.py" in output 51. ret.append(subnode.output(*args, **kwargs)) File "/usr/local/lib/python2.7/dist-packages/compressor/css.py" in output 53. return super(CssCompressor, self).output(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in output 230. content = self.filter_input(forced) File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in filter_input 192. for hunk in self.hunks(forced): File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in hunks 167. precompiled, value = self.precompile(value, **options) File "/usr/local/lib/python2.7/dist-packages/compressor/base.py" in precompile 210. command=command, filename=filename).input(**kwargs) File "/usr/local/lib/python2.7/dist-packages/compressor/filters/base.py" in input 133. raise FilterError(err) Exception Type: FilterError at / Exception Value: /usr/bin/env: node: No such file or directory

    Read the article

  • Can't import my module when start my twisted application under root

    - by kepkin
    Here is absolutely minimal application so you could try to reproduce it on your machine. Having two files for example in /home/aln/tmp/tw_test: server.tac MyLib.py MyLib.py class Solver(object): def solve(self): """ do extremely complex stuff here """ print "Hello from solve" server.tac #!/usr/bin/python import MyLib from twisted.application import internet, service from twisted.internet import protocol, reactor, defer, utils, threads from twisted.protocols import basic class MyProtocol(basic.LineReceiver): def lineReceived(self, line): if line=="new job": self.transport.write("started a job" + '\r\n') self.factory.run_defered() class MyFactory(protocol.ServerFactory, MyLib.Solver): protocol = MyProtocol def run_defered_helper(self): self.solve() def run_defered(self): d = threads.deferToThread(self.run_defered_helper) application = service.Application('MyApplication') factory = MyFactory() internet.TCPServer(1079, factory).setServiceParent(service.IServiceCollection(application)) Everything works fine when I start it under non-root user. aln@aln-laptop:tw_test$ twistd -ny server.tac 2010-03-03 22:42:55+0300 [-] Log opened. 2010-03-03 22:42:55+0300 [-] twistd 8.2.0 (/usr/bin/python 2.6.4) starting up. 2010-03-03 22:42:55+0300 [-] reactor class: twisted.internet.selectreactor.SelectReactor. 2010-03-03 22:42:55+0300 [-] <class 'MyFactory'> starting on 1079 2010-03-03 22:42:55+0300 [-] Starting factory <MyFactory object at 0x2d5ea50> 2010-03-03 22:42:59+0300 [MyProtocol,0,127.0.0.1] Hello from solve ^C2010-03-03 22:43:01+0300 [-] Received SIGINT, shutting down. 2010-03-03 22:43:01+0300 [-] (Port 1079 Closed) 2010-03-03 22:43:01+0300 [-] Stopping factory <MyFactory object at 0x2d5ea50> 2010-03-03 22:43:01+0300 [-] Main loop terminated. 2010-03-03 22:43:02+0300 [-] Server Shut Down. But if try to start it under root (which is going to happen in my real application) I receive the following exception: aln@aln-laptop:tw_test$ sudo twistd -ny server.tac [sudo] password for aln: Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 694, in run runApp(config) File "/usr/lib/python2.6/dist-packages/twisted/scripts/twistd.py", line 23, in runApp _SomeApplicationRunner(config).run() File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 411, in run self.application = self.createOrGetApplication() File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 494, in createOrGetApplication application = getApplication(self.config, passphrase) --- <exception caught here> --- File "/usr/lib/python2.6/dist-packages/twisted/application/app.py", line 505, in getApplication application = service.loadApplication(filename, style, passphrase) File "/usr/lib/python2.6/dist-packages/twisted/application/service.py", line 390, in loadApplication application = sob.loadValueFromFile(filename, 'application', passphrase) File "/usr/lib/python2.6/dist-packages/twisted/persisted/sob.py", line 215, in loadValueFromFile exec fileObj in d, d File "server.tac", line 2, in <module> import MyLib exceptions.ImportError: No module named MyLib Failed to load application: No module named MyLib If I try to load MyLib module in the python intepreter under root, it works fine: aln@aln-laptop:tw_test$ sudo python Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MyLib >>> import sys >>> print(sys.path) ['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/local/lib/python2.6/dist-packages'] >>> sys.path is absolutely the same for aln user. I tried sudo -E too. Any suggestions?

    Read the article

  • Django CMS - not able to upload images through cmsplugin_filer_image

    - by Luke
    i have a problem with a local installation on django cms 2.3.3: i've installed it trough pip, in a separated virtualenv. next i followed the tutorial for settings.py configuration, i started the server. Then in the admin i created an page (home), and i've tried to add an image in the placeholder through the cmsplugin_filer_image, but the upload seems that doesn't work. here's my settings.py: # Django settings for cms1 project. # -*- coding: utf-8 -*- import os gettext = lambda s: s PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'cms1', # Or path to database file if using sqlite3. 'USER': 'cms', # Not used with sqlite3. 'PASSWORD': 'cms', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'Europe/Rome' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'it-it' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_PATH, "media") # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_PATH, "static") STATIC_URL = "/static/" # Additional locations of static files STATICFILES_DIRS = ( os.path.join(PROJECT_PATH, "static_auto"), # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '^c2q3d8w)f#gk%5i)(#i*lwt%lm-!2=(*1d!1cf+rg&amp;-hqi_9u' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'cms.middleware.multilingual.MultilingualURLMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'cms1.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'cms1.wsgi.application' TEMPLATE_DIRS = ( os.path.join(PROJECT_PATH, "templates"), # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) CMS_TEMPLATES = ( ('template_1.html', 'Template One'), ('template_2.html', 'Template Two'), ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.core.context_processors.media', 'django.core.context_processors.static', 'cms.context_processors.media', 'sekizai.context_processors.sekizai', ) LANGUAGES = [ ('it', 'Italiano'), ('en', 'English'), ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'cms', #django CMS itself 'mptt', #utilities for implementing a modified pre-order traversal tree 'menus', #helper for model independent hierarchical website navigation 'south', #intelligent schema and data migrations 'sekizai', #for javascript and css management #'cms.plugins.file', 'cms.plugins.flash', 'cms.plugins.googlemap', 'cms.plugins.link', #'cms.plugins.picture', 'cms.plugins.snippet', 'cms.plugins.teaser', 'cms.plugins.text', #'cms.plugins.video', 'cms.plugins.twitter', 'filer', 'cmsplugin_filer_file', 'cmsplugin_filer_folder', 'cmsplugin_filer_image', 'cmsplugin_filer_teaser', 'cmsplugin_filer_video', 'easy_thumbnails', 'PIL', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } when i try to upload an image, in the clipboard section i don't have the thumbnail, but just an 'undefined' message: and this is the runserver console while trying to upload: [20/Oct/2012 15:15:56] "POST /admin/filer/clipboard/operations/upload/?qqfile=29708_1306856312320_7706073_n.jpg HTTP/1.1" 500 248133 [20/Oct/2012 15:15:56] "GET /it/admin/filer/folder/unfiled_images/undefined HTTP/1.1" 301 0 [20/Oct/2012 15:15:56] "GET /it/admin/filer/folder/unfiled_images/undefined/ HTTP/1.1" 404 1739 Also, this is project filesystem: cms1 +-- cms1 ¦   +-- __init__.py ¦   +-- __init__.pyc ¦   +-- media ¦   ¦   +-- filer_public ¦   ¦   +-- 2012 ¦   ¦   +-- 10 ¦   ¦   +-- 20 ¦   ¦   +-- 29708_1306856312320_7706073_n_1.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_2.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_3.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_4.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_5.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_6.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n_7.jpg ¦   ¦   +-- 29708_1306856312320_7706073_n.jpg ¦   ¦   +-- torrent-client-macosx.jpg ¦   +-- settings.py ¦   +-- settings.pyc ¦   +-- static ¦   +-- static_auto ¦   +-- static_manual ¦   +-- templates ¦   ¦   +-- base.html ¦   ¦   +-- template_1.html ¦   ¦   +-- template_2.html ¦   +-- urls.py ¦   +-- urls.pyc ¦   +-- wsgi.py ¦   +-- wsgi.pyc +-- manage.py So files are uploaded, but they are not accessible to cms. there's a similar question here, but doens't help me so much. It would be very helpful any help on this issue to me. Thanks, luke

    Read the article

  • Handling TclErrors in Python

    - by anteater7171
    In the following code I'll get the following error if I right click the window that pops up. Then go down to the very bottom entry widget then delete it's contents. It seems to be giving me a TclError. How do I go about handeling such an error? The Error Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\Lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "C:\Python26\CPUDEMO.py", line 503, in I TL.sclS.set(S1) File "C:\Python26\Lib\lib-tk\Tkinter.py", line 2765, in set self.tk.call(self._w, 'set', value) TclError: expected floating-point number but got "" The Code #F #PIthon.py # Import/Setup import Tkinter import psutil,time import re from PIL import Image, ImageTk from time import sleep class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): Widgets self.menu = Tkinter.Menu(self, tearoff = 0 ) M = [ "Options...", "Exit"] self.selectedM = Tkinter.StringVar() self.menu.add_radiobutton( label = 'Hide', variable = self.selectedM, command = self.E ) self.menu.add_radiobutton( label = 'Bump', variable = self.selectedM, command = self.E ) self.menu.add_separator() self.menu.add_radiobutton( label = 'Options...', variable = self.selectedM, command = self.E ) self.menu.add_separator() self.menu.add_radiobutton( label = 'Exit', variable = self.selectedM, command = self.E ) self.frame1 = Tkinter.Frame(self,bg='grey15',relief='ridge',borderwidth=4,width=185, height=39) self.frame1.grid() self.frame1.grid_propagate(0) self.frame1.bind( "<Button-3><ButtonRelease-3>", self.D ) self.frame1.bind( "<Button-2><ButtonRelease-2>", self.C ) self.frame1.bind( "<Double-Button-1>", self.C ) self.labelVariable = Tkinter.StringVar() self.label = Tkinter.Label(self.frame1,textvariable=self.labelVariable,fg="lightgreen",bg="grey15",borderwidth=1,font=('arial', 10, 'bold')) self.label.grid(column=1,row=0,columnspan=1,sticky='nsew') self.label.bind( "<Button-3><ButtonRelease-3>", self.D ) self.label.bind( "<Button-2><ButtonRelease-2>", self.C ) self.label.bind( "<Double-Button-1>", self.C ) self.F() self.overrideredirect(1) self.wm_attributes("-topmost", 1) global TL1 TL1 = Tkinter.Toplevel(self) TL1.wm_geometry("+0+5000") TL1.overrideredirect(1) TL1.button = Tkinter.Button(TL1,text="? CPU",fg="lightgreen",bg="grey15",activeforeground="lightgreen", activebackground='grey15',borderwidth=4,font=('Arial', 8, 'bold'),command=self.J) TL1.button.pack(ipadx=1) Events def Reset(self): self.label.configure(font=('arial', 10, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0) self.labela.configure(font=('arial', 8, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0) self.frame1.configure(bg='grey15',relief='ridge',borderwidth=4,width=224, height=50) self.label.pack(ipadx=38) def helpmenu(self): t2 = Tkinter.Toplevel(self) Tkinter.Label(t2, text='This is a help menu', anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="ridge",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1) t2.resizable(False,False) t2.title('Help') menu = Tkinter.Menu(self) t2.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Exit |", menu=filemenu) filemenu.add_command(label="Exit", command=t2.destroy) def aboutmenu(self): t1 = Tkinter.Toplevel(self) Tkinter.Label(t1, text=' About:\n\n CPU Usage v1.0\n\n Publisher: Drew French\n Date: 05/09/10\n Email: [email protected] \n\n\n\n\n\n\n Written in Python 2.6.4', anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="sunken",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1) t1.resizable(False,False) t1.title('About') menu = Tkinter.Menu(self) t1.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Exit |", menu=filemenu) filemenu.add_command(label="Exit", command=t1.destroy) def A (self,event): TL.entryVariable1.set(TL.sclY.get()) TL.entryVariable2.set(TL.sclX.get()) Y = TL.sclY.get() X = TL.sclX.get() self.wm_geometry("+" + str(X) + "+" + str(Y)) def B(self,event): Y1 = TL.entryVariable1.get() X1 = TL.entryVariable2.get() self.wm_geometry("+" + str(X1) + "+" + str(Y1)) TL.sclY.set(Y1) TL.sclX.set(X1) def C(self,event): s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) - 150 P = M + 150 while Y3 > M: sleep(0.0009) Y3 = int(Y3) - 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) sleep(2.00) while Y3 < P: sleep(0.0009) Y3 = int(Y3) + 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) def D(self, event=None): self.menu.post( event.x_root, event.y_root ) def E(self): if self.selectedM.get() =='Options...': Setup global TL TL = Tkinter.Toplevel(self) menu = Tkinter.Menu(TL) TL.config(menu=menu) filemenu = Tkinter.Menu(menu) menu.add_cascade(label="| Menu |", menu=filemenu) filemenu.add_command(label="Instruction Manual...", command=self.helpmenu) filemenu.add_command(label="About...", command=self.aboutmenu) filemenu.add_separator() filemenu.add_command(label="Exit Options", command=TL.destroy) filemenu.add_command(label="Exit", command=self.destroy) helpmenu = Tkinter.Menu(menu) menu.add_cascade(label="| Help |", menu=helpmenu) helpmenu.add_command(label="Instruction Manual...", command=self.helpmenu) helpmenu.add_separator() helpmenu.add_command(label="Quick Help...", command=self.helpmenu) Title TL.label5 = Tkinter.Label(TL,text="CPU Usage: Options",anchor="center",fg="black",bg="lightgreen",relief="ridge",borderwidth=5,font=('Arial', 18, 'bold')) TL.label5.pack(padx=15,ipadx=5) X Y scale TL.separator = Tkinter.Frame(TL,height=7, bd=1, relief='ridge', bg='grey95') TL.separator.pack(pady=5,padx=5) # TL.sclX = Tkinter.Scale(TL.separator, from_=0, to=1500, orient='horizontal', resolution=1, command=self.A) TL.sclX.grid(column=1,row=0,ipadx=27, sticky='w') TL.label1 = Tkinter.Label(TL.separator,text="X",anchor="s",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label1.grid(column=0,row=0, pady=1, sticky='S') TL.sclY = Tkinter.Scale(TL.separator, from_=0, to=1500, resolution=1, command=self.A) TL.sclY.grid(column=2,row=1,rowspan=2,sticky='e', padx=4) TL.label3 = Tkinter.Label(TL.separator,text="Y",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label3.grid(column=2,row=0, padx=10, sticky='e') TL.entryVariable2 = Tkinter.StringVar() TL.entry2 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable2, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry2.grid(column=1,row=1,ipadx=20, pady=10,sticky='EW') TL.entry2.bind("<Return>", self.B) TL.label2 = Tkinter.Label(TL.separator,text="X:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label2.grid(column=0,row=1, ipadx=4, sticky='W') TL.entryVariable1 = Tkinter.StringVar() TL.entry1 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable1, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entry1.grid(column=1,row=2,sticky='EW') TL.entry1.bind("<Return>", self.B) TL.label4 = Tkinter.Label(TL.separator,text="Y:", anchor="center",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label4.grid(column=0,row=2, ipadx=4, sticky='W') TL.label7 = Tkinter.Label(TL.separator,text="Text Colour:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label7.grid(column=1,row=3,stick="W",ipady=10) TL.selectedP = Tkinter.StringVar() TL.opt1 = Tkinter.OptionMenu(TL.separator, TL.selectedP,'Normal', 'White','Black', 'Blue', 'Steel Blue','Green','Light Green','Yellow','Orange' ,'Red',command=self.G) TL.opt1.config(fg="black",bg="grey90",activebackground="grey90",activeforeground="black", anchor="center",relief="raised",direction='right',font=('Arial', 10)) TL.opt1.grid(column=1,row=4,sticky='EW',padx=20,ipadx=20) TL.selectedP.set('Normal') TL.label7 = Tkinter.Label(TL.separator,text="Refresh Rate:",fg="black",bg="grey95",font=('Arial', 8 ,'bold')) TL.label7.grid(column=1,row=5,stick="W",ipady=10) TL.sclS = Tkinter.Scale(TL.separator, from_=10, to=2000, orient='horizontal', resolution=10, command=self.H) TL.sclS.grid(column=1,row=6,ipadx=27, sticky='w') TL.sclS.set(650) TL.entryVariableS = Tkinter.StringVar() TL.entryS = Tkinter.Entry(TL.separator,textvariable=TL.entryVariableS, fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10)) TL.entryS.grid(column=1,row=7,ipadx=20, pady=10,sticky='EW') TL.entryS.bind("<Return>", self.I) TL.entryVariableS.set(650) # TL.resizable(False,False) TL.title('Options') geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") s = self.wm_geometry() m = geomPatt.search(s) X = m.group(4) Y = m.group(6) TL.sclY.set(Y) TL.sclX.set(X) if self.selectedM.get() == 'Exit': self.destroy() if self.selectedM.get() == 'Bump': s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) - 150 P = M + 150 while Y3 > M: sleep(0.0009) Y3 = int(Y3) - 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) sleep(2.00) while Y3 < P: sleep(0.0009) Y3 = int(Y3) + 1 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(Y3)) if self.selectedM.get() == 'Hide': s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) + 5000 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(M)) TL1.wm_geometry("+0+190") def F (self): G = round(psutil.cpu_percent(), 1) G1 = str(G) + '%' self.labelVariable.set(G1) try: S2 = TL.entryVariableS.get() except ValueError, e: S2 = 650 except NameError: S2 = 650 self.after(int(S2), self.F) def G (self,event): if TL.selectedP.get() =='Normal': self.label.config( fg = 'lightgreen' ) TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen') if TL.selectedP.get() =='Red': self.label.config( fg = 'red' ) TL1.button.config( fg = 'red',activeforeground='red') if TL.selectedP.get() =='Orange': self.label.config( fg = 'orange') TL1.button.config( fg = 'orange',activeforeground='orange') if TL.selectedP.get() =='Yellow': self.label.config( fg = 'yellow') TL1.button.config( fg = 'yellow',activeforeground='yellow') if TL.selectedP.get() =='Light Green': self.label.config( fg = 'lightgreen' ) TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen') if TL.selectedP.get() =='Normal': self.label.config( fg = 'lightgreen' ) TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen') if TL.selectedP.get() =='Steel Blue': self.label.config( fg = 'steelblue1' ) TL1.button.config( fg = 'steelblue1',activeforeground='steelblue1') if TL.selectedP.get() =='Blue': self.label.config( fg = 'blue') TL1.button.config( fg = 'blue',activeforeground='blue') if TL.selectedP.get() =='Green': self.label.config( fg = 'darkgreen' ) TL1.button.config( fg = 'darkgreen',activeforeground='darkgreen') if TL.selectedP.get() =='White': self.label.config( fg = 'white' ) TL1.button.config( fg = 'white',activeforeground='white') if TL.selectedP.get() =='Black': self.label.config( fg = 'black') TL1.button.config( fg = 'black',activeforeground='black') def H (self,event): TL.entryVariableS.set(TL.sclS.get()) S = TL.sclS.get() def I (self,event): S1 = TL.entryVariableS.get() TL.sclS.set(S1) TL.sclS.set(TL.sclS.get()) S1 = TL.entryVariableS.get() TL.sclS.set(S1) def J (self): s = self.wm_geometry() geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)") m = geomPatt.search(s) X3 = m.group(4) Y3 = m.group(6) M = int(Y3) - 5000 self.update_idletasks() self.wm_geometry("+" + str(X3) + "+" + str(M)) TL1.wm_geometry("+0+5000") Loop if name == "main": app = simpleapp_tk(None) app.mainloop()

    Read the article

< Previous Page | 1 2 3 4