text
stringlengths
226
34.5k
Python code for finding reverse average (finding possible value sets that give a certain average) Question: Background: I am working in Python 3, but if people provide answers in other programming languages I can still use it. Any suggestions on functions or efficient algorithm or programming tips would be helpful. Problem: I have a problem involving sets of four (4) integers and their average values. The information given: 1\. the number of integers in the set (4) 2\. the average of the integers The information needed: 1\. list of possible values that would result in the given average Notes: The number of integers in the set is small so an efficient method of generating lists shouldn't be that hard, but so far I am stuck. I have been starting with the sum of the numbers (average * 4), but haven't found the right way to iterate yet. EDIT: All integers are non-negative. For my purposes they also aren't bigger than 8 digits. Answer: Working with the sum, N, rather than the average. def all_possibilities(N, k=4): if k == 1: yield (N,) return for i in xrange(N+1): for p in all_possibilities(N-i, k-1): yield (i,) + p print list(all_possibilities(5)) Produces: [(0, 0, 0, 5), (0, 0, 1, 4), (0, 0, 2, 3), (0, 0, 3, 2), (0, 0, 4, 1), (0, 0, 5, 0), (0, 1, 0, 4), (0, 1, 1, 3), (0, 1, 2, 2), (0, 1, 3, 1), (0, 1, 4, 0), (0, 2, 0, 3), (0, 2, 1, 2), (0, 2, 2, 1), (0, 2, 3, 0), (0, 3, 0, 2), (0, 3, 1, 1), (0, 3, 2, 0), (0, 4, 0, 1), (0, 4, 1, 0), (0, 5, 0, 0), (1, 0, 0, 4), (1, 0, 1, 3), (1, 0, 2, 2), (1, 0, 3, 1), (1, 0, 4, 0), (1, 1, 0, 3), (1, 1, 1, 2), (1, 1, 2, 1), (1, 1, 3, 0), (1, 2, 0, 2), (1, 2, 1, 1), (1, 2, 2, 0), (1, 3, 0, 1), (1, 3, 1, 0), (1, 4, 0, 0), (2, 0, 0, 3), (2, 0, 1, 2), (2, 0, 2, 1), (2, 0, 3, 0), (2, 1, 0, 2), (2, 1, 1, 1), (2, 1, 2, 0), (2, 2, 0, 1), (2, 2, 1, 0), (2, 3, 0, 0), (3, 0, 0, 2), (3, 0, 1, 1), (3, 0, 2, 0), (3, 1, 0, 1), (3, 1, 1, 0), (3, 2, 0, 0), (4, 0, 0, 1), (4, 0, 1, 0), (4, 1, 0, 0), (5, 0, 0, 0)] In general, there will be choose(N+k-1, k-1) solutions. A shorter solution leveraging `itertools.combinations` is this: import itertools def all_possibilities(N, k=4): for c in itertools.combinations(range(N + k - 1), k - 1): yield tuple(x - y - 1 for x, y in zip(c + (N + k - 1,), (-1,) + c))
Embedding Python in C: Error when attempting to call Python code in a C callback called by Python code Question: I have some C code that calls a Python function. This Python function accepts an address and uses WINFUNCTYPE to eventually convert it to a function that Python can call. The C function send as a parameter to the Python function will eventually call another Python function. It is at this last step which causes a crash. So in short I go from C -> Python -> C -> Python. The last C -> Python causes a crash. I've been trying to understand the problem, but I have been unable to. Can someone point out my problem? C code compiled with Visual Studio 2010 and run with the args "c:\\...\crash.py" and "func1": #include <stdlib.h> #include <stdio.h> #include <Python.h> PyObject* py_lib_mod_dict; //borrowed void __stdcall cfunc1() { PyObject* py_func; PyObject* py_ret; int size; PyGILState_STATE gil_state; gil_state = PyGILState_Ensure(); printf("Hello from cfunc1!\n"); size = PyDict_Size(py_lib_mod_dict); printf("The dictionary has %d items!\n", size); printf("Calling with GetItemString\n"); py_func = PyDict_GetItemString(py_lib_mod_dict, "func2"); //fails here when cfunc1 is called via callback... will not even go to the next line! printf("Done with GetItemString\n"); py_ret = PyObject_CallFunction(py_func, 0); if (py_ret) { printf("PyObject_CallFunction from cfunc1 was successful!\n"); Py_DECREF(py_ret); } else printf("PyObject_CallFunction from cfunc1 failed!\n"); printf("Goodbye from cfunc1!\n"); PyGILState_Release(gil_state); } int wmain(int argc, wchar_t** argv) { PyObject* py_imp_str; PyObject* py_imp_handle; PyObject* py_imp_dict; //borrowed PyObject* py_imp_load_source; //borrowed PyObject* py_dir; //stolen PyObject* py_lib_name; //stolen PyObject* py_args_tuple; PyObject* py_lib_mod; PyObject* py_func; PyObject* py_ret; Py_Initialize(); //import our python script py_dir = PyUnicode_FromWideChar(argv[1], wcslen(argv[1])); py_imp_str = PyString_FromString("imp"); py_imp_handle = PyImport_Import(py_imp_str); py_imp_dict = PyModule_GetDict(py_imp_handle); //borrowed py_imp_load_source = PyDict_GetItemString(py_imp_dict, "load_source"); //borrowed py_lib_name = PyUnicode_FromWideChar(argv[2], wcslen(argv[2])); py_args_tuple = PyTuple_New(2); PyTuple_SetItem(py_args_tuple, 0, py_lib_name); //stolen PyTuple_SetItem(py_args_tuple, 1, py_dir); //stolen py_lib_mod = PyObject_CallObject(py_imp_load_source, py_args_tuple); py_lib_mod_dict = PyModule_GetDict(py_lib_mod); //borrowed printf("Calling cfunc1 from main!\n"); cfunc1(); py_func = PyDict_GetItem(py_lib_mod_dict, py_lib_name); py_ret = PyObject_CallFunction(py_func, "(I)", &cfunc1); if (py_ret) { printf("PyObject_CallFunction from wmain was successful!\n"); Py_DECREF(py_ret); } else printf("PyObject_CallFunction from wmain failed!\n"); Py_DECREF(py_imp_str); Py_DECREF(py_imp_handle); Py_DECREF(py_args_tuple); Py_DECREF(py_lib_mod); Py_Finalize(); fflush(stderr); fflush(stdout); return 0; } Python code: from ctypes import * def func1(cb): print "Hello from func1!" cb_proto = WINFUNCTYPE(None) print "C callback: " + hex(cb) call_me = cb_proto(cb) print "Calling callback from func1." call_me() print "Goodbye from func1!" def func2(): print "Hello and goodbye from func2!" Output: Calling cfunc1 from main! Hello from cfunc1! The dictionary has 88 items! Calling with GetItemString Done with GetItemString Hello and goodbye from func2! PyObject_CallFunction from cfunc1 was successful! Goodbye from cfunc1! Hello from func1! C callback: 0x1051000 Calling callback from func1. Hello from cfunc1! The dictionary has 88 items! Calling with GetItemString PyObject_CallFunction from wmain failed! I added a PyErr_Print() to the end and this was the result: Traceback (most recent call last): File "C:\Programming\crash.py", line 9, in func1 call_me() WindowsError: exception: access violation writing 0x0000000C EDIT: Fixed a bug that abarnert pointed out. Output is unaffected. EDIT: Added in the code that resolved the bug (acquiring the GIL lock in cfunc1). Thanks again abarnert. Answer: The problem is this code: py_func = PyDict_GetItemString(py_lib_mod_dict, "func2"); //fails here when cfunc1 is called via callback... will not even go to the next line! printf("Done with GetItemString\n"); py_ret = PyObject_CallFunction(py_func, 0); Py_DECREF(py_func); As [the docs](http://docs.python.org/2/c-api/dict.html#PyDict_GetItemString) say, `PyDict_GetItemString` returns a borrowed reference. So, the first time you call here, you borrow the reference, and decref it, causing it to be destroyed. The next time you call, you get back garbage, and try to call it. So, to fix it, just remove the `Py_DECREF(py_func)` (or add `Py_INCREF(py_func)` after the `pyfunc =` line). Actually, you will usually get back a special "dead" object, so you can test this pretty easily: put a `PyObject_Print(py_func, stdout)` after the `py_func =` line and after the `Py_DECREF` line, and you'll probably see something like `<function func2 at 0x10b9f1230>` the first time, `<refcnt 0 at 0x10b9f1230>` the second and third times (and you won't see the fourth, because it'll crash before you get there). I don't have a Windows box handy, but changing `wmain`, `wchar_t`, `PyUnicode_FromWideChar`, `WINFUNCTYPE`, etc. to `main`, `char`, `PyString_FromString`, `CFUNCTYPE`, etc., I was able to build and run your code, and I get a crash in the same place… and the fix works. Also… shouldn't you be holding the GIL inside `cfunc1`? I don't often write code like this, so maybe I'm wrong. And I don't get a crash with the code as- is. Obviously, spawning a thread to run `cfunc1` _does_ crash, and `PyGILState_Ensure`/`Release` solves that crash… but that doesn't prove you need anything in the single-threaded case. So maybe this isn't relevant… but if you get another crash after fixing the first one (in the threaded case, mine looked like `Fatal Python error: PyEval_SaveThread: NULL tstate`), look into this. By the way, if you're new to Python extending and embedding: A huge number of unexplained crashes are, like this one, caused by manual refcounting errors. That's the reason things like `boost::python`, etc. exist. It's not that it's impossible to get it right with the plain C API, just that it's so easy to get it wrong, and you will have to get used to debugging problems like this.
Python numpy index set from Boolean array Question: How do I transform a Boolean array into an iterable of indexes? E.g., import numpy as np import itertools as it x = np.array([1,0,1,1,0,0]) y = x > 0 retval = [i for i, y_i in enumerate(y) if y_i] Is there a nicer way? Answer: Try [`np.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) or [`np.nonzero`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html#numpy.nonzero). x = np.array([1, 0, 1, 1, 0, 0]) np.where(x)[0] # returns a tuple hence the [0], see help(np.where) # array([0, 2, 3]) x.nonzero()[0] # in this case, the same as above. See `help(np.where)` and `help(np.nonzero)`. Possibly worth noting that in the `np.where` page it mentions that for 1D `x` it's basically equivalent to your longform in the question.
Machine Learning Email Prioritization - Python Question: I have been working on a Python coded priority email inbox, with the ultimate aim of using a machine learning algorithm to label (or classify) a selection of emails as either important or un-important. I will begin with some background information and then move into my question. I have so far developed code to extract data from an email and process it to discover the most important ones. This is achieved using the following email features: * Senders Address Frequency * Thread Activity * Date Received (time between replies) * Common Words in body/subject The code I have currently applies a ranking (or weighting) (value 0.1-1) to each email based on its importance and then applies a label of either ‘important’ or ‘un-important’ (In this case this is just 1 or 0). The status of priority is awarded if the rank is >0.5. This data is stored in a CSV file (as below). From Subject Body Date Rank Priority [email protected] HelloWorld Body Words 10/10/2012 0.67 1 [email protected] ByeWorld Body Words 10/10/2012 0.21 0 [email protected] SayWorld Body Words 10/10/2012 0.91 1 [email protected] HeyWorld Body Words 10/10/2012 0.48 0 etc ………………………………………………………………………… I have two sets of email data (One Training, One Testing). The above applies to my training email data. I am now attempting to train a learning algorithm so that I can predict the importance of the testing data. To do this I have been looking at both SCIKIT and NLTK. However, I am having trouble transferring the information I have learnt in the tutorials and implementing into my project. I have no particular requirements in regards to which learning algorithm is used. Is this as simple as applying the following? And if so how? X, y = email.data, email.target from sklearn.svm import LinearSVC clf = LinearSVC() clf = clf.fit(X, y) X_new = [Testing Email Data] clf.predict(X_new) Answer: The easiest (though probably not the fastest) solution(*) is to use scikit- learn's `DictVectorizer`. First, read in each sample with Python's `csv` module, and build a `dict` containing `(feature, value)` pairs, while keeping the priority separate: # UNTESTED CODE, may contain a bug or two; also, you need to decide how to # implement split_words datareader = csv.reader(csvfile) dicts = [] y = [] for row in datareader: y.append(row[-1]) d = {"From": row[0]} for word in split_words(row[1]): d["Subject_" + word] = 1 for word in split_words(row[2]): d["Body_" + word] = 1 # etc. dicts.append(d) # vectorize! vectorizer = DictVectorizer() X_train = vectorizer.fit_transform(dicts) You now have a sparse matrix `X_train` that, together with `y`, you can feed to a scikit-learn classifier. Be aware: 1. When you want to make predictions on unseen data, you must apply the same procedure and _the exact same`vectorizer`_ object to it. I.e. you have to build a `test_dicts` object using the loop above, then do `X_test = vectorizer.transform(test_dicts)`. 2. I've assumed you want to predict the priority directly. Predicting the "rank" instead would be a regression problem, rather than a classification one. Some scikit-learn classifiers have a `predict_proba` method which will produce the probability that email are important, but you can't train those on the ranks. (*) I am the author of scikit-learn's `DictVectorizer`, so this is not unbiased advice. It is from the horse's mouth, though :)
Pass vector (float4) kernell argument to OpenCL (Python) Question: is there any easy way how to pass float4 or any other vector argument to OpenCL kernel? For scalar argument (int, float) you can pass it directly while calling kernel. For array argument you have to first copy it to GPU using cl.Buffer() and than pass pointer. Sure it is probably possible to pass float4 the same way as array. But I ask if there is any easier and more clear way. ( especially using Python, numpy, pyOpenCL) I tried pass numpy array of size 4*float32 as float4 but it does not work. Is it possible to do it somehow else? For example : **kernnel:** __kernel void myKernel( __global float * myArray, float myFloat, float4 myFloat4 ) **Python:** myFloat4 = numpy.array ( [1.0 ,2.0 ,3.0], dtype=np.float32 ) myArray = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=myArray_host) kernelargs = ( myArray , numpy.float32(myFloat) , myFloat4) prg.myKernel(queue, cl_myArray.shape() , None, *(kernelargs) ) **I got error :** pyopencl.LogicError: when processing argument #2 (1-based): clSetKernelArg failed: invalid arg size the other possibiliy is passing it as set of scalar int or float - like: __kernel void myKernel( __global float * myArray, float myFloat, float myFloat4_x, float myFloat4_y, float myFloat4_z ) kernelargs = ( myArray , numpy.float32(myFloat) ,numpy.float32(myFloat4_x),numpy.float32(myFloat4_y),numpy.float32(myFloat4_z)) but this is also not very convenient - you can be easily lost in many variable names if you want for example pass 4x float4 and 5x int3 to the kernell. I think passing vectors (2,3,4) of int and float must be quite common in OpenCL - for example the size of 3D data grids. So I wonder if it is really necessary to pass it using cl.Buffer() as pointers. I guess that constant argument float4 is also faster than *float (because it can be shared as a constant by all workitems) Answer: I find this a nice way to create a float4 in python: import numpy as np import pyopencl as cl import pyopencl.array as cl_array data= np.zeros(N, dtype=cl_array.vec.float4) **Edit:** To also give a MWE: import numpy as np import pyopencl as cl import pyopencl.array as cl_array deviceID = 0 platformID = 0 workGroup=(1,1) N = 10 testData = np.zeros(N, dtype=cl_array.vec.float4) dev = cl.get_platforms()[platformID].get_devices()[deviceID] ctx = cl.Context([dev]) queue = cl.CommandQueue(ctx) mf = cl.mem_flags Data_In = cl.Buffer(ctx, mf.READ_WRITE, testData.nbytes) prg = cl.Program(ctx, """ __kernel void Pack_Cmplx( __global float4* Data_In, int N) { int gid = get_global_id(0); Data_In[gid] = 1; } """).build() prg.Pack_Cmplx(queue, (N,1), workGroup, Data_In, np.int32(N)) cl.enqueue_copy(queue, testData, Data_In) print testData
Why does this Python logical indexing take up so much memory Question: I have a 1-D time series that is 1e8 long (100,000,000 elements). [Here](https://www.dropbox.com/s/3eb6ywjzoo468rd/ch008.ddt) is a link to the data I am using on Dropbox. (The file is 382 MB.) **Update** Based on memory_profiling, the error occurs in the line data[absolute(data-dc)< m*std(data)]=dc. More specifically, the operation `absolute(data-dc)` eats up all the memory. `Data` is as described above and `dc` is a constant. Perhaps this is a subtle syntax error? I want to remove outliers and artifacts from it and replace those values with the median. I attempt to do that with the following function. from numpy import * from sys import argv from scipy.io import savemat from scipy.stats import scoreatpercentile def reject_outliers(data,dc,m=3): data[data==0] = dc data[bp.absolute(data-dc) < m*np.std(data)] = dc return data def butter_bandpass(lowcut,highcut,fs,order=8): nyq = 0.5*fs low = lowcut/nyq high = highcut/nyq b,a= butter(order, [low, high], btype='band') return b,a def butter_bandpass_filter(data,lowcut,highcut,fs,order=8): b,a = butter_bandpass(lowcut,highcut,fs,order=order) return lfilter(b,a,data) OFFSET = 432 filename = argv[1] outname = argv[2] print 'Opening '+ filename with open(filename,'rb') as stream: stream.seek(OFFSET) data=fromfile(stream,dtype='int16') print 'Removing Artifacts, accounting for zero-filling' dc = median(data) data = reject_outliers(data,dc) threshold = scoreatpercentile(absolute(data),85) print 'Filtering and Detrending' data = butter_bandpass_filter(data,300,7000,20000) savemat(outname+'.mat',mdict={'data':data}) Calling this on one file eats up 4 GB of RAM and 3 GB of virtual memory. I'm sure it's the second line of this function because I stepped through the script I wrote and it always hangs on this part. I can even see (in Finder on OS X) the available hard drive space plummeting by the second. The time series is not long enough to explain it. What is wrong with the second line of `reject-outliers`? Answer: I just generated 100,000,000 random floats and did the same indexing you describe. Memory usage was well under a gigabyte throughout. What else is your code doing that you are not telling us about? Try running your code through the excellent [memory_profiler](http://pypi.python.org/pypi/memory_profiler). * * * Edit: Added code and output of memory_profiler: from numpy.random import uniform import numpy @profile def go(m=3): data = uniform(size=100000000) dc = numpy.median(data) data[numpy.absolute(data-dc) < m*numpy.std(data)] = dc return data if __name__ == '__main__': go() Output: Filename: example.py Line # Mem usage Increment Line Contents ================================================ 3 @profile 4 15.89 MB 0.00 MB def go(m=3): 5 778.84 MB 762.95 MB data = uniform(size=100000000) 6 778.91 MB 0.06 MB dc = numpy.median(data) 7 874.34 MB 95.44 MB data[numpy.absolute(data-dc) < m*numpy.std(data)] = dc 8 874.34 MB 0.00 MB return data As you can see, 100M floats do not use up that much memory.
Ipython notebook crash using rmagic extension Question: I am trying to run the [rmagic functions extension](http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/3607712653c66d63e0d7f13f073bde8c0f209ba8/docs/examples/notebooks/rmagic_extension.ipynb) example, but ipython crashes with console error message '\u used without hex digits in character string starting "c:\u". I suspect that this is an R error message caused by rmagic passing c:\path instead of c:\ or c:/. There is probably an easy way to fix this (IPython or Notebook startup parameters?) , but, as a newbie to rmagic and rpy2, I need some expert help please. The following simple snippet from the example causes the kernel to die: import rpy2 %load_ext rmagic %R x=1 I am a windows user... Answer: Found a solution to this ipython/windows problem [here](https://github.com/ipython/ipython/issues/2533)
plot many circles based on x,y,r being vectors in python Question: x,y are positions of the circles and r is the radius - all vectors.I want to plot them all at once. Something like: import matplotlib.pyplot as plt from matplotlib.patches Circle #define x,y,r vectors fig = plt.figure() ax1 = fig.add_subplot(1,1,1) plt.Circle((x,y),r,color='r') plt.show() Thanks. Answer: I am not informed about the Circles patch, but here is how you can do it with the standard plot command: import numpy as np import matplotlib.pyplot as plt x = np.array([0.2,0.4]) y = np.array([0.2,1.2]) r = np.array([0.5,0.3]) phi = np.linspace(0.0,2*np.pi,100) na=np.newaxis # the first axis of these arrays varies the angle, # the second varies the circles x_line = x[na,:]+r[na,:]*np.sin(phi[:,na]) y_line = y[na,:]+r[na,:]*np.cos(phi[:,na]) plt.plot(x_line,y_line,'-') plt.show() The basic idea is to give the `plt.plot(...)` command two 2D arrays. In that case they are interpreted as a list of plots. Espacially for many plots (=many circles) this is much faster, than plotting circle by circle.
find all elements in a list of positive numbers that add up to number X Question: I'm trying to reverse engineer a legacy report and using python to solve the problem. The legacy report has an end sum number of 200,000. I know a collection of the numbers that could end up to this 200k, but this collection is littered with many other numbers that are to be filtered out (with logic i'm yet to understand). In python, How could i iterate through the list of numbers to find all entries (sub-lists) of variable length (could be 1 element that = 200k, or the product of 15 elements...) that would add up to the 200k? I started to write it out, then decided to ask for help when i realized element #1 + 2 could overflow but list element #1 + 4 + 7 could be a match to the 200k.... It's almost like factorization, however with the sum's instead of the products, and within a list of possible candidates. Not sure. Any ideas? Anyone ever done anything like this? **Additional Details:** With permutations and numpy i'm getting a result as expected, however it is taking far too long with the expected inputs and outputs. (i.e. days..?) below is where I am at: Below seems to give correct results, although it seems it will take awhile. I'll accept the answer above and let this run over night. Thanks, from itertools import permutations import numpy , pickle, random output_results = {} input_array = [random.randrange(0,15000) for i in range(1000)] desired_sum = 200000 #input_array = (1,2,9,13,12) #desired_sum = 23 for r in range(1,len(input_array)): for p in permutations(input_array, r): temp_sum = numpy.sum(p) if temp_sum == desired_sum: output_results[p] = numpy.sum(p) if r % 10 == 0: print "Finished up to number %s " % r pickle.dump( output_results, open( "save.p", "wb" ) ) Answer: [Itertools.permutations](http://docs.python.org/2/library/itertools.html#itertools.permutations) can help. Varying the value of `r` in `permutations(iterable, r)` you can try to find all the possible permutations containing `r` entries from `iterable` (your collection), of which you can easily get sums (e.g. with `numpy.sum`). If you have some idea of what to expect and set a reasonable upper limit for `r` you should get an answer in a reasonable time **edit** @joefromct: you can first estimate the largest value of `r` needed to find the solution you want in the following way (is not tested, but the idea should be correct) sorted_input = np.sorted(input_array) cumsum = np.cumsum(sorted_input) max_r = (cumsum<desired_sum).sum() if max_r == len(input_array) and sorted_input[-1] < desired_sum: print("sorry I can't do anything for you") exit() for r in range(1,max_r): [...]
How can I insert arrays into columns on a database table for my pyramid app? Question: I am trying to create an sql (sqlite) database where users upload an stl file and the data (all the points, triangles, ect.) is stored in a database so that it is permanently available. Is it possible to do this with a database with only two columns (three with the key): name (title for the url), and data (the array data)? The data array is in the format: [[[x1,y1,z1],....],[[v1,v2,v3],...]]. All points are given first and then the triangles are defined through ordering of the points given. Can this array be stored in the database, and if so, what data type would it be (integer, string, ect.)? Upon reading into this issue more, It seems that pickling would be a good way to go: <http://docs.python.org/2/library/pickle.html> I am having trouble figuring out how to implement this. Should I just add pickle(data)? Edit: upon further review, it seems like pickling introduces some security holes that do not exist if using JSON. Is it possible to simply call `jsondatastring=JSON.stringify(data)` and then save that to the database? If so, what would be the appropriate column type? Answer: If your intention is only to store the array in DB and work with it in your webapp code, SQLAlchemy's [`PickleType`](http://docs.sqlalchemy.org/en/rel_0_8/core/types.html#sqlalchemy.types.PickleType) is a good choice. Pickling and unpickling will be done transparently for you: from sqlalchemy.types import PickleType class Foo(Base): __tablename__ = 'foo' id = Column(Integer, primary_key=True) name = Column(String) array = Column(PickleType) foo = Foo(name=u'bar', array=[1, 2, 3]) session.add(foo) session.commit() foo = session.query(Foo).filter_by(name=u'bar').one() print foo.array
Access python nested dictionary items via a list of keys Question: I have a complex dictionary structure which I would like to access via a list of keys to address the correct item. dataDict = { "a":{ "r": 1, "s": 2, "t": 3 }, "b":{ "u": 1, "v": { "x": 1, "y": 2, "z": 3 }, "w": 3 } } maplist = ["a", "r"] or maplist = ["b", "v", "y"] I have made the following code which works but I'm sure there is a better and more efficient way to do this if anyone has an idea. # Get a given data from a dictionary with position provided as a list def getFromDict(dataDict, mapList): for k in mapList: dataDict = dataDict[k] return dataDict # Set a given data in a dictionary with position provided as a list def setInDict(dataDict, mapList, value): for k in mapList[:-1]: dataDict = dataDict[k] dataDict[mapList[-1]] = value Answer: Use `reduce()` to traverse the dictionary: def getFromDict(dataDict, mapList): return reduce(lambda d, k: d[k], mapList, dataDict) and reuse `getFromDict` to find the location to store the value for `setInDict()`: def setInDict(dataDict, mapList, value): getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value All but the last element in `mapList` is needed to find the 'parent' dictionary to add the value to, then use the last element to set the value to the right key. Demo: >>> getFromDict(dataDict, ["a", "r"]) 1 >>> getFromDict(dataDict, ["b", "v", "y"]) 2 >>> setInDict(dataDict, ["b", "v", "w"], 4) >>> import pprint >>> pprint.pprint(dataDict) {'a': {'r': 1, 's': 2, 't': 3}, 'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}
Why don't nested sizers expand in wxPython if hidden at init? Question: I am trying to build a 3-panel GUI and everything was going great until I tried to nest panels/windows inside of other panels and hide them upon GUI startup. See this image... The yellow/green/blue boxes were automatically expanded to fill up their panels during init, but the little purple box is built BUT then hidden during wx.Panel init until a 2 second timer expires and then at that time that object's Show() method is invoked. At that time it does not not fill up the containing panel. It seems that hiding a panel during init causes the panel sizer to pick the default size, 20x20. ![sizer test](http://i.imgur.com/pStOp5g.jpg) Here is the code: import wx import wx.lib.scrolledpanel as scrolled class NavPanel(wx.Panel): """""" def __init__(self, parent, actionPanel): """Constructor""" wx.Panel.__init__(self, parent) #, size=(200,600)) self.actionPanel = actionPanel self.SetBackgroundColour("Yellow") class ActionPanel(wx.Panel): """""" def __init__(self, parent, target_item=None): """Constructor""" wx.Panel.__init__(self, parent) self.SetBackgroundColour("Green") self.sc = NestedScrolledActionPanel(self) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.sc, 1, wx.EXPAND) self.SetSizer(sizer) def show_child(self): # Putting a sizer here doesn't work either... self.sc.Show() class NestedScrolledActionPanel(wx.ScrolledWindow): """""" def __init__(self, parent, target_item=None): """Constructor""" wx.ScrolledWindow.__init__(self, parent) self.SetBackgroundColour("Purple") # I don't want to show this at starutp, but hiding it causes the sizer to startup at 20x20! # Comment out this line and the sizer set in ActionPanel works, but you see it at startup self.Hide() class ConsolePanel(scrolled.ScrolledPanel): """""" def __init__(self, parent): """Constructor""" scrolled.ScrolledPanel.__init__(self, parent, -1) self.SetBackgroundColour("Blue") class MainPanel(wx.Panel): """""" def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) mainSplitter = wx.SplitterWindow(self) topSplitter = wx.SplitterWindow(mainSplitter) self.rightPanel = ActionPanel(topSplitter) self.rightPanel.SetBackgroundColour("Green") leftPanel = NavPanel(topSplitter, self.rightPanel) leftPanel.SetBackgroundColour("Yellow") topSplitter.SplitVertically(leftPanel, self.rightPanel, sashPosition=0) topSplitter.SetMinimumPaneSize(200) bottomPanel = ConsolePanel(mainSplitter) mainSplitter.SplitHorizontally(topSplitter, bottomPanel, sashPosition=400) mainSplitter.SetSashGravity(1) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(mainSplitter, 1, wx.EXPAND) self.SetSizer(sizer) return ######################################################################## class MainFrame(wx.Frame): """""" def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title="Sizer Test", size=(800,600)) self.panel = MainPanel(self) self.Centre() self.Show() self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) self.timer.Start(2000) def OnTimer(self, e): self.panel.rightPanel.show_child() if __name__ == '__main__': app = wx.App(redirect=False) print "Launching frame" frame = MainFrame() print "starting mainloop" app.MainLoop() The reason why I want this panel hidden upon GUI startup is because I will have many different panels residing in that ActionPanel space (the green box) and when the user clicks on a tree node in the yellow box, the panel that is displayed in the green box will be hidden and a different panel will be shown. If I don't hide all of the panels at startup, they are "stacked" on top of each other and I will have to set a timer to go through and hide them all at some point after GUI launches??? That seems hokey. How else can I do it? Answer: Add `self.Layout()` to your show_child method. Just showing the child does not trigger a layout like a size event would. For those times when layout needs to change without a size event you need to call Layout yourself.
Java NIO server and Python asyncore client Question: I have the following java NIO server and further below a python asyncore client. The server prints "Accepted...\n", however, the client's handle_connect is never called. Could someone help me with what's wrong with the server and help me connect to the server with the client? Java NIO Server: import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.Selector; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; class Server { public Selector sel; public ServerSocketChannel ssc; public SocketChannel channel; public static void main(String[] args) throws Exception { Server s = new Server(); s.openSocket(12000); s.run(); } private void openSocket(int port) throws Exception { InetSocketAddress address = new InetSocketAddress("0.0.0.0", port); ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ssc.socket().bind(address); sel = Selector.open(); ssc.register(sel, SelectionKey.OP_ACCEPT); } public void run() throws Exception { while (true) { sel.select(); Set<SelectionKey> keys = sel.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { SelectionKey key = (SelectionKey) i.next(); i.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { channel = ssc.accept(); channel.configureBlocking(false); System.out.println("Accepted...\n"); channel.register(sel, SelectionKey.OP_READ); } if (key.isReadable()) { if (channel == key.channel()) { System.out.println("Readable\n"); ByteBuffer buffer = ByteBuffer.wrap(new byte[1024]); int pos = channel.read(buffer); buffer.flip(); System.out.println(new String(buffer.array(), 0, pos)); } } } } } } Python asyncore client: import socket import select import asyncore class Connector(asyncore.dispatcher): def __init__(self, host, port): asyncore.dispatcher.__init__(self) self.buffer = "hi" self.create_socket() self.connect((host, port)) def handle_connect(self): print("[]---><---[]") # not called <------------------ def handle_read(self): pass def writable(self): len(self.buffer) > 0 def handle_write(self): sent = self.send(self.buffer) print("[]--->" + self.buffer[0:sent]) self.buffer = self.buffer[sent:] def handle_close(self): print("[]...x...[]") self.close() connector = Connector("localhost", 12000, Handler()) asyncore.loop() Python normal working client: # Echo client program import socket import sys HOST = 'localhost' # The remote host PORT = 12000 # The same port as used by the server s = None for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) print("socket") except OSError as msg: s = None continue try: s.connect(sa) print("connected") except OSError as msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) print("Sending") s.sendall(bytes("Hey server", "UTF-8")) data = s.recv(1024) # s.close() print('Received', repr(data)) **EDIT** Added isReadable to Java and added working normal python client. Answer: You made two mistakes in implementing one of the tedious asyncore methods: def writable(self): len(self.buffer) > 0 This method returns `None` (because you forgot the `return` part of that statement). The first mistake is that `None` has a false boolean value, so `Connector` is never considered writeable. The second mistake is that you need to check for writeability during the attempt to establish the connection. Since `writable` always returns false, including during the connection attempt, no progress is ever made to establish the connection. I recommend checking out [Twisted](http://twistedmatrix.com/) instead. It doesn't make you implement low-level buffer management yourself and connection setup code yourself and as a result actually produces more efficient code that's shorter and easier to write. asyncore should really be considered a historical artifact and never actually used.
Switching kivy widgets Question: I am using the Kivy python library. I have two widgets defined. When the program runs, I run the first widget. When that widgets button is pressed, I want it to dissapear and be replaced with the second widget. Here is the .kv for the two widgets #uitest.kv <TestForm>: canvas: Rectangle: pos: self.center_x, 0 size: 10, self.height BoxLayout: size: root.size padding: 40 Button: text: 'Hello' on_release: root.testCallback() <TestForm2>: canvas: Rectangle: pos: self.center_x, 0 size: self.height, 10 My main python file runs the app, and returns the first widget #main.py from testform import TestForm from kivy.app import App class UITestApp(App): def build(self): return TestForm() # Main launching point if __name__ in ('__main__', '__android__'): UITestApp().run() My first widget has a callback. This is where the code-in-question belongs from testform2 import TestForm2 from kivy.uix.widget import Widget class TestForm(Widget): def testCallback(self): TestForm2() # Code in question goes here. @TODO replace this widget with TestForm2 widget. The idea here is to have a user interface manager. This manager doesn't run the UI like a tree, but like a list and stack. The list holds instances of all my UI Forms. The stack holds the traversal of said forms, whenever we jump to a form we push it to the stack and "render" or whatever that one. EDIT: I chose my answer, but in my searches I also found the Screen object: <http://kivy.org/docs/api-kivy.uix.screenmanager.html> Personally, the clear() and add() commands are more powerful, but the screen takes a lot of that out of your hands if you're interested. Transition effects too. Answer: My suggestion is to have an interface manager widget, then you can have various widgets for your UI forms. import kivy from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.app import App class InterfaceManager(BoxLayout): def __init__(self, **kwargs): super(InterfaceManager, self).__init__(**kwargs) self.first = Button(text="First") self.first.bind(on_press=self.show_second) self.second = Button(text="Second") self.second.bind(on_press=self.show_final) self.final = Label(text="Hello World") self.add_widget(self.first) def show_second(self, button): self.clear_widgets() self.add_widget(self.second) def show_final(self, button): self.clear_widgets() self.add_widget(self.final) class MyApp(App): def build(self): return InterfaceManager(orientation='vertical') if __name__ == '__main__': MyApp().run() You wouldn't structure it like that of course. You could hold all your forms in a dictionary on the Container object and have a universal callback which provides another form by key. class InterfaceManager(BoxLayout): def __init__(self, **kwargs): super(InterfaceManager, self).__init__(**kwargs) self.forms = {} def add_form(self, key, form): self.forms[key] = form def uniCallback(self, button): self.clear_widgets() # You could introduce a more elegant key # handling system here. self.add_widget(self.forms[button.text])
Package and Module in Python for creating a Web App using Flask Question: Currently, I am in process of coding a web interface for a company. This web interface is based on python micro-framework Flask. I want to use MVC principle to build this interface. And I have some questions in mind. The model will contain the data for ORM-mapping with help of SQLAlchemy, no problem there. The views is based on some html and css, I don't think there will be a problem here either. The controller on the other hand is kind of cumbersome. I want to separate the pages into module and the script application into separate modules, and packed all these modules into a packages of controller for example like: * Session Module (Login/Logout/Cookies) * Administrator Module (Manage Registered Accounts/Content/etc.) * Application Script 1 Module * Application Script 2 Module * Application Script 3 Module I understand that to render the template you need to use the routing etc. But how do I make it that if a certain link is called, it will called the specific module and pull methods from there. Is it OK, to create a one main controller for the routing and for every method in the routing I import one of the modules above? @app.route('/') def index(): return render_template("index.html") @app.route('/login/', methods = ('GET', 'POST')) def login(): from session import login -> call method from 'login' here @app.route('/account/<username>', methods = ('GET', 'POST')) def login(): from administrator import view_account -> call method from 'view_account' here is this a good practice? or should I just start at the header and import every module I have in this package. My first thinking was to prevent that the apps to load to long because of the size of the script, only certain module will be called if the page that need that module is accessed or something like that. Answer: If I got your question right, then you for sure want to use blueprints :) Read more in [documentation](http://flask.pocoo.org/docs/blueprints/) Basically this is the way how to make Flask application modular without one controller with all the possible modules imported there or some other hacks. Here you can find an [example of application](https://github.com/mitsuhiko/flask/wiki/Large-app-how-to) which uses blueprints.
Understanding PyDict_Check behaviour Question: I've been playing around with the Python C API for a while. I like it a lot but today I hit a roadblock. I have a Python extension that has a function which expects one or two dictionaries as argument. I fear I might have misunderstood how `PyDict_Check`, or `PyArg_ParseTuple` works. Here's a dumbed down example: static PyObject * doStuffToOtherStuff(MyCustomPyObject *self, PyObject *args) { char const *fmt = "OO"; PyObject dict1, dict2; if (!PyArg_ParseTuple(args, fmt, &dict1, &dict2)) return NULL; int hasDict1 = PyDict_Check(&dict1); int hasDict2 = PyDict_Check(&dict2); printf("%d %d\n"); Py_INCREF(Py_None); return Py_None; } When built and imported I call it like this for example: myClass.doStuffToOtherStuff(dict(), None) I expect this to print ` 1 0 ` but it actually prints ` 1 1 `. So does: myClass.doStuffToOtherStuff(None, None) myClass.doStuffToOtherStuff(None, dict()) myClass.doStuffToOtherStuff({}, None) #etc... If I change `PyDict_Check` to `PyDict_CheckExact` it prints `0 0` instead, no matter what I pass as arguments. Any insight will be much appreciated. Answer: `PyArg_ParseTuple` with `O` arguments expects a pointer to a `PyObject *`, not a pointer to a `PyObject` (i.e. the variadic argument should be of type `PyObject **`). So your code should be: char const *fmt = "OO"; PyObject *dict1, *dict2; if (!PyArg_ParseTuple(args, fmt, &dict1, &dict2)) return NULL; int hasDict1 = PyDict_Check(dict1); int hasDict2 = PyDict_Check(dict2); // ...
How to use relative imports in both, module and main Question: I have the following setup of a library in python: library | - __init__.py | - lib1.py | - ... | - tools | - __init__.py | - testlib1.py so in other words, the directory `library` contain python modules and the directory `tools`, which is a subdirectory of `library` contains e.g. one file `testlib1.py`to test the library `lib1.py`. `testlib1.py` therefore need to import `lib1.py` from the directory above to do some tests etc., just by calling `python testlib1.py` from somewhere on the computer, assuming the file is in the search path. In addition, I only want ONE `PYTHONPATH` to be specified. But we all know the following idea for `testlib1.py` does not work because the relative import does not work: from .. import lib1 ... do something with lib1 I accept two kind of answers: 1. An answer which describes how still to be possible to call `testlib1.py` directly as the executing python script. 2. An answer that explains a better conceptual setup of of the modules etc, with the premise that everything has to be in the directory `project` and the tools has to be in a _different_ directory than the actual libraries. If something is not clear I suggest to ask and I will update the question. Answer: Try adding a `__init__.py` to the `tools` directory. The relative import should work.
Python MySQL connection. Running on a Virtual Machine Question: I am trying to establish a connection to MySQL that is running locally using python. i use the following code import MySQLdb db = MySQLdb.connect("localhost","username","password","dbname") I am working on a virtual machine and I am running both the Python and MySQL on the VM. I am not able to make a connection. I get this errror OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)") I have tried providing the ip address of the VM in place of localhost and still didn't work. I tried specifying the port number too. Is the connection different because it runs on a VM?? Answer: When you try to connect directly to mysql Database from command line does it work? What OS is your VM running? If its a Unix then is there a mysqld process runnning? In any case this may not have anything to do with Python. Your code snipppet looks ok. You just need to resolve the connectivity issue. Look at this page for details on how you could get to to the root of this problem. <http://dev.mysql.com/doc/refman/5.5/en/can-not-connect-to-server.html> I hope that this helps.
Using mock library to patch a class method Question: I'm writing unit tests, and I need to mock a method call so that in most of the cases it behaved as method itself except when argument gets a special value 'insert into'. Here is a simplified production code: class CommandServer(object): def __init__(self): self.rowcount = None def runSQL(self, sql): print "Do something useful" self.rowcount=5 return self class Process(object): def process(self): cs = CommandServer() cs.runSQL("create table tbl1(X VARCHAR2(10))") r = cs.runSQL("insert into tbl1 select * from tbl2") print "Number of rows: %s" % r.rowcount p = Process() p.process() which prints Do something useful Do something useful Number of rows: 5 I can make a mock version myself using the following code: runSQL = CommandServer.runSQL def runSQLPatch(self, sql): if sql.lstrip().startswith('insert into'): print "Patched version in use" class res(object): rowcount = -1 return res else: return runSQL(self, sql) CommandServer.runSQL = runSQLPatch p = Process() p.process() which prints Do something useful Patched version in use Number of rows: -1 I want to use `mock` [library](http://www.voidspace.org.uk/python/mock/) to accomplish the same (I believe that this is the library included in [python 3](http://docs.python.org/dev/library/unittest.mock-examples.html)). How can I do that? (Python 2.6.2) Answer: To be entirely clear, it's only included in python 3.3 (which I'm so happy to have learned, thank you!). Otherwise, the pattern you could use is from mock import patch with patch.object(CommandServer, 'runSQL') as runSQL: class res(object): rowcount = -1 runSQL.return_value = res p = Process() p.process() for c in runSQL.call_list: assert c[1].lstrip().startswith('insert into') is True But this would cover all cases, not just cases where you are sending `'insert into'`. This might give you a hint as to where to look, but otherwise, I don't think what you're looking for is exactly possible with mock.
Sums of entries, Python Question: > **Possible Duplicate:** > [summing up values of columns from multiple > files](http://stackoverflow.com/questions/14712268/summing-up-values-of- > columns-from-multiple-files) I have a small problem here, I'm trying to sum up entries from multiple files (50), and each of them contain 3 columns. for example, using the first 3 files: file1.txt, file2.txt, file3.txt which look like: file1.txt: 2 3 4 1 5 6 5 4 7 file2.txt: 1 2 1 2 3 2 4 3 1 file3.txt: 6 1 1 1 3 0 3 4 5 So my question is how do i sum up all the entries from column one, column two and column three from the 50 files to end up with a file that looks like: output.txt: 9 6 6 4 11 8 12 11 13 I've read in the 50 files and appended them but I'm having trouble actually summing the entries one by one. so I've done this: for p in range(50): locals()['first_col%d' % p] = [] locals()['second_col%d' % p] = [] locals()['third_col%d' % i] = [] for i in range(1,50): f = open("file"+str(i)+".txt","r") for line in f: locals()['fist_col%d' % i].append(float(line.split()[0])) locals()['second_col%d' % i].append(float(line.split()[1])) locals()['third_col%d' % i].append(float(line.split()[2])) f.close() I'm trying to think of a way to put this in a loop that will read in all the `first_cols` (`first_col1` ,`first_col2`, `first_col3`, etc), `second_cols` and `third_cols` and sum up the entries. Answer: You could use `glob` to wildcard match the filename pattern, then a bit of judicious use of `zip` and abuse `literal_eval` (might want to consider just a generator to convert to `int` instead though) - NB - this expects the same number of columns and rows for each file, otherwise truncation will occur: from glob import glob from ast import literal_eval filenames = glob('/home/jon/file*.txt') files = [open(filename) for filename in filenames] for rows in zip(*files): nums = [literal_eval(row.replace(' ', ',')) for row in rows] print map(sum, zip(*nums)) [9, 6, 6] [4, 11, 8] [12, 11, 13]
What is the fastest cache for small and rarely changing data to use with Django? Question: I am in a process of switching from PHP to Python + Django and looking for equivalent of PHP's "Array cache". For small data sets from DB like "categories" that was changing very rarely but accessed very often i was using array cache. <http://www.mysqlperformanceblog.com/2006/08/09/cache-performance-comparison/> Concept of it was to generate PHP source with the tree of categories and when the opcode was turned on it was working like embedding data into application sources. It was the fastest imaginable cache, very helpful for large load. Django manual(<https://docs.djangoproject.com/en/1.4/topics/cache/>) states: > By far the fastest, most efficient type of cache available to Django, > Memcached.. So the questions are: * Would generating a .py file with python dictionaries/lists made any sense? * Will this be faster than Memcached? If not why? * Are there any known implementations of this? * Does Python have anything like var_export() function from PHP? EDIT: As pointed in an answer i can use repr() and this can be benchmarked easily so i have created a simple benchmark: <https://github.com/fsw/pythonCachesBenchmark> output of this on my local machine was: FIRST RUN get_categories_from_db 6.57282209396 get_categories_from_memcached (SET CACHE IN 0.000940) 4.88948512077 get_categories_from_pickledfile (SET CACHE IN 0.000917) 2.87856888771 get_categories_from_pythonsrc (SET CACHE IN 0.000489) 0.0930788516998 SECOND RUN get_categories_from_db 6.63035202026 get_categories_from_memcached 4.60877108574 get_categories_from_pickledfile 2.87137699127 get_categories_from_pythonsrc 0.0903170108795 get_categories_from_pythonsrc is simple implementation of PHP's arraycache i was talking about: def get_categories_from_pythonsrc(): if not os.path.exists('catcache.py'): start = time.time() f = open( 'catcache.py', 'wb' ) categories = get_categories_from_db() f.write('x = ' + repr(categories)) f.close() print '(SET CACHE IN %f)' % (time.time() - start) import catcache return catcache.x this is my simple pickledfile cache implementation: def get_categories_from_pickledfile(): path = 'catcache.p' if not os.path.exists(path): start = time.time() pickle.dump( get_categories_from_db(), open( path, 'wb' ) ) print '(SET CACHE IN %f)' % (time.time() - start) return pickle.load(open( path, 'rb' )); complete source: <https://github.com/fsw/pythonCachesBenchmark/blob/master/test.py> I will later add "Django's low-level cache APIs" to this benchmark to see what they are about. So as my intuition suggested caching dictionary in a python .py file is the fastest way i could get (over 30 times faster than cPickle + file) As said i am new to Python so probably i am missing something here? If not: why isn't this solution widely used? Answer: Python has several solutions that may work here: * Memcached (as you already know), * pickle (as Blender mentioned) - which of course can be used with eg. Memcached, * several other caching (eg. for local memory) & serialization (eg. `simplejson`) solutions, In general `pickle` is very fast (use `cPickle` if you need more speed) and in Python you do not need anything like `var_export()` (although you can use `repr()` on variables to have their valid literal, if they are of one of primitive types). `pickle` in Python is more similar to `serialize` in PHP. Your question is not very specific, but the above should give you some insight. Also you need to take into account that PHP and Python have different philosophies, so solutions to the same problems may look differently. In this specific case `pickle` module should solve your issues.
PIL to Qimage conversion: QImage constructor does not free memory Question: I am developping a Qt application **loading** pictures with **PIL** , modifying colors and alpha channels, then **converting them as QImage**. Here is the problematic piece of code: normal **repeated usage of the ImageQt** function: # memory is filled around 7 mB/s if **name** == '**main** ': while True: im = Image.open('einstein.png') #small picture imQt = QtGui.QImage(ImageQt.ImageQt(im)) # convert to PySide.QtGui.QImage imQt.save('outtest.png')# -> rendered picture is correct #del(imQt) and del(im) does not change anything time.sleep(0.02) The problem here is the **crazy memory filling** , when the picture is supposed to be erased by the garbage collector. I checked with gc.collect(), but it did not change anything. This example shows what happends with the **imageQt** function, but in fact, I noticed this is a problem caused by QImage: **if you repeatedly use the QImage constructor with data, the memory used by python process increases** : im= Image.load('mypic.png').convert('RGBA') data = im.toString('raw','RGBA') qIm = QtGui.QImage(data,im.size[0],im.size[1],QtGui.QImage.Format_ARGB32) qIm.save('myConvertedPic.png')# -> picture is perfect If you put this code in a loop, memory will increase, as 1st example. From there i am a bit lost because this is a PySide problem... I tried to use a workaround, but it does not work either: #Workaround, but not working .... if **name** == '**main** ': while True: im = Image.open('einstein.png') #small picture imRGBA = im.convert('RGBA') # convert to RGBA imRGBA.save('convtest.png') # ->picture is looks perfect imBytes = imRGBA.tostring('raw','RGBA') #print("size %d %d" % (imRGBA.size[0],imRGBA.size[1])) qImage = QtGui.QImage(imRGBA.size[0],imRGBA.size[1],QtGui.QImage.Format_ARGB32) # create new empty picture qImage.fill(QtCore.Qt.blue) # fill with blue, otherwise it catches pieces of the picture still in memory loaded = qImage.loadFromData(imBytes,'RGBA') # load from raw data print("success %d" % loaded)# -> returns 0 qImage.save('outtest.png')# -> rendered picture is blue time.sleep(0.02) `I am really stuck here, if you could help **find a solution with this workaround** ? Because I'm really stuck here! Also I would like to **discuss the QImage problem**. Is there any reliable way to free this memory ? Could the fact I am using python3.2(32bits) be a problem in this case ? Am I the only one in this case ? The imports I am using in case of: import time import sys import PySide sys.modules['PyQt4'] = PySide # this little hack allows to solve naming problem when using PIL with Pyside (instead of PyQt4) from PIL import Image, ImageQt from PySide import QtCore,QtGui Answer: After further unsuccessful searching, I noticed, that the PIL function **image.tostring()** associated with a **QImage constructor** caused this problem im = Image.open('einstein.png').convert('RGBA') data = im.tostring('raw','RGBA') # the tostring() function is out of the loop while True: imQt = QtGui.QImage(data,im.size[0],im.size[1],QtGui.QImage.Format_ARGB32) #imQt.save("testpic.png") #image is valid time.sleep(0.01) #no memory problem ! I think I am really close to find what is wrong, but I cannot point it out. It definitely has something to do with the `data` variable being held in memory.
Enaml examples from Enthought not working with Python(x,y) Enthought Tool Suite version of Enaml Question: I recently discovered Enaml, a Python GUI development package from Enthought. I'm very interested in using it with Enthought Traits and Chaco for more rapid scientific application development. I've been using Python(x,y) as my base Python installation because I like Spyder (familiar coming from Matlab background) my initial ambition was to build a PyQt application. Python(x,y) comes with Enthought Tool Suite which seems to contain most of Enthought's internally developed tools like Traits, Chaco, Mayavi, and Enaml. I saw the [pygotham slides](http://blog.enthought.com/?cat=157) on enaml and found the [tutorial examples](http://docs.enthought.com/enaml/instructional/tut_hello_world.html) which looks really cool! When I try to run the first example, however, I get this error: Traceback (most recent call last): File "C:\Users\bnables\Documents\Python\enaml\person.py", line 8, in from enaml.stdlib.sessions import simple_session ImportError: No module named sessions I just figured out that my brand new installation of Python(x,y) 2.7.3.1 has Enthought Tool Suite version 4.2 and Enaml version 0.2... the online Enaml documentation is up to version 0.6.3. So I guess my question is - what's the best path for a Python(x,y) user to use Enaml? I was trying to avoid using Enthought Python Distribution outright, because I'm using this at work and do not have the authority or funding to purchase the paid version. Can the Enthought Tool Suite built into Python(x,y) be updated from the Enthought source repositories? Can Enaml itself be updated individually? Enthought folks, I'm taking you up on your recent proclamation of officially supporting Stack Overflow questions! Thanks! Answer: I haven't used python(x,y), but I would assume you can build a project from source. This is probably the best course of action right now. We are putting a lot of efforts into Enaml which has the disadvantage of making it rapidly changing. It is not surprising that the version 0.2 doesn't run some of the examples from pygotham. FYI, EPDFree now allows to update packages including Enaml. But considering the number of commits to Enaml everyweek, I would still recommend building from source even with EPD for another few months just to get all the cool features going in. See we are delivering on our promise to monitor SO :). Jonathan
Looking for efficient python program for this following python script Question: I am looking for a memory efficient python script for the following script. The following script works well for smaller dimension but the dimension of the matrix is 5000X5000 in my actual calculation. Therefore, it takes very long time to finish it. Can anyone help me how can I do that? def check(v1,v2): if len(v1)!=len(v2): raise ValueError,"the lenght of both arrays must be the same" pass def d0(v1, v2): check(v1, v2) return dot(v1, v2) import numpy as np from pylab import * vector=[[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]] rav= np.mean(vector,axis=0) #print rav #print vector m= vector-rav corr_matrix=[] for i in range(0,len(vector)): tmp=[] x=sqrt(d0(m[i],m[i])) for j in range(0,len(vector)): y=sqrt(d0(m[j],m[j])) z=d0(m[i],m[j]) w=z/(x*y) tmp.append(w) corr_matrix.append(tmp) print corr_matrix Answer: Make your `matrix` (and your `vector`) into numpy `array`s instead of Python `list`s. That will make it take much less memory (and also run faster). To understand why: A Python `list` is a list of Python object instances. Each one of these has type information, pointers, and all kinds of other stuff to keep around beyond just the 8-byte number. Let's say each one ends up being 64 bytes instead of 8. So, that's 64 bytes per element, times 25M elements, equals 1600M bytes! By contrast, a numpy `array` is a list of just the raw values, together with a single copy of all that extra information (in the `dtype`). So, instead of 64 * 25M bytes, you've got 8 * 25M + 64 bytes, which is only 1/8th the size. As for the speed increase: If you iterate over a 5000x5000 matrix, you're calling some code in the inner loop 25M times. If you're doing a numpy expression like `m + m`, the code inside the loop is a few lines of C code that get compiled down to a few dozen machine-code operations, which is blazingly fast. If you're doing the loop explicitly in Python, the inside of that loop has to drive the Python interpreter every time through the loop, which is much, much slower. (On top of that, the C compiler will optimize the code, and numpy may have some explicit optimizations too.) Depending on how trivial the work inside the loop is, the speedup can be anywhere from 2x to 10000x. So, even if you have to make things a bit convoluted, try to find a way to express each step as an array broadcast rather than a loop, and it will be much faster. * * * So, how do you do that? Simple. Instead of this: corr_matrix=[] for i in range(len(vector)): tmp=[] # … for j in range(len(vector)): # … tmp.append(w) corr_matrix.append(tmp) Do this: corr_matrix=np.zeros((len(vector), len(vector)) for i in range(len(vector)): # … for j in range(len(vector)): # … corr_matrix[i, j] = w That immediately eliminates all the memory problems caused by the overhead of keeping around 25M Python `float` objects, and will give you a significant speed boost too. You can't reduce the memory any further except by not keeping the whole `array` in memory at once, but you should be fine already. (You can boost the speed even more by using broadcast operations in place of loops, but if the memory is your problem, and the performance is fine, it may not be necessary.)
pub_date is invalid in Django tutorial error Question: C:\mysite>python manage.py shell Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from polls.models import Poll,Choice >>> Poll.objects.all() [] >>> import django >>> from django.utils import timezone >>> p= Poll(question="what's new?",pub_date= timezone.now()) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python27\lib\site-packages\django\db\models\base.py", line 367, in __init__ raise TypeError("'%s'is an invalid keyword argument for this function"%kwargs.keys() [0]) TypeError: 'pub_date' is an invalid keyword argument for this function Answer: Check your models.py probably you mistyped the pub_date Datetime field
Read csv file from python Question: I had some data in excel file. I changed the file to .csv file and tried to write some python code to read the file. But I am getting some unpredictable outputs. My Code is like this: INPUT_DIR = os.path.join(os.getcwd(),"Input") OUTPUT_DIR = os.path.join(os.getcwd(),"Output") print INPUT_DIR, OUTPUT_DIR def read_csv(): files = os.listdir(INPUT_DIR) for file in files: file_full_name = os.path.join(INPUT_DIR,file) print file_full_name f = open(file_full_name,'r') for line in f.readlines(): print "Line: ", line def create_sql_file(): print "Hi" if __name__ == '__main__': read_csv() create_sql_file() This gives very peculiar output: C:\calcWorkspace\13.1.1.0\PythonTest\src\Input C:\calcWorkspace\13.1.1.0\PythonTest\src\Output C:\calcWorkspace\13.1.1.0\PythonTest\src\Input\Country Risk System Priority Data_01232013 - Copy.csv Line: PK** Does someone know of this issue? Answer: First, make sure you converted the file from Excel to csv, using the `Save As` menu from Excel. Simply changing the extension doesn't work. The output you are seeing is data from Excel's native format. Once you have converted the files, use the [`csv` module](http://docs.python.org/2/library/csv.html): import csv for filename in os.listdir(INPUT_DIR): with open(os.path.join(INPUT_DIR,filename), dialect='excel-tab') as infile: reader = csv.reader(infile) for row in reader: print row If you want to read raw Excel files, use the [`xlrd` module](http://www.python-excel.org/). Here is a [sample](https://raw.github.com/python- excel/tutorial/master/students/xlrd/simple.py) that shows how to read Excel files.
Displaying current output in wx.textctrl wigdet from python code entered in another wx.textctrl Question: I use two wx.TextCtrl widgets in my wxApp. The first one is used to provide Python code by app user, e.g.: from time import sleep for i in range(4): print i sleep(4) The second one is used to display the output. To process user code I use EXEC. But I have problems with displaying output dynamically. Currently the output is displayed in second wx.TextCtrl widget but after whole code is processed (after 16 seconds). I would like to display the user's code output every 4 seconds in above code. How to do that? I was trying to use threads but there are problems with using exec in case of threads. Answer: time.sleep will block the GUI's main loop, which is why you don't see any output. You will have to put that into a separate thread if you want to go that route. Otherwise, you could use a wx.Timer. Here's a tutorial: <http://www.blog.pythonlibrary.org/2009/08/25/wxpython- using-wx-timers/> I don't think you should use Python's exec command though. That can lead to code injection issues. Instead, you should consider using the subprocess module.
How to call Excel VBA functions and subs using Python win32com? Question: My Excel workbook contains VBA subs and macros similar to those below; they sit in Module1. How to call them using Python win32com module? Public Sub setA1(ByVal s As String) ThisWorkbook.ActiveSheet.Range("A1").Value = s End Sub Public Function getA1() As String getA1 = ThisWorkbook.ActiveSheet.Range("A1").Value End Function Many thanks in advance! Answer: import win32com.client xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="c:\\temp\\book1.xls",ReadOnly=1) xl.Application.Run("setA1", '4') res = xl.Application.Run("getA1") print res xl = 0 Just as simple as this ....
Python IDLE doesn't find text files unless I specify the path Question: In my Python books and also the Python Documents this code should be enough to open a file: f = open("file.txt", "r") But if I do this I will get an error message telling me file.txt doesn't exist. If I however use the whole path where file.txt is located it opens it: f = open("C:/Users/Me/Python/file.txt", "r") Is there an explanation for this? Answer: In short - the immediate search path (the current working directory) is where Python will look... (so on Windows - possibly it'll assume C:\Pythonxy) Yes, it depends on where Python/IDLE is executed... for it to use its search path: >>> import os >>> os.getcwd() '/home/jon' >>> open('testing.txt') <open file 'testing.txt', mode 'r' at 0x7f86e140edb0> And in a shell - changing directories... then launching Python/IDLE jon@forseti:~$ cd /srv jon@forseti:/srv$ idle >>> import os >>> os.getcwd() '/srv' >>> open('testing.txt') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> open('testing.txt') IOError: [Errno 2] No such file or directory: 'testing.txt'
How to get multiple parameters with same name from a URL in Pylons? Question: So unfortunately I find myself in the situation where I need to modify an existing Pylons application to handle URLs that provide multiple parameters with the same name. Something like the following... domain:port/action?c=1&v=3&c=4 Conventionally the parameters are accessed this way... from pylons import request c = request.params.get("c") #or c = request.params["c"] This will return "4" as the value in either case, because ignoring all but the last value seems to be the standard behavior in these situations. What I really need though, is to be able to access both. I tried printing out request.params and get something like this... NestedMultiDict([(u'c', u'1'),(u'v', u'3'),(u'c', u'4')]) I haven't found a way to index into it, or access that first value for c. I found a [similar question](http://stackoverflow.com/questions/353379/how-to- get-multiple-parameters-with-same-name-from-a-url-in-php) relating to this problem, but solved with PHP: Something along these lines would work well for me, but maybe some Python code that would fit into Pylons. Has anyone dealt with something like this before? Answer: From the docs - <http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/glossary.html#term- multidict> : > multidict An ordered dictionary that can have multiple values for each key. > Adds the methods getall, getone, mixed, add and dict_of_lists to the normal > dictionary interface. See Multidict and pyramid.interfaces.IMultiDict. So just call: request.params.getall('c')
Python getting next line following a certain Condition Question: I am trying to find a good way to return a value in a url page. I want that everytime "span class=" button" is listed I can grab the next line "span class=" button" 0.87 I want to get 0.87 I am trying: import urllib url = 'http://test.com' sock = urllib.urlopen(url) content = sock.read().splitlines() sock.close() for i in content: i = i.strip() This is where I get stuck, how do I get the next line? Answer: If this is HTML you could use an html parser like [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) buttons = soup.findAll('span', {'class': 'button'}) for button in buttons: button.nextSibling this uses [`nextSibling`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#next- sibling-and-previous-sibling) which looks like it has been changed to `next_sibling` in the most recent version of beautiful soup? Python has a built in HTMLParser if your data is <span class="button"> 0.87 </span> you could create a class like in the [example](http://docs.python.org/2/library/htmlparser.html#example-html- parser-application)
Get pip to work with git and github repository Question: I'm writting a python app that depends on another one that is hosted on a github repository (never in pypi) for development reasons. Lets call them: * App being written: `AppA` * App in github: `AppB` In App A, the setup.py is like: # coding=utf-8 import sys try: from setuptools import setup, find_packages except ImportError: import distribute_setup distribute_setup.use_setuptools() from setuptools import setup, find_packages setup( ... install_requires=[ # other requirements that install correctly 'app_b==0.1.1' ], dependency_links=[ 'git+https://github.com/user/[email protected]#egg=app_b-0.1.1' ] ) Now `AppA` is being built by `Jenkins CI` with every push and I get a failure because of the next error is thrown: error: Download error for git+https://github.com/user/[email protected]: unknown url type: git+https Funny thing is that this only happens in Jenkins, it works perfectly on my computer. I tried both of the other SSH urls that github gives and those are not even considered for download. Now, AppA is included in the requirements file of a project also being built by Jenkins, so installing the dependencies manually via `pip install AppA` `pip install AppB` is not an option, the dependencies are automatically installed by being included in the `requirements.txt`. Is there any way to make pip and git with github urls work together? Any help will be very appreciated :) Thanks in advance! Answer: The problem is not with `pip`, is with `setuptools`. The responsible for the `setup()` call is `setuptools` package (setuptools or distribute project). Neither `setuptools` or `distribute` understand that kind of url, they understand tarballs/zip files. Try pointing to Github's download url - usually a zip file. Your `dependency_links` entry is probably going to look like: dependency_links=[ 'https://github.com/user/app_b/archive/0.1.1.zip#egg=app_b-0.1.1' ] For more information take a look at <http://peak.telecommunity.com/DevCenter/setuptools#dependencies-that-aren-t- in-pypi>
two for loops, second only executes on first iteration python Question: I am a python noob, and I am attempting to compare values between lines in two files and output the "line name" followed by a 1 if the line is in the second file and a 0 if the line is missing from the second file. The first iteration returns a 1, because that line is in the second file, but for the remaning > 1,000 lines, they all return a 0 regardless of whether they are in the second list or not. It seems as though the second "for loop" only executes on the first iteration. Any ideas on why? Here is my code: import sys file1 = sys.argv[1] file2 = sys.argv[2] name = str(file2) f1 = open(file1, 'r') f2 = open(file1, 'r') o1 = open((name + '1.txt'), 'w') for line in f1: name = line.strip('\r\n') count = 0 for line1 in f2: if name == line1.strip('\r\n'): count += 1 print (str(name) + '\t' + str(1)) o1.write(str(name) + '\t' + str(1) + '\r\n') if count == 0: print (str(name) + '\t' + str(0)) o1.write(str(name) + '\t' + str(0) + '\r\n') f1.close() f2.close() o1.close() Any help is very much appreciated! After some changes, this is what I have and it only returns '1s' f1 = open(file1, 'r') #opens files for reading f2 = open(file2, 'r') o1 = open((name + '1.txt'), 'w') f2s = {line.strip('\n') for line in f2} for line in f1: line = line.strip('\n') count = 0 if line in f2s: count += 1 print (str(line) + '\t' + str(1)) o1.write(str(line) + '\t' + str(1) + '\n') if count == 0: print (str(line) + '\t' + str(0)) o1.write(str(line) + '\t' + str(0) + '\n') Embarrassing, I was opening the same file twice. Rookie. Answer: `f2` is an iterator over your second file, and when that has been read, it's exhausted. You _can_ reset the iterator `f2.seek(0, 0)`, but that's not really the best way to go. Better put all the values from `f2` into a `set` and then iterate over `f1` only once: f2s = {line.strip('\n') for line in f2} for line in f1: name = line.strip('\n') # No need for \r\n if name in f2s: # etc. If you need to count the number of occurences of each line from `f1` in `f2`, then you can use a [`Counter`](http://docs.python.org/2/library/collections.html#collections.Counter): from collections import Counter f2c = Counter(line.strip('\n') for line in f2) for line in f1: name = line.strip('\n') if name in f2c: count = f2c[name]
How do you format this in Python?These are just 6 records as Json objects Question: I need to format this string.These are just 6 records of JSON arrays/objects.I need to write a python code to remove all `" ,`. I want to see only real data in a single row. Can someone help me with the code?I have a deadline for this....Please help.. {"status": "ok", "items": [{"1": {"Work_Phone_Extension": null, "Residential_Postal_OR_Zip_Code": "", "Residential_Street_Address_line_2": "", "Residential_Street_Address_line_1": "", "Work_Phone": "", "Name_Part": ["PATIENT", "TEST"], "Residence_Phone": "416-", "Mailing_City": "Toronto", "Mailing_Postal_OR_Zip_Code": "", "Mailing_Street_Address_line_2": "", "Mailing_Street_Address_line_1": "", "Cell_Phone": null, "Residential_City": "Toronto", "Residential_Country_AND_Province_OR_State": "CA_ON", "Mailing_Country_AND_Province_OR_State": "CA_ON"}, "3": {"Work_Phone_Extension": null, "Residential_Postal_OR_Zip_Code": "", "Residential_Street_Address_line_2": "", "Residential_Street_Address_line_1": "", "Work_Phone": "", "Name_Part": ["WOLFIE", "HOWLETT"], "Residence_Phone": "416-", "Mailing_City": "Toronto", "Mailing_Postal_OR_Zip_Code": "", "Mailing_Street_Address_line_2": "", "Mailing_Street_Address_line_1": "", "Cell_Phone": null, "Residential_City": "Toronto", "Residential_Country_AND_Province_OR_State": "CA_ON", "Mailing_Country_AND_Province_OR_State": "CA_ON"}, "2": {"Work_Phone_Extension": null, "Residential_Postal_OR_Zip_Code": "", "Residential_Street_Address_line_2": "", "Residential_Street_Address_line_1": "18 Yonge St", "Work_Phone": "", "Name_Part": ["Steve", "TEST"], "Residence_Phone": "416-555-5555", "Mailing_City": "Toronto", "Mailing_Postal_OR_Zip_Code": "", "Mailing_Street_Address_line_2": "", "Mailing_Street_Address_line_1": "18 Yonge St", "Cell_Phone": null, "Residential_City": "Toronto", "Residential_Country_AND_Province_OR_State": "CA_ON", "Mailing_Country_AND_Province_OR_State": "CA_ON"}, "5": {"Work_Phone_Extension": null, "Residential_Postal_OR_Zip_Code": "", "Residential_Street_Address_line_2": "", "Residential_Street_Address_line_1": "", "Work_Phone": "", "Name_Part": ["BUTTERS", "STOTCH"], "Residence_Phone": "416-", "Mailing_City": "Toronto", "Mailing_Postal_OR_Zip_Code": "", "Mailing_Street_Address_line_2": "", "Mailing_Street_Address_line_1": "", "Cell_Phone": null, "Residential_City": "Toronto", "Residential_Country_AND_Province_OR_State": "CA_ON", "Mailing_Country_AND_Province_OR_State": "CA_ON"}, "4": {"Work_Phone_Extension": null, "Residential_Postal_OR_Zip_Code": "91041", "Residential_Street_Address_line_2": "", "Residential_Street_Address_line_1": "1 Manhattan Ave.", "Work_Phone": "", "Name_Part": ["SUE", "STORM"], "Residence_Phone": "416-555-5556", "Mailing_City": "Star City", "Mailing_Postal_OR_Zip_Code": "91041", "Mailing_Street_Address_line_2": "", "Mailing_Street_Address_line_1": "1 Manhattan Ave.", "Cell_Phone": null, "Residential_City": "Star City", "Residential_Country_AND_Province_OR_State": "CA_ON", "Mailing_Country_AND_Province_OR_State": "CA_ON"}, "6": {"Work_Phone_Extension": null, "Residential_Postal_OR_Zip_Code": "", "Residential_Street_Address_line_2": "", "Residential_Street_Address_line_1": "1 Rural Rd E", "Work_Phone": "", "Name_Part": ["CLARK", "KENT"], "Residence_Phone": "416-606-0001", "Mailing_City": "Smallville", "Mailing_Postal_OR_Zip_Code": "", "Mailing_Street_Address_line_2": "", "Mailing_Street_Address_line_1": "1 Rural Rd E", "Cell_Phone": null, "Residential_City": "Smallville", "Residential_Country_AND_Province_OR_State": "CA_ON", "Mailing_Country_AND_Province_OR_State": "CA_ON"}}]} Answer: import json l_dict = json.loads(long_string) You then have a dictionary and you can format it/iterate over it however you want. In [192]: l_dict Out[192]: {u'items': [{u'1': {u'Cell_Phone': None, u'Mailing_City': u'Toronto', u'Mailing_Country_AND_Province_OR_State': u'CA_ON', u'Mailing_Postal_OR_Zip_Code': u'', u'Mailing_Street_Address_line_1': u'', u'Mailing_Street_Address_line_2': u'', u'Name_Part': [u'PATIENT', u'TEST'], u'Residence_Phone': u'416-', u'Residential_City': u'Toronto', u'Residential_Country_AND_Province_OR_State': u'CA_ON', u'Residential_Postal_OR_Zip_Code': u'', u'Residential_Street_Address_line_1': u'', u'Residential_Street_Address_line_2': u'', u'Work_Phone': u'', u'Work_Phone_Extension': None}, u'2': {u'Cell_Phone': None, u'Mailing_City': u'Toronto', u'Mailing_Country_AND_Province_OR_State': u'CA_ON', u'Mailing_Postal_OR_Zip_Code': u'', u'Mailing_Street_Address_line_1': u'18 Yonge St', u'Mailing_Street_Address_line_2': u'', u'Name_Part': [u'Steve', u'TEST'], u'Residence_Phone': u'416-555-5555', u'Residential_City': u'Toronto', u'Residential_Country_AND_Province_OR_State': u'CA_ON', u'Residential_Postal_OR_Zip_Code': u'', u'Residential_Street_Address_line_1': u'18 Yonge St', u'Residential_Street_Address_line_2': u'', u'Work_Phone': u'', u'Work_Phone_Extension': None}, u'3': {u'Cell_Phone': None, u'Mailing_City': u'Toronto', u'Mailing_Country_AND_Province_OR_State': u'CA_ON', u'Mailing_Postal_OR_Zip_Code': u'', u'Mailing_Street_Address_line_1': u'', u'Mailing_Street_Address_line_2': u'', u'Name_Part': [u'WOLFIE', u'HOWLETT'], u'Residence_Phone': u'416-', u'Residential_City': u'Toronto', u'Residential_Country_AND_Province_OR_State': u'CA_ON', u'Residential_Postal_OR_Zip_Code': u'', u'Residential_Street_Address_line_1': u'', u'Residential_Street_Address_line_2': u'', u'Work_Phone': u'', u'Work_Phone_Extension': None}, u'4': {u'Cell_Phone': None, u'Mailing_City': u'Star City', u'Mailing_Country_AND_Province_OR_State': u'CA_ON', u'Mailing_Postal_OR_Zip_Code': u'91041', u'Mailing_Street_Address_line_1': u'1 Manhattan Ave.', u'Mailing_Street_Address_line_2': u'', u'Name_Part': [u'SUE', u'STORM'], u'Residence_Phone': u'416-555-5556', u'Residential_City': u'Star City', u'Residential_Country_AND_Province_OR_State': u'CA_ON', u'Residential_Postal_OR_Zip_Code': u'91041', u'Residential_Street_Address_line_1': u'1 Manhattan Ave.', u'Residential_Street_Address_line_2': u'', u'Work_Phone': u'', u'Work_Phone_Extension': None}, u'5': {u'Cell_Phone': None, u'Mailing_City': u'Toronto', u'Mailing_Country_AND_Province_OR_State': u'CA_ON', u'Mailing_Postal_OR_Zip_Code': u'', u'Mailing_Street_Address_line_1': u'', u'Mailing_Street_Address_line_2': u'', u'Name_Part': [u'BUTTERS', u'STOTCH'], u'Residence_Phone': u'416-', u'Residential_City': u'Toronto', u'Residential_Country_AND_Province_OR_State': u'CA_ON', u'Residential_Postal_OR_Zip_Code': u'', u'Residential_Street_Address_line_1': u'', u'Residential_Street_Address_line_2': u'', u'Work_Phone': u'', u'Work_Phone_Extension': None}, u'6': {u'Cell_Phone': None, u'Mailing_City': u'Smallville', u'Mailing_Country_AND_Province_OR_State': u'CA_ON', u'Mailing_Postal_OR_Zip_Code': u'', u'Mailing_Street_Address_line_1': u'1 Rural Rd E', u'Mailing_Street_Address_line_2': u'', u'Name_Part': [u'CLARK', u'KENT'], u'Residence_Phone': u'416-606-0001', u'Residential_City': u'Smallville', u'Residential_Country_AND_Province_OR_State': u'CA_ON', u'Residential_Postal_OR_Zip_Code': u'', u'Residential_Street_Address_line_1': u'1 Rural Rd E', u'Residential_Street_Address_line_2': u'', u'Work_Phone': u'', u'Work_Phone_Extension': None}}], u'status': u'ok'}
SEGUID from python to c++ Question: I'm trying to do this in C++, I have some code in Python but I can't figure how to make it work in C++ def seguid(seq): try: #Python 2.5 sha1 is in hashlib import hashlib m = hashlib.sha1() except: #For older versions import sha m = sha.new() import base64 try: #Assume its a Seq object seq = seq.tostring() except AttributeError: #Assume its a string pass m.update(_as_bytes(seq.upper())) try: #For Python 2.5+ return base64.b64encode(m.digest()).rstrip("=") except: #For older versions import os #Note: Using os.linesep doesn't work on Windows, #where os.linesep= "\r\n" but the encoded string #contains "\n" but not "\r\n" return base64.encodestring(m.digest()).replace("\n","").rstrip("=") Answer: i Think you may embed the python code into C/C++ code.Please refer the following link for more details. <http://www.codeproject.com/Articles/11805/Embedding-Python-in-C-C-Part-I> <http://www.linuxjournal.com/article/8497>
post request using python to asp.net page Question: i want scrap the PINCODEs from "<http://www.indiapost.gov.in/pin/>", i am doing with following code written. import urllib import urllib2 headers = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Origin': 'http://www.indiapost.gov.in', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'http://www.indiapost.gov.in/pin/', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'en-US,en;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' } viewstate = 'JulXDv576ZUXoVOwThQQj4bDuseXWDCZMP0tt+HYkdHOVPbx++G8yMISvTybsnQlNN76EX/...' eventvalidation = '8xJw9GG8LMh6A/b6/jOWr970cQCHEj95/6ezvXAqkQ/C1At06MdFIy7+iyzh7813e1/3Elx...' url = 'http://www.indiapost.gov.in/pin/' formData = ( ('__EVENTVALIDATION', eventvalidation), ('__EVENTTARGET',''), ('__EVENTARGUMENT',''), ('__VIEWSTATE', viewstate), ('__VIEWSTATEENCRYPTED',''), ('__EVENTVALIDATION', eventvalidation), ('txt_offname',''), ('ddl_dist','0'), ('txt_dist_on',''), ('ddl_state','2'), ('btn_state','Search'), ('txt_stateon',''), ('hdn_tabchoice','3') ) from urllib import FancyURLopener class MyOpener(FancyURLopener): version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17' myopener = MyOpener() encodedFields = urllib.urlencode(formData) f = myopener.open(url, encodedFields) print f.info() try: fout = open('tmp.txt', 'w') except: print('Could not open output file\n') fout.writelines(f.readlines()) fout.close() i am getting response from server as "Sorry this site has encountered a serious problem, please try reloading the page or contact webmaster." pl suggest where i am going wrong.. Answer: Where did you get the value `viewstate` and `eventvalidation`? On one hand, they shouldn't end with "...", you must have omitted something. On the other hand, they shouldn't be hard-coded. One solution is like this: 1. Retrieve the page via URL "<http://www.indiapost.gov.in/pin/>" without any form data 2. Parse and retrieve the form values like `__VIEWSTATE` and `__EVENTVALIDATION` (you may take use of [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)). 3. Get the search result(second HTTP request) by adding vital form-data from step 2. **UPDATE** : According to the above idea, I modify your code slightly to make it work: import urllib from bs4 import BeautifulSoup headers = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Origin': 'http://www.indiapost.gov.in', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'http://www.indiapost.gov.in/pin/', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'en-US,en;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' } class MyOpener(urllib.FancyURLopener): version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17' myopener = MyOpener() url = 'http://www.indiapost.gov.in/pin/' # first HTTP request without form data f = myopener.open(url) soup = BeautifulSoup(f) # parse and retrieve two vital form values viewstate = soup.select("#__VIEWSTATE")[0]['value'] eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value'] formData = ( ('__EVENTVALIDATION', eventvalidation), ('__VIEWSTATE', viewstate), ('__VIEWSTATEENCRYPTED',''), ('txt_offname', ''), ('ddl_dist', '0'), ('txt_dist_on', ''), ('ddl_state','1'), ('btn_state', 'Search'), ('txt_stateon', ''), ('hdn_tabchoice', '1'), ('search_on', 'Search'), ) encodedFields = urllib.urlencode(formData) # second HTTP request with form data f = myopener.open(url, encodedFields) try: # actually we'd better use BeautifulSoup once again to # retrieve results(instead of writing out the whole HTML file) # Besides, since the result is split into multipages, # we need send more HTTP requests fout = open('tmp.html', 'w') except: print('Could not open output file\n') fout.writelines(f.readlines()) fout.close()
Python Different the datetime in a Struct Array Question: import struct from collections import namedtuple StructDeviceInfo = namedtuple('DeviceInfo', ['DeviceID', 'Capturing','Receiving','Socket','DateTime']) DeviceInfoList = [] def threaded_function(): while True: if any(x.Capturing == True and x.Datetime in DeviceInfoList different second > 5 for x in DeviceInfoList) : #here,how to do on here? print('True') if the DeviceInfoList array inside the Capturing Value is TRUE and at the same time the Datetime are different with datetime.now are more than 5 second. then print true,how to do this? p/s:the Capturing is TRUE and datetime is more than 5 seconds,must be same array index . Answer: delta = datetime.datetime.now() - x.Datetime if delta.total_seconds() > 5: # difference is greater than 5 seconds Applied to your example, assuming that `x.Datetime` actually is a `datetime.datetime` object: if any(( x.Capturing == True and (datetime.datetime.now() - x.Datetime).total_seconds() > 5 ) for x in DeviceInfoList):
Generate a set of sorted random numbers from a specific range Question: I'd like to generate a set of x unique random numbers and sort them in Python. For example: range(1000, 10000) x = 100 I've figured out to import random and use the random.randrange method, then loop to get 100 random numbers and in the end sort them. However, I don't know how to get unique numbers (such that they do not repeat) - should I validate each and every loop? Or is there any other easier way how to do it? And how should I sort them? Thanks y'all! Answer: Use [`random.sample`](http://docs.python.org/3/library/random.html#random.sample) numbers = random.sample(xrange(1000, 10000), 100) # or `range` in Python 3 The sorting part is easy - use the [`list.sort`](http://docs.python.org/3/library/stdtypes.html#list.sort) method. numbers.sort() By default this will sort it from smallest number to largest, but it takes an optional `key` argument which determines what to sort it on. There is also a [`sorted`](http://docs.python.org/3/library/functions.html#sorted) function which doesn't modify a list in-place, but rather returns a sorted list. numbers_sorted = sorted(numbers) This also has an optional `key` argument.
gevent.http.HTTPServer API suggests streaming, but instead buffers entire requests and responses Question: The APIs offered by `gevent.http.HTTPServer` would seem to support streaming in both directions. The request object does not offer the request body as a simple string, but instead provides an `.input_buffer` attribute that is a Python iterable, while in the other direction the data for a response can be delivered as chunks with the three calls: request.send_reply_start(200, 'OK') request.send_reply_chunk(...) # as many times as you wish request.send_reply_end() But I must have something mis-configured, because despite this wonderfully unbuffered API, my request handler is not getting called until the _last_ chunk of request POST data has finally arrived, and in the other direction I am not seeing _any_ headers arrive on my client socket until the server reaches `.send_reply_end()`. Is there some switch that I have to throw or some configuration setting that I have to manipulate in order to turn off buffering and see requests and send responses as they arrive, like gevent supports with raw sockets through its `StreamServer`? My application needs to supports single-file uploads and downloads that may be bigger than RAM, which will require this buffering to be turned off. Here are a simple server and client written with gevent that should show you this behavior: # srv.py import gevent.http M100 = 100 * 1024 * 1024 def main(): print 'Serving on 8088...' gevent.http.HTTPServer(('0.0.0.0', 8088), handle).serve_forever() def handle(request): print 'Is request chunked?', request.chunked for item in request.input_buffer: print 'received body segment of length', len(item), 'bytes' request.add_output_header('Content-Type', 'application/octet-stream') request.send_reply_start(200, 'OK') for i in range(5): print 'sending chunk', i request.send_reply_chunk(M100 * 'x') request.send_reply_end() if __name__ == '__main__': main() And: # cli.py import requests import time M100 = 100 * 1024 * 1024 def gen(): for i in range(5): print 'sending chunk', i yield M100 * 'x' time.sleep(1) if __name__ == '__main__': r = requests.post('http://localhost:8088/', data=gen(), stream=True) for block in r.iter_content(M100): print 'received', len(block), 'bytes from download' Thanks for any guidance! Answer: **Requests to the server:** Looking at the source code, it looks like the server's handler function is not called until the request is complete, regardless of whether or not it is sent in a chunked fashion. So you're out of luck there. **Server responses:** The server response can be sent in a streaming fashion, but you need to voluntarily yield control in the handler thread for this to work (e.g. by calling `gevent.sleep()` after each chunk). Unfortunately, `gevent` does not seem to provide a way to wait for a given chunk to finish sending before starting on the next chunk, so if you generate data faster than it can be sent you may run into memory issues. * * * Note that the above information refers to `gevent<1.0`, which uses the `libevent` library, and is not applicable to more recent versions of `gevent`. The current version of `gevent` no longer includes an `http` module so the question is moot.
Unpacking iterable into other iterable? Question: While reading data from a ASCII file, I find myself doing something like this: (a, b, c1, c2, c3, d, e, f1, f2) = (float(x) for x in line.strip().split()) c = (c1, c2, c3) f = (f1, f2) If I have a determinate number of elements per line (which I do)¹ and only one multi-element entry to unpack, I can use something like `(a, b, *c, d, e) = ...' ([Extended iterable unpacking](http://www.python.org/dev/peps/pep-3132/)). Even if I don't, I can of course replace _one_ of the two multi-element entries from the example above by a starred component: `(a, b, *c, d, e, f1, f2) = ...`. As far as I can tell, the `itertools` are not of immediate use here. Are there any alternatives to the three-line code above that may be considered "more pythonic" for a reason I'm probably not aware of? ¹It's determinate but still varies per line, the pattern is too complicated for `numpy`s functions `loadtxt` or `genfromtxt`. Answer: If you use such statements really often, and want maximum flexibility and reusability of code instead of writing such patterns really often, I'd propose creating a small function for it. Just put it into some module and import it (you can even import the script I created). For usage examples, see the `if __name__=="__main__"` block. The trick is to use a list of group ids to group values of `t` together. The length of this id list should be at least the same as the length of `t`. I will only explain the main concepts, if you don't understand anything, just ask. I use `groupby` from itertools. Even though it might not be straightforward how to use it here, I hope it might be understandable soon. As `key`-function I use a method I dynamically create via a factory-function. The main concept here is "closures". The list of group ids is being "attached" to the internal function `get_group`. Thus: * The list is specific to each call to `extract_groups_from_iterable`. You can use it multiple times, no globals are used * The state of this list is shared between subsequent calls to the same instance of `get_group` (remember: functions are objects, too! So I have two instances of `get_group` during the execution of my script. Beside of this, I have a simple method to create either lists or scalars from the groups returned by `groupby`. That's it. from itertools import groupby def extract_groups_from_iterable(iterable, group_ids): return [_make_list_or_scalar(g) for k, g in groupby(iterable, _get_group_id_provider(group_ids)) ] def _get_group_id_provider(group_ids): def get_group(value, group_ids = group_ids): return group_ids.pop(0) return get_group def _make_list_or_scalar(iterable): list_ = list(iterable) return list_ if len(list_) != 1 else list_[0] if __name__ == "__main__": t1 = range(9) group_ids1 = [1,2,3,4,5,5,6,7,8] a,b,c,d,e,f,g,h = extract_groups_from_iterable(t1, group_ids1) for varname in "abcdefgh": print varname, globals()[varname] print t2 = range(15) group_ids2 = [1,2,2,3,4,5,5,5,5,5,6,6,6,7,8] a,b,c,d,e,f,g,h = extract_groups_from_iterable(t2, group_ids2) for varname in "abcdefgh": print varname, globals()[varname] Output is: a 0 b 1 c 2 d 3 e [4, 5] f 6 g 7 h 8 a 0 b [1, 2] c 3 d 4 e [5, 6, 7, 8, 9] f [10, 11, 12] g 13 h 14 Once again, this might seem like overkill, but if this helps you reducing your code, use it.
Why are uncompiled, repeatedly used regexes so much slower in Python 3? Question: When answering [this question](http://stackoverflow.com/q/14755882/20670) (and having read [this answer](http://stackoverflow.com/a/452143/20670) to a similar question), I thought that I knew how Python caches regexes. But then I thought I'd test it, comparing two scenarios: 1. a single compilation of a simple regex, then 10 applications of that compiled regex. 2. 10 applications of an uncompiled regex (where I would have expected slightly worse performance because the regex would have to be compiled once, then cached, and then looked up in the cache 9 times). However, the results were staggering (in Python 3.3): >>> import timeit >>> timeit.timeit(setup="import re", ... stmt='r=re.compile(r"\w+")\nfor i in range(10):\n r.search(" jkdhf ")') 18.547793477671938 >>> timeit.timeit(setup="import re", ... stmt='for i in range(10):\n re.search(r"\w+"," jkdhf ")') 106.47892003890324 That's over 5.7 times slower! In Python 2.7, there is still an increase by a factor of 2.5, which is also more than I would have expected. Has caching of regexes changed between Python 2 and 3? [The docs](http://docs.python.org/dev/library/re.html#re.compile) don't seem to suggest that. Answer: The code _has_ changed. In Python 2.7, the cache is a simple dictionary; if more than `_MAXCACHE` items are stored in it, the whole the cache is cleared before storing a new item. A cache lookup only takes building a simple key and testing the dictionary, see the [2.7 implementation of `_compile()`](http://hg.python.org/cpython/file/2.7/Lib/re.py#l226) In Python 3.x, the cache has been replaced by the [`@functools.lru_cache(maxsize=500, typed=True)` decorator](http://docs.python.org/3/library/functools.html#functools.lru_cache). This decorator does _much_ more work and includes a thread-lock, adjusting the cache LRU queue and maintaining the cache statistics (accessible via `re._compile.cache_info()`). See the [3.3 implementation of `_compile()`](http://hg.python.org/cpython/file/3.3/Lib/re.py#l264) and of [`functools.lru_cache()`](http://hg.python.org/cpython/file/3.3/Lib/functools.py#l174). Others have noticed the same slowdown, and filed [issue 16389](http://bugs.python.org/issue16389) in the Python bugtracker. I'd expect 3.4 to be a lot faster again; either the `lru_cache` implementation is improved or the `re` module will move to a custom cache again. Update: With [revision 4b4dddd670d0](http://hg.python.org/cpython/rev/4b4dddd670d0) the cache change has been reverted back to the simple version found in 3.1. Python versions 3.2.4 and 3.3.1 include that revision.
Connect MySQl with Python Error : function 'inet_pton' not found Question: import mysql.connector cnx = mysql.connector.connect(user=user, password=password,host=host,database=database) cursor = cnx.cursor() add_employee = ("INSERT INTO tbl_gps " "(Locating, MainPower, Acc, PowerOff, Alarm,Speed,Direction,Latitude,Longitude,DateTime,IOState,OilState,MainID) " "VALUES (%s, %s, %s, %s, %s,% s, %s, %s, %s, %s, %s, %s, (SELECT MainID From tbl_device WHERE DeviceID = %s))") data_employee = { 'Locating': 1, 'MainPower': 1, 'Acc': 1, 'PowerOff': 1, 'Alarm': 0x80, 'Speed': 1, 'Direction': 300, 'Latitude': 10.00, 'Longtitude': -20.00, 'DateTime': '2013/2/8 01:00:00', 'IOState': 0, 'OilState': 0, 'MainID': 'NR09533' } cursor.execute(add_employee, data_employee) cnx.close() when i debug get the following error: AttributeError: function 'inet_pton' not found what wrong with my code?please help to fix it,thanks you very much ! the connector are downlaoded from Mysql official web site, and i m using Python 3.3 i have found this in google, this is a Mysql Bug?because i m using Window XP. <http://bugs.mysql.com/bug.php?id=68065> Answer: Problem Solved after i download the Connector from <http://pypi.python.org/pypi/mysql-connector-python>, the mysql official web's connector can't use
I'm looking for tutorial in web-crawlers Question: I need to learn more about web-crawlers for a personal project of mine, and I'd like to have some questions answered: 1) By what I've heard, it seems like Google uses python for his web-crawlers, is that right? 2) Following that question, would you say that it is a good choice? Is Python the most suited language for that kind of things? Why? 3) What's legal to do with web-crawlers, and what is not? I've heard that many website won't really appreciate that you download too many of their pages, but isn't that exactly what Google do? It seems like a big grey area and I'd like to know how I can make sure what I do is legal... 4) If you have any good tutorial on how to make web-crawlers (the programming language isn't important), I would really appreciate a link to it! Thank you, and sorry for mistakes, english isn't my native language... Answer: > 1) By what I've heard, it seems like Google uses python for his web- > crawlers, is that right? An early version of Google used Python for the webcrawler. This is indicated in early publications dating back to the 90s (see [Anatomy of a Search Engine](http://infolab.stanford.edu/~backrub/google.html).) Only a Google employee can tell you whether they still use Python today for their crawler. > 2) Following that question, would you say that it is a good choice? Is > Python the most suited language for that kind of things? Why? There is no way to answer this objectively. It's almost equivalent to asking "is Python a good language?" Pros of using Python for a webcrawler include the various web and networking libraries, parsers, etc. which are readily available in Python, as well as the fact that Python's performance drawbacks aren't likely to matter much for most webcrawlers, since a webcrawler typically spends all of it's time waiting for URLs to resolve and download. > 3) What's legal to do with web-crawlers, and what is not? I've heard that > many website won't really appreciate that you download too many of their > pages, but isn't that exactly what Google do? It seems like a big grey area > and I'd like to know how I can make sure what I do is legal... It's not a question of legality so much as it is a question of politeness. If you bombard a webserver with too many requests at once, it's likely to ban your IP. Commercial webcrawlers such as GoogleBot generally use crawl-wait times, so that there is a delay between requests to the same host. A well- behaved webcrawler also must obey the [Robots Exclusion Protocol](http://en.wikipedia.org/wiki/Robots_exclusion_protocol). > 4) If you have any good tutorial on how to make web-crawlers (the > programming language isn't important), I would really appreciate a link to > it! Conceptually, a webcrawler is just a FIFO queue of URLs. You choose a starting URL, place it at the top of the queue, pop and download the URL, parse the HTML and extract the links, and then add each link to the queue. Then pop the top URL and repeat ad infinitum or until some stopping condition occurs. However, in practice, a robust webcrawler is much more complicated to write because you need to account for many, many issues, such as avoiding downloading duplicate URLs, implementing crawl-wait times for each host, obeying the Robots Exclusion Protocol, avoiding [crawler traps](http://en.wikipedia.org/wiki/Spider_trap), etc. You also probably need to include logic for some kind of decent crawl strategy so your crawler doesn't spend most of it's time downloading useless garbage, as the signal-to- noise ratio of the modern World Wide Web is pretty abysmal.
Python multiple file transfer over TCP sockets Question: I am trying to write a program in python to transfer multiple files in a folder over a socket, I have the following code so far Client: def uploadFiles(folder,dcip,PORT,filetype): os.chdir(folder) dirList = os.listdir(folder) print dirList ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print PORT ms.connect((dcip, int(PORT))) for fname in dirList: if fname.endswith(str(filetype)): cmd = 'get\n%s\n' % (fname) ms.sendall(cmd) f = open(fname,'rb') data = f.read() f.close() print data r = ms.recv(2) ms.sendall(data) ms.sendall('done\n%s\n' %(fname)) ms.sendall('end\n\n') ms.close() Server: import socket,os listener_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener_socket.bind(('',33234)) filename = '' while 1: listener_socket.listen(100) connection,address_client = listener_socket.accept() if not os.path.exists(str(address_client[0])): os.makedirs(str(address_client[0])) currdir = os.getcwd() os.chdir('./'+str(address_client[0])) while(1): data = connection.recv(4096) cmd = data[:data.find('\n')] if cmd == 'get': x,filename,x = data.split('\n',2) connection.sendall('ok') f = open(filename,'wb') if cmd == 'done': continue f.write(data) if cmd == 'end': connection.close() break os.chdir(currdir) The above code goes into an infinite loop, which I do understand that it is because of the continue statement in the `if cmd == 'done'` part, I wonder why it is doing that? I mean it never gets the done message from the client, can anyone please help me fix the code? Answer: Because commands and filenames are in separate lines, it is best to parse received data by lines. Last part of block data doesn't have to finish with a `\n`, so it has to be merged with next received data block. This is (not tested) implementation of parsing received data by lines: data = '' # contains last line of a read block if it didn't finish with \n in_get, in_done, reading_file, ended = False, False, False, False while not ended: if len(data) > 100: # < update f.write( data ) # < data = '' # < data += connection.recv(4096) i = data.find('\n') while i >= 0 and not ended: line = data[:i] data = data[i+1:] if in_get: filename = line reading_file = True f = open(filename,'wb') in_get = False elif in_done: if line != filename: # done inside file content f.write( 'done\n' + line + '\n' ) else: f.close() reading_file = False in_done = False else: if line == 'get' and not reading_file: in_get = True elif line == 'done': in_done = True elif line == 'end' and not reading_file: ended = True break; else: f.write( line + '\n' ) i = data.find('\n')
Can't get a sensible result with libreplaygain.so and numpy Question: I've been trying over and over again to use `libreplaygain.so` (`ReplayGain` is an algorithm for calculating loudness of audio. ) from python, passing it data from an audio file. Here is [the header file](http://sourcecodebrowser.com/libreplaygain/1.0~r412/gain__analysis_8h_source.html) of libreplaygain. I don't understand much about `ctypes` nor C in general, so I'm hoping it could be a problem of me being stupid, and very obvious for somebody else! Here is the script I am using : import numpy as np from scipy.io import wavfile import ctypes replaygain = ctypes.CDLL('libreplaygain.so') def calculate_replaygain(samples, frame_rate=44100): """ inspired from https://github.com/vontrapp/replaygain """ replaygain.gain_init_analysis(frame_rate) block_size = 10000 channel_count = samples.shape[1] i = 0 samples = samples.astype(np.float64) while i * block_size < samples.shape[0]: channel_left = samples[i*block_size:(i+1)*block_size,0] channel_right = samples[i*block_size:(i+1)*block_size,1] samples_p_left = channel_left.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) samples_p_right = channel_right.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) replaygain.gain_analyze_samples(samples_p_left, samples_p_right, channel_left.shape[0], channel_count) i += 1 return replaygain.gain_get_chapter() if __name__ == '__main__': frame_rate, samples = wavfile.read('directions.wav') samples = samples.astype(np.float64) / 2**15 gain = calculate_replaygain(samples, frame_rate=frame_rate) print "Recommended gain: %f dB" % gain gain = calculate_replaygain(np.random.random((441000, 2)) * 2 - 1, frame_rate=44100) print "Recommended gain: %f dB" % gain The script runs, but I cannot get the same value as with the command line tool `replaygain`. In fact I always get `80.0`. To try you can replace 'directions.wav' with any sound file ... and compare the result with the result of the command `replaygain <soundfile.wav>`. Answer: `gain_get_chapter()` returns a `double`, but [the ctypes docs say](http://docs.python.org/2/library/ctypes.html#return-types) "By default functions are assumed to return the C int type." You should do something like replaygain.gain_get_chapter.restype = ctypes.c_double You should also check the return values of `gain_init_analysis` and `gain_analyze_samples`; if those aren't both 1, something else is going wrong. (Those actually are ints, so you shouldn't have to do anything else there.)
Feasibility of using pipe for ruby-python communication Question: Currently, I have two programs, one running on Ruby and the other in Python. I need to read a file in Ruby but I need first a library written in Python to parse the file. Currently, I use XMLRPC to have the two programs communicate. Porting the Python library to Ruby is out of question. However, I find and read that using XMLRPC has some performance overhead. Recently, I read that another solution for the Ruby-Python conundrum is the use of pipes. So I tried to experiment on that one. For example, I wrote this master script in ruby: (0..2).each do slave = IO.popen(['python','slave.py'],mode='r+') slave.write "master" slave.close_write line = slave.readline while line do sleep 1 p eval line break if slave.eof line = slave.readline end end The following is the Python slave: import sys cmd = sys.stdin.read() while cmd: x = cmd for i in range(0,5): print "{'%i'=>'%s'}" % (i, x) sys.stdout.flush() cmd = sys.stdin.read() Everything seems to work fine: ~$ ruby master.rb {"0"=>"master"} {"1"=>"master"} {"2"=>"master"} {"3"=>"master"} {"4"=>"master"} {"0"=>"master"} {"1"=>"master"} {"2"=>"master"} {"3"=>"master"} {"4"=>"master"} {"0"=>"master"} {"1"=>"master"} {"2"=>"master"} {"3"=>"master"} {"4"=>"master"} My question is, is it really feasible to implement the use of pipes for working with objects between Ruby and Python? One consideration is that there may be multiple instances of master.rb running. Will concurrency be an issue? Can pipes handle extensive operations and objects to be passed in between? If so, would it be a better alternative for RPC? Answer: Yes. No. If you implement it, yes. Depends on what your application needs. Basically if all you need is simple data passing pipes are fine, if you need to be constantly calling functions on objects in your remote process then you'll probably be better of using some form of existing RPC instead of reinventing the wheel. Whether that should be XMLRPC or something else is another matter. Note that RPC will have to use some underlying IPC mechanism, which could well be pipes. but might also be sockets, message queues, shared memory, whatever.
How to define list of int and defaultdict Question: I want to define a list of an integer and defaultdict in python. I am creating a parent dictionary which shall return the above list. I am being unable to define the list type. def index_struct():return defaultdict(list_struct) def list_struct(): return list(int,post_struct) def post_struct(): return defaultdict(list) Currently getting an error as list cant take two args.. Thanks for the help in advance Answer: You're right that _list()_ only takes one argument. Use the square brackets notation instead. Also note the `[int, post_struct]` won't work because nothing is calling the two constructors. You need to call the constructors manually by adding parentheses: from collections import defaultdict def index_struct():return defaultdict(list_struct) def list_struct(): return [int(), post_struct()] def post_struct(): return defaultdict(list) >>> d = index_struct() >>> d['somekey'][0] = 5 >>> d['somekey'][1]['anotherkey'] = 6 >>> d defaultdict(<function list_struct at 0x10252ff50>, {'somekey': [5, defaultdict(<type 'list'>, {'anotherkey': 6})]})
Sobel operator - Open Cv Python Question: Img is my input image which is in RGB import cv2 import numpy as np img = cv2.imread("Lenna.png") black = cv2.cvtColor(img , cv2.cv.CV_BGR2GRAY) Now I would want to apply a sobel operator to it using filter2D sobel = np.array([[-1 , 0 , 1] , [-2 , 0 , 2] , [-1 , 0 , 1] ]) dest = cv2.filter2D(black , -1 , sobel) The -1 parameter according to the docs is the depth of the image which is I believe is 'uint8' or cv2.cv.CV_8U , and when I do np.max(dest) it gives me 255 , which is expected. However when I specify my depth as cv2.cv.CV_32F , i.e dest = cv2.filter2D(black , cv2.cv.CV_32F , sobel) and do np.max(dest) , it gives me a different value greater than 255. Could someone explain the reason? Answer: The function `filter2D` performs image filtering in full precision and then saturates the resulting values to the destination data type. Actually, the output image contains a larger range of values. When you specify the type `CV_32F` the output values are kept as is. They may contain values larger than 255 and less than 0. But when the type is `CV_8U`, the results are clamped to the range of `CV_8U` data type. All the negative values become 0 and all the values larger than 255, will become 255.
python ctypes pragma pack for byte aligned read Question: I have a C++ application with below structure written to file. Now I need to unmarshal them using python, The basic problem here is how to reflect the `pragma pack` option in python. C++ Structure #pragma pack(1) struct abc { unsigned char r1; unsigned char r2; unsigned char p1; unsigned int id; }; #pragma pack() Now, the structure size is `7 not 8`,this data is written into a data file. How do I retrieve this data using python. Note : 1\. I am using ctypes, and the above structure is a sample structure. * * * _ctypes uses the native byte order for Structures and Unions. To build structures with non-native byte order, you can use one of the BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion base classes. These classes cannot contain pointer fields_ * * * The above information from python docs, does not delve into details. Answer: You can change the packing in ctypes as described [here](http://docs.python.org/2/library/ctypes.html#structure-union-alignment- and-byte-order) > By default, Structure and Union fields are aligned in the same way the C > compiler does it. It is possible to override this behavior be specifying a > _pack_ class attribute in the subclass definition. This must be set to a > positive integer and specifies the maximum alignment for the fields. This is > what #pragma pack(n) also does in MSVC. For your example this would be: from ctypes import * class abc(Structure): _pack_ = 1 _fields_ = [ ('r1',c_ubyte), ('r2',c_ubyte), ('p1',c_ubyte), ('id',c_uint)]
How do I make the program wait for an input using an Entry box in Python GUI? Question: This is the code for the function I'm using to start the main part of the program, however I want some sort of loop or something which creates ten questions, but waits for an input from the Entry box before moving onto the next question. Any ideas? def StartGame(): root = Tk() root.title("Maths Quiz - Trigonometry and Pythagoras' Theorem | Start The Game") root.geometry("640x480") root.configure(background = "gray92") global AnswerEntry TotScore = 0 Count = 0 AnswerReply = None WorkingArea = Text(root, width = 70, height = 10, wrap = WORD).place(x = 38, y = 100) n = GetRandomNumber() Angle,Opposite,Adjacent,Hypotenuse = Triangle() Question,RealAnswer = QuestionLibrary(Opposite,Adjacent,Hypotenuse,Angle,n) AskQuestion = Label(root, text = Question, wraplength = 560).place(x = 48, y = 300) PauseButton = ttk.Button(root, text = "Pause").place(x = 380, y = 10) HelpButton = ttk.Button(root, text = "Help", command = helpbutton_click).place(x = 460, y = 10) QuitButton = ttk.Button(root, text = "Quit", command = root.destroy).place(x = 540, y = 10) AnswerEntry = Entry(root) AnswerEntry.place(x = 252, y = 375) SubmitButton = ttk.Button(root, text = "Submit", command = submit_answer).place(x = 276, y = 400) TotScore,AnswerReply = IsAnswerCorrect(Answer,RealAnswer) ScoreLabel = ttk.Label(root, text = TotScore).place(x = 38, y = 10) AnswerReplyLabel = ttk.Label(root, text = AnswerReply).place(x = 295, y = 440) root.mainloop() I want the loop to start after the `AnswerReply = None` Answer: You don't want a loop. The only really important loop inside a GUI should be the `mainloop()`, handling **signal** and executing **callbacks**. Example: try: import Tkinter as Tk except ImportError: import tkinter as Tk class QAGame(Tk.Tk): def __init__(self, questions, answers, *args, **kwargs): Tk.Tk.__init__(self, *args, **kwargs) self.title("Questions and answers game") self._setup_gui() self._questions = questions[:] self._answers = answers self._show_next_question() def _setup_gui(self): self._label_value = Tk.StringVar() self._label = Tk.Label(textvariable=self._label_value) self._label.pack() self._entry_value = Tk.StringVar() self._entry = Tk.Entry(textvariable=self._entry_value) self._entry.pack() self._button = Tk.Button(text="Next", command=self._move_next) self._button.pack() def _show_next_question(self): q = self._questions.pop(0) self._label_value.set(str(q)) def _move_next(self): self._read_answer() if len(self._questions) > 0: self._show_next_question() self._entry_value.set("") else: self.quit() self.destroy() def _read_answer(self): answer = self._entry_value.get() self._answers.append(answer) def _button_classification_callback(self, args, class_idx): self._classification_callback(args, self._classes[class_idx]) self.classify_next_plot() if __name__ == "__main__": questions = ["How old are you?", "What is your name?"] answers = [] root = QAGame(questions, answers) root.mainloop() for q,a in zip(questions, answers): print "%s\n>>> %s" % (q, a) We only have a Label, an Entry and a Button (I did not care about layout!, just `pack()`). Attached to the button is a command (aka callback). When the button is pressed, the answer is read and the new question is assigned to the label. Usage of this class is understandable from the example in the `if **name** == "**main** " block. Please note: the answers-list is filled in place, the questions-list is kept unchanged.
Python json.loads doesn't work Question: I've been trying to figure out how to load JSON objects in Python. def do_POST(self): length = int(self.headers['Content-Length']) decData = str(self.rfile.read(length)) print decData, type(decData) "{'name' : 'journal2'}" <type 'str'> postData = json.loads(decData) print postData, type(postData) #{'name' : 'journal2'} <type 'unicode'> postData = json.loads(postData) print postData, type(postData) # Error: Expecting property name enclosed in double quotes Where am I going wrong? **Error Code (JScript):** var data = "{'name':'journal2'}"; var http_request = new XMLHttpRequest(); http_request.open( "post", url, true ); http_request.setRequestHeader('Content-Type', 'application/json'); http_request.send(data); **True Code (JScript):** var data = '{"name":"journal2"}'; var http_request = new XMLHttpRequest(); http_request.open( "post", url, true ); http_request.setRequestHeader('Content-Type', 'application/json'); http_request.send(JSON.stringify(data)); **True Code (Python):** def do_POST(self): length = int(self.headers['Content-Length']) decData = self.rfile.read(length) postData = json.loads(decData) postData = json.loads(postData) Answer: Your JSON data is enclosed in extra quotes making it a JSON string, _and_ the data contained within that string is _not_ JSON. Print `repr(decData)` instead, you'll get: '"{\'name\' : \'journal2\'}"' and the JSON library is correctly interpreting that as one string with the literal contents `{'name' : 'journal2'}`. If you stripped the outer quotes, the contained characters are not valid JSON, because JSON strings must always be enclosed in double quotes. For all the `json` module is concerned, `decData` could just as well have contained `"This is not JSON"` and `postData` would have been set to `u'This is not JSON'`. >>> import json >>> decData = '''"{'name' : 'journal2'}"''' >>> json.loads(decData) u"{'name' : 'journal2'}" >>> json.loads(json.loads(decData)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads return _default_decoder.decode(s) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 1 (char 1) Fix whatever is producing this string, your view is fine, it's the input that is broken.
How to split a pdf document containing multiple logical pages on each sheet? Question: I want to split a 2x2 pdf document into its original pages. Each page consists of four logical pages which are arranged like in [this](http://rainnic.altervista.org/sites/default/files/styles/large/public/images/4_slide_orizzontali_2.jpg) example. I'm trying to use `python` and `pypdf`: import copy, sys from pyPdf import PdfFileWriter, PdfFileReader def ifel(condition, trueVal, falseVal): if condition: return trueVal else: return falseVal input = PdfFileReader(file(sys.argv[1], "rb")) output = PdfFileWriter() for p in [input.getPage(i) for i in range(0,input.getNumPages())]: (w, h) = p.mediaBox.upperRight for j in range(0,4): t = copy.copy(p) t.mediaBox.lowerLeft = (ifel(j%2==1, w/2, 0), ifel(j<2, h/2, 0)) t.mediaBox.upperRight = (ifel(j%2==0, w/2, w), ifel(j>1, h/2, h)) output.addPage(t) output.write(file("out.pdf", "wb")) Unfortunately, this script does not work as intended because it outputs every fourth logical page four times. As I haven't written anything in python before, I think it's a very basic problem, presumably due to the copy operation. I would really appreciate any help. * * * **Edit** : Well, I have done some experiments. I inserted the page width and height manually like in the following: import copy, sys from pyPdf import PdfFileWriter, PdfFileReader def ifel(condition, trueVal, falseVal): if condition: return trueVal else: return falseVal input = PdfFileReader(file(sys.argv[1], "rb")) output = PdfFileWriter() for p in [input.getPage(i) for i in range(0,input.getNumPages())]: (w, h) = p.mediaBox.upperRight for j in range(0,4): t = copy.copy(p) t.mediaBox.lowerLeft = (ifel(j%2==1, 841/2, 0), ifel(j<2, 595/2, 0)) t.mediaBox.upperRight = (ifel(j%2==0, 841/2, 841), ifel(j>1, 595/2, 595)) output.addPage(t) output.write(file("out.pdf", "wb")) This code leads to the same **wrong** result as my original one, **but** if I now comment out the line `(w, h) = p.mediaBox.upperRight`, everything works! I can't find any reason for this. The tuple `(w, h)` is not even used anymore, so how can removing its definition change anything? Answer: I suspect that the problem is that the mediaBox is only a magic accessor for a variable is shared across p and all copies t. Therefore, assignments to `t.mediaBox` will result in the mediaBox having the same coordinates in all four copies. The variable behind the mediaBox field is lazily created on the first access to mediaBox, so if you comment out the line `(w, h) = p.mediaBox.upperRight`, the mediaBox variables will be created separately for each t . Two possible solutions for automatically determining the page dimensions: 1. Get the dimensions after making the copy: for p in [input.getPage(i) for i in range(0,input.getNumPages())]: for j in range(0,4): t = copy.copy(p) (w, h) = t.mediaBox.upperRight t.mediaBox.lowerLeft = (ifel(j%2==1, w/2, 0), ifel(j<2, h/2, 0)) t.mediaBox.upperRight = (ifel(j%2==0, w/2, w), ifel(j>1, h/2, h)) output.addPage(t) 2. Instantiate fresh RectangleObjects to use for mediaBox variables for p in [input.getPage(i) for i in range(0,input.getNumPages())]: (w, h) = p.mediaBox.upperRight for j in range(0,4): t = copy.copy(p) t.mediaBox.lowerLeft = pyPdf.generic.RectangleObject( ifel(j%2==1, w/2, 0), ifel(j<2, h/2, 0), ifel(j%2==0, w/2, w), ifel(j>1, h/2, h)) output.addPage(t) Using `copy.deepcopy()` will cause memory issues for large, complex PDFs,
Python - Splitting List That Contains Strings and Integers Question: myList = [ 4,'a', 'b', 'c', 1 'd', 3] how to split this list into two list that one contains strings and other contains integers in _elegant/pythonic_ way? output: myStrList = [ 'a', 'b', 'c', 'd' ] myIntList = [ 4, 1, 3 ] NOTE: didn't implemented such a list, just thought about how to find an elegant answer (is there any?) to such a problem. Answer: As others have mentioned in the comments, you should really start thinking about how you can get rid of the list which holds in-homogeneous data in the first place. However, if that really _can't_ be done, I'd use a defaultdict: from collections import defaultdict d = defaultdict(list) for x in myList: d[type(x)].append(x) print d[int] print d[str]
ipython %run testscript_in_pythonpath.py returns "no file found" error Question: I would like to use the %run magic command to run a script in a directory which is in the pythonpath variable. The script reads some files in the working directory. However, when I try to run the script using the command: %run "testscript_in_pythonpath.py ", it returns an error. I thought files in pythonpath would be accessible to the interpreter, no ?? Answer: (Reposting as an answer) `$PYTHONPATH` is what Python uses to look up modules to import, not scripts to run. To run a file from `$PYTHONPATH`, you can do `import testscript_in_pythonpath`. Or, in IPython: %run -m testscript_in_pythonpath The difference is that if the file has an `if __name__ == '__main__':` section, `%run` will trigger that. From a system shell, you can do the same thing as: python -m testscript_in_pythonpath
General map operation in C Question: how can i define a general map operation on an array in C? ideally I want something like python's map(function,array) ~~ but as a macro. I believe this would be something like C++'s std::transform, but would be in C, and not use iterators.. (this would be unary operation) I was thinking something like: template <class T*, class U*,size_t N> T* map(T (*func)(U), U* arr,size_t N) { T* tmp = (T*)malloc(sizeof(T) * N); size_t i; for(i=0;i<N;i++) { *(tmp+i) = *func(*(arr+i)); } } ... but of course templates are in C++.. so how can I 1) do the latter and 2) if you could, could you fix the above code snippet. Thanks Answer: For a template like this, there is a fairly straightforward translation to macros; the major syntactic wrinkle is that you can't return the result array, the variable to write it to has to be another parameter. #define map(func_, input_, output_, type_, n_) do { \ output_ = xmalloc(sizeof(type_) * (n_)); \ size_t i_; \ for (i_ = 0; i_ < (n_); i_++) \ output_[i_] = func_(input_[i_]); \ } while (0) This is not as type-unsafe as it looks, provided you pay attention to your compiler warnings. However, it is _not_ particularly safe if any of the actual arguments to a use of this macro isn't a simple identifier. Most importantly, _catastrophic_ things will happen if any of the actual arguments has side effects. This can be cured, as can the inability to return the result array, but only if you're willing to use GNU extensions... #define gnumap(func_, input_, type_, n_) ({ \ __typeof(func_) func__ = (func_); \ __typeof(input_) input__ = (input_), \ output__ = xmalloc(sizeof(type_) * n__); \ __typeof(n_) n__ = (n_), \ i__; \ for (i__ = 0; i__ < n__; i__++) \ output__[i__] = func__(input__[i__]); \ /* return */ output__; \ }) Would I do either of these in real life? Probably not, but sometimes it really is the least bad available option. Think of it as one step shy of rewriting that critical inner loop in assembly language. (`xmalloc`, in case you're unfamiliar with it, is the conventional name for a user-written wrapper around `malloc` that either succeeds or crashes the entire program. I use it here to dodge the question of how to cope with `malloc` failing.)
IndentationError message Django Question: I am working with Django 1.4.2 and I got the following error message: ![enter image description here](http://i.stack.imgur.com/dQzCG.png) Can someone tell me which files are having the indent problem? I tried `python -m tabnanny -v manage.py` and I got "Clean bill of health" so I think that file is alright. And I have never touched the other 2 files before. I am working with Python 2.7.2 and Django 1.4.2 on Vista. Here's the entire importlibs.py: def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level " "package") return "%s.%s" % (package[:dot], name) def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") level = 0 for character in name: if character != '.': break level += 1 name = _resolve_name(name[level:], package, level) __import__(name) # LINE 35 return sys.modules[name] Answer: Using tab in Django is a bad practice. In order to fixed your problem you must use spaces only, I think 4 spaces. Try to backspace your codes and you'll see that it's tab indention, use only spaces.
Monkeyrunner doesn't touch webview Question: I need to test android app which includes WebView with buttons. Monkeyrunner works fine for all parts of the app except WebView. Button in WebView just ignores touches from Monkeyrunner. I see that button is clicked because it became grey but then button does nothing. If I use mouse on emulator or finger on real device then button works great. I see from logcat that touch event was sent to the app but there is no action from the app. Some code: final WebView w = (WebView) findViewById(R.id.webView1); String summary = "<html><body><b>Google</b><form action=http://google.com><input type=submit><input type=text></form></body></html>"; w.loadData(summary, "text/html", null); Layout: <Button android:id="@+id/button1" android:text="Click me!" /> <WebView android:id="@+id/webView1" /> Monkeyrunner py: from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice device = MonkeyRunner.waitForConnection(10) # android.widget.Button COORDINATES - THIS WORKS FINE device.touch(10,100, 'DOWN_AND_UP') # WEBVIEW BUTTON COORDINATES - BUTTON DOESN'T WORK device.touch(200,200, 'DOWN_AND_UP') I had tried separately DOWN delay UP - the same result. Monkeyrunner from Python or from inside Java do not work too. Flavors and wrappers for monkeyrunner like ChimpChat do not work. I think it should work because there are so many web/HTML5 apps and it couldn't be true that all of them are not tested. But it appears opposite. Any ideas or suggestions how to enforce touch event for WebView components? Answer: This was a bug which I had reported to Android team. Some people had confirmed it. However with time it was merged with another bug and later that another bug was closed as "works as designed". Fortunately after few next Android versions it started to work as it supposed to do.
flickrAPI groups_leave() gives error Question: I keep getting an `<Element 'rsp' at 0x2f25830> Error: 99: Insufficient permissions. Method requires delete privileges; write granted.` error when I try to run `groups_leave()` from FlickrAPI. I use the `people_getGroups()` and it runs like a champ, so I used the same code, changing `people_getGroups()` to `groups_leave()` and it just bends over & moons me. :( ## Python 2.73 ## ## Patterned after http://stackoverflow.com/questions/3182269/retrieving-flickr-favorites ## import fileinput import time import flickrapi Start = time.time() g = 0 api_key = 'Thisisnotreallyit' api_secret = "ifItoldyou,I'dhavetokillyou" flickr = flickrapi.FlickrAPI(api_key, api_secret) uNSIDfile = '\flickrAPI\Test\GrpLeave.ttxt' InFile = open(uNSIDfile) OutFile = open('C:\flickrAPI\Test\LeftGrp.ttxt', mode='w') # group = '1569978@N25 ' for group in InFile: group = group [:-1] # gets rid of{CR}{LF} g += 1 if '@N' in group: try: Grp = flickr.groups_leave(group_id = group) fErr = '' tup = 'Left Group {0}\n'.format(Grp) OutFile.write(tup.encode('utf-8')) except flickrapi.FlickrError as fErr: tup = str(Grp) + '\t' + str(fErr) + '\n' OutFile.write(tup.encode('utf-8')) print('Left group: {0} \t {1}'.format (Grp, str(fErr))) group = '' else: pass print('{0} groups \n'.format (g)) print(" Processing time: {1}:{0}".format ( int(( time.time()-Start) % 60), int((time.time()-Start)/60))) InFile.close() OutFile.close() I tried running it from the console & it gives me: >>> group = '1389232@N25' >>> Grp = flickr.groups_leave(group_id = group) Traceback (most recent call last): File "<console>", line 1, in <module> ## File "c:\python27\lib\site-packages\flickrapi\flickrapi\__init__.py", line 349, in handler parse_format=args['format'], **args) File "c:\python27\lib\site-packages\flickrapi\flickrapi\__init__.py", line 435, in __wrap_in_parser return parser(self, data) File "c:\python27\lib\site-packages\flickrapi\flickrapi\__init__.py", line 278, in parse_etree raise FlickrError(u'Error: %(code)s: %(msg)s' % err.attrib) FlickrError: Error: 99: Insufficient permissions. Method requires delete privileges; write granted. >>> Answer: OK, once more I have the 'blonde moment!' ![enter image description here](http://i.stack.imgur.com/xrB7H.jpg) At the Services website <http://www.flickr.com/services/api/flickr.groups.leave.html> it states: **_Note:** This method requires an HTTP POST request._ I haven't yet learned how to format those, but that is for another day, eh?
How can I make jenkins run "pip install"? Question: I have a git repo and would like to get jenkins to clone it then run virtualenv venv --distribute /bin/bash venv/source/activate pip install -r requirements.txt python tests.py The console output from jenkins is: + virtualenv venv --distribute New python executable in venv/bin/python Installing distribute..........................done. Installing pip...............done. + /bin/bash venv/bin/activate + pip install -r requirements.txt Downloading/unpacking flask (from -r requirements.txt (line 1)) Running setup.py egg_info for package flask SNIP creating /usr/local/lib/python2.7/dist-packages/flask error: could not create '/usr/local/lib/python2.7/dist-packages/flask': Permission denied ---------------------------------------- Command /usr/bin/python -c "import setuptools;__file__='/var/lib/jenkins/workspace/infatics-website/build/flask/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-hkdBAi-record/install-record.txt failed with error code 1 Storing complete log in /home/jenkins/.pip/pip.log Build step 'Execute shell' marked build as failure Finished: FAILURE I've tried adding sudo before the command, but it's doesn't work either: + sudo pip install -r requirements.txt sudo: no tty present and no askpass program specified Sorry, try again. sudo: no tty present and no askpass program specified Sorry, try again. sudo: no tty present and no askpass program specified Sorry, try again. sudo: 3 incorrect password attempts Build step 'Execute shell' marked build as failure Finished: FAILURE Any ideas how to get around this? Also when I run pip install -r requirement.txt in a terminal as the jenkins user it doesn't need sudo permission. Can I get jenkins (the process) to run as the jenkins user? Answer: The fact that you have to run use `sudo` to run `pip` is a big warning that your virtual environment isn't working. The build output shows that `pip` is installing the requirements in your system site-packages directory, which is not the way virtualenv works. Your build script doesn't actually preserve the activated virtual environment. The environment variables set by the activate script are set in a child bash process and are not propagated up to the build script. You should source the `activate` script instead of running a separate shell: virtualenv venv --distribute . venv/bin/activate pip install -r requirements.txt python tests.py If you're running this as one build step, that should work (and install your packages in _venv_). If you want to add more steps, you'll need to set the PATH environment variable in your other steps. You're probably better off providing full paths to `pip` and `python` to ensure you're not dependent on system package installations.
Python evernote api Error Question: Trying to build app that connects with Evernote API, in Python/Django. For the below code i get the following error message: " 'Store' object has no attribute 'NoteFilter' " from <http://dev.evernote.com/documentation/reference/NoteStore.html#Svc_NoteStore> One can see, that NoteFilter is attribute of NoteStore. def list(request): nbname="mihkel's notebook" client = EvernoteClient(token=token, sandbox=False) note_store = client.get_note_store() notebooks = note_store.listNotebooks() for nb in notebooks: if nbname == nb.name: nb = nb filter = note_store.NoteFilter() filter.notebookGuid = nb.guid notelist = note_store.findNotes(token,filter,0,10) break return render_to_response('list.html', {'nb': nb, 'notelist':notelist}) Answer: Solution: from evernote.edam.notestore import NoteStore .... .... def list.. : ... Filter = NoteStore.NoteFilter()
Error when connecting to Google Mail over SMTP using smtplib in Python Question: My issue is that when I run the following code, I get a WinError 10061, and from all of my searching it looks like this is a result of the foreign machine not being set up properly, but I assume that Google has that taken care of for gmail, so the error lies on my side. All of the other examples I could find were using localhost and getting this error, and it was because they did not have a local mail server set up. Would that still be the case with this problem? I am sure I am missing something obvious. Also, the error code is in full. Thank you in advance! import smtplib fromaddr = '[email protected]' toaddrs = '[email protected]' msg = 'Random stuff!' username = 'username' password = 'pass' server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit() Error: Traceback (most recent call last): File "C:/Users/Brett/PycharmProjects/Texting/sendMessage.py", line 13, in <module> server = smtplib.SMTP('smtp.gmail.com') File "C:\Python33\lib\smtplib.py", line 238, in __init__ (code, msg) = self.connect(host, port) File "C:\Python33\lib\smtplib.py", line 317, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python33\lib\smtplib.py", line 288, in _get_socket self.source_address) File "C:\Python33\lib\socket.py", line 424, in create_connection raise err File "C:\Python33\lib\socket.py", line 415, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Answer: Having used the Gmail SMTP server in the past, I can only point out that the number for the SMTP port actually defaults to the appropriate one for Gmail, so the port argument (which can also be tacked onto the server name with a colon) can be omitted. Given this, you probably should try a different machine to ensure you're not running into networking errors, etc. Also, port 587 requires that ID check takes place, which means Gmail may think you're spamming or some other nonsense. Port 25, the default taken when no port number is entered, does not perform such a check.
Python Error while using Google Apps Engine Question: I am hosting a website on Google Apps Engine and am trying to use Python's mail API to take POST data and send an email. Here is my script: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import mail class SendEmail(webapp.RequestHandler): def post(self): name = self.request.get('name') # self.response.out.write(name) email = self.request.get('email') tempSubject = self.request.get('subject') msg = self.request.get('message') if name is None: self.response.out.write("Error: You did not enter a name.") elif email is None: self.response.out.write("Error: You did not enter an email.") elif tempSubject is None: self.response.out.write("Error: You did not enter a subject.") elif msg is None: self.response.out.write("Error: You did not enter a message.") else: _subject = "Msg from: " + name + "Re: " + tempSubject message = mail.EmailMessage(sender = "[email protected]", to = "[email protected]", subject = _subject, body = msg, reply_to = email) message.send() def runApp(): application = webapp.WSGIApplication([('/email', SendEmail)], debug=True) run_wsgi_app(application) if __name__ == '__main__': runApp() And here is the traceback from the log on the server: <type 'exceptions.NameError'>: name 'name' is not defined Traceback (most recent call last): File "/base/data/home/apps/s~alex-young/1.365202894602706277/email.py", line 5, in <module> class SendEmail(webapp.RequestHandler): File "/base/data/home/apps/s~alex-young/1.365202894602706277/email.py", line 14, in SendEmail if name is None: I ran the script locally with no errors, but once I try to run it on the server it keeps insisting the `name` variable I declared doesn't exist. Any idea why this happens? Also, if I comment out that line, it says `email` doesn't exist, and so forth Answer: As it turns out, sometimes I used spaces to indent and other times I used tabs. Python didn't like that. Here is the final code: import cgi from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import mail class SendEmail(webapp.RequestHandler): def post(self): name = self.request.get('name', '') email = self.request.get('email', '') tempSubject = self.request.get('subject', '') msg = self.request.get('message', '') if name is None: self.response.out.write("Error: You did not enter a name.") elif email is None: self.response.out.write("Error: You did not enter an email.") elif tempSubject is None: self.response.out.write("Error: You did not enter a subject.") elif msg is None: self.response.out.write("Error: You did not enter a message.") else: _subject = "Message from: " + name + ", Re: " + tempSubject msg += "\n\nI can be reached at " msg += email message = mail.EmailMessage(sender = "[email protected]", to = "[email protected]") message.subject = _subject message.body = msg message.send() self.redirect('/') def runApp(): application = webapp.WSGIApplication([('/email', SendEmail)], debug=True) run_wsgi_app(application) if __name__ == '__main__': runApp()
Parsing yaml python Question: There is a file in yaml markup a: b:x test2 test test3 How to use python (2.7.x) and PyYAML get x? Answer: You can't! The YAML you posted results in a dict containing just a single key, `a` which maps to the value `"b:x test2 test test3"` \- you can easily test that by [pasting your YAML here](http://yaml-online-parser.appspot.com/). The reason for this is that you cannot mix `key: value` pairs and keyless items (like there would be in an array). However, let's assume that you have proper YAML that contains an object `a` containing another object that maps `b` to `x`. For example this: a: b: x c: test2 d: test e: test3 In this case you'd use `foo['a']['b']` to access `x` with `foo` being the object returned by your YAML parser. The python code to get `foo` could look like this: import yaml with open('yourfile.yaml') as f: foo = yaml.safe_load(f) I'm using `safe_load` since you most likely do not intend to create arbitrary Python objects from your YAML document and thus you want to use a function that cannot open a security hole if ever passed a malicious YAML document.
How to generate a new table in PostgreSQL by iterating over an existing table of OSM data Question: I have a PostgreSQL database made up of the OSM map data for London. I imported this data using osm2psql. I would like to: * Iterate over every line in the planet_osm_line table * Break up the lines into individual line segments * Calculate a value for each line segment (in this example set value to 0.5) * Write the line segment as a new entry into a new table. The python code below seems to achieve this but with one problem. It only seems to be accessing as small section of the overall database. import psycopg2 conn = psycopg2.connect("dbname=db user=username") maincur = conn.cursor() readcur = conn.cursor() writecur = conn.cursor() maincur.execute("DROP TABLE lines_red") maincur.execute("CREATE TABLE lines_red (osm_id bigint, name text, way geometry, value float);") maincur.execute("SELECT osm_id, ST_NPOINTS(way) FROM planet_osm_line") for record in maincur: pointlist = [] for i in range(0,record[1]): readcur.execute("SELECT ST_ASTEXT(ST_POINTN(way, %s+1)) FROM planet_osm_line WHERE osm_id=%s;",(i,record[0])) output = readcur.fetchone() pointlist.append(output[0]) for i in range(0,record[1]-1): if pointlist[i+1] != None: value = 0.5 writecur.execute("INSERT INTO lines_red (name, way, value) VALUES ('testname', ST_Makeline(%s, %s), %s);", (pointlist[i],pointlist[i+1],value)) conn.commit() maincur.close() readcur.close() writecur.close() conn.close() To illustrate the image below shows the full planet_osm_line table shown in grey and the result of the query shown in red. The red lines should cover the entire map as the code should traverse the full planet_osm_line table. I am using tilemill to display the results. ![Result of trying to iterate over the entire planet_osm_line table](http://i.stack.imgur.com/X2AeR.png) Answer: The problem in this case was with my use of TileMill. When a new layer is created the default setting for its extent is to pre- calculate based on the database table used as input. This means that the layer will only ever be the size of the dataset with which it was initially created. In this case I had iterated over a subset of my data as a test of my code and the extents were calculated based on the results. When I iterated over the whole data set the code iterated over the entire database but only displayed the results within the previously calculated constraints. The solution is to create a new layer or set the extents setting in the layer to 'dynamic' rather than 'pre-calculate'
How can I search sub-folders using glob.glob module in Python? Question: I want to open a series of subfolders in a folder and find some text files and print some lines of the text files. I am using this: configfiles = glob.glob('C:/Users/sam/Desktop/file1/*.txt") But this cannot access the subfolders as well. Does anyone know how I can use the same command to access subfolders as well? Answer: Current versions of `glob.glob()` cannot list files in subdirectories recursively (an [update that will be included in python 3.5 when released](http://bugs.python.org/issue13968) adds a `**` option for arbitrary nested directory traversal). I'd use [`os.walk()`](http://docs.python.org/2/library/os.html#os.walk) combined with [`fnmatch.filter()`](http://docs.python.org/2/library/fnmatch.html#fnmatch.filter) instead: import os import fnmatch path = 'C:/Users/sam/Desktop/file1' configfiles = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(path) for f in fnmatch.filter(files, '*.txt')] This'll walk your directories recursively and return all absolute pathnames to matching `.txt` files. In this _specific_ case the `fnmatch.filter()` may be overkill, you could also use a `.endswith()` test: import os path = 'C:/Users/sam/Desktop/file1' configfiles = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(path) for f in files if f.endswith('.txt')]
*.pyc files not being found Question: I'm writing an application that loads byte-compiled `*.pyc` files under Python 3.3. I am distributing the `*.pyc` files without their corresponding `*.py` files to (try to) protect my source code. (Yes, as noted [here](http://stackoverflow.com/questions/11368304/what-are-the-limitations- of-distributing-pyc-files), trying to deter decompilation by byte-compiling Python isn't the most secure option, but I can always add other code-security measures if I find I need to.) However, I have found that Python isn't loading the `*.pyc` files without their original `*.py` files in place. (According to [PEP 3147](http://www.python.org/dev/peps/pep-3147/), the `*.pyc` files are kept in a subdirectory called `__pycache__` in the directory where the `*.py` file would be. I am following this convention with my own code.) Under an earlier iteration of my project that used Python 2.7, I byte-compiled the Python sources and placed the generated `*.pyc` files into the same directory as the `*.py` files; that worked just fine. Clearly, there is a problem with how Python is finding the `__pycache__` folder. What am I doing wrong? (And yes, I have set `sys.path` appropriately; otherwise it would not be finding the `*.py` file when I insert it as a debugging measure.) Answer: From [PEP 3147](http://www.python.org/dev/peps/pep-3147/): > If the py source file is missing, the pyc file inside `__pycache__` will be > ignored. This eliminates the problem of accidental stale pyc file imports. > > For backward compatibility, Python will still support pyc-only > distributions, however it will only do so when the pyc file lives in the > directory where the py file would have been, i.e. not in the `__pycache__` > directory. pyc file outside of `__pycache__` will only be imported if the py > source file is missing. So, if you want to make pyc-only distributions, you will have to put your compiled files in the same place as the .py files would have gone. According to the PEP, `compileall` has the option of creating this exact layout so you don't have to go copying things out of `__pycache__`, so check it out.
Structuring Data in Python (list from lists?) Question: I'm currently developing a script in Python 2.7 which pulls approximately 50 string values from a URL and places these values in a list. For each of these 50 values, they each have a further respective 20 associated string values. So for example, I may capture two initial values from a URL which are "Ford" and "BMW". I will then requery "Ford" to find associated models such as "Focus" and "Mondeo" etc.... Eventually I need to join those values to carry out a further URL query (ie. www.ford.com/fiesta and www.ford.com/mondeo and www.bmw.com/xxxx) I am wondering what the best was is to structure my data? I am thinking of creating a list of parent values and then for each parent value, create a sub- list titles the parent value with its associated values in the list. Is there a better way to structure the data? Answer: A friendly advice: keep things simple. Refer to the Zen of Python when in doubt: <http://www.python.org/dev/peps/pep-0020/> "Simple is better than complex." I would go for a dict of lists, or even better, a `defaultdict` (<http://docs.python.org/2/library/collections.html#collections.defaultdict>): from collections import defaultdict cars = defaultdict(list) cars["Ford"].append("Mondeo") cars["Ford"].append("Focus") cars["BMW"].append("SuperCoolModel") print cars Gives: defaultdict(<type 'list'>, {'BMW': ['SuperCoolModel'], 'Ford': ['Mondeo', 'Focus']})
generating list for joint distribution Question: I'm pretty sure this is an easy problem but I am completely blacking out on how to fix this. I am trying to work my way through the PGM class on coursera and it starts of with joint probability distribution. So I am trying to generate a list of all possible distributions given n variables, where each variable can take on some discrete value between 0...z so for instance say we have 3 variables, and each can take on values of just 0 and 1 I want to generate this: [[0, 0, 1] [0, 1, 0] [1, 0, 0] [1, 1, 0] [0, 1, 1] [1, 1, 1] [1, 0, 1] [0, 0, 0]] I am working in python I am drawing a blank on how to dynamically generate this. Answer: If you prefer list comprehension: [[a, b, c] for a in range(2) for b in range(2) for c in range(2)] And I forgot to mention that you can use pprint to get the effect you want: >>> import pprint >>> pprint.pprint([[a, b, c] for a in range(2) for b in range(2) for c in range(2)]) [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]] >>>
Python module dependencies Question: I'm trying to make my own module for easy sprite rendering & creation for personal uses. The only problem is, it needs pygame. If I were to put `import pygame` at the top of my module, could I then in another program, setup pygame instead of setting it up in the module? In general, does importing modules in one program, then importing that program into your main module, does the main program inherit the same dependencies, or do you need to explicitly re-import them? Module to be used: import pygame def makeSprite(): # todo write code INCLUDING PYGAME DEPENDENCIES pass def updateSprite(): # todo write code INCLUDING PYGAME DEPENDENCIES pass Program using module: import myModule # myModule is the name of the module above pygame.init() makeSprite(arg1, arg2) updateSprite(arg1, arg2) pygame.functionCallFromPygame() Can the main program also use the module? Thank you. Answer: That shouldn't be a problem. As long as nothing tries to actually use pygame functionality before `pygame.init()` is called, it'll work fine. (In other words, as long as whatever program using your library calls `pygame.init()` before calling your library's functions, you'll be fine.)
Loading JSON object with special values as a string Question: I'm trying to create a string JSON object to load using the `json` module; however, I'm having some trouble since some of my values are the python `True` and `False` rather than unicode strings. For example, I want do the following: >>> newDict = json.loads(u'{"firstKey": True, "secondKey": False}') >>> newDict.get('firstKey') == True True but I'm getting: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode obj, end = self._scanner.iterscan(s, **kw).next() File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan rval, next_pos = action(m, context) File "/usr/lib64/python2.6/json/decoder.py", line 185, in JSONObject raise ValueError(errmsg("Expecting object", s, end)) ValueError: Expecting object: line 1 column 13 (char 13) and of course if I change the `True` and `False` to `"True"` and `"False"`, my condition is not met either as they are now strings and `False` would be returned. Answer: Can you use lowercase `true` and `false`? >>> import json >>> d = {'firstKey': True, 'secondKey': False} >>> json.dumps(d) '{"secondKey": false, "firstKey": true}' >>> s = json.dumps(d) >>> json.loads(s) == d True
Python int to percent Question: I need monthlyPayment as percentage so instead of range = [4, 5, 6, 7, 8] I need range = [0.04, 0.05, 0.06, 0.07, 0.08] Do you know how to do it, and still get the calculation from totalPayment import math loanAmt=int(input("Enter the Amount (greater then 0) of the Loan: ")) numYears=int(input("Enter the number of years as an integer: ")) for monthlyRate in range(4,9): monthlyPayment = loanAmt * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12)) totalPayment = monthlyPayment * numYears * 12 print("{0:.0f}%".format(monthlyRate),'\t','$%.2f' %monthlyPayment,'\t','\t','$%.2f' %totalPayment) Answer: You can use this: for monthlyRate in (x/100.0 for x in range(4,9)): print monthlyRate 0.04 0.05 0.06 0.07 0.08
Input datatype error Question: I have a program which takes a string and converts it into list which looks like this - `['CTTC', 'CGCT', 'TTTA', 'CATG']`. (its actually a lot longer than this). Now I need to find how many of these list elements have a `C or A or T or G` as its 1st letter. This needs to be taken from the terminal i.e. using the `input` function. Now as far i know, in python 3.2 the datatype of input function is by default taken as a string (`str`) and not like an integer (`int`) (can be seen by using `isinstance`). However since I am using a college server, the python version is older (i think 2.7 or later but below 3.0). In this case, when I use the input function to ask the user to choose a letter- `initial = input("Choose a letter:")`, and when I enter any letter (A,T,G,or C) it gives me an error `NameError: name 'C' is not defined`. When i checked the datatype using `isinstance`, i realized that the python version takes the datatype of input as an `int` . When i try to convert it into a string, it gives the same error. Is it the problem of the version or is it something i am doing wrong. My code is below. import sys #import random file = open(sys.argv[1], 'r') string = '' for line in file: if line.startswith(">"): pass else: string = string + line.strip() w = input("Please enter window size:") test = [string[i:i+w] for i in range (0,len(string),w)] #seq = input("Please enter the number of sequences you wish to read:") #first = random.sample((test), seq) print test l = input("Enter letter for which you wish to find the probability:") lin = str(l) print lin Answer: Use `raw_input`, not `input`. In Python 2.x, `input` expects valid Python code, where as `raw_input` will convert the input to string. In Python 3.x `input` works the same as `raw_input`. To solve your _actual_ problem, which is counting the number of first letters, you can use either a [`defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict) or a [`Counter`](http://docs.python.org/2/library/collections.html#collections.Counter). `Counter` is only available if your Python version is 2.7 and above. `defaultdict` was added in 2.5. >>> from collections import Counter >>> i = ['CTTC','CGCT','TTTA','CATG','ABCD'] >>> c = Counter(x[0] for x in i) >>> c['C'] 3 Here is the `defaultdict` approach: >>> from collections import defaultdict >>> d = defaultdict(int) >>> for x in i: ... d[x[0]] += 1 ... >>> d['C'] 3
Python: KeyError 'shift' Question: I am new to Python and try to modify a pair trading script that I found here: <https://github.com/quantopian/zipline/blob/master/zipline/examples/pairtrade.py> The original script is designed to use only prices. I would like to use returns to fit my models and price for invested quantity but I don't see how do it. I have tried: * to define a data frame of returns in the main and call it in run * to define a data frame of returns in the main as a global object and use where needed in the 'handle data' * to define a data frame of retuns directly in the handle data I assume the last option to be the most appropriate but then I have an error with panda 'shift' attribute. More specifically I try to define 'DataRegression' as follow: DataRegression = data.copy() DataRegression[Stock1]=DataRegression[Stock1]/DataRegression[Stock1].shift(1)-1 DataRegression[Stock2]=DataRegression[Stock2]/DataRegression[Stock2].shift(1)-1 DataRegression[Stock3]=DataRegression[Stock3]/DataRegression[Stock3].shift(1)-1 DataRegression = DataRegression.dropna(axis=0) where 'data' is a data frame which contains prices, stock1, stock2 and stock3 column names defined globally. Those lines in the handle data return the error: File "A:\Apps\Python\Python.2.7.3.x86\lib\site-packages\zipline-0.5.6-py2.7.egg\zipline\utils\protocol_utils.py", line 85, in __getattr__ return self.__internal[key] KeyError: 'shift' Would anyone know why and how to do that correctly? Many Thanks, Vincent Answer: This is an interesting idea. The easiest way to do this in zipline is to use the Returns transform which adds a returns field to the event-frame (which is an ndict, not a pandas DataFrame as someone pointed out). For this you have to add the transform to the initialize method: ` self.add_transform(Returns, 'returns', window_length=1) ` (make sure to add `from zipline.transforms import Returns` at the beginning). Then, inside the batch_transform you can access returns instead of prices: @batch_transform def ols_transform(data, sid1, sid2): """Computes regression coefficient (slope and intercept) via Ordinary Least Squares between two SIDs. """ p0 = data.returns[sid1] p1 = sm.add_constant(data.returns[sid2]) slope, intercept = sm.OLS(p0, p1).fit().params return slope, intercept Alternatively, you could also create a batch_transform to convert prices to returns like you wanted to do. @batch_transform def returns(data): return data.price / data.price.shift(1) - 1 And then pass that to the OLS transform. Or do this computation inside of the OLS transform itself. HTH, Thomas
Why does easy install want access to my rootfs for a "develop" install? Question: I'm looking at a python application server and I wanted to play around with the code. I'm lead to believe passing "develop" to setup.py should leave everything in place without installing anything. However when running so it is attempting to creating directories in my rootfs. ./setup.py develop Gives: running develop Checking .pth file support in /usr/local/lib/python2.7/dist-packages/ error: can't create or remove files in install directory I thought this might be something to do with package checking but surely attempting to write stuff into the rootfs is wrong? Answer: The `develop` command wants to add a `.pth` entry for your project so that it can be imported as an egg. See the [Development mode documentation](http://pythonhosted.org/setuptools/setuptools.html#development- mode), as well as the [`develop` command docs](http://pythonhosted.org/setuptools/setuptools.html#develop). The default is to put that entry in site-packages. Set a different library path with the `--install-dir` switch.
Python - Print a value without intterupting a loop/function Question: Using Python 2.7 on Windows 7. I has a recursive function, to find a file in the path, also looking in the sub-folders. **My Problem:** During long searches, I wish to see the value of `retval` on `KeyboardInterrupt`. But the code is raising an error on `KeyboardInterrupt`, as it is interrupting a "deeper" function call/run. **My Question:** Is there any way to not interrupt the loop, but still have the values printed, Or A different way to do the same (that is not using `KeyboardInterrupt` but something else) **My Code:** import os def search(path,filename): try: global found folders = [] retval = [] try: for item in os.listdir(path): if not os.path.isfile(os.path.join(path, item)): folders.append(os.path.join(path, item)) else: if item == filename: found += 1 retval.append(os.path.join(path, item)) except WindowsError,e: print str(e)[10:] for folder in folders: retval += search(folder,filename) return retval except KeyboardInterrupt: print retval found = 0 path = 'C:\\' filename = 'test.txt' print search(path,filename) Answer: You can add the `KeyboardInterrupt` handler lower in the hierarchy: for folder in folders: try: retval += search(folder,filename) except KeyboardInterrupt: print retval return retval You could test that, although I'm not quite sure how that handles inside a loop like the one you have.
Using Python help throws SEGFAULT Question: While using Python help I typed modules and got the following error: help> modules Please wait a moment while I gather a list of all available modules... /usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning: g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed import gobject._gobject /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed from gtk import _gtk ** (python:12351): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register existing type `GdkDevice' from gtk import _gtk /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata: assertion `node != NULL' failed from gtk import _gtk Segmentation fault (core dumped) See also: <https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/896836> How can I fix or get around this issue and get the help I want? Answer: Such "lists of modules" (`pydoc -k` too) require importing everything available into one process and this may cause all kinds of problems. Don't do that. See also <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=697402>
Convert text prediction script [Markov Chain] from javascript to python Question: i've been trying the last couple days to convert [this js script](http://blog.javascriptroom.com/2013/01/21/markov-chains/) to python code. My implementation (blindfull cp mostly, some minor fixes here and there) so far: import random class markov: memory = {} separator = ' ' order = 2 def getInitial(self): ret = [] for i in range(0, self.order, 1): ret.append('') return ret def breakText(self, txt, cb): parts = txt.split(self.separator) prev = self.getInitial() def step(self): cb(prev, self.next) prev.shift()#Javascript function. prev.append(self.next) #parts.forEach(step) # - step is the function above. cb(prev, '') def learn(self, txt): mem = self.memory def learnPart(key, value): if not mem[key]: mem[key] = [] mem[key] = value return mem self.breakText(txt, learnPart) def step(self, state, ret): nextAvailable = self.memory[state] or [''] self.next = nextAvailable[random.choice(nextAvailable.keys())] if not self.next: return ret ret.append(next) nextState = state.slice(1) return self.step(nextState, ret) def ask(self, seed): if not seed: seed = self.genInitial() seed = seed + self.step(seed, []).join(self.separator) return seed Issues: 1. I have absolutely no knowledge of javascript. 2. When i try to "learn" some text to a "markov" class object [e.g.: a=markov(); a.learn("sdfg");] i get the following error: "TypeError: unhashable type: 'list'", for the "mem" dictionary at the "learnPart" function, member of the "learn" function. So my question so far is why does this exception [TypeError for a list object, falsely referring to a dictionary object (which is hashable)] occur? thanks in advance for any suggestions, directions, points, help in general :D Answer: Guy who wrote the article speaking. Glad you found it useful! Now, my first implementation of a Markov chain was actually in Python, so this answer will focus on how to write it in a more Pythonic way. I'll show how to go about making an order-2 Markov chain, since they're easy to talk about, but you can of course make it order-N with some modifications. ### Data Structures In js, the two prominent data structures are the generic object and the array (which is an extension to the generic object). In Python however, you have other options for more finely-grained control. Here're the major differences in the two implementations: * A state in our chain is really a tuple - an immutable, ordered structure, with a fixed amount of elements. We always want `n` elements (in this case, `n=2`) and their order has meaning. * Manipulating the memory will be easier if we use a [defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict) wrapping a list, so we can skip the "checking if a state doesn't exist, and then doing X", and instead just do X. So, we stick a `from collections import defaultdict` at the top and change how `markov.memory` is defined: memory = defaultdict(list) Now we change `markov.getInitial` to return a tuple (remember this explains an order-2 chain): def getInitial(self): return ('', '') (if you want to expand it further, you can use a really neat Python trick: `tuple([''] * 2)` will return the same thing. Instead of empty strings, you can use `None`) We'll get to changing what uses `genInitial` in a bit. ### Yield and iteration A strong concept which doesn't exist in js (yet) but does exist in Python is the `yield` operator ([see this question](http://stackoverflow.com/questions/231767/the-python-yield-keyword- explained) for great explanations). Another feature of Python is its generic `for` loop. You can go over nearly anything quite easily, including generators (functions which use `yield`). Combining the two, and we can redefine `breakText`: def breakText(self, txt): #our very own (ε,ε) prev = self.getInitial() for word in txt.split(self.separator): yield prev, word #will be explained in the next paragraph prev = (prev[1], word) #end-of-sentence, prev->ε yield prev, '' The magic part above, `prev = (prev[1], word)` can be explained best by example: >>> a = (0, 1) >>> a (0, 1) >>> a = (a[1], 2) >>> a (1, 2) That's how we advance through the word list. And now we move up to what uses `breakText`, to the redefinition of `markov.learn`: def learn(self, txt): for part in self.breakText(txt): key = part[0] value = part[1] self.memory[key].append(value) Because our memory is a `defaultdict`, we don't have to worry about the key not existing. ### A pee break on the side of the road OK, we have half of the chain implemented, time to see it in action! What we have so far: from collections import defaultdict class Markov: memory = defaultdict(list) separator = ' ' def learn(self, txt): for part in self.breakText(txt): key = part[0] value = part[1] self.memory[key].append(value) def breakText(self, txt): #our very own (ε,ε) prev = self.getInitial() for word in txt.split(self.separator): yield prev, word prev = (prev[1], word) #end-of-sentence, prev->ε yield (prev, '') def getInitial(self): return ('', '') (I changed the class name from `markov` to `Markov` because I cringe every time a class begins with a lowercase letter). I saved it as `brain.py` and loaded up Python. >>> import brain >>> bob = brain.Markov() >>> bob.learn('Mary had a little lamb') >>> bob.memory defaultdict(<class 'list'>, {('had', 'a'): ['little'], ('Mary', 'had'): ['a'], ('', ''): ['Mary'], ('little', 'lamb'): [''], ('a', 'little'): ['lamb'], ('', 'Mary'): ['had']}) Success! Let's look at the result more carefully, to see that we got it right: { ('', ''): ['Mary'], ('', 'Mary'): ['had'], ('Mary', 'had'): ['a'], ('a', 'little'): ['lamb'], ('had', 'a'): ['little'], ('little', 'lamb'): ['']} _zips up_ Ready to drive on? We still have to _use_ this chain! ### Changing the `step` function We've already met what we need to remake `step`. We have the defaultdict, so we can use `random.choice` right away, and I can cheat a bit because I know the order of the chain. We can also get rid of the recursion (with some sorrow), if we see it as a function which takes a single step through the chain (my bad in the original article - a badly named function). def step(self, state): choice = random.choice(self.memory[state] or ['']) if not choice: return None nextState = (state[1], choice) return choice, nextState I regretfully added the `or ['']` because `random.choice` moans about empty lists. Finally, we move a larger portion of the logic to `ask` (the actual construction of the sentence): def ask(self, seed=False): ret = [] if not seed: seed = self.getInitial() while True: link = self.step(seed) if link is None: break ret.append(link[0]) seed = link[1] return self.separator.join(ret) Yes, a bit yucky. We could have given `step` a better name and made it a generator, but I'm late for a meeting with my pregnant wife who's about to give birth to a baby who left the stove on fire in my car that's being towed! I better hurry! ### The grand finale But first, a talk with bob: from collections import defaultdict import random class Markov: memory = defaultdict(list) separator = ' ' def learn(self, txt): for part in self.breakText(txt): key = part[0] value = part[1] self.memory[key].append(value) def ask(self, seed=False): ret = [] if not seed: seed = self.getInitial() while True: link = self.step(seed) if link is None: break ret.append(link[0]) seed = link[1] return self.separator.join(ret) def breakText(self, txt): #our very own (ε,ε) prev = self.getInitial() for word in txt.split(self.separator): yield prev, word prev = (prev[1], word) #end-of-sentence, prev->ε yield (prev, '') def step(self, state): choice = random.choice(self.memory[state] or ['']) if not choice: return None nextState = (state[1], choice) return choice, nextState def getInitial(self): return ('', '') And loading it up: >>> import brain >>> bob = brain.Markov() >>> bob.learn('Mary had a little lamb') >>> bob.ask() 'Mary had a little lamb' >>> bob.learn('Mary had a giant crab') >>> bob.ask(('Mary', 'had')) 'a giant crab' There is, of course, room for improvement and expanding on the concept. But it wouldn't be any fun if if I just gave you the answer. Hopefully this will still help after 4 months.
Using buttons in Tkinter to navigate to different pages of the application? Question: I have quite a simple question here. In Tkinter (python), i was wondering who to use a button to go to different pages of my application, e.g a register page, and a login page. I am aware that GUI does not have 'pages' like websites do, ive seen a few different ways, but what is the best way to make links to different pages? Thank you all very much! Answer: Make each page a frame. Then, all your buttons need to do is hide whatever is visible, then make the desired frame visible. A simple method to do this is to stack the frames on top of each other (this is one time when `place` makes sense) and then ,`lift()` the frame you want to be visible. This technique works best when all pages are the same size; in fact, it requires that you explicitly set the size of containing frame. The following is a contrived example. This isn't the only way to solve the problem, just proof that it's not a particularly hard problem to solve: import Tkinter as tk class Page(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) def show(self): self.lift() class Page1(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) label = tk.Label(self, text="This is page 1") label.pack(side="top", fill="both", expand=True) class Page2(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) label = tk.Label(self, text="This is page 2") label.pack(side="top", fill="both", expand=True) class Page3(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) label = tk.Label(self, text="This is page 3") label.pack(side="top", fill="both", expand=True) class MainView(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) p1 = Page1(self) p2 = Page2(self) p3 = Page3(self) buttonframe = tk.Frame(self) container = tk.Frame(self) buttonframe.pack(side="top", fill="x", expand=False) container.pack(side="top", fill="both", expand=True) p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1) p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1) p3.place(in_=container, x=0, y=0, relwidth=1, relheight=1) b1 = tk.Button(buttonframe, text="Page 1", command=p1.lift) b2 = tk.Button(buttonframe, text="Page 2", command=p2.lift) b3 = tk.Button(buttonframe, text="Page 3", command=p3.lift) b1.pack(side="left") b2.pack(side="left") b3.pack(side="left") p1.show() if __name__ == "__main__": root = tk.Tk() main = MainView(root) main.pack(side="top", fill="both", expand=True) root.wm_geometry("400x400") root.mainloop()
multiple users doing form submission with python CGI Question: I have a simple cgi script in python collecting a value from form fields submitted through post. After collecting this, iam dumping these values to a single text file. Now, when multiple users submit at the same time, how do we go about it? In C\C++ we use semaphore\mutex\rwlocks etc? Do we have anything similar in python. Also, opening and closing the file multiple times doesnt seem to be a good idea for every user request. We have our code base for our product in C\C++. I was asked to write a simple cgi script for some reporting purpose and was googling with python and cgi. Please let me know. Thanks! Santhosh Answer: There are lots of python based servers you could use. Here's one: [Twisted](http://twistedmatrix.com/trac/) > Twisted is an event-driven networking engine written in Python and licensed > under the open source from twisted.internet import protocol, reactor class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(protocol.Factory): def buildProtocol(self, addr): return Echo() reactor.listenTCP(1234, EchoFactory()) reactor.run() You probably want to drop the values into a database instead of a text file. However threading is available and so you can use `lock()` to ensure only one user writes to the file at a time. <http://effbot.org/zone/thread-synchronization.htm> > Locks are typically used to synchronize access to a shared resource. For > each shared resource, create a Lock object. When you need to access the > resource, call acquire to hold the lock (this will wait for the lock to be > released, if necessary), and call release to release it
My form is called twice but why? Question: When I try to save my form i meet this error : Exception Value: Cannot assign None: "TriggerService.user" does not allow null values. Exception Location: /usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py in __set__, line 362 here are my models, forms and views **models.py** class TriggerService(models.Model): """ TriggerService """ provider = models.ForeignKey(TriggerType, related_name='+', blank=True) consummer = models.ForeignKey(TriggerType, related_name='+', blank=True) description = models.CharField(max_length=200) user = models.ForeignKey(User) date_created = models.DateField(auto_now_add=True) **forms.py** class TriggerServiceForm(forms.ModelForm): """ TriggerService Form """ class Meta: """ meta to add/override anything we need """ model = TriggerService widgets = { 'description':\ TextInput(attrs={'placeholder':\ _('A description for your new service')}), } exclude = ('user', 'date_created') provider = forms.ModelChoiceField(queryset=TriggerType.objects.all()) consummer = forms.ModelChoiceField(queryset=TriggerType.objects.all()) def save(self, user=None): myobject = super(TriggerServiceForm, self).save(commit=False) print "i am:" print user myobject.user = user myobject.save() **views.py** class TriggerServiceCreateView(CreateView): form_class = TriggerServiceForm template_name = "triggers/add_trigger.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(TriggerServiceCreateView, self).dispatch(*args, **kwargs) def form_valid(self, form): self.object = form.save(user=self.request.user) return super(TriggerServiceCreateView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(TriggerServiceCreateView, self).get_context_data(**kwargs) context['action'] = 'add_trigger' return context Like you can see in my forms I added a print to follow what happens here and strangely the save of my form i done twice, why ? and how to avoid this behavior ? i am: foxmask i am: None Answer: This: def form_valid(self, form): # call form.save manually: creates "i am: foxmask" self.object = form.save(user=self.request.user) # Call parent form_valid(), CreateView.form_valid() ... # ... which also calls form.save() without user argument !! # So, it should create "i am: None" because the default value for # the user argument of the save() method of your form is None. return super(TriggerServiceCreateView, self).form_valid(form) And [`CreateView.form_valid()`](https://github.com/django/django/blob/1.4.3/django/views/generic/edit.py#L111) calls `TriggerServiceForm.save()` with `user=None`. So you can't use super() here as it will call the direct parent. Why not keep it simple: from django import http # ... def form_valid(self, form): self.object = form.save(user=self.request.user) return http.HttpResponseRedirect(self.get_success_url())
Convert CSV to txt and start new line every 10 values using Python Question: I have a csv file with an array of values 324 rows and 495 columns. All the values for each row and col are the same. I need to have this array split up so that every 10 values is put in a new row. So for each of the 324 rows, there will be 49 full columns with 10 values and 1 column with 5 values (495 col / 10 values = 49 new rows with 10 values and 1 new row with 5 values). Then go to the next row and so on for 324 rows. The trouble i'm having is listed as follows: 1. line.split(",") does not seem to be doing anything 2. Everything after the line.split doesn't seem to do anything either 3. i'm not sure my for newrow in range...is correct 4. I haven't put in the write output to text file yet, i think it should be outFile.write(something goes here, not sure what) 5. i put "\n" after print statement, but it just printed it out I'm a beginner programmer. Script: import string import sys # open csv file...in read mode inFile= open("CSVFile", 'r') outFile= open("TextFile.txt", 'w') for line in inFile: elmCellSize = line.split(",") for newrow in range(0, len(elmCellSize)): if (newrow/10) == int(newrow/10): print elmCellSize[0:10] outFile.close() inFile.close() Answer: You should really be using the csv module, but I can give some advice anyway. One problem you're having is that when you say `print elmCellSize[0:10]`, you are always taking the first 10 elements, not the most recent 10 elements. Depending on how you want to do this, you could keep a string to remember the most recent 10 elements. I'll show an example below, after mentioning a few things that you can fix with your code. First note that `line.split(',')` returns a list. So your choice of variable name `elmCellSize` is a little misleading. If you were to say `lineList = line.split(',')` it might make more sense? Or if you were to say `lineSize = len(line.split(','))` and use that? Also (although I don't know anything about Python 2.x) I think `xrange` is a function for Python 2.x which is more efficient than `range`, although it works exactly the same way. Instead of saying `if (newrow/10) == int(newrow/10)`, you can actually say `if index % 10 == 0`, to check if index is a multiple of 10. `%` can be thought of as 'remainder', so it will give the remainder of `newrow` when divided by `10`. (Ex: 5 % 10 = 5; 17 % 10 = 7; 30 % 10 = 0) Now instead of printing `[0:10]`, which will always print the first 10 elements, you want to print from the current index back 10 spaces. So you can say `print lineList[index-10:index]` in order to print the most recent 10 elements. In the end you'll have something like ... lineList = line.split(',') # Really, you should use csv reader # Open the file to write to with open('yourfile.ext', 'w') as f: # iterate through the line for index, value in enumerate(lineList): if index % 10 == 0 and index != 0: # Write the last 10 values to the file, separated by commas f.write(','.join(lineList[index-10:index])) # new line f.write('\n') # print print lineList[index-10:index] I'm certainly not an expert, but I hope this helps!
Unable to get ToMany to work in Tastypie Question: I'm following the Tastypie docs, and have found myself utterly stuck. I have the following: API: class ProjectResource(ModelResource): milestones = fields.ToManyField('ProjectTrackerServer.projects.api.MilestoneResource', 'projects', related_name='project', full=True) class Meta: queryset = Project.objects.all() resource_name = 'project' class MilestoneResource(ModelResource): project = fields.ToOneField('ProjectTrackerServer.projects.api.ProjectResource', 'project') class Meta: queryset = Milestone.objects.all() resource_name = 'milestone' [UPDATE: The above API worked - based one the models below ] Here are my models. MODEL - Milestone: from django.db import models from ProjectTrackerServer.projects.models import Project class Milestone(models.Model): project = models.ForeignKey(Project, related_name='projects') name = models.TextField() start_date = models.DateField() due_date = models.DateField() completed_date = models.DateField() description = models.TextField() status = models.IntegerField() def __unicode__(self): return self.name MODEL - Project: from django.db import models from django.template.defaultfilters import slugify class Project(models.Model): name = models.CharField(max_length=200) start_date = models.DateField() end_date = models.DateField() pm_id = models.IntegerField() status = models.IntegerField() slug = models.SlugField() def __unicode__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name)[:50] return super(Project, self).save(*args, **kwargs) I still get the same error: {"error_message": "'Project' object has no attribute 'milestones'", "traceback": "Traceback (most recent call last):\n\n File \"C:\Python27\lib\site-packages\tastypie\resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"C:\Python27\lib\site-packages\tastypie\resources.py\", line 406, in dispatch_detail\n return self.dispatch('detail', request, **kwargs)\n\n File \"C:\Python27\lib\site-packages\tastypie\resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"C:\Python27\lib\site-packages\tastypie\resources.py\", line 1058, in get_detail\n bundle = self.full_dehydrate(bundle)\n\n File \"C:\Python27\lib\site-packages\tastypie\resources.py\", line 654, in full_dehydrate\n bundle.data[field_name] = field_object.dehydrate(bundle)\n\n File \"C:\Python27\lib\site-packages\tastypie\fields.py\", line 690, in dehydrate\n the_m2ms = getattr(bundle.obj, self.attribute)\n\nAttributeError: 'Project' object has no attribute 'milestones'\n"} Answer: ::Additional resources:: [This blog has an excellent django-tastypie reverse relationship example](http://djangoandlove.blogspot.com/2012/11/tastypie-following-reverse- relationship.html) When I had the error **AttributeError: 'Options' object has no attribute 'api_name'\n"}** I had the example line typed out as milestones = fields.ToManyField('ProjectTrackerServer.projects.api.Milestone', 'projects', full=True) Make sure you are listing the "..api.Milestone**Resource** ~Also~ If you're getting an empty list where the relationships are, make sure that the second argument you pass into the ".ToManyField" matches your related name specified in your models file. milestones = fields.ToManyField('ProjectTrackerServer.projects.api.MilestoneResource', 'projects', full=True) class Milestone(models.Model): project = models.ForeignKey(Project, related_name='projects') ...
Using ipcluster to connect to an OS X server w/ EPD from Linux? Question: I am trying to use IPython.parallel's support for SSH to allow my Linux client to run remote `ipengine`s from an OS X server that has EPD64 installed. This fails, however, as it attempts to use my local machine to figure out the right command to run on the remote host, which has its `ipengineapp` package in a different location. How do I modify `ipcluster_config.py` to recognize the difference? Concretely, when I run `ipcluster start --log-level=DEBUG` on the remote host, I get console output telling me that contains a line like the following: [IPClusterStart] Starting LocalEngineLauncher: ['/Library/Frameworks/EPD64.framework/Versions/7.3/bin/python', '-c', 'from IPython.parallel.apps.ipengineapp import launch_new_instance; launch_new_instance()', '--profile-dir', u'/Users/username/.ipython/profile_default', '--cluster-id', u'', '--log-to-file', '--log-level=20'] On the other hand, when run from my local machine with `ipcluster start --log- level=DEBUG`, I get the following line, as would be appropriate for a Linux host: [IPClusterStart] Starting SSHEngineLauncher: ['ssh', '-tt', u'hostname', '/usr/bin/python', u'/usr/lib/python2.7/site-packages/IPython/parallel/apps/ipengineapp.py', '--profile-dir', u'/home/username/.ipython/profile_ssh', '--log-to-file', '--log-level=20'] My `ipcluster_config.py` for this example is: c = get_config() c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher' c.IPClusterStart.controller_launcher_class = 'SSHControllerLauncher' c.SSHEngineSetLauncher.engines = { 'hostname1': 12, 'hostname2': 12, } Answer: I think this is improved in 0.14, but the config value you are looking for is `SSHEngineSetLauncher.engine_cmd`. Edit this in ipcluster_config.py, so it's something like: c.SSHEngineSetLauncher.engine_cmd = ['/path/to/your/python', '-c', 'from IPython.parallel.apps.ipengineapp import launch_new_instance; launch_new_instance()'] or, sometimes even the simplest thing works, as long as your PATH is configured in a simple ssh session: c.SSHEngineSetLauncher.engine_cmd = ['ipengine']
convert python dataframe to list Question: I have a Python dataFrame with multiple columns. LogBlk Page BayFail 0 0 [0, 1, 8, 9] 1 16 [0, 1, 4, 5, 6, 8, 9, 12, 13, 14] 2 32 [0, 1, 4, 5, 6, 8, 9, 12, 13, 14] 3 48 [0, 1, 4, 5, 6, 8, 9, 12, 13, 14] I want to find BayFails that is associated with LogBlk=0, and Page=0. df2 = df[ (df['Page'] == 16) & (df['LogBlk'] == 0) ]['BayFail'] This will return [0,1,8,9] What I want to do is to convert this pandas.series into a list. Does anyone know how to do that? Answer: `pandas.Series`, has a [`tolist` method](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html#numpy- ndarray-tolist): In [10]: import pandas as pd In [11]: s = pd.Series([0,1,8,9], name = 'BayFail') In [12]: s.tolist() Out[12]: [0L, 1L, 8L, 9L] * * * Technical note: In my original answer I said that `Series` was a subclass of `numpy.ndarray` and inherited its `tolist` method. While that's true for Pandas version 0.12 or older, In the soon-to-be-released Pandas version 0.13, `Series` has been refactored to be a subclass of `NDFrame`. `Series` still has a `tolist` method, but it has no direct relationship to the `numpy.ndarray` method of the same name.
Parsing XML with LXML and Python Question: I have the following XML: <nfl> <season season="2012"/> <conference label="AFC"> <division label="Eastern Division"> <team city="Buffalo" name="Bills" alias="Buf" /> <team city="Miami" name="Dolphins" alias="Mia" /> <team city="New England" name="Patriots" alias="NE" /> <team city="New York" name="Jets" alias="NYJ" /> </division> <division label="Western Division"> <team city="Denver" name="Broncos" alias="Den" /> <team city="Kansas City" name="Chiefs" alias="KC" /> <team city="Oakland" name="Raiders" alias="Oak" /> <team city="San Diego" name="Chargers" alias="SD" /> </division> <division label="Northern Division"> <team city="Cincinnati" name="Bengals" alias="Cin" /> <team city="Cleveland" name="Browns" alias="Cle" /> <team city="Pittsburgh" name="Steelers" alias="Pit" /> <team city="Baltimore" name="Ravens" alias="Bal" /> </division> <division label="Southern Division"> <team city="Houston" name="Texans" alias="Hou" /> <team city="Tennessee" name="Titans" alias="Ten" /> <team city="Indianapolis" name="Colts" alias="Ind" /> <team city="Jacksonville" name="Jaguars" alias="Jac" /> </division> </conference> <conference label="NFC"> <division label="Eastern Division"> <team city="Dallas" name="Cowboys" alias="Dal" /> <team city="New York" name="Giants" alias="NYG" /> <team city="Philadelphia" name="Eagles" alias="Phi" /> <team city="Washington" name="Redskins" alias="Was" /> </division> <division label="Western Division"> <team city="St. Louis" name="Rams" alias="StL" /> <team city="Arizona" name="Cardinals" alias="Ari" /> <team city="San Francisco" name="49ers" alias="SF" /> <team city="Seattle" name="Seahawks" alias="Sea" /> </division> <division label="Northern Division"> <team city="Chicago" name="Bears" alias="Chi" /> <team city="Detroit" name="Lions" alias="Det" /> <team city="Green Bay" name="Packers" alias="GB" /> <team city="Minnesota" name="Vikings" alias="Min" /> </division> <division label="Southern Division"> <team city="Atlanta" name="Falcons" alias="Atl" /> <team city="New Orleans" name="Saints" alias="NO" /> <team city="Tampa Bay" name="Buccaneers" alias="TB" /> <team city="Carolina" name="Panthers" alias="Car" /> </division> </conference> </nfl> I want to load into my model, the team "city", "name" and "alias" along with the parent "division label", "conference label" and "season". In Python, I iterate through the data as follows: from lxml import etree doc = etree.parse('thisxmlfile.xml') for s in doc.xpath('//season'): for c in doc.xpath('//conference'): for t in doc.xpath('//conference/division/team'): print s.get('season'), c.get('label'), t.get('city'), t.get('name'), t.get('alias') But of course, it iterates through all "team" tags twice - once for each "conference" tag. What I want to do is iterate through all "team" tags once and get the parent "division label", parent "conference label" and parent "season season". Pretty sure I need to reference XPATH Axes and was looking for some help? The output I'm looking for is: 2012 AFC Buffalo Bills Buf 2012 AFC Miami Dolphins Mia 2012 AFC New England Patriots NE . . . 2012 NFC New Orleans Saints NO 2012 NFC Tampa Bay Buccaneers TB 2012 NFC Carolina Panthers Car Note: the above output does not include the "division label" but once I figure out how to get the "conference label", it should be easy. Thanks in advance for any help. Answer: Here is how you can get the wanted output: from lxml import etree doc = etree.parse('thisxmlfile.xml') # There is only one "season" element season = doc.find('season').get('season') # XPath query relative to root node for conference in doc.xpath('conference'): # XPath query relative to "conference" node for team in conference.xpath('division/team'): print season, conference.get('label'), print team.get('city'), team.get('name'), team.get('alias')
Python CSV writer with utf-8 code formats Question: I am trying to write something in Dutch to a CSV a file and this is what happens In the following program, ideally, "Eéntalige affiche in Halle !!" should be written in the csv file. However, it's writing "Eéntalige affiche in Halle !!" # -*- encoding: utf-8 -*- import csv S="Eéntalige affiche in Halle !!".encode("utf-8") file=c = csv.writer(open("Test.csv","wb")) file.writerow([S]) In the CSV file== ? "Eéntalige affiche in Halle !!" Answer: You are writing data correctly. The problem lies in whatever is _reading_ the data; it is interpreting the UTF-8 data as Latin 1 instead: >>> print('E\xe9ntalige affiche in Halle !!') Eéntalige affiche in Halle !! >>> 'E\xe9ntalige affiche in Halle !!'.encode('utf8') b'E\xc3\xa9ntalige affiche in Halle !!' >>> print('E\xe9ntalige affiche in Halle !!'.encode('utf8').decode('latin1')) Eéntalige affiche in Halle !! The U+00E9 codepoint (é, LATIN SMALL LETTER E WITH ACUTE) is encoded to two bytes in UTF-8, C3 and A9 in hex. If you treat those two bytes as Latin1 instead, where each character is always only _one_ byte, you get `Ã` and `©` instead. There is no standard for how to treat CSV files and encoding, you'll need to adjust your encoding to the intended target application to read this information. Microsoft Excel reads CSV files according to the current codepage, for example. If your CSV reader is expecting Latin 1, by all means, encode to Latin 1 instead.
How to print a specific xml value using python? Question: I have the xml which looks like below <api> <apicat> <cat> <id>1</id> <name>testname</name> </cat> <cat> <id>2</id> <name>testname2</name> </cat> <cat> <id>3</id> <name>testname3</name> </cat> </apicat> How to print the name which has id=2? And also please note that if the xml is not bringing back values in the same order and also if the number of results is higher 10,000? Answer: You can do this easily with [lxml](/questions/tagged/lxml "show questions tagged 'lxml'") module with a [xpath](/questions/tagged/xpath "show questions tagged 'xpath'") expression : from lxml import etree file = "file://path/to/file.xml" doc = etree.parse(file) print doc.xpath('//cat[id=2]/name/text()')[0] See <http://lxml.de/> and a [Xpath tutorial](http://www.w3schools.com/xpath/default.asp) Your XML file is not valid, this one should be : <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <api> <apicat> <cat> <id>1</id> <name>testname</name> </cat> <cat> <id>2</id> <name>testname2</name> </cat> <cat> <id>3</id> <name>testname3</name> </cat> </apicat> </api>
Create for loop for naming output file Python Question: So i'm importing a list of names e.g. Textfile would include: Eleen Josh Robert Nastaran Miles my_list = ['Eleen','Josh','Robert','Nastaran','Miles'] Then i'm assigning each name to a list and I want to write a new excel file for each name in that list. #1. Is there anyway I can create a for loop where on the line: temp = os.path.join(dir,'...'.xls') _________________________ def high_throughput(names): import os import re # Reading file in_file=open(names,'r') dir,file=os.path.split(names) temp = os.path.join(dir,'***this is where i want to put a for loop for each name in the input list of names***.xls') out_file=open(temp,'w') data = [] for line in in_file: data.append(line) in_file.close() Answer: Take a look at [`openpyxl`](http://pythonhosted.org/openpyxl/), especially if you need to create `.xlsx` files. Below example assumes the Excel workbooks are created as blank. from openpyxl import Workbook names = ['Eleen','Josh','Robert','Nastaran','Miles'] for name in names: wb = Workbook() wb.save('{0}.xlsx'.format(name))
Python using re module to parse an imported text file Question: def regexread(): import re result = '' savefileagain = open('sliceeverfile3.txt','w') #text=open('emeverslicefile4.txt','r') text='09,11,14,34,44,10,11, 27886637, 0\n561, Tue, 5,Feb,2013, 06,25,31,40,45,06,07, 19070109, 0\n560, Fri, 1,Feb,2013, 05,21,34,37,38,01,06, 13063500, 0\n559, Tue,29,Jan,2013,' pattern='\d\d,\d\d,\d\d,\d\d,\d\d,\d\d,\d\d' #with open('emeverslicefile4.txt') as text: f = re.findall(pattern,text) for item in f: print(item) savefileagain.write(item) #savefileagain.close() The above function as written parses the text and returns sets of seven numbers. I have three problems. 1. Firstly the 'read' file which contains exactly the same text as text='09,...etc' returns a `TypeError expected string or buffer`, which I cannot solve even by reading some of the posts. 2. Secondly, when I try to write results to the 'write' file, nothing is returned and 3. thirdly, I am not sure how to get the same output that I get with the print statement, which is three lines of seven numbers each which is the output that I want. This is the first time that I have used regex, so be gentle please! Answer: This should do the trick, check comments for explanation about what Im doing here =) Good luck import re filename = 'sliceeverfile3.txt' pattern = '\d\d,\d\d,\d\d,\d\d,\d\d,\d\d,\d\d' new_file = [] # Make sure file gets closed after being iterated with open(filename, 'r') as f: # Read the file contents and generate a list with each line lines = f.readlines() # Iterate each line for line in lines: # Regex applied to each line match = re.search(pattern, line) if match: # Make sure to add \n to display correctly when we write it back new_line = match.group() + '\n' print new_line new_file.append(new_line) with open(filename, 'w') as f: # go to start of file f.seek(0) # actually write the lines f.writelines(new_file)
Can't get OpenCV to work with Python on a Mac Question: I am having trouble getting OpenCV to work with Python on my Mac. I have tried installing it with MacPorts and with Cmake (which I installed from MacPorts) using the methods found at here: <http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port>. I also had to download Xcode to make MacPorts work. I ran `sudo port -v install opencv +python27` and it seemed to work fine. However when I tried to import OpenCV in Python using `import cv`, the module could not be found. If any of this information helps, I have OSX 10.6.8 Snow Leopard, python 2.7.3, and am trying to install OpenCV 2.4.3. I am not a very experienced programmer so my troubleshooting attempts are falling short of a solution. Any help is appreciated. Thanks! Answer: I haven't tried the MacPorts installation, but you might want to try this: import cv2 from cv2.cv import *
Cant add image to Tkinter Listbox Question: I'm trying to add an image to a Listbox, but instead of the image I see an entry called "pyimage1" in the Listbox. I've successfully displayed images using the Text and Label widgets, but I can't figure out the Listbox widget. I checked the documentation but it doesn't indicate how to properly update a Listbox with an image. What is the best method to add an image as a Listbox entry? Here is what I've tried so far: #!/usr/bin/python # test: lb_and_jpg.py from Tkinter import * from PIL import Image, ImageTk import os my_image_file = os.getcwd() + r'\logo.jpg' class MainApp: def __init__(self, parent): self.myParent = parent self.main_container = Frame(parent) self.main_container.grid(row=0, rowspan=10, column=0, columnspan=20) # Defining frames self.left_frame = Frame(self.main_container) self.left_frame.grid(row=0, rowspan=10, column=0, columnspan=5) self.right_frame = Frame(self.main_container) self.right_frame.grid(row=0, rowspan=10, column=6, columnspan=14) self.left_listbox = Listbox(self.left_frame, height=10, width=5) self.left_listbox.grid(row=0, column=0) self.right_listbox = Listbox(self.right_frame, height=10, width=14) self.right_listbox.grid(row=0, column=0) my_img = Image.open(my_image_file) my_image = ImageTk.PhotoImage(my_img) self.right_listbox.insert(END, my_image) root = Tk() root.title("ListBox and JPG") mainapp = MainApp(root) root.mainloop() Answer: You cannot add images to the listbox. You will need to use another widget, such as the ttk.Treeview widget.
list intersection algorithm implementation only using python lists (not sets) Question: I've been trying to write down a list intersection algorithm in python that takes care of repetitions. I'm a newbie to python and programming so forgive me if this sounds inefficient, but I couldn't come up with anything else. Here, L1 and L2 are the two lists in question, and L is the intersection set. 1. Iterate through L1 2. Iterate through L2 3. If element is in L1 and in L2 4. add it to L 5. remove it from L1 and L2 6. iterate through L 7. add elements back to L1 and L2 I'm 100% sure this is not the algorithm used within Mathematica to evaluate list intersection, but I can't really come up with anything more efficient. I don't want to modify L1 and L2 in the process, hence me adding back the intersection to both lists. Any ideas? I don't want to make use of any built in functions/data types other than lists, so no import sets or anything like that. This is an algorithmic and implementation exercise, not a programming one, as far as I'm concerned. Answer: How about: 1. Iterate though L1 2. Iterate though L2 3. If (in L1 and L2) and not in L -> add to L Not particularly efficient, but in code it would look something like this (with repetitions to make the point): >>> L1 = [1,2,3,3,4] >>> L2 = [2,3,4,4,5] >>> L = list() >>> for v1 in L1: for v2 in L2: if v1 == v2 and v1 not in L: L.append(v1) >>> L [2,3,4] You avoid deleting from L1 and L2 simply by checking if the element is already in L and adding to L if it is not. Then it doesn't matter if there are repetitions in L1 and L2.
Modifying logging message format based on message logging level in Python3 Question: I asked this question for python 2 [here](http://stackoverflow.com/questions/1343227/can-pythons-logging-format- be-modified-depending-on-the-message-log-level), but bumped into the issue again when the the answer no longer worked for Python 3.2.3. Here's code that works on Python 2.7.3: import logging # Attempt to set up a Python3 logger than will print custom messages # based on each message's logging level. # The technique recommended for Python2 does not appear to work for # Python3 class CustomConsoleFormatter(logging.Formatter): """ Modify the way DEBUG messages are displayed. """ def __init__(self, fmt="%(levelno)d: %(msg)s"): logging.Formatter.__init__(self, fmt=fmt) def format(self, record): # Remember the original format format_orig = self._fmt if record.levelno == logging.DEBUG: self._fmt = "DEBUG: %(msg)s" # Call the original formatter to do the grunt work result = logging.Formatter.format(self, record) # Restore the original format self._fmt = format_orig return result # Set up a logger my_logger = logging.getLogger("my_custom_logger") my_logger.setLevel(logging.DEBUG) my_formatter = CustomConsoleFormatter() console_handler = logging.StreamHandler() console_handler.setFormatter(my_formatter) my_logger.addHandler(console_handler) my_logger.debug("This is a DEBUG-level message") my_logger.info("This is an INFO-level message") A run using Python 2.7.3: tcsh-16: python demo_python_2.7.3.py DEBUG: This is a DEBUG-level message 20: This is an INFO-level message As far as I can tell, conversion to Python3 requires only a slight mod to CustomConsoleFormatter.**init**(): def __init__(self): super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=None, style='%') On Python 3.2.3: tcsh-26: python3 demo_python_3.2.3.py 10: This is a DEBUG-level message 20: This is an INFO-level message As you can see, my desire to replace '10' with 'DEBUG' is being thwarted. I've tried digging around in Python3 source and it looks like the PercentStyle instantiation is clobbering self._fmt after I, well, clobber it myself. My logging chops stop just short of being able to work around this wrinkle. Can anyone recommend another way or perhaps point out what I'm overlooking? Answer: With a bit of digging, I was able to modify the Python 2 solution to work with Python 3. In Python2, it was necessary to temporarily overwrite `Formatter._fmt`. In Python3, support for multiple format string types requires us to temporarily overwrite `Formatter._style._fmt` instead. # Custom formatter class MyFormatter(logging.Formatter): err_fmt = "ERROR: %(msg)s" dbg_fmt = "DBG: %(module)s: %(lineno)d: %(msg)s" info_fmt = "%(msg)s" def __init__(self): super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=None, style='%') def format(self, record): # Save the original format configured by the user # when the logger formatter was instantiated format_orig = self._style._fmt # Replace the original format with one customized by logging level if record.levelno == logging.DEBUG: self._style._fmt = MyFormatter.dbg_fmt elif record.levelno == logging.INFO: self._style._fmt = MyFormatter.info_fmt elif record.levelno == logging.ERROR: self._style._fmt = MyFormatter.err_fmt # Call the original formatter class to do the grunt work result = logging.Formatter.format(self, record) # Restore the original format configured by the user self._style._fmt = format_orig return result And here is Halloleo's example of how to use the above in your script (from the [Python2 version of this question](http://stackoverflow.com/questions/1343227/can-pythons-logging- format-be-modified-depending-on-the-message-log-level)): fmt = MyFormatter() hdlr = logging.StreamHandler(sys.stdout) hdlr.setFormatter(fmt) logging.root.addHandler(hdlr) logging.root.setLevel(DEBUG)
whitespaces in the path of windows filepath Question: I am working on file operations using python. I have a filepath as : filepath = "E:/ABC/SEM 2/testfiles/all.txt" when I am opening the file using python, it says me : IOError: No such file: but, the file is present on the drive. It may be because windows cannnot take "SEM 2" properly as it contains space. How can I deal with such whitespaces in the path of window path? Answer: There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi 32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> >>> os.makedirs("C:/ABC/SEM 2/testfiles") >>> open("C:/ABC/SEM 2/testfiles/all.txt","w") <open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420> >>> exit() C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles" Volume in drive C has no label. Volume Serial Number is 46A0-BB64 Directory of c:\ABC\SEM 2\testfiles 13/02/2013 10:20 PM <DIR> . 13/02/2013 10:20 PM <DIR> .. 13/02/2013 10:20 PM 0 all.txt 1 File(s) 0 bytes 2 Dir(s) 78,929,309,696 bytes free C:\Users\Gnibbler>
About handling a redirection in python Question: I am new to python and am trying to learn some new modules. Fortunately or unfortunately, I picked up the urllib2 module and started using it with one URL that's causing me problems. To begin with, I created the Request object and then called Read() on the response object. It was failing. Turns out its getting redirected but the error code is still 200. Not sure what's going on. Here is the code -- def get_url_data(url): print "Getting URL " + url user_agent = "Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 Firefox/14.0.1" headers = { 'User-Agent' : user_agent } request = urllib2.Request(url, str(headers) ) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: print response.geturl() print response.info() print response.getcode() return False; else: print response print response.info() print response.getcode() print response.geturl() return response I am calling the above function with <http://www.chilis.com>". I was expecting to receive a 301, 302, or 303 but instead I see 200. Here is the response I see -- Getting URL http://www.chilis.com <addinfourl at 4354349896 whose fp = <socket._fileobject object at 0x1037513d0>> Cache-Control: private Server: Microsoft-IIS/7.5 SPRequestGuid: 48bbff39-f8b1-46ee-a70c-bcad16725a4d X-SharePointHealthScore: 0 X-AspNet-Version: 2.0.50727 X-Powered-By: ASP.NET MicrosoftSharePointTeamServices: 14.0.0.6120 X-MS-InvokeApp: 1; RequireReadOnly Date: Wed, 13 Feb 2013 11:21:27 GMT Connection: close Content-Length: 0 Set-Cookie: BIGipServerpool_http_chilis.com=359791882.20480.0000; path=/ 200 http://www.chilis.com/(X(1)S(q24tqizldxqlvy55rjk5va2j))/Pages/ChilisVariationRoot.aspx?AspxAutoDetectCookieSupport=1 Can someone explain what this URL is and how to handle this? I know I can use the "Handling Redirects" section from Diveintopython.net but there also with the code on that page I see the same response 200. EDIT: Using the code from DiveintoPython, I see its a temporary redirection. What I don't understand is why the HTTP Errorcode from code is 200. Isn't that supposed to be the actual return code? EDIT2: Now that I see it better, its not a weird redirection at all. I am editing the title. EDIT3: If urllib2 follows the redirection automatically, I am not sure why the following code does not get the front page for chilis.com. docObj = get_url_data(url) doc = docObj.read() soup = BeautifulSoup(doc, 'lxml') print(soup.prettify()) If I use the URL that the browser eventually ends up getting redirected to it works (<http://www.chilis.com/EN/Pages/home.aspx>"). Answer: `urllib2` automatically follows redirects, so the information you're seeing is from the page that was redirected to. If you don't want it to follow redirect, you'll need to subclass `urllib2.HTTPRedirectHandler`. Here's a relevant SO posting on how to do that: [How do I prevent Python's urllib(2) from following a redirect](http://stackoverflow.com/questions/554446/how-do-i-prevent-pythons- urllib2-from-following-a-redirect/554580#554580) Regarding EDIT 3: it looks like `www.chilis.com` requires accepting cookies. This can be implemented using `urllib2`, but I would suggest installing the `requests` module (<http://pypi.python.org/pypi/requests/>). The following seems to do exactly what you want (without any error handling): import requests r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') print(soup.prettify())
Python - Parse float string to an integer Question: I want to convert a string like "0.75" into 3/4. Do python has any builtin function for this. I know i can convert it using float("0.75") to get a float value. But I need only integer number without loosing resolution. I can write a function like multiplying it by 100, so I will get 75/100, but still how to evaulate to 3/4. Any idea would be much appreciated. Answer: >>> from fractions import Fraction >>> Fraction(0.75) Fraction(3, 4) See the [docs](http://docs.python.org/2/library/fractions.html). One caveat: Non-binary fractions (i.e. fractions derived from [floating point numbers that cannot be represented accurately in binary](http://docs.python.org/2/tutorial/floatingpoint.html), like `0.9`) may yield surprising results unless you pass the string representation of the `float`: >>> Fraction(0.9) Fraction(8106479329266893, 9007199254740992) >>> Fraction("0.9") Fraction(9, 10)
Importing Sets in python Question: When I am trying to use sets it's showing that there is nothing named set. from sets import set > ImportError: cannot import name set How do I fix it? Answer: You don't _need_ to import the [`sets` module](http://docs.python.org/2/library/sets.html); sets are built in now. Just use the built-in [`set()` type](http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset) instead: >>> set() set([]) You can use the `{1, 2, 3}` set literal syntax too: >>> {1, 2, 3} set([1, 2, 3]) If you want to use the slower `sets` module anyway, the object is called `Set` with a capital `S`: >>> from sets import Set but note that the module has been deprecated; using it does not add anything over the built-in types. The module has been removed altogether in Python 3.
inheriting numpy.vectorize-ed functions Question: While hunting down an obscure bug, I've stumbled onto something best demonstrated by this minimal example: import numpy as np class First(object): def __init__(self): self.vF = np.vectorize(self.F) print "First: vF = ", self.vF def F(self, x): return x**2 class Second(First): def __init__(self): super(Second, self).__init__() print "Second: vF = ", self.vF def F(self, x): raise RuntimeError("Never be here.") def vF(self, x): return np.asarray(x)*2 I'd expect that an instance of the `Second` would have an explicitly defined `vF` method, but that does not seem to be the case: arg = (1, 2, 3) f = First() print "calling first.vF: ", f.vF(arg) s = Second() print "calling second.vF: ", s.vF(arg) produces First: vF = <numpy.lib.function_base.vectorize object at 0x23f9310> calling first.vF: [1 4 9] First: vF = <numpy.lib.function_base.vectorize object at 0x23f93d0> Second: vF = <numpy.lib.function_base.vectorize object at 0x23f93d0> calling second.vF: Traceback (most recent call last): ... RuntimeError: Never be here. so that it seems that `s.vF` and `f.vF` is the same object, even though `s.vF == f.vF` is `False`. Is this an expected/known/documented behavior, and `numpy.vectorize` does not play nicely with inheritance, or am I missing something simple here? (sure, in this particular case the problem is easy to fix by either changing `First.vF` to a normal Python method, or just not calling `super` in the `Second`'s constructor.) Answer: This has nothing to do with NumPy. It is a consequence of the interaction of perfectly reasonable language design decisions (and the way you decided to use the language): * Instance attributes take precedence over class attributes. I'm sure you'll agree that this is reasonable. * Methods are class attributes, and not special at that. I'm sure you'll agree that this is reasonable (if you don't, look into descriptors, specifically bound methods which allows `self.F` to work). * Inherited instance attributes are attached to the same object, not to some weird "parent proxy" object or something. I'm sure you'll agree that this is reasonable. In combination, these perfectly reasonable behaviors may yield unexpected behavior, if you do not keep the details in mind and instead work with a simplified mental model (e.g. mentally segregating methods and "data" attributes). In detail, this happens in your example: * The respective constructor is called. This is either `First.__init__`, or `Second.__init__` which immediately calls `First.__init__`. * Therefore, `obj.vF` is _always_ the vectorized function created in `First.__init__` for all `obj`. * However, each object's vectorized function wraps the `self.F` of the respective object. In the case of the second object, this is the `RuntimeError`-raising `Second.F`. You should probably just use a regular `vF` method here, as this allows easy overriding by subclasses, due to the way attribute lookup works (see also: MRO).
Append several variables to a list in Python Question: I want to append several variables to a list. The number of variables varies. All variables start with "volume". I was thinking maybe a wildcard or something would do it. But I couldn't find anything like this. Any ideas how to solve this? Note in this example it is three variables, but it could also be five or six or anything. volumeA = 100 volumeB = 20 volumeC = 10 vol = [] vol.append(volume*) Answer: You can use `extend` to append any iterable to a list: vol.extend((volumeA, volumeB, volumeC)) Depending on the prefix of your variable names has a bad code smell to me, but you can do it. (The order in which values are appended is undefined.) vol.extend(value for name, value in locals().items() if name.startswith('volume')) If order is important (IMHO, still smells wrong): vol.extend(value for name, value in sorted(locals().items(), key=lambda item: item[0]) if name.startswith('volume'))
How do I correctly close a pipe shared by two processes? Question: I'm attempting to use pipes to communicate between processes in python. These processes will be called from different threads, and so may not have direct access to the `Popen` object for each process. I've written script below, as a simple proof of concept, but have found that my recieving process never terminates. import os import subprocess import traceback import shlex if __name__ == '__main__': (fd_out, fd_in) = os.pipe() pipe_in = os.fdopen(fd_in, 'w') pipe_out = os.fdopen(fd_out, 'r') file_out = open('outfile.data', 'w+') cmd1 = 'cat ' + ' '.join('parts/%s' % x for x in sorted(os.listdir('parts'))) cmd2 = 'pbzip2 -d -c' pobj1 = subprocess.Popen(shlex.split(cmd1), stdout=pipe_in) pobj2 = subprocess.Popen(shlex.split(cmd2), stdin=pipe_out, stdout=file_out) print 'closing pipe in' pipe_in.close() print 'closing pipe out' pipe_out.close() print 'closing file out' file_out.close() print 'waiting on process 2' pobj2.wait() print 'done' This runs correctly in many ways. The data chunks get piped to the 2nd process, and the 2nd process decompresses the stream and writes it to a file. I can watch the processes until they seem to be just waiting (and doing nothing), terminate the 2nd process, and the file seems to be completely written. So, I'm wondering why the 2nd process never terminates. It seems that it never realizes that the input stream has been closed. How do I close the pipe properly, so that the process knows to terminate? david_clymer@zapazoid:/home/tmp/db$ python test.py closing pipe in closing pipe out closing file out waiting on process 2 ^Z [1]+ Stopped python test.py david_clymer@zapazoid:/home/tmp/db$ bg [1]+ python test.py & david_clymer@zapazoid:/home/tmp/db$ jobs -l [1]+ 31533 Running python test.py & david_clymer@zapazoid:/home/tmp/db$ ps -fp 31533 UID PID PPID C STIME TTY TIME CMD 1000 31533 22536 0 15:22 pts/2 00:00:00 python test.py david_clymer@zapazoid:/home/tmp/db$ lsof |grep $(pwd) bash 3432 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db bash 22536 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db python 31533 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31536 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31536 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31537 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31537 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31538 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31538 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31539 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31539 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31540 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31540 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31541 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31541 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31542 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31542 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31543 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31543 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data pbzip2 31535 31544 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db pbzip2 31535 31544 david_clymer 1u REG 253,3 12255300000 397270 /home/tmp/db/outfile.data lsof 31599 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db grep 31600 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db lsof 31602 david_clymer cwd DIR 253,3 483328 408117 /home/tmp/db david_clymer@zapazoid:/home/tmp/db$ strace -p 31533 Process 31533 attached - interrupt to quit wait4(31535, ^C <unfinished ...> Process 31533 detached I imagine I am doing something stupid. I'd like to know what, and why. Answer: The second process is probably inheriting the input end of the pipe, which therefore never gets closed. I'm not a Python expert, but perhaps it's possible to avoid this is by `Popen`ing the second process first with a `stdin=PIPE`, then `Popen` the first process with the second processes's `.stdin` as its `stdout`. (`Popen` probably arranges for the process not to have a handle to the input end of the pipe that it creates internally.) In order to work around the file descriptor inheritance, call subprocess using `close_fds=True`: pobj2 = subprocess.Popen(shlex.split(cmd2), stdin=pipe_out, stdout=file_out, close_fds=True)