text
stringlengths
226
34.5k
Using print() inside recursive functions in Python3 Question: I am following the book Introduction to Computing Using Python, by Ljubomir Perkovic, and I am having trouble with one of the examples in recursion section of the book. The code is as follows: def pattern(n): 'prints the nth pattern' if n == 0: # base case print(0, end=' ') else: #recursive step: n > 0 pattern(n-1) # print n-1st pattern print(n, end=' ') # print n pattern(n-1) # print n-1st pattern For, say, `pattern(1)`, the output should be `0 1 0`, and it should be displayed horizontally. When calling the function `pattern(1)`, nothing prints out, however. But if this is followed by a print statement without arguments, then the results are displayed. >>>pattern(1) >>>print() 0 1 0 If I remove the `end` argument of the `print()` functions inside the recursive function, I get correct output (albeit it displays it vertically): >>> pattern(1) 0 1 0 This makes me think that the recursive code itself is correct (plus I confirmed it was with the source provided by the book's website, and with the errata sheet). I am not sure, however, why the `print` statement isn't printing the output as the functions run, if the `end` parameter is included. Any help would be greatly appreciated. Answer: The `print` function doesn't always flush the output. You should flush it explicitly: import sys def pattern(n): 'prints the nth pattern' if n == 0: # base case print(0, end=' ') else: #recursive step: n > 0 pattern(n-1) # print n-1st pattern print(n, end=' ') # print n pattern(n-1) # print n-1st pattern sys.stdout.flush() Note that on python3.3 `print` has a new keyword argument `flush` that you can use to forcibly flush the output(and thus avoid using `sys.stdout.flush`). * * * On a general note I'd decouple the output from the pattern, doing, for example: def gen_pattern(n): if n == 0: yield 0 else: for elem in gen_pattern(n-1): yield elem yield n for elem in gen_pattern(n-1): yield elem def print_pattern(n): for elem in gen_pattern(n): print(elem, end=' ') sys.stdout.flush() This makes the code more flexible and reusable, and has the advantage of calling `flush` only once, or you could also call it once every `x` elements(actually I believe `print` already does this. It flushes if trying to write many characters on the screen). In python3.3 the code could be simplified a little: def gen_pattern(n): if n == 0: yield 0 else: yield from gen_pattern(n-1) yield n yield from gen_pattern(n-1)
multiprocess.apply_async How do I wrap *args and **kwargs? Question: I'm trying to get [`multiprocess.apply_async`](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply_async) to take in both `*args` and `**kwargs`. The docs indicate that this might be possible with the calling sequence: apply_async(func[, args[, kwds[, callback]]]) But I can not figure out how to get the calling syntax correct. With the minimal example: from multiprocessing import Pool def f(x, *args, **kwargs): print x, args, kwargs args, kw = (), {} print "# Normal call" f(0, *args, **kw) print "# Multicall" P = Pool() sol = [P.apply_async(f, (x,), *args, **kw) for x in range(2)] P.close() P.join() for s in sol: s.get() This works as expected giving the output # Normal call 0 () {} # Multicall 0 () {} 1 () {} When args is not an empty tuple, for example `args = (1,2,3)`, the single call works, but the multiprocessing solution gives: # Normal call 0 (1, 2, 3) {} # Multicall Traceback (most recent call last): File "kw.py", line 16, in <module> sol = [P.apply_async(f, (x,), *args, **kw) for x in range(2)] TypeError: apply_async() takes at most 5 arguments (6 given) With the kwargs argument I get, for example `kw = {'cat':'dog'}` # Normal call 0 () {'cat': 'dog'} # Multicall Traceback (most recent call last): File "kw.py", line 15, in <module> sol = [P.apply_async(f, (x,), *args, **kw) for x in range(2)] TypeError: apply_async() got an unexpected keyword argument 'cat' How do I properly wrap `multiprocess.apply_async`? Answer: You don't have to use `*` and `**` explicitly. Simply pass the tuple and the dict and let `apply_async` unpack them: from multiprocessing import Pool def f(x, *args, **kwargs): print x, args, kwargs args, kw = (1,2,3), {'cat': 'dog'} print "# Normal call" f(0, *args, **kw) print "# Multicall" P = Pool() sol = [P.apply_async(f, (x,) + args, kw) for x in range(2)] P.close() P.join() for s in sol: s.get() Output: # Normal call 0 (1, 2, 3) {'cat': 'dog'} # Multicall 0 (1, 2, 3) {'cat': 'dog'} 1 (1, 2, 3) {'cat': 'dog'} Remember that in python's documentation, if a function accepts `*args` and `**kwargs` its signature explicitly states that: the_function(a,b,c,d, *args, **kwargs) In your case: apply_async(func[, args[, kwds[, callback]]]) There are no `*` there, hence `args` is **one** argument, which is unpacked when calling `func` and `kwargs` is **one** argument and processed in the same way. Also note that it's not possible to have other arguments after `**kwargs`: >>> def test(**kwargs, something=True): pass File "<stdin>", line 1 def test(**kwargs, something=True): pass ^ SyntaxError: invalid syntax
iPython giving me a syntax error Question: I'm running python 2.4 right now and have installed iPython onto my ubuntu machine. The problem I'm having right now is that it keeps giving me an ImportError whenever I try to launch it from the terminal. Right now the symbolic link is located `/usr/local/bin` and the actual file is inside `/usr/bin/` Error Message: File "/usr/local/bin/ipython", line 9 except ImportError as e: ^ SyntaxError: invalid syntax iPython File... #!/opt/ttools/bin/python ## YES THIS IS THE CORRECT PATH """Terminal-based IPython entry point. """ from IPython.frontend.terminal.ipapp import launch_new_instance try: launch_new_instance() except ImportError as e: if "qt.console.qtconsoleapp" in e.message: print "Could not start qtconsole. Please install ipython-qtconsole" elif "html.notebook.notebookapp" in e.message: print "Could not start notebook. Please install ipython-notebook" else: # if there is no clue on the cause -- just re-raise raise I've never had an issue like this when I had to set it up on my mac... Any help would be appreciated. Thanks !! EDIT :: SOLUTION Download <http://archive.ipython.org/release/0.10.2/ipython-0.10.2-py2.6.egg> navigate to downloads folder and run the following command: `sudo easy_install ipython-0.10.2-py2.6.egg` Answer: iPython dropped support for python < 2.6 since version 0.11, you'll have to install 0.10 (or possibly even 0.9) from the archive: <http://archive.ipython.org/release/>
How can i quote escape characters in csv writer in python Question: I am writing the csv file like this for a in products: mylist =[] for h in headers['product']: mylist.append(a.get(h)) writer.writerow(mylist) My my few fields are text fields can conatins any characters like `,` `"` `'` `\n` or anything else. what is the safest way to write that in csv file. also file will also have integers and floats Answer: You should use **QUOTE_ALL** quoting option: import StringIO import csv row = ["AAA \n BBB ,222 \n CCC;DDD \" EEE ' FFF 111"] output = StringIO.StringIO() wr = csv.writer(output, quoting=csv.QUOTE_ALL) wr.writerow( row ) # Test: contents = output.getvalue() parsedRow = list(csv.reader([contents]))[0] if parsedRow == row: print "BINGO!"
Python yaml dump confuse Question: Let's say I have a json file like below, call it `src.json`. { "main": { "contenttype": "Document" }, "dublin": { "title": "ダウンロード", "description": "", "creators": [ "池田大作" ], "created": "2012-04-23 10:09:34.642940" } } I wanna dump the `dublin` contents to `dst.yaml` using `yaml` in `python`. Here is my code: import json import yaml with open('src.json') as f: data = json.load(f) dump = {'title': data.get('dublin', {}).get('title', ''), 'description': data.get('dublin', {}).get('description', ''), 'creator': data.get('dublin', {}).get('creators',[''])[0], 'created': data.get('dublin', {}).get('created', '') } with open('dst.yaml', 'w') as stream: yaml.safe_dump(dump, stream, allow_unicode=True ) However, I am not satisfied with the result: {created: '2010-03-26 09:26:44.002029', creator: 池田大作, description: ' ', title: ダウンロード} The satisfied one should be : created: 2010-03-26 09:26:44.002029 creator: 池田大作 description: '' title: ダウンロード Then, my questions are: 1. Why `'2010-03-26 09:26:44.002029'` has single quotes while `title` and `creator` not? How to remove single quotes around the date ? 2. Where is the line break? It should have with yaml dumping operation. Any one help! Answer: 1. Because it has a space in it. 2. Set `default_flow_style=False` in your call to `yaml.dump()`. * * * Also, you don't need to do all of that reconstruction; you could just dump the existing dublin dict directly: import json import yaml with open('src.json') as f: data = json.load(f) with open('dst.yaml', 'w') as stream: yaml.safe_dump(data.get('dublin', {}), stream, allow_unicode=True, default_flow_style=False)
django reset contenttypes mismatch Question: Have deleted my database. Have run SyncDb. Trying to load from dump ..-python manage.py loaddata dump.json. Get- "<1062 Duplicate entry '' for key.." Have run "python manage.py reset contentypes" But get- Error: Error: contenttypes couldn't be reset. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin.py sqlreset contenttypes'. That's the SQL this command wasn't able to run. The full error: (1217, 'Cannot delete or update a parent row: a foreign key constraint fails') Have try to run: > > > from django.core import management >>> >>> management.call_command("flush", verbosity=, interactive=False) >>> >>> management.call_command("totally reset", "contenttypes", verbosity=, interactive=False) >>> >>> management.call_command("loaddata", "full_test_data.json", verbosity=) But get- syntax error. Have python 2.7. and Django 1.4 Any ideas? Answer: Try setting `foreign_key_checks` false, DATABASES = { 'default': { # ... 'OPTIONS': { "init_command": "SET foreign_key_checks = 0;", }, } } But you should definitely try to use the dumpdata command with the [\--natural](https://docs.djangoproject.com/en/dev/ref/django-admin/#django- admin-option---natural) option to make sure there's no hardcoded content types in your fixtures.
apache server not using proper virtualenv with WSGI setting Question: I am facing a problem related to django wsgi script. I have been using two virtualenv for my two application and I have deployed these two application on my local server with different port. Apache configuration file for first Appplication looks like: listen 8081 WSGIPythonPath /home/user/app1:/home/user/virtual-env1/lib/python2.7/site-packages <VirtualHost mylocalip:8081> ServerAdmin webmaster@localhost ServerName www.app1.com DocumentRoot /home/user/app1 <Directory /home/user/app1/static-root> Options Indexes Order Allow,Deny Allow from all IndexOptions FancyIndexing </Directory> <Directory /home/user/app1> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> WSGIScriptAlias / /home/user/app1/django.wsgi WSGIPassAuthorization On Alias "/static" /home/user/workspace/app1/static_root </VirtualHost> and Apache configuration for second application is almost same but instead of virtual-env1, I am using virtual-env2 and different port. But when I run my second application on the server I got this error. **AttributeError at /** 'Settings' object has no attribute 'DB_FILES' Request Method: GET Request URL: http://mylocalip:8091/ Django Version: 1.4.3 Exception Type: AttributeError Exception Value: 'Settings' object has no attribute 'DB_FILES' Exception Location: /home/user/virtual-env1/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185 Python Executable: /usr/bin/python Python Version: 2.7.2 Python Path: ['/home/user/virtual-env1/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/home/user/virtual-env1/lib/python2.7/site-packages/pip-1.1-py2.7.egg', '/home/user/app1', '/home/user/virtual-env1/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages/pip-1.1-py2.7.egg', '/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/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/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-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol', '/home/user/app2', '/home'] My django.wsgi file loks like this: import os, sys apache_configuration = os.path.dirname (__file__) project = os.path.dirname (apache_configuration) workspace = os.path.dirname (project) sys.path.append ("/home/user/app2") sys.path.append (workspace) os.environ ['DJANGO_SETTINGS_MODULE'] = 'app2.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler () I don't know why my server is looking inside the virtual-env1 instead of virtual-env2. Please help me as I am new to django and wsgi. Answer: Here's what helped me in similar situation. My wsgi file looks like this: import os import sys # activate venv activate_this = 'full_path_to_activate_this.py' execfile(activate_this, dict(__file__=activate_this)) # insert project path to sys path path = 'full_path_to_your_project' if path not in sys.path: sys.path.insert(0, path) import django.core.handlers.wsgi os.environ['DJANGO_SETTINGS_MODULE'] = 'your_settings' application = django.core.handlers.wsgi.WSGIHandler() May be this isn't the best approach, but it worked for me. I remember that I've googled and found many different solutions, here's some related links: * [Setting up Apache and Python WSGI to use VirtualEnv](http://stackoverflow.com/questions/6723494/setting-up-apache-and-python-wsgi-to-use-virtualenv) * [Setting up django on apache (mod_wsgi, virtualenv)](http://stackoverflow.com/questions/10898216/setting-up-django-on-apache-mod-wsgi-virtualenv) * [Django Apache wsgi virtualenv import error](http://stackoverflow.com/questions/13753151/django-apache-wsgi-virtualenv-import-error) Hope that helps.
Should unit tests run faster with a gevent patched codebase? Question: We’re investigating gevent as a drop in performance enhancer for our Flask API. There is a lot of communication over psycopg2 and Redis in our codebase. We thought we’d try running the test suite with and without: import gevent.monkey gevent.monkey.patch_all() import psycogreen.gevent psycogreen.gevent.patch_psycopg() My understanding is that `patch_all()` makes many blocking calls in the standard library more efficient on the whole by letting other threads perform work while waiting for the return call. Our unit tests take about 160 seconds to run in total and the difference between gevent patched and non-patched was negligible. Should we be seeing the power of gevent in our test suite, or does it only reveal itself in a real life production environment? More info: Using py.test running pretty regular python-2.7.2 unittest. Gevent 1.0rc2. Answer: Your understanding is correct, but are you running the tests in parallel? Perhaps [using nose](http://stackoverflow.com/questions/4710142/can-pythons- unittest-test-in-parallel-like-nose-can)? My understanding is that gevent wont really improve the 'straight line speed' of any linear code path, its a mechanism to enable concurrency in a single process.
Python: Create a list of nonmatching values Question: I've been working on program which searches a folder and finds matching files names based on a list of vaules from an input list and then copies them to a folder. The program works but now I want to add one extra layer to it; Get a list of non matching samples and then output it a CSV file. The code is not efficient, but it gets the job done though I am aware that it may not be properly set up to do what I ask. import os, fnmatch, csv, shutil, operator #Function created to search through a folder location to for using a specific list of keywords def locate(pattern, root=os.curdir): matches = [] for path, dirs, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): matches.append(os.path.join(path, filename)) return matches #output file created to store the pathfiles outfile="G:\output.csv" output=csv.writer(open(outfile,'w'), delimiter=',',quoting=csv.QUOTE_NONE) #Opens the file and stores the values in each row path="G:\GIS\Parsons Stuff\samples.csv" pathfile=open(path,'rb') openfile=csv.reader((pathfile), delimiter = ',') samplelist=[] samplelist.extend(openfile) #for loop used to return the list of tuples for checklist in zip(*samplelist): print checklist #an empty list used to store the filepaths of sample locations of interest files=[] #for loop to search for sample id's in a folder and copies the filepath for x in checklist: LocatedFiles=locate(x, "G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\") print LocatedFiles files.append(LocatedFiles) # flattens the list called files into a managable list flattenedpath=reduce(operator.add, files) #filters out files that match the filter .pdf filteredpath=[] filteredpath.append(fnmatch.filter(flattenedpath,"*.pdf*")) #outputs the file path a .csv file called output output.writerows(files) pathfile.close() #location of where files are going to be copied dst='C:\\TestFolder\\' #filters out files that match the filer .pdf filtered=[] filtered.append(fnmatch.filter(flattenedpath,"*.pdf*")) filteredpath=reduce(operator.add,filtered) #the function set() goes through the list of interest to store a list a unique values. delete_dup=set(filteredpath) delete_dup=reduce(operator.add,zip(delete_dup)) #for loop to copy files in the list delete_dup for x in delete_dup: shutil.copy(x,dst) My idea is that since the lists "samplelist" and "files" are the same length: len(samplelist) 36 len(files) 36 I should be able to pull out the index values of each empty list from "files", pass it to a list which stores the index value which can be used to pull out elements from "samplelist". I've tried using the following links for ideas to do this but have had no luck: [In Python, how can I find the index of the first item in a list that is NOT some value?](http://stackoverflow.com/questions/2748235/in-python-how-can-i- find-the-index-of-the-first-item-in-a-list-that-is-not-some) [Finding matching and nonmatching items in lists](http://stackoverflow.com/questions/8960676/finding-matching-and- nonmatching-items-in-lists) [In Python, how do I find the index of an item given a list containing it?](http://stackoverflow.com/questions/176918/in-python-how-do-i-find-the- index-of-an-item-given-a-list-containing-it?rq=1) [Pythonic way to compare two lists and print out the differences](http://stackoverflow.com/questions/2387981/pythonic-way-to- compare-two-lists-and-print-out-the-differences?rq=1) **Following is the output from the list called "samplelist"** `('*S42TPZ2*', '*S3138*', '*S2415*', '*S2378*', '*S2310*', '*S2299*', '*S1778*', '*S1777*', '*S1776*', '*S1408*', '*S1340*', '*S1327*', '*RW-61*', '*MW-247*', '*MW-229*', '*MW-228*', '*MW-209*', '*MW-208*', '*MW-193*', '*M51TPZ6*', '*M51TP21*', '*H1013*', '*H1001*', '*H0858*', '*H0843*', '*H0834*', '*H0514*', '*H0451*', '*H0450*', '*EY1TP9*', '*EY1TP7*', '*EY1TP6*', '*EY1TP5*', '*EY1TP4*', '*EY1TP2*', '*EY1TP1*')` **Following is the output from the list called "files"**(I am not going to list all the outputs since it is unnecessary, just wanted to give an idea of what the list looks like) `[[], [], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S2415.pdf'], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S2378.pdf'], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\MW-247.S2310.pdf', 'G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S2310.MW-247.pdf', 'G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S2310.pdf'], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S2299.pdf'], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S1778.pdf'], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S1777.pdf'], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S1776.pdf'], ['G:\\GIS\\Parsons Stuff\\boring logs\\boring logs\\S1408.pdf']` Answer: I'm not quite sure this is what you are asking for but couldn't you: index_list = [] for n, item in enumerate(list): if len(item) == 0: index_list.append(n) that little piece of code will iterate over you list and if the list contain an empty list it will return the index of the empty list and add it to another list!
How can i check call arguments if they will change with unittest.mock Question: One of my classes accumulates values in a list, uses the list as an argument to a method on another object and deletes some of the values in this list. Something like element = element_source.get() self.elements.append(element) element_destination.send(elements) self.remove_outdated_elements() But when when i was trying to test this behavior, i've found that mocks don't copy their arguments. >>> from unittest.mock import Mock >>> m = Mock() >>> a = [1] >>> m(a) <Mock name='mock()' id='139717658759824'> >>> m.call_args call([1]) >>> a.pop() 1 >>> m.assert_called_once_with([1]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.3/unittest/mock.py", line 737, in assert_called_once_with return self.assert_called_with(*args, **kwargs) File "/usr/lib/python3.3/unittest/mock.py", line 726, in assert_called_with raise AssertionError(msg) AssertionError: Expected call: mock([1]) Actual call: mock([]) Is there a way to make Mock copy it's call arguments? If not, what is the best way to test this kind of behavior? Answer: There is a chapter "[Coping with mutable arguments](http://docs.python.org/dev/library/unittest.mock- examples.html#coping-with-mutable-arguments)" in the documentation, which suggests several solutions to your problem. I'd go with this one: >>> from copy import deepcopy >>> class CopyingMock(MagicMock): ... def __call__(self, *args, **kwargs): ... args = deepcopy(args) ... kwargs = deepcopy(kwargs) ... return super(CopyingMock, self).__call__(*args, **kwargs) ... >>> c = CopyingMock(return_value=None) >>> arg = set() >>> c(arg) >>> arg.add(1) >>> c.assert_called_with(set()) >>> c.assert_called_with(arg) Traceback (most recent call last): ... AssertionError: Expected call: mock(set([1])) Actual call: mock(set([])) >>> c.foo <CopyingMock name='mock.foo' id='...'>
Issue installing cx_Oracle on Linux - Import only works from Site-Packages Directory Question: I have installed cx_Oracle to connect Python and Oracle for programming; however, I can only import cx_Oracle into python if I am in the directory where cx_Oracle lives. How can I import cx_Oracle globally? Below is code demonstrating the problem. Thanks for your help. **Python Can't Import cx_Oracle** user@T420 ~ $ python Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named cx_Oracle **Python Can Import cx_Oracle from the Directory Where it is Located** user@T420 /usr/lib/python2.7/site-packages $ ls cx_Oracle-5.1.2-py2.7.egg-info cx_Oracle.so user@T420 /usr/lib/python2.7/site-packages $ python Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cx_Oracle >>> Answer: Python on Debian does not use the site-packages folder. You can simply move the files into the dist-packages folder and everything should work. The other solution as Aaron mentioned would be to add the path to site-packages into the sys.path folder. However, the python site.py folder says the following: **Quote from site.py file:** > For Debian and derivatives, this sys.path is augmented with directories for > packages distributed within the distribution. Local addons go into > /usr/local/lib/python/dist-packages, Debian addons install into > /usr/{lib,share}/python/dist-packages. /usr/lib/python/site-packages is not > used.
Python background process not writing to MySQL db Question: I apologize if this question has been asked before, but I was unable to find any record of this issue. Full disclosure: I've only been using Python for a few months and MySQL for about 1 month. I've written a short Python script on a Raspberry Pi (running Raspbian Wheezy) that sniffs wifi packets and writes signal strength info to a MySQL database. I've also created a small PHP file that grabs the info from the database and presents it in a table (pretty basic). All components of this little system work exactly as planned, however... When I run the Python script in the background (sudo python my_script.py &) it does not appear to update the MySQL database with new readings. Yet it also throws no errors and outputs to the console without a problem (I have a line printed each time a wifi packet is intercepted and its RSSI is added to the database). I encountered the same problem when starting the script at boot up using the /etc/rc.local file. No errors, but no updates in the database either. Is the problem on the Python side of things? A MySQL setting that I need to change? Is there something else I'm completely missing? EDITED TO ADD CODE: #!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mdb import sys from scapy.all import * # Create connection to MySQL database called 'DATABASE' at localhost with username 'USERNAME' and password 'PASSWORD' HOST = "localhost" USER = "USERNAME" PW = "PASSWORD" DB = "DATABASE" con = mdb.connect(HOST, USER, PW, DB) # set interface that will be used to monitor wifi interface = "mon0" with con: cur = con.cursor() # This function will be called every time a packet is intercepted. Packet is passed to function as 'p' def sniffmgmt(p): # These are the 3 types of management frames that are sent exclusively by clients (allows us to weed out packets sent by APs) stamgmtstypes = (0, 2, 4) if p.haslayer(Dot11): # Make sure packet is a client-only type if p.subtype in stamgmtstypes: # Calculate RSSI sig_str = -(256-(ord(p.notdecoded[-4:-3]))) # Update database with most recent detection cur.execute("REPLACE INTO attendance(mac_address, rssi, timestamp) VALUES('%s', %d, NOW())" % (p.addr2, sig_str)) # Print MAC address that was detected (debugging only) print "MAC Address (%s) has been logged" % (p.addr2) # Tell scapy what interface to use (see above) and which function to call when a packet is intercepted. lfilter limits packets to management frames. sniff(iface=interface, prn=sniffmgmt, store=0, lfilter=lambda x:x.type==0) Thanks! Kyle P.S. For those who are wondering: this is not intended for malicious use, it is being used to investigate product tracking techniques at our warehouse. Answer: I expect you're not calling `commit` on the db transaction.
python ctypes vs namedtuple Question: So I have two simple ctypes struct class S2 (ctypes.Structure): _fields_ = [ ('A2', ctypes.c_uint16*10), ('B2', ctypes.c_uint32*10), ('C2', ctypes.c_uint32*10) ] class S1 (ctypes.Structure): _fields_ = [ ('A', ctypes.c_uint16), ('B', ctypes.c_uint32), ('C', S2) ] Is it possible to do this same for example with namedtuple? How lists are handled in namedtuple? Edit: struc.pack usage test_data = '0100000002000000' + 10*'01' + 10*'01' + 10*'01' S2 = collections.namedtuple('S2', ['A2', 'B2', 'C2']) S1 = collections.namedtuple('S1', ['A', 'B', 'REF_to_S2']) Data2 = S2._make(struct.unpack('10p10p10p', binascii.unhexlify(test_data[16:]))) ##this is not working, because there must be 3 args.. Data1 = S1._make(struct.unpack('ii', binascii.unhexlify(test_data[0:16]))) In the end i want to print data in readable format ( having key:value pairs visible). But now i cannot figure out how should i handle that unpack operation with two diffrent namedtuples...? this unpack.struct operation will take care that value type issues, right ? Answer: > Is it possible to do this same for example with namedtuple? It depends on what you mean by "same". You can easily create `namedtuple` types with the same fields: S2 = collections.namedtuple('S2', ['A2', 'B2', 'C2']) S1 = collections.namedtuple('S1', ['A', 'B', 'C']) However, they're obviously not the same type, and won't have the same behavior. * * * First, these fields are normal Python attributes (and also normal `tuple` members), which means they don't have static types; they can hold values of any type. So, you can do this: s2 = S2([ctypes.c_uint16(i) for i in range(10)], [ctypes.c_uint32(i) for i in range(10)], [ctypes.c_uint32(i) for i in range(10)]) s1 = S1(ctypes.c_uint16(1), ctypes.c_uint32(2), s2) But you can also do this: s2 = S2('a', 'b', 'c') s1 = S1('d', 'e', s2) … or even: s1 = S1('d', 'e', 'f') And also, note that even the first example actually created `list`s of 10 `ctypes` values, not `ctypes` arrays. If you want that, you have to cast them explicitly. * * * Second, `namedtuple`s are an extension of `tuple`s, which means they're immutable, so you can't do this: s1.C = s2 * * * And most importantly, a `namedtuple` can't be used as a `ctypes.Structure`—you can't pass it to a C function, you have to write manual logic (e.g., around `struct.pack`) if you want to serialize it in some specific binary format, etc. * * * > How lists are handled in namedtuple? As mentioned above, the members of a `namedtuple` aren't statically typed, and can hold values of any type. So, they're handled the same way they are in a `tuple`, `list`, a normal class instance, a global variable, etc. Just stick a `list` in there and you've got a `list`. * * * > yes that stuct.pack is what i need. But i cannot figure out how i should > point that the last value in s1 is reference to s2 structure. From the `namedtuple` side, you just use an `S2` instance as the value for the `S1.C`, as in my examples above. Again, the items/attributes of a `namedtuple` are just like any other attributes/variables/etc. in Python, just names that hold references to objects. So, `s1 = S1(1, 2, s2)` will make the third item of `s1` into another reference to the same object that `s2` refers to. As for how to use `struct` to serialize the data: The `struct` module doesn't have any way to directly delegate to an embedded object. But since the output of `pack` is just a `bytes` (or, in Python 2.x, `str`) object, you can do this with normal string manipulation: # version 1 s2_struct = struct.Struct('!HII') s1_header = struct.Struct('!HI') def pack_s2(s2): return s2_struct.pack(s2.A2, s2.B2, s2.C2) def unpack_s2(s2): return S2._make(s2_struct.unpack(s2)) def pack_s1(s1): return s1_header.pack(s1.A, s1.B) + pack_s2(s1.C) def unpack_S1(s1): offset = len(s1_header) a, b = s1_header.unpack(s1[:offset]) c = unpack_s2(s1[offset:]) return S1._make(a, b, c) (I personally would use `S2(*struct.unpack` rather than `S2._make`, but since the documentation does the latter repeatedly, I guess that has to be the intended way to do things…) Alternatively, you can flatten the format strings manually: s2_struct = struct.Struct('!HII') s1_struct = struct.Struct('!HIHII') def pack_s2(s2): return s2_struct.pack(s2.A2, s2.B2, s2.C2) def pack_s1(s1): return s1_struct.pack(s1.A, s1.B, s1.C.A2, s1.C.B2, s1.C.C2) def unpack_s2(s2): return S2._make(s2_struct.unpack(s2)) def unpack_S1(s1): a, b, a2, b2, c2 = s1_struct.unpack(s1) c = S2(a2, b2, c2) return S1(a, b, c) I think the second version is easier to read, but it's also easier to get wrong, and requires you to think about composing objects at the binary level instead of the Python level, so… choose whichever you find the lesser of two evils.
Two Class instances in Python not different Question: I'm working on another data acquisition project, which has turned into an object oriented programming question. In “main” at the bottom of my code I make two instances of the Object DAQInput. When I wrote this, I thought my method .getData would refer to the taskHandle of the particular instance, but it does not. When I run, the code does the getData task with the first handle twice, so clearly I don’t really understand object oriented programming in Python. I’m sorry this code will not run without PyDAQmx and a National Instruments board attached. from PyDAQmx import * import numpy class DAQInput: # Declare variables passed by reference taskHandle = TaskHandle() read = int32() data = numpy.zeros((10000,),dtype=numpy.float64) sumi = [0,0,0,0,0,0,0,0,0,0] def __init__(self, num_data, num_chan, channel, high, low): """ This is init function that opens the channel""" #Get the passed variables self.num_data = num_data self.channel = channel self.high = high self.low = low self.num_chan = num_chan # Create a task and configure a channel DAQmxCreateTask(b"",byref(self.taskHandle)) DAQmxCreateAIThrmcplChan(self.taskHandle, self.channel, b"", self.low, self.high, DAQmx_Val_DegC, DAQmx_Val_J_Type_TC, DAQmx_Val_BuiltIn, 0, None) # Start the task DAQmxStartTask(self.taskHandle) def getData(self): """ This function gets the data from the board and calculates the average""" print(self.taskHandle) DAQmxReadAnalogF64(self.taskHandle, self.num_data, 10, DAQmx_Val_GroupByChannel, self.data, 10000, byref(self.read), None) # Calculate the average of the values in data (could be several channels) i = self.read.value for j in range(self.num_chan): self.sumi[j] = numpy.sum(self.data[j*i:(j+1)*i])/self.read.value return self.sumi def killTask(self): """ This function kills the tasks""" # If the task is still alive kill it if self.taskHandle != 0: DAQmxStopTask(self.taskHandle) DAQmxClearTask(self.taskHandle) if __name__ == '__main__': myDaq1 = DAQInput(1, 4, b"cDAQ1Mod1/ai0:3", 200.0, 10.0) myDaq2 = DAQInput(1, 4, b"cDAQ1Mod2/ai0:3", 200.0, 10.0) result = myDaq1.getData() print (result[0:4]) result2 = myDaq2.getData() print (result2[0:4]) myDaq1.killTask() myDaq2.killTask() Answer: These variables: class DAQInput: # Declare variables passed by reference taskHandle = TaskHandle() read = int32() data = numpy.zeros((10000,),dtype=numpy.float64) sumi = [0,0,0,0,0,0,0,0,0,0] Are class variables. They belong to the class itself and are shared among instances of the class (i.e. if you modify `self.data` in `Instance1`, `Instace2`'s `self.data` is modified as well). If you want them to be instance variables, define them in `__init__`.
Using Beautiful Soup to extract Norwegian text from HTML files, losing the Norwegian characters Question: I have a Python script that uses Beautiful Soup to extract the text from HTML files in a directory. However, I'm having trouble getting the encoding to work properly. At first I though there may be a problem with the HTML files themselves. However, when I view the source of an HTML file in Notepad.exe, I for instance see this: `Vi er her for deg, og du må gjerne ta kontakt med oss på 815 32 000 eller på Facebook om du har noen spørsmål.` However, when I view the same HTML file in Internet Explorer, I see this: `Vi er her for deg, og du mÃ¥ gjerne ta kontakt med oss pÃ¥ 815 32 000 eller pÃ¥ Facebook om du har noen spørsmÃ¥l.` And, the Internet Explorer text is the same text that my Python script appends into my text file. So, obviously the encoding is detectable, and it's no surprise that IE doesn't understand it, but I can't seem to figure out why Python can't handle it. The encoding should be latin-1, which I thought wouldn't be a problem. Here's the code I have: import os import glob from bs4 import BeautifulSoup path = "c:\\users\\me\\downloads\\" for infile in glob.glob(os.path.join(path, "*.html")): markup = (infile) soup = BeautifulSoup(open(markup, "r").read()) with open("example.txt", "a") as myfile: myfile.write(soup.get_text()) myfile.close() Being as that seems to break the encoding, I thought I could pass latin-1 encoding, like so: soup = BeautifulSoup(open(markup, "r").read()) soup = soup.prettify("latin-1") But that gives me the error: Traceback (most recent call last): File "bsoup.py", line 12, in <module> myfile.write(soup.get_text()) AttributeError: 'bytes' object has no attribute 'get_text' Answer: `.prettify()` already returns bytes, so you just write that directly to the file, but you have to open that file in _binary_ mode (note the `'ab'` mode used below): soup = BeautifulSoup(open(markup, "r").read()) with open("example.txt", "ab") as myfile: myfile.write(soup.prettify('latin-1')) There is no need to call `myfile.close()`; the `with` statement already takes care of that. To save only the text, open the file in text mode (`'a'`) and specify the encoding to use on save: soup = BeautifulSoup(open(markup, "r").read()) with open("example.txt", "a", encoding='latin-1') as myfile: myfile.write(soup.get_text()) Now Python will automatically encode the unicode text to latin-1 for you. When you see something like `Ã¥` instead of `å`, then you are interpreting UTF-8 bytes as Latin-1. You may want to read up on Python and Unicode: * [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://joelonsoftware.com/articles/Unicode.html) by Joel Spolsky * The [Python Unicode HOWTO](http://docs.python.org/3/howto/unicode.html) * [Pragmatic Unicode](http://nedbatchelder.com/text/unipain.html) by Ned Batchelder
PIP install my OS project Question: I've created an open source project and tried to register it with PIP so people can use pip install. Unfortunately I can't seem to get it work. Here are the commands I've tried: Created a setup.py file: from distutils.core import setup setup(name='AyeGotchoPayCheque', version='.9', description='Payment Gateway Interface', author='Rico Cordova', author_email='[email protected]', url='http://www.python.org/sigs/ayegotchopaycheque-sig/', packages=['ayegotchopaycheque', 'ayegotchopaycheque'], ) Then I used the command `python setup.py register` and answered the questions. I've tried several other solutions and can't seem to get this working. Any suggestions? EDIT 1: It seems I've successfully registered my project with the wrong `name=AyeGotchoPayChecque`, note the extra "c". How can I "unregister" this project and re-register with the correct name? Answer: To "unregister", log into PyPI and go to the account page for the package you registered, then click on the "Remove this package completely" button. Then, you can reregister with the correct name. Don't forget to upload the project as well. I prefer to do it at the same time that I register: python setup.py egg_info -RDb "" sdist register upload Each time you upgrade your package's version number, re-run the above code, and PyPI will keep all versions of your package on the package's website.
Python HTTP Error 403 Forbidden Question: I am a bit of a Python Newbie, and I've just been trying to get some code working. Below is the code, and also the nasty error I keep getting. > > import pywapi import string > > google_result = pywapi.get_weather_from_google('Brisbane') > > print google_result > def getCurrentWather(): > city = google_result['forecast_information']['city'].split(',')[0] > print "It is " + > string.lower(google_result['current_conditions']['condition']) + " and > " + google_result['current_conditions']['temp_c'] + " degree > centigrade now in "+ city+".\n\n" > return "It is " + > string.lower(google_result['current_conditions']['condition']) + " and > " + google_result['current_conditions']['temp_c'] + " degree > centigrade now in "+ city > > def getDayOfWeek(dayOfWk): > #dayOfWk = dayOfWk.encode('ascii', 'ignore') > return dayOfWk.lower() > > def getWeatherForecast(): > #need to translate from sun/mon to sunday/monday > dayName = {'sun': 'Sunday', 'mon': 'Monday', 'tue': 'Tuesday', 'wed': > 'Wednesday', ' thu': 'Thursday', 'fri': 'Friday', 'sat': > 'Saturday', 'sun': 'Sunday'} > > forcastall = [] > for forecast in google_result['forecasts']: > dayOfWeek = getDayOfWeek(forecast['day_of_week']); > print " Highest is " + forecast['high'] + " and "+ "Lowest is " + > forecast['low'] + " on " + dayName[dayOfWeek] > forcastall.append(" Highest is " + forecast['high'] + " and "+ > "Lowest is " + forecast['low'] + " on " + dayName[dayOfWeek]) > return forcastall > Now is the error: > > Traceback (most recent call last): File > "C:\Users\Alex\Desktop\JAVIS\JAISS-master\first.py", line 5, in > <module> > import Weather File "C:\Users\Alex\Desktop\JAVIS\JAISS- > master\Weather.py", line 4, in > <module> > google_result = pywapi.get_weather_from_google('Brisbane') File > "C:\Python27\lib\site-packages\pywapi.py", line 51, in > get_weather_from_google > handler = urllib2.urlopen(url) File "C:\Python27\lib\urllib2.py", line > 126, in urlopen > return _opener.open(url, data, timeout) File > "C:\Python27\lib\urllib2.py", line 400, in open > response = meth(req, response) File "C:\Python27\lib\urllib2.py", line > 513, in http_response > 'http', request, response, code, msg, hdrs) File > "C:\Python27\lib\urllib2.py", line 438, in error > return self._call_chain(*args) File "C:\Python27\lib\urllib2.py", line > 372, in _call_chain > result = func(*args) File "C:\Python27\lib\urllib2.py", line 521, in > http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP > Error 403: Forbidden > Thanks for any help I can get! Answer: The 403 error doesn't come from your code but from Google. Google lets you know that you don't have permission to access the resource you were requesting, in this case the weather API, because it has been discontinued (403 technically stands for Forbidden, they could also have gone for 404 Not Found or 410 Gone). For more information, read <http://thenextweb.com/google/2012/08/28/did- google-just-quietly-kill-private-weather-api/> Other than that, your code is correct.
How to use a array of heaps in python Question: I need to create and use n heaps, I am trying to use heapq and is trying to push elements into a list of lists, where each element is to be considered a seperate heap. But its behaving weirdly. I just wanna push the elements 6 and 7 into my 3rd heap. but its getting pushed into all my heaps. any way out of this?? >>> test [[], [], [], []] >>> >>> heappush(test[2],6) >>> heappush(test[2],7) >>> test [[6, 7], [6, 7], [6, 7], [6, 7]] Answer: You seem to have created `test` something like this: >>> from heapq import heappush >>> test = [[]] * 4 >>> >>> heappush(test[2],6) >>> heappush(test[2],7) >>> test [[6, 7], [6, 7], [6, 7], [6, 7]] This creates four references to the _same_ list object. Use a list comprehension to make four distinct lists: >>> test = [[] for _ in range(4)] >>> heappush(test[2],6) >>> heappush(test[2],7) >>> test [[], [], [6, 7], []]
Draw a terrain with python? Question: I have a numpy 2d-array representing the geometrical height of a specific area where a street will be build. I can visualize this using `scipy.misc.toimage`. However I would like to get a simple 3D view of the area. Is there a simple way to plot or render this data as an 3d-image? Answer: Perhaps use matplotlib's [plot_surface](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#surface- plots) or [plot_wireframe](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#wireframe- plots): import matplotlib.pyplot as plt import numpy as np import mpl_toolkits.mplot3d.axes3d as axes3d np.random.seed(1) fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) N = 100 X, Y = np.meshgrid(np.arange(N), np.arange(N)) heights = np.sin(2*np.pi*np.sqrt(X**2+Y**2)/N) ax.plot_surface(X, Y, heights, cmap=plt.get_cmap('jet')) plt.show() ![enter image description here](http://i.stack.imgur.com/Ivf1y.png) These functions require three 2D-arrays: X, Y, Z. You have the heights, `Z`. To generate the standard `X` and `Y` locations associated with those `Z`s, you could use `np.meshgrid`.
How to convert country names to ISO 3166-1 alpha-2 values, using python Question: I have a list of countries like: countries=['American Samoa', 'Canada', 'France'...] I want to convert them like this: countries=['AS', 'CA', 'FR'...] Is there any module or any way to convert them? Answer: There is a module called [`pycountry`](https://pypi.python.org/pypi/pycountry). Here's an example code: import pycountry input_countries = ['American Samoa', 'Canada', 'France'] countries = {} for country in pycountry.countries: countries[country.name] = country.alpha2 codes = [countries.get(country, 'Unknown code') for country in input_countries] print codes # prints [u'AS', u'CA', u'FR']
Dynamically place legend in plot Question: I am creating plots in pyplot in Python. Each plot contains two or more subplots. I know I can statically place a legend in the plot by defining the parameter `loc`; however, my choice of location will sometimes cover the data in my plot. How would I place the legend dynamically in the location that interferes with the data the least? Answer: As tcaswell has already stated, use `ax.legend(loc='best')`: import matplotlib.pyplot as plt import numpy as np pi = np.pi sin = np.sin t = np.linspace(0.0, 2 * pi, 50) markers = ['+', '*', ',', ] + [r'$\lambda$'] phases = [0, 0.5] fig, ax = plt.subplots(len(phases)) for axnum, phase in enumerate(phases): for i, marker in enumerate(markers, 1): ax[axnum].plot(t, i*sin(2*t + phase*pi), marker=marker, label='$i,\phi = {i},{p}$'.format(i=i, p=phase)) ax[axnum].legend(loc='best', numpoints=1) plt.show() ![enter image description here](http://i.stack.imgur.com/SQjuJ.png) Interestingly, the location of the legend is not fixed. If you move the graph using the GUI, the location of the legend will readjust itself automatically.
python package import modules using __init__.py Question: I have made a package in the following structure: test.py pakcage1/ __init__.py module1.py module2.py In the `test.py` file, with the code from package1 import * what I want it to do is to from numpy import * from module1 import * from module2 import * **What should I write in`__init__.py` file to achieve this?** Currently in my `__init__.py` file I have from numpy import * __all__ = ['module1','module2'] and this doesn't give me what I wanted. In this way numpy wan't imported at all, and the modules are imported as import module1 rather than from module1 import * Answer: If you want this, your `__init__.py` should contain just what you want: from numpy import * from module1 import * from module2 import * When you do `from package import *`, it imports all names defined in the package's `__init__.py`. Note that this could become awkward if there are name clashes among the modules you import. If you just want convenient access to the functions in those modules, I would suggest using instead something like: import numpy as np import module1 as m1 import module2 as m2 That is, import the modules (not their contents), but under shorter names. You can then still access numpy stuff with something like `np.add`, which adds only three characters of typing but guards against name clashes among different modules.
Python: Connect 4 with TKinter Question: Alrighty I'm trying to implement a GUI for a game of Connect Four by using TKinter. Now I have the grid and everything set up what I'm having trouble with is getting the chip to show up on the board. Here is my output: ![enter image description here](http://i.stack.imgur.com/HNfyE.png) What I'm trying to do is make it so when I click one of the bottom column buttons a chip appears (and since this is connect four it should go from bottom to top) Here is my code: from Tkinter import * from connectfour import * from minimax import * from player import * import tkMessageBox class ConnectFourGUI: def DrawGrid(self): for i in range(0,self.cols+1): self.c.create_line((i+1)*self.mag,self.mag,\ (i+1)*self.mag,(self.rows+1)*self.mag) for i in range(0,self.rows+1): self.c.create_line(self.mag,(i+1)*self.mag,\ self.mag*(1+self.cols),(i+1)*self.mag) def __init__(self,wdw): wdw.title("Connect Four") self.mag = 60 self.rows = 6 self.cols = 7 self.c = Canvas(wdw,\ width=self.mag*self.cols+2*self.mag,\ height = self.mag*self.rows+2*self.mag,\ bg='white') self.c.grid(row=1,column=1,columnspan=2) rlabel=Label(root, text="Player1:") rlabel.grid(row=0,column=0) self.player1_type=StringVar(root) options= ["Human", "Random", "Minimax"] self.player1_type.set(options[2]) self.rowbox=OptionMenu(root, self.player1_type, *options) self.rowbox.grid(row=0, column=1) rlabel2=Label(root, text="Player2:") rlabel2.grid(row=0,column=2) self.player2_type=StringVar(root) self.player2_type.set(options[0]) self.rowbox=OptionMenu(root, self.player2_type, *options) self.rowbox.grid(row=0, column=3) begin=Button(root, text="Start", command=self.game_start) begin.grid(row=0, column=4) self.c.grid(row=1, column=0, columnspan=7) play_col=[] for i in range(self.cols): play_col.append(Button(root, text= "Col %d" %i, command=lambda col= i: self.human_play(col))) play_col[i].grid(row=10,column="%d"%i) ## self.DrawCircle(1,1,1) ## self.DrawCircle(2,2,1) ## self.DrawCircle(5,3,2) self.DrawGrid() self.brd = ConnectFour() def game_start(self): self.board=ConnectFour() print self.player1_type.get() print self.player2_type.get() if self.player1_type.get()=="Random": self.player1 = RandomPlayer(playernum=1) if self.player2_type.get()== "Random" or self.player2_type.get() == "Minimax": tkMessageBox.showinfo("Bad Choice", "You Have to choose At least 1 Human Player") else: self.player elif self.player1_type.get()=="Minimax": self.player1=MinimaxPlayer(playernum=2, ply_depth=4, utility=SimpleUtility(5,1)) if self.player2_type.get()== "Random" or self.player2_type.get() == "Minimax": tkMessageBox.showinfo("Bad Choice", "You Have to choose At least 1 Human Player") elif self.player1_type.get()=="Human": self.player1=Human(playernum=1) if self.player2_type.get()=="Human": self.player2=Human(playernum=2) elif self.player2_type.get()=="Random": self.player2=RandomPlayer(playernum=2) elif self.player2_type.get()=="Minimax": self.player2=MinimaxPlayer(playernum=2, ply_depth=4, utility=SimpleUitlity(5,1)) #self.currentplayer==1 #self.draw() def human_play(self, col): if self.player1_type.get()=="Human" and self.player2_type.get() =="Human": while True: self.DrawCircle(row,col,1) if self.brd.is_game_over() is None: self.DrawCircle(row,col,2) if self.brd.is_game_over() is None: pass else: print "Player 2 wins!" break else: print "Player 1 wins!" break def DrawCircle(self,row,col,player_num): if player_num == 1: fill_color = 'red' elif player_num == 2: fill_color = 'black' #(startx, starty, endx, endy) self.c.create_oval(col*self.mag,row*self.mag,(col+1)*self.mag,(row+1)*self.mag,fill=fill_color) root=Tk() ConnectFourGUI(root) root.mainloop() I know I'm supposed to call the DrawCircle function in the Human Play function, I'm just unsure as to how I'm supposed to set it all up. any advice as to how I could go about this would be greatly appreciated! Answer: Your code is depending on a few packages I don't have, so I can't be more specific, but the way I'd go about doing something like this is to track the X and Y coords of the chip works out the the row and column that it'd go into in the widget. You'll need to create a location object, a tuple maybe, and then a way to translate the location object into a drawable location. Then it's just a matter of incrementing either X or Y and detecting if there's a chip below it.
im trying to get proxies using regex python out of a web page Question: import urllib.request import re page = urllib.request.urlopen("http://www.samair.ru/proxy/ip-address-01.htm").read() re.findall('\d+\.\d+\.\d+\.\d+', page) i dont understand why it says: File "C:\Python33\lib\re.py", line 201, in findall return _compile(pattern, flags).findall(string) TypeError: can't use a string pattern on a bytes-like object Answer: import urllib import re page = urllib.urlopen("http://www.samair.ru/proxy/ip-address-01.htm").read() print re.findall('\d+\.\d+\.\d+\.\d+', page) Worked and gave me the result: ['056.249.66.50', '100.44.124.8', '103.31.250.115', ... **Edit** * This works for python2.7
Printing and editing multiple lists in python Question: Im trying to create a small text based game, and to achieve this I am created 20 lists, added 75 spaces to fill the lists, then printed each of the lists one at a time, all at the same time. I was hoping to then be able to edit the lists at certain positions so that when the lists were printed again, the console would display text where I placed it. This is what I came up with so far... The desired effect was to have the console print this: ============================ = = = TEXT ADVENTURE: = = WAR OF ZE MONSTERS = = = ============================ But instead I get this: =========================== I don't know exactly what is happening with my draw function or my write function but (to me) it would seem as if it should work. Any help would be amazing as I am relatively new to python. Thanks in advance! import time # # Joel Williams # # Purpose: Create a Working Text Engine # # start of classes class line(): def __init__(self): counter = 0 self.list = [] while (counter != lineSize): self.list.append(' ') counter = counter + 1 class cursor(): def __init__(self): self.cursorPosY = 0 self.cursorPosX = 0 self.cursorPos = [self.cursorPosY, self.cursorPosX] def setCursorPos(self,y,x): self.cursorPosY = y self.cursorPosX = x self.cursorPos = [self.cursorPosY, self.cursorPosX] # end of cursor class # start of peliminary declarations lineSize = 74 term = cursor() _1 = line() _2 = line() _3 = line() _4 = line() _5 = line() _6 = line() _7 = line() _8 = line() _9 = line() _10 = line() _11 = line() _12 = line() _13 = line() _14 = line() _15 = line() _16 = line() _17 = line() _18 = line() _19 = line() _20 = line() # end of preliminary declarations # start of preliminary functions def delLine(x): del x[:] counter = 0 x = [] while (counter != lineSize): x.append(' ') counter = counter + 1 def clear(): # clears all lists delLine(_1.list) delLine(_2.list) delLine(_3.list) delLine(_4.list) delLine(_5.list) delLine(_6.list) delLine(_7.list) delLine(_8.list) delLine(_9.list) delLine(_10.list) delLine(_11.list) delLine(_12.list) delLine(_13.list) delLine(_14.list) delLine(_15.list) delLine(_16.list) delLine(_17.list) delLine(_18.list) delLine(_19.list) delLine(_20.list) def clearLine(): if(term.cursorPosY == 0): delLine(_1.list) elif(term.cursorPosY == 1): delLine(_2.list) elif(term.cursorPosY == 2): delLine(_3.list) elif(term.cursorPosY == 3): delLine(_4.list) elif(term.cursorPosY == 4): delLine(_5.list) elif(term.cursorPosY == 5): delLine(_6.list) elif(term.cursorPosY == 6): delLine(_7.list) elif(term.cursorPosY == 7): delLine(_8.list) elif(term.cursorPosY == 8): delLine(_9.list) elif(term.cursorPosY == 9): delLine(_10.list) elif(term.cursorPosY == 10): delLine(_11.list) elif(term.cursorPosY == 11): delLine(_12.list) elif(term.cursorPosY == 12): delLine(_13.list) elif(term.cursorPosY == 13): delLine(_14.list) elif(term.cursorPosY == 14): delLine(_15.list) elif(term.cursorPosY == 15): delLine(_16.list) elif(term.cursorPosY == 16): delLine(_17.list) elif(term.cursorPosY == 17): delLine(_18.list) elif(term.cursorPosY == 18): delLine(_19.list) elif(term.cursorPosY == 19): delLine(_20.list) def draw(): # draws the lists # each lists is a line (Y) # each of the list's properties are the text (X) i1 = ''.join(_1.list) i2 = ''.join(_2.list) i3 = ''.join(_3.list) i4 = ''.join(_4.list) i5 = ''.join(_5.list) i6 = ''.join(_6.list) i7 = ''.join(_7.list) i8 = ''.join(_8.list) i9 = ''.join(_9.list) i10 = ''.join(_10.list) i11 = ''.join(_11.list) i12 = ''.join(_12.list) i13 = ''.join(_13.list) i14 = ''.join(_14.list) i15 = ''.join(_15.list) i16 = ''.join(_16.list) i17 = ''.join(_17.list) i18 = ''.join(_18.list) i19 = ''.join(_19.list) i20 = ''.join(_20.list) print i1 print i2 print i3 print i4 print i5 print i6 print i7 print i8 print i9 print i10 print i11 print i12 print i13 print i14 print i15 print i16 print i17 print i18 print i19 print i20 print i20 def write(str): # changes the lists c = 0 for i in str: if term.cursorPosX > lineSize: term.cursorPosX = 0 if term.cursorPosY > 19: term.cursorPosY = 0 else: term.cursorPosY = term.cursorPosY + 1 if term.cursorPosY is 0: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 1: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 2: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 3: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 4: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 5: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 6: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 7: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 8: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 9: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 10: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 11: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 12: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 13: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 14: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 15: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 16: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 17: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 18: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 elif term.cursorPosY is 19: _1.list[term.cursorPosX] = str[c] c = c + 1 term.cursorPosX = term.cursorPosX + 1 def writf(str,y,x): write(str) term.setCursorPos(y,x) def ask(x): i = raw_input(x) return i def wait(i): time.sleep(i) def cursorPos(y,x): term.setCursorPos(y,x) # end of preliminary functions # start of actual stuff # start of Main Stuff # start of game functions def startScreen(): writf('============================ ',8,10) writf('= = ',9,10) writf('= TEXT ADVENTURE: = ',10,10) writf('= WAR OF ZE MONSTERS = ',11,10) writf('= = ',10,10) writf('============================ ',12,10) draw() wait(5) # end of game functions def Main(): startScreen() Main() # end of Stuff # end of actual stuff Answer: If you want to manage a text based "screen", you would be better off using the curses module. This is designed exactly for what you want, though it is somewhat complicated. Also, you could make your program about eighteen times shorter by using more functions, because you are repeating the same code many times.
scikit-learn svm import error Question: I'm running [ Canopy ](https://enthought.com/products/canopy/) 64-bit on a mac. After installing scikit-learn (using the package manager), I tried to import svm, and got the following error. ImportError: dlopen(/Users/johnsaccount/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/sklearn/svm/liblinear.so, 2): Library not loaded: /System@rpath/libBLAS.dylib Referenced from: /Users/johnsaccount/Library/Enthought/Canopy_64bit/User/lib/python2.7/site- packages/sklearn/svm/liblinear.so Reason: image not found Any ideas on what might be the problem? Answer: Jsen, My apologies for this error, it was my mistake when building that egg. The update should now be available and fix that error (the fixed version is 0.13.1-3, both 0.13.1-1 and 0.13.1-2 are broken on os x).
restart apache every 12 hours using linux service and python file Question: Hi i want to use this for restart apache service every 12 hours and i put the file `apache_rest` in `/etc/init.d/apache_rest` i run but get some error : [root@localhost init.d]# service apache_rest start Starting server /etc/init.d/apache_rest: line 13: /sbin/start-stop-daemon: No such file or directory apache_rest file: #!/bin/bash WORK_DIR="/var/lib/foo" DAEMON="/usr/bin/python" ARGS="/home/lol/apache.py" PIDFILE="/var/run/foo.pid" USER="foo" case "$1" in start) echo "Starting server" mkdir -p "$WORK_DIR" /sbin/start-stop-daemon --start --pidfile $PIDFILE \ --user $USER --group $USER \ -b --make-pidfile \ --chuid $USER \ --exec $DAEMON $ARGS ;; stop) echo "Stopping server" /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose ;; *) echo "Usage: /etc/init.d/$USER {start|stop}" exit 1 ;; esac exit 0 and the python file : #!/usr/bin/python import os,signal,time,multiprocessing stop_event = multiprocessing.Event() def stop(signum, frame): stop_event.set() signal.signal(signal.SIGTERM, stop) if __name__ == '__main__': while not stop_event.is_set(): os.system('service httpd restart') time.sleep(43200) thanks ^_^ Answer: Simply add this line to root's crontab: 0 1,13 * * * /etc/init.d/httpd restart You don't need such a convoluted solution.
Releasing memory of huge numpy array in IPython Question: _UPDATE:- This problem solved itself after a machine reboot. Not yet able to figure out why this error was happening before._ I have a function that loads a huge numpy array (~ 980MB) and returns it. When I first start Ipython and call this function, it loads the array into the variable without any problem. But if I run the same command again, it exits raising a "Memory Error". I tried the following, del hugeArray Still the same error was occurring. I even tried the following del hugeArray gc.collect() gc.collect() Initially, `gc.collect()` returned 145 and the second call returned 48. But even after this when I call the function, it was still raising a Memory error. The only way I could load again was to restart ipython. Is there something I can do to free all memory in ipython, so that I don't have to restart it? \----------------Update Following is the output of `%whos` Variable Type Data/Info ------------------------------ gc module <module 'gc' (built-in)> gr module <module 'Generate4mRamp' <...>rom 'Generate4mRamp.pyc'> np module <module 'numpy' from '/us<...>ages/numpy/__init__.pyc'> plt module <module 'matplotlib.pyplo<...>s/matplotlib/pyplot.pyc'> Out of this, gr is my module containing the function which i used to load the data cube. \---------How to Reproduce the error The following simple function is able to reproduce the error. import numpy as np import gc def functionH(): cube=np.zeros((200,1024,1024)) return cube testcube=functionH() #Runs without any issue del testcube testcube=functionH() # Raises Memory Error del testcube gc.collect() gc.collect() testcube=functionH() # Still Raises Memory Error **This error is occurring only in Ipython. In simple python (>>>) after giving`del testcube`, there is no Memory Error.** Answer: Are you looking at the value? IPython caches output variables as e.g. `Out[8]`, so if you examine it, it will be kept in memory. You can do `%xdel testcube` to delete the variable and remove it from IPython's cache. Alternatively, `%reset out` or `%reset array` will clear either all your output history, or only references to numpy arrays.
Changes to a Gmail notification script Question: After a long search I've found [this python script](https://github.com/gevermann/gmail-iphone- push/blob/master/server/server.py) that does what I need in order to get a real time notification to my iOS app when a new email arrives. I usually write in Objective-c and this is the first time I'm dealing with `Python`. Before I'll try to setup and run the script I'd like to understand it a bit better. This is the part that I'm not sure about: # Because this is just an example, exit after 8 hours time.sleep(8*60*60) #finally: # Clean up. idler.stop() idler.join() M.close() # This is important! M.logout() My questions: 1. Should I comment out `time.sleep(8*60*60)` If I want to keep the connection active at all times? 2. What's the use for the Clean up section? Do I need it if I want to keep the connection? 3. Why `M.logout()` is important? The main question that includes all the above is What changes (if any) I need to do to this script in order for it to function without stoping or timing out. Thanks Answer: The script has started another thread, the actual work is done in this other thread. For some reason the main thread is left without anything to do, that's why the author has put the time.sleep(8*60*60) to occupy it for a while. If you want to keep the connection active at all times you need to uncomment the `try:`/`finally:`, see bellow. If you are new to python beware that indentation is used to define blocks of code. The cleanup part might actually not be useful if you don't plan to stop the program, but with the `try:`/`finally:` the cleanup code will be executed even if you stop the program with Ctrl+C. Not tested: # Had to do this stuff in a try-finally, since some testing # went a little wrong..... try: # Set the following two lines to your creds and server M = imaplib2.IMAP4_SSL("imap.gmail.com") M.login(USER, PASSWORD) # We need to get out of the AUTH state, so we just select # the INBOX. M.select("INBOX") numUnseen = getUnseen() sendPushNotification(numUnseen) #print M.status("INBOX", '(UNSEEN)') # Start the Idler thread idler = Idler(M) idler.start() # Sleep forever, one minute at a time while True: time.sleep(60) finally: # Clean up. idler.stop() idler.join() M.close() # This is important! M.logout()
Python non-int float Question: Alright so I have beat my head over my desk for a few days over this one and I still cannot get it I keep getting this problem: Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 44, in <module> File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 35, in main File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in __init__ builtins.TypeError: can't multiply sequence by non-int of type 'float' over and over. I think I have hit the wall and really I have done a ecent amount of looking and testing but if anyone could point me in teh right direction it would be greatly appreciated. from math import pi, sin, cos, radians def getInputs(): a = input("Enter the launch angle (in degrees): ") v = input("Enter the initial velocity (in meters/sec): ") h = input("Enter the initial height (in meters): ") t = input("Enter the time interval between position calculations: ") return a,v,h,t class Projectile: def __init__(self, angle, velocity, height): self.xpos = 0.0 self.ypos = height theta = pi *(angle)/180 self.xvel = velocity * cos(theta) self.yvel = velocity * sin(theta) def update(self, time): self.xpos = self.xpos + time * self.xvel yvel1 = self.yvel - 9.8 * time self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 self.yvel = yvel1 def getY(self): "Returns the y position (height) of this projectile." return self.ypos def getX(self): "Returns the x position (distance) of this projectile." return self.xpos def main(): a, v, h, t = getInputs() cball = Projectile(a, v, h) zenith = cball.getY() while cball.getY() >= 0: cball.update(t) if cball.getY() > zenith: zenith = cball.getY() print ("/n Distance traveled: {%0.1f} meters." % (cball.getY())) print ("The heighest the cannon ball reached was %0.1f meters." % (zenith)) if __name__ == "__main__": main() Answer: Your input functions return strings, not numeric types. You need to convert them to integers or floats first as appropriate. I think the particular error you're seeing is when you try to calculate theta. You multiply pi (a floating-point number) by angle (which holds a string). The message is telling you that you can't multiply a string by a float, but that you could multiply a string by an int. (E.g. `"spam" * 4` gives you `"spamspamspamspam"`, but `"spam" * 3.14` would make no sense.) Unfortunately, that's not a very helpful message, because for you it's not pi that's the wrong type, but angle, which should be a number. You should be able to fix this by changing getInputs: def getInputs(): a = float(input("Enter the launch angle (in degrees): ")) v = float(input("Enter the initial velocity (in meters/sec): ")) h = float(input("Enter the initial height (in meters): ")) t = float(input("Enter the time interval between position calculations: ")) return a,v,h,t * * * I should also note that this is an area where Python 2.* and Python 3.* have different behaviour. In Python 2.* , `input` read a line of text and then evaluated it as a Python expression, while `raw_input` read a line of text and returned a string. In Python 3.* , `input` now does what `raw_input` did before - reads a line of text and returns a string. While the 'evaluate it as an expression' behaviour could be helpful for simple examples, it was also dangerous for anything but a trivial example. A user could type in any expression at all and it would be evaluated, which could do all sorts of unexpected things to your program or computer.
Python, using ctypes to create C++ class wrapper Question: I'm well aware that there is no standard ABI for c++, so this is what I did: //trialDLL.h #ifndef TRIALDLL_H_ #define TRIALDLL_H_ class MyMathFuncs { private: double offset; public: MyMathFuncs(double offset); ~MyMathFuncs(); double Add(double a, double b); double Multiply(double a, double b); double getOffset(); }; #ifdef __cplusplus extern "C"{ #endif #ifdef TRIALDLL_EXPORT #define TRIALDLL_API __declspec(dllexport) #else #define TRIALDLL_API __declspec(dllimport) #endif TRIALDLL_API MyMathFuncs* __stdcall new_MyMathFuncs(double offset); TRIALDLL_API void __stdcall del_MyMathFuncs(MyMathFuncs *myMath); TRIALDLL_API double __stdcall MyAdd(MyMathFuncs* myMath, double a, double b); #ifdef __cplusplus } #endif #endif And the definition .cpp: (Other class functions' definitions are omitted) //trialDLL.cpp #include "trialDLL.h" MyMathFuncs* __stdcall new_MyMathFuncs(double offset) { return new MyMathFuncs(offset); } void __stdcall del_MyMathFuncs(MyMathFuncs *myMath) { myMath->~MyMathFuncs(); } double __stdcall MyAdd(MyMathFuncs *myMath, double a, double b) { return myMath->Add(a, b); } // class functions double MyMathFuncs::Add(double a, double b) { return a+b+ this->offset; } And I build this into a dll and named it trialDLL3.dll. Then in python, I wrote a module as: #trialDLL3.py import ctypes from ctypes import WinDLL class MyMath(object): def __init__(self, offset): self.FunMath = WinDLL('trialDLL3.dll') self.FunMath.new_MyMathFuncs.argtypes = [ctypes.c_double] self.FunMath.new_MyMathFuncs.restype = ctypes.c_void_p self.FunMath.MyAdd.argtypes = [ctypes.c_void_p, \ ctypes.c_double, ctypes.c_double] self.FunMath.MyAdd.restype = ctypes.c_double self.obj = self.FunMath.new_MyMathFuncs(offset) def FunAdd(self, a, b): self.FunMath.MyAdd(self.obj, a, b) def delete(): self.FunMath.del_MyMathFuncs() After all these, strange things happened. In the IDLE python shell, I did: theMath = MyMath(3.3) #create the instance theMath.FunAdd(3.3, 3.3) #call the function The second line returned None instead of 9.9. Then I tried another way round, putting this line in the shell: theMath.FunMath.MyAdd(theMath.obj, 3.3 ,3.3) And this line returns me an unsurprising 9.9, but surprising when compared to the last result None. Shouldn't these two lines identical? And I decided to run all those lines explicitly in python shell and see what can go wrong, writing: (excluding the imports) loadedDLL = WinDLL('trialDLL3.dll') loadedDLL.new_MyMathFuncs.argtypes = [ctypes.c_double] loadedDLL.new_MyMathFuncs.restype = ctypes.c_void_p loadedDLL.MyAdd.argtypes = [ctypes.c_void_p, \ ctypes.c_double, ctypes.c_double] loadedDLL.MyAdd.restype = ctypes.c_double obj = loadedDLL.new_MyMathFuncs(3.3) FunMath.MyAdd(obj, 3.3, 3.3) All these lines finally returned 9.9. Aren't these lines identical to the two lines if the trialDLL3.py module is imported? theMath = MyMath(3.3) #create the instance theMath.FunAdd(3.3, 3.3) #call the function If they are the same deal, why the two line class version returns None and the explicit way return expected 9.9? Thanks in advance! Answer: Everything works fine... but you forgot to pass along the return value of the C function in the method MyMath.FunAdd! def FunAdd(self, a, b): return self.FunMath.MyAdd(self.obj, a, b) ^^^^^^
How to get a row from coo_matrix as a dense vector in Python? Question: I'm new to Python and could you help me about some basic sparse matrix operation: 1. How to extract a dense row vector from a sparse matrix without make the whole matrix dense beforehand? `coo_matrix.getrow()` only returns a sparse representation 2. How to extract a proportion of rows (say, 80%) randomly from a sparse matrix? I need to use them as training data and the proportion left as test data. Thanks in advance! Answer: 1. `coo_matrix.getrow().todense()` 2. Use a different sparse representation that supports slicing, for example `csr_matrix`. For sparse matrix A, A[i] will give the ith row. For example: In [9]: from random import sample In [10]: A = csr_matrix(...) In [11]: n = A.shape[0] In [12]: indices = sample(range(n), 4*n/5) In [13]: A[indices].todense()
Restrictions in terms of using external libraries (Python) in a Storm Bolt Question: I want to implement a Bolt (<https://github.com/nathanmarz/storm>) that does some heavy processing on a tuples using scikit Machine Learning API (<http://scikit-learn.org/>) For example - from sklearn import decomposition from sklearn import datasets trans_corpus = vectorizer.fit_transform(corpus) tfidf = text.TfidfTransformer().fit_transform(trans_corpus) ... ... Is this possible ? Is having sklearn and all it's dependencies installed on each node in the cluster enough? Answer: Theoretically, it should be possible unless there is something really weird about scikit I don't know. You just need to build your topologies such that you can write your bolts in Python, which I suspect you already know is possible and there are plenty of examples.
Python : efficient bytearray incrementation Question: How to iterate all possible values of `bytearray of length = n` in Python ? in worst case `n <= 40bytes` For example, iterate for `n = 4` : 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000010 . . . . 11111111 11111111 11111111 11111110 11111111 11111111 11111111 11111111 Answer: You can use `itertools.product`: In [11]: from itertools import product In [15]: for x in product('01',repeat=4): #for your n=4 change repeat to 32 print "".join(x) ....: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
Python - variable is getting set to 0 and can't figure out why Question: Okay, so I'm making a little game with pygame and building the map by generating tiles to a multidimensional array. In order to do that I'm using two for loops. def create(this, t): if t == "grasslands": for j in range(0, this.numRows): for i in range(0, this.numColumns): this.column.append(this.Tile("grass", j * this.tileWidth, i * this.tileHeight)) this.row.append(this.column) The value for **j * this.tileWidth** is getting passed into the Tile initialization correctly. After though the **column[whatever].x** value is still 0. The **y** value gets set just fine, and if I use **i** or any other value instead of **j** things work just fine. Is this something I'm doing wrong or something wonky with Python? **_mapgen.py_** import pygame from sprite import * from assets import * class mapG: def __init__(this, resw, resh): this.numRows = 3 this.numcolumns = 3 this.tileWidth = 128 this.tileHeight = 128 this.row = [] this.column = [] this.width = this.numRows * this.tileWidth this.height = this.numcolumns * this.tileHeight def create(this, t): if t == "grasslands": for j in range(0, this.numRows): for i in range(0, this.numcolumns): this.column.append(this.Tile("grass", j * this.tileWidth, i * this.tileHeight)) this.row.append(this.column) def tileAt(this, x, y): pass def moveRight(this): for j in range(0,this.numRows): for i in range(0, this.numcolumns): this.row[j][i].incX(1) def Update(this, src): for j in range(0,this.numRows): for i in range(0, this.numcolumns): this.row[j][i].Update(src) print(this.row[j][i].y, this.row[j][i].x) class Tile: def __init__(this, name, xpos, ypos): this.y = ypos this.x = xpos this.image = assets.tile[name + ".png"] this.sprite = sprite(this.image, this.x, this.y, 100, 100) def incX(this, amount): this.sprite.IncX(amount) def decX(this, amount): this.sprite.DecX(amount) def incY(this, amount): this.sprite.IncY(amount) def decY(this, amount): this.sprite.DecY(amount) def Update(this, src = None): if src != None: this.sprite.Update(src) **_sprite.py_** import pygame import assets class sprite: def __init__(this, image, xpos, ypos, width = None, height = None): this.image = image this.x = xpos this.y = ypos this.width = width this.height = height if this.width != None and this.height != None: this.image = pygame.transform.scale(image, (this.width,this.height)) def GetPos(this): return (this.x, this.y) def IncX(this, amount): this.x += amount def IncY(this, amount): this.y += amount def DecX(this, amount): this.x -= amount def DecY(this, amount): this.y -= amount def Update(this, src = None): if src != None: src.blit(this.image, this.GetPos()) Answer: I believe the issue you have comes from your use of the `this.column` variable in the `create` method. You're only creating one column list (in `__init__`) and then reusing it for all the columns of your map. This won't work. Your `this.row` list ends up having multiple references to the same column list, which ends up containing all of the `Tile` objects you create. You only see some of them later, since your iteration code uses predefined dimensions, rather than actually iterating over the whole of the lists. To understand this, try to imagine how the iteration progresses for a 2x2 grid (ignoring the tile dimensions). I'm putting each `i` and `j` value on it's own line to show how it progresses, and giving the values of `row` and `columns` after each step side: j=0: i=0: column.append(Tile(i, j)) # column is [Tile(0, 0)] # row is [] i=1: column.append(Tile(i, j)) # column is [Tile(0, 0), Tile(0, 1)] # row is [] row.append(column) # column is [Tile(0, 0), Tile(0, 1)] # row is [[Tile(0, 0), Tile(0, 1)]] j=1: # column is not reset! i=0: column.append(Tile(i, j)) # column is [Tile(0, 0), Tile(0, 1), Tile(1, 0)] # row is [[Tile(0, 0), Tile(0, 1), Tile(1, 0)]] i=1: column.append(Tile(i, j)) # column is [Tile(0, 0), Tile(0, 1), Tile(1, 0), Tile(1, 1)] # row is [[Tile(0, 0), Tile(0, 1), Tile(1, 0), Tile(1, 1)]] row.append(column) # column is [Tile(0, 0), Tile(0, 1), Tile(1, 0), Tile(1, 1)] # row is [[Tile(0, 0), Tile(0, 1), Tile(1, 0), Tile(1, 1)], # [Tile(0, 0), Tile(0, 1), Tile(1, 0), Tile(1, 1)]] The `row` list contains two references to the same `column` list of four tiles. Your code had intended to add the first two `Tile(0, 0)` and `Tile(0,1)` to the first column, then the last two tiles `Tile(1, 0)` and `Tile(1, 1)` to the second column. But because the same list was used both times, you end up with all the values together, and then the whole bunch repeated. When you iterate, you're only seeing the repeated values on the left part of the diagram above. Here's how to fix it: def create(this, t): if t == "grasslands": for j in range(0, this.numRows): column = [] # Create a new list! This is the key! for i in range(0, this.numColumns): column.append(this.Tile("grass", j * this.tileWidth, i * this.tileHeight)) this.row.append(column) You can get rid of the line in the constructor that initializes `self.column` too. It's only needed temporarily, so there's no need to use an instance variable.
Ascii codec cannot decode HTML when saving to file in python Question: I have a text that is part of html. I would like to save it to a file. This works fine in debug mode in Eclipse, but fails on runtime from shell. I am using a short example of html that fails. xx = '<input type="hidden" name="charset_test" value="€,´,€,´,水,Д,Є" />' with codecs.open('myfile.htm'), 'wb', encoding="utf-8") as output: output.write(data) and I get: Exception 'ascii' codec can't decode byte 0xe2 in position XXX: ordinal not in range(128) where XXX is the position in the relevant file of the "strange" symbols, such as the EURO sign. Why is this working from Eclipse and not from shell? How do I solve this? I tried HTMLParser.HTMLParser().unescape() unquote() unicode() Nothing worked... Answer: The following code works for me... # coding=utf-8 import codecs data = '<input type="hidden" name="charset_test" value="€,´,€,´,水,Д,Є" />' with codecs.open('myfile.htm', 'wb', encoding="utf-8") as output: output.write(data.decode('utf-8')) ...but if the source data is already UTF-8 encoded, and you also want to write UTF-8 data, there's no need to decode it to a Python `unicode` object, then re-encode back to UTF-8. You can just do... # coding=utf-8 data = '<input type="hidden" name="charset_test" value="€,´,€,´,水,Д,Є" />' with open('myfile.htm', 'wb') as output: output.write(data)
Read numeric value from txt. file and compare it to condition Python Question: I'm new to Python and working on final project for my degree. I want to write a Python script which will read numeric value (like: 21, 23, 28 etc.) and compare it to value in the script. If the value matches it should execute another python script. Everything seem to work correctly, but the red value from file make no change in conditions matching. The script every time executes statement ELSE instead of IF while the condition is really true. Here is my code: import time import sys import os check_period = 2 fo = open("/home/pi/thermometer1.txt", "r+") str = fo.readline(); fo.close() while True: fo = open("/home/pi/thermometer1.txt", "r+") str = fo.readline(); if str < 25 : os.system("python /home/pi/servo/servo1/servo6.py") print str fo.close() else: os.system("python /home/pi/servo/servo1/servo1.py") print str fo.close() time.sleep(check_period) One more question would be how to edit this script which will compare one .txt file with numeric value like. 23 to other .txt file with numeric value like. 27 and if condition is met execute another python script (similar like the code above). Thanks in advance for all comments. Answer: Reading from the file you get strings, not integers. Since they're different (non-comparible) types, any comparison you do result in a consistent, but arbitrary value based on the types1. Apparently, strings are considered greater than integers (for Cpython -- Other implementations might behave differently). You need to construct an integer out of your string instead: int_from_str = int(fo.readline()) * * * While we're at it, there are much better ways to iterate over a file: with open("/home/pi/thermometer1.txt") as fin: for line in fin: int_from_str = int(fin) ... 1On python3.x, any comparison other than `==` will raise an exception.
Python: loop through several csv files Question: I was wondering if anybody knew how I could change a script in Python so it goes through a folder containing csv files and takes them in groups of three. The script is working when I type the file names in the command line, but I've got lots of files, so that would take forever. It looks like this now: resultsdir = "blah" #filename1=sys.argv[1] #filename2=sys.argv[2] #filename3=sys.argv[3] file1 = open(resultsdir+"/"+filename1+".csv") file2 = open(resultsdir+"/"+filename2+".csv") file3 = open(resultsdir+"/"+filename3+".csv") I'm a complete beginner, I hope I've been able to explain what I want. Cheers for any help! Answer: You could use the `glob` module (<http://docs.python.org/3.3/library/glob.html>) to get all `.csv` files in a directory and open them then. **Example:** import glob resultsdir = "blah" files = sorted(glob.glob(resultsdir+'/*.csv')) while len(files) >= 3: file1 = open(files.pop(0)) file2 = open(files.pop(0)) file3 = open(files.pop(0)) # Do something # if the number of files can't be divided by 3 do something # with the 1 or 2 files which are left **Edit:** Changed `files.pop()` to `files.pop(0)` to get the files from the first to the last and not from the last to the first file.
devappserver2, remote_api, and --default_partition Question: To access a remote datastore locally using the original dev_appserver I would set --default_partition=s as mentioned [here](http://stackoverflow.com/questions/9280613/badrequesterror-app- smyapphr-cannot-access-app-devmyapphrs-data-why/9281772#9281772) In March 2013 Google made devappserver2 the default development server, and it does not support --default_partition resulting in the original, dreaded: BadRequestError: app s~appname cannot access app dev~appname's data It appears like the first few requests are served correctly with os.environ["APPLICATION_ID"] == 's~appname' Then a subsequent request results in a call to /_ah/warmup and then os.environ["APPLICATION_ID"] == 'dev~appname' The docs specifically mention related topics but appear geared to dev_appserver [here](https://developers.google.com/appengine/docs/python/tools/devserver) > Warning! Do not get the App ID from the environment variable. The > development server simulates the production App Engine service. One way in > which it does this is to prepend a string (dev~) to the APPLICATION_ID > environment variable, which is similar to the string prepended in production > for applications using the High Replication Datastore. You can modify this > behavior with the --default_partition flag, choosing a value of "" to match > the master-slave option in production. Google recommends always getting the > application ID using the get_application_id() method, and never using the > APPLICATION_ID environment variable. Answer: You can do the following dirty little trick: from google.appengine.datastore.entity_pb import Reference DEV = os.environ['SERVER_SOFTWARE'].startswith('Development') def myApp(*args): return os.environ['APPLICATION_ID'].replace("dev~", "s~") if DEV: Reference.app = myApp
How to subclass Clock in Pyglet? Question: I want to subclass Clock class of pyglet.clock module, but I have some troubles when I use schedule_interval: The following code doesn't print anything and the object c looks like if not ticked at all: #!/usr/bin/env python # -*- coding: utf-8 -*- import pyglet class Clock(pyglet.clock.Clock): def __init__(self): super(Clock, self).__init__() class Test(object): def update(self, dt): print dt w = pyglet.window.Window() @w.event def on_draw(): w.clear() t = Test() c = pyglet.clock.Clock() c.schedule_interval(t.update, 1/60.0) pyglet.app.run() But the next works fine. #!/usr/bin/env python # -*- coding: utf-8 -*- import pyglet class Clock(pyglet.clock.Clock): def __init__(self): super(Clock, self).__init__() pyglet.clock.set_default(self) class Test(object): def update(self, dt): print dt w = pyglet.window.Window() @w.event def on_draw(): w.clear() t = Test() c = Clock() c.schedule_interval(t.update, 1/60.0) pyglet.app.run() The only difference is the pyglet.clock.set_default(self) sentence in the constructor method of Clock. I think this is not clear or, at least, is not the best way of subclassing pyglet.clock.Clock to have your own derived Clock class. **The questions:** There is some way to set the default clock automatically with Pyglet? There is a solution more elegant or pythonic? Is possible do this without the pyglet.clock.set_default(self) line? Answer: I haven't used pyglet, but here's my guess: You're almost there. The reason your first implementation probably didn't work is because of these lines: c = pyglet.clock.Clock() c.schedule_interval(t.update, 1/60.0) Here, you are creating a new Clock instance and are scheduling a callback on it. However, at no point are you actually associating that instance of a clock with pyglet. So, when you run... pyglet.app.run() ...you never actually told pyglet about the new clock instance `c`. Instead, pyglet will use an instance that it made itself. Check out this [source code for pyglet from the clock module](https://code.google.com/p/pyglet/source/browse/pyglet/clock.py)...: # Default clock. _default = Clock() def set_default(default): '''Set the default clock to use for all module-level functions. By default an instance of `Clock` is used. :Parameters: `default` : `Clock` The default clock to use. ''' global _default _default = default def get_default(): '''Return the `Clock` instance that is used by all module-level clock functions. :rtype: `Clock` :return: The default clock. When pyglet starts up, it creates its own instance of the clock (called `_default`). If you want to use your own, you need to use `set_default()` to replace it. Therefore, to fix your first piece of code, you probably would need to do one of the following: c = pyglet.clock.get_default() c.schedule_interval(t.update, 1/60.0) ...or... c = pyglet.clock.Clock() pyglet.clock.set_default(c) c.schedule_interval(t.update, 1/60.0) The second example above is pointless: pyglet already gives you an instance of Clock, so you'd really just duplicating something that pyglet has already done for you. Either way though, you end up scheduling the callback on the clock **that pyglet is using**. So, it should now make sense that, yes, you do need to call `set_default()`. This is how you tell pyglet to use your object rather than the one it makes by default. Now, you **could** conceivably put this `set_default()` call where you currently have it (in the constructor). However, it probably makes more sense to do this... class Clock(pyglet.clock.Clock): def __init__(self): super(Clock, self).__init__() ... c = Clock() pyglet.clock.set_default(c) **Edit** : In response to the question of why you would do this outside the constructor: First, as a general rule of thumb, a constructor should only be used to construct the object. By adding set_default, you are not only constructing the object, you are also changing the state of some other entity (the pyglet.clock module). This can cause confusion, as I will show below. Assume I wrote code that looked like this... c = MyClock() c2 = UnpausedClock() In this example, I have previously implemented two different clock types: `NewClock` and `UnpausedClock`. `UnpausedClock` will only consider time to be passing when the game is unpaused. If I put `set_default()` in the constructor of these two new classes, then `UnpausedClock` would become the new default clock (which I don't want). By NOT putting `set_default()` in the constructor, and instead doing the following: c = MyClock() c2 = UnpausedClock() pyglet.clock.set_default(c) My code is more explicit, and less confusing. Of course, the code will work either way, but I feel that having the set_default OUTSIDE the constructor gives you more flexibility to use the class as you need to later on.
python feedparser ImportError: No module named feedparser Question: I receive an error when I attempt to include the feedparser library into the interactive Python environment: >>>> import feedparser Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named feedparser This also happens with BeautifulSoup and pydelicious. Why am I getting this error? Using OS X 10.8.3, which include the following files in the /usr/bin directory: $ ll python* -rwxr-xr-x 2 root wheel 58896 Mar 17 20:55 python -rwxr-xr-x 6 root wheel 925 Nov 16 10:30 python-config lrwxr-xr-x 1 root wheel 75 Nov 16 10:30 python2.5 -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5 lrwxr-xr-x 1 root wheel 82 Nov 16 10:30 python2.5-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5-config lrwxr-xr-x 1 root wheel 75 Nov 16 10:30 python2.6 -> ../../System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 lrwxr-xr-x 1 root wheel 82 Nov 16 10:30 python2.6-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6-config lrwxr-xr-x 1 root wheel 75 Nov 16 10:30 python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 lrwxr-xr-x 1 root wheel 82 Nov 16 10:30 python2.7-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config -rwxr-xr-x 2 root wheel 58896 Mar 17 20:55 pythonw lrwxr-xr-x 1 root wheel 76 Nov 16 10:30 pythonw2.5 -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/pythonw2.5 lrwxr-xr-x 1 root wheel 76 Nov 16 10:30 pythonw2.6 -> ../../System/Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw2.6 lrwxr-xr-x 1 root wheel 76 Nov 16 10:30 pythonw2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7 Python's location: $ which python /usr/bin/python Python's version: $ python -V Python 2.7.2 It was probably unnecessary, but I installed Python with Homebrew: $ brew install python Which installed these files: $ brew list python /usr/local/Cellar/python/2.7.4/bin/smtpd2.py /usr/local/Cellar/python/2.7.4/bin/smtpd2.7.py /usr/local/Cellar/python/2.7.4/bin/smtpd.py /usr/local/Cellar/python/2.7.4/bin/pythonw2.7 /usr/local/Cellar/python/2.7.4/bin/pythonw2 /usr/local/Cellar/python/2.7.4/bin/pythonw /usr/local/Cellar/python/2.7.4/bin/python2.7-config /usr/local/Cellar/python/2.7.4/bin/python2.7 /usr/local/Cellar/python/2.7.4/bin/python2-config /usr/local/Cellar/python/2.7.4/bin/python2 /usr/local/Cellar/python/2.7.4/bin/python-config /usr/local/Cellar/python/2.7.4/bin/python /usr/local/Cellar/python/2.7.4/bin/pydoc2.7 /usr/local/Cellar/python/2.7.4/bin/pydoc2 /usr/local/Cellar/python/2.7.4/bin/pydoc /usr/local/Cellar/python/2.7.4/bin/pip-2.7 /usr/local/Cellar/python/2.7.4/bin/pip /usr/local/Cellar/python/2.7.4/bin/idle2.7 /usr/local/Cellar/python/2.7.4/bin/idle2 /usr/local/Cellar/python/2.7.4/bin/idle /usr/local/Cellar/python/2.7.4/bin/easy_install-2.7 /usr/local/Cellar/python/2.7.4/bin/easy_install /usr/local/Cellar/python/2.7.4/bin/2to3-2.7 /usr/local/Cellar/python/2.7.4/bin/2to3-2 /usr/local/Cellar/python/2.7.4/bin/2to3 /usr/local/Cellar/python/2.7.4/Build Applet.app/Contents/ (8 files) /usr/local/Cellar/python/2.7.4/Frameworks/Python.framework/ (4858 files) /usr/local/Cellar/python/2.7.4/IDLE.app/Contents/ (8 files) /usr/local/Cellar/python/2.7.4/Python Launcher.app/Contents/ (17 files) /usr/local/Cellar/python/2.7.4/share/man/ (3 files) /usr/local/Cellar/python/2.7.4/share/python/ (317 files) Then I installed feedparser: $ pip install feedparser Which resulted in these files: $ ll /usr/local/lib/python2.7/site-packages/f* -rw-r--r-- 1 foobar admin 166583 Apr 24 20:16 /usr/local/lib/python2.7/site-packages/feedparser.py -rw-r--r-- 1 foobar admin 138040 Apr 24 20:16 /usr/local/lib/python2.7/site-packages/feedparser.pyc I was hoping to avoid these sorts of problems by using Homebrew (which has worked well with other libraries). What am I missing? Answer: If your Python is at `/usr/bin/python`, then you are not using the Homebrew- built Python, but the OS X default one. (Also note the version number discrepancies in your output.) So any package that you install with `pip` will be installed into the Homebrew space, but will not be visible to the OS X-supplied Python installation. (OS X does not supply `pip`, so that's quite like the Homebrew one.) The fix for you is quite likely to update your path to have `/usr/local/bin` come before `/usr/bin`.
Controlling MDrive 23 with Python under Linux Question: MDrive 23 motor takes commands from a terminal, and I got it to work with screen program: screen /dev/ttyUSB0 Is this is called a serial terminal? I'm unfamiliar with the details of the connection, but feel like I should be able to use PySerial to send the commands. I tried: import serial ser = serial.Serial('/dev/ttyUSB0', 19200) ser.isOpen() # Returns True ser.write('ma 100000\r\n') # Does nothing... ser.inWaiting() # Returns 0 ser.close() I didn't know how to set the other init variables, like: parity = serial.PARITY_ODD, stopbits = serial.STOPBITS_TWO bytesize = serial.SEVENBITS I'm going to try guessing some values next... The documentation is lame, but it mentions MODBUS TCP and Mcode. How do I set these and are there any syntax errors in my snippet? I know how to send arguments to the Serial object, but I do not know what values are typical. Answer: The other parameters to the Serial constructor are set in a similar way as port and baudrate: ser = serial.Serial(port = '/dev/ttyUSB0', baudrate=19200, bytesize=serial.SEVENBITS, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO) ser.write('whatever') ser.flush() # wait for data to be written ser.close() * * * Edit: It [seems](http://motion.schneider- electric.com/support/knowledge_base.html) the default settings are 9600 baud, 8 bits, no parity and 1 stop bit. In addition no flow-control is used. That would be equivalent to: ser = serial.Serial(port = '/dev/ttyUSB0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False, rtscts=False, dsrdtr=False) As all values, except port, are set to their defaults, you may use: ser = serial.Serial(port = '/dev/ttyUSB0') The last thing to worry about is which (read) timeout to set. This is measured/set in seconds (float allowed) and sets how long a read() command will block before returning what has been read.
Using the twitter API and Python to obatain retweeter's id Question: I have an issue that has been bothering for a while now, and which I have tried really hard to fix but have found no solution. So I'm doing an internship doing research on complex networks, nothing business-oriented, it's mostly physics and network theory research that they are doing. So what I'm doing is writing scripts for them to obtain data from twitter and tumblr (such as friend lists, and retweets) and then then graphing the user-to-user relations. Anyways, going straight to my problem, I have already written my script pretty much, mainly using the twitter-python wrapper. However, none of the wrappers for python has any way of using the GET statuses/retweets/:id which returns the 100 first retweeter's ids. I've looked through all different twitter libraries for python and could not find anything. I found tweety for MATLAB but I'm using Ubuntu and it hasn't been easy to obtain. So my question is, how can I implement this API myself, without a wrapper? is there any wrapper, even in another language that you guys would know allows me to do this? I wouldn't mind getting the retweet information in a file and then using my python script to go over it and get the information I need. Thank you very much! This is the resource I wanna use: <https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid> EDIT: So with tweepy this is what I'm trying to do auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) tweet = auth.retweets(TWEET_ID) print json.dumps(tweet, indent=1) Answer: Looks like [tweepy](http://pythonhosted.org/tweepy/html/index.html) should work for you. See [docs](http://pythonhosted.org/tweepy/html/api.html?highlight=retweet#API.retweets) and [source](https://github.com/tweepy/tweepy/blob/master/tweepy/api.py#L124). Example: import tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(key, secret) api = tweepy.API(auth) public_tweets = api.search("stackoverflow") for tweet in public_tweets: print api.retweets(tweet.id) Hope that helps.
Error using etree in lxml Question: I want to use xpath in python . I tried import xml.etree.ElementTree as ET Since this library has limited usage I had to use lxml after a long session of search on google. I had several problems during installation and finally i installed lxml but when i use from lxml import etree it throws back an error as below. could you please tell me the solution to this problem!!! Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from lxml import etree ImportError: DLL load failed: %1 is not a valid Win32 application. Can any1 tell me what the problem would be?? Thanks for assistance!! Answer: I solved this by downloading the 64-bit version of lxml here: <https://pypi.python.org/pypi/lxml/3.4.1> lxml-3.4.1.win-amd64-py2.7.exe It's the only one that worked to solve the win32 error. You might want to destroy the old version of lxml before you do this.
How to flag end of loop over dictionary with two int's tuple as key - combination-like loop needed Question: i have in memory a dictionary with the following pattern: value_refs[tuple([a,b])] = some float value the dictionary is a pool of all the possible combinations of the values of 4000 references, previously computated (some millions). ex: ... value_refs[1,4] =0,76543 value_refs[1,5] =0,89734 #i want this value, since it is the bigger of all the second ref's, # related with the ref. 1 (first tuple in the key) ... value_refs[1,4000] =0,77543 ... ... value_refs[4000,30] =0,76543 value_refs[4000,31] =1,89734 # I want this value, since it is the bigger of all the second # references, related with the ref. 4000 (first tuple in the key) value_refs[4000,32] =0,77543 The problem is that i don't know how to make a loop over the entire dictionary keys in the same mode as 'combinations' do, using them as iterables, like: asymptote=0 cache=[] pool_chain={} for c in value_refs.keys()[c][0]: # [0] because i need the first tuple value of the key, by rank for d in value_refs.keys()[d][1]: # [1] because i need a loop over the range of all the second #tuple values in the dict pool, versus the outer loop while True: try: if value_refs[c,d] > asymptote: cache=[c,d] asymptote=value_refs[c,d] except KeyError: pass except StopIteration: pool_chain[cache]=asymptote asymptote=0 #and now c would advance by an ordered rank intil the number 4000... I know that the above code doesn't work, because of bad syntax but i think that is the best way to post the question. The unordered nature of the dictionaries in python is (i think) a problem to that nested loops process the 2-tuple keys by an ordered way, like 1,2, 1,3 ... 1,4000 2,3 2,4 and so on. How can i iterate over my dictionary in memory in an ordered way (by rank) and extract both the 2-tuple key and the value that is the biggest for the second value in the key versus the first tuple-value in the same key, and this for all combinations? Thanks in advance. Answer: How about a 2D-array with 4000*4000 elements? Takes less memory and is faster then such a dict. Especially, if you have **all the possible combinations**. Have a look at [Numpy](http://www.numpy.org/). import numpy as np arr = np.empty((4000,4000)) for i, a in enumerate([...]): for j, b in enumerate([...]): arr[i, j] = ... ... for i in arr.shape[0]: for j in arr.shape[1]: ... arr[i, j]
Changing date format after converting from int value in python Question: Is it possible to change format of date from (YYYY,MM,DD) to (DD,MM,YYYY).. import datetime date_value = 41381.0 date_conv= datetime.date(1900, 1, 1) + datetime.timedelta(int(date_value)) print date_conv output: date_conv = 2013-04-19 [Converting date formats python - Unusual date formats - Extract %Y%M%D](http://stackoverflow.com/questions/14271791/converting-date-formats- python-unusual-date-formats-extract-ymd?answertab=votes#tab-top) current output is in (YYYY,MM,DD) formate. Answer: print date_conv.strftime('%d.%m.%Y') prints the date in `DD.MM.YYYY` format. More formatting options [here](http://docs.python.org/2/library/datetime.html#strftime-strptime- behavior).
How to prevent bottle from handling signals Question: I am building an application using the Bottle web-framework. I would like to catch signals USR1 and USR2 to do some work aside from the bottle server. Mainly I want to be able to reload configuration without shutting down the web server because I want some objects to live on. I tried to handle the signals (USR1 and USR2) on my own using : signal.signal(signal.SIGUSR1, my_handler) The problem is that, upon receiving a sigUSR1, the bottle web server crashes with the following trace : Traceback (most recent call last): File "giomanager.py", line 46, in <module> run( giomanager, port=60200 ) File "/usr/lib/python2.7/dist-packages/bottle.py", line 2389, in run server.run(app) File "/usr/lib/python2.7/dist-packages/bottle.py", line 2087, in run srv.serve_forever() File "/usr/lib/python2.7/SocketServer.py", line 225, in serve_forever r, w, e = select.select([self], [], [], poll_interval) select.error: (4, 'Interrupted system call') Do you have an idea why is this happening ? Is it possible to prevent bottle from receiving those signals ? Answer: You didn't post your code, so I'm guessing that it might boil down to something like this: import signal from bottle import route, run def my_handler(*args): print 'in signal handler', args signal.signal(signal.SIGUSR1, my_handler) @route('/hello') def hello(): return "Hello World!\n" run(host='localhost', port=8080, debug=True) Which, incidentally, works for me--it prints "in signal handler." **But** : what I really wanted to suggest is that you consider another mechanism altogether for refreshing your data. I've had much success with a separate refresh thread that repeatedly sleeps for some duration, then wakes up and polls a certain file (or url) to see if there's new data. There are several reasons why this might be better than using signals, not least of which is that it'll be a pain (or impossible) to signal each process if you ever run multi-process. Besides, you weren't planning on running the Bottle development server in production, were you? (It's [not recommended](http://bottlepy.org/docs/dev/deployment.html#server-options) for anything but the smallest of apps.) Given that, once you run your Bottle app within another webserver, signal handling becomes tricky.
python pandas index is_unique not working Question: I'm new to python so please call me on not including relevant information. I've installed python, ipython, and am using the notebook on an Ubuntu installation in a VM. I'm working through examples laid out in Wes McKinney's Python for Data Analysis. After the following import statements: from pandas import Series, DataFrame import pandas as pd I defined a dataframe with: series1 = Series(range(5), index=['a', 'a', 'b', 'b', 'c']) And subsequently wanted to test the indexes uniqueness with: series1.index.is_unique And get this error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/username/<ipython-input-64-e42615bb2da2> in <module>() ----> 1 series1.index.is_unique AttributeError: 'Index' object has no attribute 'is_unique' The book indicates this attribute exists. Other stackoverflow questions and answers reference this attribute. What am I doing wrong? Thanks After being asked what version of pandas I was using, I checked and it was 0.7.0 Upgrading with pip install --upgrade pandas Got me where I needed to be. Answer: Make sure you are using an updated version, no issues here with `0.11.0`: >>> from pandas import Series, DataFrame >>> s = Series(range(5), index=['a', 'a', 'b', 'b', 'c']) >>> s.index.is_unique False Either download the most recent version from [here](https://pypi.python.org/pypi/pandas#downloads), or upgrade from command line: pip install --upgrade pandas For this snippet there's no need to `import pandas as pd` on the second line, so I've removed it.
AttributeError: Extension instance has no attribute '__version__' Question: Here is the script.. from distutils.core import setup, Extension nmap = Extension('nmap',sources = ['nmap/nmap.py', 'nmap/__init__.py', 'nmap/example.py']) from nmap import * setup ( name = 'python-nmap', version = nmap.__version__, author = 'Alexandre Norman', author_email = '[email protected]', license ='gpl-3.0.txt', keywords="nmap, portscanner, network, sysadmin",) ... and i got this error: Traceback (most recent call last): File "C:\Python27\nmap.py", line 6, in <module> from nmap import * File "C:\Python27\nmap.py", line 17, in <module> version = nmap.__version__, AttributeError: Extension instance has no attribute '__version__' Answer: There are a number of problems here. 1. Your `nmap` package isn't an extension, it's a pure-Python package; don't create an `Extension` object for it. Python extension are written in [C or C++](http://docs.python.org/2/extending/building.html). 2. You're trying to access `nmap.__version__`, presumably because you defined that variable in `nmap/__init__.py`, but `nmap` here is that `Extension` object you created; it's trying to access the variable from the wrong thing. 3. Even if you remove the `Extension` object, you still wouldn't be able to access `nmap.__version__`, because you imported your package incorrectly; you meant to use `import nmap`. 4. You never actually pass your package to `setup`, so `distutils` won't know about it. There are a few examples of how to do that [in the documentation](http://docs.python.org/2/distutils/examples.html#pure-python-distribution-by-package). The [`distutils` documentation](http://docs.python.org/2/distutils/index.html) is pretty big, but it's a good idea to read through all of it at least once.
Enthought Canopy 64bit on OSX: import pyglet.gl failure Question: ## Retaining question for posterity; see workaround in edit The Pyglet package comes installed at base and isn't removable. Using the current fully updated version 1.1.4 of Pyglet, I get repeatable errors related to importing the item `pyglet.gl.gl_info`; for instance, upon attempting to create a `pyglet.window.Window()`, upon trying to `import pyglet.gl`, or upon attempting to import pygarrayimage via `from pygarrayimage.arrayimage import ArrayInterfaceImage`. In all such cases the relevant traceback ends with the uninformative message: /Users/[username]/Library/Enthought/Canopy_64bit/System/lib/python2.7/site-packages/pyglet/image/__init__.py in <module>() 142 143 from pyglet import gl --> 144 from pyglet.gl import * 145 from pyglet.gl import gl_info 146 from pyglet import graphics /Users/[username]/Library/Enthought/Canopy_64bit/System/lib/python2.7/site-packages/pyglet/gl/__init__.py in <module>() 102 from pyglet.gl.glext_arb import * 103 from pyglet.gl.glext_missing import * --> 104 from pyglet.gl import gl_info 105 106 import sys as _sys ImportError: cannot import name gl_info I am using OSX 10.6.8 on an Intel processor, with Canopy 64-bit, and these are 100% repeatable. Given the traceback one might assume `gl_info` mistakenly isn't included, but this isn't the case. `dir(pyglet.gl.gl_info)` can successfully be run. ## **Edit: Solved this problem.** Pyglet 1.1.4 does not support 64-bit on OSX, so until Enthought packages a newer release of Pyglet in Canopy, here is a workaround for 64-bit OSX users. 1. Acquire source for any release of Pyglet 1.2alpha1 or beyond. 2. Extract source to your directory of choice. 3. Append this directory to the **beginning** of your PYTHONPATH environment variable, in **both** `~/.bash_profile` (for terminal shells) and `/etc/launchd.conf` (for GUI processes) with a line similar to: `export PYTHONPATH=/Users/[username]/src/pyglet-1.2alpha1:$PYTHONPATH` 4. Run this bash command in an unrelated directory and confirm the path printed leads to your 1.2alpha1 source directory: `$ python -c "import pyglet; print pyglet.__path__[0]"` Answer: If you don't wish to modify your bash_profile, you can simply do the following: 1. Extract latest Pyglet source to your directory of choice and cd to that directory (it should contain a setup.py file). 2. Use Canopy's Python to install Pyglet by doing the following (on Mac 64 bit): `~/Library/Enthought/Canopy_64bit/User/bin/python setup.py install` The location of Canopy's Python for different platforms is listed here: <https://support.enthought.com/entries/23646538-Make-Canopy-s-Python-be-your- default-Python-i-e-on-the-PATH->
Putting a pointer as a value in a method call [python] Question: I'm trying to have a function where I can put in a list and a pointer, and have it apply that pointer to the objects in the list to give me the object with the lowest value of that pointer. def GetLowest(ListObject,Value): ObjectX=ListObject[0] for i in ListObject: if i.Value<=ObjectX.Value: ObjectX=i return ObjectX Then I could do things like (assuming I have lists of these objects) `GetLowest(Rectangles,Area)` and have it check the area of each rectangle. Or maybe something more complex like `GetLowest(Backpacks,Wearer.ShoeSize)`. I'm going to want to use this in a few places around my program. Thanks in advance, guys! Answer: It looks to me like you would like to use the builtin [`min`](http://docs.python.org/3/library/functions.html#min) function. `min` takes an iterable (e.g. a list) and returns the minumum element. You can also give it a `key` function which is called to do the comparison. e.g.: smallest_rectangle = min(list_of_rectangles,key=lambda rect:rect.area) backpack_with_small_shoes = min(backpacks,key=lambda b: b.wearer.shoe_size) The various functions in the [`operator`](http://docs.python.org/3/library/operator.html#operator.attrgetter) module are really useful here too. For example, the first statement above could be written as: from operator import attrgetter smallest_rectangle = min(list_of_rectangles,key=attrgetter('area'))
Python ImportError for strptime in spyder for windows 7 Question: I can't for the life of me figure out what is causing this very odd error. I am running a script in python 2.7 in the spyder IDE for windows 7. It uses datetime.datetime.strptime at one point. I can run the code once and it seems fine (although I haven't finished debugging, so exceptions have been raised and it hasn't completed normally yet), then if I try running it again I get the following (end of traceback only is shown): > File "C:\path\to\test.py", line 220, in std_imp > self.data[key].append(dt.datetime.strptime(string_var, string_format_var)) > ImportError: Failed to import _strptime because the import lockis held by > another thread. I am not running multiple threads with Threading etc. The only way to get the code to make it past this point is to completely restart the computer. Restarting spyder won't work. Web searches haven't seemed to yield any clues or indications of others who have had this happen. Does anyone understand what is going on? Is this some sort of GIL problem? What is the import lock, and why does it seem to be preventing me from importing this method of the datetime module once I have already tried running the code once? Answer: The solution, as noted by mfitzp, was to include a dummy call to datetime.datetime.strptime at the beginning of the script. e.g. # This is a throwaway variable to deal with a python bug throwaway = datetime.datetime.strptime('20110101','%Y%m%d')
Running code with another interpreter on a Perl script Question: [This thread](http://unix.stackexchange.com/questions/74244/hybrid-code-in- shell-scripts-sharing-variables) discusses a way of running Python code from within a Bash script. Is there any way to do something similar from within a Perl script? i.e. is there any way to **run Python code typed on a Perl script?** Note that I am not asking about running a Python **file** from a Perl script. I am asking about running Python code directly typed within the same file that has the Perl script (in the same way that the other thread discussed how to run Perl code from which a Bash script). Example: # /bin/perl use 5.010 my $some_perl_variable = 'hello'; # ... BEGIN PYTHON BLOCK ... # We are still in the same file. But we are now running Python code import sys; print some_perl_variable # Notice that this is a perl variable for r in range(3): print r # ... END PYTHON BLOCK ... say "We are done with the Perl script!" say "The output of the Python block is:" print $output" 1; Should print: We are done with the Perl script! The output of the Python block is: hello 1 2 3 We are done with the perl script Answer: It sounds like you would be interested in the [`Inline`](https://metacpan.org/module/Inline) module. It allows Perl to call code in many other languages, and relies on support modules for each language. You don't say what you want to do, but you mention Python and there is an [`Inline::Python`](https://metacpan.org/module/Inline%3a%3aPython).
Python "ImportError: No module named numpy" Question: Okay so I'm fairly new to Python, I ran the commands sudo easy_install pip sudo pip install numpy Afterwards, I typed python followed by `import numpy` and got the error `ImportError: No module named numpy` Did I miss something? Do I need to add something to sys.path? Answer: I solved it, I had to add a path where everything was installed to my PYTHONPATH env variable. I don't know why the installer didn't automatically do that.
how to add all array's elements to one list in python Question: with a 2 dimension array which looks like this one: myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']] every elements is an array which has fixed length elements. how to become this one, mylist = ['jacob','mary','jack','white','fantasy','clothes','heat','abc','edf','fgc'] here's my solve mylist = [] for x in myarray: mylist.extend(x) should be more simple i guess Answer: Use `itertools.chain.from_iterable`: from itertools import chain mylist = list(chain.from_iterable(myarray)) Demo: >>> from itertools import chain >>> myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']] >>> list(chain.from_iterable(myarray)) ['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc'] However, [Haidro's `sum()` solution](http://stackoverflow.com/a/16316703) is faster for your shorter sample: >>> timeit.timeit('f()', 'from __main__ import withchain as f') 2.858742465992691 >>> timeit.timeit('f()', 'from __main__ import withsum as f') 1.6423718839942012 >>> timeit.timeit('f()', 'from __main__ import withlistcomp as f') 2.0854451240156777 but `itertools.chain` wins if the input gets larger: >>> myarray *= 100 >>> timeit.timeit('f()', 'from __main__ import withchain as f', number=25000) 1.6583486960153095 >>> timeit.timeit('f()', 'from __main__ import withsum as f', number=25000) 23.100156371016055 >>> timeit.timeit('f()', 'from __main__ import withlistcomp as f', number=25000) 2.093297885992797
savetxt two columns in python,numpy Question: I have some data as numpy 2D array list- array([[ 0.62367947], [ 0.95427859], [ 0.97984112], [ 0.7025228 ], [ 0.86436385], [ 0.71010739], [ 0.98748138], [ 0.75198057]]) array([[-1., 1., -1.], [-1., 1., 1.], [ 1., 1., 1.], [ 1., -1., 1.], [-1., -1., -1.], [ 1., 1., -1.], [ 1., -1., -1.], [-1., -1., 1.]]) And I want to save them in a txt file so that they look like 0.62367947 -1 1 -1 0.95427859 -1 1 1 0.97984112 1 1 1 Can someone help me how I can do it using numpy savetxt Answer: import numpy as np R = np.array([[0.62367947], [0.95427859], [0.97984112], [0.7025228], [0.86436385], [0.71010739], [0.98748138], [0.75198057]]) phase = np.array([[-1., 1., -1.], [-1., 1., 1.], [1., 1., 1.], [1., -1., 1.], [-1., -1., -1.], [1., 1., -1.], [1., -1., -1.], [-1., -1., 1.]]) np.savetxt('R2.txt', np.hstack([R, phase]), fmt=['%0.8f','%g','%g','%g']) yields 0.62367947 -1 1 -1 0.95427859 -1 1 1 0.97984112 1 1 1 0.70252280 1 -1 1 0.86436385 -1 -1 -1 0.71010739 1 1 -1 0.98748138 1 -1 -1 0.75198057 -1 -1 1 * * * [np.hstack](http://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html) stacks arrays horizontally. Since `R` and `phase` are both 2-dimensional, `np.hstack([R, phase])` yields In [137]: np.hstack([R,phase]) Out[137]: array([[ 0.62367947, -1. , 1. , -1. ], [ 0.95427859, -1. , 1. , 1. ], [ 0.97984112, 1. , 1. , 1. ], [ 0.7025228 , 1. , -1. , 1. ], [ 0.86436385, -1. , -1. , -1. ], [ 0.71010739, 1. , 1. , -1. ], [ 0.98748138, 1. , -1. , -1. ], [ 0.75198057, -1. , -1. , 1. ]]) Passing this 2D array to `np.savetxt` gives you the desired result.
Make vim highlight python builtins when they are not followed by a dot Question: Is there a way to highlight built in Python functions in vim _only_ when they are preceded by 1 more whitespaces? Furthermore, is there a modular way to do this? That is, I don't want to edit every single `syn keyword pythonBuiltinFunc abs chr ...` line, I just want to be able to say something like `syn keyword pythonBuiltinFunc onlymatchafter="\s+"`? EDIT: Here's an example, since the two people who answered my question didn't seem to understand what I was asking which is my fault for not being more clear. When I write the following Python code import numpy as np x = np.abs(np.random.randn(10, 10)) The word `abs` gets highlighted simply because vim is essentially just matching anything that has the word `abs` in it that is not inside of a string. How can I get vim to highlight the Python builtins WITHOUT highlighting them when they are preceded by a dot? Answer: The matched text of `:syn keyword` can only be comprised of _keyword characters_ ; though that set can be configured (`:setlocal iskeyword=...`), it would be foolish to include whitespace in there. You have two options: Either re-write all keywords with `:syn match` (which can include whitespace), or make all keywords `contained` and define a `:syn region` that only starts after whitespace. Both are rather huge interventions that basically mean you're (re-)writing your own Python syntax. You haven't told us **why** you'd want that... I'd say it's a bad idea.
can't concatenate strings in Python-3 Question: when running this script in Python-3: #!/usr/bin/python # -*- coding: utf-8 -*- import socket import random import os import threading import sys class bot(threading.Thread): def __init__( self, net, port, user, nick, start_chan ): self.id= random.randint(0,1000) self.irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) self.irc_connect ( net, port ) self.irc_set_user( user,nick ) self.irc_join( start_chan ) self.finnish=False threading.Thread.__init__(self) def run( self ): while not self.finnish: serv_data_rec = self.irc.recv ( 4096 ) if serv_data_rec.find ( "PING" ) != -1: self.irc.send( "PONG"+ serv_data_rec.split() [ 1 ] + "\r\n" ) elif serv_data_rec.find("PRIVMSG")!= -1: line = serv_data_rec.split( "!" ) [ 0 ] + " :" + serv_data_rec.split( ":" ) [ 2 ] self.irc_log( line ) self.irc_message( line ) def stop( self ): self.finnish = True self.irc_quit() def irc_connect( self, net, port ): self.net = net self.port = port self.irc.connect ( ( net, port ) ) def irc_set_user( self, user, nick ): self.user = user self.nick = nick self.irc.send( "NICK " + nick + "\r\n" ) self.irc.send( "USER " + user + "\r\n" ) def irc_join( self, chan ): self.chan = chan self.irc.send( "JOIN " + chan + "\r\n" ) def irc_message( self, msg ): self.irc.send( "PRIVMSG " + self.chan+" " + msg + " \r\n" ) def irc_message_nick( self, msg , nick): self.irc.send( "PRIVMSG " + self.chan+" " + nick + " " + msg + " \r\n" ) def irc_ping( self ): self.irc.send("PING :" + self.net) def irc_log( self, line ): if not os.path.exists("./logs"): os.makedirs("./logs") f = open("./logs/" + self.net + self.chan + "#" + "% s" %self.id,'a') try: f.write( line ) finally: f.close() def irc_quit( self ): self.irc.send( "QUIT\r\n" ) def irc_quit_msg(self, msg): self.irc.send( "QUIT :" + msg + "\r\n" ) def main(): bot_main= bot( "irc.freenode.net",6667,"botty botty botty :Python IRC","hello_nick","#martin3333" ) bot_main.start() while 1: inp = raw_input() if inp =="!QUIT": bot_main.stop() break sys.exit(0) if __name__ == '__main__': main() I get the following traceback: File "./hatebozzer.py", line 84, in <module> if __name__ == '__main__': main() File "./hatebozzer.py", line 75, in main bot_main= bot( "irc.freenode.net",6667,"botty botty botty :Python IRC","hello_nick","#martin3333" ) File "./hatebozzer.py", line 14, in __init__ self.irc_set_user( user,nick ) File "./hatebozzer.py", line 43, in irc_set_user self.irc.send( "NICK " + nick + "\r\n" ) TypeError: 'str' does not support the buffer interface I know that strings are treated completly differently in Python 3, but I am not trying to convert strings or do anything exotic. I just want to concatenate them, so what did I wrong here? Answer: `send` wants a sequence of `bytes` as its argument. In Python2, `"NICK " + nick + "\r\n"` is a sequence of bytes. But in Python3, it is a `str`, which in Python2 would have been called a `unicode`. In Python3 this is not a sequence of bytes. In Python3, to convert the `str` to a sequence of bytes, apply an encoding: ("NICK " + nick + "\r\n").encode('utf-8') or (to follow best practices, use `format` instead of `+`): "NICK {n}\r\n".format(n=nick).encode('utf-8')
Add sub-elements to newly created elements in python elementtree Question: I am trying to add the following subtree to an element 'Drugs' in an xml file using elementtree in Python based on the data in CSV file: <Drug> <DrugID>1<DrugID> <Dose>40</Dose> <Unit>mg</Unit> </Drug> <Drug> <DrugID>3<DrugID> <Dose>1</Dose> <Unit>g</Unit> </Drug> The thing is once I have created the Drug element, how do I reference it to use the append function? `element.append()` as I understand it needs element to be a direct reference to the parent. If I use `.find()` when adding the second drug, I may instead get a reference to the first drug. I am cycling through each line of CSV while doing this so that's why I'd rather add element by element rather than appending a subtree to the element Drugs. Answer: Use the [`SubElement` factory](http://docs.python.org/2/library/xml.etree.elementtree.html#building- xml-documents) to add new elements, it's much easier to use: from xml.etree import ElementTree as ET # drugs is a reference to your <Drugs> element for row in csvreader: drug = ET.SubElement(drugs, 'Drug') ET.SubElement(drug, 'DrugID').text = row[0] ET.SubElement(drug, 'Dose').text = row[1] ET.SubElement(drug, 'Unit').text = row[2] where I assume that the columns 1 - 3 are the drug id, dose and unit, adjust as required for your CSV file. Calling `SubElement()` creates the element, adds it to the parent and returns the newly created element for further processing.
Invisible button (using pack_forget) still occupies space Question: I use pack_forget() to make a button invisible. But when i subsequently create a label, it appears bellow the invisible button. How can i avoid this displacement? The following sample code demonstrates the issue: from tkinter import * class Application(Frame): def secondwidget(self): self.b.pack_forget() self.l = Label(text="Lowered Label :(") self.l.pack() def firstwidget(self): self.b = Button(self) self.b["text"] = "Button" self.b["command"] = self.secondwidget self.b.pack() def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.firstwidget() root = Tk() app = Application(master=root) app.mainloop() root.destroy() EDIT: I use python 3.2 Answer: You forgot to set parent for label: self.l = Label(text="Lowered Label :(") print(self.l.winfo_parent() == str(self)) >>> False Compare: self.b = Button(self) print(self.b.winfo_parent() == str(self)) >>> True
Executable Python Zip with C extensions Question: I have a zip file with a `__main__.py` that executes fine: ./myapp But inside of this zip, there is a C extension library.so file that must be loaded but this library.so file is not being found. If I execute the directory (without zipping it), it executes correctly. So it appears the C extensions are not supported or is some configuration issue. Any ideas? <http://www.python.org/dev/peps/pep-0441/> Answer: C extensions cannot be loaded from `.zip` libraries. This is a limitation outside of Python's control. This already applied to [`zipimport` support](http://docs.python.org/2/library/zipimport.html): > Any files may be present in the ZIP archive, but only files .py and .py[co] > are available for import. ZIP import of dynamic modules (.pyd, .so) is > disallowed.
Python numpy loadtxt fails with date time Question: I am trying to use numpy loadtxt to load a csv file into an array. But it seem i can't get the date time correctly loaded. Below demonstrates what is happening. Did I do something wrong? >>> s = StringIO("05/21/2007,03:27") >>> np.loadtxt(s, delimiter=",", dtype={'names':('date','time'), 'formats':('datetime64[D]', 'datetime64[m]')}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/npyio.py", line 796, in loadtxt items = [conv(val) for (conv, val) in zip(converters, vals)] File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/npyio.py", line 573, in <lambda> return lambda x: int(float(x)) ValueError: invalid literal for float(): 05/21/2007 Answer: Trying MichealJCox's solution did not work for me. My version of numpy (1.8) would not accept a time number as given by `strpdate2num('%m/%d/%Y')`, it would only accept a date string or datetime object. Therefore, I used a more complex converter, which converts the time string to a time number and then to a datetime object usable by numpy : from matplotlib.dates import strpdate2num, num2date ... convert = lambda x: num2date(strpdate2num('%m/%d/%Y')(x)) np.loadtxt(s, delimiter=",", converters={0:convert}, dtype= ... This seems like a bulky solution though.
Using variables declared in functions and use them in another function in a different class Question: #!/usr/bin/python import MainPanel import wx ######################################################################## class OtherFrame(wx.Frame):##open PDB frame """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, wx.ID_ANY, "Secondary Frame") panel = wx.Panel(self)##create panel chain = wx.Button(panel, label = "OK", pos=(100,80),size=(53,25))##button create self.Bind(wx.EVT_BUTTON,self.getchain,chain)##bind event to button go to getchain method def getchain(self,event): global flag flag = 1 import OtherFrame ####### class MainPanel(wx.Panel):##main frame """""" #---------------------------------------------------------------------- def __init__(self, parent, size = (5000,5000)): """Constructor""" wx.Panel.__init__(self, parent=parent, size = (5000,5000)) self.frame = parent Publisher().subscribe(self.showFrame, ("show.mainframe")) def showFrame(self, msg): #------------------------------------------------------------------ def createfigure(): OtherF = OtherFrame.OtherFrame() OtherF.getchain() print flag First of all I have shortened down my code massively due to it being over 1000 lines of code. What I am wanting to do is get the variables declared in `getchain` and use them in the `def createfigure`. They are from different classes. At the moment I am getting the error `getchain() takes exactly 2 arguments (1 given)` Could someone tell me where I am going wrong, and how to get the variables I use in `def getchain(self,event)` and use them in `def createfigure` Answer: You shouldn't do that. If you really, really want to, then it's better to make the variables class properties by pre-pending them with "self.". So if you want to access the "flag" variable in the other class, make it "self.flag". Then you can access it using OtherF.flag. However, I think if you need to get something from another class, I recommend using pubsub to pass it around. Here's a tutorial: * <http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/>
Point in convex polygon Question: I'm trying to make a function that will return `True` if the given (x,y) point is inside a convex polygon. I'm trying to make it without numpy or any similar imports, just pure python code. I've already found a sample solution, which seems OK at first sight, but it's not working correctly, and I can't figure out why. The code is as follows: def point_in_poly(x,y,poly): n = len(poly) inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x == p2x or x <= xints: inside = not inside p1x,p1y = p2x,p2y return inside If I test it for (9,9), for the following polygon, it gives me `True`: polygon = [(0,10),(10,10),(10,0),(0,0)] point_x = 9 point_y = 9 print point_in_poly(point_x,point_y,polygon) But when I change the order of the points of the polygon, for the same point, it gives me `False`: polygon = [(0,0), (0,10), (10,0), (10,10)] point_x = 9 point_y = 9 print point_in_poly(point_x,point_y,polygon) Anybody knows the reason? Thanks! Answer: In the particular case you are having problems with is special: polygon = [(0,0), (0,10), (10,0), (10,10)] Changing the order of points in a polygon can have significant impact on algorithms. If you draw your polygon on a graph you'll see you have a horizontal hourglass shape. The polygon border overlaps itself. In geospatial analysis this overlap is not allowed because visually and logically you now have two closed polygons with a common intersection point. By the way most geospatial software doesn't deal well with triangles either. In this case the point at 9,9 will trick the ray casting algorithm used in your method above because it can easily cross the doubled-over polygon boundary twice. Please run the following code to see what is going on. (9,9) is on the line and this algorithm doesn't account for it. (5,8) is way outside: import turtle as t polygon = [(0,0), (0,100), (100,0), (100,100)] t.goto(0,0) fp = None for p in polygon: t.goto(p) if not fp: fp=p t.goto(fp) t.up() t.goto(90,90) t.write("90,90") t.dot(10) t.goto(50,80) t.write("50,80") t.dot(10) t.done() This code handles the (9,9) edge case: [http://geospatialpython.com/2011/08/point-in-polygon-2-on- line.html](http://i.stack.imgur.com/xYNRu.png) ![The code above draws this image.](http://i.stack.imgur.com/xYNRu.png)
Multiprocessing with Python and Arguements Question: related to my last post (Which somehow got marked off and closed), I wrote some code to create a thread for a command handler for my python TCP listener. What basically happens is that I send in some data and it goes in the TCP connecter. Then the TCP connector creates another process and sends the data that it received through the process to the function in the command listener. I do not know what is going on. Please help! import socket import sys import errno from multiprocessing import Process, Queue # @UnresolvedImport import CommandHandler class tcpconnection: def tcp(self): data = '' q = Queue() p = Process(target=CommandHandler.CommandHandler.commands(), args=(self, data)) # HOST = '' # Symbolic name meaning all available interfaces PORT = 9999 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) p.start() p.join() if not data: break conn.send(data) conn.close() Says that: p = Process(target=CommandHandler.CommandHandler.commands(), args=(self, data)) TypeError: unbound method commands() must be called with CommandHandler instance as first argument (got nothing instead) Answer: `target=CommandHandler.CommandHandler.commands()` sets the `target` argument to the result of the invocation of the `commands` method. What you probably intended to do was to use that method as tharget, so you should use: p = Process(target=CommandHandler.CommandHandler.commands, args=(self, data)) Also the error tells you that you're trying to call an unbound method on a class, but you need an object to call it on, probably: p = Process(target=CommandHandler.CommandHandler().commands, args=(self, data)) but that's not your only issue: while True: data = conn.recv(1024) p.start() p.join() This loop will fail after the first invocation, because you can't restart an already started process.
Searching for books with the Amazon Product Advertising API - Python Question: tl;dr : I am using the Amazon Product Advertising API with Python. How can I do a keyword search for a book and get XML results that contain TITLE, ISBN, and PRICE for each entry? Verbose version: I am working in Python on a web site that allows the user to search for textbooks from different sites such as eBay and Amazon. Basically, I need to obtain simple information such as titles, ISBNS, and prices for each item from a set of search results from one of those sites. Then, I can store and format that information as needed in my application (e.g, displaying HTML). In eBay's case, getting the info I needed wasn't too hard. I used `urllib2` to make a request based on a sample I found. All I needed was a special security key to add to the URL: def ebaySearch(keywords): #keywords is a list of strings, e.g. ['moby', 'dick'] #findItemsAdvanced allows category filter -- 267 is books #Of course, I replaced my security appname in the example below url = "http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsAdvanced&SERVICE-NAME=FindingService&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=[MY-APPNAME]&RESPONSE-DATA-FORMAT=XML&REST-PAYLOAD&categoryId=267&keywords=" #Complete the url... numKeywords = len(keywords) for k in range(0, numKeywords-1): url += keywords[k] url += "%20" #There should not be %20 after last keyword url += keywords[numKeywords-1] request = urllib2.Request(url) response = urllib2.urlopen(request) #file like thing (due to library conversion) xml_response = response.read() ... ...Then I parsed this with minidom. In Amazon's case, it doesn't seem to be so easy. I thought I would start out by just looking for an easy wrapper. But their developer site doesn't seem to provide a python wrapper for what I am interested in (the Product Advertising API). One that I have tried, python-amazon-product-api 0.2.5 from <https://pypi.python.org/pypi/python-amazon-product-api/>, has been giving me some installation issues that may not be worth the time to look into (but maybe I'm just exasperated..). I also looked around and found pyaws and pyecs, but these seem to use deprecated authentication mechanisms. I then figured I would just try to construct the URLs from scratch as I did for eBay. But Amazon requires a time stamp in the URLs, which I suppose I could programatically construct (perhaps something like these folks, who go the whole 9 yards with the signature: <https://forums.aws.amazon.com/thread.jspa?threadID=10048>). Even if that worked (which I doubt will happen, given the amount of frustration the logistics have given so far), the bottom line is that I want name, price, and ISBN for the books that I search for. I was able to generate a sample URL with the tutorial on the API website, and then see the XML result, which indeed contained titles and ISBNs. But no prices! Gah! After some desperate Google searching, a slight modification to the URL (adding &ResponseGroup=Offers and &MerchantID=All) did the trick, but then there were no titles. (I guess yet another question I would have, then, is where can I find an index of the possible ResponseGroup parameters?) Overall, as you can see, I really just don't have a solid methodology for this. Is the construct-a-url approach a decent way to go, or will it be more trouble than it is worth? Perhaps the tl;dr at the top is a better representation of the overall question. Answer: Another way could be [amazon-simple-product- api](https://github.com/yoavaviram/python-amazon-simple-product-api): from amazon.api import AmazonAPI amazon = AmazonAPI(ACCESS_KEY, SECRET, ASSOC) results = amazon.search(Keywords = "book name", SearchIndex = "Books") for item in results: print item.title, item.isbn, item.price_and_currency To install, just clone from github and run sudo python setup.py install Hope this helps!
querying data from sqlalchemy database Question: engine = create_engine('sqlite:///nwtopology.db', echo=False) Base = declarative_base() class SourcetoPort(Base): """""" __tablename__ = 'source_to_port' id = Column(Integer, primary_key=True) port_no = Column(Integer) src_address = Column(String) #---------------------------------------------------------------------- def __init__(self, src_address,port_no): """""" self.src_address = src_address self.port_no = port_no Session = sessionmaker(bind=engine) session = Session() self.mac_to_port[packet.src]=packet_in.in_port if(self.matrix.get((packet.src,packet.dst))==None): self.matrix[(packet.src,packet.dst)]=0 print "found a new flow" #create an databse entry with address and port entry = SourcetoPort(src_address=str(packet.src) , port_no=packet_in.in_port) #add the record to the session object session.add(entry) #add the record to the session object session.commit() self.matrix[(packet.src,packet.dst)]+=1 print "incrementing flow count" #if self.mac_to_port.get(packet.dst)!=None: if session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).count(): #do stuff if the flow information is already in the databaase. I am very new to python and sql alchemy and stuff.the above code is releavnt portions of a network controller.The above piece of code gets called whenever a new packet comes in.My question is if session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).count(): is this the correct/most efficient way to know if the src_address is already in the databse.?Can someone suggest some better method.relying on positive count doesn't seem too rigid. Answer: Couple suggestions 1) make sure that your table has index created on src_address field. If you are using SQLAlchemy to create schema index can be added with this simple change to table definition. (see more at [Describing Databases with MetaData: Indexes part of SQLAlchemy manual](http://docs.sqlalchemy.org/en/rel_0_8/core/schema.html?highlight=index#indexes)) class SourcetoPort(Base): """""" __tablename__ = 'source_to_port' id = Column(Integer, primary_key=True) port_no = Column(Integer) src_address = Column(String, index=True) 2) To check if there any records with src_address=str(packet.dst) there is another way by using EXISTS. So it won't have to scan all records what has such src_address but return results as soon as it finds first records with such field value. if session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).count(): #do stuff if the flow information is already in the databaase. Replace count query with exists query from sqlalchemy.sql.expression import exists if session.query(exists().where(SourcetoPort.src_address == '123')).scalar() is not None: #do stuff if the flow information is already in the database. 3) I'm not sure what task your are solving by programming this script. I just hope you are not going to start new python script every time new network packet arrives to network interface. Starting new python interpreter process takes seconds and there can be thousands of packets per second arriving. In the latter case I would consider running such network controller program as a daemon and would cache all information in memory. Also I would implement database operations to run asynchronously in separate thread or even thread pool, so they won't block main thread controlling network flow.
Registration Form import error Question: I am following DjangoBook tutorial and i have encountered a problem on chapter 14 ( User Registration ) In _django.contrib.auth.forms_ , there is a `UserCreationForm` class. I am trying to create a new class based on `UserCreationForm` called `RegisterForm` This is my class `RegisterForm` in _django.contrib.auth.forms_ class RegisterForm(UserCreationForm): email = forms.EmailField(label="Email") fullname = forms.CharField(label="Full name") class Meta: model= User fields = ("username","fullname","email",) This is the view function def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/books/") else: form = RegisterForm(UserCreationForm) return render(request, "registration/register.html", { 'form': form, }) I have no idea why i am getting a ImportError which states that I cannot import name `RegisterForm` in my view , can someone help me out thanks. This is my stack trace Environment: Request Method: GET Request URL: http://127.0.0.1:8000/register/ Django Version: 1.5.1 Python Version: 2.7.2 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.admin', 'mysite.books') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 103. resolver_match = resolver.resolve(request.path_info) File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in resolve 319. for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in url_patterns 347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in urlconf_module 342. self._urlconf_module = import_module(self.urlconf_name) File "C:\Python27\lib\site-packages\django\utils\importlib.py" in import_module 35. __import__(name) File "C:\Users\Ray Lim\Desktop\project\home\username\djcode\mysite\mysite\urls.py" in <module> 14. from mysite.books import views File "C:\Users\Ray Lim\Desktop\project\home\username\djcode\mysite\mysite\books\views.py" in <module> 11. from django.contrib.auth.forms import RegisterForm Exception Type: ImportError at /register/ Exception Value: cannot import name RegisterForm Answer: As of **Django 1.5** there is no such form in the module `django.contrib.auth.forms.` You might want to use an editor that would highlight such things for you. Such as [PyCharm](https://www.jetbrains.com/pycharm/). Still, point stands, you should have at least basic understanding of `Python` to learn `Django`. You see, the statements class RegisterForm(UserCreationForm) ... # And then: form = RegisterForm(UserCreationForm) Hardly make any sense from Python perspective. You are writing Python code. In Python. You'll have to learn Python. Yes, it is possible to go another way, but it is much harder.
Synchronizing Plone 4 sites Question: I'm using Plone 4 for my sites and I was wondering if there is a way to synchronize two plone sites i.e. be able to synchronize my development site with my production site. I have looked at [Zsyncer](https://pypi.python.org/pypi/Products.ZSyncer) product and it appears it is no longer maintained. Besides, the last version is not compatible with Plone 4. I am thinking of writing a custom script that will handle exporting of the data.fs files and the src files as explained in these two articles: [Copying a remote site database](http://developer.plone.org/hosting/zope.html#copying-a-remote-site- database) [Copying a Plone site](http://plone.org/documentation/kb/copying-a-plone-site) Is there a better way of synchronizing two plone sites as described by my use case above? Answer: For keeping the code synchronized, you want collective.hostout For the database, use collective.recipe.backup - you could probably also use hostout to import the backups
Global name in Python Question: I want to find out whether two numbers **N1** and **N2** are the permutations of the same digits. For example `123` and `321` are permutations of the same digits, where as `234` and `123` are not. I have used Python to solve the problem of which I am not an expert. I am using `IDLE Python GUI` on `Windows 7`. The specifications are `Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32`. The Python code is shown below, def k(n, m): s1 = n s2 = m k = 0 fl = 0 while k < 10 : arr1[k] = 0 arr2[k] = 0 k = k + 1 while s1 > 0 : t = s1 % 10 arr1[t] = 1 t = s2 % 10 arr2[t] = 1 s1 = s1 / 10 s2 = s2 / 10 k = 0 while k < 10 : if arr1[k] != arr2[k]: fl = 1 k = k + 1 return fl I saved the file as `k.py` and imported using the following command `import k`. But when I tried to execute the code as `k.k(123, 321)` I am getting the following error. Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> k.k(123,321) File "k.py", line 7, in k global arr2 NameError: global name 'arr1' is not defined I tried to declare the arrays as follows, arr1 = [] arr2 = [] I also tried, global arr1 = [] global arr2 = [] and global arr1 global arr2 But I am still getting the same error. What is wrong with my code? I have checked the following answers in **SO** but I couldn't solve my problem. [Help Defining Global Names](http://stackoverflow.com/questions/3595690/help- defining-global-names) [use of "global" keyword in python](http://stackoverflow.com/questions/4693120/use-of-global-keyword-in- python) **What I believed was that in Python you don't have to declare any variables, instead you can simply use them. Am I wrong about this assumption?** Any suggestions? Thank you. Answer: There is no need to do anything with global values here. Everything should be contained within the function. The problem is simply that you don't define `arr1` or `arr2` before you try appending to them. You need to define them _in that function_ , along with `s1`, `s2`, `k` and `fl`. **Edit** I should add that your code is extremely unPythonic. All these while loops with incrementing counters should be replaced with for loops: `for k in range(10)` etc. But the first loop isn't even necessary - you should have `arr1 = [0] * 10` and the same for `arr2`.
how to disable the automatic mapping of std::vector<std::vector<double> > to tuple of tuples in swig python? Question: Apparently, swig transform automatically `std::vector<std::vector<double> >` to a tuple of tuples. I want to prevent this, and I want the type to be kept as is. How can I achieve it? I tried specifying a definition for the type %template(StdVectorStdVectorDouble) std::vector<std::vector<double> >; but apparently it does not work. Answer: Two techniques: 1. `%clear` the typemap for the type before the function is processed by SWIG. 2. Declare the `%template` _after_ the function is processed by SWIG. ### Example 1 %module x %begin %{ #pragma warning(disable:4127 4211 4701 4706) %} %include <std_vector.i> %template(vd) std::vector<double>; %template(vvd) std::vector<std::vector<double> >; %clear std::vector<std::vector<double> >; %inline %{ #include<vector> std::vector<std::vector<double> > func() { std::vector<std::vector<double> > temp; std::vector<double> a; a.push_back(1.5); temp.push_back(a); return temp; } %} ### Example 2 %module x %begin %{ #pragma warning(disable:4127 4211 4701 4706) %} %include <std_vector.i> %inline %{ #include<vector> std::vector<std::vector<double> > func() { std::vector<std::vector<double> > temp; std::vector<double> a; a.push_back(1.5); temp.push_back(a); return temp; } %} %template(vd) std::vector<double>; %template(vvd) std::vector<std::vector<double> >; ### Result (of both) Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import x >>> x.func() <x.vvd; proxy of <Swig Object of type 'std::vector< std::vector< double,std::allocator<double > > > *' at 0x00000000025F6900> >
Importing the `this` module? Question: Typing the following in a a Python shell does not produce an error: from this import * What is the `this` module? Answer: `this` is the [`zen of python`](http://www.python.org/dev/peps/pep-0020/) written by Tim Peters >>> from this import * The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. ..... >>> d {'A': 'N', 'C': 'P', 'B': 'O', 'E': 'R', 'D': 'Q', 'G': 'T', 'F': 'S', 'I': 'V', 'H': 'U', 'K': 'X', 'J': 'W', 'M': 'Z', 'L': 'Y', 'O': 'B', 'N': 'A', 'Q': 'D', 'P': 'C', 'S': 'F', 'R': 'E', 'U': 'H', 'T': 'G', 'W': 'J', 'V': 'I', 'Y': 'L', 'X': 'K', 'Z': 'M', 'a': 'n', 'c': 'p', 'b': 'o', 'e': 'r', 'd': 'q', 'g': 't', 'f': 's', 'i': 'v', 'h': 'u', 'k': 'x', 'j': 'w', 'm': 'z', 'l': 'y', 'o': 'b', 'n': 'a', 'q': 'd', 'p': 'c', 's': 'f', 'r': 'e', 'u': 'h', 't': 'g', 'w': 'j', 'v': 'i', 'y': 'l', 'x': 'k', 'z': 'm'} >>> c '!' And why would `from this import *` raise an error? Using the above syntax simply merges `this` module's namespace into current namespace. >>> import this >>> dir(this) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'c', 'd', 'i', 's'] Also try: import antigravity
Assigning a function (which is assigned dynamically) along with specific parameters, to a variable. Question: Ok, so here's the deal, say I have a function( take_action ), that calls another function. But we don't know which function take_action is going to call. I had that part figured out thanks to [this question](http://stackoverflow.com/questions/4246000/python-calling-functions- dynamically), the thing is, on that question they deal with functions that take no arguments, my take_action could take one of several different functions that are quite different from each other, with completely different actions taken, different arguments. Now for some example code: def take_action(): action['action']() #does other stuff with 'other_stuff_in_the_dic' def move(x,y): #stuff happens action = {'action': move, 'other_stuff_in_the_dic': 'stuff' } (In this case the 'action' would be move, but like I said, that's assigned dynamically depending on certain user input) What I would like to do, is something like this: action = { 'action': move(2,3), 'other_stuff': 'stuff' } (Obviously that calls the function there, since it has the (), hence it wouldn't work) I'm only a beginner programmer, and the only thing I thought of is using a list, which is in another key inside the dic, but that would just pass one list argument, instead of each content of the list being passed on as an argument. What would be a way to achieve this, so the 'action' key (or the dictionary on another key?) also stores the arguments it should use when I call it on take_action? Answer: Use [`functools.partial()`](http://docs.python.org/3/library/functools.html#functools.partial) to store functions with their arguments: from functools import partial action = {'action': partial(move, 2, 3), 'other_stuff': 'stuff'} Calling `action['action']()` results in `move(2, 3)` being called.
Take a screenshot from a website from commandline or with python Question: i will take a screenshot from this page: [http://books.google.de/books?id=gikDAAAAMBAJ&pg=PA1&img=1&w=2500](http://books.google.de/books?id=gikDAAAAMBAJ&pg=PA1&img=1&w=2500) or save the image that it outputs. But i can't find a way. With wget/curl i get an "unavailable error" and also with others tools like webkit2png/wkhtmltoimage/wkhtmltopng. Is there a clean way to do it with python or from commandline? Best regards! Answer: You can use ghost.py if you like. <http://jeanphix.me/Ghost.py/> Here is an example of how to use it. from ghost import Ghost ghost = Ghost(wait_timeout=4) ghost.open('http://www.google.com') ghost.capture_to('screen_shot.png') The last line saves the image in your current directory. Hope this helps
Histogram in Python Using matplotlib Question: I am struggling with this really badly. There is something that I'm just not getting. I have a function, which I want to plot a histogram of a dictionary with the keys on the x-axis and the values on the y-axis, then save the file in a location specified when calling the function. What I have is: ​import matplotlib.pyplot as plt def test(filename): dictionary = {0:1000, 1:20, 2:15, 3:0, 4:5} xmax = max(dictionary.keys()) ymax = max(dictionary.values()) plt.hist(dictionary,xmax) plt.title('Histogram Title') plt.xlabel('Label') plt.ylabel('Another Label') plt.axis([0, xmax, 0, ymax]) plt.figure() plt.savefig(filename) test('test_graph.svg') I simply cannot get this to work, and I've struggled for a very long time reading other questions and documentation. Any help would be greatly appreciated. Thanks. EDIT: The error I have is: File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager window = Tk.Tk() File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) TclError: no display name and no $DISPLAY environment variable Answer: You are getting snarled up by the state-machine interface: import matplotlib.pyplot as plt def test(filename): dictionary = {0:1000, 1:20, 2:15, 3:0, 4:5} xmax = max(dictionary.keys()) ymax = max(dictionary.values()) plt.figure() # <- makes a new figure and sets it active (add this) plt.hist(dictionary,xmax) # <- finds the current active axes/figure and plots to it plt.title('Histogram Title') plt.xlabel('Label') plt.ylabel('Another Label') plt.axis([0, xmax, 0, ymax]) # plt.figure() # <- makes new figure and makes it active (remove this) plt.savefig(filename) # <- saves the currently active figure (which is empty in your code) test('test_graph.svg') See [How can I attach a pyplot function to a figure instance?](http://stackoverflow.com/questions/14254379/how-can-i-attach-a- pyplot-function-to-a-figure-instance/14261698#14261698) for a longer explanation of the state-machine vs OO interfaces for matplotlib.
Looking for command line ftp client (linux) Question: I am looking to batch download a large number of files (>800). I have a text file with the list of all the filenames. These filenames are then used to derive the URL from which they can be downloaded. I had been parsing through the file with a python script, using subprocess to wget the files. wget ftp://ftp.name.of.site/filename-prefix/filename/filename+suffix However for reasons unknown to me, wget is failing to properly connect. I wanted to know if I could essentially use an ftp program that would work in a similar manner, i.e. no login and stay within the commandline. Edit: What's in my text file: ERS032033 ERS032214 ERS032234 ERS032223 ERS032218 The ERS### act as the prefix. The whole thing is the filename. The final file (i.e. filename+suffix) would look something like: ERS032033_1.fastq.gz Submitting the correct url is not the problem. Answer: Since you are using Python, I suggest dropping the subprocess approach and using the `urllib` module instead: import urllib handle = urllib.urlopen('ftp://ftp.name.of.site/filename-prefix/filename/filename+suffix') print handle.read() handle.close() Assuming you are using Python 2 ([urllib.request](http://docs.python.org/3/library/urllib.request.html#module- urllib.request) for Python 3) If you simply need batch download, [urllib.urlretrieve](http://docs.python.org/2/library/urllib.html#urllib.urlretrieve) is a cleaner approach.
Using django.test.client to test app http requests, getting errors Question: We're beginning to write unit tests for our API (created with the Django Rest Framework). We decided to start off simple and use the built in unittest and django.test.client classes. I've got the stub of a test written and it runs just fine: #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import unittest # from django.test.client import Client class TestGrowth(unittest.TestCase): def setUp(self): # self.client = Client() pass def test_numbers_3_4(self): self.assertEqual(4, 4, True) def test_strings_a_3(self): self.assertEqual('andy', 'andy', True) def suite(): suite = unittest.TestSuite() # Add test cases to suite suite.addTests(unittest.makeSuite(TestGrowth)) return suite if __name__ == '__main__': # Run test suite unittest.TextTestRunner(verbosity=2).run(suite()) However as soon as I uncomment the line reading `from django.test.client import Client` I get an error: Traceback (most recent call last): File "./AccountGrowth.py", line 8, in <module> from django.test.client import Client File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/test/__init__.py", line 5, in <module> from django.test.client import Client, RequestFactory File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/test/client.py", line 21, in <module> from django.db import close_connection File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/db/__init__.py", line 11, in <module> if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES: File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/vagrant/.virtualenvs/emmasocial/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. We are defining DATABASES in settings.py as follows: if "DATABASE_URL" in os.environ: # Parse database configuration from $DATABASE_URL DATABASES = { 'default': dj_database_url.config() } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'emmasocial', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '', # 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. } } I'm running the tests from within the vagrant shell inside `<app>/api/tests` with the following command `python ./AccountGrowth.py`. Can anyone shed some light on why this is happening? Answer: You're not running the tests via Django's test runner, which sets all that up for you. You don't need that `if __name__ == '__main__'` block or its explicit call to `run()`, and you should run your tests via `./manage.py test`.
Python function which will call a 1D vector values Question: I have the next sequence of numbers of A array( is an array 1D ) 1. -1.7654142212e-06 2. 7.0737426918e-07 3. 1.63230254789e-06 4. 1.88255344022e-06 5. 5.00966829007e-06 6. 1.88631278169e-06 7. -4.08751917695e-06 8. 9.12971786351e-07 9. 5.33615185204e-06 10. -1.01338496378e-05 are 100 values, just say that are only 10. I need a function that will call these numbers. EDIT using x, x= np.linspace(0,1000,10) I used scipy.interpolate.interp1d and its not working so good... EDIT the interpolation take the first and last value, and do an aproximation. In my case the values are too small, and accuracy is important. Also, A values are changing on each x step, enough to cause an error after few iterations. So if our array is A = ((-1.7654142212e-06 , ....,-1.01338496378e-05 ))` I need a function to work like that: EDIT e.a. A_FUNCTION(0) = -1.7654142212e-06 .... to call any value I want, without call the approximation of the value, (for a specific #number of x) inside another function on the main or a second script. Answer: why don't you just create a function that takes two inputs: an array, and number In [15]: A Out[15]: array([-4611686018427387904, -4611686018427387904, 7, 0, -4611686018427387904, 5764616295532855496, -4611686018427387899, -4611686018427387904, 4, 1407374883553280]) In [16]: def grab_item(array,number): ....: return array[number] ....: In [17]: grab_item(A,8) Out[17]: 4 After the multitude of comments, here is an example of what I believe you want through using this function: In [24]: x = np.linspace(0,1000,100) In [25]: grab_item(x,9) Out[25]: 90.909090909090907
python csv reader, loop from the second row Question: In python 2.7.3, how can I start the loop from the second row? e.g. first_row = cvsreader.next(); for row in ???: #expect to begin the loop from second row blah...blah... Answer: first_row = next(csvreader) # Compatible with Python 3.x (also 2.7) for row in csvreader: # begins with second row # ... Testing it really works: >>> import csv >>> csvreader = csv.reader(['first,second', '2,a', '3,b']) >>> header = next(csvreader) >>> for line in csvreader: print line ['2', 'a'] ['3', 'b']
Certain trigonometry packages from numpy Question: I'm writing code that solves the intersection of a few functions which involve cos and sin and other various trig functions in python. But I feel like importing NumPy as a whole is too much of a load on such a small program, is there any other way to get basic trig functions and pi, without importing as a whole or is just specifying from numpy import cos from numpy import sin ... the easiest and most economical way to do this? Answer: `sin`, `cos`, and `pi` are also in the [`math`](http://docs.python.org/2/library/math.html) module. So just: from math import sin, cos, pi No numpy required. If you're using `sin` and `cos` on numpy arrays, it's better to use the numpy version, but otherwise, the ones from the math module are good.
Accessing API using Python Question: I was trying to retrieve data from an API and i was receiving **'set' object has no attribute 'items'** This is my api.py and i have import it to my views import json import urllib import urllib2 import pycurl def get_resources(request, filter, endpoint, lookup): headers = {'X-Auth-Token:%s' % request.user.token, 'Content-Type:application/json'} data = urllib.urlencode(filter) url = endpoint+lookup req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) result = json.loads(response.read()) return result and my views.py is like this def indexView(request): resources = json.dumps(get_resources(request,{}, api_endpoint, '/v2/meters')) return HttpResponse(resources, mimetype='application/json') I know that i was doing wrong here, I hope someone who could help me thanks. Answer: The line: headers = {'X-Auth-Token:%s' % request.user.token, 'Content-Type:application/json'} defines a [`set`](http://docs.python.org/2/library/stdtypes.html#set). And it should probably be a dictionary (which has `:` somewhere in after which follows the value for the key before the `:`)
Implement nested interface of generic parent class with ironpython Question: I wan't to implement the following C#/.Net interface with IronPython: public static class Consumes<TMessage> where TMessage : class { public interface All { void Consume(TMessage message); } } This is the python code I tried so far: class TestMessage(object): pass class TestConsumer(Consumes[TestMessage].All): def Consume(self, message): pass From this I get the following exception: > TypeError: TestConsumer: cannot inhert from open generic instantiation > MassTransit.Consumes`1+All[TMessage]. Only closed instantiations are > supported. A valid C# class definition to implement this interface looks following: public class TestConsumer : Consumes<TestMessage>.All { public void Consume(TestMessage msg) { } } So is it not possible to implement this kind of in IronPython? Or am I doing wrong? Thank you in advance! Answer: It looks like implementing the nested interface as class TestConsumer(Consumes[TestMessage].All): does not correctly bind the type parameter `TMessage` even though that would be expected from the syntax. If the type is provided at the end ("for the interface instead of the surrounding class") it seems to work as expected: class TestConsumer(Consumes.All[TestMessage]): What would also work is importing the interface `All` explicitly and use it looking like a standalone generic interface: from MyLib.Consumes import All class TestConsumer(All[TestMessage]): It does not seem obvious if this behavior is correct/defined that way or if there is a bug in the [type generation](https://github.com/IronLanguages/main/blob/master/Languages/IronPython/IronPython/Runtime/Types/NewTypeInfo.cs) (besides from the "inhert"-typo) or in the way the generic parameters are defined/bound. It looks to be also accepted to bind the parameter twice: class PyTestConsumer(Consumes[String].All[String]): even with different values which does not make much sense looking at it from a .NET perspective: class PyTestConsumer(Consumes[List[String]].All[String]):
Have a python file move itself Question: I'm writing a script that emulates a unix environment with python (yes, I know that may sound silly). Basically I set up the "pwd" and "ls" commands before the "cd" command. Now I need my python script to navigate itself around directories by moving itself. I was wondering if anyone could point me in the right direction? eg.What commands to use, etc Note. I would prefer it if I only had to use built-in modules. Thank You! Answer: I am not sure I understand you properly, but if you are talking about moving through the standard unix file system and not copying the script to different locations, you could easily just wrap the three commands (pwd,ls,cd) as python functions, just as you were describing. In fact, I did this as part of the wx_py project; they aren't perfect clones, but they work well enough. Here are the three functions: import os import glob def pwd(): print os.getcwd() def cd(path,usePrint=True): os.chdir(os.path.expandvars(os.path.expanduser(path))) if usePrint: pwd() def ls(str='*',fullpath=False): g=glob.glob(os.path.expandvars(os.path.expanduser(str))) if fullpath: for i in g: print i else: for i in g: print os.path.split(i)[1] The full file is at: <https://github.com/davidmashburn/wx_py/blob/master/wx_py/path.py> I'm sure others may have done a better job, so please just take these functions as a starting point.
Python File append error Question: This code works fine for me. Appends data at the end. def writeFile(dataFile, nameFile): fob = open(nameFile,'a+') fob.write("%s\n"%dataFile) fob.close() But the problem is when I close the program and later run again I found that all the previous data were lost. Process is started to write from the start and there is no data in the file. But during the run it perfectly add a line at the end of file. I can't understand the problem. Please some one help. NB: I am using Ubuntu-10.04 with python 2.6 Answer: There is nothing wrong with the code you posted here... I tend to agree with other the comments that this file is probably being overwritten elsewhere in your code. The only suggestion I can think of to test this explicitly (if your use case can tolerate it) is to throw in an exit() statement at the end of the function and then open the file externally (aka in gedit) and see if the last change took. Alternatively to the exit, you could run the program in the terminal and include a call to pdb at the end of this function which would interrupt the program without killing it: import pdb; pdb.set_trace() You will then have to hit c to continue the program each time this runs. If that checks out, do a search for other places this file might be getting opened.
Is it possible to create a variable as a placeholder for 'current' value of a class in python? Question: Let's say we have a class: _NOTE: this is a dummy class only._ class C(object): def __init__(self): self.a = -10 self.b = 5 self.c = 2 def modify(self, **kwargs): for keyword in kwargs: vars(self)[keyword] = kwargs[keyword] return(self) And we want to use this modify method to change values in our object: myclass = C() myclass = myclass.modify(a=10) But when I want to change the value based on the original one, I have to write this: myclass = C() myclass = myclass.modify(a=myclass.a/10) Or: myclass = myclass.modify(a=abs(myclass.a)) My question is, is there a way, to create a global variable in a module, that I can import and use it as a placeholder for current value, so I can use this formula: from globvars import current myclass = C() myclass = myclass.modify( a=abs(current) % current ** 2, b=current//2, c=bool(current) ) First I tried to a create a class, which will store the operation it is taking and a value, and `modify()` will look first for its variable as a keyword and then execute the function. Actually it is only working for simple situations like: `current+10` or `current**2`. But when I realised, I want to use this `current` for example with an `hsba(current)` (_color converter_) function, where `current` is pointing to an object stored in an other object, I just give up, I can't write this to every class I'm going to use.. Is there a solution for this? Maybe it's quite easy, I just can't see it :) Thanks in advance for replies! Answer: Your `modify` method could take the name of the attribute to modify, and a function that takes the current value of the attribute and returns its new computed value. Then you can do something like: def compute_new_value(current): new_value = abs(current) % current ** 2 return new_value myclass = C() myclass.modify('a', compute_new_value) For simple cases, `lambda` makes it less verbose: myclass.modify('a', lambda cur: cur + 4) And your class: class C(object): [...] def modify(self, attr_name, func): cur_value = getattr(self, attr_name) new_value = func(cur_value) setattr(self, attr_name, new_value) **Edit** : I may have missed something. Since you're writing `myclass = myclass.modify...`, should the `modify` method return a _copy_ of the object ?
is there an ast python3 documentation? (At least for the Syntax) Question: Im trying to work with the ast class in python. I want to get all Function calls and their corresponding arguments. How can I Implement that? The official Documentation on python.org is really vague. Also i tried implementing visit_Name and visit_Call. But that gives me more than the names of the Call. It would be nice if there were some documentation which attributes which nodes possesses. For example id for Name-nodes and func for Call-nodes. Answer: I know of no other documentation, but a lot can be learned by studying examples, such as [this one](http://stackoverflow.com/a/1515403/190597), by Alex Martelli. You could start by modifying it just slightly, this way: import ast class FuncVisit(ast.NodeVisitor): def __init__(self): self.calls = [] self.names = [] def generic_visit(self, node): # Uncomment this to see the names of visited nodes # print(type(node).__name__) ast.NodeVisitor.generic_visit(self, node) def visit_Name(self, node): self.names.append(node.id) def visit_Call(self, node): self.names = [] ast.NodeVisitor.generic_visit(self, node) self.calls.append(self.names) self.names = [] def visit_keyword(self, node): self.names.append(node.arg) tree = ast.parse('''\ x = foo(a, b) x += 1 bar(c=2)''') v = FuncVisit() v.visit(tree) print(v.calls) yields [['foo', 'a', 'b'], ['bar', 'c']]
Unicode Disappearing in html.parser Question: I am extracting HTML from some webpage with Unicode characters as follows: def extract(url): """ Adapted from Python3_Google_Search.py """ user_agent = ("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) " "AppleWebKit/525.13 (KHTML, like Gecko)" "Chrome/0.2.149.29 Safari/525.13") request = urllib.request.Request(url) request.add_header("User-Agent",user_agent) response = urllib.request.urlopen(request) html = response.read().decode("utf8") return html I am decoding properly as you can see. So `html` is now a unicode string. When printing html, I can see the Unicode characters. I am using `html.parser` to parse the HTML and subclassed it: from html.parser import HTMLParser class Parser(HTMLParser): def __init__(self): ## some init stuff #### rest of class When parsing out the HTML using the class's `handle_data`, it appears that the Unicode characters are removed/suddenly disappear. The docs do not mention anything about encodings. Why does HTML Parser remove non-ascii characters, and how can I fix such an issue? Answer: Apparently, `html.parser` will call `handle_entityref` whenever it encounters a non-ascii character. It passes the named character reference, and to convert that to the unicode character, I used: html.entities.html5[name] Python's documentation does not mention that. I've never seen worse documentation that Python.
Tkinter adding line number to text widget Question: Trying to learn tkinter and python. I want to display line number for the Text widget in an adjacent frame from Tkinter import * root = Tk() txt = Text(root) txt.pack(expand=YES, fill=BOTH) frame= Frame(root, width=25) # frame.pack(expand=NO, fill=Y, side=LEFT) root.mainloop() I have seen an example on a site called unpythonic but its assumes that line height of txt is 6 pixels. I am trying something like this: 1) Binding Any-KeyPress event to a function that returns the line on which the keypress occurs: textPad.bind("<Any-KeyPress>", linenumber) def linenumber(event=None): line, column = textPad.index('end').split('.') #creating line number toolbar try: linelabel.pack_forget() linelabel.destroy() lnbar.pack_forget() lnbar.destroy() except: pass lnbar = Frame(root, width=25) for i in range(0, len(line)): linelabel= Label(lnbar, text=i) linelabel.pack(side=LEFT) lnbar.pack(expand=NO, fill=X, side=LEFT) Unfortunately this is giving some weird numbers on the frame. Is there a simpler solution ? How to approach this. thnks Answer: I have a relatively foolproof solution, but it's complex and will likely be hard to understand because it requires some knowledge of how Tkinter and the underlying tcl/tk text widget works. I'll present it here as a complete solution that you can use as-is because I think it illustrates a unique approach that works quite well. Note that this solution works no matter what font you use, and whether or not you use different fonts on different lines, have embedded widgets, and so on. ## Importing Tkinter Before we get started, the following code assumes tkinter is imported like this if you're using python 3.0 or greater: import tkinter as tk ... or this, for python 2.x: import Tkinter as tk ## The line number widget Let's tackle the display of the line numbers. What we want to do is use a canvas, so that we can position the numbers precisely. We'll create a custom class, and give it a new method named `redraw` that will redraw the line numbers for an associated text widget. We also give it a method `attach`, for associating a text widget with this widget. This method takes advantage of the fact that the text widget itself can tell us exactly where a line of text starts and ends via the `dlineinfo` method. This can tell us precisely where to draw the line numbers on our canvas. It also takes advantage of the fact that `dlineinfo` returns `None` if a line is not visible, which we can use to know when to stop displaying line numbers. class TextLineNumbers(tk.Canvas): def __init__(self, *args, **kwargs): tk.Canvas.__init__(self, *args, **kwargs) self.textwidget = None def attach(self, text_widget): self.textwidget = text_widget def redraw(self, *args): '''redraw line numbers''' self.delete("all") i = self.textwidget.index("@0,0") while True : dline= self.textwidget.dlineinfo(i) if dline is None: break y = dline[1] linenum = str(i).split(".")[0] self.create_text(2,y,anchor="nw", text=linenum) i = self.textwidget.index("%s+1line" % i) If you associate this with a text widget and then call the `redraw` method, it should display the line numbers just fine. This works, but has a fatal flaw: you have to know when to call `redraw`. You could create a binding that fires on every key press, but you also have to fire on mouse buttons, and you have to handle the case where a user presses a key and uses the auto-repeat function, etc. The line numbers also need to be redrawn if the window is grown or shrunk or the user scrolls, so we fall into a rabbit hole of trying to figure out every possible event that could cause the numbers to change. There is another solution, which is to have the text widget fire an event whenever "something changes". Unfortunately, the text widget doesn't have direct support for that. However, we can write a little Tcl code to intercept changes to the text widget and generate an event for us. In an answer to the question "[binding to cursor movement doesnt change INSERT mark](http://stackoverflow.com/q/13835207/7432)" I offered a similar solution that shows how to have a text widget call a callback whenever something changes. This time, instead of a callback we'll generate an event since our needs are a little different. ## A custom text class Here is a class that creates a custom text widget that will generate a `<<Change>>` event whenever text is inserted or deleted, or when the view is scrolled. class CustomText(tk.Text): def __init__(self, *args, **kwargs): tk.Text.__init__(self, *args, **kwargs) self.tk.eval(''' proc widget_proxy {widget widget_command args} { # call the real tk widget command with the real args set result [uplevel [linsert $args 0 $widget_command]] # generate the event for certain types of commands if {([lindex $args 0] in {insert replace delete}) || ([lrange $args 0 2] == {mark set insert}) || ([lrange $args 0 1] == {xview moveto}) || ([lrange $args 0 1] == {xview scroll}) || ([lrange $args 0 1] == {yview moveto}) || ([lrange $args 0 1] == {yview scroll})} { event generate $widget <<Change>> -when tail } # return the result from the real widget command return $result } ''') self.tk.eval(''' rename {widget} _{widget} interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget} '''.format(widget=str(self))) ## Putting it all together Finally, here is an example program which uses these two classes: class Example(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.text = CustomText(self) self.vsb = tk.Scrollbar(orient="vertical", command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.text.tag_configure("bigfont", font=("Helvetica", "24", "bold")) self.linenumbers = TextLineNumbers(self, width=30) self.linenumbers.attach(self.text) self.vsb.pack(side="right", fill="y") self.linenumbers.pack(side="left", fill="y") self.text.pack(side="right", fill="both", expand=True) self.text.bind("<<Change>>", self._on_change) self.text.bind("<Configure>", self._on_change) self.text.insert("end", "one\ntwo\nthree\n") self.text.insert("end", "four\n",("bigfont",)) self.text.insert("end", "five\n") def _on_change(self, event): self.linenumbers.redraw() ... and, of course, add this at the end of the file to bootstrap it: if __name__ == "__main__": root = tk.Tk() Example(root).pack(side="top", fill="both", expand=True) root.mainloop()
construct an unknown url from known information Question: I'm trying to create a python script... basically... I have a url to some site url = "http://www.somesite.com/foo/bar/" Files on server: 1-123j.jpg 2-123.jpg 3-123d.jpg 4-1594ss.jpg ... ... 45000-457li.jpg I know the beginning of the filename (a number) and the file extension (.jpg), but there is a part of the name that is unknown(some random string that I don't know)... How do I construct a url to "2-123.jpg" if I don't know the 123 part of the name? What I know... correctURL = "http://www.somesite.com/foo/bar/2-*****.jpg" the correct url would be: "http://www.somesite.com/foo/bar/2-123.jpg" Is this even possible? Answer: Aside from mentioning that it is quite hard to guess random urls, I'll go ahead and post an answer with some assumptions that might lead to a valid solution. The disclaimer here is that I don't know what your possibilities are with regard to server access and such, and hence will make several assumptions on filename formats or directory contents and the like. If you have no server access, then your solution doesn't really have a real answer to it, I guess. So, here goes. First, get a list of filenames on the server: import os with open('filenames.txt') as f: files = os.listdir('.') # Assuming you are in the correct dir f.write('\n'.join(files)) This gives you all available files on the server. Generate this as often as you want, automate it, preferably with copying it to your web server so that you are always up to date. Then, on your web server, do something like this: files = open('filenames.txt').read().split('\n') d = {} for f in files: s = f.split('-', 1) d[s[0]] = s[-1] Your dictionary now contains the key/value pairs needed to construct the correct filename. You can do this periodically, storing the result somewhere for faster access, or just run it whenever you need to construct an url. The final step is to construct the url, like so: n = 2 # The number you got somewhere fmt = 'http://www.somesite.com/foo/bar/{}-{}' url = fmt.format(n, d[n])
for loops, indexing, taking the min value of a list Question: I have two shapefiles: of lakes and of cities. I need to find the closest city to each lake and add the name of the city into the lake shapefile. I have: for lake in lake_cursor: lake_geom = lake.Shape city_dist_list = [] #create a city dis list = a list of dist from one lake to each city for cityID in range(0, city_length-1): #obtaining x and y for both cities and lakes cityX = citylist_X_Coor[cityID] cityY = citylist_Y_Coor[cityID] lakeX = lake_geom.centroid.X lakeY = lake_geom.centroid.Y #calculate distance dist = math.sqrt((cityX-lakeX)**2 + (cityY-lakeY)**2) #add the dist to the city dist list city_dist_list.append(dist) closest = min(city_dist_list) closestID = city_dist_list.index(closest) lake.City_Name = citylist_City_Name[closestID] lake.X_Coor = citylist_X_Coor[closestID] lake.Y_Coor = citylist_Y_Coor[closestID] print closest but I keep getting an error message starting at `lake.City_Name`. The python shell isn't telling me what is wrong - any ideas? And how to fix it as well? Thanks! the traceback shows: Traceback (most recent call last): File "C:\Users\xxx\xxx\xxx.py", line 71, in <module> lake.City_Name = citylist_City_Name[closestID] File "C:\Program Files\ArcGIS\Desktop10.1\arcpy\arcpy\arcobjects\_base.py", line 35, in __setattr__ return setattr(self._arc_object, attr, ao) RuntimeError: ERROR 999999: Error executing function. Answer: Without seeing the rest of your code, it's hard to tell for certain, but it sure looks from the traceback like you are trying to do an update in a SearchCursor. A SearchCursor's rows don't have setters. Make sure you are using an UpdateCursor, and don't forget to do a `lake_cursor.updateRow(lake)` for each lake you update. Below is a simple example of how to use an UpdateCursor. import arcpy fc = 'c:/temp/temp.shp' rows = arcpy.UpdateCursor(fc) for row in rows: print row.Mapname row.Mapname = 'Some Value' rows.updateRow(row) del row, rows This example uses a regular `arcpy.UpdateCursor`. If you have ArcGIS 10.1, then you can use an `arcpy.da.UpdateCursor`, which will run lot faster. Read about these UpdateCursors [here](http://resources.arcgis.com/en/help/main/10.1/index.html#//018v00000064000000) and [here](http://resources.arcgis.com/en/help/main/10.1/index.html#//018w00000014000000).
improving speed of Python module import Question: The question of how to speed up importing of Python modules has been asked previously ([Speeding up the python "import" loader](http://stackoverflow.com/questions/2010255/speeding-up-the-python- import-loader) and [Python -- Speed Up Imports?](http://stackoverflow.com/questions/6025635/python-speed-up-imports)) but without specific examples and has not yielded accepted solutions. I will therefore take up the issue again here, but this time with a specific example. I have a Python script that loads a 3-D image stack from disk, smooths it, and displays it as a movie. I call this script from the system command prompt when I want to quickly view my data. I'm OK with the 700 ms it takes to smooth the data as this is comparable to MATLAB. However, it takes an additional 650 ms to import the modules. So from the user's perspective the Python code runs at half the speed. This is the series of modules I'm importing: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import scipy.ndimage import scipy.signal import sys import os Of course, not all modules are equally slow to import. The chief culprits are: matplotlib.pyplot [300ms] numpy [110ms] scipy.signal [200ms] I have experimented with using `from`, but this isn't any faster. Since Matplotlib is the main culprit and it's got a reputation for slow screen updates, I looked for alternatives. One is PyQtGraph, but that takes 550 ms to import. I am aware of one obvious solution, which is to call my function from an interactive Python session rather than the system command prompt. This is fine but it's too MATLAB-like, I'd prefer the elegance of having my function available from the system prompt. I'm new to Python and I'm not sure how to proceed at this point. Since I'm new, I'd appreciate links on how to implement proposed solutions. Ideally, I'm looking for a simple solution (aren't we all!) because the code needs to be portable between multiple Mac and Linux machines. Answer: you could build a simple server/client, the server running continuously making and updating the plot, and the client just communicating the next file to process. I wrote a simple server/client example based on the basic example from the `socket` module docs: <http://docs.python.org/2/library/socket.html#example> here is server.py: # expensive imports import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import scipy.ndimage import scipy.signal import sys import os # Echo server program import socket HOST = '' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while 1: conn, addr = s.accept() print 'Connected by', addr data = conn.recv(1024) if not data: break conn.sendall("PLOTTING:" + data) # update plot conn.close() and client.py: # Echo client program import socket import sys HOST = '' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall(sys.argv[1]) data = s.recv(1024) s.close() print 'Received', repr(data) you just run the server: python server.py which does the imports, then the client just sends via the socket the filename of the new file to plot: python client.py mytextfile.txt then the server updates the plot. On my machine running your imports take 0.6 seconds, while running `client.py` 0.03 seconds.
Lookarounds in python Question: I have a problem regarding lookarounds in Python: >>> spacereplace = re.compile(b'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I) >>> q = "a b (c or d)" >>> q = spacereplace.sub(" and ", q) >>> q # What is meant to happen: 'a and b and (c or d)' # What instead happens 'a and b and (c and or and d)' The regex is supposed to match any space which is not next to the words "and" or "or", but this doesn't seem to be working. Can anyone help me with this? EDIT: In response to a commentor, I broken down the regex into multiple lines. (?<!\band) # Looks behind the \s, matching if there isn't a word break, followed by "and", there. (?<!\bor) # Looks behind the \s, matching if there isn't a word break, followed by "or", there. \s # Matches a single whitespace character. (?!or\b) # Looks after the \s, matching if there isn't the word "or", followed by a word break there. (?!and\b) # Looks after the \s, matching if there isn't the word "and", followed by a word break there. Answer: You presumably confused raw string modifier `r` with `b`. >>> import re >>> spacereplace = re.compile(r'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I) >>> q = "a b (c or d)" >>> spacereplace.sub(" and ", q) 'a and b and (c or d)' Sometimes, if regexp doesn't work, it may help to `DEBUG` it with `re.DEBUG` flag. In this case by doing that you may notice, that word boundary `\b` is not detected, which may give a hint where to search for mistake: >>> spacereplace = re.compile(b'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I | re.DEBUG) assert_not -1 literal 8 literal 97 literal 110 literal 100 assert_not -1 literal 8 literal 111 literal 114 in category category_space assert_not 1 literal 111 literal 114 literal 8 assert_not 1 literal 97 literal 110 literal 100 literal 8 >>> spacereplace = re.compile(r'(?<!\band)(?<!\bor)\s(?!or\b)(?!and\b)', re.I | re.DEBUG) assert_not -1 at at_boundary literal 97 literal 110 literal 100 assert_not -1 at at_boundary literal 111 literal 114 in category category_space assert_not 1 literal 111 literal 114 at at_boundary assert_not 1 literal 97 literal 110 literal 100 at at_boundary
Scrape a Google Chart script with Scraperwiki (Python) Question: I'm just getting into scraping with Scraperwiki in Python. Already figured out how to scrape tables from a page, run the scraper every month and save the results on top of each other. Pretty cool. Now I want to [scrape this page](http://developer.android.com/about/dashboards/index.html "this page") with information on Android versions and run the script monthly. In particular, I want the table for the version, codename, API and distribution. It's not easy. The table is called with a wrapper div. Is there any way to scrape this information? I can't find any solution. Plan B is to scrape the visualisation. What I eventually need, is the codename and the percentage, so that's sufficient. This information can be found in the HTML in a Google Chart script. ![Google Chart API script](http://i.stack.imgur.com/UdEFd.jpg) But I can't find this information with my 'souped' HTML. I have [a public scraper over here](https://scraperwiki.com/scrapers/android_scraper/ "scraper"). You can edit it to make it work. Can anyone explain how I can approach this problem? A working scraper with comments on what's going on would be awesome. Answer: As this is stored and rendered in JavaScript, the raw Python scraper is unable to execute this code and view the visualisation or table. ScraperWiki is great however I've always found, if you're doing a single page each month, a python script + cron is much better and, if you need to have this JavaScript parsing, using [Selenium](http://docs.seleniumhq.org/) and it's [python driver](https://pypi.python.org/pypi/selenium) is a much more powerful solution. When you have the selenium server installed you can do _roughly_ the following (in pseudocode) #!/bin/env python from selenium import webdriver browser = webdriver.Firefox() # Load page with all Javascript rendered in the DOM for you. browser.get("http://developer.android.com/about/dashboards/index.html") # Find the table table = browser.find_element_by_xpath("/html/body/div[3]/div[2]/div/div/div[2]/div/div/table") # Do something with the table element # Save the data browser.close() Then just have a cron job running the script on the first day of the month like so: 0 0 1 * * /path/to/python_script.py
Cannot import flask from project directory but works everywhere else Question: So I have run into a funny problem when trying to use Flask, I can only run it from ~/ (home) and not from ~/Projects/projectfolder. I'm using Python 2.7.4 installed via their homepage, virtualenv and virtualenvwrapper. Every time it's the same: $ mkvirtualenv project New python executable in project/bin/python Installing setuptools............done. Installing pip...............done. Then I install Flask: $ pip install flask [...] Successfully installed flask Werkzeug Jinja2 Cleaning up... Then I open Python from my home directory: (project) $ python >>> from flask import Flask >>> Then I quit and go to my project folder: (project) $ cd ~/Projects/example (project) $ python >>> from flask import Flask Traceback (most recent call last): File "<stdin>", line 1, in <module> File "flask.py", line 1, in <module> from flask import Flask ImportError: cannot import name Flask And I'm a bit lost as to why this is happening, anybody have any ideas? Answer: According to you traceback, you have a module of your own called `flask.py` in `~/Projects/example`. The current directory is searched before the actual package installation path, so it shadows the "real" Flask.
how to access a nested comprehensioned-list Question: I have a working solution for creating a list some of random numbers, count their occurrencies, and put the result in a dictionary which looks the following: random_ints = [random.randint(0,4) for _ in range(6)] dic = {x:random_ints.count(x) for x in set(random_ints)]) so that for, say [0,2,1,2,1,4] I get {0: 1, 1: 2, 2: 2, 4:1} I was wondering if its possible to express this in a one liner, preferably without the use of a library function - I want to see what's possible with python :) When I try to integrate the two lines in one I dont know howto express the two references to the same comprehensioned list of random_ints ..??? I expected something like: dic = {x:random_ints.count(x) for x in set([random.randint(0,4) for _ in range(6)] as random_ints)) which of course does not work... I looked (nested) list comprehensions up here on SO, but I could not apply the solutions I found to my problem. thanks, s. Answer: Here is a one-liner that relies on `random` and `collections` modules. >>> import collections >>> import random >>> c = collections.Counter(random.randint(0, 6) for _ in range(100)) >>> c Counter({2: 17, 1: 16, 0: 14, 3: 14, 4: 14, 5: 13, 6: 12})
How to make each tweet on its own line? Question: I am wanting to have each tweet be on its own line. Currently, this breaks at each response (I listed Response_1...I am using through Response_10) Any ideas? #!/usr/bin/env python import urllib import json response_1 = urllib.urlopen("http://search.twitter.com/search.json?q=microsoft&page=1") for i in response_1: print (i, "\n") Answer: You have to parse the json as a python object first, only then you can iterate over it. #!/usr/bin/env python import urllib import json response_1 = json.loads(urllib.urlopen("http://search.twitter.com/search.json?q=microsoft&page=1").read()) for i in response_1['results']: print (i, "\n")
Python: Number ranges that are extremely large? Question: val = long(raw_input("Please enter the maximum value of the range:")) + 1 start_time = time.time() numbers = range(0, val) shuffle(numbers) I cannot find a simple way to make this work with extremely large inputs - can anyone help? I saw a question like this - but I could not implement the range function they described in a way that works with shuffle. Thanks. Answer: To get a random permutation of the range `[0, n)` in a memory efficient manner; you could use [`numpy.random.permutation()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html#numpy.random.permutation): import numpy as np numbers = np.random.permutation(n) If you need only small fraction of values from the range e.g., to get `k` random values from `[0, n)` range: import random from functools import partial def sample(n, k): # assume n is much larger than k randbelow = partial(random.randrange, n) # from random.py result = [None] * k selected = set() selected_add = selected.add for i in range(k): j = randbelow() while j in selected: j = randbelow() selected_add(j) result[i] = j return result print(sample(10**100, 10))
Go into sudo user, run couple of commands, go back to normal user in Python script Question: The problem I've run into is that I want to temporarily get into the sudo user, run a couple of commands, and then go back to a normal user and run the commands in that mode. You can find the script I'm gonna use it in here: <https://github.com/Greduan/dotfiles/blob/master/scripts/symlinks.py> Basically, when I'm installing the scripts under the `/bin` folder of my dotfiles I need sudo access in order to make a symlink to that folder. You can find this part of the script under the last for statement in the code. However, since I do depend on some commands that use the current user as a guideline to do stuff, I can't just run the entire script as `sudo`. Last time I tried I got a lot of errors about a folder not existing. Thanks for all the help you can provide. Answer: If you don't mind installing an external dependency, the [`sh` module](http://amoffat.github.io/sh/) makes this pretty simple: import sh sh.cp('foo.txt', 'bar.txt') with sh.sudo: sh.cp('foo2.txt', 'bar2.txt')
unable to run PyQt4 example Question: I am trying to run a pyqt4 example through Notepad++. I asked this question earlier ([Nothing happens when running PyQt4 example code](http://stackoverflow.com/questions/16380923/nothing-happens-when- running-pyqt4-example-code)), and ended up uninstalling Enthought Canopy and all remnants of python and installing cygwin. Now, when I run the example code I get the following error from npp's console. nppExec command --> `C:\cygwin\bin\python2.7.exe -i "$(FULL_CURRENT_PATH)"`. The example code is shown all the way at the bottom. The closest I can get is to start cygwin x (type startx from the bash shell) where I can get the example window to come up, although I am unable to exit out of the window. I feel like I am in over my head here, I just want to create some simple GUI's and I am struggling just to get an example to work. Does Cygwin's python installation lack the classic IDLE? C:\cygwin\bin\python2.7.exe -i "C:\Users\Brian\Dropbox\Python\PYqt_practice.py" Process started >>> cygwin warning: MS-DOS style path detected: C:\Users\Brian\Dropbox\Python\PYqt_practice.py Preferred POSIX equivalent is: /cygdrive/c/Users/Brian/Dropbox/Python/PYqt_practice.py CYGWIN environment variable option "nodosfilewarning" turns off this warning. Consult the user's guide for more details about POSIX paths: http://cygwin.com/cygwin-ug-net/using.html#using-pathnames C:\Users\Brian\Dropbox\Python\PYqt_practice.py: cannot connect to X server <<< Process finished. (Exit code 1) ================ READY ================ PyQt4 example code import sys from PyQt4 import QtGui def main(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() w.resize(250, 150) w.move(300, 300) w.setWindowTitle('Simple') w.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Answer: PyQT4 and PyQT5 installed with Cygwin emulate directly what their equivalent Linux packages do, meaning they **do** expect you to run an X server. Packages dedicated to Windows obviously don't. Basically you have two choices: 1. Give up on Cygwin and use packages dedicated to Windows, that don't need X server. (You could also run non-Cygwin python in Cygwin environment, but that's going to cause you some headaches, for example with Unicode.) 2. Install X server for Cygwin like this: 1. Get `xorg-server` package 2. Run `startx` If this causes you problems, try: 2. Run `xwin -multiwindow` instead of `startx` Now an icon should appear in your tray. 3. Click it with right mouse button 4. Hover to "applications" 5. Click `xterm`. Congratulations! You just ran an `xterm` shell in X environment. See if your application works now.
Python. Return current cursor position and position last left mouse click Question: I want to be able to define the cursor position of the last left mouse click as a point and the current cursor position as a point in real-world coordinates. The code I have so far has the Tkinter import and Math import. I have the GUI all sorted out for this part but I don't know how to define the functions to be able to display it as a label for my GUI. class PointFrame(Frame): def __init__(self, master): Frame.__init__(self, master) self.LastClick= Label(self, text= "Last Point Clicked:") self.LastClick.pack(side= LEFT) self.CurrentPosition= Label(self, text="Cursor Point:") self.CurrentPosition.pack(side= LEFT) Need to create the functions below. Answer: Something like this: from tkinter import * class App(): def __init__(self): root = Tk() self.last_point = (0, 0) self.prev_var = StringVar(value='-:-') self.curr_var = StringVar(value='-:-') labels = Frame(root) labels.pack() Label(labels, text='Last Point Clicked: ').pack(side=LEFT) prev = Label(labels, textvariable=self.prev_var) prev.pack(side=LEFT) Label(labels, text='Current point: ').pack(side=LEFT) curr = Label(labels, textvariable=self.curr_var) curr.pack(side=LEFT) self.canvas = Canvas(root, background='white') self.canvas.pack() self.canvas.bind('<Button-1>', self.on_click) self.canvas.bind('<Motion>', self.on_motion) self.line = self.canvas.create_line(0, 0, 0, 0) self.curr_text = self.canvas.create_text(0, 0) root.mainloop() def on_click(self, event): # Last click in absolute coordinates self.prev_var.set('%s:%s' % self.last_point) # Current point in relative coordinates self.curr_var.set('%s:%s' % (event.x - self.last_point[0], event.y - self.last_point[1])) self.last_point = event.x, event.y def on_motion(self, event): self.canvas.coords(self.line, self.last_point[0], self.last_point[1], event.x, event.y) self.canvas.coords(self.curr_text, event.x, event.y) self.canvas.itemconfigure(self.curr_text, text="%s\n%s\n\n\n" % (event.x - self.last_point[0], event.y - self.last_point[1])) App()