text
stringlengths
226
34.5k
Pygame doesn't catch keydown events on mac Question: When I am trying to catch keys pressed, they are printed in Terminal, but not caught by pygame and the script. Script is executed as follows: >>>import scriptname >>>scriptname.wa() scriptname file: import pygame from pygame.locals import * def wa(): pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) alive_key = True while alive_key: for event in pygame.event.get(): if event.type == QUIT: alive_key = False elif event.type == KEYDOWN and event.key == K_q: print '\nThis is not happening\n' screen.fill((0, 0, 0)) if pygame.mouse.get_pressed()[0]: pygame.event.post( pygame.event.Event(KEYDOWN, key=K_q, mod=0, unicode=u'q')) pygame.display.update() pygame.quit() If events are created on mouse press (as presented in code), they work. I am using OS X 10.8.5, python 2.7, pygame2.7 1.9.1. Everything works perfectly in Windows 7 with similar configuration. Thanks! Answer: change your code to: elif event.type == KEYDOWN or event.type == pygame.KEYDOWN: # for testing purpose print event if event.key == pygame.K_q: print '\nThis is not happening\n I'm using OS X 10.9.5, python 2.7.7, pygame-1.9.2pre-py2.7-macosx10.7. Had the similar problem as yours earlier. I found this solution here: <http://content.gpwiki.org/index.php/Python:Pygame_keyboard_input> I think this is not mac's fault, possibly.
Running a loop while a function is true in python Question: I have a function which returns either `True` or `False`. I'm trying to perform a loop where that function is called several times until it returns `False`, and count how many times it ran. import random as rand def test_function(): return rand.random > 0.5 count = 0 while test_function(): count += 1 print count All this is doing is running it once though, and holding whatever value it got. Answer: You forgot to actually call `rand.random`. Add `()` after it to do this: return rand.random() > 0.5 Below is a demonstration: >>> import random as rand >>> rand.random <built-in method random of Random object at 0x01DC02A8> >>> rand.random() 0.4878133430124779 >>> Right now, your code is testing if the function object itself is greater than `0.5`.
How to pass along username and password to cassandra in python Question: I'm learning and just setup my cassandra cluster and trying to use python as the client to interact with it. In the yaml, I set the authenticator to be PasswordAuthenticator. So now I plan to provide my username and password over to the connect function but find no where to put them. cluster = Cluster(hosts) session = cluster.connect(keyspace) Basically, you provide only the host and the keyspace. The documentation kind of suggest a connection with anonymous? <http://datastax.github.io/python- driver/getting_started.html#connecting-to-cassandra> If I just use the example, I will get the following error raise NoHostAvailable("Unable to connect to any servers", errors) cassandra.cluster.NoHostAvailable: ('Unable to connect to any servers', {'hou722067': AuthenticationFailed('Remote end requires authentication.',)}) Is the authentication information supplied through some config files? It seems like a very basic functionality and I can't imagine it's not covered in the python client driver. I must have miss something. In short, my question is: How do I login to cassandra using python? Thanks in advance for any hint possible! ================================================= Got it figured. I should provide the username and password in the auth_provider field which is a function returning a dictionary containing ‘username’ and ‘password’ keys with appropriate string values. Something like def getCredential(self, host): credential = {'username':'myUser', 'password':'myPassword'} return credential cluster = Cluster(nodes, auth_provider=getCredential) Answer: Following the ops recommendation use: from cassandra.cluster import Cluster def getCredential(self): return {'username': 'foo', 'password': 'bar'} node_ips = ['0.0.0.0', '0.0.0.1'] cluster = Cluster(node_ips, protocol_version=1, auth_provider=getCredential) session = cluster.connect() If you're using protocol version 2 then you must authenticate with an AuthProvider object. EX: from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster ap = PlainTextAuthProvider(username=foo, password=bar) c = Cluster(protocol_version=2, auth_provider=ap) s = c.connect() Can someone can explain best practices using either of these methods to authenticate with a remote cluster?
How to correctly catch an exception raised by a module? Question: In a python project I use a module [python- mpd2](https://github.com/Mic92/python-mpd2) that connects to an (mpd.)server. The server closes the connection after one minute. Most methods provided by the module would then result in an `mpd.ConnectionError`. I try to build a wrapper class that tries to execute the method but reconnects to the server in case of a previous disconnect. What I have is this: from mpd import MPDClient, MPDError class MPDProxy: def __init__(self, host="localhost", port=6600, timeout=10): self.client = MPDClient() self.host = host self.port = port self.client.timeout = timeout self.connect(host, port) def __getattr__(self, name): return self._call_with_reconnect(getattr(self.client, name)) def connect(self, host, port): self.client.connect(host, port) self.client.consume(1) # when we call self.client.next() the previous stream is deleted from the playlist if len(self.client.playlist()) > 1: cur = (self.client.playlist()[0][6:]) self.client.clear() self.add(cur) def _call_with_reconnect(self, func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ConnectionError: self.connect(self.host, self.port) return func(*args, **kwargs) return wrapper mpd_proxy = MPDProxy() However, the `ConnectionError` would not be caught. >>> from MPDProxy import mpd_proxy >>> mpd_proxy.play() >>> mpd_proxy.stop() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "./MPDProxy.py", line 26, in wrapper func(*args, **kwargs) File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 588, in decorator return wrapper(self, name, args, bound_decorator(self, returnValue)) File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 229, in _execute return retval() File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 583, in decorator return function(self, *args, **kwargs) File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 352, in _fetch_nothing line = self._read_line() File "/usr/local/lib/python3.3/dist-packages/mpd.py", line 260, in _read_line raise ConnectionError("Connection lost while reading line") mpd.ConnectionError: Connection lost while reading line How would I correctly catch the ConnectionError? Answer: you need something like the following: def connect(self): try: self.client.connect(self._host, self._port) # Catch socket errors except IOError as err: errno, strerror = err raise PollerError("Could not connect to '%s': %s" % (self._host, strerror)) # Catch all other possible errors # ConnectionError and ProtocolError are always fatal. Others may not # be, but we don't know how to handle them here, so treat them as if # they are instead of ignoring them. except MPDError as e: raise PollerError("Could not connect to '%s': %s" % (self._host, e)) For more info on this look at the examples under [Documentation](https://github.com/Mic92/python-mpd2#documentation) Also, according to your error message the correct error to catch for `ConnectionError` is `mdp.ConnectionError`. ConnectionError is an exception defined by mdp.
functions in python - need explanation Question: can someone simply explain functions in python? I just can't get my head around them. So I have had a go at them, and this is what I've ended up with, but it keeps saying that character is not a global variable def char_name(): character = input("Enter character name: ") return character; def main(): char_name() print(character) main() Can anyone explain functions? Answer: This part is a function: def char_name(): character = input("Enter character name: ") return character; It's important to realize that the variable `character` exists _only_ inside the function. Not outside of it. That's a great feature -- it means that if you decide that `name` is a better name for the variable after all, then you only need to change the variables inside the function, and guaranteed nowhere else. No assignments to variables elsewhere can influence what happens in your function. It's all there. The function has a _return value_ equal to the value of the variable at the end of the function. def main(): char_name() print(character) And here's another function, that also tries to have a variable named `character`. It happens to have the same name, but that's just a coincedence, it's a different function so it's a different variable. Unfortunately, this variable is only used but never set to any value, and Python can't find it as a global variable either, so it throws an exception. `char_name` is called, but its return value is not used for anything, so it's discarded. What you want to do is this: def main(): name = char_name() # I picked a different name to make my point print(name) The function `char_name` is called, _and its return value is assigned to the variable`name`_. Now you can print it.
instance has no attribute 'sock' Question: I have a basic server program running in Python using Twisted. I am trying to reject a user and am trying to use `self.sock.close()`. When that line gets called I get an exception: > AttributeError: IphoneChat instance has no attribute 'sock'. This is strange because before this line of code was executing and not causing an exception: from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor class IphoneChat(protocol): def connectionMade(self): self.sock.close() return That is it right now I changed it when i was trying to reject a incoming connection. Answer: self.transport.loseConnection() is another way to do self.sock.close() when using twisted. I can not figure out why it was working and then stopped working.
Two-dimensional arrays in Python Question: I'm reading in data for three separate cities and I want to keep each set of data in a two-dimensional array, but as I get past a part of my code, loops keep writing over things from my first two cities as I only have a one- dimensional array. Where should I set up these 2-D arrays to keep my files organized and what function and arguments should I use to do so? Arrays should be 3X54 (3 for each city, 54 for each year of data) EDIT: All the initial variables in the code below (i.e. precip, tmin, tmax) will have over 19,000 elements in them at the beginning which I end up averaging over each year later in the code. import numpy as np import matplotlib.pyplot as plt import pandas as pd city = ['Lubbock.txt','Erie.txt','Oslo.txt'] years = np.arange(1960,2014,1) months_summer = range(5,8,1) for x in range(0,len(city),1): data = np.genfromtxt(city[x], skip_header=2, usecols=(1), dtype=('S8')) data2 = np.genfromtxt(city[x], skip_header=2, usecols=(2,3,4)) #ONLY GET 1-D ARRAY WHEN I ASK FOR SHAPE OF VARIABLE AFTER THIS POINT dates = pd.DatetimeIndex(data[:]) year = dates.year month = dates.month day = dates.day precip = data2[:,0]/10. tmax = data2[:,1]/10. tmin = data2[:,2]/10. tmaxF = (tmax*(9./5.))+32. tminF = (tmin*(9./5.))+32. precipinches = precip*0.03937007874 tmax_avg = [] JJA3tmax_avg = [] JJAtmax_avg = [] DJFtmax_avg = [] for yr in years: toavg = np.where(year == yr) tmax_avg.append(np.average(tmax[toavg])) for mo in months_summer: sumtoavg = np.where(month == mo) JJA3tmax_avg.append(np.average(tmax[sumtoavg])) JJAtmax_avg.append(np.average(JJA3tmax_avg)) JJA3tmax_avg = [] dec_this_year = (year == yr) & (month == 12) jan_next_year = (year == (yr+1)) & (month == 1) feb_next_year = (year == (yr+1)) & (month == 2) wintoavg = np.where(dec_this_year & jan_next_year & feb_next_year) DJFtmax_avg.append(np.average(tmax[wintoavg])) tmaxmean30 = np.average(tmax_avg[1:31]) JJAtmaxmean30 = np.average(JJAtmax_avg[1:31]) DJFtmaxmean30 = np.average(DJFtmax_avg[1:31]) #THIS IS THE DATA THAT I'M PLOTTING tmax_avg_dep = tmax_avg - tmaxmean30 JJAtmax_avg_dep = JJAtmax_avg - JJAtmaxmean30 DJFtmax_avg_dep = DJFtmax_avg - DJFtmaxmean30 Answer: This line: data[:] creates a _shallow_ copy. You need a [_deep_ copy](http://docs.python.org/2/library/copy.html#copy.deepcopy): import copy copy.deepcopy(data) From the docs: > The difference between shallow and deep copying is only relevant for > compound objects (objects that contain other objects, like lists or class > instances): > > * A shallow copy constructs a new compound object and then (to the extent > possible) inserts references into it to the objects found in the original. > * A deep copy constructs a new compound object and then, recursively, > inserts copies into it of the objects found in the original. >
Numpy way of appending the data retrieved from for loop Question: I am looking for the numpy way of appending the data retrieved from for loop as in the example below: import glob, gdal, numpy as np tiff_files = glob.glob('*.tif') all_data = [] #LOOKING FOR ALTERNATIVE HERE for f in tiff_files: data_open = gdal.Open(f) data_array = data_open.ReadAsArray().astype(np.float32) all_data.append(data_array) # #LOOKING FOR ALTERNATIVE HERE The above code works, but would be better to append the data_array retrieved from for loop directly into the numpy array rather than using python list. Any idea would be appreciated. Answer: If you want to make it a one-liner: np.array([gdal.Open(f).ReadAsArray().astype(np.float32) for f in glob.glob('*.tif')]) but making data in a `ndarray` is not faster than the builtin `list`. E.g: In [391]: timeit a=[0]*1000 100000 loops, best of 3: 10.1 us per loop In [392]: timeit a=np.array([0]*1000) 1000 loops, best of 3: 265 us per loop
Python 2.7 Dict with key value pairs of lists is reordered Question: I'm trying to use a dict of key value pairs to store and access lists based on the appropriate keys. Below is what I'm using. newDict = {'mod':[0,2], 'pro':[2,3], 'st':[6,10]} newDict2 = {'a':[0,2], 'b':[2,3], 'c':[6,10]} I'm building this dict in a specific order so I can iterate through it with a `for` loop. But for whatever reason when I print or put it through a `for` loop the order of the keys is reordered. print "the newDict is: " + str(newDict) print "the newDict2 is: " + str(newDict2) for key in newDict: print "the key is: " + str(key) The output of this is below. newDict is: {'pro': [2, 3], 'mod': [0, 2], 'st': [6, 10]} newDict2 is: {'a': [0, 2], 'c': [6, 10], 'b': [2, 3]} the key is: pro the key is: mod the key is: st I'm more concerned with the order of the keys than the values of the lists. So I don't want to order it by the values of the lists. I've been doing research but can't figure out why it's changing the order. I've tried changing the values in the lists to try and figure it out but I haven't been able to find a pattern. I thought dict's were used when order wasn't a concern. Maybe dicts aren't the way to go about this. Any help is greatly appreciated. Answer: As you mention, python dictionaries do not maintain order. This means that you are not guaranteed to get out the key value pairs in any order when printing the `dict` or iterating over it after it is created or modified. However, this order, whatever it is, will be maintained as long as no items are inserted or removed. The lists in your `dict`, which are values corresponding to keys, are not changing; they still match the keys they were assigned to. However, the order of the key value pairs has changed. You can use an `OrderedDict` if you would like the key value pairs to maintain order. from collections import OrderedDict newDict = OrderedDict([('mod', [0,2]), ('pro',[2,3]), ('st',[6,10])]) newDict2 = OrderedDict([('a',[0,2]), ('b',[2,3]), ('c',[6,10])])
Read python pickle data stream in Android Question: I have this file which contains python pickle data stream. I've to read contents of this file in Android. For example, if I wanted to read this data stream in python, I'd just use the following code queue = pickle.load(open('filename', 'rb')) I want to achieve same thing in Android such that I can read this pickle stream data and store it in some kind of collection. How can I achieve this? Answer: UPDATE: This only works for pickle protocols `2` and `3`. I think the [Unpickler](https://github.com/irmen/Pyrolite/blob/master/java/src/net/razorvine/pickle/Unpickler.java) class from [Pyrolite](http://pythonhosted.org/Pyro4/pyrolite.html) (MIT license) may be of particular interest to you. It is technically Java, but Android is basically Java. To unpickle you would do something similar to the following: InputStream stream = new FileInputStream("filename"); Unpickler unpickler = new Unpickler(); Object data = unpickler.load(stream); // And cast *data* to the appropriate type. With the imports: import java.io.FileInputStream; import java.io.InputStream; import net.razorvine.pickle.Unpickler; These are the objects supported by default: PYTHON ----> JAVA ------ ---- None null bool boolean int int long long or BigInteger (depending on size) string String unicode String complex net.razorvine.pickle.objects.ComplexNumber datetime.date java.util.Calendar datetime.datetime java.util.Calendar datetime.time java.util.Calendar datetime.timedelta net.razorvine.pickle.objects.TimeDelta float double (float isn't used) array.array array of appropriate primitive type (char, int, short, long, float, double) list java.util.List<Object> tuple Object[] set java.util.Set dict java.util.Map bytes byte[] bytearray byte[] decimal BigDecimal custom class Map<String, Object> (dict with class attributes including its name in "__class__") Please also note: > The unpickler simply returns an Object. Because Java is a statically typed > language you will have to cast that to the appropriate type. Refer to this > table to see what you can expect to receive. * * * UPDATE: I ran tests using the various pickle protocols (`0-3`) and found that it fails for `0` and `1`, but succeeds for `2` and `3`. Here's the python code used to generate the pickled data: import pickle class Data(object): def __init__(self): self.x = 12 data = Data() for p in [0, 1, 2]: with open('data.{}'.format(p), 'wb') as fh: pickle.dump(data, fh, protocol=p) # Python 3 only. with open('data.3', 'wb') as fh: pickle.dump(data, fh, protocol=3) And the java code to unpickle it: import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.util.Map; import net.razorvine.pickle.Unpickler; public class Test { public static void main(String[] args) throws IOException { String filename = args[0]; InputStream inputStream = new FileInputStream(filename); Unpickler unpickler = new Unpickler(); Map<String, Object> data = (Map<String, Object>)unpickler.load(inputStream); } } When run with `data.0` and `data.1`, it fails with: Exception in thread "main" net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for copy_reg._reconstructor) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:617) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:170) at net.razorvine.pickle.Unpickler.load(Unpickler.java:84) at Test.main(Test.java:13) When run with `data.2` and `data.3`, it succeeds.
How does struct.unpack and struct.pack works? Question: I'm currently trying to to learn how to parse PPM file. I did the following in a python interpreter: >>> x = open('file.ppm') >>> x.readline() 'P6\n' >>> x.readline() '2 3\n' >>> x.readline() '255\n' >>> x.readline() '\n' >>> x.readline() '\x174R\x03\xd7\x1e\xb5e!-\xcd(D\\oL\x01' I understand the basic structure of a PPM file. I'm most curious about the last line, however. The byte encoding that contains the info on the pixel's colour. The file above should parse back into P6 2 3 255 10 23 52 82 3 215 30 181 101 33 45 205 40 68 92 111 76 1 By using `struct.pack('B',x)`, I see that the integers get packed into the byte encoding above. However, I'm not sure how to reverse this process using `struct.unpack`. Most importantly, I'm not sure where to cut off each of the byte encoding since they all appear on the same line, and each doesn't seem to have the same length either (?). I also tried to pack the whole line by doing `struct.pack('I','\x174R\x03\xd7\x1e\xb5e!-\xcd(D\\oL\x01')`. I don't understand why it could not directly convert the byte encoding into integers. How can I use `struct.pack(...)` to parse the byte encoding back into integers? Also, what is happening as those values are being packed/ unpacked? Answer: First three strings are not packed by `struct.pack`. So simply use them (`strip` or `rstrip` if you want remove spaces around). >>> 'P6\n' 'P6\n' >>> 'P6\n'.rstrip() 'P6' For the last bytes: >>> b = b'\x174R\x03\xd7\x1e\xb5e!-\xcd(D\\oL\x01' >>> struct.unpack('%dB' % len(b), b) (23, 52, 82, 3, 215, 30, 181, 101, 33, 45, 205, 40, 68, 92, 111, 76, 1) or using [`bytearray`](http://docs.python.org/2/library/functions.html#bytearray): (You can use [`bytes`](http://docs.python.org/3/library/functions.html#bytes) instead in Python 3.x); Iterating `bytearray` yields `int`s. >>> list(bytearray(b)) [23, 52, 82, 3, 215, 30, 181, 101, 33, 45, 205, 40, 68, 92, 111, 76, 1] **NOTE** As Martijn Pieters commented, you'd better open the file with binary mode when you're dealing with binary data. f = open('file.ppm', 'rb') # b: binary mode
Python copy larger file too slow Question: I am trying to copy a large file (> 1 GB) from hard disk to usb drive using `shutil.copy`. A simple script depicting what I am trying to do is:- import shutil src_file = "source\to\large\file" dest = "destination\directory" shutil.copy(src_file, dest) It takes only 2-3 min on linux. But the same file copy on same file takes more that 10-15 min under Windows. Can somebody explain why and give some solution, preferably using python code? **Update 1** Saved the file as test.pySource file size is 1 GB. Destinantion directory is in USB drive. Calculated file copy time with ptime. Result is here:- ptime.exe test.py ptime 1.0 for Win32, Freeware - http://www. Copyright(C) 2002, Jem Berkes <jberkes@pc-t === test.py === Execution time: 542.479 s 542.479 s == 9 min. I don't think `shutil.copy` should take 9 min for copying 1 GB file. **Update 2** Health of the USB is good as same script works well under Linux. Calculated time with same file under windows native xcopy.Here is the result. ptime 1.0 for Win32, Freeware - http://www.pc-tools.net/ Copyright(C) 2002, Jem Berkes <jberkes@pc-tools.net> === xcopy F:\test.iso L:\usb\test.iso 1 File(s) copied Execution time: 128.144 s 128.144 s == 2.13 min. I have 1.7 GB free space even after copying test file. Answer: Just to add some interesting information: WIndows does not like the tiny buffer used on the internals of the shutil implementation. I've quick tried the following: * Copied the original **shutil.py** file to the example script folder and renamed it to **myshutil.py** * Changed the 1st line to `import myshutil` * Edited the **myshutil.py** file and changed the **copyfileobj** from > def copyfileobj(fsrc, fdst, length=16*1024): to > def copyfileobj(fsrc, fdst, length=16*1024*1024): Using a 16 MB buffer instead of 16 KB caused a huge performance improvement. Maybe Python needs some _tuning_ targeting Windows internal filesystem characteristics?
Modification of text files over ssh with Python - performance Question: I need to replace some lines in text files via ssh, if they contain a certain key string. I wrote the following simple Python function for that: def ssh_edit_file(h, u, file_in, file_out, key, new): import paramiko, string, os c_out = [] ssh = paramiko.SSHClient() ssh.load_system_host_keys(os.environ["HOME"] + "/.ssh/known_hosts") ssh.connect(h,username=u) ftp = ssh.open_sftp() f_in = ftp.file(file_in, "r") c_in = f_in.readlines() for line in c_in: if string.find(line, key) > 0: c_out.append(new + '\n') else: s = line c_out.append(s) f_out = ftp.file(file_out, "w") f_out.writelines(c_out) f_in.close() f_out.close() ftp.close() ssh.close() This is a bit slow, which is ok for most of my files. If I use it for larger files (~2k lines), speed becomes a problem. What could be done to speed this up easily? Answer: The idea of using [sed](/questions/tagged/sed "show questions tagged 'sed'") worked well for my case. In return for the helpful suggestion I like the share solution: def ssh_edit_file(h, u, file_in, file_out, key, new): """ SSH_EDIT_FILE - replace a line in a remote file """ import warnings try: s = new.replace("'","\'") if file_in == file_out: ssh_exe('sed -i "s/.*' + key + '.*/' + s + '/g" ' + file_out, h = h, u = u ) else: ssh_exe('sed -e "s/.*' + key + '.*/' + s + '/g" ' + file_in + '>|' + file_out, h = h, u = u ) except: warnings.warn('key not found') def ssh_exe(cmd, client=None, h=None,u=None): """ SSH_EXE - Run command via ssh """ import paramiko, os if h: if client: raise RuntimeError('Please specify either client of h and u') client = paramiko.SSHClient() client.load_system_host_keys(os.environ["HOME"] + "/.ssh/known_hosts") client.connect(h,username=u) else: if h or u: raise RuntimeError('Please specify either client of h and u') stdin, stdout, stderr = client.exec_command(cmd) if stdout.channel.recv_exit_status(): e = stderr.readlines() if not e == []: raise RuntimeError('Error in executing ' + cmd + '\n'.join(e)) if h: client.close()
xpath works for just one item when add // in it Question: I have this html page <page> <div class="results-list"> <div class="item paid-featured-item"></div> <div class="item paid-featured-item"></div> <div class="item paid-featured-item"></div> <div class="item paid-featured-item"></div> <div class="item paid-featured-item"></div> <div class="item paid-featured-item"></div> <div class="item paid-featured-item"></div> <div class="item paid-featured-item"></div> </div> </page> and Inside each "item paid-featured-item", I have this: <div class="item paid-featured-item"> <div class="somethign"> <div class="title"> This is the title </div> </div> <div class="anotherthing"> </div> </div> I want to extract the title using xpath. ### what I have tried Container = "//div[@class='results-list']" for item in Container: title = "//div[@class='title']/text()" I get 8 titles but each one is the title of the first item. ### i am sure that is because i used // what should I do please? ### first I don't want to use css selectors because it is not allowed in my work ### second I don't want to use `class="something"` because this div not always exist in my page. ### third i am using scrapy with python ### fourth appreciate your help Answer: Say your page looks like (`page.html`): <page> <div id="results-list"> <div class="item paid-featured-item"> <div class="something"> <div class="title">Title 1</div> </div> <div class="anotherthing"></div> </div> <div class="item paid-featured-item"> <div class="something"> <div class="title">Title 2</div> </div> <div class="anotherthing"></div> </div> <div class="item paid-featured-item"> <div class="something"> <div class="title">Title 3</div> </div> <div class="anotherthing"></div> </div> <div class="item paid-featured-item"> <div class="something"> <div class="title">Title 4</div> </div> <div class="anotherthing"></div> </div> </div> </page> To extract each title, you do: from scrapy.selector import Selector sel = Selector(text=open('page.html').read()) container = sel.xpath('//div[@id="results-list"]') items = container.xpath('.//div[@class="item paid-featured-item"]') for item in items: # *extracted* is a single-item list containing the title. extracted = item.xpath('.//div[@class="title"]/text()').extract() title = extracted[0] print title This will output: Title 1 Title 2 Title 3 Title 4
Why does my python/pygame application not pop up properly Question: I have made a program with python and pygame and bundled it into a .app file using py2app. It just doesn't open up properly when i click the icon, it doesn't appear on the screen until i click the icon on the dock, by then some of the code has already ran and it ruins the point of the actual program. I also can't seem to change the icon from the normal icon to the icon that i made, i have put it into the folder, replacing the default one. The icon doesn't appear on the dock, the pygame snake does. Finally will the .app file work on any mac? BTW, this is just a program for some fun Code: import random, pygame, time, sys time.sleep(2) colour_1 = (0,255,255) colour_2 = (0,255,0) colour_3 = (255,255,0) colour_4 = (255,0,0) colour_5 = (0,0,255) black = (0,0,0) white = (255,255,255) h = 500 w = 500 pygame.init() FPS = 30 fpsClock = pygame.time.Clock() screen = pygame.display.set_mode((w,h)) pygame.display.set_caption("You just lost the game") alpha = 255 shape = screen.convert_alpha() stimulus = pygame.Rect(0,0,500,500) def the_game(): #Makes the text "the game" and the text "you just lost it" fade into the screen global alpha alpha = alpha - 5 ############## Font = pygame.font.SysFont("monospace",40,True,False) Text = Font.render("The Game",1,white) screen.blit(Text,(140,125)) pygame.draw.rect(shape,(0,0,0,alpha),stimulus) screen.blit(shape,(0,0)) pygame.display.update(stimulus) fpsClock.tick(FPS) def lost_it(): #Writes "the game" and "you just lost it" onto the screen Font = pygame.font.SysFont("monospace",40,True,False) Text = Font.render("The Game",1,(white)) text = Font.render("YOU JUST LOST IT",1,(white)) screen.blit(text,(50,250)) screen.blit(Text,(140,125)) pygame.display.update() def flash(): #Writes "the game" and "you just lost it" onto the screen #Changes the background colour of the screen Font = pygame.font.SysFont("monospace",40,True,False) Text = Font.render("The Game",1,(black)) text = Font.render("YOU JUST LOST IT",1,(black)) rand = random.randint(0,5) if rand == 1: screen.fill(colour_1) if rand == 2: screen.fill(colour_2) if rand == 3: screen.fill(colour_3) if rand == 4: screen.fill(colour_4) if rand == 5: screen.fill(colour_5) screen.blit(text,(50,250)) screen.blit(Text,(140,125)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); sys.exit(); while True: if alpha == 0: break else: the_game() time.sleep(1) lost_it() while True: flash() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); sys.exit(); Answer: There is a method in pygame.display called set_icon. You can use it to override default snake icon
Python Regex - checking for a capital letter with a lowercase after Question: I am trying to check for a capital letter that has a lowercase letter coming directly after it. The trick is that there is going to be a bunch of garbage capital letters and number coming directly before it. For example: AASKH317298DIUANFProgramming is fun as you can see, there is a bunch of stuff we don't need coming directly before the phrase we do need, `Programming is fun`. I am trying to use regex to do this by taking each string and then substituting it out with `''` as the original string does not have to be kept. re.sub(r'^[A-Z0-9]*', '', string) The problem with this code is that it leaves us with `rogramming is fun`, as the `P` is a capital letter. How would I go about checking to make sure that if the next letter is a lowercase, then I should leave that capital untouched. (The `P` in `Programming`) Answer: Use a negative look-ahead: re.sub(r'^[A-Z0-9]*(?![a-z])', '', string) This matches any uppercase character or digit that is _not_ followed by a lowercase character. Demo: >>> import re >>> string = 'AASKH317298DIUANFProgramming is fun' >>> re.sub(r'^[A-Z0-9]*(?![a-z])', '', string) 'Programming is fun'
Python 3.3 nameerror name not defined Question: # Main file (robot.py) from common.delay import PreciseDelay from common.generic_distance_sensor import GenericDistanceSensor, MB10X3 from common.ez_can_jaguar import EzCANJaguar igus_can = 1 l_actuator_can = 2 igus_can = EzCanJaguar(igus_can) l_actuator = EzCanJaguar(l_actuator_can) # Common folder contents `__init__.py` `ez_can_jaguar.py` `delay.py` `generic_distance_sensor.py` # Traceback C:\Users\Ethan_000\workspace\2014\aerial_assist\robot\source>python robot.py Traceback (most recent call last): File "robot.py", line 67, in <module> igus_can = EzCanJaguar(igus_can) NameError: name 'EzCanJaguar' is not defined # Notes `__init__.py` is empty I use pydev in eclipse and giving an "Unresolved import" error on all of the imports Answer: `EzCANJaguar` and `EzCanJaguar` aren't the same thing. Python is case sensitive.
Need Tkinter code for python GUI for implementation of TSP in Branch and bound and dynamic programming methods.. Question: Need Tkinter code for python GUI for implementation of TSP in Branch and bound and dynamic programming methods.. The below code is working fine and i need a gui platform for my project presentation tomorrow. i tried programming in tkinter but not getting along with the code. in the GUI i need text boxes to read no: of cities and a n*n matrix. output screen displays cost of path and optimal route. Can u guys help me with it? thanks in advance. import itertools INF = 100000000 best_cost = 0 def reduce(size, w, row, col, rowred, colred): rvalue = 0 for i in range(size): temp = INF for j in range(size): temp = min(temp, w[row[i]][col[j]]) if temp > 0: for j in range(size): if w[row[i]][col[j]] < INF: w[row[i]][col[j]] -= temp rvalue += temp rowred[i] = temp for j in range(size): temp = INF for i in range(size): temp = min(temp, w[row[i]][col[j]]) if temp > 0: for i in range(size): if w[row[i]][col[j]] < INF: w[row[i]][col[j]] -= temp rvalue += temp colred[j] = temp return rvalue def bestEdge(size, w, row, col): mosti = -INF ri = 0 ci = 0 for i in range(size): for j in range(size): if not w[row[i]][col[j]]: minrowwelt = INF zeroes = 0 for k in range(size): if not w[row[i]][col[k]]: zeroes += 1 else: minrowwelt = min(minrowwelt, w[row[i]][col[k]]) if zeroes > 1: minrowwelt = 0 mincolwelt = INF zeroes = 0 for k in range(size): if not w[row[k]][col[j]]: zeroes += 1 else: mincolwelt = min(mincolwelt, w[row[k]][col[j]]) if zeroes > 1: mincolwelt = 0 if minrowwelt + mincolwelt > mosti: mosti = minrowwelt + mincolwelt ri = i ci = j return mosti, ri, ci def explore(n, w, edges, cost, row, col, best, fwdptr, backptr): global best_cost colred = [0 for _ in range(n)] rowred = [0 for _ in range(n)] size = n - edges cost += reduce(size, w, row, col, rowred, colred) if cost < best_cost: if edges == n - 2: for i in range(n): best[i] = fwdptr[i] if w[row[0]][col[0]] >= INF: avoid = 0 else: avoid = 1 best[row[0]] = col[1 - avoid] best[row[1]] = col[avoid] best_cost = cost else: mostv, rv, cv = bestEdge(size, w, row, col) lowerbound = cost + mostv fwdptr[row[rv]] = col[cv] backptr[col[cv]] = row[rv] last = col[cv] while fwdptr[last] != INF: last = fwdptr[last] first = row[rv] while backptr[first] != INF: first = backptr[first] colrowval = w[last][first] w[last][first] = INF newcol = [INF for _ in range(size)] newrow = [INF for _ in range(size)] for i in range(rv): newrow[i] = row[i] for i in range(rv, size - 1): newrow[i] = row[i + 1] for i in range(cv): newcol[i] = col[i] for i in range(cv, size - 1): newcol[i] = col[i + 1] explore(n, w, edges + 1, cost, newrow, newcol, best, fwdptr, backptr) w[last][first] = colrowval backptr[col[cv]] = INF fwdptr[row[rv]] = INF if lowerbound < best_cost: w[row[rv]][col[cv]] = INF explore(n, w, edges, cost, row, col, best, fwdptr, backptr) w[row[rv]][col[cv]] = 0 for i in range(size): for j in range(size): w[row[i]][col[j]] = w[row[i]][col[j]] + rowred[i] + colred[j] # code for branch & bound def bb(w,size): global best_cost for i in range(size): a[i][i]=INF print('The cost matrix:') for i in range(size): print(a[i]) col = [i for i in range(size)] row = [i for i in range(size)] best = [0 for _ in range(size)] route = [0 for _ in range(size)] fwdptr = [INF for _ in range(size)] backptr = [INF for _ in range(size)] best_cost = INF explore(size, w, 0, 0, row, col, best, fwdptr, backptr) index = 0 for i in range(size): route[i] = index index = best[index] index = [] cost = 0 for i in range(size): if i != size - 1: src = route[i] dst = route[i + 1] else: src = route[i] dst = 0 cost += w[src][dst] index.append(src+1) index.append(1) print('B&B Minimum cost:',cost) print('B&B Optimal path:',index) return # code for dynamic programming def dp(A,N): v=[x for x in range(1,N)] s=tuple(itertools.permutations(v,N-1)) l=len(s) C=[] for i in range(l): t=s[i] c=A[0][t[0]] for j in range(1,len(t)): c+=A[t[j-1]][t[j]] c+=A[t[j]][0] C=C+[c] m=min(C) print('DP Minimum cost:',m) d={k:p for (k,p) in zip(C,s)} r=d[m] r=[x+1 for x in r] r.insert(0,1) r.append(1) print('DPOptimal tour:',r) return #### getting inputs from user n=int(input('Enter the no.of cities:')) a=[[0 for i in range(n)]for j in range(n)] print('Enter the cost matrix:') for i in range(n): for j in range(n): a[i][j]=int(input()) # calling branch & bound bb(a,n) #calling dynamic programming dp(a,n) Answer: That is basically asking someone to write your application for you. Tkinter can be hard to get a grasp of for some people but it should take no more than a few hours. If you write a separate application that just displays "hello world" when a button is pressed like you will learn [here](http://zetcode.com/gui/tkinter/) then it is just a case of repeating code and making your logic fit. The community would be happy to help you when code does not do what you think. Try go through the tutorial and then come back with your issues. Just a side note: Put more whitespace/comments in your code when posting, it will make answers much faster and relevant.
Simple Python Echo Server - Wrong Argument Question: import select import socket import sys host = '' port = 50000 backlog = 5 size = 1024 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host,port)) server.listen(5) input = [server,sys.stdin] running = 1 while running: inputready,outputready,exceptready = select.select(input,[],[]) for s in inputready: if s == server: # handle the server socket client, address = server.accept() input.append(client) elif s == sys.stdin: # handle standard input junk = sys.stdin.readline() running = 0 else: # handle all other sockets data = s.recv(size) if data: s.send(data) else: s.close() input.remove(s) server.close() Whenever I run this code, I get this error message for my argument for the while loop: inputready,outputready,exceptready = select.select(input,[],[]) TypeError: argument must be an int, or have a fileno() method. How can I fix this to make the server run properly? Sorry if this is a bad question, I'm new to python and I can't figure this out. Thanks. Answer: Yeah found the solution to your problem their seem to be `sys.stdin` , the python IDLE GUI for some reason doesn't allow you to use `sys.stdin.fileno()` in your code, while if you run it in the command prompt or the terminal it will work fine on linux. [Link](http://bugs.python.org/issue3003) An if your using windows, you cant pass the `sys.stdin` as an argument to the select() function, as in windows it accepts only sockets as arguments. As Explained in the documentation [Documentation](http://docs.python.org/2/library/select.html) > Note: File objects on Windows are not acceptable, but sockets are. On > Windows, the underlying select() function is provided by the WinSock > library, and does not handle file descriptors that don’t originate from > WinSock. So to mitigate the problem , such that it works on both windows and linux: import select import socket import sys host = '' port = 50000 backlog = 5 size = 1024 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host,port)) server.listen(backlog) input1 = [server] running = 1 while running: inputready,outputready,exceptready = select.select(input1,[],[]) for s in inputready: if s == server: # handle the server socket client, address = server.accept() input1.append(client) elif s == sys.stdin: # handle standard input junk = sys.stdin.readline() running = 0 else: # handle all other sockets data = s.recv(size) if data: s.send(data) else: s.close() input1.remove(s) server.close()
How do I split this string in python 2.7 keeping spaces? Question: I am looking for a way to take a string and output it as a list with each character split? >>> sentence = 'hello I am cool' >>> what_i_want(sentence) ['h', 'e', 'l', 'l', 'o', ' ', 'I', ' ', 'a', 'm', ' ', 'c', 'o', 'o', 'l'] However, this doesn't seem to work: >>> sentence = 'hello I am cool' >>> sentence = ' '.join(sentence).split() >>> print sentence ['h', 'e', 'l', 'l', 'o', 'I', 'a', 'm', 'c', 'o', 'o', 'l'] It doesn't print the space in between! Also, this doesn't work: >>> import re >>> splitter = re.compile(r'(\s+|\S+)') >>> sentence = 'hello I am cool' >>> splitter.findall(sentence) ['hello', ' ', 'I', ' ', 'am', ' ', 'cool'] >>> sentence = ' '.join(sentence) >>> splitter.findall(sentence) ['h', ' ', 'e', ' ', 'l', ' ', 'l', ' ', 'o', ' ', 'i', ' ', 'a', ' ', 'm', ' ', 'a', ' ', 'j'] Can anyone tell me an efficient and relatively easy way to do this? Thanks in advance! Answer: Passing a string to [`list`](http://docs.python.org/2/library/functions.html#list), you will get a list of single-character strings. >>> sentence = 'hello I am cool' >>> list(sentence) ['h', 'e', 'l', 'l', 'o', ' ', 'I', ' ', 'a', 'm', ' ', 'c', 'o', 'o', 'l']
django views : passing a dictionarry Question: I'm starting with Django (coming from CodeIgniter) and everything is very confusing... I want to get my blog posts ordered by pub_date, and I want to display them in the templates grouped by month+year. I tried this but obviously it's not working... And my knowledge of Python + Django is so bad that I don't see why not. def index(request): blogs = Blog.objects.order_by('-pub_date') blogs_per_date = {} for blog in blogs: blogs_per_date[blog.pub_date.month + '-' + blog.pub_date.year] = blog context = {'blogs': blogs_per_date} return render(request, 'layout.html', context); Here's my try with an object : def index(request): blogs = Blog.objects.order_by('-pub_date') blogs_per_date = new object for blog in blogs: blogs_per_date.blog.(pub_date.month + ' ' + blog.pub_date.year) = blog context = {'blogs': blogs_per_date} return render(request, 'layout.html', context); Answer: You can bypass this by using the [`regroup` tag](https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#regroup) in your template. {% regroup blogs by pub_date as blogs_by_date %} <ul> {% for blog in blogs_by_date %} <li>{{ blog.grouper }} <ul> {% for item in blog.list %} <li>{{ item }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> Your view now is simply: def index(request): objects = Blog.objects.order_by('-pub_date') return render(request, 'layout.html', {'blogs': objects}) If you want to do this in your view, you need to create a dictionary, where each key is the date object and the value is a list of blog objects. Something like this will work: from collections import defaultdict def index(request): by_date = defaultdict(list) for obj in Blog.objects.order_by('-pub_date'): by_date[obj.pub_date].append(obj) return render(request, 'layout.html', {'blogs': by_date}) Now, in your `layout.html`, you have: <ul> {% for key,items in blogs.iteritems %} <li>{{ key }} <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> </li> {% endfor %} </ul>
Python: file-object conflicts Question: I'm beginning with python and I created a class of file-object deriving from the 'file' class to be able to manipulate large datafiles. I have created specific methods to work on these files that are built like shown below. I need to return a new instance of MyClass after each method to be able to keep working on them. The problem is that when I use several time the same method there are conflict with the file foo.txt that is used as a temporary file because it is still used as the support of MyClass instance. Is there a way around this ? Or do I need to create randomized names for all my files ? Thanks for your answers, George Class MyClass(file): "Similar to open(file_path,'r')" def __init__(self,file_path): file.__init__(self,file_path) self.tell() def method(self): """Extract informations from self to write them in a temporary file foo.txt that will be used to return a new instance of MyClass""" output=open('foo.txt','w') self.seek(0) # Extracting information from self output.write(information) output.close() return MyClass('foo.txt') I have completed the exemple to make it more clear. I think that my problem is that I am returning a new instance of MyClass from a file I create in the method. If I use the method several times without closing the instances generated from foo.txt, the instances become empty and return 'None' because foo.txt is re-written. For exemple: a=MyClass('/path/to/file') b=a.method() c=b.method() Then returns an error because b is empty Answer: well, your diagnostic is right, and your problem is that your use case is wrong. If you do want to do what it looks like you want, here's how it should work: a=MyClass('/path/to/file') a.method('/path/to/foo.txt') b=MyClass('/path/to/foo.txt') b.method('/path/to/bar.txt') c=MyClass('/path/to/bar.txt') which is simple and will work well (of course, I won't give the details of how you give the argument to `open()`). Though, it lacks elegancy. To improve on that, you may want to create unique temporary files, which will enable you to do what you want: a=MyClass('/path/to/file') b=a.method() c=b.method() but the problem is that you still don't handle correctly the newly created/opened temporary files. So, you'd better use context manager: with open('/path/to/file') as a: with MyClass(a).method() as b: with MyClass(b).method() as c: # use a, b and c files here pass # and now, a is closed, b and c are deleted. so you close the files when you don't need them anymore: import tempfile Class MyClass(): def __init__(self,file): self.file = file def method(self): """Extract informations from self to write them in a temporary file foo.txt that will be used to return a new instance of MyClass""" output = tempfile.TemporaryFile() self.seek(0) # Extracting information from self output.write(information) return output of course, that's one way of doing it, you may work it out in many other ways. The beauty of this solution is that your [temporary file gets deleted when you `close()` is called](http://docs.python.org/2/library/tempfile.html#tempfile.TemporaryFile), which happens when you exit the context of the file. Of course, there are other ways to implement this, but I find this is the most simple and explicit way to work it out (given you give an explicit name to `method()` of course). HTH
python-print statement :syntax error -invalid syntax;IMPORT ERROR:NO MODULE NAMED PYPARSING Question: from __future__ import print_function////// from pyparsing import *//ERROR IN THIS LINE/////// from copy import deepcopy def convertToCNF(exp): print("Given formula:", exp, sep="\n", end="\n\n") parserOutput = parse(exp) if parserOutput == False: print("Not well formed formula") exit(0) root = makeTreeFromParserOutput(parserOutput) root.makeCNF() CNF = str(root) if CNF[0] == "(" and CNF[-1] == ")": CNF = CNF[1:-1] print("CNF for the formula is:", CNF, sep="\n") This code shows an error in print statement which is near `sep="\n",end="\n\n")` can anyone please tell me whats the error? Answer: You can use `from __future__ import print_function` in python-2 to enable yourself to use python3 print feature.
Python: calling method in the map function Question: `map()` and list comprehension are roughly equivalent: map(function, list1) [function(i) for i in list1] What if the function we want to use is a method? [i.function() for i in list1] map(.function, list1) # error! map(run_method(function), list1) # error! How could I perform this kind of manipulation with `map`? Answer: You'd use [`operator.methodcaller()`](http://docs.python.org/2/library/operator.html#operator.methodcaller): from operator import methodcaller map(methodcaller('function'), list1) `methodcaller()` accepts additional arguments that are then passed into the called method; `methodcaller('foo', 'bar', spam='eggs')(object)` is the equivalent of `object.foo('bar', spam='eggs')`. If all objects in `list1` are the same type or subclasses of that type, _and_ the method you want to call doesn't take any arguments, you can pass in the unbound method to `map` as the function to call. For example, to lowercase all strings in a list, you can use: map(str.lower, list_of_strings) where `str.lower` is the unbound method on the `str` type. Note that a list comprehension is not really the equivalent of a `map()` here. `map()` can only do _one_ loop, entirely in C. `map()` will `zip()` multiple iterable arguments, and `map()` in Python 3 is itself an iterator. A list comprehension on the other hand can do multiple (nested) loops and add in filtering, and the left-hand expression can be any valid Python expression including nested list comprehensions.
import behavior when accessing global variables in Python Question: In **bar.py** : var = 1 def set_var(): global var var = 2 In **foo.py** : from bar import * print(var) set_var() print(var) In **foo2.py** : import bar print(bar.var) bar.set_var() print(bar.var) If I run foo.py the output is: 1 1 but if I run foo2.py the output is: 1 2 which is what I would expect. I only would like to understand this behavior, since I am new to Python and haven't find a good reason for this. PD: Additional info. I want to develop a module that uses a singleton object and I have some legacy code that uses this object. I would prefer not to prefix every reference to that object in the legacy code, so that is why I though that importing the module with the _from library import object_ syntax would help. So in the library I have functions that access the global object to configure it just as in the example (bar.py). And in the legacy code I hoped it only would be needed to do some kind of import as it is done in foo.py. Thanks for the guidance. EDITED: SECOND EXAMPLE In bar.py var_list = list(range(0, 2)) var_list2 = list(range(0, 2)) def set_var(): global var_list var_list = list(range(0, 3)) var_list2.append(2) In foo.py from bar import * print(var_list) print(var_list2) set_var() print(var_list) print(var_list2) The output is: [0, 1] [0, 1] [0, 1] [0, 1, 2] I understand that in **set_var** we are creating a new object with **list()** , but I would expect in foo.py to access this new object when I refer to it with **var_list** (just as it would work using the syntax **bar.var_list**). I need some more background. Thanks Answer: "var" in bar.py is `bar.var`. Always (unless it's `__main__.var`, but that's a different issue). Any manipulation of that name happens only in/to that module and not to copies that were made any where else such as those done via `from bar import ...`.
boto dynamodb batch_write and delete_item -- 'The provided key element does not match the schema' Question: I'm trying to delete a large number of items in a DynamoDB table using boto and python. My Table is set up with the primary key as a device ID (think MAC address.) There are multiple entries in the table for each device ID, as the secondary key is a UNIX timestamp. From my reading this code should work: from boto.dynamodb2.table import Table def delete_batch(self, guid): table = Table('Integers') with table.batch_write() as batch: batch.delete_item(Id=guid) Source: <http://docs.pythonboto.org/en/latest/dynamodb2_tut.html#batch- writing> However it returns 'The provided key element does not match the schema' as the error message. I suspect the problem is because guid is not unique in my table. Given that, is there way to delete multiple items with the same primary key without specifying the secondary key? Answer: You are providing only the hash part of the key and not an item (hash+range) - this is why you get an error and can't delete items. You can't ask DynamoDB to delete all items with a hash key (the same way Query gets them all) Read [this answer](http://stackoverflow.com/a/9159431/359134) by Steffen for more information
Python lxml etree check if node exists Question: I have this XML: <MasterPage> <NextPage> <prefix> I want to check if the `prefix` node exists; I tried this, but it didn't work: self.doc=etree.parse(xmlFile) if hasattr(self.doc, 'MasterPage/NextPage/prefix'): Answer: >>> from lxml.html import fromstring >>> import lxml.html as PARSER >>> data = """<MasterPage> ... <NextPage> ... <prefix>""" >>> root = PARSER.fromstring(data) >>> node_list = [] >>> for ele in root.getiterator(): ... node_list.append(ele.tag) ... >>> if "prefix" in node_list: ... print "True" ... True >>> node_list ['masterpage', 'nextpage', 'prefix']
Converting a function from sympy to numpy (attribute error) Question: import numpy as np import sympy as sym from numpy import sin from sympy import symbols, diff func = lambda x: sin(x) x = symbols('x') print diff(func(x),x) This works if I replace my function with a polynomial, or if I place the trig function directly into the diff operator. But in this format I get AttributeError: sin. Basically I think python can't recognize func as just being a trig function which it knows how to symbolically integrate. I could just have sympy import sin and then things would work, but then I'm stuck with func referencing sin in the sympy namespace and there are future things I want to do with func which require that it be defined using sin in the numpy namespace. Answer: You should build your expression up symbolically using SymPy functions, and then use `lambdify` to convert them into things that can be evaluated with NumPy.
Evaluate integral from sympy as lambda function Question: I'm using the sympy module of python. I do is this: x= Symbol('x') integrate(x**2+2,x) The answer is: x**3/3 + 2*x Now, the question is this: Is there a way to make this answer a lambda function of x? Answer: Yes, use `lambdify`: >>> f = lambdify(x, integrate(x**2+2,x)) >>> f(2) 6.666666666666666 If you want to use this with numpy, set `"numpy"` as the second argument of lambdify >>> import numpy as np >>> f = lambdify(x, integrate(x**2+2,x), "numpy") >>> f(np.arange(10)) array([ 0. , 2.33333333, 6.66666667, 15. , 29.33333333, 51.66666667, 84. , 128.33333333, 186.66666667, 261. ]) (you'll probably want to `import numpy as np` and `import sympy as sp` and not import names directly if you do this, since functions from the two do not mix)
How does PySerial work? Question: Say I have the following python script to read in serial data from my Arduino: import serial ser = serial.Serial("dev/ttyACM1", 9600) ser.timeout = 2 ser.readlines() On the other end I've flashed my Arduino with a program that sends 20 voltage readings every 0.5 seconds. The Arduino starts sending those readings from the moment it's hooked up, then after 20 seconds it stops and sends nothing. Now what I've noticed is that I can read those 20 voltage values using the first script whenever I want. That is, I can hook up the Arduino, wait a couple of minutes then read in the values. This makes me think that the data is getting stored somewhere. I'm inclined to think that it's not being stored on the Arduino but on my laptop somewhere. I've come up with a few questions that I hope the community could help me with: 1. Where is PySerial getting the data from (the Arduino or some buffer on my laptop)? 2. For how long is the data stored in this place? 3. Is there a way to clear this space before reading in values? 4. How much storage space is there? 5. When you set the baud rate in PySerial (second line in script), is this the rate that PySerial reads data from the storage area (not the Arduino)? 6. I've noticed that if I set the baud rate in PySerial too high the first few lines of data are fragmented and sometimes completely wrong, why? 7. Not exactly related but when you set serial.Serial.timeout are the units in seconds? I appreciate your time. Answer: Have you tried using a terminal program like TerraTerm (windows) or GTKTerm (linux) to open the same port to the arduino? I think this would be helpful to answer some of your questions. Some quick answers to your questions that I can dump off the top of my head. 1. From the port specified, I'm guessing you are asking something deeper than this? 2. If you do a x = ser.readlines() then the data will be in x as long as you'd like. 3. There is a flush function defined in PySerial 4. Not sure. You can specify how many characters you would like to read though example: x = ser.read(number) The pyserial documentation states the following Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read. <http://pyserial.sourceforge.net/pyserial_api.html> 5. This is the clock rate of the port you are opening, ie /dev/ttyACM1, most serial comms are at 9600, if you happen to be using a USB to serial you'll need 115200 6. Clock rate mismatch. You're computer is sampling data at a rate higher than the arduino is providing it, causing it to be incorrectly displayed. 7. Seconds, quote from Pyserial documentation : "timeout = x: set timeout to x seconds (float allowed)" Same link as number 4 Hope that helps some!
regEx works in notepad++ but not in python Question: let's say we have this: ................. === Operation 'abcd::ddca:dsd' ended in 1.234s /1.234s (100.00%) execution time ................ Using notepad++, I am able to identify this with: ^\=* Operation '([\d\D]*)' ended in (\d*.\d*)s\s*/(\d*.\d*)s \([\d\D]*\) execution time I want the operation name and execution times to be grouped. In python, trying this: exp=re.compile(r"^\=* Operation \'([\d\D]*)\' ended in (\d*.\d*)s\s*/(\d*.\d*)s \([\d\D]*\) execution time") provides nothing. I've tried `\\(` for escaping the literal paranthesis but it didn't work. I'm guessing I don't need to do that since I'm using r"[exp]" when building the object expression. Any ideas on how to get the same result as in notepad++? **LE: tried only with:** exp=re.compile(r"^\=* Operation \'([\d\D]*)\'", flags=re.MULTILINE) still doesn't find anything. **LE2:** later in the code I'm using `groups=exp.match(INPUT)` and I get the pairs with `groups.group(n)` ANSWER: the problem was `match`. Using `search` **fixed the problem** Answer: The regular expression mentioned in the question is working for me without any change. >>> s = """ ... ................. ... === Operation 'abcd::ddca:dsd' ended in 1.234s /1.234s (100.00%) execution time ... ................ ... """ >>> import re >>> exp = re.compile(r"^\=* Operation \'([\d\D]*)\' ended in (\d*.\d*)s\s*/(\d*.\d*)s \([\d\D]*\) execution time", flags=re.M) >>> re.search(exp, s) <_sre.SRE_Match object at 0x1038766b8> >>> re.findall(exp, s) [('abcd::ddca:dsd', '1.234', '1.234')] Two things to consider though: 1. Use `re.M` in the flags argument 2. User `search` or `findall` method to do the matching. Make sure you are not using `re.match` because it will match only the beginning of the string.
Stitching images in python Question: I would like to stitch multiple (5 or 6) images using python. I'm new to python but I want to use this since it runs on the server and is opensource. OpenCV seems very well capable of doing this and would be my prefered option, but the functions are mostly in C++ and I can't find any example that does it in python (although it should be capable). I found this link: <http://richardt.name/teaching/supervisions/vision-2011/practical/> but I think that I'm not capable of doing the exercise. I also found a lot about panotools and Hugin. Hugin is supposed to be able to do the stitching using HSI (Hugin Scripting Interface) but the documentation is very scarce. The example I found should maybe work, but I can't get Hugin and HSI to work in python, there is no explaination on how to install/import the library. Is there anyone that can help me with this? I come from programming in php and am really new to Python, OpenCV and Hugin. Many thanks Answer: I think this is the code you want import cv2 import numpy as np img1 = cv2.imread('Bird1.jpg') img2 = cv2.imread('Bird2.jpg') img3 = np.hstack((img1,img2)) cv2.imwrite('Bird3.jpg',img3) Note : These two input images size(height,width) should be same. Input Image:- ![enter image description here](http://i.stack.imgur.com/lT0tZ.jpg) Output Image :- ![enter image description here](http://i.stack.imgur.com/pM63v.png)
Shebang for compiled Python code Question: I used to add shebang line at top of Python script as, #!/usr/bin/python ... And I can execute the my.py file by, chmod a+r my.py ./my.py But after compiled to bytecode, the script can only be executed by python and the shebang does not work anymore. python my.pyc Is there anyway to make shebang workable to compiled python script? ./my.pyc Answer: Shebang works only for text scripts, not binary files. Nevertheless, you can use `binfmt_misc` to execute `*.pyc` files directly, as reported in [this Python ML thread](https://mail.python.org/pipermail/python- list/2010-January/564393.html): > Linux, you can use binfmt_misc to make executables out of pyc code. Run: > > > import imp,sys,string > magic = string.join(["\\x%.2x" % ord(c) for c in imp.get_magic()],"") > reg = ':pyc:M::%s::%s:' % (magic, sys.executable) > open("/proc/sys/fs/binfmt_misc/register","wb").write(reg) > > > once on your Linux system (or, rather, at boot time), and all pyc files > become executable (if the x bit is set). > > **In Debian, installing the binfmt-support package will do that for you.** (emphasis is mine, note that this will apply to all Debian derivatives, including Ubuntu. The same solution works in Fedora too).
using python WeakSet to enable a callback functionality Question: I'm investigating if I can implement an easy callback functionality in python. I thought I might be able to use weakref.WeakSet for this, but there is clearly something I'm missing or have misunderstood. As you can see in the code I first tried with a list of call back methods in 'ClassA' objects, but realized that this would keep objects that have been added to the list of callbacks alive. Instead I tried using weakref.WeakSet but that doesnt do the trick either (at least not en this way). Comments in the last four lines of code explain what I want to happen. Can anyone help me with this? from weakref import WeakSet class ClassA: def __init__(self): #self.destroyCallback=[] self.destroyCallback=WeakSet() def __del__(self): print('ClassA object %d is being destroyed' %id(self)) for f in self.destroyCallback: f(self) class ClassB: def destroyedObjectListener(self,obj): print('ClassB object %d is called because obj %d is being destroyed'%(id(self),id(obj))) a1=ClassA() a2=ClassA() b=ClassB() a1.destroyCallback.add(b.destroyedObjectListener) #a1.destroyCallback.append(b.destroyedObjectListener) print('destroyCallback len() of obj: %d is: %d'%(id(a1),len(a1.destroyCallback))) # should be 1 a2.destroyCallback.add(b.destroyedObjectListener) #a2.destroyCallback.append(b.destroyedObjectListener) print('destroyCallback len() of obj: %d is: %d'%(id(a2),len(a2.destroyCallback))) # should be 1 del a1 # Should call b.destroyedObjectListener(self) in its __del__ method del b # should result in no strong refs to b so a2's WeakSet should automatically remove added item print('destroyCallback len() of obj: %d is: %d'%(id(a2),len(a2.destroyCallback))) # should be 0 del a2 # Should call __del__ method UPDATE: solution based on the accepted answer can be found on github: git@github.com:thgis/PythonEvent.git Answer: You cannot create weak references to method objects. Method objects are _short lived_ ; they are created on the fly as you access the name on the instance. See the [descriptor howto](http://docs.python.org/2/howto/descriptor.html) how that works. When you access a method name, a _new_ method object is created for you, and when you then add that method to the `WeakSet`, no other references exist to it anymore, so garbage collection happily cleans it up again. You'll have to store something less transient. Storing instance objects themselves would work, then call a predefined method on the registered callbacks: def __del__(self): for f in self.destroyCallback: f.destroyedObjectListener(self) and to register: a1.destroyCallback.add(b) You can also make `b` _itself_ a callable by giving it a `__call__` method: class ClassB: def __call__(self,obj): print('ClassB object %d is called because obj %d ' 'is being destroyed' % (id(self), id(obj))) Another approach would be to store a reference to the underlying function object plus a reference to the instance: import weakref class ClassA: def __init__(self): self._callbacks = [] def registerCallback(self, callback): try: # methods callback_ref = weakref.ref(callback.__func__), weakref.ref(callback.__self__) except AttributeError: callback_ref = weakref.ref(callback), None self._callbacks.append(callback_ref) def __del__(self): for callback_ref in self._callbacks: callback, arg = callback_ref[0](), callback_ref[1] if arg is not None: # method arg = arg() if arg is None: # instance is gone continue callback(arg, self) continue else: if callback is None: # callback has been deleted already continue callback(self) Demo: >>> class ClassB: ... def listener(self, deleted): ... print('ClassA {} was deleted, notified ClassB {}'.format(id(deleted), id(self))) ... >>> def listener1(deleted): ... print('ClassA {} was deleted, notified listener1'.format(id(deleted))) ... >>> def listener2(deleted): ... print('ClassA {} was deleted, notified listener2'.format(id(deleted))) ... >>> # setup, one ClassA and 4 listeners (2 methods, 2 functions) ... >>> a = ClassA() >>> b1 = ClassB() >>> b2 = ClassB() >>> a.registerCallback(b1.listener) >>> a.registerCallback(b2.listener) >>> a.registerCallback(listener1) >>> a.registerCallback(listener2) >>> >>> # deletion, we delete one instance of ClassB, and one function ... >>> del b1 >>> del listener1 >>> >>> # Deleting the ClassA instance will only notify the listeners still remaining ... >>> del a ClassA 4435440336 was deleted, notified ClassB 4435541648 ClassA 4435440336 was deleted, notified listener2
Disablling scrolling of a scroll bar while keeping it visible in wxPython Question: I am currently working with wxPython v3.0, python v2.7 on Windows 7 OS. I have question regarding the scroll bars. In my application I have a GUI which has many scrolled panels. The scroll bar of these scrolled panels are working fine too. **Problem:** My question is that is it possible to disable the scrolling of a scroll bar while keeping it visible on a particular scrolled panel? _The scroll bar shouldn't scroll when being clicked on the scroll buttons or by dragging the scroll bar_. I know that we can disable horizontal or vertical scrolling by using `SetupScrolling(scroll_y=False)` and `SetupScrolling(scroll_x=False)`. But this will also make the scroll bar invisible. I also tried setting the scroll rate to 0 by using `rate_y` & `rate_x`, this also makes the scroll bar invisible. In short I want to show the scroll bar but make it do nothing. Is there a way to capture the scroll events and make them to do nothing? I tried a hit and trial method by binding `myPanel` with [wx.EVT_SCROLLWIN](http://wxpython.org/Phoenix/docs/html/ScrollWinEvent.html#scrollwinevent) to execute a function that does nothing. Unfortunately it didn't worked (the scroll bar is still scrolling). myPanel = wx.lib.scrolledpanel.ScrolledPanel(self, -1, style=wx.SIMPLE_BORDER) myPanel.Bind(wx.EVT_SCROLLWIN, self.onScroll) def onScroll(self, event): pass Here is a quick & dirty code sample to play around and can be [downloaded too](https://db.tt/wQK3FDhd)! to avoid identation errors.: #!/usr/bin/env python import wx import wx.lib.scrolledpanel class GUI(wx.Frame): def __init__(self, parent, id, title): screenSize = (400, 400) wx.Frame.__init__(self, None, id, title, size=screenSize) myFont = wx.Font(15, wx.MODERN, wx.NORMAL, wx.BOLD) panelsSizer = wx.BoxSizer(wx.VERTICAL) sizer1 = wx.BoxSizer(wx.VERTICAL) myPanel = wx.lib.scrolledpanel.ScrolledPanel(self, -1,style=wx.SIMPLE_BORDER) myPanel.Bind(wx.EVT_SCROLLWIN, self.onScroll) myPanel.SetupScrolling() panel1 = wx.lib.scrolledpanel.ScrolledPanel(myPanel, -1, style=wx.SIMPLE_BORDER) panel1.SetBackgroundColour('#FFFFFF') panel2 = wx.lib.scrolledpanel.ScrolledPanel(myPanel, -1, style=wx.SIMPLE_BORDER) panel2.SetBackgroundColour('#55F4FF') k = 0 for i in range(1,7): sPanel ='Panel' +str(k) sPanel = wx.Panel(panel1) label = str(k)+'This is panel-1' text = wx.StaticText(sPanel, -1, label) text.SetForegroundColour('#0101DF') text.SetFont(myFont) sizer1.Add(sPanel, 0, wx.ALL, 5) sizer1.Add(wx.StaticLine(panel1), 0, wx.ALL|wx.EXPAND, 0) k += 1 panel1.SetSizer(sizer1) panelsSizer.Add(panel1, 1, wx.EXPAND) panelsSizer.Add(panel2, 1, wx.EXPAND) myPanel.SetSizer(panelsSizer) def onScroll(self, event): pass if __name__=='__main__': app = wx.App() frame = GUI(parent=None, id=-1, title="Test") frame.Show() app.MainLoop() Any suggestion? Thank you for your time. Answer: Woo hoo, I read you solved it. Meanwhile, this is the best awful hack I could come up with: #!/usr/bin/env python import wx import wx.lib.scrolledpanel class GUI(wx.Frame): def __init__(self, parent, id, title): screenSize = (400, 400) wx.Frame.__init__(self, None, id, title, size=screenSize) myFont = wx.Font(15, wx.MODERN, wx.NORMAL, wx.BOLD) panelsSizer = wx.BoxSizer(wx.VERTICAL) sizer1 = wx.BoxSizer(wx.VERTICAL) myPanel = wx.lib.scrolledpanel.ScrolledPanel(self, -1,style=wx.SIMPLE_BORDER) myPanel.Bind(wx.EVT_SCROLLWIN, self.onScroll) myPanel.SetupScrolling() panel1 = wx.lib.scrolledpanel.ScrolledPanel(myPanel, -1, style=wx.SIMPLE_BORDER) panel1.SetBackgroundColour('#FFFFFF') panel2 = wx.lib.scrolledpanel.ScrolledPanel(myPanel, -1, style=wx.SIMPLE_BORDER) panel2.SetBackgroundColour('#55F4FF') k = 0 for i in range(1,7): sPanel ='Panel' +str(k) sPanel = wx.Panel(panel1) label = str(k)+'This is panel-1' text = wx.StaticText(sPanel, -1, label) text.SetForegroundColour('#0101DF') text.SetFont(myFont) sizer1.Add(sPanel, 0, wx.ALL, 5) sizer1.Add(wx.StaticLine(panel1), 0, wx.ALL|wx.EXPAND, 0) k += 1 panel1.SetSizer(sizer1) panelsSizer.Add(panel1, 1, wx.EXPAND) panelsSizer.Add(panel2, 1, wx.EXPAND) myPanel.SetSizer(panelsSizer) self.scrolled_panel=myPanel def onScroll(self, event): print "scroll event" for child in self.scrolled_panel.GetChildren(): try: child.SetThumbPosition(0) print "set child" except: print "oops,probably not a scrollbar :) " if __name__=='__main__': app = wx.App() frame = GUI(parent=None, id=-1, title="Test") frame.Show() app.MainLoop() It doesn't stop them dragging the scrollbar, but it does pop it back after they let go. **Update: The code above only works on OSX, not Windows.** Under OSX, the children of a ScrolledPanel are reported as: wxWindowList: [<wx._controls.ScrollBar; proxy of <Swig Object of type 'wxScrollBar *' at 0x10068f830> >, <wx._controls.ScrollBar; proxy of <Swig Object of type 'wxScrollBar *' at 0x100691230> >, <wx._core.Window; proxy of <Swig Object of type 'wxWindow *' at 0x100691d20> >, <wx.lib.scrolledpanel.ScrolledPanel; proxy of <Swig Object of type 'wxPyScrolledWindow *' at 0x1004ac990> >, <wx.lib.scrolledpanel.ScrolledPanel; proxy of <Swig Object of type 'wxPyScrolledWindow *' at 0x1004af8e0> >] It's the two ScrollBar's that my hack is targetting. Under Windows, the same call returns: wxWindowList: [<wx.lib.scrolledpanel.ScrolledPanel; proxy of <Swig Object of type 'wxPyScrolledWindo w *' at 0x26837b8> >, <wx.lib.scrolledpanel.ScrolledPanel; proxy of <Swig Object of type 'wxPyScroll edWindow *' at 0x26839b0> >] This is much harder to understand. Where are the scroll bars hiding? I guess this is what you get for hacking into components that are supposed to be encapsulated for you :)
Python create many-to-many relationships from a list Question: I have a list, say `terms = ['A', 'B', 'C', 'D']` Which is the best way to create a list-of-lists or list-of-tuples of many-to- many relationships like this; [['A','B'],['A','C'],['A','D'],['B','C'],['B','D'],['C','D']] Answer: Using [`itertools.combinations()`](http://docs.python.org/2/library/itertools.html#itertools.combinations): from itertools import combinations list(combinations(terms, r=2)) Demo: >>> from itertools import combinations >>> terms = ['A', 'B', 'C', 'D'] >>> list(combinations(terms, r=2)) [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')] These are tuples, not lists, but that's easily remedied if that is a problem: >>> map(list, combinations(terms, r=2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]
Django - test client receives 403 because of csrf Question: I'm using Django 1.6 and python 3.3. I'm trying to test POST form with django test client, and it receives 403 after sending request. If I add `@csrf_exempt` at my view method, everything works perfect. But the Django documentation says that it should work with enabled csrf protection fine: > For this reason, Django’s HTTP client for tests has been modified to set a > flag on requests which relaxes the middleware and the csrf_protect decorator > so that they no longer rejects requests. Here is my test code: def testSimple(self): c = Client('Chrome 1.0') from partners.views import cashier response = c.post(reverse(cashier.simple), {'x': 123}) self.assertContains(response,'html') And here is a view: def simple(request): return render(request, 'partners/cashier/index.html') And when I run this test I see: > AssertionError: 403 != 200 So, can you please tell me what I'm doing wrong? Answer: Client() has the following `__init__`: `def __init__(self, enforce_csrf_checks=False, **defaults):` You're setting enforce_csrf_checks to True b/c 'Chrome 1.0' evaluates to truthy! If you want to set the user agent: `c = Client(HTTP_USER_AGENT='Mozilla/5.0')`
How to expose Python callbacks to Fortran using modules Question: [This scipy documentation page](http://docs.scipy.org/doc/numpy- dev/f2py/python-usage.html#call-back-arguments) about F2Py states: > [Callback functions] may also be explicitly set in the module. Then it is > not necessary to pass the function in the argument list to the Fortran > function. This may be desired if the Fortran function calling the python > callback function is itself called by another Fortran function. However, I can't seem to find an example of how this would be done. Consider the following Fortran / Python combination: **test.f** : subroutine test(py_func) use iso_fortran_env, only stdout => output_unit !f2py intent(callback) py_func external py_func integer py_func !f2py integer y,x !f2py y = py_func(x) integer :: a integer :: b a = 12 write(stdout, *) a end subroutine **call_test.py** : import test def func(x): return x * 2 test.test(func) Compiled with the following command (Intel compiler): python f2py.py -c test.f --fcompiler=intelvem -m test What changes would I have to take to expose `func` to the entire Fortran program in the form of a module, so that I could call the function from inside the subroutine `test`, or any other subroutine in any other fortran file in the project? Answer: The following worked for me. Note the absence of the parameters passed to test. The python file is as stated in the question. subroutine test() use iso_fortran_env, only stdout => output_unit !f2py intent(callback) py_func external py_func integer py_func integer y,x !f2py y = py_func(x) integer :: a integer :: b a = 12 write(stdout, *) a end subroutine As an aside, I then wrapped `py_func` in a subroutine so that I could call it without having to declare the following in every file / function I use it: integer y y = py_func(x)
Python 3 rounding behavior in Python 2 Question: In Python 2.x, the built-in [`round`](http://docs.python.org/2/library/functions.html#round) has the following behavior: > if two multiples are equally close, rounding is done **away from 0** (so. > for example, round(0.5) is 1.0 and round(-0.5) is -1.0) In Python 3.x, [this has changed](http://docs.python.org/3/library/functions.html#round) to the more common: > if two multiples are equally close, rounding is done **toward the even > choice** (so, for example, both round(0.5) and round(-0.5) are 0, and > round(1.5) is 2). Is there an easy way to get this behavior in Python 2.x? Unfortunately, the [`future_builtins`](http://docs.python.org/2/library/future_builtins.html) module doesn't include this. Maybe there's another similar module I haven't found yet? Or, another way to pull Python 3.x functions into Python 2.x? Obviously, I could write a new function that produces the desired behavior, but I'm more curious if a solution exists that uses the actual Python 3.x function, to avoid adding unnecessary complexity and code to maintain. Answer: Unless you mind a numpy dependency, [`numpy.around`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html) may do the thing: >>> from numpy import around >>> around(0.5) 0 >>> around(-0.5) -0 >>> around(1.5) 2.0
Python - extending properties like you'd extend a function Question: ## Question **How can you extend a python property?** A subclass can extend a super class's function by calling it in the overloaded version, and then operating on the result. Here's an example of what I mean when I say "extending a function": # Extending a function (a tongue-in-cheek example) class NormalMath(object): def __init__(self, number): self.number = number def add_pi(self): n = self.number return n + 3.1415 class NewMath(object): def add_pi(self): # NewMath doesn't know how NormalMath added pi (and shouldn't need to). # It just uses the result. n = NormalMath.add_pi(self) # In NewMath, fractions are considered too hard for our users. # We therefore silently convert them to integers. return int(n) **Is there an analogous operation to extending functions, but for functions that use the property decorator?** I want to do some additional calculations immediately after getting an expensive-to-compute attribute. I need to keep the attribute's access lazy. I don't want the user to have to invoke a special routine to make the calculations. basically, I don't want the user to ever know the calculations were made in the first place. However, the attribute must remain a property, since i've got legacy code I need to support. Maybe this is a job for decorators? If I'm not mistaken, decorator is a function that wraps another function, and I'm looking to wrap a property with some more calculations, and then present it as a property again, which seems like a similar idea... but I can't quite figure it out. ## My Specific Problem I've got a base class **LogFile** with an expensive-to-construct attribute **.dataframe**. I've implemented it as a property (with the property decorator), so it won't actually parse the log file until I ask for the dataframe. So far, it works great. I can construct a bunch (100+) LogFile objects, and use cheaper methods to filter and select only the important ones to parse. And whenever I'm using the same LogFile over and over, i only have to parse it the first time I access the dataframe. Now I need to write a LogFile subclass, **SensorLog** , that adds some extra columns to the base class's dataframe attribute, but I can't quite figure out the syntax to call the super class's dataframe construction routines (without knowing anything about their internal workings), then operate on the resulting dataframe, and _then_ cache/return it. # Base Class - rules for parsing/interacting with data. class LogFile(object): def __init__(self, file_name): # file name to find the log file self.file_name = file_name # non-public variable to cache results of parse() self._dataframe = None def parse(self): with open(self.file_name) as infile: ... ... # Complex rules to interpret the file ... ... self._dataframe = pandas.DataFrame(stuff) @property def dataframe(self): """ Returns the dataframe; parses file if necessary. This works great! """ if self._dataframe is None: self.parse() return self._dataframe @dataframe.setter def dataframe(self,value): self._dataframe = value # Sub class - adds more information to data, but does't parse # must preserve established .dataframe interface class SensorLog(LogFile): def __init__(self, file_name): # Call the super's constructor LogFile.__init__(self, file_name) # SensorLog doesn't actually know about (and doesn't rely on) the ._dataframe cache, so it overrides it just in case. self._dataframe = None # THIS IS THE PART I CAN'T FIGURE OUT # Here's my best guess, but it doesn't quite work: @property def dataframe(self): # use parent class's getter, invoking the hidden parse function and any other operations LogFile might do. self._dataframe = LogFile.dataframe.getter() # Add additional calculated columns self._dataframe['extra_stuff'] = 'hello world!' return self._dataframe @dataframe.setter def dataframe(self, value): self._dataframe = value Now, when these classes are used in an interactive session, the user should be able to interact with either in the same way. >>> log = LogFile('data.csv') >>> print log.dataframe #### DataFrame with 10 columns goes here #### >>> sensor = SensorLog('data.csv') >>> print sensor.dataframe #### DataFrame with 11 columns goes here #### I have lots of existing code that takes a **LogFile** instance which provides a **.dataframe** attribute and dos something interesting (mostly plotting). I would LOVE to have **SensorLog** instances present the same interface so they can use the same code. Is it possible to extend the super-class's dataframe getter to take advantage of existing routines? How? Or am I better off doing this a different way? Thanks for reading that huge wall of text. You are an internet super hero, dear reader. Got any ideas? Answer: You should be calling the superclass properties, not bypassing them via `self._dataframe`. Here's a generic example: class A(object): def __init__(self): self.__prop = None @property def prop(self): return self.__prop @prop.setter def prop(self, value): self.__prop = value class B(A): def __init__(self): super(B, self).__init__() @property def prop(self): value = A.prop.fget(self) value['extra'] = 'stuff' return value @prop.setter def prop(self, value): A.prop.fset(self, value) And using it: b = B() b.prop = dict((('a', 1), ('b', 2))) print(b.prop) Outputs: {'a': 1, 'b': 2, 'extra': 'stuff'} I would generally recommend placing side-effects in setters instead of getters, like this: class A(object): def __init__(self): self.__prop = None @property def prop(self): return self.__prop @prop.setter def prop(self, value): self.__prop = value class B(A): def __init__(self): super(B, self).__init__() @property def prop(self): return A.prop.fget(self) @prop.setter def prop(self, value): value['extra'] = 'stuff' A.prop.fset(self, value) Having costly operations within a getter is also generally to be avoided (such as your parse method).
it is possible to download GitHub repository to my local computer Question: hello friends i just started to use GitHub and i just want to know it is possible to download github repository to my local computer through by Using GitHub Api or Api libraries (ie. python library " pygithub3" for Github api) Answer: Using [`github3.py`](http://github3py.rtfd.org/) you can clone all of your repositories (including forks and private repositories) by doing: import github3 import subprocess g = github3.login('username', 'password') for repo in g.iter_repos(type='all'): subprocess.call(['git', 'clone', repo.clone_url]) If you're looking to clone an arbitrary repository you can do this: import github3 import subprocess r = github3.repository('owner', 'repository_name') subprocess.call(['git', 'clone', repo.clone_url]) pygithub3 has not been actively developed in over a year. I would advise not use it since it is unmaintained and missing a large number of the additions GitHub has made to their API since then.
python lxml.html: returns null list for yahoo finance Question: The following code returns an empty list; import lxml.html url = 'http://finance.yahoo.com/q/pr?s=AYR+Profile' content = lxml.html.parse(url) sector = content.xpath('//*[@id="yfncsumtab"]/tbody/tr[2]/td[1]/table[2]/tbody/tr/td/table/tbody/tr[2]/td[2]/a') print sector [] I cross checked on the console in chrome .. $x('//*[@id="yfncsumtab"]/tbody/tr[2]/td[1]/table[2]/tbody/tr/td/table/tbody/tr[2]/td[2]/a')[0].text and I get the output as; 'Services' Where am I messing up? Answer: In the `html` code resolved by `lxml` there aren't `<tbody>` elements, so you have to omit them in the `xpath` expression. Also, add `text()` at the end to extract the content of the link: sector = content.xpath('//*[@id="yfncsumtab"]/tr[2]/td[1]/table[2]/tr/td/table/tr[2]/td[2]/a/text()')
Using storm in python Question: I want to make a hello world in python using storm. My server manager(Linux server) have told me that storm is installed on the server and I'm seeing the control panel now. When I'm trying to import storm as this tutorial mentioned: <https://storm.canonical.com/Tutorial#Importing> an error says: ImportError: No module named storm What should I do to import this library? Answer: What's your OS version? It might doesn't install success. Your OS version in that ppa doesn't work. Try: sudo apt-get --purge remove python-storm sudo rm -rf /etc/apt/sources.list.d/storm-ppa-*.list sudo apt-get update sudo apt-get install python-storm Or use [pypi](https://pypi.python.org/pypi/storm) to reinstall
Unable to call python Function in Webkit report Openerp Question: My report file contains class AccountInvoice_Report(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(AccountInvoice_Report, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'cr':cr, 'uid': uid, 'get_address': self.get_address, }) and I have written get_address function. when i call that function in my mako file as <% get_address() %> Then it gives Error as File "memory:0xb23c67ccL", line 208, in render_body <% get_address()%> TypeError: 'Undefined' object is not callable What mistake I am doing file defining or calling the function. Answer: **my_parser.py** import time from openerp.report import report_sxw class AccountInvoice_Report(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(AccountInvoice_Report, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'cr':cr, 'uid': uid, 'get_address': self.get_address,}) def get_address(self): #your code return 'address' report_sxw.report_sxw('report.your_report_name', 'model', 'path/to/mako', parser=AccountInvoice_Report) Include this parser in `__init__.py` import my_parser also don't forget to import your report folder in main `__init__.py`
How to read hundreds of csv files from a directory and sum a specific column from each of them? Question: I have around 650 csv files in a directory. Each of them have three columns with header(#ch# ##kev## ###count###), and 2050 rows.One of the file image is shown here partly. ch kev count 0 0 0 1 0 0 2 0 0 . . . . . . . . . 100 0 30 101 0 70 . . . . . . 200 . 1000 201 0 1037 . . . . . . 2050 0 0 I would like to sum of column(###count###) for a specific range (100 -200) of value of column(#ch#). I am able to write the program only for a single csv file is show below: import csv cr = csv.reader(open("D:\\Pythontest\\test1.csv", 'r')) cr.next() ['ch', 'kev', 'count'] total = 0 for row in cr: if 100 <= int(row[0]) <= 200: total += int(row[2]) print total But I don't know how to write the program for all of the files at a time. I would like to extract sum value from each of the file and put them together in a separate file. I am using Python 2.7. Answer: Since you have a working program for one file all you need is a way to use that program on each file. I suggest doing the following: * Learn how to use the glob module to list all the csv files, <http://pymotw.com/2/glob/> * Move your code to a function, <http://www.tutorialspoint.com/python/python_functions.htm>, taking the filename as an argument and returning the total for that file. * Loop over each file that glob gives you and run the function, adding up the total as you go. Good luck and if you run into a problem with one of the steps feel free to post a new question that's more specific.
Error when trying to use pymysql with sqlalchemy sre_constants.error: nothing to repeat Question: I tried to use pymsql with sqlalchemy using this code : from sqlalchemy import create_engine engine = create_engine("mysql+pymsql://root:@localhost/pydb") conn = engine.connect() and this exception is raised here is the full stack trace : Traceback (most recent call last): File "D:\Parser\dal__init__.py", line 3, in engine = create_engine("mysql+pymsql://root:@localhost/pydb") File "C:\Python33\lib\site-packages\sqlalchemy-0.9.2-py3.3.egg\sqlalchemy\engine__init__.py", line 344, in create_engine File "C:\Python33\lib\site-packages\sqlalchemy-0.9.2-py3.3.egg\sqlalchemy\engine\strategies.py", line 48, in create File "C:\Python33\lib\site-packages\sqlalchemy-0.9.2-py3.3.egg\sqlalchemy\engine\url.py", line 163, in make_url File "C:\Python33\lib\site-packages\sqlalchemy-0.9.2-py3.3.egg\sqlalchemy\engine\url.py", line 183, in _parse_rfc1738_args File "C:\Python33\lib\re.py", line 214, in compile return _compile(pattern, flags) File "C:\Python33\lib\re.py", line 281, in _compile p = sre_compile.compile(pattern, flags) File "C:\Python33\lib\sre_compile.py", line 498, in compile code = _code(p, flags) File "C:\Python33\lib\sre_compile.py", line 483, in _code _compile(code, p.data, flags) File "C:\Python33\lib\sre_compile.py", line 75, in _compile elif _simple(av) and op is not REPEAT: File "C:\Python33\lib\sre_compile.py", line 362, in _simple raise error("nothing to repeat") sre_constants.error: nothing to repeat Answer: Drop the `:` from your connection string after your username. It should instead be `mysql+pymsql://root@localhost/pydb`
Python backtracking strings lenght n from alphabet {a,b,c} with #a=#b Question: i want to make an algoritm that finds for a given n the strings made on the alphabet {a,b,c} in which the number 'a' appears the same times of 'b' i came out with this n=3 #length String h=-1 #length prefix L=['a','b','c'] #alphabet S=['','','',''] #solution par=0 # it's zero if a and b have same occurence def P(n,h,par,L,S): if h==n: if par==0: print(S) else: for i in L: if i=='a': par+=1 if i=='b': par-=1 S[h+1]=i P(n,h+1,par,L,S) #Update the stack after recursion if S[h+1]=='a': par-=1 if S[h+1]=='b': par+=1 P(n,h,par,L,S) i apologize for the poor string implementation but it works and it's only for studying purpose, the question is: there are ways to avoid some work for the algorithm? because it only checks #a and #b in the end after have generate all n-length strings for this alphabet. my goal is to achieve O(n*(number of strings to print)) Answer: Is this what you're trying to do: from itertools import combinations_with_replacement alphabet = "abc" def combs(alphabet, r): for comb in combinations_with_replacement(alphabet, r): if comb.count('a') == comb.count('b'): yield comb For this, list(combs(alphabet, 3)) == [('a', 'b', 'c'), ('c', 'c', 'c')] and list(combs(alphabet, 4)) == [('a', 'a', 'b', 'b'), ('a', 'b', 'c', 'c'), ('c', 'c', 'c', 'c')] This will produce all combinations and reject some; according to [the docs for `combinations_with_replacement`](http://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement): > The number of items returned is `(n+r-1)! / r! / (n-1)!` when `n > 0`. where `n == len(alphabet)`.
Importing modules from different directories Question: I have a problem importing a module: It is under this directory `./dao` and the code that calls it is here `./core`. Schematically represented as: rnaspace/ __init__.py core/ __init__.py logger.py dao/ __init__.py storage_configuration_reader.py This is the error message: Traceback (most recent call last): File "logger.py", line 21, in <module> from rnaspace.dao.storage_configuration_reader import storage_configuration_reader ImportError: No module named rnaspace.dao.storage_configuration_reader This file it is there `/rnaspace/dao/storage_configuration_reader.py` and in the same folder the `__init__.py` file as follows: """ Package dao Gathers files that access to the plateform data """ If I understood well [this question](http://stackoverflow.com/q/1260792/2886003), it should work. I think that the problem is that one is not the subdirectory of the other (or that the path is not exaclly that one), there is a way to go around it? Or need I to apply the solution to [this question](http://stackoverflow.com/questions/11068198/no-module-named-fitness- python-import-error?lq=1)? **EDIT** The `__init__.py` file of the rnaspace folder: import rnaspace.dao.storage_configuration_reader as scr def update_conf(conf_path, predictors_conf_dir): scr.update_conf(conf_path, predictors_conf_dir) Answer: from rnaspace.dao.storage_configuration_reader import storage_configuration_reader That is wrong because there is no "storage_configuration_reader" directory in "dao" directory This is how it should be: from rnaspace.dao import storage_configuration_reader **EDIT:** or this way: import rnaspace.dao.storage_configuration_reader
How do I open a text file in TextEdit from Python on Mac? Question: else: tkMessageBox.showinfo('Report Created', 'Your report was sucessfully created') file = 'Student Report.txt' os.system('TextEdit'+file) I am writing a program that creates a report from data from a database, writes that data to a text file and then is supposed to launch that text file so that it can be printed. How do I achieve this? I have attempted to use webbrowser but no luck. Answer: You can use the `/usr/bin/open` OSX utility: NAME open -- open files and directories SYNOPSIS open [-e] [-t] [-f] [-F] [-W] [-R] [-n] [-g] [-h] [-b bundle_identifier] [-a application] file ... [--args arg1 ...] DESCRIPTION The open command opens a file (or a directory or URL), just as if you had double-clicked the file's icon. If no application name is specified, the default application as deter- mined via LaunchServices is used to open the specified files. If the file is in the form of a URL, the file will be opened as a URL. You can specify one or more file names (or pathnames), which are interpreted relative to the shell or Terminal window's current working directory. For example, the following com- mand would open all Word files in the current working directory: open *.doc Opened applications inherit environment variables just as if you had launched the application directly through its full path. This behavior was also present in Tiger. You should also use the [`subprocess` module](http://docs.python.org/2/library/subprocess.html#using-the-subprocess- module) instead of `os.system`, as it is much easier to avoid escaping issues with it: import subprocess subprocess.call(['open', '-a', 'TextEdit', file])
collect all directories matching criteria from directory tree in python Question: How can I collect all directories that match a criteria (like 'contain a file named foo.txt') recursively from a directory tree? something like: def has_my_file(d): return ('foo.txt' in os.listdir(d)) walk_tree(dirname, criterion=has_my_file) for the tree: home/ bob/ foo.txt sally/ mike/ foo.txt `walk_tree` should return: ['home/bob/', 'home/sally/mike'] is there such a function in python libraries? Answer: Use [`os.walk`](http://docs.python.org/3/library/os.html#os.walk): import os result = [] for parent, ds, fs in os.walk(dirname): if 'foo.txt' in fs: result.append(parent) Using list comprehension: result = [parent for parent, ds, fs in os.walk(dirname) if 'foo.txt' in fs]
Sorting a list of tuples in python according to an element index Question: How can I sort a list of tuples according to the int in a certain position? (without a for loop) eg. Sorting `l = [(1,5,2),(7,1,4),(1,6,3)]` according to the third element in each tuple? Answer: You can use [`list.sort`](http://docs.python.org/3/library/stdtypes.html#list.sort), its key function, and [`operator.itemgetter`](http://docs.python.org/3/library/operator.html#operator.itemgetter): >>> from operator import itemgetter >>> l = [(1,5,2),(7,1,4),(1,6,3)] >>> l.sort(key=itemgetter(2)) >>> l [(1, 5, 2), (1, 6, 3), (7, 1, 4)] >>> * * * You could also use a [lambda function](http://docs.python.org/3/tutorial/controlflow.html#lambda- expressions) instead of `operator.itemgetter`: >>> l = [(1,5,2),(7,1,4),(1,6,3)] >>> l.sort(key=lambda x: x[2]) >>> l [(1, 5, 2), (1, 6, 3), (7, 1, 4)] >>> However, the latter is [generally faster](http://stackoverflow.com/a/17243726/2555451).
multiple argument from terminal using python Question: I am able to run this properly using os.system. It is writing pcap file into text. os.system("tshark -z 'proto,colinfo,tcp.srcport,tcp.srcport' -r filename.pcap > testfile") But when I tried to give input file from termimal, I got following error: tshark: -z invalid argument host = raw_input("Enter file name: ") test = subprocess.Popen(["tshark","-z","'proto,colinfo,tcp.srcport,tcp.srcport'","-r",host,">","testfile"], stdout=subprocess.PIPE) output = test.communicate()[0] Can anybody please figure out where I am making mistake? Answer: To emulate the `os.system` command, use the `shell=True` parameter to `subprocess.Popen` and provide the same command string (not an array of strings): subprocess.Popen("tshark -z 'proto,colinfo,tcp.srcport,tcp.srcport' -r " + host + "> testfile", stdout=subprocess.PIPE, shell=True) You need a shell to interpret your command line as you are using output redirection to a file ("> testfile"). In your example, you are passing each element of the string list to the execve() system call and hence as parameters to the `tshark` command (which gets `'proto,colinfo,tcp.srcport,tcp.srcport'` as the argument to the `-z` option instead of `proto,colinfo,tcp.srcport,tcp.srcport` and which won't know what to do with the `>` and `testfile` arguments). As wnnmaw points out in his comment, using `os.system` or `subprocess.Popen` with `shell=True` with command lines built from user input (the `host` variable in your case) allows a user to pass arbitrary data to the shell. This can be used to execute (potentially nasty) commands on your system. For instance, setting `host` in your example to `; /bin/rm -rf /` would delete every file on a UNIX system (assuming the user running the process had enough privilege). It is therefore very important to validate an user input before adding it to the command string.
python-dpkt: ICMP packet parsing Question: How can I parse a ICMP packet (using dpkt) to check if it is a request or a response coming from A to B? I found some examples for TCP and UDP packets (below) but I can't find anything for IP packets. import dpkt f = open('test.pcap') pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data if tcp.dport == 80 and len(tcp.data) > 0: http = dpkt.http.Request(tcp.data) print http.uri f.close() Also, is there any good tutorial for dpkt? Answer: This is an old question but for folks coming across this, I've added an ICMP example to the dpkt repo. The docs can be found here: <http://dpkt.readthedocs.io/en/latest/print_icmp.html> and the example code can be found in dpkt/examples/print_icmp.py # For each packet in the pcap process the contents for timestamp, buf in pcap: # Unpack the Ethernet frame (mac src/dst, ethertype) eth = dpkt.ethernet.Ethernet(buf) # Make sure the Ethernet data contains an IP packet if not isinstance(eth.data, dpkt.ip.IP): print 'Non IP Packet type not supported %s\n' % eth.data.__class__.__name__ continue # Now grab the data within the Ethernet frame (the IP packet) ip = eth.data # Now check if this is an ICMP packet if isinstance(ip.data, dpkt.icmp.ICMP): icmp = ip.data # Pull out fragment information do_not_fragment = bool(ip.off & dpkt.ip.IP_DF) more_fragments = bool(ip.off & dpkt.ip.IP_MF) fragment_offset = ip.off & dpkt.ip.IP_OFFMASK # Print out the info print 'Timestamp: ', str(datetime.datetime.utcfromtimestamp(timestamp)) print 'Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst), eth.type print 'IP: %s -> %s (len=%d ttl=%d DF=%d MF=%d offset=%d)' % \ (inet_to_str(ip.src), inet_to_str(ip.dst), ip.len, ip.ttl, do_not_fragment, more_fragments, fragment_offset) print 'ICMP: type:%d code:%d checksum:%d data: %s\n' % (icmp.type, icmp.code, icmp.sum, repr(icmp.data)) **Example Output** Timestamp: 2013-05-30 22:45:17.283187 Ethernet Frame: 60:33:4b:13:c5:58 02:1a:11:f0:c8:3b 2048 IP: 192.168.43.9 -> 8.8.8.8 (len=84 ttl=64 DF=0 MF=0 offset=0) ICMP: type:8 code:0 checksum:48051 data: Echo(id=55099, data='Q\xa7\xd6}\x00\x04Q\xe4\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./01234567') Timestamp: 2013-05-30 22:45:17.775391 Ethernet Frame: 02:1a:11:f0:c8:3b 60:33:4b:13:c5:58 2048 IP: 8.8.8.8 -> 192.168.43.9 (len=84 ttl=40 DF=0 MF=0 offset=0) ICMP: type:0 code:0 checksum:50099 data: Echo(id=55099, data='Q\xa7\xd6}\x00\x04Q\xe4\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./01234567')
python - pull pdfs from webpage and convert to html Question: My goal is to have a python script that will access particular webpages, extract all pdf files on each page that have a certain word in their filename, convert them into html/xml, then go through the html files to read data from the pdfs' tables. So far I have imported mechanize (for browsing the pages/finding the pdf files) and I have pdfminer, however I'm not sure how to use it in a script to perform the same functionality it does on the command line. What is the most effective group of libraries for accomplishing my task, and how would you recommend approaching each step? I apologize if this is too specific for stackoverflow, but I'm having trouble using google searches and sparse documentation to piece together how to code this. Thanks! EDIT: So I've decided to go with Scrapy on this one. I'm really liking it so far, but now I have a new question. I've defined a PDFItem() class to use with my spider with fields title and url. I have a selector thats grabbing all the links I want, and I want to go through these links and create a PDFItem for each one. Here's the code I have below: links = sel.xpath('//a[contains(@href, "enforcementactions.pdf") and contains(@class, "titlelink")]') item = PDFItem() for link in links: item['title'] = link.xpath('/text()') item['url'] = URL + link.xpath('@href').extract()[0] The url line works well, but I don't really know how to do the same for title. I guess I could just perform the query at the top, but adding '/text()' to the end of the selector, but this seems excessive. Is there a better way to just go through each link object in the links array and grab the text and href value? Answer: I would use [Scrapy](http://scrapy.org/). Scrapy is the best tool for crawling an entire website and generating a list of all PDF links. A spider like this would be very easy to write. You definitely don't need Mechanize. After that, I would use [Poppler](http://poppler.freedesktop.org/) to convert each PDF to HTML. It's not a Python module, but you can use the command `pdftohtml`. In my experience, I've had better results with Poppler than PDFMiner. **Edit:** links = sel.xpath('//a[contains(@href, "enforcementactions.pdf") and contains(@class, "titlelink")]') for link in links: item = PDFItem() item['title'] = link.xpath('text()').extract()[0] item['url'] = URL + link.xpath('@href').extract()[0]
Android Bluetooth Client and Server Won't Connect Question: I am currently trying to create an app that connects Google Glass(client) to my computer(python server). I would like to send simple strings. I have tried multiple ways but haven't had much luck. I am currently using some sample code I found. After running both, i get the message > "In onResume() and an exception occurred during write: Socket Closed" on Glass, and my computer(HP Pavillion Dv6 running Ubuntu 12.04 with Bluetooth Dongle) completely freezes. One time the GUI itself crashed and I was looking at a stack trace on the console(that scary black screen). Here is the client code: import java.io.IOException; import java.io.OutputStream; import java.util.UUID; import com.myPackage.glassbluetooth.R; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; public class ConnectTest extends Activity { TextView out; private static final int REQUEST_ENABLE_BT = 1; private BluetoothAdapter btAdapter = null; private BluetoothSocket btSocket = null; private OutputStream outStream = null; // Well known SPP UUID private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Insert your server's MAC address private static String address = "00:1F:81:00:08:30"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); out = (TextView) findViewById(R.id.out); out.append("\n...In onCreate()..."); btAdapter = BluetoothAdapter.getDefaultAdapter(); CheckBTState(); } @Override public void onStart() { super.onStart(); out.append("\n...In onStart()..."); } @Override public void onResume() { super.onResume(); out.append("\n...In onResume...\n...Attempting client connect..."); // Set up a pointer to the remote node using it's address. BluetoothDevice device = btAdapter.getRemoteDevice(address); // Two things are needed to make a connection: // A MAC address, which we got above. // A Service ID or UUID. In this case we are using the // UUID for SPP. try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); } // Discovery is resource intensive. Make sure it isn't going on // when you attempt to connect and pass your message. btAdapter.cancelDiscovery(); // Establish the connection. This will block until it connects. Log.d("CONNECTTEST", "Try to open socket"); try { btSocket.connect(); Log.d("CONNECTTEST", "btSocket.connect executed"); out.append("\n...Connection established and data link opened..."); } catch (IOException e) { try { btSocket.close(); } catch (IOException e2) { AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); } } // Create a data stream so we can talk to server. out.append("\n...Sending message to server..."); try { outStream = btSocket.getOutputStream(); } catch (IOException e) { AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + "."); } String message = "Hello from Android.\n"; byte[] msgBuffer = message.getBytes(); try { outStream.write(msgBuffer); } catch (IOException e) { String msg = "In onResume() and an exception occurred during write: " + e.getMessage(); if (address.equals("00:00:00:00:00:00")) msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code"; msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n"; AlertBox("Fatal Error", msg); } } @Override public void onPause() { super.onPause(); out.append("\n...In onPause()..."); if (outStream != null) { try { outStream.flush(); } catch (IOException e) { AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + "."); } } try { btSocket.close(); } catch (IOException e2) { AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + "."); } } @Override public void onStop() { super.onStop(); out.append("\n...In onStop()..."); } @Override public void onDestroy() { super.onDestroy(); out.append("\n...In onDestroy()..."); } private void CheckBTState() { // Check for Bluetooth support and then check to make sure it is turned on // Emulator doesn't support Bluetooth and will return null if(btAdapter==null) { AlertBox("Fatal Error", "Bluetooth Not supported. Aborting."); } else { if (btAdapter.isEnabled()) { out.append("\n...Bluetooth is enabled..."); } else { //Prompt user to turn on Bluetooth Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } } public void AlertBox( String title, String message ){ new AlertDialog.Builder(this) .setTitle( title ) .setMessage( message + " Press OK to exit." ) .setPositiveButton("OK", new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }).show(); } } and here is the server code: from bluetooth import * server_sock=BluetoothSocket( RFCOMM ) server_sock.bind(("",PORT_ANY)) server_sock.listen(1) port = server_sock.getsockname()[1] uuid = "1aefbf9b-ea60-47de-b5a0-ed0e3a36d9a5" testUuid = "00001101-0000-1000-8000-00805F9B34FB" advertise_service( server_sock, "GlassServer", service_id = testUuid, service_classes = [ uuid, SERIAL_PORT_CLASS ], profiles = [ SERIAL_PORT_PROFILE ], # protocols = [ OBEX_UUID ] ) print("Waiting for connection on RFCOMM channel %d" % port) client_sock, client_info = server_sock.accept() print("Accepted connection from ", client_info) try: while True: data = client_sock.recv(1024) if len(data) == 0: break print("received [%s]" % data) except IOError: pass print("disconnected") client_sock.close() server_sock.close() print("all done") Here is the output of hcitool: $ hcitool scan Scanning ... F4:B7:E2:F9:74:63 GLASS-YUKON $ hcitool dev Devices: hci0 00:1F:81:00:08:30 Does anyone have any idea whats going on? Also, if you know of any relevant sample programs that might work I would be interested in trying them! Thanks in advance! Bump, can anyone help with this? After experimenting with a computer which had bluetooth capabilities built in, I was able to hone in on the problem a little more. The problem occurs when the code attempts to create the RFComm socket. Using the code I have now, I get an exception Service Discovery failed. I got rid of that error after using the advice found here: [Service discovery failed exception using Bluetooth on Android ](http://stackoverflow.com/questions/3397071/service-discovery-failed- exception-using-bluetooth-on-android) but now I get an exception that says "Host is down". None of the fixes I found worked. Any ideas? Answer: I can answer one part of my question: The kernel panic is not due to my code but rather faulty driver software for my Bluetooth Dongle. I tried the code on a computer which natively had Bluetooth capabilities and I got the same results sans the kernel panic.
left hand side eigenvector in python? Question: How do calculate the left hand side eigenvector in python? >>> import from numpy as np >>> from scipy.linalg import eig >>> np.set_printoptions(precision=4) >>> T = np.mat("0.2 0.4 0.4;0.8 0.2 0.0;0.8 0.0 0.2") >>> print "T\n", T T [[ 0.2 0.4 0.4] [ 0.8 0.2 0. ] [ 0.8 0. 0.2]] >>> w, vl, vr = eig(T, left=True) >>> vl array([[ 0.8165, 0.8165, 0. ], [ 0.4082, -0.4082, -0.7071], [ 0.4082, -0.4082, 0.7071]]) This does not seem correct, google has not been kind on this! Answer: Your result is correct to my understanding. However, you might be misinterpreting it. The [numpy docs](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html) are a bit clearer on what the left eigenvectors should be. > Finally, it is emphasized that v consists of the right (as in right-hand > side) eigenvectors of a. A vector y satisfying dot(y.T, a) = z * y.T for > some number z is called a left eigenvector of a, and, in general, the left > and right eigenvectors of a matrix are not necessarily the (perhaps > conjugate) transposes of each other. I.e. you need to transpose the vectors in `vl`. `vl[:,i].T` is the i-th left eigenvector. If I test this, I get, that the results are correct. >>> import numpy as np >>> from scipy.linalg import eig >>> np.set_printoptions(precision=4) >>> T = np.mat("0.2 0.4 0.4;0.8 0.2 0.0;0.8 0.0 0.2") >>> print "T\n", T T [[ 0.2 0.4 0.4] [ 0.8 0.2 0. ] [ 0.8 0. 0.2]] >>> w, vl, vr = eig(T, left=True) >>> vl array([[ 0.8165, 0.8165, 0. ], [ 0.4082, -0.4082, -0.7071], [ 0.4082, -0.4082, 0.7071]]) >>> [ np.allclose(np.dot(vl[:,i].T, T), w[i]*vl[:,i].T) for i in range(3) ] [True, True, True]
Can't import shared.SharedService in thrift tutorial Question: I seem to be mis-understanding something about Apache Thrift. I have it installed and generated python bindings using the tutorial.thrift file. I manipulated my `PYTHONPATH` environmental variable to allow me to import from the generated files. When I import `tutorial.Calculator' it can't find`shared.SharedService`. Is this a dependency of Apache Thrift or something I have to define? ericu@eric-phenom-linux:~/tmp$ export PYTHONPATH=$PYTHON:`pwd`/gen-py ericu@eric-phenom-linux:~/tmp$ echo $PYTHONPATH :/home/ericu/tmp/gen-py ericu@eric-phenom-linux:~/tmp$ c c: command not found ericu@eric-phenom-linux:~/tmp$ cd ericu@eric-phenom-linux:~$ pyhon No command 'pyhon' found, did you mean: Command 'python' from package 'python-minimal' (main) pyhon: command not found ericu@eric-phenom-linux:~$ python Python 2.7.5 Stackless 3.1b3 060516 (default, Sep 23 2013, 20:17:03) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tutorial >>> tutorial.Calculator Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'Calculator' >>> import tutorial.Calculator Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ericu/tmp/gen-py/tutorial/Calculator.py", line 10, in <module> import shared.SharedService ImportError: No module named shared.SharedService >>> Answer: The SharedService is part of another Thrift IDL file, which is included into the tutorial.thrift IDL file. Tbus, you have to generate the code for the Shared service as well. The easiest way is to call the Thrift compiler with the `-r` option ("recursive") which will generate code for the passed IDL file and all included dependencies. The tutorial pages are indeed misleading here. If you want to file a JIRA ticket, please do.
Xlsxwriter: TypeError: "expected string or buffer" Question: I have that exception, as described in the title, when trying to generate an excel file from a model which is filtered by a query. The query works as expected and gives me the right and complete results. However, the big deal occurs when I try to, actually, generate the excel file: File "/home/luismasuelli/Proyectos/CentralCar/main/views.py", line 100, in export_xls workbook.close() File "/home/luismasuelli/.virtualenvs/py27dj15/local/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 237, in close self._store_workbook() File "/home/luismasuelli/.virtualenvs/py27dj15/local/lib/python2.7/site-packages/xlsxwriter/workbook.py", line 405, in _store_workbook xml_files = packager._create_package() File "/home/luismasuelli/.virtualenvs/py27dj15/local/lib/python2.7/site-packages/xlsxwriter/packager.py", line 139, in _create_package self._write_shared_strings_file() File "/home/luismasuelli/.virtualenvs/py27dj15/local/lib/python2.7/site-packages/xlsxwriter/packager.py", line 265, in _write_shared_strings_file sst._assemble_xml_file() File "/home/luismasuelli/.virtualenvs/py27dj15/local/lib/python2.7/site-packages/xlsxwriter/sharedstrings.py", line 53, in _assemble_xml_file self._write_sst_strings() File "/home/luismasuelli/.virtualenvs/py27dj15/local/lib/python2.7/site-packages/xlsxwriter/sharedstrings.py", line 83, in _write_sst_strings self._write_si(string) File "/home/luismasuelli/.virtualenvs/py27dj15/local/lib/python2.7/site-packages/xlsxwriter/sharedstrings.py", line 95, in _write_si string = re.sub('(_x[0-9a-fA-F]{4}_)', r'_x005F\1', string) File "/home/luismasuelli/.virtualenvs/py27dj15/lib/python2.7/re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or buffer What could be causing me that exception? I tried to change the encoding to put utf8 as suggested but that doesn't help me here. I'm working with Xlsxwriter 0.5.2 / python 2.7.4 (ubuntu) from a django app, as follows: # -*- coding: utf8 -*- #... from StringIO import StringIO #... import datetime #... from django.http import HttpResponse, Http404 #... import xlsxwriter #... from main.models import Contact #... def export_xls(request, period=''): deltas = { 'D': datetime.timedelta(days=1), 'W': datetime.timedelta(days=7), 'M': datetime.timedelta(days=30), '6M': datetime.timedelta(days=182), 'Y': datetime.timedelta(days=365) } query = Contact.objects.all().order_by('-enviado_en') if period: query = query.filter(enviado_en__gt=datetime.datetime.now() - deltas[period]) stream = StringIO() workbook = xlsxwriter.Workbook(stream, {'in_memory': True}) worksheet = workbook.add_worksheet('Contactos') #poner encabezados header_format = workbook.add_format() header_format.set_align("center") header_format.set_bold() header_format.set_font_name('Arial') worksheet.set_column(9, 9, 40) worksheet.write_string(0, 0, Contact._meta.get_field('enviado_en').verbose_name, header_format) worksheet.write_string(0, 1, Contact._meta.get_field('nombre').verbose_name, header_format) worksheet.write_string(0, 2, Contact._meta.get_field('apellido').verbose_name, header_format) worksheet.write_string(0, 3, Contact._meta.get_field('email').verbose_name, header_format) worksheet.write_string(0, 4, Contact._meta.get_field('telefono').verbose_name, header_format) worksheet.write_string(0, 5, Contact._meta.get_field('ciudad').verbose_name, header_format) worksheet.write_string(0, 6, Contact._meta.get_field('vehiculo').verbose_name, header_format) worksheet.write_string(0, 7, Contact._meta.get_field('kilometraje').verbose_name, header_format) worksheet.write_string(0, 8, Contact._meta.get_field('dia_preferente').verbose_name, header_format) worksheet.write_string(0, 9, Contact._meta.get_field('mensaje').verbose_name, header_format) #poner cada fila body_format = workbook.add_format() body_format.set_font_name('Arial') current_row = 1 for contact in query: worksheet.write(current_row, 0, contact.enviado_en.strftime("%d/%m/%Y %H/%M/%S"), body_format) worksheet.write(current_row, 1, contact.nombre, body_format) worksheet.write(current_row, 2, contact.apellido, body_format) worksheet.write(current_row, 3, contact.email, body_format) worksheet.write(current_row, 4, contact.telefono, body_format) worksheet.write(current_row, 5, contact.ciudad, body_format) worksheet.write(current_row, 6, contact.get_vehiculo_display(), body_format) worksheet.write(current_row, 7, contact.get_kilometraje_display(), body_format) worksheet.write(current_row, 8, contact.get_dia_preferente_display(), body_format) worksheet.write(current_row, 9, contact.mensaje, body_format) current_row += 1 workbook.close() data = stream.getvalue() response = HttpResponse(content=data, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=reporte-%s.xlsx' % datetime.datetime.now().strftime("%Y%m%d%H%M%S") return response Being my model Contact: class Contact(models.Model): DIAS = ( #('?', 'Cualquiera'), ('L', 'Lunes'), ('M', 'Martes'), ('I', 'Miercoles'), ('J', 'Jueves'), ('V', 'Viernes'), ('S', 'Sábado') ) KILOMETRAJE = ( #('??', '(No especifica)'), ('00', '0km'), ('05', '1 - 5000km'), ('10', '5000km - 10000km'), ('15', '10001km - 15000km'), ('20', '15001km - 20000km'), ('25', '20001km - 25000km'), ('30', '25001km - 30000km'), ('35', '30001km - 35000km'), ('40', '35001km - 40000km'), ('45', '40001km - 45000km'), ('50', '45001km - 50000km'), ('55', '50001km - 55000km'), ('60', '55001km - 60000km'), ('65', '60001km - 65000km'), ('70', '65001km - 70000km'), ('75', '70001km - 75000km'), ('80', '75001km - 80000km'), ('85', '80001km - 85000km'), ('90', '85001km - 90000km'), ('95', '90001km - 950000km'), ('XX', '95001km - 100000km'), ('++', 'Más de 100000km') ) enviado_en = models.DateTimeField(default=tznow, null=False, db_index=True, verbose_name=_(u"Enviado en")) #campos de contacto nombre = models.CharField(max_length=30, null=False, blank=False, db_index=True, verbose_name=_(u"Nombre")) apellido = models.CharField(max_length=30, null=False, blank=False, db_index=True, verbose_name=_(u"Apellido")) email = models.EmailField(null=False, blank=False, db_index=True, verbose_name=_(u"E-mail")) telefono = models.CharField(max_length=10, null=False, blank=False, db_index=True, validators=[contact_phone_number_format], verbose_name=_(u"Teléfono")) ciudad = models.CharField(max_length=20, null=False, blank=False, validators=[validate_ciudad], verbose_name=_(u"Ciudad")) #campos solamente de cotizacion vehiculo = models.CharField(max_length=20, blank=True, db_index=True, choices=vehicle_choices(), verbose_name=_(u"Vehículo")) kilometraje = models.CharField(max_length=2, blank=True, db_index=True, choices=KILOMETRAJE, default='05', verbose_name=_(u"Kilometraje")) #campos solamente de agendar cita dia_preferente = models.CharField(max_length=1, blank=True, choices=DIAS, default='L', verbose_name=_(u'Día para cita')) #mensaje mensaje = models.TextField(max_length=4095, null=False, blank=False, verbose_name=_(u"Mensaje")) assume vehicle_choices() exists and returns a valid choice set for the input field. Answer: I found the answer: verbose_name objects are, actually, proxies returned from ugettext_lazy. calling force_unicode(ugl_obj) converts them to string (conversion is not done automagically). in my case, each value in the header printing was wrapped, e.g.: worksheet.write_string(0, 0, force_unicode(Contact._meta.get_field('enviado_en').verbose_name), header_format)
Trying to make a shortcut through python Question: Python 2.7 from Tkinter import * import os class App: def __init__(self, master): self.frame = Frame(master) self.b = Button(self.frame, text = 'Open', command = self.openFile) self.b.grid(row = 1) self.frame.grid() def openFile(self): os.startfile("C:\Users\David\Desktop\minecraft.jar") root = Tk() app = App(root) root.mainloop() using py2exe it shows this error and its not compiling: SyntaxError: 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape Answer: You need to escape `\` in the following string literal. Otherwise, it is recognized as unicode escape sequence. >>> "C:\Users\David\Desktop\minecraft.jar" File "<stdin>", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape Explicitly escape them: >>> "C:\\Users\\David\\Desktop\\minecraft.jar" 'C:\\Users\\David\\Desktop\\minecraft.jar' or use raw string literals: >>> r"C:\Users\David\Desktop\minecraft.jar" 'C:\\Users\\David\\Desktop\\minecraft.jar' BTW, Python 2.x does not raise the SyntaxError for the string literal `"C:\Use..."` (unless you use `from __future__ import unicode_literals`). Check if you're using Python 3.x when using py2exe.
Struggling with recursive function, what am I doing wrong Question: I'm fairly new to python and understand that recursion is an important concept to grasp. I've been dabbling with various scripts to exercise my knowledge and have come up with the following script to simulate a lottery draw, where you simply draw six from 49 numbers and compare them with another six to see if you've won. I'm struggling though with the recursive function taking the value of another function. I'm sure it's going to be straightforwardish, but cannot fathom it myself. Here's my code so far: from random import randint def drawSix(): six = [] while len(six) < 6: a = randint(1,49) if a not in six: six.append(a) return sorted(six) def lottery(draw,ticket): if draw == ticket: return 'win' return lottery(drawSix(),drawSix()) I call the function with lottery(drawSix(),drawSix()) and get the following recursively. Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> lottery(drawSix(),drawSix()) File "/Users/johnhopkins/Desktop/lottery.py", line 14, in lottery return lottery(drawSix(),drawSix()) Answer: def lottery(draw,ticket): if draw == ticket: return 'win' return lottery(drawSix(),drawSix()) The odds of you actually generating two identical tickets are quite large, well over 1000 which is the maximum stack size of Python. You need to either do this iteratively to avoid blowing your stack. def lottery(draw,ticket): while draw != ticket: draw, ticket = drawSix(), drawSix() return "win" Note this has a very ugly `O(n)` of `O(inf)` you could end up running this forever if you were unlucky and still not finding a winning pair
Cython: How to expose void* and function pointer in struct? Question: I have a C header with: typedef struct { <normal members> void (*cb_func)(glp_tree *T, void *info); void *cb_info; <normal members> } glp_iocp; Currently, in my pxd file: ctypedef struct IntOptCP "glp_iocp": <normal members> int out_dly # mip.out_dly (milliseconds) #void (*cb_func)(Tree* tree, void* info) # mip.cb_func #void* cb_info # mip.cb_info <normal members> In a pyx file, at some point, I do (essentially): cdef class MyClass: IntOptCP _iocp <__cintit__ and the like> def some_method(self): <manipulation of self._iocp> controls = dict() controls = self._iocp return controls This works nicely. However, now I also wish to expose `cb_func` and `cb_info`. This then breaks the assignment to controls. What I would like to have is two python object types (classes?), one for `cb_func` and one for `cb_info`, instances of which can be passed through to `cb_func` and `cb_info` arguments of the `glp_iocp` struct. I have read <https://github.com/cython/cython/tree/master/Demos/callback> (and have used pycapsule), but nevertheless, I am too inexperienced/unfamiliar with Cython to see how I can use that information for my specific case. So, any help and pointers on how to (best) expose `cb_func` and `cb_info` are welcome. Answer: It seems you can expose `cb_func` and `cb_info` doing something similar to this toy example: import numpy as np cimport numpy as np ctypedef void (*f_type)(int, double*, double*) ctypedef struct IntOptCP: int a double *b double *c f_type f cdef class MyClass: cdef IntOptCP _iocp def exec_f(self): self._iocp.f(self._iocp.a, self._iocp.b, self._iocp.c) cdef void myfunc(int a, double *b, double *c): cdef int i for i in range(a): b[i] += 1 c[i] += 1 def main(): cdef f_type f cdef np.ndarray[np.float64_t, ndim=1] b, c cdef int a a = 100 b = np.zeros(a, dtype=np.float64) c = np.zeros(a, dtype=np.float64) test = MyClass() test._iocp.a = a test._iocp.b = &b[0] test._iocp.c = &c[0] test._iocp.f = myfunc print 'before', a, b, c test.exec_f() print 'after', a, b, c
Creating a specific python dictionary Question: Re-asking clearly my question : I want to produce this json output using flask.jsonify, how can I build the corresponding dictionary to do so ? { "cluster": { "members": [ { "name": "host1", "disks": [ { "fstype": "btrfs", "size": "62G", "status": "up" }, { "fstype": "btrfs", "size": "260G", "status": "up" }, { "fstype": "btrfs", "size": "263G", "status": "up" }, { "fstype": "btrfs", "size": "257G", "status": "up" } ] }, { "name": "host2", "disks": [ { "fstype": "btrfs", "size": "66G", "status": "up" }, { "fstype": "btrfs", "size": "259G", "status": "up" } ] }, { "name": "host3", "disks": [ { "fstype": "btrfs", "size": "62G", "status": "up" }, { "fstype": "btrfs", "size": "259G", "status": "up" }, { "fstype": "btrfs", "size": "257G", "status": "up" }, { "fstype": "btrfs", "size": "263G", "status": "up" } ] } ], "name": "MyCluster1", "status": "HEALTH_OK" } } Re-asking clearly my question : I want to produce this json output using flask.jsonify, how can I build the corresponding dictionary to do so ? Answer: If your long text field is a string called 'text', then you can load it as a json object like this: import json new = json.loads(text)
How do i output a single digit as a double digit in python 2.7 Question: I just started to play around with python and decided to make a random number generator for my lotto numbers and so far so good it works, and even got it to work in Tkinter. But i can't seem to figure out where and how to format the output so that it displays some nicely formatted rows of lists. Any help or suggestions would be greatly appreciated. Hugo The script I got working so far in python 2.7 import random from Tkinter import * import Tkinter as ttk def f(): my_list = [] while len(my_list) < 6: new_number = random.randrange(45) + 1 if new_number in my_list: continue my_list.append(new_number) winners = sorted(my_list) if len(my_list) == 6: return winners def genereer(*args): x = int(getal.get()) my_list2 = [] if x < 11: while len(my_list2) < x: f() my_list2.append(f()) for item in my_list2: ttk.Label(mainframe, text=item).grid(column=0, sticky=W) root = Tk() root.title("Lotto nummers generator.") mainframe = ttk.Frame(root) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(1, weight=1) mainframe.rowconfigure(1, weight=1) getal = StringVar() ttk.Label(mainframe, text="Hoeveel rijtjes will je spelen? (max 10)").grid(column=0, row=1,sticky=W) getal_entry = ttk.Entry(mainframe, width=3, textvariable=getal) getal_entry.grid(column=1, row=1, sticky=W) ttk.Button(mainframe, text="Genereer", command=genereer).grid(column=3, row=1, sticky=W) getal_entry.focus() root.bind("<Return>", genereer) root.mainloop() Answer: I was never using TKinter, but I tried sth like that: ... MAX_VALUE = 46 NUMS_PER_SAMPLE = 6 POOL = range(1, MAX_VALUE+1) def f(): return sorted(random.sample(POOL, NUMS_PER_SAMPLE)) def genereer(*args): x = int(getal.get()) if x > 10: return for x in range(x): for i, item in enumerate(f()): ttk.Label(mainframe, text=item).grid(row=x+2, column=i, sticky=E) ... It's not perfect, because it uses the same grid as initial label and button, but from that point you should be able to adjust it to your needs. I also simplified your code by taking advantage of standard library ([`random.sample`](http://docs.python.org/2/library/random.html#random.sample) is your friend).
What combination of python-mode, ipython, (ipython.el) versions/releases and init.el/.emacs.d code work? Question: My goal is to use Emacs 24 as my python editor ( also has a Matlab and R editor but that's not what my question is about ). (Please let me know if I left out any information or if I did not state something clearly.) I've been able to set up my packages and my init.el file in such a way that I'm able to get tab completion, correct highlighting and snippets for python. I'm using python-mode.el as my python mode. **The problems** all revolve around this: I want to use ipython as my python shell, in order to use its tab completion functions when debugging scripts. * However, when I start ipython (using M-x ipython) I have no tab completion. Furthermore, it does not show "[1] in:", however it does show "[1] out:". * I would like to make ipython my default shell in Emacs. However, attempts at this have failed (e.g. setting C:\PATH\TO\IPython.exe onto py-python-command). * When I try to run my python script using C-c C-c it runs using the normal Python, and indeed stops at the position I tell the debugger to stop (I use ipdb.set_trace). however when I use another type of command that is supposed to start IPython (like setting the region to my entire script and running py-execute-region-ipython) IPython does not function. It does start an IPython shell, or at least it seems to, but I can just type in the shell like it was a text editor (fyi: in the mini buffer it shows "Comint:run shell-compile"). **My question** is: What combination of package versions and lisp code in my init.el file should allow me to use ipython with tab completion as my default shell in Emacs? I am willing to downgrade some of the packages if necessary. **Extra info** : From what I've read on the Project page of Python-mode.el I understand that there are still some bugs regarding IPython with the latest version of this package, so it's probably necessary to use an old version. I've been googling a lot to search for a solution, and I've not been able to find one that works for me. I'm running * python-mode 6.1.3, * ipython 1.1.0 * I tried ipython.el from <https://raw.github.com/ipython/ipython/d2d967af9de6081c8cdbab0eab1115164e5e72bd/docs/emacs/ipython.el>, But from contact with the developer of python-mode.el this seems to be deprecated, and no integrated into python-mode.el. * GNU Emacs 24.3.1 (i386-mingw-nt6.1.7601) of 2013-03-17 on MARVIN * Windows 7 64bit. My init.el looks like (python stuff is at the bottom): ` ;; Requisites: Emacs >= 24 (require 'package) (package-initialize) (add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/")) (add-to-list 'package-archives '("marmalade" . "http://marmalade-repo.org/packages/") t) (package-refresh-contents) (defun install-if-needed (package) (unless (package-installed-p package) (package-install package))) ;; make more packages available with the package installer --> ;; removed python mode since the version I got had errors (setq to-install '( ;python-mode magit yasnippet jedi auto-complete autopair find-file-in-repository flycheck)) (mapc 'install-if-needed to-install) ;;------------R STUFF----------- (add-to-list 'load-path "C:\\emacs-24.3\\site-lisp\\ess-13.09-1") (setq ess-use-auto-complete t) (load "ess-site") ;;------------MatLab STUFF----------- ; add folder of matlab-mode.el (add-to-list 'load-path "C:\\Users\\Rob Ter Horst\\AppData\\Roaming\\.emacs.d\\elpa\\matlab-mode-20130829.142") (load-library "matlab-load") (matlab-cedet-setup) (setq matlab-show-mlint-warnings t) (add-hook 'matlab-mode-hook 'auto-complete-mode) (add-hook 'matlab-mode-hook 'mlint-minor-mode) ;;------------GENERAL STUFF----------- ; Ido mode: Ido-powered versions of code. Most ido commands are named ido-xxxxx ; so find-file becomes ido-find-file, and so on. (setq ido-enable-flex-matching t) (setq ido-everywhere t) (ido-mode t) (global-linum-mode t) ;Use y or n always instead of yes/no (defalias 'yes-or-no-p 'y-or-n-p) ;; -------------------- extra nice things Andrea Crotti-------------------- ;; use shift to move around windows (windmove-default-keybindings 'shift) (show-paren-mode t) ; Turn beep off (setq visible-bell nil) (custom-set-variables '(ansi-color-names-vector ["#242424" "#e5786d" "#95e454" "#cae682" "#8ac6f2" "#333366" "#ccaa8f" "#f6f3e8"]) '(custom-enabled-themes (quote (wheatgrass)))) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) (put 'downcase-region 'disabled nil) ;;------------PYTHON STUFF----------- ;(require 'magit) ;(global-set-key "\C-xg" 'magit-status) (require 'auto-complete) (require 'autopair) (require 'yasnippet) (require 'jedi) ;yasnipped settings (setq yas-snippet-dirs '("C:\\Users\\Rob Ter Horst\\AppData\\Roaming\\.emacs.d\\elpa\\yasnippet-20140106.1009\\snippets")) (add-to-list 'load-path "C:\\Users\\Rob Ter Horst\\AppData\\Roaming\\.emacs.d\\elpa\\yasnippet-20140106.1009") (global-set-key [f7] 'find-file-in-repository) ; auto-complete mode extra settings (setq ac-auto-start 2 ac-override-local-map nil ac-use-menu-map t ac-candidate-limit 20) ;; ;; Python mode settings (setq py-install-directory "C:\\Users\\Rob Ter Horst\\AppData\\Roaming\\.emacs.d\\self_installed\\python-mode.el-6.1.3") (add-to-list 'load-path py-install-directory) (add-to-list 'auto-mode-alist '("\\.py$" . python-mode)) (when (featurep 'python) (unload-feature 'python t)) (require 'python-mode) (setq py-electric-colon-active t) (add-hook 'python-mode-hook 'autopair-mode) (add-hook 'python-mode-hook 'yas-minor-mode) (add-hook 'python-mode-hook 'auto-complete-mode) ;; ;; Jedi settings ;; It's also required to run "pip install --user jedi" and "pip ;; install --user epc" to get the Python side of the library work ;; correctly. ;; With the same interpreter you're using. ;; if you need to change your python intepreter, if you want to change it ;; (setq jedi:server-command ;; '("python2" "/home/andrea/.emacs.d/elpa/jedi-0.1.2/jediepcserver.py")) (add-hook 'python-mode-hook (lambda () (jedi:setup) (jedi:ac-setup) (local-set-key "\C-cd" 'jedi:show-doc) (local-set-key (kbd "M-SPC") 'jedi:complete) (local-set-key (kbd "M-.") 'jedi:goto-definition))) ; ipython settings (setq py-python-command "C:\\Python27\\Scripts\\ipython.exe") (setq py-complete-function 'ipython-complete py-shell-complete-function 'ipython-complete py-shell-name "ipython" py-which-bufname "IPython") ;(require 'ipython) ;With tab autocompletion in ipdb I get an error that might be solved by changing this var ;the error: "variable binding depth exceeds max-specpdl-size" (setq max-specpdl-size 32000) ; Try to add flycheck --> flycheck causes emacs to become incredibly slow on big script with ; many style errors (as present in a lot of my older scripts, so I do not want to activate it ; by default ;(setq flycheck-highlighting-mode 'lines) ;(add-hook 'python-mode-hook 'global-flycheck-mode) ;(flycheck-select-checker 'python-flake8) ;(provide 'init-flycheck) (yas-reload-all) ` Answer: With Emacs24, I use the default python.el (not python-mode.el), which started [on github](https://github.com/fgallina/python.el). 1. when I start ipython with `python-shell-switch-to-shell` or `C-c C-p` (Python menu -> start interpreter), I get ipython. Tab completion works. 2. ipython is the default python interpreter (see my init file) 3. when I have started a ipython shell I can send a file or the selected region to it (commands available in the menu), and it gets evaluated correctly. As a side note, you can start the jedi autocompletion with `jedi:setup` when you are in a python shell. It gives nice popups with parameters help and doc, and you can choose to fire it at the dot (instead of after 3 characters). See [IPython auto-completion emacs24 doesn't work](http://stackoverflow.com/questions/9777861/ipython-auto-completion- emacs24-doesnt-work) . It can be seen as a complement rather than a replacement to ipython. Following my config: ;; trying ipython tab completion: that works :) (setq python-shell-interpreter "ipython" python-shell-interpreter-args "" python-shell-prompt-regexp "In \\[[0-9]+\\]: " python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: " python-shell-completion-setup-code "from IPython.core.completerlib import module_completion" python-shell-completion-module-string-code "';'.join(module_completion('''%s'''))\n" python-shell-completion-string-code "';'.join(get_ipython().Completer.all_completions('''%s'''))\n" ) taken from <http://www.emacswiki.org/emacs/PythonProgrammingInEmacs#toc5> Hope this helps.
How can I test the actual resolution of my camera when I acquire a frame using OpenCV? Question: I am working in Python/OpenCV, acquiring frames from a USB webcam (Logitech C615 Camera, supposedly HD 1080p). 1080p has a 16:9 aspect ratio and thus I should be able to acquire images at all of these resolutions: 1920 x 1080 1600 x 900 1366 x 768 1280 x 720 1024 x 576 I didn't write the camera driver however, so how do I know if I am really getting these pixels off of the camera? For example, I can specify 3840 x 2160 and I get a video frame of that size! Is there a systematic way I can evaluate/determine the real resolution or effective resolution of the camera given these different resolution settings? Below is some Python/OpenCV code to demonstrate. import numpy as np import cv2, cv import time cap = cv2.VideoCapture(0) # note you may need to pass 1 instead of 0 into this to get your camera cap.set(3,3840) #horizontal pixels cap.set(4,2160) #vertical pixels cap.set(5, 15) #frame rate time.sleep(2) #trying to solve a delay issue ... never mind this #acquire the video from the camera while(cap.isOpened()): ret, frame = cap.read() cv2.imshow("captured video", frame) if cv2.waitKey(33) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() Answer: "Is there a systematic way I can evaluate/determine the real resolution or effective resolution of the camera given these different resolution settings? " - just ask for it : import cv2 cam = cv2.VideoCapture(0) w = cam.get(cv2.CV_CAP_PROP_FRAME_WIDTH) h = cam.get(cv2.CV_CAP_PROP_FRAME_HEIGHT) print w,h while cam.isOpened(): err,img = cam.read() cv2.imshow("lalala", img) k = cv2.waitKey(10) & 0xff if k==27: break
Simple π(x) in Haskell vs C++ Question: I'm learning Haskell. My interest is to use it for personal computer experimentation. Right now, I'm trying to see how fast Haskell can get. Many claim parity with C(++), and if that is true, I would be very happy (I should note that I will be using Haskell whether or not it's fast, but fast is still a good thing). My test program implements π(x) with a very simple algorithm: Primes numbers add 1 to the result. Prime numbers have no integer divisors between 1 and √x. This is not an algorithm battle, this is purely for compiler performance. Haskell seems to be about 6x slower on my computer, which is fine (still 100x faster than pure Python), but that could be just because I'm a Haskell newbie. Now, my question: **How, without changing the algorithm, can I optimize the Haskell implementation? Is Haskell really on performance parity with C?** Here is my `Haskell` code: import System.Environment -- a simple integer square root isqrt :: Int -> Int isqrt = floor . sqrt . fromIntegral -- primality test prime :: Int -> Bool prime x = null [x | q <- [3, 5..isqrt x], rem x q == 0] main = do n <- fmap (read . head) getArgs print $ length $ filter prime (2:[3, 5..n]) Here is my `C++` code: #include <iostream> #include <cmath> #include <cstdlib> using namespace std; bool isPrime(int); int main(int argc, char* argv[]) { int primes = 10000, count = 0; if (argc > 1) { primes = atoi(argv[1]); } if (isPrime(2)) { count++; } for (int i = 3; i <= primes; i+=2) { if (isPrime(i)){ count++; } } cout << count << endl; return 0; } bool isPrime(int x){ for (int i = 2; i <= floor(sqrt(x)); i++) { if (x % i == 0) { return false; } } return true; } Answer: Your Haskell version is constructing a lazy list in `prime` only to test if it is null. This seems to indeed be a bottle neck. The following version runs just as fast as the C++ version on my machine: prime :: Int -> Bool prime x = go 3 where go q | q <= isqrt x = if rem x q == 0 then False else go (q+2) go _ = True 3.31s when compiled with -O2 vs. 3.18s for C++ with gcc 4.8 and -O3 for n=5000000. Of course, 'guessing' where the program is slow to optimize it is not a very good approach. Fortunately, Haskell has good profiling tools on board. Compiling and running with $ ghc --make primes.hs -O2 -prof -auto-all -fforce-recomp && ./primes 5000000 +RTS -p gives # primes.prof Thu Feb 20 00:49 2014 Time and Allocation Profiling Report (Final) primes +RTS -p -RTS 5000000 total time = 5.71 secs (5710 ticks @ 1000 us, 1 processor) total alloc = 259,580,976 bytes (excludes profiling overheads) COST CENTRE MODULE %time %alloc prime.go Main 96.4 0.0 main Main 2.0 84.6 isqrt Main 0.9 15.4 individual inherited COST CENTRE MODULE no. entries %time %alloc %time %alloc MAIN MAIN 45 0 0.0 0.0 100.0 100.0 main Main 91 0 2.0 84.6 100.0 100.0 prime Main 92 2500000 0.7 0.0 98.0 15.4 prime.go Main 93 326103491 96.4 0.0 97.3 15.4 isqrt Main 95 0 0.9 15.4 0.9 15.4 --- >8 --- which clearly shows that `prime` is where things get hot. For more information on profiling, I'll refer you to [Real World Haskell, Chap 25](http://book.realworldhaskell.org/read/profiling-and-optimization.html). To really understand what is going on, you can look at (one of) GHC's intermediate languages _Core_ , which will show you how the code looks like after optimization. Some good info is [at the Haskell wiki](http://www.haskell.org/haskellwiki/Performance/GHC). I would not recommend to do that unless necessary, but it is good to know that the possibility exists. To your other questions: 1) How, without changing the algorithm, can I optimize the Haskell implementation? Profile, and try to write inner loops so that they don't do any memory allocations and can be made strict by the compiler. Doing so can take some practice and experience. 2) Is Haskell really on performance parity with C? That depends. GHC is amazing and can often optimize your program very well. If you know what you're doing you can usually get close to the performance of optimized C (100% - 200% of C's speed). That said, these optimizations are not always easy or pretty to the eye and high level Haskell can be slower. But don't forget that you're gaining amazing expressiveness and high level abstractions when using Haskell. It will usually be fast enough for all but the most performance critical applications and even then you can often get pretty close to C with some profiling and performance optimizations.
Getting "package R does not exist" when building from command-line Question: I created an activity on a separate project using Eclipse. When I imported it into my cocos2d-x android project and built the project using `python build_native.py` (which is basically building the app using the NDK) and `ant debug`, I get an error saying: error: package R does not exist pointing to the line: setContentView(R.layout.some_activity); ^ I have added the `res/layout/some_activity.xml` in my cocos2d-x project as well as the manifest entries: <application <!-- <application> tag info --> > <activity <!-- cocos2d-x native activity --> > </activity> <!-- the activity I imported --> <activity android:name="com.mycompany.myapp.SomeActivity" android:label="" android:theme="@android:style/Theme.Dialog" android:excludeFromRecents="true" android:noHistory="true" /> </application> I also copied the needed `*.java` files inside the `src` folder (in the exact same folder structure). I also tried cleaning manually (by deleting the `bin`, `gen`, `obj`, and `assets` folders) and through `ant clean`. I am not using Eclipse to build, only from the command-line. **EDIT** : I also tried adding `import com.mycompany.myapp.R;` as well as `import com.mycompany.R;` on `SomeActivity.java` but it still didn't fix it. How do I fix this error? Any other steps I am missing? Answer: I had to import the cocos2d-x project's package name, not the imported activity's package name. For example, if your cocos2d-x project's package name was `com.mycompany.cocosapp` and your imported activity's package name was `com.mycompany.myapp`, import `com.mycompany.cocosapp.R` instead of `com.mycompany.myapp.R`.
Unable to find virtualenv or django after installing with pip Question: I installed virtualenv using pip and now receive the following error whenever I actually try and use it: % virtualenv Traceback (most recent call last): File "/bin/virtualenv", line 5, in <module> from pkg_resources import load_entry_point File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 2705, in <module> File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 668, in require File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 571, in resolve pkg_resources.DistributionNotFound: virtualenv==1.11.2 % Similarly, I installed django with pip, and when I try and import django in python I get: `ImportError: No module named django`. Answer: I tried to install virtualenv again, this time using easy_install instead of pip. easy_install gave me an error saying that it was having issues with my `PYTHONPATH` environment variable. Lo and behold, after reading <http://www.stereoplex.com/blog/understanding-imports-and-pythonpath>, `PYTHONPATH` is what python uses to find modules, and my `PYTHONPATH` was unset. After setting `PYTHONPATH` to `/lib/python3.3/site-packages` (where pip was installing my modules), both virtualenv and importing django functioned properly. Note: because I have both python2.7 and python 3.3 installed, for me `pip` actually installs packages to `/lib/python2.7/site-packages` while `pip3` installs packages to the aforementioned `/lib/python3.3/site-packages`. For the unfamiliar, information on setting environment variables can be found here: <https://help.ubuntu.com/community/EnvironmentVariables>
Sort os.listdir files Python Question: If have downloaded several years of data stored in files with the following naming convention, year_day.dat. For example, the file named 2014_1.dat has the data for January 1, 2014. I need to read these data files ordered by day, 2014_1.dat, 2014_2.dat, 2014_3.dat until the end of the year. In the folder they are listed in that ordered BUT when I create a list of the files in the directory they are reordered 2014_1.dat, 2014_10.dat, 2014_100.dat, 2014_101.dat...2014.199.dat, 2014_2.dat. I think I need to use a sort function but how do I force it to sort the listed files by day so I can continue processing them? Here's the code so far: import sys, os, gzip, fileinput, collections # Set the input/output directories wrkDir = "C:/LJBTemp" inDir = wrkDir + "/Input" outDir = wrkDir + "/Output" # here we go inList = os.listdir(inDir) # List all the files in the 'Input' directory print inList #print to screen reveals 2014_1.dat.gz followed by 2014_10.dat.gz NOT 2014_2.dat.gz HELP d = {} for fileName in inList: # Step through each input file readFileName = inDir + "/" + fileName with gzip.open(readFileName, 'r') as f: #call built in utility to unzip file for reading for line in f: city, long, lat, elev, temp = line.split() #create dictionary d.setdefault(city, []).append(temp) #populate dictionary with city and associated temp data from each input file collections.OrderedDict(sorted(d.items(), key=lambda d: d[0])) # QUESTION? why doesn't this work #now collect and write to output file outFileName = outDir + "/" + "1981_maxT.dat" #create output file in output directory with .dat extension with open(outFileName, 'w') as f: for city, values in d.items(): f.write('{} {}\n'.format(city, ' '.join(values))) print "All done!!" raw_input("Press <enter>") # this keeps the window open until you press "enter" Answer: Try this if all of your files start with '2014_': sorted(inList, key = lambda k: int(k.split('_')[1].split('.')[0])) Otherwise take advantage of tuple comparison, sorting by the year first then the second part of your file name. sorted(inList, key = lambda k: (int(k.split('_')[0]), int(k.split('_')[1].split('.')[0])))
Understanding Cython "typedness" report Question: I'm using Cython to make my Python code more efficient. I have read about the Cython's function `cython -a filename.pyx` to see the "typedness" of my cython code. Here is the short [reference](http://docs.cython.org/src/quickstart/cythonize.html#determining- where-to-add-types) from Cython web page. My environment is Windows 7, Eclipse PyDev, Python 2.7.5 32-bit, Cython 0.20.1 32-bit, MinGW 32-bit. Here is the report for my code: ![enter image description here](http://i.stack.imgur.com/BQpC3.png) So does the color yellow mean efficient or non-efficient code? The more yellow it is the more....what? Another question, I can click on the numbered rows and the following report opens (e.g. row 23): ![enter image description here](http://i.stack.imgur.com/samlq.png) What does this mean? P.S. If you can't see the image well enough --> right click --> view image (on Windows 7) ;) Thnx for any assistance =) **UPDATE:** In case somebody wants to try my toy code here they are: **hello.pyx** import time cdef char say_hello_to(char name): print("Hello %s!" % name) cdef double f(double x) except? -2: return x**2-x cdef double integrate_f(double a, double b, int N) except? -2: cdef int i cdef double s, dx s = 0 dx = (b-a)/N for i in range(N): s += f(a+i*dx) return s * dx cpdef p(): s = 0 for i in range(0, 1000000): c = time.time() integrate_f(0,100,5) s += time.time()- c print s **test_cython.py** import hello as hel hel.p() **setup.py** from distutils.core import setup from Cython.Build import cythonize setup( name = 'Hello world app', ext_modules = cythonize("hello.pyx"), ) From command line prompt I used the command (to generate C, pyd etc files): python setup.py install build --compiler=mingw32 To generate the report I used: cython -a hello.pyx Answer: I think I perhaps got it myself already. Someone can correct me if I'm mistaken: The more "yellowish" the line is, then less efficient it is The most efficient lines are the white-colored lines, because these are translated into pure C-code.
Cannot use django-mssql provider Question: Does anyone know how to use the django-mssql provider? I've installed the requirements but I cannot get it to work. Without sqlserver_ado in settings.py it imports fine: (testenv) C:\Users\Robin\test>python manage.py shell Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import sqlserver_ado >>> ^Z With a database set to use sqlserver_ado in settings.py: (testenv) C:\Users\Robin\test>python manage.py shell ImproperlyConfigured: 'sqlserver_ado' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: u'mysql', u'oracle', u'postgresql_psycopg2', u'sqlite3' Error was: cannot import name InterfaceError EDIT: Django==1.5 django-mssql==1.5b1 EDIT 2: Browsing the source for django-mssql reveals that it's trying to import InterfaceError from django.db.utils which doesn't exist in Django 1.5 Answer: It's mentioned on the project's Bitbucket page at <https://bitbucket.org/Manfre/django-mssql/overview> that: "The current version of django-mssql supports Django 1.6. If using an older version of Django, you will need to use an earlier version of django-mssql. django-mssql 1.4 supports Django 1.4 and 1.5." I installed 1.4 and now I just need to get the provider working.
No module named _struct ironpython Question: I've trying to use IronPython 2.7.4 with .net 3.5. I've create a new project and added needed references: IronPython.dll IronPython.Modules.dll Microsoft.Dynamic.dll Microsoft.Scripting.dll Microsoft.Scripting.Core.dll Then in my c# code i'm using a preparation script to define lib path string preparationstring = "import sys\nsys.path.append(r\"C:\\Python27\\Lib\")"; Then i'm trying to execute script which is using "struct" module and getting an error No module named _struct How can i resolve it? Answer: It's strange, but IronPython.Modules.dll does'not automatically copied to the bin directory. After i've got manually copied it everything starts to be ok.
python: getting output from `print` inside a function Question: Im using a library of functions that some of them print data I need: def func(): print "data" How can I call this function and get the printed data into a string? Answer: If you can't change those functions, you will need to redirect `sys.stdout`: >>> import sys >>> stdout = sys.stdout >>> import StringIO >>> s = StringIO.StringIO() >>> sys.stdout = s >>> print "hello" >>> sys.stdout = stdout >>> s.seek(0) >>> s.read() 'hello\n'
How to return a more meaningful 500 error in a python-eve app Question: I have some code in a python-eve app that retrieves some data from a device and populates a resource when that resource is requested for the first time. Sometimes the code can't successfully connect to the device. In this case, I would like to return an error message that explains this better, rather than just a plain 500 error. Here is the on_fetch_item hook: def before_returning_item(resource, _id, document): if resource == "switches": if "interfaces" not in document.keys(): # retrieve and store switch config if it hasn't been stored yet r = app.data.driver.db[resource] try: switch = prepare_switch_from_document(document) except socket.timeout: # raise some more meaningful error with message pass interface_list = switch.get_formatted_interfaces() r.update({'_id': _id}, {'interfaces': interface_list}) document['interfaces'] = interface_list app.on_fetch_item += before_returning_item Thanks in advance. Answer: All you have to do is take advantage of Flask's `abort` method: from flask import abort def before_returning_item(resource, _id, document): if resource == "switches": if "interfaces" not in document.keys(): # retrieve and store switch config if it hasn't been stored yet r = app.data.driver.db[resource] try: switch = prepare_switch_from_document(document) except socket.timeout: # raise some more meaningful error with message abort(500) interface_list = switch.get_formatted_interfaces() r.update({'_id': _id}, {'interfaces': interface_list}) document['interfaces'] = interface_list app.on_fetch_item += before_returning_item If you want to add a custom description: abort(500, description='My custom abort description')
remove empty last line from string (output from pipe) Question: I like to remove the empty line after my output: #!/usr/bin/python os.system("find /home/pi/bsp/musik/musik/ -name ""*.mp3"" | shuf -n 1 > /home/pi/bsp/musik/musik/track") What I get is: >>>cat track /home/pi/bsp/musik/musik/2/Little Green Bag - George Baker Selection - Reservoir Dogs.mp3 But when I print the file in Python its a different story: >>>sudo python play.py /home/pi/bsp/musik/musik/2/Lilly Allen - Fuck You.mp3 >>>> ...with a extra line in the end. I like to pass track to omxplayer but with the additional line in the end there is no way...so I thought it can´t be to hard to get rid of it: I tried to save a to a new file and remove the empty line with: os.system("sed '/^$/d' /home/pi/bsp/musik/track > /home/pi/bsp/musik/tt") os.system("mv /home/pi/bsp/musik/tt /home/pi/bsp/musik/track ") or remove it right in the pipe with: sed '/^$/d' or remove it from the sting with: text = os.linesep.join([s for s in text.splitlines() if s]) or: track[:track.rfind('\n')] And after all nothing worked so far. Could please someone give the tree in my way a push? Answer: Assuming `play.py` is `print`ing the contents of the file, the extra line at the end is coming from the `print` statement. If you need to output the contents of the file with Python, you can use `sys.stdout.write` instead of `print`, or `rstrip('\n')` the string, or put a comma at the end of the print statement, or use the print function with `end=''`. If you're directing input to OMXPlayer with shell redirection or something like that, it'll probably work fine without any extra effort. import sys sys.stdout.write(file_contents) or print file_contents.rstrip('\n') or print file_contents, or from __future__ import print_function print(file_contents, end='')
Why does IPython notebook only output one DIV from this code? Question: In an IPython notebook I input this code in a cell: from IPython.display import HTML HTML("""<div>One</div>""") HTML("""<div>Two</div>""") How come the output cell only contains the second div? EDIT. @Dunno has shown how I can put all the html into one `HTML()` and both elements are rendered, but I still don't understand what's going on. Here's a more general case: When I enter this in an input cell: 1 2 3 The output is 3 But if I enter the following: print 1 print 2 print 3 Then I get this output: 1 2 3 What's the difference? Is IPython notebook only evaluating the last statement when I don't use `print` statements? Or is each subsequent evaluation overwriting the previous one? Answer: Yeah I found some [documentation](http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Part%205%20-%20Rich%20Display%20System.ipynb#HTML) on this, and `HTML` is actually a class, not a function. So the correct code would be from IPython.display import HTML myhtml = HTML("""<div>One</div><div>Two</div>""") #make the html object myhtml #display it Now it makes sense why your code displays only one div. To display multiple parts create multiple variables, containing the html and then concatenate them inside one call to HTML. div1 = """<div>One</div>""" div2 = """<div>Two</div>""" myhtml = HTML(div1 + div2) myhtml * * * **Edit:** [I opened a ticket](http://github.com/ipython/ipython/issues/5208) on ipython's github profile to see if it's a bug or a feature that only the last line of statements is displayed. Turns out, it's planned behaviour: _quoting Thomas Kluyver:_ > This is deliberate, because if you call something in a for loop that returns > a value: > > > for line in lines: > f.write(line) # Returns number of bytes written > > > You probably don't want to see all those numbers in the output. > > The rule in IPython is: if the last statement in your code is an expression, > we display its >value. 1;2 is a pair of statements, whereas 1,2 is one > statement, so both values will >display. > > I hope that explains things a bit. We're happy to revisit decisions like > this, but it's >been this way for years, and I don't think anyone has taken > issue with it.
create a matrix out of a dictionary in python with labeled columns and rows Question: currently i have a dictionary that looks something like this: {'a':[1,2,3,0,0],'b':[1,5,2,1,4], 'c':[1,2,4,12,1]} I'm trying to create a covariance matrix out of this dictionary. i already have a defined covariance function so ideally the output would look something like this (along with the keys as the labels for the rows and columns): a b c a b c The ith row jth column output would call the covariance function and have as its input the value (a vector) of key i and the value (a vector) of key j. For example: covariance([1,5,2,1,4],[1,2,4,12,1]) I'm doing something like this right now to print out all the covariances but I'd prefer it in a matrix form: keys=dictionary.keys() values=dictionary.values() for counter in range(len(values)-1): print keys[counter]-1 + '&' + keys[counter] + ':' + covariance(values[counter-1],values[counter]) counter+=1 which gives me: a & b: 0.10 b & c: 0.20 but no association with a & c any help would be greatly appreciated. thanks. Answer: Sometimes the fantastic numpy, scipy and Pandas family comes to the rescue. Taking a quick stab at this you may try something like import pandas as pd df = pd.DataFrame({'a':[1,2,3,0,0],'b':[1,5,2,1,4], 'c':[1,2,4,12,1]}) covariance = df.cov()
Nested Tags/Table in BeautifulSoup Python scraping Question: I've pored over Google for half a day looking for the right answer to this. The closest thing I've come to is this StackOverflow post: [Nested tags in BeautifulSoup - Python](http://stackoverflow.com/questions/15749354/nested- tags-in-beautifulsoup-python) Effectively I'm scraping wait time data from a complex page with nested elements using BeautifulSoup in Python. Some of the HTML elements have classes/ids, but most do not. Looking at the DOM I can see the path to the elements I want. I've written a preliminary script that points to the right path (...I think) but the console keeps printing out an empty array. Even changing this code to print out something simple (like soup.select('body h2')) doesn't print anything. Here is my code from BeautifulSoup import BeautifulSoup import requests url = 'http://www.alexianbrothershealth.org/wait-times' r = requests.get(url) soup = BeautifulSoup(r.text) wait_times = soup.select('body div div div div div div div table tbody tr td') print wait_times Any ideas what I need to change to make this work? I have many more sites to get to, so figuring out the right syntax for the .select() pointer would really be helpful. I've tried using lxml with XPath and that also prints out an empty array. The page source tells me that it's in the HTML and not loading via javascript on the client so I should be okay there. PS I'm a newb, so any complex answer will be entirely lost on me ;) Answer: I don't think select is the BeautifulSoup method you're looking for. Select uses css selectors, but you're just looking for the right set of tags. If all the times you're looking for are in 's, I'd use tds = soup.find_all("td") for cell in tds: children = cell.findChildren() ... do actual work ... Alternatively, if you want to use select (which you definitely can), try removing the whole first set of tags: soup.select("table tbody tr td") works fine.
Getting completely wrong fit from python scipy.optimize.curve_fit Question: Update: solved! It is producing parameters with the correct signs now, and they do fit the curve. The problem was defining func(a,b,c,x) but curve_fit needs to read x first: func(x,a,b,c). Thanks everyone for all the help! I'll have quantitative analysis when I meet with my boss today :) Here's some of the new fits: <http://imgur.com/NHnzR2A> (I still get a run-time error: RuntimeWarning: overflow encountered in power return a*(math.e**(b*(math.e**(c*x)))) ) * * * Can anyone help me figure out what's wrong with this code? I am new to scipy. I am trying to model bacterial growth with the [Gompertz equation](http://en.wikipedia.org/wiki/Gompertz_function), but my code produces a curve_fit that's completely wrong. You can see images of my real data, the model equation, and the fit this code produces in [this imgur album](http://imgur.com/a/s2cA3) Thanks! * * * Fixed code: #!/usr/bin/python from numpy import * from scipy.optimize import curve_fit values = numpy.asarray(values) y = values[:2000//5].astype(numpy.float) y - y[0] #subtracting blank value x = numpy.arange(len(y))*5 def Function(x,a,b,c): #a = upper asymptote #b = negative = x axis displacement #c = negative = growth rate return a*(math.e**(b*(math.e**(c*x)))) parameters, pcov = curve_fit(Function, x, y, p0=[0.1,-1300,-0.0077]) #Graph data and fit to compare yaj = Function( numpy.asarray(x), parameters[0], parameters[1], parameters[2] ) figure(1, figsize=(8.5,11)) subplot(211) plot(x,y,'g-') xlim(min(x),max(x)) ylim(min(y),max(y)) subplot(212) plot(x,yaj,'r-') xlim(min(x),max(x)) ylim(min(yaj),max(yaj)) savefig('tempgraph.pdf') return parameters Answer: Imports: import numpy as np import matplotlib.pyplot as plt import scipy.optimize as opt Sample values: values = np.array('0.400 0.400 0.397 0.395 0.396 0.394 0.392 0.390 0.395 0.393 0.392 0.392 0.390 0.388 0.390 0.388 0.385 0.383 0.388 0.387 0.387 0.387 0.385 0.386 0.387 0.379 0.379 0.378 0.375 0.376 0.374 0.373 0.372 0.368 0.373 0.370 0.371 0.370 0.370 0.370 0.367 0.368 0.368 0.365 0.365 0.366 0.364 0.361 0.361 0.356 0.355 0.357 0.354 0.353 0.350 0.351 0.353 0.355 0.350 0.354 0.352 0.351 0.348 0.348 0.347 0.345 0.346 0.343 0.348 0.346 0.344 0.343 0.342 0.341 0.346 0.346 0.345 0.343 0.348 0.345 0.346 0.342 0.344 0.344 0.340 0.341 0.345 0.345 0.343 0.339 0.343 0.344 0.343 0.346 0.344 0.344 0.345 0.347 0.344 0.344 0.338 0.340 0.343 0.340 0.342 0.336 0.334 0.336 0.337 0.338 0.338 0.343 0.342 0.342 0.336 0.334 0.336 0.330 0.325 0.324 0.323 0.319 0.323 0.322 0.318 0.314 0.314 0.319 0.315 0.316 0.313 0.315 0.314 0.314 0.315 0.313 0.308 0.312 0.311 0.310 0.312 0.311' ' 0.311 0.309 0.309 0.316 0.317 0.312 0.309 0.311 0.308 0.310 0.312'.split('\t'), dtype=float) Old data preparation: x=[] y=[] x_val = 0 for i in values: #values is a list of several thousand experimental data points if x_val < 100: x.append(float(x_val)) y.append(float(i)) x_val += 5 x = np.asarray(x) y = np.asarray(y) Easier data prep: y1 = values[:100//5] x1 = np.arange(len(y1))*5 Check it is the same: print np.allclose(y, y1) print np.allclose(x, x1) Use numpy to define fit function: def function(x, a,b,c): #a = upper asymptote #b = negative = x axis displacement #c = negative = growth rate return a*(np.exp(b*(np.exp(c*x)))) Fit using starting point p0: pars, pcov = opt.curve_fit(function, x1, y1, p0=[0.1, -10, 0.1]) Draw: yaj = function(x1, *pars) plt.figure(1, figsize=(8.5, 11)) plt.plot(x1, y1, 'g-', x1, yaj, 'r-') plt.xlim(min(x1), max(x1)) plt.ylim(min(y1), max(y1)) plt.show()
python context sensitive regex for parsing hierchical text structure Question: I have a string like this: Group 1: Line A Line B Line C Group 2: Line A Line B I am wondering if it is possible to parse this with a regex with the results being something like: Group: 1, Line: A Group: 1, Line: B Group: 1, Line: C Group: 2, Line: A Group: 2, Line: B Here is what I have so far: regex = r'''(?x) (?<=Group\s(\d):\n) (?:Line\s\w+\n)* Line\s(\w+) ''' match_iter = re.finditer(regex,test,re.M|re.S|re.I) for m in match_iter: print m.groups() But this is wrong because I am only getting: ('1', 'C') ('2', 'B') And I'm stuck here... any idea how I can do this? (or if it is even possible to do with re) EDIT: I am looking for a regex only solution because I am trying to plug this into a light framework that will only take a regex and not arbitrary code. I can't use anything with states etc. This means In the above code snippet I can only change the value of 'regex'. Answer: import re regex = re.compile("(Group) (\d+)|(Line) (\w+)") INPUT = """ Group 1: Line A Line B Line C Group 2: Line A Line B""" def main(): group, line = None, None for match in regex.finditer(INPUT): if match.group(1): # found a Group group = match.group(2) else: # found a Line line = match.group(4) print("Group: {group}, Line: {line}".format(group=group, line=line)) if __name__=="__main__": main() returns Group: 1, Line: A Group: 1, Line: B Group: 1, Line: C Group: 2, Line: A Group: 2, Line: B
Passing a Custom Switch class to Mininet topology Question: This is a topology file for a popular network simulator called mininet I have created a class MultiSwitch() below which I want to be passed to my Topology class to be used as the default switch is there a way to do that? I am not very proficient in Python from mininet.topo import Topo from mininet.node import OVSSwitch, Controller, RemoteController # Two "external" controllers c0 = RemoteController( 'c1', ip='192.168.81.132') c1 = RemoteController( 'c2', ip='192.168.81.130') cmap = { 's1': c0, 's2': c0, 's3': c1,'s4':c1 } class MultiSwitch( OVSSwitch ): def start( self, controllers ): return OVSSwitch.start( self, [ cmap[ self.name ] ] ) class OnosTopo( Topo ): "Simple topology example." def __init__( self ): "Create custom topo." # Initialize topology Topo.__init__( self ) # Add hosts and switches h1 = [ self.addHost( 'h1')] h2 = [ self.addHost( 'h2')] h3 = [ self.addHost( 'h3')] h4 = [ self.addHost( 'h4')] s1 = [ self.addSwitch( 's1', dpid="0000000000000201")] s2 = [ self.addSwitch( 's2', dpid="0000000000000202")] s3 = [ self.addSwitch( 's3', dpid="0000000000000203")] s4 = [ self.addSwitch( 's4', dpid="0000000000000204")] #host to switch links self.addLink('s1','h1') self.addLink('s2','h2') self.addLink('s3','h3') self.addLink('s4','h4') #switch to swtich links self.addLink('s1','s2') self.addLink('s3','s4') topos = { 'onostopo': ( lambda: OnosTopo() ) } Answer: the mininet.topo.py defines a method called as add_switch(),may be you can try over-writting the add_switch() method with a custom add_switch() which adds your custom switch in your custom topology, so whenever you run your topology, the add_switch() method would create the custom switch .
How to calculate RMSE using IPython/NumPy? Question: I'm having issues trying to calculate root mean squared error in IPython using NumPy. I'm pretty sure the function is right, but when I try and input values, it gives me the following TypeError message: TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple' Here's my code: import numpy as np def rmse(predictions, targets): return np.sqrt(((predictions - targets) ** 2).mean()) print rmse((2,2,3),(0,2,6)) Obviously something is wrong with my inputs. Do I need to establish the array before I put it in the `rmse():` line? Answer: It says that subtraction is not defined for tuples. Try print rmse(np.array([2,2,3]), np.array([0,2,6])) instead.
Networkx: Nodes as Objects OR Nodes as ID's with Dictionary Attribute Tables Question: Which is the most efficient in terms of memory management and computation speed? The simple test below suggests it is slightly better to store attributes within nodes as a python object vs. dictionary lookups through attribute tables. Will this always the case due to how the memory is allocated? As a test I constructed a simple example: class country(): def __init__(self, name, gdp): self.name = name self.gdp = gdp def __repr__(self): return str(self.name) #Country Objects countries = dict() countries['AUS'] = country('AUS', 2000) countries['USA'] = country('USA', 10000) countries['ZWE'] = country('ZWE', 13) #Attribute Dictionary gdp = dict() gdp['AUS'] = 2000 gdp['USA'] = 10000 gdp['ZWE'] = 13 Constructing Networks: #Nodes as ID's G1 = nx.Graph() G1.add_nodes_from(countries.keys()) G1.nodes() #Nodes as Objects G2 = nx.Graph() for c in countries.keys(): G2.add_node(countries[c]) G2.nodes() Running %timeit in IPython: **G1f()** #Lookup Data from Strings Network def G1f(): for n in G1.nodes(): print "Node: %s" % n print "\tGDP: %s" % gdp[n] %timeit G1f **Output for G1f():** 10000000 loops, best of 3: 26.4 ns per loop **G2f()** #Lookup Data from Objects def G2f(): for n in G2.nodes(): print "Node: %s" % n.name print "\tGDP: %s" % n.gdp %timeit G2f **Output for G2f()** 10000000 loops, best of 3: 21.8 ns per loop * * * **Updated** **G3f() [from answers]** G3 = nx.Graph() for c,v in gdp.items(): G3.add_node(c, gdp=v) def G3f(): for n,d in G3.nodes(data=True): print "Node: %s" % n print "\tGDP: %s" % d['gdp'] **Output for G13f():** 10000 loops, best of 3: 63 µs per loop Answer: You could also use node attributes like this: import networkx as nx #Attribute Dictionary gdp = dict() gdp['AUS'] = 2000 gdp['USA'] = 10000 gdp['ZWE'] = 13 G3 = nx.Graph() for c,v in gdp.items(): G3.add_node(c, gdp=v) print G3.nodes(data=True) def G3f(): for n,d in G3.nodes(data=True): print "Node: %s" % n print "\tGDP: %s" % d['gdp'] It's not clear to me the test timings are very significant. Unless this is a very huge problem (maybe someday everyone will have their own country!) there might not be much difference in speed or memory. I suspect that the overhead of creating many small custom objects (country()) will end up using more memory and time.
Dice generator, Picking number of sides in PYTHON 3.3.4 Question: Just wondering howto make a dice program: A game uses dice with 4, 6 and 12 sides to determine various outcomes. Design, code and test a program that will simulate throwing dice with these numbers of sides. The user should be able to input which dice is being thrown, eg 4, 6 or 12. The program should output the dice chosen and the score, for example ‘6 sided dice thrown, score 4’ The user should be able to repeat this process as many times as required. THks import random dice = int(raw_input("What sided dice woud you like to roll? 4, 6 or 12?")) while dice !=0: print random.randint(1,dice) dice = int(raw_input("What sided dice woud you like to roll? 4, 6 or 12? press 0 to stop.")) Answer: You are actually trying to run Python 2 code in a Python 3 interpreter: The statement print i has been replaced by the function print(i) and raw_input(...) has been replaced by input(...)
Unable to make enemy move towards player Question: I'm struggling to get this working. Basically, I want my enemy sprite to chase my player sprite. At the moment, it moves away diagonally to the bottom right edge of the screen. I'm learning python my making a game and am still new so I apologise if this is a very simple thing I'm having issues with. Relevant code: class Enemy(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.bitmap = pygame.image.load("ball.bmp") self.enemy_rect = self.bitmap.get_rect() self.enemy_rect.topleft = [100, 200] self.speed = 2 def move_to_player(self, Player): dx, dy = self.enemy_rect.x - player.player_rect.x, self.enemy_rect.y - player.player_rect.y dist = math.hypot(dx, dy) if dist == 0: dist = 1 else: dx, dy = dx / dist, dy / dist self.enemy_rect.x += dx * self.speed self.enemy_rect.y += dx * self.speed while 1: # main game loop enemy.move_to_player(player) And all code, for context: import pygame import sys import pygame.locals import math pygame.init() size = width, height = 800, 500 colour = 100, 20, 30 # colour for background screen = pygame.display.set_mode(size) pygame.display.set_caption('Test') class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.bitmap = pygame.image.load("ball.bmp") self.player_rect = self.bitmap.get_rect( self.player_rect.topleft = [100, 200] def move(self, x, y): self.player_rect.centerx += x self.player_rect.centery += y def render(self): screen.blit(self.bitmap, (self.shipRect)) class Enemy(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.bitmap = pygame.image.load("ball.bmp") self.enemy_rect = self.bitmap.get_rect() self.enemy_rect.topleft = [100, 200] self.speed = 2 def move_to_player(self, Player): dx, dy = self.enemy_rect.x - player.player_rect.x, self.enemy_rect.y - player.player_rect.y dist = math.hypot(dx, dy) if dist == 0: dist = 1 else: dx, dy = dx / dist, dy / dist self.enemy_rect.x += dx * self.speed self.enemy_rect.y += dx * self.speed player = Player() enemy = Enemy() player.player_rect.x = 50 player.player_rect.y = 50 enemy.enemy_rect.x = 500 enemy.enemy_rect.y = 300 while 1: # main game loop for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player.move(0, 5) if event.key == pygame.K_UP: player.move(0, -5) if event.key == pygame.K_LEFT: player.move(-5, 0) if event.key == pygame.K_RIGHT: player.move(5, 0) if player.player_rect.colliderect(enemy.enemy_rect): pygame.display.set_caption('Hit!') screen.fill(colour) screen.blit(player.bitmap, player.player_rect) screen.blit(enemy.bitmap, enemy.enemy_rect) enemy.move_to_player(player) pygame.display.flip() Answer: First off, `self.enemy_rect.y += dx * self.speed` probably should be `self.enemy_rect.y += dy * self.speed` Secondly, I think you have your math backwards such that your enemy will flee. Let's try a simple example: Player at 0,0; enemy at 2,0. Expected result if speed = 2: both at 0,0 dx = 2, dy = 0 (before normalizing by hypot) dx = 1, dy = 0 (after) New result: player still at 0,0; enemy at 4,0
Unexpected indentation errors Question: Pretty new to python/programming in general, been working on a script but have run into indentation errors around line `for line in csv.reader( open(filename), delimiter="\t"):` been trying a few things but could use a little help sorting it out, any ideas? Could you explain any responses you have, helps with the learning process thank you! #!/usr/bin/python import csv import pprint pp = pprint.PrettyPrinter(indent=4) import sys import getopt import re changes = {} import argparse parser = argparse.ArgumentParser() parser.add_argument ("infile", metavar="CSV", nargs="+", type=str, help="data file") args = parser.parse_args() sample_names = [] SIMILARITY_CUTOFF = 95 # # Function that investigates the similarity between two samples. # # def similar_samples( sample_name1, sample_name2): combined_changes = dict() for change, fraction in changes[ sample_name1 ]: if ( change not in combined_changes): combined_changes[change] = [] combined_changes[change].append(float(fraction)) for change, fraction in changes[ sample_name2 ]: if ( change not in combined_changes): combined_changes[change] = [] combined_changes[change].append(float(fraction)) passed_changes = 0 failed_changes = 0 for change in combined_changes.keys(): if ( len(combined_changes[ change ]) == 1): failed_changes +=1 continue sum = 0 count = 0 for a in combined_changes[ change ]: sum += a count += 1 mean = sum/ count for a in combined_changes[ change ]: if ( mean > a + 2 or mean < a - 2): failed_changes += 1 else: passed_changes += 1 # print "passed changes: %d, failed changes: %d" % ( passed_changes, failed_changes) if ( passed_changes * 100 / (passed_changes + failed_changes) > SIMILARITY_CUTOFF): print " vs ".join([sample_name1, sample_name2]) + " : Similar samples" return 1 else: print " vs ".join([sample_name1, sample_name2]) + " : Different samples" return 0 # print "mean %.2f \n" % ( sum/ count) for filename in args.infile: sample_name = filename #sample_name = re.search("^(.*)\_", filename).group(1) changes[ sample_name ] = [] sample_names.append( sample_name ) for line in csv.reader( open(filename), delimiter="\t"): for item in line[2:]: if not item.strip(): continue item = item.split(":") item[1] = item[1].rstrip("%") changes[ sample_name].append([line[1]+item[0],item[1]]) for i in range(0, len(sample_names)): for j in range(i+1, len(sample_names)): similar = similar_samples( sample_names[ i ], sample_names[ j ]) exit() Answer: Indentation error. Try indenting sample_names.append( sample_name ) line
Run function from the command line and pass arguments to function Question: I'm using similar approach to call python function from my shell script: python -c 'import foo; print foo.hello()' But I don't know how in this case I can pass arguments to python script and also is it possible to call function with parameters from command line? Answer: python -c 'import foo, sys; print foo.hello(); print(sys.argv[1])' "This is a test" or echo "Wham" | python -c 'print(raw_input(""));' There's also [argparse](http://docs.python.org/3/library/argparse.html) (py3 link) that could be used to capture arguments, such as the `-c` which also can be found at `sys.argv[0]`. A second library do exist but is discuraged, called `getopt.getopt`.
Cross-platform way to get default directory for Python console scripts? Question: Is there cross-platform way to get default directory for console scripts the same way one can use `sys.executable` to get path to the Python's interpreter in cross-platform way? Context: There's Python script which runs various tools like pip using subprocess module and it would be good to make sure to run tools that accompany Python's interpreter used to run this script. Please note that the script may be run from within virtualenv which had not been activated – `./venv/bin/python script.py` Answer: Yes, [`sysconfig`](http://docs.python.org/3.3/library/sysconfig.html) module provides such API through [`get_path()`](http://docs.python.org/3.3/library/sysconfig.html#sysconfig.get_path) function: Linux: pdobrogost@host:~/tmp$ venv/bin/python -c "import sysconfig; print(sysconfig.get_path('scripts'))" /home/users/pdobrogost/tmp/venv/bin Windows: X:\>venv\Scripts\python.exe -c "import sysconfig; print(sysconfig.get_path('scripts'))" X:\venv\Scripts References: <https://groups.google.com/forum/#!topic/comp.lang.python/s3vLkVy2xJk> <https://mail.python.org/pipermail/distutils-sig/2014-February/023867.html> Thank you Ned Batchelder, Oscar Benjamin, Paul Moore and Vinay Sajip for help.
Simulate windows drag and drop with code? Question: I think I may have asked a similar question in the past, but I am still stuck... As part of an automated process, I must "import" a specific subset of media files into a closed-source third-party application (Dartfish, incase it matters). **Here is the situation:** * The media (video) files are all in one folder (there are 1000s of them, and reorganization is not an option unfortunately). * On any given iteration of the script I am writing, only 13 _specific_ files must be imported into the application. * There is no import function in the app that must receive the files. * This same app _does_ allow you to drap and drop files into a specific pane, and this allows you to essentially import them. The current workaround I am using is very unstable and ugly, and uses a complex procedure of regex queries to isolate the files in Xplorer2, and then uses AutoIT to select them, and then finally drag them into the application. **Proposed Solution:** I need a way to drag and drop the specific subset of video files I need at any given time into this application, preferably without automating clicks and cursor movement (there are way too many points of failure in this setup). I am essentially just passing a list of filenames to the application (by dragging them there), so I figure there has got to be a way of automating this drag and drop purely in code - perhaps using C/C#/C++ and the windows API? Bonus points if the solution can be ported to Python somehow... but not necessary. If anyone can point me in the right direction with this (programming language doesn't matter; I'll learn whatever I need to know), and preferably give me a basic outline or example of how I can accomplish such a task, I would really appreciate it! This has been driving me nuts for over a year now! Answer: 1) Inject into target process 2) Get IDropTarget of target window function GetDropTargetFromWnd(AWnd: HWND): IDropTarget; var Unknow: IUnknown; begin Unknow := IUnknown(GetProp(AWnd, PChar(GlobalFindAtom('OleDropTargetInterface')))); if Assigned(Unknow) then Unknow.QueryInterface(IDropTarget, Result) end; 3) Create IDataObject with your files 4) Call IDropTarget.DragEnter 5) Call IDropTarget.Drop **Updated algorithm:** 1) Register your unique message with RegisterWindowMessage 2) Install global hook with SetWindowsHookEx with WH_CALLWNDPROC type (additional dll is required) 3) Create fixed file with 13 names 4) Send unique message registered in steip 1 to target window 5) You hook will be loaded into target process 6) Inside hook procedure check message 7) If message is your unique message 7.1) Get IDropTarget of target window 7.2) Load names from fixed file 7.3) Create IDataObject with your files 7.4) Call IDropTarget.DragEnter 7.5) Call IDropTarget.Drop 8) If all files don’t processed yet then go to 3 9) Uninstall global hook **Update 2** Also you can try send WM_DROPFILES message to target window from you hook dll.
QuTiP Python: Another version of PIL Question: I try to install QuTip (<http://qutip.org/docs/2.2.0/installation.html>) on Windows using Python(x,y). After the installation I cannot import qutip from qutip import * it gives the error message C:\Python27\lib\site-packages\PIL\Image.py:71: RuntimeWarning: The _imaging extension was built for another version of Pillow or PIL Does anybody know how to fix this? Answer: I had the same message when trying yo use PIL 2.3.0-6 coming with Python(x,y). I had to upgrade to PIL 2.4.0
'NoneType' object is not callable beautifulsoup error while using get_text Question: I wrote this code for extracting all text from a web page: from BeautifulSoup import BeautifulSoup import urllib2 soup = BeautifulSoup(urllib2.urlopen('http://www.pythonforbeginners.com').read()) print(soup.get_text()) The problem is I get this error: print(soup.get_text()) TypeError: 'NoneType' object is not callable Any idea about how to solve this? Answer: The method is called `soup.getText()`, i.e. camelCased. Why you get `TypeError` instead of `AttributeError` here is a mystery to me!
Error by doing Copy Paste with win32com (Glade GTK Python) Question: I have a simple function "Copy", for copy and paste with win32com. It runs several times without problems. But if i use a button(GUI GTK Glade) to trigger the function "Copy()", it runs only once. The second time i get the following Error: Gdk-CRITICAL (recursed) **: inner_clipboard_window_procedure: assertion `success' failed aborting... Can you help me ? CopyPaste: import os, sys import win32com.client def Copy(): # Pfad zum Template path_to_temp = r"C:\004_Python_Workspace\Persek\Template.xls" # Pfad zum Testpaket xlsPath = r"C:\004_Python_Workspace\Testfolder\Testanweisung_LK_ASL.xls" # Blattname im Template und im Testpaket Sheet = 'ECU_Config' excel_app = win32com.client.dynamic.Dispatch('Excel.Application') ###### Kopiere ECU_Config aus Template ##### excel_workbook1 = excel_app.Workbooks.Open(path_to_temp) excel_workbook1.Worksheets(Sheet).UsedRange.Copy() ###### Fuege in das neue Testpaket ein ##### excel_workbook2 = excel_app.Workbooks.Open(xlsPath) excel_workbook2.Worksheets(Sheet).Range('A1').PasteSpecial() excel_workbook2.worksheets(Sheet).Columns('A:B').AutoFit() excel_workbook2.Close(SaveChanges=True) del excel_workbook2 excel_workbook1.Close() del excel_workbook1 excel_app.Quit() Glade GtK Trigger with a button: def on_debug_clicked(self, object, data=None): CopyPaste_Error.Copy() Update 1a: Until "UsedRange.Copy()" line is all the same. excel_workbook1.Worksheets(Sheet).UsedRange.Copy() excel_app.Quit() Answer: Now i found the solution, but i dont know why. I include "win32clipboard" import os, sys import win32com.client import win32clipboard def Copy(): win32clipboard.OpenClipboard() # Pfad zum Template path_to_temp = r"C:\004_Python_Workspace\Persek\Template.xls" # Pfad zum Testpaket xlsPath = r"C:\004_Python_Workspace\Testfolder\Testanweisung_LK_ASL.xls" # Blattname im Template und im Testpaket Sheet = 'ECU_Config' excel_app = win32com.client.dynamic.Dispatch('Excel.Application') ###### Kopiere ECU_Config aus Template ##### excel_workbook1 = excel_app.Workbooks.Open(path_to_temp) excel_workbook1.Worksheets(Sheet).UsedRange.Copy() ###### Fuege in das neue Testpaket ein ##### excel_workbook2 = excel_app.Workbooks.Open(xlsPath) excel_workbook2.Worksheets(Sheet).Range('A1').PasteSpecial() excel_workbook2.worksheets(Sheet).Columns('A:B').AutoFit() excel_workbook2.Close(SaveChanges=True) del excel_workbook2 excel_workbook1.Close() del excel_workbook1 excel_app.Quit() win32clipboard.CloseClipboard()
Pandas DataFrame column another DataFrame when I'm expecting a Series Question: I have a DataFrame object called "design" which I construct from a DataFrame object called "df" like so: design = df.loc[year, [DV] + IVs + controls].copy(deep=True) where "DV" = a string "IVs" = list of strings "controls" = list of strings When I then try to access a column of "design" I _usually_ get a Series, as expected, and can use the .unique() method: design[DV].unique() ^ works fine, usually. However, _sometimes_ , when I use a different combination of DV, IVs, and controls, design[DV] is a DataFrame (which doesn't have a .unique() method). I'm stumped as to why. Any ideas? Note: Maybe this is important? Sometimes "controls" is an empty list. Sometimes the lists contain strings that are unicode. Thanks in advance! Edit: @AndyHayden, here's an example: design = DataFrame with one column-duplicate ('SPKATH'): DV = 'LETDIE1' ipdb> design.columns Index([u'LETDIE1', u'SUICIDE1', u'REGION', u'AGE', u'SEX', u'RACE', u'DEGREE', u'INCOME', u'RELIG', u'RELITEN', u'ATTEND', u'POLVIEWS', u'SPKATH', u'SPKCOM', u'SPKATH'], dtype=object) When I call design[DV].unique() I get an error: > /home/misha/.local/lib/python2.7/site-packages/pandas-0.12.0-py2.7-linux-x86_64.‌​egg/pandas/core/frame.py(2088)__getattr__() 2087 raise AttributeError("'%s' object has no attribute '%s'" % -> 2088 (type(self).__name__, name)) 2089 ipdb> a self = <class 'pandas.core.frame.DataFrame'> Index: 1530 entries, 1977.0 to 1977.0 Data columns (total 1 columns): LETDIE1 1530 non-null values dtypes: float64(1) name = unique Answer: One situation where this occurs is if you have **duplicate** columns, that is, DV is in IVs or controls. For example: In [11]: df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('ABC')) In [12]: df_a = df.loc[:, list('ABB')] In [13]: df_a Out[13]: A B B 0 1 2 2 1 4 5 5 In [14]: df_a['A'] # a Series Out[14]: 0 1 1 4 Name: A, dtype: int64 In [15]: df_a['B'] # a DataFrame Out[15]: B B 0 2 2 1 5 5 One way to get around this is to select by position: In [16]: df_a.iloc[:, 1] # always a Series Out[16]: 0 2 1 5 Name: B, dtype: int64
Calling a local python script from javascript Question: I have the following requirement: 1.Need to call a python script which resides locally, from javascript. It will carry out some operations and return a xml file. 2.Then I need to return the xml file to the javascript. 3.The javascript will carry out the parsing of the xml and display the values in the HTML. Can you kindly give me some pointers on how to carry out steps 1 and 2?I have tried to find answers to this but I haven't got a well defined solution. Thanks, Sayan Answer: Your browser **can't** (and know you how to) **execute Python functions** /modules. What you want is to make an [AJAX request](http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp). Basically, you need to put a web server in front of your Python function and then return the result of the function, here your XML file, when a certain URL is called. There's a lot of lightweight web framework that should help you to setup a quick web server to do that. For instance, [Flask](http://flask.pocoo.org/). Here's an example, totally inspired from the homepage of Flask: from flask import Flask from yourmodule import function_that_return_xml app = Flask(__name__) @app.route("/") def hello(): xml = function_that_return_xml() # make fancy operations if you want return xml if __name__ == "__main__": app.run() Then, here you can call `http://localhost:5000` (default address, put it online if you want other users to use it) to get your XML file.
How do I package/distribute a Python 2.7 application with selenium? Question: I am fairly new to Python and I have developed a program that has a Tkinter GUI and uses selenium WebDriver to scrape information. I need to find a way to package all of this so that it can be used on other computers. I call three extra modules (selenium, openpyxl, BeautifulSoup) in my script. Is there a way to make this an executable file? Or will they have to call it through their command window? I have heard of a program called Advanced Installer, would this do what i want? Thank you I realize that my question is very broad, i just don't know where to begin. This application is only applicable to people within my company, so i don't want it to be available to others. I just want to be able to move all the necessary files to another computer and they can just click one button and go. Answer: I encourage you to read how to package a python application. Typically what you want to do is release your application on the [Python Packaging Index](http://pypi.python.org/), so that your app is available as a Python module for other developers and users. Once you release your app on PyPI, you can go ahead and provide users with further options like easy install. Note that releasing your app and making it available to the world is something that you'd certainly want to do. The best way to package your application is by using [distutils](http://docs.python.org/2/library/distutils.html). Since packaging a python app is a considerably broad topic, I won't be able to cover it in entirety here. However, here are a few guides to get you started: * [Hitchhiker’s Guide to Packaging](http://guide.python-distribute.org/index.html) * [Distributing Python modules](http://docs.python.org/2/distutils/) * [Guide to open-sourcing a python project](http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/) Finally, a good practice is to look at existing open-source Python projects and look at the way their `setup` script and the `MANIFEST.in` file is written. For doing that, you would need to understand the way the project is structured, which is important in realizing the correct way to package an application. Hope this helps. All the best!
How to convert raw images into png using python Question: I'm trying to convert raw image data into png with python. I'm pretty new to python and especially to image processing... The raw file is a 16 bit greyscale image. As I already scanned the forums I came up with the following solution: from PIL import Image, ImageFilter import numpy as np from scipy import ndimage, misc rawfile = np.fromfile('test.raw', dtype=np.int16) rawfile.shape = (1025,1025) imgSize = (1025,1025) img = Image.fromstring('L', imgSize, rawfile, 'raw', 'F;16') img.save("rawData.png") But I keep getting the following errors: Traceback (most recent call last): File "****\Programs\Python 2.7.6\readraw\readraw.py", line 11, in <module> img = Image.fromstring('L', imgSize, rawfile, 'raw', 'F;16') File "****\Programs\Python 2.7.6\lib\site-packages\PIL\Image.py", line 1835, in fromstring return frombytes(*args, **kw) File "****\Programs\Python 2.7.6\lib\site-packages\PIL\Image.py", line 1822, in frombytes im.frombytes(data, decoder_name, args) File "****\Programs\Python 2.7.6\lib\site-packages\PIL\Image.py", line 608, in frombytes d = _getdecoder(self.mode, decoder_name, args) File "****\Programs\Python 2.7.6\lib\site-packages\PIL\Image.py", line 390, in _getdecoder return decoder(mode, *args + extra) ValueError: unknown raw mode Can someone explain to me why the raw mode is unknown? I checked the Docs and as far as I understand the topic, the PILLOW lib should come with this?! Best regards * * * Thank you guys for your help! I altered my code and now it seems to work: from PIL import Image, ImageFilter import numpy as np from scipy import ndimage, misc rawfile = np.fromfile('test.raw', "uint16") rawfile.shape = (1025,1025) misc.imsave("test.png", rawfile) Answer: I don't think PIL understands numpy objects. I would think PIL Image has a method to read the raw file from disk. Then you can modify the image in memory and save/export it in the format you like.
weird python indexing with CSV file Question: I have simple phenomena that I'm having trouble understanding. I load in a csv file import csv with open('Salaries.csv', 'rb') as csvfile: Salaries = csv.reader(csvfile, delimiter=',') Salaries = [row for row in Salaries] I query it, and see 5 columns, for example print Salaries[1][:] ['1985', 'BAL', 'AL', 'murraed02', '1472819'] If I look for the 5th index, which doesn't exist, it correctly throws an error: print Salaries[1][5] IndexError: list index out of range But if I run index 0:5 it doesn't throw an error: print Salaries[1][0:5] ['1985', 'BAL', 'AL', 'murraed02', '1472819'] and weirdly, i see these results print Salaries[1][0:1] ['1985'] print Salaries[1][0] 1985 print Salaries[1][1] BAL I know I'm missing something basic here, I'm just not getting it. help? Answer: running `print Salaries[1][0:5]` will print the list with a slice from the `0th` index up to and _not including_ the `5th` index, so in math terms, the range is [0,4] or [0,5). >>> mylist = [0,1,2,3,4] >>> mylist[0:4] [0, 1, 2, 3] #4 is excluded, although it is the 4th index In 2.7, you can arbitrarily slice up to any number and it will return the entire list if your slice range is longer than its length >>> mylist[0:10231] [0, 1, 2, 3, 4] Something to note, this is typical of python in functions such as `range(x,y)` which is up until and not including `y`. This allows for calls such as `for i in range(0,len(mylist))` although many python users would suggest a different way of doing something.
Python newbie exercise: Rock Paper Scissors Question: I've been trying to code a simple game of RPS where the user plays against the computer. There's just 1 iteration at this point (because I got stuck...) and no validation whether the user's input is valid. The problem I got stuck with is that whatever I tried to do in order to get the computer's and the user's score stored in a variable, it they kept being equal to 0, no matter what indentation I tried or wherever I tried to place the return. (as you could see in my code below... some parts that I tried with no luck are commented out). Ideally, since I plan on multiple iterations, I'd like the variables u and v themselves to be updated and keep score, not just print who won the specific iteration. Can you help me understand what I'm doing wrong here? Cheers from random import randrange rps = ["r", "p", "s"] def gameplay(user,comp): u = 0 #user's score v = 0 #computer's score print "Computer chose: " + comp if comp == user: pass elif comp == "r" and user == "p": u += 1 #print u #return u elif comp == "r" and user == "s": v += 1 #print v #return v elif comp == "p" and user == "s": u += 1 #print u #return u elif comp == "p" and user == "r": v += 1 #print v #return v elif comp == "s" and user == "r": u += 1 #print u #return u elif comp == "s" and user == "p": v += 1 #print v #return v return u return v gameplay(raw_input("your move?"),rps[randrange(3)]) print u print v Answer: just for fun ... see if you can understand this OOP implementation (its never too early to start learning OOP) WIN,TIE,LOSE = 1,0,-1 class RockPaperScissors: def __str__(self): return self.__class__.__name__ class Rock(RockPaperScissors): def __cmp__(self,other): if isinstance(other,Rock): return TIE if isinstance(other,Paper): return LOSE return WIN class Paper(RockPaperScissors): def __cmp__(self,other): if isinstance(other,Paper): return TIE if isinstance(other,Scissors):return LOSE return WIN class Scissors(RockPaperScissors): def __cmp__(self,other): if isinstance(other,Scissors): return TIE if isinstance(other,Rock):return LOSE return WIN def RPS(ltr_code): return {'r':Rock,'p':Paper,'s':Scissors}[ltr_code.lower()]() player = RPS("r") computer = RPS("s") if player > computer: print "Player Wins! %s beats %s"%(player,computer) elif player < computer: print "Computer wins!! %s beats %s"%(computer,player) else: print "Tied!! %s ties %s"%(computer,player)
How to write a mssql database with Python's SQLAlchemy? Question: Does anyone know a tutorial for making a MSSql database from python using SQLAlchemy. The reason for using MSsql is that some of my co-workers prefer Excel as the way to access the data. I looked around but I could not find a simple example for a newcommer like me Any advise would be gratefully acknoledged. Allan Answer: You can download SQL Server 2012 Express. It installs pretty easy, you won't even need Python to set it up. <http://www.microsoft.com/en-us/download/details.aspx?id=29062> It can import Flat files (such as Text), Excel, and Access files very easily. Just make sure you choose the right version - 32 or 64 bit. Here's a YouTube video on [how to import an Excel file into SQL Server](http://www.youtube.com/watch?v=Z1vqhYlwcyA).
reading *.his (image) file in Python Question: I am trying to read an image file which is in *.his format. Honestly, I do not know much about this format, on spending some time on google I figured out that its a binary format and it can be read in ImageJ software as a raw format import. On further inquiry, I found the following details of the *.his file: * Image type = 16-bit unsigned * Matrix dimensions in pixels = w1024 x h1024 * Skip header info = 100 Bytes (The number of bytes in the file before the first byte of image data). * Little-Endian Byte Order With this information in hand, I started out ... * * * Just wanted to print the values in one by one, just to see the output: f = open("file.his", 'rb') f.seek(100) try: byte = f.read(2) while byte != "": byte = f.read(2) print unpack('<H', byte) finally: f.close() It prints some numbers out and then the error message : ..... (64846,) (64846,) (64830,) Traceback (most recent call last): print unpack(' Plz can someone suggest me how to read this kind of file. I still think 'unpack' is the right function however if someone has similar experience, any response greatly appreciated. Rky. Answer: I've done a very similar task with *.inr image file maybe the logic could help you, here its what you could apply: **1-Reading the file** First you need to read the file. file = open(hisfile, 'r') inp = file.readlines() **2-Get header** In my case i done a for loop until the number of characters was 256, in your case you need to count the bits so you could "print" line by line to find out when you need to stop or try to use this to count the bits: import sys sys.getsizeof(line) #returns the size of the object **3-Data** When you already know that the following lines are the raw data you need to put them in one variable with a for loop: for line in inp: raw_data += line **4-Convert the data** To convert the string to a numpy array you could do: data = fromstring(raw_data, dtype='uint16') And then aplying the shape data: data = data.reshape((1024,1024)).transpose() #You need to see if the transpose part its relevant,because in my case was fundamental. Maybe if you have an example of the file i could try to read it and help you more. Of course you could do all the process in 1 for loop using if's.