text
stringlengths
226
34.5k
Python convert a list of strings in a nested list to list Question: I have a variable called last_price which outputs: SPY Date 2015-02-02 00:00:00+00:00 201.92 I want to extend last_price to a shape of 1000,1 using the following code: lp_list=[] lp_len=np.ones(1000) for o in lp_len: p=last_price lp_list.append(p) but print lp_list outputs: [ SPY Date 2015-02-02 00:00:00+00:00 201.92, SPY Date 2015-02-02 00:00:00+00:00 201.92, SPY Date 2015-02-02 00:00:00+00:00 201.92 etc... Regardless of what my final end use is, how can I convert lp_list to a flat list of the price string only (201.92)? When I try to flatted using a list comprehension I get the following: >>flat_lp = [y for x in lp_list for y in x] >>print flat_lp ...['SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', 'SPY', etc... Is there a way that I can create a flat list of just last_price variable with output of 201.92, repeated 1000 times, such as in the below: >>print lp_list ...[201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, etc... Two things to consider: 1) last_price is a dataframe type: <class 'pandas.core.frame.DataFrame'> 2) The elements in lp_list need to be float type integer Thanks Answer: If you just want to repeat your price you can just use `itertool.repeat` , so you dont need loops , you can split the string then pick the last element with `[-1]` indexing : >>> s=""" SPY ... Date ... 2015-02-02 00:00:00+00:00 201.92""" >>> s.split() ['SPY', 'Date', '2015-02-02', '00:00:00+00:00', '201.92'] >>> from itertools import repeat >>> repeat(s.split()[-1],10) repeat('201.92', 10) >>> list(repeat(float(s.split()[-1]),10)) [201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92, 201.92]
Install cartopy using pip on mac os and macports Question: I am trying to install [`cartopy`](http://scitools.org.uk/cartopy/) on OS X 10.10 (Yosemite). My python is installed using macports and when I run: sudo pip install cartopy I get the following error: /usr/bin/clang -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -pipe -Os -I/opt/local/Library/Frameworks/Python.framework/Versions/3.4/include -I./lib/cartopy -I/opt/local/Library/Frameworks/Python.framework/Versions/3.4/include/python3.4m -c lib/cartopy/trace.cpp -o build/temp.macosx-10.10-x86_64-3.4/lib/cartopy/trace.o lib/cartopy/trace.cpp:236:10: fatal error: 'geos_c.h' file not found #include "geos_c.h" ^ 1 error generated. error: command '/usr/bin/clang' failed with exit status 1 ---------------------------------------- Command "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip-build-hwrcv0a1/cartopy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ytar95bq-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-hwrcv0a1/cartopy Note that I installed the dependencies as noted [here](http://scitools.org.uk/cartopy/docs/latest/installing.html#installing) and `geos_c.h` can be found in `/opt/local/include`. It seems like `pip` fails to find this dependency in the `macports` tree. Did anyone experienced this kind of problem? How can I fix it? This question was also raised as an issue at <https://github.com/SciTools/cartopy/issues/535>. Answer: There was recently a bit of work to improve the `pip install cartopy` experience. Would you mind trying it again with cartopy v0.12.0. See <https://github.com/SciTools/cartopy/issues/610> for reference.
Python: Only saving three latest scores Question: This is my short quiz made for children. The main body of the program works fine. But it must save the three latest `correctAnswers` for each user onto a `.txt` file, deleting the old scores. I've spent quite some time trying to work out how to use JSON or Pickle for my code but I have no idea how to use them for my code. Any help will be appreciated. if usersGroup == a: with open("groupA.txt","a+") as f: f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) elif usersGroup == b: with open("groupB.txt","a+") as f: f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) elif usersGroup == c: with open("groupC.txt","a+") as f: f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) else: print("Sorry, we can not save your data as the group you entered is not valid.") Answer: You need to overwrite not append if you are updating the three scores at once: open("groupA.txt","w") To keep the last two from the previous run and write the latest single score: with open("groupA.txt","a+") as f: sores = f.readlines()[-2:] # get last two previous lines with open("groupA.txt","w") as f: # write previous 2 f.writelines(scores) # write latest f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) Might be easier pickle or json a dict and keep a list of scores replacing the last score with the latest. import pickle from collections import defaultdict with open('scores.pickle', 'ab') as f: try: scores = pickle.load(f) except ValueError: scores = defaultdict(list) # do your logic replacing last score for each name or adding names with open('scores.pickle', 'wb') as f: # pickle updated dict pickle.dump(f,scores) If you want human readable format use `json.dump` and a normal dict, you can use dict.setdefault instead of the functionality of using a defaultdict: import json with open('scores.json', 'a') as f: try: scores = json.load(f) except ValueError: scores = {} # add user if not already in the dict with a list as a value scores.setdefault(name,[]) # just append the latest score making sure when you have three to relace the last scores[name].append(whatever) # do your logic replacing last score for each name or adding names with open('scores.json', 'w') as f: json.dump(scores,f)
Edit IPython cell in an external editor Question: It would be great to have a keyboard short-cut in IPython notebook, which would allow to edit the content of the current cell in an external editor (e.g. gvim). Maybe just copy the content of the current cell into a temporary file, launch gvim on it, and update the current cell each time the file is saved (and delete the temporary file when exiting gvim). Also, maybe update the temporary file if the cell is edited from the browser, so that gvim knows the file has changed. I am aware of projects like vim-ipython and ipython-vimception, but they don't correspond to my needs. I think the browser is enough for simple things, but when more powerful editing is required there is no need to reinvent the wheel. Do you know if such a feature exists in IPython notebook already? Thanks. Answer: This is what I came up with. I added 2 shortcuts: * 'g' to launch gvim with the content of the current cell (you can replace gvim with whatever text editor you like). * 'u' to update the content of the current cell with what was saved by gvim. So, when you want to edit the cell with your preferred editor, hit 'g', make the changes you want to the cell, save the file in your editor (and quit), then hit 'u'. Just execute this cell to enable these features: %%javascript IPython.keyboard_manager.command_shortcuts.add_shortcut('g', { handler : function (event) { var input = IPython.notebook.get_selected_cell().get_text(); var cmd = "f = open('.toto.py', 'w');f.close()"; if (input != "") { cmd = '%%writefile .toto.py\n' + input; } IPython.notebook.kernel.execute(cmd); cmd = "import os;os.system('gvim .toto.py')"; IPython.notebook.kernel.execute(cmd); return false; }} ); IPython.keyboard_manager.command_shortcuts.add_shortcut('u', { handler : function (event) { function handle_output(msg) { var ret = msg.content.text; IPython.notebook.get_selected_cell().set_text(ret); } var callback = {'output': handle_output}; var cmd = "f = open('.toto.py', 'r');print(f.read())"; IPython.notebook.kernel.execute(cmd, {iopub: callback}, {silent: false}); return false; }} );
yum install firefox error - libnssutil3.so Question: I'm getting this error while installing/listing **firefox** or **python** on a Linux server. Any ideas how to fix it. # yum install firefox There was a problem importing one of the Python modules required to run yum. The error leading to this problem was: /usr/lib64/libnssutil3.so: undefined symbol: PL_ClearArenaPool Please install a package which provides this module, or verify that the module is installed correctly. It's possible that the above module doesn't match the current version of Python, which is: 2.4.3 (#1, Oct 23 2012, 22:02:41) [GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] If you cannot solve this problem yourself, please go to the yum faq at: http://wiki.linux.duke.edu/YumFaq Instead of getting the following output/value for firefox -version command. $ firefox --version Mozilla Firefox 17.0.9 **I'm getting:** XPCOMGlueLoad error for file /opt/firefox/libxpcom.so: libxul.so: cannot open shared object file: No such file or directory Couldn't load XPCOM. _python -h_ command output looks valid. python -V shows: Python 2.4.3 When I'm running Selenium tests (which requires firefox and Xvfb), I get the following error: org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output: XPCOMGlueLoad error for file /opt/firefox/libxpcom.so: libxul.so: cannot open shared object file: No such file or directory Couldn't load XPCOM. XPCOMGlueLoad error for file /opt/firefox/libxpcom.so: libxul.so: cannot open shared object file: No such file or directory Couldn't load XPCOM. Answer: The problem is not python, it’s the LD_LIBRARY_PATH that does not include /lib64 and /usr/lib64 setting values. we fixed this by pre-pending /lib64:/usr/lib64 to the LD_LIBRARY_PATH. export LD_LIBRARY_PATH=/usr/lib64/:/lib64:$LD_LIBRARY_PATH After this point, when I did yum help or yum install firefox (it didn't give the above error) BUT: **firefox --version** still gave the error: XPCOMGlueLoad error for file /opt/firefox/libxpcom.so: libxul.so: cannot open shared object file: No such file or directory Couldn't load XPCOM. Now, I finally ran "yum install firefiox" and it downloaded/installed bunch of components and at the end said: Installing : alsa-lib 20/23 Installing : xulrunner 21/23 Installing : firefox 22/23 Installing : firefox 23/23 Installed: firefox.i386 0:17.0.9-1.el5_9 firefox.x86_64 0:17.0.9-1.el5_9 Dependency Installed: GConf2.i386 0:2.14.0-9.el5 ORBit2.i386 0:2.14.3-5.el5 alsa-lib.i386 0:1.0.17-1.el5 atk.i386 0:1.12.2-1.fc6 avahi.i386 0:0.6.16-10.el5_6 avahi-glib.i386 0:0.6.16-10.el5_6 cairo.i386 0:1.2.4-5.el5 cups-libs.i386 1:1.3.7-30.el5_9.3 gamin.i386 0:0.1.7-10.el5 gnome-vfs2.i386 0:2.16.2-12.el5_9 gnutls.i386 0:1.4.1-10.el5_9.2 gtk2.i386 0:2.10.4-29.el5 libIDL.i386 0:0.8.7-1.fc6 libXcursor.i386 0:1.1.7-1.2 libXfixes.i386 0:4.0.1-2.1 libXinerama.i386 0:1.0.1-2.1 libXrandr.i386 0:1.1.1-3.3 libacl.i386 0:2.2.39-8.el5 libattr.i386 0:2.4.32-1.1 pango.i386 0:1.14.9-8.el5_7.3 xulrunner.i386 0:17.0.9-1.el5_9 Complete! Now firefox version is showing correctly. **firefox --version** Mozilla Firefox 17.0.9 Everything is working now.
Parallel: Run for loop in Python Question: I want to make my coed run in Parallel, which is shown as below, for j in range(nj): for i in range(ni): # assign matrix coefficient This is a very large matrix, which results in very low execution time, how can I run this kind of code in Parallel? Thanks in advance! Answer: You probably looking for `multiprocessing` module. import multiprocessing import random import time def f(x,y): print multiprocessing.current_process() time.sleep(random.random()) return x*y p = multiprocessing.Pool(10) res= [] for i in xrange(1,10): for j in xrange(1,10): res.append(p.apply_async(f, [i,j])) for r in res: print r.get()
Translation Using Dictionaries (Python) Question: Alright so my teacher gave me the assignment below, and we have only been working with dictionaries for about a day: 1) Create a dictionary to translate a sentence from one language to another (such as Spanish to English). 2) The program should then write a sentence in the first language, then in the second language. So far, my code is this: def userinput(): inputsentence = input("What sentence would you like to translate?(Hint! Make the sentence I speak _ more than my friends") spanoreng = input("Is this sentence Spanish or English?(Please enter span or eng") return(inputsentence,spanoreng) def spantoeng(spantoengtras,inputsentence): inputsentence.lower() inputsentence.split() print(inputsentence) def engtospan(engtospantrans,inputsentence): inputsentence.lower() inputsentence.split() print(inputsentence) def main(): spantoengtrans = {'yo' : 'I', 'hablo' : 'speak', 'espanol' : 'spanish', 'ingles' : 'english', 'mas' : 'more', 'de' : 'than','mis' : 'my', 'amigos' : 'friends'} engtospantrans = {'I' : 'yo', 'speak' : 'hablo', 'spanish' : 'espanol', 'english' : 'ingles', 'more' : 'mas', 'than' : 'de','my' : 'mis', 'friends' : 'amigos'} (inputsentence,spanoreng) = userinput() if spanoreng == 'span': spantoeng(spantoengtrans,inputsentence) elif spanoreng == 'eng': engtospan(engtospantrans,inputsentence) else: print("please type span or eng") (inputsentence,spanoreng) = userinput() main() All I'm having trouble with is changing the list using the dictionary. Also, my .lower() seems to not be doing anything. help? EDIT: realized my mistake. thanks. Answer: I don't see **any** list -- I only see strings, which are immutable, and no use of the dictionary. So the core function could be: def translate(sentence, transdict): words = sentence.split() trans = [transdict.get(w.lower(),w) for w in words] print(' '.join(trans)) `split` makes the sentence into a list of whitespace-separated words; then the list comprehension makes it into a list of translated words (leaving words alone if they're not in the dictionary); finally we join the latter list back into a space-separated sentence. Of course this leaves a lot to be desired, but it's hard to do better without regular expressions -- and if you've been using dictionaries for just a day regular expressions may be well beyond your studies so far. In case they're not: import re def maketrans(somedict): def trans(mo): word = mo.group() return somedict.get(word.lower(), word) return trans and then translated = re.sub(r'\w+', maketrans(right_dict), sentence) print (translated) will preserve punctuation and spacing. But what between RE's and higher order functions, I suspect you'd better ignore this one until later in your Python studies:-).
Finding the path for a Python module without importing it Question: How can I find the path for a Python module without importing it? It seems like it should be obvious but I can't find a function to do this. (Yes I double-checked the docs for `imp`). Note: I can't import the module. Also this is a python2 specific issue, so I can't use `importlib.find_loader`. * * * update per comment: In python3 this can be done with `importlib.find_loader` which returns an object with a `path` property, which works for packages and files (unlike `imp.find_module`). Answer: Something like this maybe: import imp print imp.find_module("mymodule")
Parsing Google Analytics API Python json response into python dataframe Question: Trying to parse Google Analytics API Python json response into python dataframe, and then ETL to MS SQL Server using python. I get a successful output called feed import json, gdata data_query = gdata.analytics.client.DataFeedQuery({ 'ids': 'ga:67981229', 'dimensions': 'ga:userType,ga:sessionCount,ga:source', ##ga:source,ga:medium 'metrics': 'ga:pageviews', ##'filters': 'ga:pagePath==/my_url_comes_here/', ##'segment':'', 'start-date': '2015-01-01', 'end-date': '2015-01-03', 'prettyprint': 'true', 'output':'json', }) feed = my_client.GetDataFeed(data_query) However, when I try to parse the the data using this code it doesn't work and I get the below error > > > response = json.parse(feed) ## I also tried json.load(feed) and > json.loads(feed) >>> >>> data = json.parse(feed) Traceback (most recent call last): File "", line 1, in data = json.parse(feed) AttributeError: 'module' object has no attribute 'parse' >>> >>> data = json.loads(feed) Traceback (most recent call last): File "", line 1, in data = json.loads(feed) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/**init**.py", line 338, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer >>> >>> data = json.load(feed) Traceback (most recent call last): File "", line 1, in data = json.load(feed) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/**init**.py", line 286, in load return loads(fp.read(), AttributeError: 'DataFeed' object has no attribute 'read' And I have already imported all of json as seen at the top, furthermore - my end objective is to ETL this to MS SQL Server - so any help on effective method to do this with a JSON Python object would help a LOT! Thanks! Answer: Instead of parsing the json response manually into a dataframe you could try using the Pandas library which has built in [methods](http://pandas.pydata.org/pandas- docs/version/0.15.2/remote_data.html#remote-data-ga) to query the Google Analytics API. Once you get your Google Analytics Metrics into a dataframe, you could insert records into SQL Server using the [to_sql](http://pandas.pydata.org/pandas- docs/version/0.15.2/generated/pandas.DataFrame.to_sql.html#pandas.DataFrame.to_sql) method.
How to bring Tkinter window in front of other windows? Question: I'm working with some Tkinter Python code (Python 3.4), and I've come across a problem. When I create my Tkinter window it doesn't show up in front. I do it currently with the following code: from tkinter import * win = Tk() win.minsize(width=1440, height=828) win.maxsize(width=1440, height=828) The `minsize()` and `maxsize()` make the window cover my entire screen, but the original python running window (The one that would`print("Hello, World!")`) ends up on top. Is there a way to fix this? I'm running OS X 10.10.1. Answer: Set it as the _topmost_ (but it will always stay in front of the others): win.attributes('-topmost', True) # note - before topmost To not make it _always_ in front of the others, insert this code before the mainloop: win.lift() win.attributes('-topmost', True) win.attributes('-topmost', False) Don't forget `win.mainloop()` at the end of your code (even if in some cases it's not explicitly required) Other discussions on the same problem: * [How to put a Tkinter window on top of the others](http://stackoverflow.com/questions/8691655/how-to-put-a-tkinter-window-on-top-of-the-others) * [Make Tkinter jump to the front](http://stackoverflow.com/questions/1892339/make-tkinter-jump-to-the-front)
Python - multiple list by a scalar Question: Refer to the question mentioned on this link [In Python how will you multiply individual elements of an array with a floating point or integer number?](http://stackoverflow.com/questions/8194959/in-python-how-will-you- multiply-individual-elements-of-an-array-with-a-floating) I use `import numpy as np`; then multiply a list with a flaoting number and stored the updated values in the same list. However, the new values are like [[array([ 10.])] ..... Now I want to remove array and use the list with the integer value. Answer: you want to turn the `np.array()` back to a list? import numpy as np P=2.45 S=[22, 33, 45.6, 21.6, 51.8] SP = P*np.array(S) SP_LIST =list(SP) As the post you link to also contains: [x * P for x in S] returns a list directly
Elasticsearch Percolator with python api Question: Hi I am trying to do a percolator index using "elasticsearch.py" api. But I am not even getting any results. The API documentation seems to have 3 or 4 functions related to percolation. I have checked the following possibilities. can anyone be of some help , so that I can solve it. es = Elasticsearch() query = {'query': {'term': {'message': 'bonsai tree'}}} es.create(index='test', doc_type='message', percolate=query, id='kuku2', body = {"message":"bonsai tree"}) doc = {'doc': {'message': 'I am a bonsai tree'}} k = es.percolate(index='test', doc_type='type1', body=doc) print k ###### Result ##### u'matches': [], u'total': 0, u'took': 0, u'_shards': {u'successful': 1, u'failed': 0, u'total': 1}} I hope "es.percolate" is used for searching. "es.create" allows us to register documents as percolate index. But it is not so perfectly mentioned in the documentation. ".percolate" have also used in the place of index. Please help. Answer: The following piece of text works for me (on ES 1.4.4). The key point seems to be the use of `doc_type='.percolator'` in `es.create`. from elasticsearch import Elasticsearch from elasticsearch.client.indices import IndicesClient es = Elasticsearch() ies = IndicesClient(es) mapping = { "mappings": { "my-type": { "properties": { "content": { "type": "string" } } } } } ies.create(index='test_index', body=mapping) query = { "query": { "match": { "content": "python" } } } es.create(index='test_index', doc_type='.percolator', body=query, id='python') doc1 = {'doc': {'content': 'this is something about python'}} res = es.percolate("test_index", doc_type="my-type", body = doc1) print res # result: # {u'matches': [{u'_id': u'python', u'_index': u'test_index'}], u'total': 1, u'took': 3, u'_shards': {u'successful': 5, u'failed': 0, u'total': 5}} doc2 = {'doc': {'content': 'this is another piece of text'}} res = es.percolate("test_index", doc_type="my-type", body = doc2) print res # result: # {u'matches': [], u'total': 0, u'took': 2, u'_shards': {u'successful': 5, u'failed': 0, u'total': 5}}
Python3 Flask upload file in server memory Question: I'm using Flask in Python3 as a webserver, and am using the upload function of Flask. Uploading a file to the server results in a `werkzeug.datastructures.FileStorage` object. One of the functions I need this file in, also needs to be able to open files from path objects, so at the moment, I'm using `open(file_to_open)`. If possible, I would like to avoid writing the uploaded file to a temporary file, just to read it in again. So my question consists of two parts: 1: Would it be possible to "translate" this FileStorage object to a file object? 2: If so, would this also work on the current code (`open(file_to_open)`)? Answer: Incoming file uploads are indeed presented as `FileStorage` objects. However, this does _not_ necessarily mean that an actual physical file is involved. When parsing file objects, Werkzeug uses the `stream_factory()` callable to produce a file object. The default implementation only creates an actual physical file for file sizes of 500kb and over, to avoid eating up memory. For _smaller_ files an in-memory file object is used instead. I'd not tamper with this arrangement; as it works right now the issue is handled transparently and your harddisk is only involved when the file uploads would otherwise tax your memory too much. Rather, I'd alter that function to not require a filename and / or accept a file object. If your function can only take a path _or_ the contained data as a string, you can see if you need to read the file by introspecting the underlying `.stream` attribute: from werkzeug._compat import BytesIO filename = data = None if file_upload.filename is None: data = file_upload.read() # in-memory stream, so read it out. else: filename = file_upload.filename
Persist Read-Only Data Across Jobs via Python Multiprocessing Process Subclass Question: I am using the [Python multiprocessing module](https://docs.python.org/2/library/multiprocessing.html) and am looking for a way to attach read only data once when the process is constructed. I want this data to persist across multiple jobs. I planned to subclass Process and attach data to the class, something like this: import multiprocessing class Worker(multiprocessing.Process): _lotsofdata = LotsOfDataHolder() def run(self, arg): do something with _lotsofdata return value if __name__ == '__main__': jobs = [] for i in range(5): p = Worker() jobs.append(p) p.start() for j in jobs: j.join() However, the number of jobs is on the order of 500k so I would rather use the Pool construct and I don't see a way to tell Pool to use a subclass of process. Is there a way to tell Pool to use a subclass of Process or is there another way to persist data on a worker for multiple jobs that works with Pool? Note: There is along explanation [here](http://stackoverflow.com/questions/659865/python-multiprocessing- sharing-a-large-read-only-object-between-processes), but subclassing process was not specifically discussed. *I see now that the args are passed to the process constructor. This makes my approach all the more unlikely. Answer: As [explained in this answer](http://stackoverflow.com/a/659888/1595865), **multiple processes don't share the same memory space**. This makes statements like `persist data on a worker for multiple jobs` meaningless: there's no way for a worker to access any other worker's data. What multiprocessing _can_ do is **copying** the same initial data over workers. This happens auto-magically: import multiprocessing _lotsofdata = [0]*1000 def run(arg): return arg+_lotsofdata[0] pool= multiprocessing.Pool() l=[1,2,3] print pool.map(run, l) * * * If you don't want to copy memory, you're left to implement your own (OS dependent) mechanism for sharing state between processes. There's several approaches for that outlined in the linked answer. Realistically, unless you're trying to do supercomputations on a cluster with dozens of CPUs, I'd think twice before going down that path.
RethinkDB import error Question: I'm trying to import CSV or JSON file to Rethink DB but I always get the same error: rethinkdb import -f ~/Downloads/convertcsv.json --table test.stats --format json [ ] 0% 0 rows imported in 1 table 'indexes' In file: /home/xxxxx/Downloads/convertcsv.json Errors occurred during import I don't see anything in logs and the same files import ok on my laptop. Import creates the table but that's about it. My system: \- List item \- Ubuntu 10.10 \- Python 2.7.8 \- rethinkdb 1.16.0+1~0utopic (GCC 4.9.1) Already tried to re-install RethinkDB, `sudo pip2 install --upgrade rethinkdb`. Not sure what else I can do. Answer: This appears to have been an oversight when adding export/import of secondary indexes - the import script is looking for the `indexes` field in the info, which doesn't exist when importing a single file. This can be worked around by providing the flag `--no-secondary-indexes`. A fix was released in the RethinkDB Python driver version `1.16.0-2`, see the Github issue [#3278](https://github.com/rethinkdb/rethinkdb/issues/3728) for details.
Python SocksiPy package error: TypeError: Type str doesn't support the buffer API for string? Question: When i try and connect to gmail through this code: import socks import imaplib import socket import socks s = socks.socksocket() s.setproxy(socks.PROXY_TYPE_HTTP, '192.168.208.51', 3128) s.connect(('imap.gmail.com', 993)) I get the error message: Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> s.connect(('imap.gmail.com', 993)) File "C:\Python34\lib\site-packages\socks.py", line 406, in connect self.__negotiatehttp(destpair[0],destpair[1]) File "C:\Python34\lib\site-packages\socks.py", line 357, in __negotiatehttp while resp.find("\r\n\r\n")==-1: TypeError: Type str doesn't support the buffer API Any ideas? Im on a computer that uses a proxy hence using SocksiPy to connect to imap.gmail.com Answer: There's nothing wrong with your code; you are using a version of SocksiPy that has not been ported to Python 3. You should upgrade to version 1.02. Or you should switch back to Python 2. * * * **Explaination:** This is Python 3. Unlike Python 2, `bytes` and `str` objects are not interchangeable. If you try to do stuff like this: >>> b'abc'.find('a') You'll get the error you are seeing. In fact, the "buffer API" is the one implemented by `bytes` objects.
Python: As date strings get passed into dictionary - values jumbled Question: As I pull the date data from my excel file on my computer which is listed as: "10/1/10" - and stored in an array `dData`, and the numerical version of the date is stored in `nData` as: `734046`, so when you call `dData[0]` it returns `"10/1/10"` and when you call `nData` it returns `734046`. HOWEVER The code in bold as I pass in 10/1/10 it returns 735536, which is not the exact key-value pair that it should be organized chronologically. import numpy as np import pandas as pd import xlrd import csv import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime import time import random import statistics import numpy from numpy.random import normal from scipy import stats dData = [] #Date in string format - Month/Day/Year pData = [] #Date in float format - Value.Decimals nData = [] #Data in Dates in int - Formatted Date Data for plotting in Matpl def loadData(dates, prices, numDates): dateDictionary = {} # empty dictionary that will contain string dates to number dates numDateToPrice = {} # empty dictionary that will contain number dates to string dates nestedDictionary = {} # empty dictionary that will contain a nested dictionary str date : {numbertodate: price} with open('/Users/dvalentin/Code/IndividualResearch/CrudeOilFuturesAll.csv', 'rU') as csvfile: #This is where I pull data from an excel file on my comp reader = csv.reader(csvfile, delimiter=',') for row in reader: dates.append(row[0]) numDates.append(row[1]) prices.append(row[2]) **for x in dates: for x in numDates: dateDictionary[x] = y print dateDictionary** for x in numDates[x]: for y in prices[y]: numDateToPrice[x] = y plt.plot_date(x=numDates, y=prices, fmt="r-") plt.plot() plt.title("Crude Oil Futures") plt.ylabel("Closing Price") plt.grid(True) plt.show() Answer: import pandas as pd import datetime as dt dates = ['10/1/10', '10/2/10','11/3/10','1/4/11'] prices = [12,15,13,18] df = pd.DataFrame({'dates':dates,'prices':prices}) df = df.set_index(pd.DatetimeIndex(df['dates'])) df = df.drop('dates', axis = 1) print df.ix['20101002'] print df['20101001':'20101002'] print df['2010'] print df['2010-10'] This seems to be a better way to organize your data instead of messing around with the numerical code for the date. You can always manipulate the datetimeindex for graphical parameters and style it out how you want. But this datetimeindex is much easier to manipulate data with instead of having to use dictionaries. More info on datetime indices: <http://pandas.pydata.org/pandas- docs/dev/generated/pandas.DatetimeIndex.html>. Hope this helps!
Python-Requests, extract url parameters from a string Question: I am using this awesome library called [`requests`](http://docs.python- requests.org/en/latest) to maintain python 2 & 3 compatibility and simplify my application requests management. I have a case where I need to parse a url and replace one of it's parameter. E.g: http://example.com?param1=a&token=TOKEN_TO_REPLACE&param2=c And I want to get this: http://example.com?param1=a&token=NEW_TOKEN&param2=c With the `urllib` I can achieve it this way: from urllib.parse import urlparse from urllib.parse import parse_qs from urllib.parse import urlencode url = 'http://example.com?param1=a&token=TOKEN_TO_REPLACE&param2=c' o = urlparse(url) query = parse_qs(o.query) if query.get('token'): query['token'] = ['NEW_TOKEN', ] new_query = urlencode(query, doseq=True) url.split('?')[0] + '?' + new_query >>> http://example.com?param2=c&param1=a&token=NEW_TOKEN How can you achieve the same using the `requests` library? Answer: You cannot use `requests` for this; the library **builds** such URLs if passed a Python structure for the parameters, but does not offer any tools to parse them. That's not a goal of the project. Stick to the `urllib.parse` method to parse out the parameters. Once you have a dictionary or list of key-value tuples, just pass that to `requests` to build the URL again: try: # Python 3 from urllib.parse import urlparse, parse_qs except ImportError: # Python 2 from urlparse import urlparse, parse_qs o = urlparse(url) query = parse_qs(o.query) # extract the URL without query parameters url = o._replace(query=None).geturl() if 'token' in query: query['token'] = 'NEW_TOKEN' requests.get(url, params=query) You can get both the `urlparse` and `parse_qs` functions in both Python 2 and 3, all you need to do is adjust the import location if you get an exception. Demo on Python 3 (without the import exception guard) to demonstrate the URL having been built: >>> from urllib.parse import urlparse, parse_qs >>> url = "http://httpbin.org/get?token=TOKEN_TO_REPLACE&param2=c" >>> o = urlparse(url) >>> query = parse_qs(o.query) >>> url = o._replace(query=None).geturl() >>> if 'token' in query: ... query['token'] = 'NEW_TOKEN' ... >>> response = requests.get(url, params=query) >>> print(response.text) { "args": { "param2": "c", "token": "NEW_TOKEN" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.5.1 CPython/3.4.2 Darwin/14.1.0" }, "origin": "188.29.165.245", "url": "http://httpbin.org/get?token=NEW_TOKEN&param2=c" }
Issues with logging on to a website with Python 2.7 requests Question: I am attempting to automatically log on to the William Hill Website (<http://sports.williamhill.com/bet/en-gb>) using the requests module for Python 2.7 import requests with requests.Session() as c: url = "https://sports.williamhill.com/bet/" Username = "blarxxx" PASSWORD = "blarxxx" r = c.get(url) Rcookies = r.cookies login_data = dict(username=Username, password=PASSWORD, action="DoLogin", target_page="http://sports.williamhill.com/bet/en-gb", tmp_username="Username") page1 = c.post(url,data=login_data, headers={"Referer" : "http://sports.williamhill.com/bet/en-gb/betting/t/295/English-Premier-League.html"}) print page1.content However, this does not log me on. I have reviewed the post data from Chrome's inspect element and there are two other variable posted, loginuid and ioBlackBoxCopy. I assumed that these would be provided by the site in a cookie however I have not been able to locate them. So you are aware the cookie information from <https://sports.williamhill.com/bet/> is as follows: <<class 'requests.cookies.RequestsCookieJar'>[<Cookie CSRF_COOKIE=c2962a27a04d24250b13 for .williamhill.com/>, <Cookie TS01b0a0b6=0148840b445dac7f6388fc9588136faf4ebdb641d2b4ba2c7e1c3eda9a7079782232d97eaad7893999b63092cda29c0e07ad6757dfa994c354e332e3abda1d2bbfd684a7edc8beb96d001cad8478ffc5e53ab684ffaa39ed82c91fb9b77f5c70f63f174ad9421f9daa69f1d8a3170251041bca95512cbfcf8eaa3b483e3659120e2fc4690c for .williamhill.com/>, <Cookie cust_lang=en-gb for .williamhill.com/>, <Cookie cust_login= for .williamhill.com/>, <Cookie cust_prefs=en|ODDS|form|TYPE|PRICE|||0|SB|0|0||0|en|0|TIME|TYPE|0|1||0||0|1|0||TYPE| for .williamhill.com/>, <Cookie TS017d04d1=0148840b4403f8c68f0800245a6bf453cfe0f084759d52c21d738abcb353a043964350398d for sports.williamhill.com/>]> I'm relatively new to the Requests module and to logging on to a website through python. I would be grateful if you could let me know if I am approaching this correctly and how I can obtain the additional inputs in my post request, if indeed they are needed. Many thanks J Answer: Did you try to see the source of WH in browser? There are two hidden fields - login_uid and action. May be it will be usefull to you? But I don't know if you will be able to download html at all because it is built by big js script which is loaded when you send request to WH. PS I'm trying to do the same and only WebDriver works for me.
Replace VBA's object "Empty" with pythoncom.Missing doesn't work Question: Few years ago I wrote script in Python to automate few tedious processes that I was doing in SolidWorks_2012. I was running that script on Win7 32 bit with python 27 32 bit and SolidWorks_2012 32 bit. Now, I faced exactly the same problem and I tried to use old script but on **OpenDoc6** (and on others functions, where **values pass by ref**) it raises exception: "Objects of type 'PyOleMissing' can not be converted to a COM VARIANT" Here is some sample that I can't make to work: import win32com.client as win32 import pythoncom sw = win32.Dispatch('SldWorks.Application') path_to_file = "some_path" sw_asm = sw.OpenDoc6(path_to_file, 2, 1, "", pythoncom.Missing, pythoncom.Missing) Here is some specification of this function from docs for VBA: Function OpenDoc6( _ ByVal FileName As System.String, _ ByVal Type As System.Integer, _ ByVal Options As System.Integer, _ ByVal Configuration As System.String, _ ByRef Errors As System.Integer, _ ByRef Warnings As System.Integer _ ) As ModelDoc2 As you can see two latest are passing by references. Also [here](http://stackoverflow.com/questions/19454804/pointer-callout-for- selectbyid2) is the same issue without any solution. And just in case this may be important, now I'm running win 8 64, python 27 32/64 and SolidWorks 2014 64. **Thank you in advance!** Answer: just insert empty variables. Had the same error in VBA where you had to pass variables declared as LONG or it would not work.
How to append a string at the end of each line of a string in python? Question: Let's say, one has stored the stdout of a shell command in a variable. Example for demonstration: #!/usr/bin/python import subprocess proc = subprocess.Popen(['cat', '--help'], stdout=subprocess.PIPE) output = proc.stdout.read() Variable `output` now holds content similar to this: Usage: cat [OPTION]... [FILE]... Concatenate FILE(s), or standard input, to standard output. ... For complete documentation, run: info coreutils 'cat invocation' How could one append something to each line besides the last line? So it looks like the following? Usage: cat [OPTION]... [FILE]...<br></br> Concatenate FILE(s), or standard input, to standard output.<br></br> ...<br></br> For complete documentation, run: info coreutils 'cat invocation' It would be possible to count the line numbers, to iterate through it, construct a new string and omit appending for the last line... But... Is there a simpler and more efficient way? Answer: _"append[ing] a string at the end of each line"_ is equivalent to replacing each newline with string + newline. Sooo: s = "Usage...\nConcatenate...\n...\nFor complete..." t = s.replace("\n", "<br><br>\n") print t
Index a Python DataFrame with two Conditions Question: I'm trying to get a subset of a DataFrame based on two conditions. Here my simplified example: import pandas as pd test = pd.DataFrame(np.ones(48),index = pd.date_range('2015-01-01',periods = 48, freq = '1800S')) I'd now like to get all values that are in the timerange t> 08:00 and t<22:00, thus I tried: result = test[test.index.hour>8 & test.index.hour<22] I then get the ValueError that the truth value of an array with more than one element is ambiguous, use a.any() or a.all() - and here I'm out of luck... . Answer: There are 2 simple solutions : * First: enclose your conditions into braces like `(test.index.hour > 8) & (test.index.hour<22)` due to operator & precedence * Second : use [the query function](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html)
Why doesn't python phonenumbers library work in this case? Question: It seems like '5187621769' should be a very easy number for the phonenumbers library to parse. It's 10 digits with a US area code. But...no luck. **Setup:** import phonenumbers number = '5187621769' **Method 1:** parsed = phonenumbers.parse(number) This throws an error. **Method 2:** parsed = phonenumbers.parse("+" + number) Gives country code = 51, which is not US. I know I can do: parsed = phonenumbers.parse(number,region="US") But I don't always know the number will be US (this is just one case where I discovered I wasn't getting desired behavior). Is there an option or formatting trick I'm missing? Thanks! Answer: It would a very easy number if phonenumbers was an US only library. You are missing the "+1" a.k.a. country code. If you would like to assume that numbers that phonenumbers can't parse are US numbers you could do something like: try: parsed = phonenumbers.parse(number) except phonenumbers.NumberParseException as npe: parsed = phonenumbers.parse('+1{}'.format(number))
Use both h5py and pytables in the same Python process Question: The two main Python libraries for HDF5 interaction are `h5py` and `pytables`. They don't play nicely together, particularly on windows >>> import tables >>> import h5py ImportError: DLL load failed >>> import h5py >>> import tables # works fine I need to use both in the same application but I'm unable to get full functionality from both libraries when each is imported. Is there a solution to this? Answer: According to [this thread on github](https://github.com/h5py/h5py/issues/390) no, I don't think you can. It seems that h5py cannot do anything about it, so I would start an issue with the [pytables github](https://github.com/PyTables/PyTables/issues). Also, could you possibly use two different scripts? That way the import wouldn't bork.
Storing the the results of unit test in python in some SQL Database Question: I am learning the different possibilities to write and run (unit) tests in Python. I would like to store the output of the tests in a SQL database -preferably sqlite. I found a way to run the tests using the nose framework from inside the code like this: import nose import os os.chdir('./projects/project A') result = nose.run() print 'The result:', result And I get the following output: The result: True .... ---------------------------------------------------------------------- Ran 4 tests in 0.013s OK I am forced to parse the stderr/stdout or is there any better way to get the test results and messages for further processing ? Answer: You can run `nosetests --with-xunit` to get the results in a standard XUnit file format (XML). You can then parse and process that to insert it into a database. You can also look for a third-party plugin that writes it in a different output format. The last option would be to write a plugin yourself.
Unzip zip files in folders and subfolders with python Question: I try to unzip 150 zip files. All the zip files as different names, and they all spread in one big folder that divided to a lot of sub folders and sub sub folders.i want to extract each archive to separate folder with the same name as the original zip file name and also in the same place as the original zip file . my code is: import zipfile import os,os.path,sys pattern = '*.zip' folder = r"C:\Project\layers" files_process = [] for root,dirs,files in os.walk(r"C:\Project\layers"): for filenames in files: if filenames == pattern: files_process.append(os.path.join(root, filenames)) zip.extract() After i run the code nothing happened. Thanks in advance for any help on this. Answer: UPDATE: Finally, this code worked for me: import zipfile,fnmatch,os rootPath = r"C:\Project" pattern = '*.zip' for root, dirs, files in os.walk(rootPath): for filename in fnmatch.filter(files, pattern): print(os.path.join(root, filename)) zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
Figuring out how to expand a grammar (Python) Question: Im trying to write code that will return an expanding grammar. so in this example I will specify a length of 3, N = N D will expand it self to N = N D D and then it will expand again to N = N D D D but then exit the program, any advice for making this happen? I currently tried to do the replace method in printGrammar but as you can see when you run it for some reason NT (the non terminal being replaced, in this example N), and item (the value from the dictionary, in this case N D and D) wont replace and I am left with a list with 'N' instead of what I want which is N D D, can someone please help me? Binary.txt is: N = N D N = D D = 0 D = 1 Code is import sys import string from collections import defaultdict #default length of 3 stringLength = 3 #get last argument of command line(file) if len(sys.argv) == 1: #get a length from user try: stringLength = int(input('Length? ')) filename = input('Filename: ') except ValueError: print("Not a number") elif len(sys.argv) == 2: #get a length from user try: stringLength = int(input('Length? ')) filename = sys.argv[1] except ValueError: print("Not a number") elif len(sys.argv) == 3: filename = sys.argv[2] stringLength = sys.argv[1].split('l')[1] else: print("Invalid input!") #get start symbol with open(filename, "r") as grammar: #read file lines = grammar.readlines() start = lines[0].split('=')[0] start = start.replace(" ", "") #checks #print(stringLength) #print(filename) #print(start) def str2dict(filename): result = defaultdict(list) with open(filename, "r") as grammar: #read file lines = grammar.readlines() count = 0 #loop through for line in lines: #append info line = line.rstrip() result[line[0]].append(line.split('=')[1]) return result workingDict = str2dict("Binary.txt") print(workingDict) def strings(grammar, start): queue = [start] while len(queue): current = queue.pop(0) # for each symbol in the current string for n, sym in enumerate(current): # if this symbol is a non-terminal if sym in grammar: # for each rule for this symbol... for rhs in grammar[sym]: # replace it with the right part new = current[:n] + rhs + current[n+1:] # does the result contain non-terminals if any(s in grammar for s in new): # yes, place it into the queue queue.append(new) else: # no, return it yield new for x in strings(workingDict, stringLength): print (x) if len(x) > 4: break Answer: Assuming your grammar is in the form grammar = { 'N': ['ND', 'D'], 'D': ['0', '1'] } the algorithm looks straightforward: * iterate over the current string (which is initially just one symbol) * if the symbol is a non-terminal, replace it with its production * if the result contains non-terminals, place it in a queue for further processing * otherwise, return the result (which is a string of terminals) * pick the next "current" string from the top of the queue and continue : def strings(grammar, start): queue = [start] while len(queue): current = queue.pop(0) # for each symbol in the current string for n, sym in enumerate(current): # if this symbol is a non-terminal if sym in grammar: # for each rule for this symbol... for rhs in grammar[sym]: # replace it with the right part new = current[:n] + rhs + current[n+1:] # does the result contain non-terminals if any(s in grammar for s in new): # yes, place it into the queue queue.append(new) else: # no, return it yield new Usage: for x in strings(grammar, 'N'): print x if len(x) > 4: break
Django 1.7 ValueError: invalid literal for int() with base 10: 'a' Question: I am getting this error: Operations to perform: Apply all migrations: account, jobs, assets, sessions, admin, auth, laptops, contenttypes, mardes Running migrations: Applying assets.0004_auto_20150202_1707...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 160, in handle executor.migrate(targets, plan, fake=options.get("fake", False)) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 63, in migrate self.apply_migration(migration, fake=fake) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 97, in apply_migration migration.apply(project_state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 107, in apply operation.database_forwards(self.app_label, schema_editor, project_state, new_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards field, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/schema.py", line 42, in add_field super(DatabaseSchemaEditor, self).add_field(model, field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 397, in add_field definition, params = self.column_sql(model, field, include_default=True) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 120, in column_sql default_value = self.effective_default(field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 183, in effective_default default = field.get_db_prep_save(default, self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 1722, in get_db_prep_save return self.related_field.get_db_prep_save(value, connection=connection) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 627, in get_db_prep_save prepared=False) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 907, in get_db_prep_value value = self.get_prep_value(value) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 915, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'a' When running python manage.py migrate. For this app there is only an admin.py and models.py file, everything else is blank. Here is the models.py file: from django.db import models from django.contrib.auth.models import User class Asset_type(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Asset_os(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Asset_cs_status(models.Model): status = models.CharField(max_length=50) def __str__(self): return self.status class Asset_floor(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Asset(models.Model): DLO = ( ('0', 'Desktop'), ('1', 'Laptop'), ('2', 'Other'), ) user = models.ForeignKey(User) asset_type = models.ForeignKey(Asset_type) asset_os = models.ForeignKey(Asset_os) asset_cs_status = models.ForeignKey(Asset_cs_status) asset_floor = models.ForeignKey(Asset_floor) ppl = models.CharField(max_length=40, unique=True) desktop_laptop = models.CharField(max_length=1, choices=DLO) date_of_purchase = models.DateField() extra_info = models.CharField(max_length=250, default='-') pc_name = models.CharField(max_length=100, null=True, default='-') bookable = models.BooleanField(default=False) image = models.ImageField(upload_to='asset_files/%Y/%m/%d', null=True, blank=True, help_text='Optional') def __str__(self): return self.asset_type.name+' ('+self.ppl+')' Please let me know if you need to see anything else. BC Answer: The solution was found looking in the assets.0004_auto_20150202_1707 file under assets > migrations It had picked up a default value I had typed in previously. Removing the files and regenerating them solved the problem.
Psycopg2 uses up memory on large select query Question: I am using psycopg2 to query a Postgresql database and trying to process all rows from a table with about 380M rows. There are only 3 columns (id1, id2, count) all of type integer. However, when I run the straightforward select query below, the Python process starts consuming more and more memory, until it gets killed by the OS. Minimal working example (assuming that mydatabase exists and contains a table called mytable): import psycopg2 conn = psycopg2.connect("dbname=mydatabase") cur = conn.cursor() cur.execute("SELECT * FROM mytable;") At this point the program starts consuming memory. I had a look and the Postgresql process is behaving well. It is using a fair bit of CPU, which is fine, and a very limited amount of memory. I was expecting psycopg2 to return an iterator without trying to buffer all of the results from the select. I could then use `cur.fetchone()` repeatedly to process all rows. So, how do I select from a 380M row table without using up available memory? Answer: You can use [server side cursors](http://initd.org/psycopg/docs/usage.html#server-side-cursors). cur = conn.cursor('cursor-name') # server side cursor cur.itersize = 10000 # how much records to buffer on a client cur.execute("SELECT * FROM mytable;")
Changing the voice with PYTTSX module in python Question: When using the Pyttsx module within python, how do you change the voice ID that is used when playing out text? The documentation provided illustrates how to cycle through all the available voices, but does not make clear how to choose a specific one. Answer: import pyttsx engine = pyttsx.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) #change index to change voices engine.say('I'm a little teapot...') engine.runAndWait()
Iterating through files in a folder in D Question: In D programming, how can I iterate through all files in a folder? Is there a D counterpart to [python's glob.iglob](https://docs.python.org/2/library/glob.html)? Answer: <http://dlang.org/phobos/std_file.html#dirEntries> So like import std.file; foreach(string filename; dirEntries("folder_name", "*.txt", SpanMode.shallow) { // do something with filename } See the docs for more info. The second string, the *.txt filter, is optional, if you leave it out, you see all files. The SpanMode can be shallow to skip going into subfolders or something like SpanMode.depth to descend into them.
How do I create a Python namespace (argparse.parse_args value)? Question: To interactively test my python script, I would like to create a `Namespace` object, similar to what would be returned by `argparse.parse_args()`. The obvious way, >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.parse_args() Namespace() >>> parser.parse_args("-a") usage: [-h] : error: unrecognized arguments: - a Process Python exited abnormally with code 2 may result in Python repl exiting (as above) on a silly error. So, **what is the easiest way to create a Python namespace with a given set of attributes?** E.g., I can create a `dict` on the fly (`dict([("a",1),("b","c")])`) but I cannot use it as a `Namespace`: AttributeError: 'dict' object has no attribute 'a' Answer: You can create a simple class: class Namespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) and it'll work the exact same way as the `argparse` `Namespace` class when it comes to attributes: >>> args = Namespace(a=1, b='c') >>> args.a 1 >>> args.b 'c' Alternatively, just _import the class_ ; it is available from the `argparse` module: from argparse import Namespace args = Namespace(a=1, b='c')
Python - File does not exist error Question: I'm trying to do a couple things here with the script below (it is incomplete). The first thing is to loop through some subdirectories. I was able to do that successfully. The second thing was to open a specific file (it is the same name in each subdirectory) and find the minimum and maximum value in each column EXCEPT the first. Right now I'm stuck on finding the max value in a single column because the files I'm reading have two rows which I want to ignore. Unfortunately, I'm getting the following error when attempting to run the code: Traceback (most recent call last): File "test_script.py", line 22, in <module> with open(file) as f: IOError: [Errno 2] No such file or directory: 'tc.out' Here is the current state of my code: import scipy as sp import os rootdir = 'mydir'; #mydir has been changed from the actual directory path data = [] for root, dirs, files in os.walk(rootdir): for file in files: if file == "tc.out": with open(file) as f: for line in itertools.islice(f,3,None): for line in file: fields = line.split() rowdata = map(float, fields) data.extend(rowdata) print 'Maximum: ', max(data) Answer: To open a file you need to specify full path. You need to change the line with open(file) as f: to with open(os.path.join(root, file)) as f:
How to sort integers in a variable? Question: > Please note that this is on Python 3.3 **Here is the code:** students=int(input("How many student's score do you want to sort? ")) options=input("What do you want to sort: [Names with scores] , [Scores high to low] , [Scores averages] ? ") options=options.upper() if options == ("NAMES WITH SCORES") or options == ("NAME WITH SCORE") or options == ("NAME WITH SCORES") or options == ("NAMES WITH SCORE"): a=[] for i in range(0,students): name=input("Enter your scores and name: ") a.append(name) a.sort() print("Here are the students scores listed alphabetically") print(a) if options == ("SCORES HIGH TO LOW") or options == ("SCORE HIGH TO LOW"): b=[] number=0 for i in range(0,students): number = number+1 print("Student "+str(number)) name2=int(input("Enter your first score: ")) name3=int(input("Enter your second score: ")) name4=int(input("Enter your third score: ")) b.append(name2) b.append(name3) b.append(name4) final_score = name2 + name3 + name4 print (final_score) b.sort(final_score) print("Student "+str(number) ) print(b) **Here is the outcome of the code:** >>> How many student's score do you want to sort? 2 What do you want to sort: [Names with scores] , [Scores high to low] , [Scores averages] ? scores high to low Student 1 Enter your first score: 1 Enter your second score: 2 Enter your third score: 3 Student 2 Enter your first score: 3 Enter your second score: 5 Enter your third score: 6 14 Traceback (most recent call last): File "H:\GCSE Computing\Task 3\Task 3.py", line 31, in <module> b.sort(final_score) TypeError: must use keyword argument for key function >>> I want the code to add the three scores of the students and sort the total scores of the students, with the according name. For example: (2 Students) **Student 1** * Score 1 - 2 * Score 2 - 4 * Score 3 - 7 _(Therefore the total is 13)_ **Student 2** * Score 1 - 5 * Score 2 - 1 * Score 3 - 4 _(Therefore the total is 10)_ _(The program prints in order from highest to lowest)_ "Student 1 - 15 , Student 2 - 10" Answer: You need to use the syntax `key=final_score` when passing a function to sort by: `b.sort(key=final_score)` But the sort method expects a `function` to be passed in **not** a variable so passing the `int` value from adding `name2 + name3 + name4` is not going to work. If you just want the list of scores sorted simply call `b.sort()` What you should be doing is using a defautdict and using each name as key and store all scores in a list: from collections import defaultdict d = defaultdict(list) for _ in range(students): name = input("Enter your name: ") scores = input("Enter your scores separated by a space: " # add all scores for the user to the list d[name].extend(map(int,scores.split())) To show mean, total and max it is trivial: # from statistics import mean will work for python 3.4 for k,v in d.items(): print("Scores total for {} is {}".format(k,sum(v))) print("Scores average for {} is {}".format(k,sum(v)/len(v))) # mean(v) for python 3,4 print("Highest score for {} is {}".format(k, max(v))) Print sorted by highest user total score: print("The top scoring students from highest to lowest are:") for k,v in sorted(d.items(),key=lambda x:sum(x[1]),reverse=True): print("{} : {}".format(k,sum(v))) Now you have a dict where the student names are the keys and each students scores are all stored in a list. Really you should add a try/except taking the user input and verify it is in the correct format.
Changing the values on the x and y axis of a graph in Python Question: if I had something like; import numpy as np, math as m, matplotlib.pyplot as plt def test(): x = [1,2,3] y = [m.log(0.1),m.log(0.2),m.log(0.3)] fig1 = plt.figure() plt.plot(x,y) plt.show() This will display a graph with the y axis showing negative numbers. I was wondering how you make the graph display it as a logarithm instead (like what the list y was initially defined to be). Thanks! Answer: Well the log of a fraction is negative, by the definition of a log. For example 10^x=1/2, x _must_ be negative to get a fractional value. That is the idea behind a log. So your best bet is to display with a log scale so that it displays positive fractions. ~~The easiest way to do this would be to take`10^x` where x is the decimal value, of every y value. Then you will have the y output as decimals, instead of negative numbers. Then you can set `.ylabel()` as "log scale".~~ **Edit:** I think what you are looking for is answered [on this stackoverflow question](https://stackoverflow.com/questions/3100985/plot-with-custom-text- for-x-axis-points) about making custom ticks. You should be able to use `yticks` instead of `xticks` used in the answer.
Why is my python function being skipped? Question: I've got a small script that's trying to execute an external command. But for some reason, the function that I made to execute the command is being completely skipped over! No errors seem to be raised, it just doesn't execute. I've got a few debug print statements inside it to verify that the function gets entered, but they never print. And I've got a print statement outside of it to verify that the script isn't dying. So what gives? from xml.etree import ElementTree as et import subprocess pomFileLocation = "pom.xml" uiAutomationCommand = "mvn clean install" revertPomFileCommand = "git checkout pom.xml" profileToSetToDefault = "smoketest" def modifyxml( datafile, value ): print( "modifying " + datafile ) tree = et.parse( datafile ) rootNodes = tree.getroot() for node in rootNodes: if "profiles" in node.tag: for profile in node.iter(): foundIt = False for param in profile.iter(): if "id" in param.tag and profileToSetToDefault in param.text: foundIt = True break if foundIt == True: for param in profile.iter(): if "activation" in param.tag: for child in param.iter(): if "activeByDefault" in child.tag: child.text = value tree.write( datafile ) return def runExternalCommand( comm ): print( "running command " + comm ) p = subprocess.Popen( comm, bufsize=-1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate()[0] print( str(p) ) while( True ): print( "still running" ) retcode = p.poll() line = p.stdout.readline() yield line if( retcode is not None ): print("Exiting") break return if __name__ == '__main__': modifyxml( pomFileLocation, "true" ) #runExternalCommand( uiAutomationCommand ) runExternalCommand( revertPomFileCommand ) print( "finished" ) Answer: `runExternalCommand` uses `yield`, so if you want it to execute all the way to the end, you ought to call it like `for something in runExternalCommand(revertPomFileCommand):`. Or just delete the `yield` line, since you don't seem to need it anyway. def runExternalCommand( comm ): print( "running command " + comm ) p = subprocess.Popen( comm, bufsize=-1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate()[0] print( str(p) ) while( True ): print( "still running" ) retcode = p.poll() line = p.stdout.readline() yield line if( retcode is not None ): print("Exiting") break return if __name__ == '__main__': modifyxml( pomFileLocation, "true" ) #runExternalCommand( uiAutomationCommand ) for line in runExternalCommand( revertPomFileCommand ): pass print( "finished" ) Or def runExternalCommand( comm ): print( "running command " + comm ) p = subprocess.Popen( comm, bufsize=-1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate()[0] print( str(p) ) while( True ): print( "still running" ) retcode = p.poll() line = p.stdout.readline() if( retcode is not None ): print("Exiting") break return if __name__ == '__main__': modifyxml( pomFileLocation, "true" ) #runExternalCommand( uiAutomationCommand ) runExternalCommand( revertPomFileCommand ) print( "finished" )
how to adding new tab in readline python Question: I have a problem can't adding a new tab in reading file. I've tried readline, but I am confused.. f = open('data.txt', 'r') count = 0 for i in f.readlines(): count += 1 if count == 3: #adding new tab print i, In here, I have `data.txt` which contains data like this: af Afrikaans sq Albanian ar Arabic hy Armenian az Azerbaijani eu Basque But I can't adding new tab if the data is in a certain count readline. I want to make it like this.. af Afrikaans hy Armenian sq Albanian az Azerbaijani ar Arabic eu Basque Answer: you can create one list to store your lines per 3 iteration then append this it to `last_q` and at last you can use `zip` function to zip `last_q` and join the pairs with `\t` then write to file again : import copy q = [] last_q= [] with open('newefile.txt','r') as f: for line in f: q.append(line.strip()) if len(q)==3 : last_q.append(copy.copy(q)) q=[] with open('newefile.txt','w') as f: for lines in zip(*last_q) : print lines f.write('\t'.join(lines)+'\n') Demo : print last_q deque([deque(['af Afrikaans\thy Armenian', 'sq Albanian\taz Azerbaijani', 'ar Arabic\teu Basque'], maxlen=3)]) print zip(*last_q) [('af Afrikaans', 'hy Armenian'), ('sq Albanian', 'az Azerbaijani'), ('ar Arabic', 'eu Basque')] Final result : af Afrikaans hy Armenian sq Albanian az Azerbaijani ar Arabic eu Basque
Attribute error when generating random numbers in Python Question: I asked a similar question regarding this same piece of code earlier but once again I have found myself stuck. Particularly on the generation of a license plate containing two letters, two numbers, and then two letters. I hope that this question isn't a duplicate but in this circumstance I am very stuck with what to do, this is the code so far and I hope you can identify where I am going wrong: from datetime import date, datetime, time, timedelta import time, string from random import uniform, random def timeDelta(): print("Average Speed Checker") start = (input("Car has passed Cam1: ")) licensePlate = str(firstLetters + randomNumber + " " + secondLetters) print(licensePlate) if start in ("y"): camInput1 = datetime.now() print(camInput1) print("Car is travelling...") time.sleep(1) print("Car is travelling...") time.sleep(1) print("Car has passed cam2") camInput2 = camInput1 + timedelta(seconds = uniform(5, 10)) timeDelta = camInput2 - camInput1 distance = 200 duration = timeDelta.total_seconds() print("Time Delta is equal to: {0}".format(duration)) speedCarMs = distance/duration print("Car is travelling in m/s at: {0}".format(speedCarMs)) speedCarMph = 2.237*speedCarMs print("Car is travelling in MPH at: {0}".format(speedCarMph)) if speedCarMph > 60: fileInput: def possibleNumber(): possibleNumbers = (1,2,3,4,5,6,7,8,9,0) randomNumber = random.sample(possibleNumbers, 2) def randomLetters1(y): return ''.join(random.choice(string.ascii_uppercase) for x in range(y)) firstLetters = (randomLetters1(2)) secondLetters = (randomLetters1(3)) print("Choose which function you want to use: ") while True: answer = (input("Choice: ")) if answer in ("speed"): timeDelta() else: print("Invalid response") According to python, the issue is to do with this: AttributeError: 'builtin_function_or_method' object has no attribute 'choice' Answer: You did not import the `random` module. You imported the `random.random()` **function** : from random import uniform, random If you wanted to use `choice()` and `sample()` as well, import that in addition: from random import uniform, random, choice, sample and adjust your use of those functions: def possibleNumber(): possibleNumbers = (1,2,3,4,5,6,7,8,9,0) randomNumber = sample(possibleNumbers, 2) def randomLetters1(y): return ''.join(choice(string.ascii_uppercase) for x in range(y)) Or, instead, import _just the module_ : import random and your code will work as you don't actually _use_ `random()` anywhere, provided you replace `uniform()` with `random.uniform()`: camInput2 = camInput1 + timedelta(seconds = random.uniform(5, 10)) I'll reiterate again that you don't need to create `camInput2`, as `camInput1 + some_timedelta - camInput1` produces the same value as `some_timedelta`; you can just use: timeDelta = timedelta(seconds = random.uniform(5, 10)) You never call the `randomNumbers()` function, nor does the function _return_ anything. The `randomNumber` local name in that function is not available outside of the function. Have the function return the result and use the function where you now try to use the result via the `randomNumber` name: def possibleNumber(): possibleNumbers = (1,2,3,4,5,6,7,8,9,0) return random.sample(possibleNumbers, 2) and licensePlate = str(firstLetters + possibleNumber() + " " + secondLetters)
Python: create sublist without copying Question: I have a question about how to create a sublist (I hope this is the right term to use) from a given list without copying. It seems that slicing can create sublists, but does it with copying. Here is an example. In [1]: a = [1,2,3] In [2]: id(a) Out[2]: 4354651128 In [3]: b = a[0:2] In [4]: b Out[4]: [1, 2] In [5]: id(b) Out[5]: 4354621312 In [6]: id(a[0:2]) Out[6]: 4354620880 See here the id of b and a[0:2] are different, although their values are the same. To double check, change the value in a, the value in b does not change. In [7]: a[1] = 4 In [8]: a Out[8]: [1, 4, 3] In [9]: b Out[9]: [1, 2] So to get back to my question, how can I create sublists but without copying? I mean, when value of a[1] is set to 4, b will be [1, 4]. I searched around and did not find much help (maybe I am not using the right keywords). Thank you! * * * Edits: Thank you all for your comments and answers! Here is what I have learned. * There is no built-in way in Python to create a view of a list (or to create a sublist without copying). * The easiest way to do this is to use the numpy array. * Although numpy array has limitations on data type compared with list, it does serve my purpose (to implement quicksort with no extra memory) Here is the same process with numpy array. In [1]: import numpy as np In [2]: a = np.arange(1,4) In [3]: a Out[3]: array([1, 2, 3]) In [4]: b = a[0:2] In [5]: b Out[5]: array([1, 2]) In [6]: id(b) Out[6]: 4361253952 In [7]: id(a[0:2]) Out[7]: 4361254032 In [8]: a[1] = 4 In [9]: a Out[9]: array([1, 4, 3]) In [10]: b Out[10]: array([1, 4]) Answer: `numpy`'s array objects support this notion of creating interdependent sub- lists, by having slicing return `views` rather than copies of the data. Altering the original `numpy` array will alter the views created from the array, and changes to any of the views will also be reflected in the original array. Especially for large data sets, views are a great way of cutting data in different ways, while saving on memory. >>> import numpy as np >>> array1 = np.array([1, 2, 3, 4]) >>> view1 = array1[1:] >>> view1 array([2, 3, 4]) >>> view1[1] = 5 >>> view1 array([2, 5, 4]) >>> array1 array([1, 2, 5, 4]) # Notice that the change to view1 has been reflected in array1 For further reference, see the [`numpy` documentation on views](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html) as well as [this SO post](http://stackoverflow.com/questions/4370745/view- onto-a-numpy-array).
Code for guessing game won't print anything after I enter my number Question: I am trying to make a guessing game with python but my code won't seem to work. I am just getting into python so I am not the best. Here is my code. print "Hello" print "You have found me, haven't you?" print "Well, since you did all the work to find me..." print "I will let you have my diamond and gold infused microwave!" print "But there is a twist" print "You have to guess my favorite number! You only have one try!" print "It is a number from 1 to 5" guess=raw_input("What is my number?") import random for x in range(1): print random.randint(1,5) correct=random.randint def correct_number(correct): if correct==guess: print "Dang! You got it!" elif correct > guess: print "Wrong! Too low!" elif correct < guess: print "Wrong! Too High!" I need it to say "Dang it! You won!" if you get it right, "Wrong! Too high!" if your guess is too high, and "Wrong! Too low!" if your guess is too low. Answer: correct=random.randint This sets `correct` to be the function _that produces_ a random number, not a random number itself. There's a number of things wrong or "weird" about the code, but this is what's causing your error. You should instead CALL the function correct = random.randint(1,5) And speaking of calling functions, you never call your `correct_number` function either. You should probably do something like: guess = raw_input("what is my number? ") correct = random.randint(1,5) def correct_number(): if guess == correct: # yay if guess < correct: # too low if guess > correct: # too high correct_number()
Delete words which have 2 consecutive vowels in it Question: What i want is remove the words which have more than two consecutive vowels in it. So input: s = " There was a boat in the rain near the shore, by some mysterious lake" Output: [boat,rain,near,mysterious] So here is my code. I was just wondering if there is any better way to do this or is this efficient enough.And if you can do this with python dict or lists are ok? :) I'm new to python so yeah. :) comments would be nice. def change(s): vowel = ["a","e","i","o","u"] words = [] a = s[:].replace(",","").split() for i in vowel: s = s.replace(i, "*").replace(",","") for i,j in enumerate(s.split()): if "**" in j: words.append(a[i]) return words Answer: Alternatively, you could always use regular expressions and list comprehension to get the list of words: >>> import re >>> [x for x in s.split() if re.search(r'[aeiou]{2}', x)] ['boat', 'rain', 'near', 'mysterious'] `s.split()` splits the sentence into a list of words. The expression `[x for x in s.split()]` considers each word in this list in turn. The `re.search(r'[aeiou]{2}', x)` part of the expression searches each word for two consecutive letters from the group `[aeiou]`. Only if two consecutive vowels are found is the word put in the new list.
Java syntax equivalent to Python syntax? Question: So, if you have ever looked on my page you might have found that I'm a Grade 10 student that's just started his computer science course in high school. Yaay! :) The language that we are learning is Java, something which in my opinion, is very different from Python (at least so far). However, there's one thing that I have noticed when starting a Java program. Sorry if the syntax is off or wrong. public static void main(String [] args){ String school = "A beautiful school"; System.out.print(school); } Is this equivalent to Python's: if __name__ == "__main__": school = "A beautiful school" print(school) I've asked my teacher about this but didn't seem to get an answer that I completely understand. I also took a look at this [question](http://stackoverflow.com/questions/2390063/what-does-public-static- void-mean-in-java), but it seemed as if it only answered the different keywords `public`, `static`, `void`, (which I only slightly understand as of now). So does `public static void main` act the same as `if __name__ == "__main__"`? If not, what's the difference between the two? Thanks in advance! Answer: When you do `if __name__ == "__main__":` you are checking to see if you are in `main` already. It's different because the entire python script is considered to be "main" in the way that `public static void main` is considered to be "main" in java. When you run a python file, it starts from the very top and works its way down looking for executable statements (it bypasses declarations such as function `def`initions and `class`es). When you run a java class it looks for the `main` method and starts from there. The reason for having this `if __name__ == "__main__":` is so that it _only_ executes when you run the python file directly. As you will learn soon, python files can also be considered as "modules" to be included from other python scripts. In such cases you would not want this 'main' logic to be implicitly executed. Much like you almost never invoked a classes `main` when importing it as part of a larger app in java.
python memory exception when not at full memory usage Question: I am using Ubuntu 64bit 12.04. My machine has 64gigs of RAM. I am running a script where I have to store ~9gig of data into a dictionary. It is a simple dictionary where keys are 30 characters and value is just a integer. However, the script is throwing a memory exception at around 58% memory usage. What is going on here? Is there a max limit to dictionary size? Answer: I don't think there is a max value that limits the size of a dictionary in Python. Assuming your script is running under Unix, you can increase the memory limit your process can consume via standard library module [resource](https://docs.python.org/2/library/resource.html). >>> import resource >>> resource.setrlimit(resource.RLIMIT_AS, (10**9, 10**9)) You may also want to periodically check the memory usage with `resource.getrusage()` function. The resulting object has the attribute `ru_maxrss`, which gives total memory usage for the calling process. >>> import resource >>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss >>> 20631552 By this way, at least you can make sure that it is your script which eats the memory.
LED control on Raspberry Pi by GPIO with Python Question: I am using momentary switches wired to GPIO pins on a Raspberry Pi to control 4 LEDs. I have five buttons wired up. The first 4 buttons when pressed toggle the state of a connected LED from on to off or off to on depending on the current state. The fifth button turns on all 4 LEDs or turns off all 4 LEDs based on the on/off state of GPIO 18. I also have an extra LED wired to GPIO pin 18, this simply turns on or off based on the state of pin 18. The idea of this project is to be able to independently control the LEDs and have a master control button as well. The LED attached to pin 18 is a monitoring LED, it should be on if ANY of the 4 LEDs is on and it should only be off if all 4 of the LEDs are off simultaneously. This is all based on python scripts that monitor for button presses and act accordingly. The code I've written to control all LEDs at once looks like this: import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP) chan_list = (4,17,22,27) GPIO.setup(chan_list,GPIO.OUT) GPIO.output(chan_list,0) GPIO.setup(18,GPIO.OUT) GPIO.output(18,0) while True: input_state = GPIO.input(26) if input_state == False: chan_list = (4,17,22,27) GPIO.output(18, not GPIO.input(18)) time.sleep(0.1) GPIO.output(chan_list, GPIO.input(18)) time.sleep(0.4) This code appears to operate perfectly. As you can see it toggles the current state of pin 18 and then applies that state to pins 4,17,22 and 27 which are the pins the LEDs are connected to. The code I've written to control the individual LEDs is a bit more complicated and it looks like this: import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(4,GPIO.OUT) GPIO.output(4,0) GPIO.setup(17,GPIO.OUT) GPIO.setup(22,GPIO.OUT) GPIO.setup(27,GPIO.OUT) GPIO.setup(18,GPIO.OUT) while True: input_state = GPIO.input(5) if input_state == False: if GPIO.output(17,0) == False: GPIO.output(4, not GPIO.input(4)) elif GPIO.output(22,0) == False: GPIO.output(4, not GPIO.input(4)) elif GPIO.output(27,0) == False: GPIO.output(4, not GPIO.input(4)) else: GPIO.output(4, not GPIO.input(4)) time.sleep(0.1) GPIO.output(18, GPIO.input(4)) time.sleep(0.4) There are 4 versions of this with the pins adjusted, one version for each LED, This version uses pin 5 as an input to detect button presses and pin 4 as an output to activate the LED. What I want is to do is this: When pressed (if LED1 is off) - Toggle LED1 on, also toggle pin 18 on to activate the indicator light. - Take no further action. When pressed (if LED1 is on) - Check if pin 17 is on or off; - If pin 17 is on toggle LED1 off and take no further action. - If pin 17 is off check if pin 22 is on or off; - If pin 22 is on toggle LED1 off and take no further action. - If pin 22 is off check if pin 27 is on or off; - If pin 27 is on toggle LED1 off and take no further action. - If pin 27 is off toggle LED1 off then set pin 18 to the current status of pin 4 (LED1). However, what is actually happening is this: When pressed (if LED1 is off) - Turns off all of the other 3 LEDs then toggles LED1 on and toggles pin 18 on. When pressed (if LED1 is off) - Turns off all LEDs and toggles pin 18 off. I can not for the life of me figure this out. Your help is hugely appreciated. P.S. Pardon my ignorance, I started learning python yesterday and have no prior programming experience at all. I'm sure it's something simple but I can't seem to solve it. Answer: Sounds like you have 3 logical blocks: 1. Individual LED control 2. Master LED control 3. Monitor-LED indicator control Decouple your code into functions, let's name them `checkIndividualButton`, `checkMasterButton` and `updateMonitorLed`, one for each logical block, and call them from your main loop import RPi.GPIO as GPIO import time # our 3 functions will go here, yet to be written # setup pins here all_leds = [???,???,???,???] GPIO.setup blah blah blah while True: checkIndividualButton(button_pin=17, led_pin=4) # assuming button wired to pin 17 controls LED on pin 4 checkIndividualButton(????, ????) # fill this in checkIndividualButton(????, ????) # fill this in checkIndividualButton(????, ????) # fill this in checkMasterButton(master_button_pin=26, monitor_led_pin=18, all_leds) # notice reference to all_leds which we setup above updateMonitorLed(all_leds, monitor_led_pin=18) Now all you have to do is implement individual functions, each doing Just One Job(TM): def checkIndividualButton(button_pin, led_pin): is_pressed = GPIO.input(button_pin) if is_pressed: GPIO.output(led_pin, not GPIO.input(led_pin)) def checkMasterButton(master_button_pin, monitor_led_pin, all_led_pins): is_pressed = GPIO.input(master_button_pin) if is_pressed: GPIO.output(monitor_led_pin, not GPIO.input(monitor_led_pin)) time.sleep(0.1) GPIO.output(all_led_pins, GPIO.input(monitor_led_pin)) time.sleep(0.4) def updateMonitorLed(all_leds_pins, monitor_led_pin): is_any_led_on = False for led_pin in all_leds_pins: if GPIO.input(led_pin): is_any_led_on = True GPIO.output(monitor_led_pin, is_any_led_on) time.sleep(0.1) Paste this block of functions into the right place in your main program. DISCLAIMER: I have not tested this. There are ways to optimize and cleanup the code further, happy to guide you in comments if you'd like.
Simple HTML Email: Basic CSS styles being stripped Question: I am sending a simple email from the command line on a linux machine through a python script. I have looked up answers about why CSS might get changed, stripped, etc. in email clients. However, I can't seem to solve what looks to me like a simple issue. When I send a simple HTML email with a table, random td's get their styles stripped. When I render the same HTML in a browser, it looks fine. Here is the python code: #!/usr/bin/python import os import subprocess def make_html_report(data, subject): text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' text += '<html lang="en"><head>' text += '<meta charset="utf-8"/>' text += '<title>{0}</title>'.format(subject) text += '</head>' text += '<body>' text += '<table style="border:solid 1px #000000; border-collapse: collapse; width: 300px;">' for row, line in enumerate(data): tr_style = "" if row == 0: tr_style += "border-bottom:solid 1px #000000;" text += '<tr style="{0}">'.format(tr_style) for index, item in enumerate(line): td_style = "border-right:solid 1px #000000;" if row != 0: if index == 1: td_style += "text-align:right; padding-right:5px;" if float(line[3]) < 0: td_style += "color:#ff0000;" if index != 1 or row == 0: td_style += "text-align:center;" text += '<td style="{0}">{1}</td>'.format(td_style, item) text += '</tr>' text += '</table>' text += '<p style="margin-top: 20px;">Random example email. Why is it not working??</p>' text += '</body>' text += '</html>' print text return text def send_report(html_content, subject): SENDMAIL = "/usr/sbin/sendmail" # sendmail location p = os.popen("%s -t" % SENDMAIL, "w") text = "From: {0}\nTo: {1}\nSubject: {2}\nContent-Type: text/html\nMIME-Version: 1.0\n\n{3}".format( "[email protected]", "[email protected]", subject, html_content ) print "\n{0}".format(text) p.write(text) sts = p.close() if __name__ == "__main__": subject = "example subject" data = [["head1","head2","head3","head4"], [1,2,3,4], [4,3,2,1], [8,7,6,4], [6,5,4,-5], [5,4,3,-2], [8,7,6,4], [6,5,4,-5], [5,4,3,-2]] send_report(make_html_report(data, subject), subject) I used an html checker. Everything was fine. But any time I send an email some or all of these things happen: (1) td's lose their style element all together (2) a random space is inserted into the style element and thus, it does not render. Example: `<td style="text-align: c enter:>`. There is a space inserted within the word center. Does anyone have an idea about what is going on here? Answer: According to RFC 2822 2.1.1, <http://www.faqs.org/rfcs/rfc2822.html>, each line of an email SHOULD contain less than 78 characters. Try inserting some new lines (\n), so that no line is longer than 78 characters. I think this function can do that (Sorry, if not, I'm a PHP developer): <http://perldoc.perl.org/Text/Wrap.html>
django inplaceedit testing project Question: New to django… Since a month i'm trying to follow [this](https://github.com/goinnn/django-inplaceedit- bootstrap/tree/master/testing) tutorial without success. When i syncdb i get following error: (virt-inplaceedit)Mac:testing manuelstrasser$ python manage.py syncdb Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/django/apps/config.py", line 123, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/__init__.py", line 1, in <module> from sorl.thumbnail.fields import ImageField File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/fields.py", line 6, in <module> from sorl.thumbnail import default File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/default.py", line 3, in <module> from sorl.thumbnail.helpers import get_module_class File "/Users/manuelstrasser/Desktop/inplace/virt-inplaceedit/lib/python2.7/site-packages/sorl/thumbnail/helpers.py", line 5, in <module> from django.utils import simplejson ImportError: cannot import name simplejson I installed simplejson but still same error. Anyone haveing experiences with this tutorial? I did everything exactly as per description… Answer: `django.utils.simplejson` is deprecated in django 1.7. Looks like you use old version of the `sorl-thumbnail`. [Current version](https://github.com/mariocesar/sorl-thumbnail) of `sorl-thumbnail` supports django 1.7 so try to update this library.
BLAST via Biopython NCBIWWW. Where can I find the complete database list? Question: I am using the module Biopython module NCBIWWW to blast some sequences online. I would like to blast my sequences against different databases available, however I cannot find a comprehensive list of them. Here is an eample of simple query to the Nucleotide collection database using "blastn" algorithm. from Bio.Blast import NCBIWWW result_handle = NCBIWWW.qblast("blastn", "nt", some_sequence) As you can see, the database Nucleotide collection is specified as "nt". With what shall I substitute "nt" in case I want to query the Human GRCh37/hg19 database for example? And if I want to query other species/builds? Is there any comprehensive list available where I can find the short names for all the databases available at <http://blast.ncbi.nlm.nih.gov> ? Thanks! Answer: You can simply go to [http://blast.ncbi.nlm.nih.gov/Blast.cgi?PROGRAM=tblastn&PAGE_TYPE=BlastSearch&LINK_LOC=blasthome](http://blast.ncbi.nlm.nih.gov/Blast.cgi?PROGRAM=tblastn&PAGE_TYPE=BlastSearch&LINK_LOC=blasthome) and click on the database drop down list and you will find the database names there like, nr, nt, est etc. Try [http://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE=BlastSearch&PROG_DEF=blastn&BLAST_PROG_DEF=megaBlast&BLAST_SPEC=OGP__9606__9558](http://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE=BlastSearch&PROG_DEF=blastn&BLAST_PROG_DEF=megaBlast&BLAST_SPEC=OGP__9606__9558) for Human Genome.
Python findall, regex, unicode Question: I'm trying to write a Python script that searches thru a directory tree and lists all .flac files and derives Arist, Album and Title from resp. dir/subdir/filename and write that to a file. The code works fine, until it hits a unicode character. Here's the code: import os, glob, re def scandirs(path): for currentFile in glob.glob(os.path.join(path, '*')): if os.path.isdir(currentFile): scandirs(currentFile) if os.path.splitext(currentFile)[1] == ".flac": rpath = os.path.relpath(currentFile) print "**DEBUG** rpath =", rpath title = os.path.basename(currentFile) title = re.findall(u'\d\d\s(.*).flac', title, re.U) title = title[0].decode("utf8") print "**DEBUG** title =", title fpath = os.path.split(os.path.dirname(currentFile)) artist = fpath[0][2:] print "**DEBUG** artist =", artist album = fpath[1] print "**DEBUG** album =", album out = "%s | %s | %s | %s\n" % (rpath, artist, album, title) flist = open('filelist.tmp', 'a') flist.write(out) flist.close() scandirs('./') code output: **DEBUG** rpath = Thriftworks/Fader/Thriftworks - Fader - 01 180°.flac **DEBUG** title = 180° **DEBUG** artist = Thriftworks **DEBUG** album = Fader Traceback (most recent call last): File "decflac.py", line 25, in <module> scandirs('./') File "decflac.py", line 7, in scandirs scandirs(currentFile) File "decflac.py", line 7, in scandirs scandirs(currentFile) File "decflac.py", line 20, in scandirs out = "%s | %s | %s | %s\n" % (rpath, artist, album, title) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 46: ordinal not in range(128) But when tried in Python console, it is working fine: >>> import re >>> title = "Thriftworks - Fader - 01 180°.flac" >>> title2 = "dummy" >>> title = re.findall(u'\d\d\s(.*).flac', title, re.U) >>> title = title[0].decode("utf8") >>> out = "%s | %s\n" % (title2, title) >>> print out dummy | 180° So, my questions: 1) How come the same code works in the console, but not in the script? 2) How to fix the script? Answer: Python console works with your terminal and interprets unicode encoding according to its locale. Replace the line with the new `str.format`: out = u"{} | {} | {} | {}\n".format(rpath, artist, album, title) And encode to utf8 when writing to a file: with open('filelist.tmp', 'a') as f: f.write(out.encode('utf8')) or `import codecs` and do directly: with codecs.open('filelist.tmp', 'a', encoding='utf8') as f: f.write(out) or, since utf8 is default: with open('filelist.tmp', 'a') as f: f.write(out)
Scraping data through paginated table using python Question: I am scraping data through google finance's historical page for a stock ([http://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=PLfUVIDTDuSRiQKhwYGQBQ](http://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=PLfUVIDTDuSRiQKhwYGQBQ)). I can scrape the 30 rows on the current page. The issue I am facing is that I am unable to scrape through the rest of data in the table (31-241 rows). How do I go to the next page or link. Following is my code: import urllib2 import xlwt #to write into excel spreadsheet from bs4 import BeautifulSoup # Main Coding Section stock_links = open('stock_link_list.txt', 'r') #opening text file for reading #url="https://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=zHXOVLPnApG2iALxxYCADQ" for url in stock_links: OurFile = urllib2.urlopen(url) OurHtml = OurFile.read() OurFile.close() soup = BeautifulSoup(OurHtml) #soup1 = soup.find("div", {"class": "gf-table-wrapper sfe-break-bottom-16"}).get_text() soup1 = soup.find("table", {"class": "gf-table historical_price"}).get_text() end = url.index('&') filename = url[47:end] file = open(filename, 'w') #opening text file for writing file.write(soup1) #file.write(soup1.get_text()) #writing to the text file file.close() #closing the text file Answer: You will have to fine tune it and I would catch more specific errors but you can keep increasing the `start` to get the next data: url = "https://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=W8LUVLHnAoOswAOFs4DACg&start={}&num=30" from bs4 import BeautifulSoup import requests # Main Coding Sectio start = 0 while True: try: nxt = url.format(start) r = requests.get(nxt) soup = BeautifulSoup(r.content) print(soup.find("table",{"class": "gf-table historical_price"}).get_text()) except Exception as e: print(e) break start += 30 This gets all the table data up to the last date feb 7 : ...... Date Open High Low Close Volume Feb 7, 2014 552.60 557.90 548.25 551.50 119,711
How to set random time interval in scrapy/python? Question: I am trying to set random time interval and call that function between iteration in python/scrapy Note: How to set Random time interval between iteration and function in python scrapy import random class MySpider(CrawlSpider): def xxxxxx(self): xxxxxx def xxxx(self,response): for list in lists: for xxxxxxx: item = example() yield request def xxxxxx(self, response): item=response.meta['item'] return item Answer: Maybe this could work as scrapy is a framwork based on twisted import random from twisted.internet import reactor INTERVAL = xxxx def callRandomTime(): youFunc() reactor.callLater(INTERVAL * random.random(), callRandomTime)
Xor tuple function Question: I'm a beginner in python and I'm blocked on a series of instructions I have to do. I need to make a function that takes into parameter two tuples of 3 integers. The function will perform a xor between the 2 first integers, then the 2 second integers, and the 2 third integers. Finally, it will return these results as a tuple. Here's the function I used earlier in the code: def xor (a,b): return (bool (a) and not(bool(b))) or (not(bool (a))) and bool (b) If it's not accurate or downright false, please let me know. Thanks! Answer: In Python, the `^` infix operator represents xor for integers (you can see this by looking at the documentation for `int.__xor__` but _be careful_ , the `__xor__` behavior can be overloaded for other types and may not reflect anything related to a usual logical xor operation). So in this case, you can do it like: def xor(tup_a, tup_b): return tuple(a^b for a,b in zip(tup_a, tup_b)) For example: In [5]: xor((1,2,3), (3, 2, 1)) Out[5]: (2, 0, 2) This makes use of the `zip` function, which you should read about if not familiar. One convention about this function: if `tup_a` and `tup_b` do not have the same lengths, then the zipping process will only happen up to the length of the shorter one, and the rest of the items from the longer one will be discarded. If you want to write some extra code to do something special to handle those extra items, you'll have to modify this function definition to use `itertools.izip_longest`. For example, suppose that if `tup_a` is shorter than `tup_b` then you want to use a dummy value of `0` in the places where `tup_a` isn't long enough to match up with something from `tup_b` ... from itertools import izip_longest def xor(tup_a, tup_b, fill=0): return tuple(a^b for a,b in izip_longest(tup_a, tup_b, fillvalue=fill)) Then: In [11]: xor((1,2,3), (3, 2, 1)) Out[11]: (2, 0, 2) In [12]: xor((1,2), (3, 2, 1)) Out[12]: (2, 0, 1)
Alternate Python List Reverse Solution Needed Question: I had a job interview today. During it I was asked to write down an algorithm that will reverse a list. First I offered the answer using the reversed() method: x = [1,2,3,4,5] y = reversed(x) for i in y: print i The senior developer conducting the interview asked me if I know another way, upon which I wrote down the other known method with slicing: x = [1,2,3,4,5] y = x[::-1] Unfortunately he was unhappy with this solution as well and asked me to think of another one. After few minutes I said I could not come up with a better one. He said that this was not good enough for their standards. I am perfectly fine with his opinion and have no problem practicing more on my code. My question is, what is a better solution that I am not aware of, if there is one. Could there be some other more 'programmer' way...Only other thing that comes to mind is recursion, however I thought of it only after the interview was already done. Thanks. Answer: Both your answers are good in terms of python so the interviewer must have been asking you to implement your own method: Using recursion: def recur_rev(l): return recur_rev(l[1:]) + l[:1] if l else l Or a list comp and range starting at the length of l -1 and going in reverse: l = list(range(100)) print([l[ind] for ind in range(len(l)-1,-1,-1)]) Using itertools.count: from itertools import count cn = count(len(l) -1, -1) print([l[next(cn)] for ele in l]) For efficiency use a generator expression: rev = (l[next(cn)] for ele in l) for ele in rev: print(ele) Or using map: print(list(map(l.__getitem__,range(len(l)-1,-1,-1)))) # list needed for python3 [99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] without the list call on map we will get a map object we can iterate over in python3, you can use [itertools.imap](https://docs.python.org/2/library/itertools.html#itertools.imap) in python2 to achieve a similar result
Use urllib.urlretrieve and ignore proxy Question: I'm trying to use [urllib.urlretrieve](http://%20https://docs.python.org/2/library/urllib.html#urllib.urlretrieve) to fetch some files from a server. I need it to ignore any proxy settings on the system however. I have had a look at [urllib.urlopen](https://docs.python.org/2/library/urllib.html#urllib.urlopen) but I am not sure how I could use it to download files. Currently my call looks something like this: `urllib.urlretrieve(url, import_path + "/%s" % filename)` Any assistance would be great. Thanks. Answer: In the Python docs it's said `filehandle = urllib.urlopen(some_url, proxies={})` will cause the system not to us any proxies, even the system's ones. It's pretty simple to deal with `urlopen()`. `filehandle` supports `read()` method to get data. Open a file then and write that data into it. Let `filehandle` be full of data after a successful call. fi=open(some_file,mode) fi.write(filehandle.read()) fi.close()
python: need a deepcopy equivalent breaking all shared identity Question: Due to some constrains I need to create a fresh copy of an object alongwith fresh copies of all its attributes and for attributes of its attributes and so on recursively. Existing deepcopy() is recursive, but when multiple objects within the tree being copied have the same starting identity, they also have the same ending identity (even though their ending identities don't match their starting identities). For the following case: class A: def __init__(self, x): self.x = x v = A(1) o = [v, v] copy.deepcopy does following: dc_o = copy.deepcopy(o) assert dc_o[0] is not o[0] # new identity from the original assert dc_o[0] is dc_o[1] # but maintains identity within the copied tree assert dc_o[0] == dc_o[1] # ...as well as value But, what I need is: r_dc_o = recursive_deepcopy(o) assert r_dc_o[0] is not o[0] # new identity from the original assert r_dc_o[0] is not r_dc_o[1] # also new identity from elsewhere inside copy assert r_dc_o[0] == r_dc_o[1] # while maintaining the same value How can I do this? Answer: Fully automating a recursive deepcopy in a way that _didn't_ memoize objects would be extremely dangerous -- it would mean you couldn't have any kind of objects with internal references preserved in a way that would make those references useful after the copy operation (think about objects with a "parent" link, or objects that link to a shared registry or similar resource). That said, if you really wanted to do this (and you shouldn't -- it **will** break a great many objects passed through the operation), you can accomplish it by constructing a memo dictionary that ignored attempts at adding keys, and passing that as a second argument to `deepcopy()`. So, here we are: import copy class baddict(dict): def __setitem__(self, k, v): pass class A: def __init__(self, x): self.x = x def __eq__(self, other): self.x == other.x v = A(1) o = [v, v] r_dc_o = copy.deepcopy(o, baddict()) assert r_dc_o[0] is not r_dc_o[1] assert r_dc_o[0] == r_dc_o[1] I'd suggest thinking about _why_ you need this behavior, and trying to come up with a better way to accomplish it. Even a `baddict` implementation that looked at the value and skipped memoizing only if values were instances of a specific class would be safer than what we're doing here.
Cannot get raw UDP socket to work using Python on a Linux machine with specific IP and Port Question: I am trying to connect using Python on a Linux system to a Windows system that is listening at a certain IP and port number using UDP socket. I know the IP and port number but I do not know any host names. But I thought it would be easy to just connect and send a small message. I keep getting an error no matter how I specify the address. import socket def openSocket(): HOST = "1.1.1.1" PORT = 111 server_address = (HOST, PORT) s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL) ) s.connect(server_address) s.sendAll("HELLO") s.close() openSocket() Answer: You just have to read the error: s.connect(server_address) File "<string>", line 1, in connect TypeError: argument 1 must be string, not tuple which points you directly at your `connect()` call. Now compare this to the official python [documentation](https://docs.python.org/2/library/socket.html#socket.SOCK_DGRAM). I've noticed that you've wanted to generate a UDP socket, but used `RAW` as type instead of `DGRAM`. `RAW` will give you raw network protocol level access (ie. lower level than UDP), and can't therefore be used with `(HOST,PORT)` tuples.
Issue with very simple python3 program Question: Complete noob with python 3. I have some code and can't figure out for the life of me why I keep getting the output I do. For some reason the elif statements aren't getting recognized. Here is the output first and the code down below: 3 Your fortune for today is: Please press enter to end #Program for fortune cookies var1 = "It's going to be a good day" var2 = "You'll have a long life" var3 = "Your life will be short" var4 = "Things will be good" var5 = "Life will be fun" import random randNum = random.randint(1, 5) statement = "" print(randNum) if randNum == 1: statement = var1 elif randNum == 2: statement = var2 elif randNum == 3: statement == var3 elif randNum == 4: statement == var4 elif randNum == 5: statement == var5 print("Your fortune for today is: ", statement) input("Please press enter to end") Answer: You are not assigning `varx` to `statement` (in some cases, 3, 4 and 5th cases), but comparing. Just change all: statement == varx To: statement = var3 Except from that, it seems to work.
compare two dictionaries in python Question: How do i campare dictionaries that contain dictionaries ? This will work in case the dictionaries contain simple values # will show the keys with different values d1_keys = set(dict1.keys()) d2_keys = set(dict2.keys()) intersect_keys = d1_keys.intersection(d2_keys) modified = {} for i in intersect_keys: if dict1[i] != dict2[i] : modified.update({i : (dict1[i], dict2[i])}) but i have a dictionary like this: { 'medic1' : {'date' : '02/02/2015', 'no' : '123' }, 'medic2' : {'date' :'02/03/2015', 'no' : '456' }} Answer: By recursion function for nested dictionary. 1. Get common keys from both dictionary by `keys()` and `set operation.` 2. Iterate common keys by `for` loop. 3. Check `type` of value of key is `dict` or not. 4. If value type is `dict` then call same function and pass values dictionary as arguments. and add result as key into `modified` dictionary. 5. If value type is not dict then add into `modified` dictionary. code: dict1 = { 'medic1' : {'date' : '02/02/2015', 'no' : '123' }, 'medic2' : {'date' : '02/03/2015', 'no' : '456' }, 'testkey1': 'testvalue1', 'testkey2': 'testvalue2', 'testkey3':{ "level2_1":"value2_1", "level2_2":{ "level3_1": "value3_1_change", "level3_2": "value3_2", } } } dict2 = { 'medic1' : {'date' : '02/02/2015', 'no' : '456' }, 'medic2' : {'date' : '02/03/2015', 'no' : '456' }, 'testkey1': 'testvalue1', 'testkey2': 'testvalue22', 'testkey3':{ "level2_1":"value2_1", "level2_2":{ "level3_1": "value3_1", "level3_2": "value3_2", } } } import copy def compareDict(dict1, dict2): d1_keys = dict1.keys() d2_keys = dict2.keys() intersect_keys = set(d1_keys).intersection(set(d2_keys)) modified = {} for i in intersect_keys: if dict1[i] != dict2[i] : if isinstance(dict1[i], dict) and isinstance(dict1[i], dict): modified[i]=compareDict(dict1[i], dict2[i]) else: modified.update({i : (dict1[i], dict2[i])}) return copy.deepcopy(modified) modified = compareDict(dict1, dict2) import pprint pprint.pprint(modified) output: vivek@vivek:~/Desktop/stackoverflow$ python 5.py {'medic1': {'no': ('123', '456')}, 'testkey2': ('testvalue2', 'testvalue22'), 'testkey3': {'level2_2': {'level3_1': ('value3_1_change', 'value3_1')}}}
Error using ncdump - NetCDF4 Python Question: I am using python to read a netcdf dataset. I have installed netcdf and I am trying to read the data by typing, ncdump("sample.nc",header_only=0). And I get the below error: /bin/sh: 1: ncdump.exe: not found. sample.nc is a netcdf file created using the following code: from netCDF4 import Dataset import numpy as np sfile = Dataset('sample.nc',mode='w', format='NETCDF4') Can anyone help me understand this error. I am quite new to this concept. Thanks Answer: I had this problem today, and I came across your question during my research to solve my problem. You don't have the ncdump command installed most likely. Download netCDF4.3.3.1-NC4-64.exe or the 32 bit version from the <http://www.unidata.ucar.edu/software/netcdf/docs/winbin.html>. I installed them to my program files. Add the path to the ncdump commands to your system path. I believe they are located in the bin folder once you have run the install. My path was... C:\Program Files (x86)\netCDF 4.3.3.1\bin Good Luck. ncdump -h filename in command prompt should work
Insufficient permission Site verification Google Question: I want to use python and the verification site api (v1) to verify website in my webmaster tools. In this example I want to get all verified sites using the verification api, because that function doesn't have parameters. (I know that it's possible via the webmaster tools, as well) #!/usr/bin/python import httplib2 from apiclient import errors from apiclient.discovery import build from oauth2client.client import OAuth2WebServerFlow from oauth2client.file import Storage http = httplib2.Http() storage = Storage('credentials') storage_verify = Storage('credentials_verify') credentials = storage.get() credentials_verify = storage_verify.get() http_wm = credentials.authorize(http) http_sv = credentials_verify.authorize(http) webmasters_service = build('webmasters', 'v3', http=http_wm) verification_service = build('siteVerification', 'v1', http=http_sv) site_list = webmasters_service.sites().list().execute() print(site_list) # this line generates the error verified_site_list = verification_service.webResource().list().execute() print(verified_site_list) There is an insufficient permission error: googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/siteVerification/v1/webResource?alt=json returned "Insufficient Permission"> I have read and write access for the siteVerification api (I've checked my token here: `https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=TOKEN` ) Any ideas what I'm doing wrong or how I can debug the code? Answer: Make sure you read and understand <https://developers.google.com/site- verification/v1/invoking> in its entirety. Especially you need to appreciate: > Verify a new site > > To verify a site, > > > - First request a verification token by calling getToken. > - Place the token on your site using whatever method you choose. > - Ask Google to verify that the site is yours, using the insert > operation. > All you need to do is properly construct two requests, `getToken` and `insert`. What "properly" means, is discussed in all detail in the docs I linked above. If you really need help with code, you need to show a minimal working example so that we can reproduce the error you retrieve.
Python login program Question: I'm writing a login program in Python,it takes the usernames and the passwords,and stores it for each user in a separate .txt file. I can already register,the program creates the file,but i can't login. Here's the code: ############### import getpass import time ussr=False passwd1=False acc=False notin=False reg=False t=[] ############### #f;a;;b;c;d;z;;;;; ############### def bor(): global acc print("1-->Login") print("2-->Register") a=int(input("B/R: ")) if a==1: acc=True if a==2: acc=False def ACCOUNT(): if acc==True: login() if acc==False: register() def file(): global jel f=open(z,"r") sor=f.read() jel=sor.strip().split() for s in jel: t.append(s) f.close() def register(): global reg reg=True global z b=input("Username: ") c=getpass.getpass('Passwd') z=input("Filename(.txt!):") f2=open(z,"w") f2.close() f=open(z,"r+") if b not in f: notin=True f.close if notin==True: f1=open(z,"a") f1.write(b) f1.write(c) f1.close if notin==False: print("This username is already taken") exit def login(): global usr global passwd global passwd1 global ussr global z usr=input("Username: ") passwd=getpass.getpass('Password') z=input("Filename(.txt!):") for i in t: if usr==i: ussr=True if passwd==i: passwd1=True def check(): if reg==True: exit if ussr==True and passwd1==True: print("Login succesful") time.sleep(12) if ussr==True and passwd1==False: print("Wrong password") if ussr==False and passwd1==True: print("Wrong username") bor() ACCOUNT() file() check() Answer: Please avoid using global variables, and start programming more "pythonic". Begin using a class object and function arguments. Really, global variables are BAD. Then: def ACCOUNT(): if acc==True: login() if acc==False: register() Is an horrible statement. def ACCOUNT(acc): if acc: login() else: register() is way better. You have to consider "if, else, elif", when you write conditions: if a == 1: doSomething() elif a == 2: doSomethingElse() else: doAnotherThing() To be clear, unless you need to check the variable type, generally "if varname" is ok (it will return false if an object is empty, or if a boolean value is equal to False and None as well). If you have to check on a boolean value, you generally don't have to specify the condition you're looking for. "if not a" is _more pythonic_ than "if a == False" (but, again, it will match "None" as well and not just "False"!!) And tell yourself, everytime you declare a global variable: "**I am doing something wrong, and there's for sure a better way to do this**. You can pass variables as function arguments: def sumFunction(arg1, arg2): return arg1 + arg2 and you can declare classes, to store variables, functions that work on the same task, and start programming better: class Authentication(): def __init__(self): # the __init__ class method is run everytime the function is istantiated self.example = 'I am an example' def Login(self, username, password): # this will do authentication things with # username and password variables, that lives # ONLY in this function (namespace) def Register(self, username, password): # do register things you can then istantiate the class Authentication like this auth = Authentication() and use the instance as you wish: auth.Login(username, password) auth.Register(username, password) "self" is the class namespace, viewed from itself. You can store whatever you like in it, and you can call sub-functions in class from one to another, prepending the "self." prefix In the example I have provided, you can access the "I am an example text" in this way: >>> x = Authentication() >>> x.example 'I am an example' Finally, when you declare a class method (a function in a class), you always have to specify "self" at first argument, but you don't need to pass it when calling the method from the outside (so a class method with 3 arguments: (self, arg1, arg2), will expect TWO arguments to work, just arg1 and arg2. **Read more, write less** , good luck.
Scikit-Learn's Pipeline: A sparse matrix was passed, but dense data is required Question: I'm finding it difficult to understand how to fix a Pipeline I created (read: largely pasted from a tutorial). It's python 3.4.2: df = pd.DataFrame df = DataFrame.from_records(train) test = [blah1, blah2, blah3] pipeline = Pipeline([('vectorizer', CountVectorizer()), ('classifier', RandomForestClassifier())]) pipeline.fit(numpy.asarray(df[0]), numpy.asarray(df[1])) predicted = pipeline.predict(test) When I run it, I get: TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array. This is for the line `pipeline.fit(numpy.asarray(df[0]), numpy.asarray(df[1]))`. I've experimented a lot with solutions through numpy, scipy, and so forth, but I still don't know how to fix it. And yes, similar questions have come up before, but not inside a pipeline. Where is it that I have to apply `toarray` or `todense`? Answer: Unfortunately those two are incompatible. A `CountVectorizer` produces a sparse matrix and the RandomForestClassifier requires a dense matrix. It is possible to convert using `X.todense()`. Doing this will substantially increase your memory footprint. Below is sample code to do this that I found at <http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of- pipelines.html> which allows you to call .todense() in a pipeline stage. class DenseTransformer(TransformerMixin): def transform(self, X, y=None, **fit_params): return X.todense() def fit_transform(self, X, y=None, **fit_params): self.fit(X, y, **fit_params) return self.transform(X) def fit(self, X, y=None, **fit_params): return self Once you have your `DenseTransformer`, you are able to add it as a pipeline step. pipeline = Pipeline([ ('vectorizer', CountVectorizer()), ('to_dense', DenseTransformer()), ('classifier', RandomForestClassifier()) ]) Another option would be to use a classifier meant for sparse data like `LinearSVC`. from sklearn.svm import LinearSVC pipeline = Pipeline([('vectorizer', CountVectorizer()), ('classifier', LinearSVC())])
Open URL encoded filenames in Unix Question: I'm a python n00b. I have downloaded URL encoded file and I want to work with it on my unix system(Ubuntu 14). When I try and run some operations on my file, the system says that the file doesn't exist. How do I change my filename to a unix recognizable format? Some of the files I have download have spaces in them so they would have to be presented with a backslash and then a space. Below is a snippet of my code link = "http://www.stephaniequinn.com/Music/Scheherezade%20Theme.mp3" output = open(link.split('/')[-1],'wb') output.write(site.read()) output.close() shutil.copy(link.split('/')[-1], tmp_dir) Answer: The "link" you have actually is a [URL](http://%3E%3E%3E%20import%20urllib.parse%20%3E%3E%3E%20url%20=%20%22http://www.stephaniequinn.com/Music/Scheherezade%20Theme.mp3%22%20%3E%3E%3E%20urllib.unqote\(url\)%20Traceback%20\(most%20recent%20call%20last\):%20%20%20File%20%22%3Cstdin%3E%22,%20line%201,%20in%20%3Cmodule%3E%20AttributeError:%20'module'%20object%20has%20no%20attribute%20'unqote'%20%3E%3E%3E%20urllib.parse.unquote\(url\)%20'http://www.stephaniequinn.com/Music/Scheherezade%20Theme.mp3'%20%3E%3E%3E). URLs are special and are not allowed to contain certain characters, such as spaces. These special characters can still be represented, but in an encoded form. The translation from special characters to this encoded form happens via a certain rule set, often known as "URL encoding". If interested, have a read over here: <http://en.wikipedia.org/wiki/Percent-encoding> The encoding operation can be inverted, which is called decoding. The tool set with which you downloaded the files you mentioned most probably did the decoding already, for you. In your link example, there is only one special character in the URL, "%20", and this encodes a space. Your download tool set probably decoded this, and saved the file to your file system with the actual space character in the file name. That is, most likely you have a file in the file system with the following [basename](http://linux.die.net/man/1/basename): Scheherezade Theme.mp3 So, when you want to open that file from within Python, and all you have is the `link`, you first need to get the decoded variant of it. Python can decode URL-encoded strings with built-in tools. This is what you need: >>> import urllib.parse >>> url = "http://www.stephaniequinn.com/Music/Scheherezade%20Theme.mp3" >>> urllib.parse.unquote(url) 'http://www.stephaniequinn.com/Music/Scheherezade Theme.mp3' >>> This assumes that you are using Python 3, and that your `link` object is a unicode object (type `str` in Python 3). Starting off with the **decoded** URL, you can derive the filename. Your `link.split('/')[-1]` method might work in many cases, but J.F. Sebastian's answer provides a more reliable method.
Generating url with fields.Url when using Flask-Restful generates BuildError Question: I wanted to adapt the wonderful [Tutorial from Miguel Grinberg](http://blog.miguelgrinberg.com/post/designing-a-restful-api-using- flask-restful) to create a unittest test-executor. I principally just adapted the code from Miguel to my needs, but I get a problem with generating the uri inside the fields map. As long as I remove the 'uri': fields.Url('test') everything works fine, but otherwise I get a Build Error: BuildError: ('test', {'Test_environment_id': 123, 'Test_duration': '0.5 sec', 'Success': 1, 'Failure_count': 0, 'Tested_files': 'Some files', 'Request_id': 1, 'Runs_count': 3, 'Created_on': '01.01.1970', 'Error_count': 0, 'Requester': 'John', 'Skipped_count': 2}, None) I discovered very similar Question here on stackoverflow [here](http://stackoverflow.com/questions/22619969/two-variable-urls-using- flask-restful) but this did not help me to understand what is wrong with my code.I can use the described work-around from that question, but I would really like to know what am I doing wrong. Here is my code: #!/usr/bin/python __author__ = 'karlitos' from flask import Flask, jsonify, abort, make_response, request from flask.ext.restful import Api, Resource, reqparse, fields, marshal,url_for from time import strftime from glob import glob import os import sqlite3 CURRENT_DIRECTORY = os.getcwd() PROJECT_DIRECTORIES = glob('{}/projects/*'.format(CURRENT_DIRECTORY)) # create a sqlite database connection object db_con = sqlite3.connect('{}unittest.db'.format(CURRENT_DIRECTORY)) app = Flask(__name__, static_url_path="") api = Api(app) tests = [ { 'Request_id': 1, 'Requester': 'John', 'Created_on': '01.01.1970', 'Test_environment_id': 123, 'Tested_files': 'Some files', 'Test_duration': '0.5 sec', 'Runs_count': 3, 'Error_count': 0, 'Failure_count': 0, 'Skipped_count': 2, 'Success': 1 } ] """Structure storing the `Request_id`'s of all test currently running indexed by their `Test_environment_id`'s.""" env_id_of_running_tests = {} """Structure serving as a template for the `marshal` function which takes raw data and a dict of fields to output and filters the data based on those fields.""" test_fields = { 'Request_id': fields.Integer, 'Requester': fields.String, 'Created_on': fields.String, 'Test_environment_id': fields.Integer, 'Tested_files': fields.String, 'Test_duration': fields.String, 'Runs_count': fields.Integer, 'Error_count': fields.Integer, 'Failure_count': fields.Integer, 'Skipped_count': fields.Integer, 'Success': fields.Boolean, 'uri': fields.Url('test') } """Validation function for the environment-id type which has to be in range [1,100]""" def env_id_type(value, name): if value <= 1 or value >= 100: raise ValueError("The parameter '{}' is not between 1 and 100. The value: {} was provided".format(name, value)) return value class TestsAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('Requester', type=str, required=True, help='No requester name provided', location='json') self.reqparse.add_argument('Test_environment_id', type=env_id_type, required=True, help='Bad environment-id provided, between 1 and 100.', location='json') super(TestsAPI, self).__init__() def get(self): return {'tests': [marshal(test, test_fields) for test in tests]} def post(self): args = self.reqparse.parse_args() request_id = tests[-1]['Request_id'] + 1 # check if the current Test_environment_id is not under the currently running test if args['Test_environment_id'] in env_id_of_running_tests: return {'message': 'Another test with the same Environment-ID is still running.'}, 409 else: env_id_of_running_tests[args['Test_environment_id']] = request_id test = { 'Request_id': request_id, 'Requester': args['Requester'], 'Created_on': strftime('%a, %d %b %Y %H:%M:%S'), 'Test_environment_id': args['Test_environment_id'], 'Tested_files': 'Some files', 'Test_duration': '', 'Runs_count': None, 'Error_count': None, 'Failure_count': None, 'Skipped_count': None, 'Success': None } tests.append(test) return {'test started': marshal(test, test_fields)}, 201 class TestAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('Request_id', type=int, required=True, help='No Request-ID provided', location='json') super(TestAPI, self).__init__() def get(self, request_id): test = [test for test in tests if test['Request_id'] == request_id] print 'Request_ID', request_id if len(test) == 0: abort(404) return {'test ': marshal(test[0], test_fields)} api.add_resource(TestsAPI, '/test-executor/api/tests', endpoint='tests') api.add_resource(TestAPI, '/test-executor/api/tests/<int:request_id>', endpoint='test') if __name__ == '__main__': app.run(debug=True) Answer: Your 'test' endpoint's route has a parameter `request_id` (with a lowercase initial r), but your test data dict has an entry with the key `Request_id` (upper case initial R). When marshalling the data, flask-restful looks for an entry with the lowercase `request_id` in the test data dictionary in order to construct the URL, but it can't find it because of the case mismatch. If you change the parameter in the route to uppercase `Request_id` it'll take care of your BuildError for requests to the 'tests' endpoint. But with a request to the test endpoint, you'll then have new easily fixable errors due to similar case mismatches in TestAPI.get().
Python-ping module not found after installation Question: I tried to install [python-ping](https://pypi.python.org/pypi/python- ping/2011.10.17.376a019) with `pip` but I was getting: Downloading/unpacking python-ping Could not find a version that satisfies the requirement python-ping (from versions: 2011.10.12.11fc9f7, 2011.10.12.1d8e600, 2011.10.13.12050a5, 2011.10.17.376a019) Cleaning up... No distributions matching the version for python-ping Storing debug log for failure in /root/.pip/pip.log So I installed it with `pip install --pre python-ping` and the installation outputted: Downloading/unpacking python-ping Downloading python-ping-2011.10.17.376a019.tar.gz Running setup.py (path:/tmp/pip-build-8QnXqD/python-ping/setup.py) egg_info for package python-ping warning: no previously-included files matching '*.pyc' found under directory '*' warning: no previously-included files matching '*.pyo' found under directory '*' Installing collected packages: python-ping Running setup.py install for python-ping changing mode of build/scripts-2.7/ping.py from 644 to 755 warning: no previously-included files matching '*.pyc' found under directory '*' warning: no previously-included files matching '*.pyo' found under directory '*' changing mode of /usr/bin/ping.py to 755 Successfully installed python-ping Cleaning up... Despite the warnings I assumed it was successful. I then tried to import the ping module to give it a test, copy-pasting the [first answer here](http://stackoverflow.com/questions/316866/ping-a-site-in- python), but I'm getting: ImportError: No module named ping First time I encounter any problems installing a module with `pip`. How can I fix this? Answer: According the the `setup.py` of the package of `python-ping`, it does not install a module, but instead installs a script (which should be installed in your python scripts folder). You should invoke the script directly, eg: `ping.py www.google.com`. If this does not work, make sure your path is set to include the python scripts folder on your system. If you'd prefer a module solution, check out `ping` on pypi, <https://pypi.python.org/pypi/ping/0.2>
python script for saving subsequent images without overwriting Question: I am new to python but I have been able to make a script (pls see code below and attached picture ) that accesses abaqus .odb output file and saves the contour map as a .tiff file. Since this script runs at interval, the new image file overwrites the previous but I actually want to save the subsequent images with different name e.g. VMises_01, VMises_02, VMises_03, etc. Please i need asssistance in modifying the script to do this. Thank you in advance for your help. # -*- coding: mbcs -*- from abaqus import * from abaqusConstants import * session.Viewport(name='Viewport: 1', origin=(0.0, 0.0), width=153.191665649414, height=265.695220947266) session.viewports['Viewport: 1'].makeCurrent() session.viewports['Viewport: 1'].maximize() from caeModules import *![enter image description here][1] from driverUtils import executeOnCaeStartup executeOnCaeStartup() session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues( referenceRepresentation=ON) Mdb() session.viewports['Viewport: 1'].setValues(displayedObject=None) import os os.chdir(r"C:\Work\2015 CA") o1 = session.openOdb(name='C:/Work/2015 CA/cafe_del.odb') session.viewports['Viewport: 1'].setValues(displayedObject=o1) session.viewports['Viewport: 1'].odbDisplay.display.setValues(plotState=( CONTOURS_ON_DEF, )) session.viewports['Viewport: 1'].odbDisplay.commonOptions.setValues( visibleEdges=FEATURE, deformationScaling=UNIFORM, uniformScaleFactor=1) session.printToFile(fileName='C:/Work/2015 CA/VMises_01', format=TIFF, canvasObjects=(session.viewports['Viewport: 1'], )) session.odbs['C:/Work/2015 CA/cafe_del.odb'].close() Answer: One simple way of getting a unique filename would be to append a timestamp. e.g. replace session.printToFile( fileName='C:/Work/2015 CA/VMises_01', format=TIFF, canvasObjects=(session.viewports['Viewport: 1'], )) with session.printToFile( fileName='C:/Work/2015 CA/VMises_%s' % datetime.datetime.now().strftime('%Y%d%m%H%M%S') , format=TIFF, canvasObjects=(session.viewports['Viewport: 1'], )) If instead you want the counter 01, 02, 03, etc, that you proposed, then you'll either need to (a) keep a record of the current number within the script (either in memory or to disk if the script doesn't run continuously), or (b) look at the directory contents to determine the next available number each time.
Python: lxml formatting Question: I need to create an xml file. Is there a possibility to get the following formatting? The len of the list is normally bigger and always different. So I can not use if loop with a request of the list length. Needed formatting: <test> <fanart> <thumb preview="http://image.tmdb.org/t/p/w342/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg">http://image.tmdb.org/t/p/original/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg</thumb> <thumb preview="http://image.tmdb.org/t/p/w342/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg">http://image.tmdb.org/t/p/original/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg</thumb> <thumb preview="http://image.tmdb.org/t/p/w342/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg">http://image.tmdb.org/t/p/original/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg</thumb> <thumb preview="http://image.tmdb.org/t/p/w342/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg">http://image.tmdb.org/t/p/original/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg</thumb> </fanart> </test> Code: import lxml.builder E = lxml.builder.ElementMaker() nfo = E.test() list = [('http://image.tmdb.org/t/p/w342/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg','http://image.tmdb.org/t/p/original/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg'), ('http://image.tmdb.org/t/p/w342/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg','http://image.tmdb.org/t/p/original/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg'), ('http://image.tmdb.org/t/p/w342/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg','http://image.tmdb.org/t/p/original/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg'), ('http://image.tmdb.org/t/p/w342/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg','http://image.tmdb.org/t/p/original/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg')] for (link_thumb, link_orig) in list: fanart = E.fanart(E.thumb(link_orig,preview=link_thumb)) nfo.append(fanart) print lxml.etree.tostring(nfo, pretty_print=True) Output: <test> <fanart> <thumb preview="http://image.tmdb.org/t/p/w342/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg">http://image.tmdb.org/t/p/original/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg</thumb> </fanart> <fanart> <thumb preview="http://image.tmdb.org/t/p/w342/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg">http://image.tmdb.org/t/p/original/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg</thumb> </fanart> <fanart> <thumb preview="http://image.tmdb.org/t/p/w342/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg">http://image.tmdb.org/t/p/original/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg</thumb> </fanart> <fanart> <thumb preview="http://image.tmdb.org/t/p/w342/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg">http://image.tmdb.org/t/p/original/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg</thumb> </fanart> </test> Thank you! Answer: You appended `fanart` elements for each `image`; instead make 1 `fanart` element and append it to the `nfo`; then append each image into that `fanart` element: import lxml.builder E = lxml.builder.ElementMaker() nfo = E.test() fanart = E.fanart() nfo.append(fanart) items = [('http://image.tmdb.org/t/p/w342/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg','http://image.tmdb.org/t/p/original/krkkgbtWHlMXVLbPGdIxzxKJERM.jpg'), ('http://image.tmdb.org/t/p/w342/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg','http://image.tmdb.org/t/p/original/izYCpovyAIKLI2i3gmhSKxlR8Pk.jpg'), ('http://image.tmdb.org/t/p/w342/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg','http://image.tmdb.org/t/p/original/vmrnxaYx1xlG5jhuFUs51dd3VPA.jpg'), ('http://image.tmdb.org/t/p/w342/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg','http://image.tmdb.org/t/p/original/pPFbXcONHBntJIAsEn8TaIPPCpZ.jpg')] for (link_thumb, link_orig) in items: fanart.append(E.thumb(link_orig,preview=link_thumb)) print lxml.etree.tostring(nfo, pretty_print=True)
Executing python class code located in folders Question: I currently have a folder structure like this: . ├── main.py └── parent.py └── classes └── subclass1.py └── subclass2.py └── subclass3.py Each of the `subclass`es are a subclass of `parent`, and parent is an abstract class. The subclasses need to execute some functions like `mix()` and `meld()`, and each of these subclasses must implement `mix()` and `meld()`. I would like to write `main.py` such that the functions in each of the subclasses are executed, without me having to `import` their files into my program. That is, I'd like something akin to the following to happen: def main(): # Note that I don't care about the order of which these for each subclass in the sources folder: execute `mix()` and `meld()` # Note that I don't mind which order the order # of which the subclasses' functions are invoked. Is there any way I could get this to happen? Essentially, what I want to do is drop a bunch of classes into the `classes` folder, with only `mix()` and `meld()` defined, and let this program run wild. Answer: I've never tried this, but I _think_ it does what you're asking for: import os import imp import runpy package = 'classes' _, path, _ = imp.find_module(package) for m in os.listdir(path): if m.endswith('.py'): runpy.run_module( package + '.' + os.path.splitext(m)[0], run_name="Mix_Meld" ) Then, inside of your subclasses, you can write: if __name__ == 'Mix_Meld': ClassName.mix() ClassName.meld() This may result in additional code, granted, but if you ever need to stop the execution in one of the files, doing so is just a matter of commenting out that part of the code. Another advantage is extensibility and polymorphism; if you need to run the code a bit differently for each one of these modules in the future, you only have to change the behaviour in the specific modules. The callee (`main.py`) will remain oblivious to those changes and continue calling the modules the usual way.
IndexError: too many indices for array while plotting ROC curve with scikit-learn? Question: I would like to plott the ROC curve that scikit-lern implements so I tried the following: from sklearn.metrics import roc_curve, auc false_positive_rate, recall, thresholds = roc_curve(y_test, prediction[:, 1]) roc_auc = auc(false_positive_rate, recall) plt.title('Receiver Operating Characteristic') plt.plot(false_positive_rate, recall, 'b', label='AUC = %0.2f' % roc_auc) plt.legend(loc='lower right') plt.plot([0, 1], [0, 1], 'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.ylabel('Recall') plt.xlabel('Fall-out') plt.show() And this is the output: Traceback (most recent call last): File "/Users/user/script.py", line 62, in <module> false_positive_rate, recall, thresholds = roc_curve(y_test, prediction[:, 1]) IndexError: too many indices for array Then from a [previous question](https://stackoverflow.com/questions/25125300/plotting-roc-curve-too- many-indices-error) I tried this: false_positive_rate, recall, thresholds = roc_curve(y_test, prediction) And got this traceback: /usr/local/lib/python2.7/site-packages/sklearn/metrics/metrics.py:705: DeprecationWarning: elementwise comparison failed; this will raise the error in the future. not (np.all(classes == [0, 1]) or /usr/local/lib/python2.7/site-packages/sklearn/metrics/metrics.py:706: DeprecationWarning: elementwise comparison failed; this will raise the error in the future. np.all(classes == [-1, 1]) or Traceback (most recent call last): File "/Users/user/PycharmProjects/TESIS_CODE/clasificacion_simple_v1.py", line 62, in <module> false_positive_rate, recall, thresholds = roc_curve(y_test, prediction) File "/usr/local/lib/python2.7/site-packages/sklearn/metrics/metrics.py", line 890, in roc_curve y_true, y_score, pos_label=pos_label, sample_weight=sample_weight) File "/usr/local/lib/python2.7/site-packages/sklearn/metrics/metrics.py", line 710, in _binary_clf_curve raise ValueError("Data is not binary and pos_label is not specified") ValueError: Data is not binary and pos_label is not specified Then I also tried this: false_positive_rate, recall, thresholds = roc_curve(y_test, prediction[0].values) And this is the traceback: AttributeError: 'numpy.int64' object has no attribute 'values' Any idea of how to correctly plot this metric?. Thanks in advance! This is the shape of the prediction varibale: print prediction.shape (650,) this is the shape of `testing_matrix: (650, 9596)` Answer: The variable `prediction` needs to be a `1d array` (the same shape as `y_test`). You can check by inspecting the shape attribute e.g. `y_test.shape`. I think prediction[0].values returns AttributeError: 'numpy.int64' object has no attribute 'values' because you are trying to call `.values` on an element of prediction. **Update:** ValueError: Data is not binary and pos_label is not specified I didn't notice this before. If your classes are not binary, you have to specify the `pos_label` parameter when in`roc_curve` so it plots one class vs the rest. For this to work you need your class labels to be integers. You can use: from sklearn.preprocessing import LabelEncoder class_labels = LabelEncoder() prediction_le = class_lables.fit_transform(prediction) `pediction_le` returns classes recodes a `int` **Update 2:** Your predictor is only returning one class, so you cannot plot the ROC curve
read and write files from dropbox using python Question: I am trying to write a code (for my personal use) that will access a particular directory in my dropbox. The code currently uses local folder in my machine, and also lives in my local machine. The minimal code is: $ cat sync.py #!/usr/bin/python3 import dropbox #This part is not yet needed as my work is still local client = dropbox.client.DropboxClient\ ("<access_code>") print(client.account_info()) with open("~/Dropbox/ToDo/greet.html", "r") as fin: print(fin.read()) This works fine, but I have to be with my laptop on. Can I put the code in dropbox itself and make it run every hour? (in my local machine I do it with cron) Kindly help. Answer: No, Dropbox itself doesn't offer any sort of application hosting where you can run code like this remotely.
searching files from a lot of files for a keyword and printing the sentence containing keyword,filename in python Question: import os path = 'C:\\Users\\Kabeer\\Documents\\testdata' listing = os.listdir(path) for infile in listing: read_f = open(infile) for line in read_f: if 'arch' in line: print(line) print ("current file is: " + infile) I have placed all the files in a folder. I want to read each file for a keyword. If it contains the keyword then print the name of file and entire sentence containing keyword. I am absolute beginner in python. The code above is also picked from stackoverflow forum only. I am getting error. File not found error read_f=open(infile).No such file or directory. I know error is in loop. How to put each file through loop? I tried also putting all the files in list. But I am not able to get each file and read from loop. Thanks Kabeer Answer: Try use `read_f = open(os.path.join(path,infile))`
PhantomJS don't load mobile.twitter.com via Selenium Question: My configuration - _Selenium 2.44.0 + Python 3.4.2 + PhantomJS 2.0.0 (on Windows 7 x64)_. I try to load <https://mobile.twitter.com> from Python program using PhantomJS WebDriver and I get error message: Traceback (most recent call last): File "C:\Python\Python342x64\myprog\code.py", line 11, in <module> browser.get('https://mobile.twitter.com/') File "C:\Python\Python342x64\lib\site-packages\selenium-2.44.0-py3.4.egg\selenium\webdriver\remote\webdriver.py", line 185, in get self.execute(Command.GET, {'url': url}) File "C:\Python\Python342x64\lib\site-packages\selenium-2.44.0-py3.4.egg\selenium\webdriver\remote\webdriver.py", line 171, in execute response = self.command_executor.execute(driver_command, params) File "C:\Python\Python342x64\lib\site-packages\selenium-2.44.0-py3.4.egg\selenium\webdriver\remote\remote_connection.py", line 349, in execute return self._request(command_info[0], url, body=data) File "C:\Python\Python342x64\lib\site-packages\selenium-2.44.0-py3.4.egg\selenium\webdriver\remote\remote_connection.py", line 417, in _request resp = opener.open(request) File "C:\Python\Python342x64\lib\urllib\request.py", line 455, in open response = self._open(req, data) File "C:\Python\Python342x64\lib\urllib\request.py", line 473, in _open '_open', req) File "C:\Python\Python342x64\lib\urllib\request.py", line 433, in _call_chain result = func(*args) File "C:\Python\Python342x64\lib\urllib\request.py", line 1202, in http_open return self.do_open(http.client.HTTPConnection, req) File "C:\Python\Python342x64\lib\urllib\request.py", line 1177, in do_open r = h.getresponse() File "C:\Python\Python342x64\lib\http\client.py", line 1172, in getresponse response.begin() File "C:\Python\Python342x64\lib\http\client.py", line 351, in begin version, status, reason = self._read_status() File "C:\Python\Python342x64\lib\http\client.py", line 313, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "C:\Python\Python342x64\lib\socket.py", line 371, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] Code of my program: import os, sys from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.common.exceptions import NoSuchElementException from random import randint from time import sleep browser = webdriver.PhantomJS('C:\Program Files (x86)\PhantomJS\phantomjs.exe') browser.get('https://mobile.twitter.com/') sleep(randint(5,10)) browser.save_screenshot('out1.png') g = open('C:\\Python\\Python342x64\\prog\\page.htm', 'a', encoding='utf8', errors='replace') g.write(browser.page_source + '\n') If I use Firefox instead of PhantomJS, everything work fine. (or if i load desktop version of twitter) How I can fix this problem with PhantomJS? Answer: try to set user agent like: Android / Firefox 29: Mozilla/5.0 (Android; Mobile; rv:29.0) Gecko/29.0 Firefox/29.0
Python Regular expression for splitting mentions of two years appearing altogether Question: I have the following case, where in my string I have improperly formatted mentions of the form "(19561958)" that I would like to split into "(1956-1958)". The regular expression that I tried is: import re a = "(19561958)" re.sub(r"(\d\d\d\d\d\d\d\d)", r"\1-", a) but this returns me "(19561958-)". How can I achieve my purpose? Many thanks! Answer: You could capture the two years separately, and insert the hyphen between the two groups: >>> import re >>> re.sub(r'(\d{4})(\d{4})', r'\1-\2', '(19561958)') '(1956-1958)' Note that `\d\d\d\d` is written more concisely as `\d{4}`. * * * As currently written, this will insert a hyphen between the first two groups of four in _any_ eight-digit-plus number. If you _require_ the parentheses for the match, you can include them explicitly with look-arounds: >>> re.sub(r''' (?<=\() # make sure there's an opening parenthesis prior to the groups (\d{4}) # one group of four digits (\d{4}) # and a second group of four digits (?=\)) # with a closing parenthesis after the two groups ''', r'\1-\2', '(19561958)', flags=re.VERBOSE) '(1956-1958)' Alternatively, you could use word boundaries, which would also deal with e.g. spaces around an eight-digit number: >>> re.sub(r'\b(\d{4})(\d{4})\b', r'\1-\2', '(19561958)') '(1956-1958)'
circular numpy array indices Question: I have a 1-D numpy array `a = [1,2,3,4,5,6]` and a function that gets two inputs, `starting_index` and `ending_index`, and returns `a[staring_index:ending_index]`. Clearly I run into trouble when `ending_index` is smaller than `starting_index`. In this case, the function should start from the starting_index and traverse the vector `a` in a circular way, i.e., return all the elements coming after `starting_index` plus all the elements from index zero to `ending_index`. For instance, if `starting_index=4` and `ending_index=1` then the output should be `output = [5,6,1]`. I can implement it with an `if` condition but I was wondering if there is any Pythonic and concise way to do it? Answer: Unfortunatly you cannot do this with slicing, you'll need to concatonate to two segments: import numpy as np a = [1, 2, 3, 4, 5, 6] if starting_index > ending_index: part1 = a[start_index:] part2 = a[:end_index] result = np.concatenate([part1, part2]) else: result = a[start_index:end_index]
Uninstalled IPython on Ubuntu but can still be used Question: I tried to install rpy2 earlier today, to use IPython Notebooks in conjunction with R. I'm using Ubuntu 12.04. However, I had issues with using the magics extension, so went off down a rathole to resolve... I've tried to uninstall IPython via the command sudo apt-get remove --auto-remove ipython ... which seemed to work correctly, and from looking in `/usr/lib/python2.7/dist-packages`, I manually can't see an IPython directory. I double checked the uninstallation method worked: me@my_laptop:/usr/lib/python2.7/dist-packages$ sudo apt-get remove -auto-remove ipython Reading package lists... Done Building dependency tree Reading state information... Done Package ipython is not installed, so not removed 0 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade. However, I can go into a terminal and type `ipython` I get the following -- note that I can import the package as well: me@my_laptop:/usr/lib/python2.7/dist-packages$ pwd /usr/lib/python2.7/dist-packages me@my_laptop:/usr/lib/python2.7/dist-packages$ ipython Python 2.7.3 (default, Dec 18 2014, 19:10:20) Type "copyright", "credits" or "license" for more information. IPython 3.0.0-b1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import IPython In [2]: IPython Out[2]: <module 'IPython' from '/usr/local/lib/python2.7/dist-packages/IPython/__init__.pyc'> NB I tried to use the comment by kermit666 in, butthis did not seem to help: [Broken IPython notebook install Ubuntu 13.10 how to force reinstall](http://stackoverflow.com/questions/20454921/broken-ipython- notebook-install-ubuntu-13-10-how-to-force-reinstall) Does Python cache its packages somehow, like in a database, that I need to update somehow? I don't understand how it is loading something that in theory has been deleted? Answer: you just check the package where it's located $ which ipython May be u get the path `/usr/local/bin/` and then type the command. $ sudo rm -rf /usr/local/bin/ipython It may be works.It's worked for me.
In a Django web application, would large files or many unnecessary import statements slow down my server? Question: In my Django web app, I have pretty much one large file that contains all my views. This has a ton of imported python libraries that are only used for certain views. Does this slow my code? Like in python does importing things like python natural language toolkit (nlkt) and threading libraries slow down the code when its not needed? I know its not great for a maintainability/style standpoint to have one big file like this, but I am asking purely from a performance standpoint. Answer: No, code speed is not affected by the size of your modules. Additional imports only affect the memory footprint (a little more memory is needed to hold the extra code objects) and startup speed (more files are loaded from disk when your Django server starts). However, this doesn't really affect code running speeds; Python does not have to do extra work to run your code.
install issue with python - spacy package in anaconda environment Question: I'm attempting to follow [this tutorial](http://honnibal.github.io/spaCy/quickstart.html) to install the natural language processing package spaCy into a python 3 anaconda environment, windows 8 I opened console, cd-ed to my site-packages folder, activated environment, pip-ed for install, everything seemed fine except I couldn't run the second command here $ pip install spacy $ python -m spacy.en.download Now I can successfully load the package but when I run the second line below, I get the following error >>> from spacy.en import English #this works >>> nlp = English() #this doesn't Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\garrett\Anaconda\envs\py3k\lib\site-packages\spacy\en\__init__.py", line 64, in __init__ get_lex_props=get_lex_props) File "spacy/vocab.pyx", line 42, in spacy.vocab.Vocab.__init__ (spacy/vocab.cpp:2216) OSError: Directory C:\Users\garrett\Anaconda\envs\py3k\lib\site-packages\spacy\en\data\vocab not found -- cannot load Vocab. I think that it is due to the fact that I couldn't run `python -m spacy.en.download` **Can anyone give me an idea of what`python -m spacy.en.download` is supposed to be doing?** **Can anyone provide a walkthrough for how to get spaCy installed in an anaconda environment?** here's the error I get after setting the directory, activating python env, running command. The first several times I tried, my spyder editor went unresponsive and I killed the console, the most recent time I got this error $ cd C:\Users\garrett\Anaconda\envs\py3k\Lib\site-packages $ C:\Users\garrett\Anaconda\envs\py3k\Lib\site-packages>activate py3k $ [py3k] C:\Users\garrett\Anaconda\envs\py3k\Lib\site-packages>python -m spacy.en.download Moving existing dir C:\Users\garrett\Anaconda\envs\py3k\Lib\site-packages\spacy\en\data to /tmp Traceback (most recent call last): File "C:\Users\garrett\Anaconda\envs\py3k\lib\runpy.py", line 160, in _run_module_as_main "__main__", fname, loader, pkg_name) File "C:\Users\garrett\Anaconda\envs\py3k\lib\runpy.py", line 73, in _run_code exec(code, run_globals) File ".\spacy\en\download.py", line 56, in <module> plac.call(main) File ".\plac_core.py", line 309, in call cmd, result = parser_from(obj).consume(arglist) File ".\plac_core.py", line 195, in consume return cmd, self.func(*(args + varargs + extraopts), **kwargs) File ".\spacy\en\download.py", line 51, in main shutil.move(DEST_DIR, '/tmp') File "C:\Users\garrett\Anaconda\envs\py3k\lib\shutil.py", line 521, in move raise Error("Destination path '%s' already exists" % real_dst) shutil.Error: Destination path '/tmp\data' already exists appreciate any help or advice you can provide Answer: You have hit [this bug](https://github.com/honnibal/spaCy/issues/41) which should be already fixed in the last version. Apparently spacy can't download the data because the destination already exists (may be from a previous interrupted download). A workaround would be to delete the `/temp/data` folder and retry the download.
How to implement login handover from mechanize to pycurl Question: I need to login into a website by using mechanize in python and then continue traversing that website using pycurl. So what I need to know is how to transfer a logged-in state established via mechanize into pycurl. I assume it's not just about copying the cookie over. Or is it? Code examples are valued ;) **Why I'm not willing to use pycurl alone:** I have time constraints and my mechanize code worked after 5 minutes of modifying [this](http://www.pythonforbeginners.com/mechanize/browsing-in-python-with- mechanize) example as follows: import mechanize import cookielib # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # debugging messages? #br.set_debug_http(True) #br.set_debug_redirects(True) #br.set_debug_responses(True) # User-Agent (this is cheating, ok?) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] # Open the site r = br.open('https://thewebsite.com') html = r.read() # Show the source print html # or print br.response().read() # Show the html title print br.title() # Show the response headers print r.info() # or print br.response().info() # Show the available forms for f in br.forms(): print f # Select the first (index zero) form br.select_form(nr=0) # Let's search br.form['username']='someusername' br.form['password']='somepwd' br.submit() print br.response().read() # Looking at some results in link format for l in br.links(url_regex='\.com'): print l Now if I could only transfer the right information from br object to pycurl I would be done. **Why I'm not willing to use mechanize alone:** Mechanize is based on urllib and urllib is a nightmare. I had too many traumatizing issues with it. I can swallow one or two calls in order to login, but please no more. In contrast pycurl has proven for me to be stable, customizable and fast. From my experience, pycurl to urllib is like star trek to flintstones. PS: In case anyone wonders, I use BeautifulSoup once I have the html Answer: Solved it. Appartently it WAS all about the cookie. Here is my code to get the cookie: import cookielib import mechanize def getNewLoginCookieFromSomeWebsite(username = 'someusername', pwd = 'somepwd'): """ returns a login cookie for somewebsite.com by using mechanize """ # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but does not hang on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # User-Agent br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:26.0) Gecko/20100101 Firefox/26.0')] # Open login site response = br.open('https://www.somewebsite.com') # Select the first (index zero) form br.select_form(nr=0) # Enter credentials br.form['user']=username br.form['password']=pwd br.submit() cookiestr = "" for c in br._ua_handlers['_cookies'].cookiejar: cookiestr+=c.name+'='+c.value+';' return cookiestr In order to activate the usage of that cookie when using pycurl, all you have to do is to type the following before `c.perform()` occurs: c.setopt(pycurl.COOKIE, getNewLoginCookieFromSomeWebsite("username", "pwd")) Keep in mind: some websites may keep interacting with the cookie via `Set- Content` and pycurl (unlike mechanize) does not automatically execute any operations on cookies. Pycurl simply receives the string and leaves to the user what to do with it.
Python3 correct way to import relative or absolute? Question: I am writing a python module _neuralnet_. It was working all fine in Python2, but in Python3, imports are failing. This is my code structure. neuralnet/ __init__.py train.py # A wrapper to train (does not define new things) neuralnet.py # Defines the workhorse class neuralnet layers/ __init__.py inlayer.py # Defines input layer class hiddenlayer.py application/ # A seperate application (not part of the package) classify.py # Imports the neuralnet class from neuralnet.py train.py needs to import neuralnet.py's neuralnet class. neuralnet.py needs to import layers/inlayer.py etc. (I prefer relative imports.) I have a different application (classify.py) which needs to import this module. Where I do... from neuralnet.neuralnet import neuralnet I have tried a few ways to import. Either I get an error (mostly arcane like parent is not imported) 1) While running train.py (which is a part of the neuralnet module) from . import layer # In file neuralnet.py SystemError: Parent module '' not loaded, cannot perform relative import Or 2) while running classify.py (which is outside the module). from layer.inlayers import input_layer # In file neuralnet.py ImportError: No module named 'layer' My imports worked perfectly well for years in Python2. I am wondering what Python3 expects of me? Should I move train.py to outside my module (technically it is not a part of the module)? Please suggest best practice. Thanks Rakesh Answer: In Python 3, _implicit_ relative imports are forbidden, see <https://www.python.org/dev/peps/pep-0328/> and <https://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax>: > The only acceptable syntax for relative imports is from .[module] import > name. All import forms not starting with . are interpreted as absolute > imports. (PEP 0328) `from .stuff import Stuff` is an _explicit_ relative import, which you "should" make use of whenever possible, and _must_ use in Python 3, whenever possible. Head over to <http://stackoverflow.com/a/12173406/145400> for a deeper analysis on relative imports.
How to get Python List from QVariant Question: If `Qt.UserRole` the model's `headerData()` returns a Python list variable: if role==Qt.UserRole: return QVariant(['one','two','three']) Instead of a regular Python list a function that calls with: returnedValue = myModel(index.column(), Qt.Horizontal, Qt.UserRole) gets a `QVariant` object: <PyQt4.QtCore.QVariant object at 0x10d3b67c0> An attempt to convert the returned `QVariant` object to Python using: pythonList=returnedValue.toPyObject() didn't work. I have tried to do: for each in returnedValue.toList(): print each But that still prints out some QVariants. What method should be used to convert QVariant to Python list? Answer: QVariant is a general container for almost all kinds of built-in types, so in order to cast QVariant data back, you need to know what kind of data it is stored. from PyQt4.QtCore import QVariant a = QVariant(['one', 'two', 'three']) aList = [unicode(i.toString()) for i in a.toList()] print aList output is as : `[u'one', u'two', u'three']`
Python - retrieved different result when using curl and requests library Question: I'm trying to build a python crawler using `requests` library. When i use `get` method i retrieved result look like: `THá» THAO`. But when i use `curl` i got `THỂ THAO` and it is my expected result. Here is my code: def get_raw_channel(): r = requests.get('http://vtv.vn/') raw_html = r.text soup = BeautifulSoup(raw_html) o_tags = soup.find_all("option") for o_tag in o_tags: print o_tag.text # raw_channel = RawChannel(o_tag.text.strip(), o_tag['value']) # channels_file.write(raw_channel.__str__() + '\n') Here is my curl cmd: `curl http://vtv.vn/` **Question:** why the results is different? How can i achieve `curl`'s result by using `requests`? Answer: I tried your code and in my case the encoding was 'ISO-8859-1', try to encode your data into UTF-8 before process it in BS, something like: ... raw_html = r.text.encode("utf-8") soup = BeautifulSoup(raw_html) ... **UPDATE:** I made some more tests, looks like everything worked for me because I explicitly set encoding for request, take a look In [1]: import requests In [2]: from BeautifulSoup import BeautifulSoup In [3]: r = requests.get('http://vtv.vn/') In [4]: r.encoding = "utf-8" In [5]: raw_html = r.text In [6]: soup = BeautifulSoup(raw_html) In [7]: soup.findAll("option") Out[7]: [<option value="1"> VTV1</option>, ... stripped out some output ... VTVCab3 - Thể thao TV</option>, <option value="13"> ... stripped out some output ... ]
ImportError: Module not found but sys.path is showing the file resides under the path Question: When I print sys.path in my code I get the following as output: ['C:\Netra_Step_2015\Tests\SVTestcases', 'C:\Netra_Step_2015\Tests\SVTestcases\TC-Regression', 'C:\Python27\python27.zip', 'C:\Python27\DLLs', 'C:\Python27\lib', etc.] Now, when I write "import testCaseBase as TCB" where testcaseBase.py is in this path: C:\Netra_Step_2015\Tests\SVTestcases\Common\shared I get an error: "**ImportError: No module named testCaseBase"** My code is in C:\Netra_Step_2015\Tests\SVTestcases\TC- Regression\regression.py. My code goes ahead with compilation, but testcaseBase.py which is residing in a parallel directory fails to compile. What might be the reason? Answer: put **C:\Netra_Step_2015\Tests\SVTestcases\Common\shared** in your PYTHONPATH env
MongoDB, Python and PyMongo: Document size too large with BSONObj size is invalid Question: I am getting this error when writing to Mongo: OperationalFailure caught 10334 {u'connectionId': 2365, u'code': 10334, u'ok': 1.0, u'err': u'BSONObj size: 17254820 (0xA4490701) is invalid. Size must be between 0 and 16793600(16MB) First element: 0: This is a normal document full of strings and integers, constructed in Python, yet it's size seems to be 17,25MB. What would you do? This is how the data looks like: { date: new Date(1417996800000), visitors: [ { owner: "AS3320 Deutsche Telekom AG", ip: "82.148.15.23", views: 844 }, { owner: "AS29314 VECTRA S.A.", ip: "173.235.42.25", views: 458 }, ... ] } There are many, many elements in that array, yet I am surprised that the amount surpasses 16MB. After limiting the size of the array down to 8500 elements, I am getting this PyMongo error: $ operator made object too large Answer: There are a lot of things to think about when designing your Mongo schemas, but generally the schema should reflect how you use your data. The [6 Rules of Thumb for MongoDB Schema Design](http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb- schema-design-part-1) article series on the MongoDB Blog is a good start. My first thought is to turn your documents "inside out" and store this kind of document in a collection: { date: new Date(1417996800000), owner: "AS3320 Deutsche Telekom AG", ip: "82.148.15.23", views: 844 }, { date: new Date(1417996800000), owner: "AS29314 VECTRA S.A.", ip: "173.235.42.25", views: 458 }, ... This way you're not limiting how many unique users you can have per day. If you are indexing on the `date` field, looking up visitors by date is still efficient. If you are not using the `owner` field much, maybe it can be moved to its own collection as well. { ip: "82.148.15.23", owner: "AS3320 Deutsche Telekom AG"}, { ip: "173.235.42.25", owner: "AS29314 VECTRA S.A."}, ... Not a definitive answer, obviously, but it might be a start. About checking the size of the document before writing (which I don't think is a good way to get around poor schema design). Data is handled as BSON by MongoDB internally so you can use the [`bson` module](https://pypi.python.org/pypi/bson/0.3.3): import bson len(bson.dumps(my_document)) If you get the "operator made object too large" error, see [this question](http://stackoverflow.com/questions/11224942/mongodb-update-with- upsert-fails).
python file writing in threads not writing all lines Question: I tested my code output and sort it, but I am not having 0-1999 as expected, lines is missing. Is my code thread unsafe? please suggest how to add thread lock in my code, and i found that my except all doesn't throw any errors, is it correct? thanks import time, threading, random class MyThreadWithArgs(threading.Thread): def __init__(self, string): threading.Thread.__init__(self) self.string = string def run(self): try: fo = open("foo.np2", "a") fo.write( self.string ) fo.write( '\n' ) time.sleep(random.uniform(0.1, 0.9)) fo.close() except: print ("error logging " + self.string) ttl_threads = 2000 for i in range(ttl_threads): t = MyThreadWithArgs(string = str(i)) t.start() Answer: This will probably work as expected. Exception handling removed for simplicity. import time, threading, random class MyThreadWithArgs(threading.Thread): def __init__(self, string): threading.Thread.__init__(self) self.string = string def run(self): fo.write( self.string + '\n' ) time.sleep(random.uniform(0.1, 0.9)) fo = open("foo.np2", "a") ttl_threads = 2000 for i in range(ttl_threads): t = MyThreadWithArgs(string = str(i)) t.start() In the original program, you're opening multiple handles to the same file in append mode. Each of handles maintains its own pointer to what it thinks is the end of the file, but it's possible for thread-0 to modify the file before thread-1 gets to write. thread-1 will still write to where the end-of-file _WAS_ when it called open. By keeping only one file descriptor open, you have only one end-of-file pointer and the underlying `write` system call is _probably_ reentrant on a given file descriptor via OS internal locking mechanisms. The other change I made was concatenating the strings from the two calls to `write()` because as two separate calls, you're giving the schedule a chance to switch threads in between system calls, and likely to end up with two `self.string` values in a row followed by two or more `\n` strings in a row. I don't know off the top of my what (if any) guarantees python makes about `write`, I'm just going off what I know about how `<unistd.h> write()` works in C on most POSIX platforms. If you want guarantees, check the python documentation, or surround the `write()` call with a lock.
OpenERP - Python development environment Question: I have installed Odoo v8 on VM, with Ubuntu. I am using GEDIT for editing .py and .xml files. Is there a Python development environment out there where I can develop, and more importantly, debug my Python code? Thanks in advance for your help. Answer: Try installing Eclipse, which is popularly used for Odoo development. It helps in debugging also.
Python - Select all elements a list of a list Question: I want to write a series of code (it may be func, loop or etc.) to get first 6 chars of each list of every list. It looks like this: [http://www.mackolik.com/AjaxHandlers/FixtureHandler.aspx?command=getMatches&id=3170&week=1](http://www.mackolik.com/AjaxHandlers/FixtureHandler.aspx?command=getMatches&id=3170&week=1) this is the first list of my list, second can be found here: week=2. It goes through 11. In addition to this, each list element of my list differentiates. Can you help me or give an idea to deal with. Answer: It looks like you you have a wretched multi-level data-in-string-in-list-of- list structure: data = [ ["[[342212,'21/02',,'MS'], [342276,'21/02',,'MS']]"], ["[[342246,'21/02',,'MS']]"] ] and you want to collect `[342212, 342276, 342246]`. To do this properly you pretty much have to parse each string to an actual data structure; this is complicated by the fact that consecutive commas (`,,`) are not valid Python syntax import ast def fix_string(s): # '[,,,]' s = s.replace("[,", "[None,") # '[None,,,]' s = s.replace(",,", ", None,") # '[None, None,,]' s = s.replace(",,", ", None,") # '[None, None, None,]' s = s.replace(",]", ", None]") # '[None, None, None, None]' return s data = [ast.literal_eval(fix_string(s)) for row in data for s in row] which gives us data = [ [ [342212,'21/02', None, 'MS'], [342276,'21/02', None, 'MS'] ], [ [342246,'21/02', None, 'MS'] ] ] then you can collect values like ids = [item[0] for batch in data for item in batch]
Execute a command on Remote Machine in Python Question: I am writing a program in python on Ubuntu, to execute a command `ls -l` on RaspberryPi, connect with Network. Can anybody guide me on how do I do that? Answer: Sure, there are several ways to do it! Let's say you've got a Raspberry Pi on a `raspberry.lan` host and your username is `irfan`. # subprocess It's the default Python library that runs commands. You can make it run `ssh` and do whatever you need on a remote server. scrat [has it covered in his answer](http://stackoverflow.com/a/28413657/974317). You definitely should do this if you don't want to use any third-party libraries. You can also automate the password/passphrase entering using [`pexpect`](http://pexpect.readthedocs.org/en/latest/). # paramiko [`paramiko`](https://github.com/paramiko/paramiko) is a third-party library that adds SSH-protocol support, so it can work like an SSH-client. The example code that would connect to the server, execute and grab the results of the `ls -l` command would look like that: import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('raspberry.lan', username='irfan', password='my_strong_password') stdin, stdout, stderr = client.exec_command('ls -l') for line in stdout: print line.strip('\n') client.close() # fabric You can also achieve it using [`fabric`](http://docs.fabfile.org/en/1.10/tutorial.html). Fabric is a deployment tool which executes various commands on remote servers. It's often used to run stuff on a remote server, so you could easily put your latest version of the web application, restart a web-server and whatnot with a single command. Actually, you can run the same command on multiple servers, which is awesome! Though it was made as a deploying and remote management tool, you still can use it to execute basic commands. # fabfile.py from fabric.api import * def list_files(): with cd('/'): # change the directory to '/' result = run('ls -l') # run a 'ls -l' command # you can do something with the result here, # though it will still be displayed in fabric itself. It's like typing `cd /` and `ls -l` in the remote server, so you'll get the list of directories in your root folder. Then run in the shell: fab list_files It will prompt for an server address: No hosts found. Please specify (single) host string for connection: [email protected] * * * **A quick note** : You can also assign a username and a host right in a `fab` command: fab list_files -U irfan -H raspberry.lan Or you could put a host into the `env.hosts` variable in your fabfile. [Here's how to do it](http://docs.fabfile.org/en/1.10/tutorial.html#defining- connections-beforehand). * * * Then you'll be prompted for a SSH password: [[email protected]] run: ls -l [[email protected]] Login password for 'irfan': And then the command will be ran successfully. [[email protected]] out: total 84 [[email protected]] out: drwxr-xr-x 2 root root 4096 Feb 9 05:54 bin [[email protected]] out: drwxr-xr-x 3 root root 4096 Dec 19 08:19 boot ...
Dll load failed, in python 2.7 running on windows 8.1 Question: I'am using Boneh-Lynn-Shacham Identity Based Signature scheme for my final year project for getting encryption keys from charm.toolbox.pairinggroup import * from charm.engine.util import * debug = False class IBSig(): def __init__(self, groupObj): global group group = groupObj def dump(self, obj): ser_a = serializeDict(obj, group) return str(pickleObject(ser_a)) def keygen(self, secparam=None): g, x = group.random(G2), group.random() g_x = g ** x pk = { 'g^x':g_x, 'g':g, 'identity':str(g_x), 'secparam':secparam } sk = { 'x':x } return (pk, sk) def sign(self, x, message): M = self.dump(message) if debug: print("Message => '%s'" % M) return group.hash(M, G1) ** x def verify(self, pk, sig, message): M = self.dump(message) h = group.hash(M, G1) if pair(sig, pk['g']) == pair(h, pk['g^x']): return True return False def main(): groupObj = PairingGroup('../param/d224.param') m = { 'a':"hello world!!!" , 'b':"test message" } bls = IBSig(groupObj) (pk, sk) = bls.keygen(0) sig = bls.sign(sk['x'], m) if debug: print("Message: '%s'" % m) if debug: print("Signature: '%s'" % sig) assert bls.verify(pk, sig, m) if debug: print('SUCCESS!!!') if __name__ == "__main__": debug = True main() when I am implementing it in python the code was not able to find the module named pairing though I have added Charm module to my library.Getting error like Traceback (most recent call last): File "C:\Users\Sailesh\Desktop\bls.py", line 1, in <module> from charm.toolbox.pairinggroup import * File "C:\Python27\lib\charm\toolbox\pairinggroup.py", line 2, in <module> from charm.core.math.pairing import serialize ImportError: DLL load failed: The specified module could not be found. I have taken the code from [Boneh-Lynn-Shacham Identity Based Signature code](https://code.google.com/p/charm- crypto/source/browse/trunk/schemes/sig_short_bls04.py?r=120) and downloaded the module charm from [charm module link](https://github.com/JHUISI/charm/downloads). Let me know where is the error or whether the problem is with the module. I cant figure out what is the problem. Thanks in advance. Answer: Try the 0.43 version directly fron github: <https://github.com/JHUISI/charm/releases>
Best way to get user to input items of different types into a list Question: What's the best way in Python to prompt a user to input items to an empty list and ensure the entries are evaluated to correct data types? For example user enters following mix of `int`, `float`, `str` and `list` item values: 24 190.45 'steve' 'steve smith' ['4A', '7B'] `new_list` becomes `[24, 190.45, 'steve', 'steve smith', ['4A', '7B']]` I have tried two methods, each with significant issues. **Method 1** \- asking user to input space delimited line of list items, using `eval()` to evaluate and store data types correctly, and using `str.split()` to split string into component items using `' '` as delimiter: # user enters values separated by spaces input_list = [eval(l) for l in(raw_input('Enter the items for your list separated by spaces: ').split())] # check by printing individual items with data type and also complete list for item in input_list: print item, type(item) print input_list However, I understand using `eval()` is not good from a security perspective. Also using `' '` delimiter for the split means I can't enter a string item like `'steve smith'`. However, I don't want to ask the user to input something ugly like comma delimiters, etc.. **Method 2** \- using a `while` loop with `break`, asking the user to input each list item: input_list = [] while True: item = eval(raw_input('Enter new list item (or <Enter> to quit): ')) if item: input_list.append(item) else: break Again, this uses `eval()` which I believe should be avoided. Also hitting `Enter` to break throws an EOF parsing error, I'm guessing because `eval()` can't evaluate it. Is there a better way to do this? Answer: Method two is clearly superior, but needs a slight tweak to avoid the error you're seeing: from ast import literal_eval def get_input_list(): input_list = [] while True: item = raw_input('Enter new list item (or <Enter> to quit): ') if not item: break input_list.append(literal_eval(item)) return input_list Note the fact that the input is _only evaluated once it's known to be non- empty_ , and the use of [`ast.literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval), which is safer than `eval`, although more limited: > The string or node provided may only consist of the following Python literal > structures: strings, numbers, tuples, lists, dicts, booleans, and `None`. In use: >>> get_input_list() Enter new list item (or <Enter> to quit): 24 Enter new list item (or <Enter> to quit): 190.45 Enter new list item (or <Enter> to quit): 'steve' Enter new list item (or <Enter> to quit): [24, 190.45, 'steve'] You could also add error handling, in case the user inputs a malformed string or something that can't be evaluated (e.g. `'foo` or `bar`): try: input_list.append(literal_eval(item)) except (SyntaxError, ValueError): print "Input not understood. Please try again."
Interface use in golang for mocking third party libraries Question: I'm trying to create a simple mock for unit testing some code using the VMware vSphere API client - [govmomi](http://godoc.org/github.com/vmware/govmomi) \- but I'm having trouble finding a usable pattern. A simple use case for the client library would be to retrieve the installed licenses for a vSphere cluster: vclient, err := govmomi.NewClient(*vcurl, true) if err != nil { return err } lic, err := vclient.LicenseManager().ListLicenses() `NewClient()` returns a pointer to a Client structure, `Client.LicenseManager()` returns an instance of a LicenseManager structure, and `LicenseManager.ListLicenses()` returns a slice of structures containing the license info. Coming from a Python background, I'd usually monkey patch the `ListLicenses()` method on `LicenseManger` for a mock, but I can't seem to come up with a comparable pattern or methodology in Go. To this point, I've tried creating a wrapper structure `VCenterClient` with the govmomi `Client` structure as an anonymous member and a "constructor" function `NewVCenter()` to create new instances of the wrapper structure with logic for mocks: import ( "net/url" "github.com/vmware/govmomi" "github.com/vmware/govmomi/vim25/types" ) type VCenterClient struct { VCenterClientInterface } type VCenterClientInterface interface { LicenseManager() LicenseManager } type LicenseManager interface { ListLicenses() ([]types.LicenseManagerLicenseInfo, error) } type VCenterClientMock struct{} type LicenseManagerMock struct{} func (v *VCenterClientMock) LicenseManager() LicenseManager { return LicenseManagerMock{} } func (l LicenseManagerMock) ListLicenses() ([]types.LicenseManagerLicenseInfo, error) { return make([]types.LicenseManagerLicenseInfo, 0), nil } func NewVCenterClient(uri string, mock bool) *VCenterClient { if mock { return &VCenterClient{&VCenterClientMock{}} } vcurl, _ := url.Parse(uri) vclient, _ := govmomi.NewClient(*vcurl, true) return &VCenterClient{vclient} } ...but I having trouble using interfaces to properly abstract the nested structures in the govmomi library. I know the above will not work as `govmomi.LicenseManager()` returns a structure of type `govmomi.LicenseManager` and my `VCenterClientInterface.LicenseManager()` method returns an interface of type `LicenseManager`. However, I'm struggling to find an alternative. Any help on a better design pattern or proper use of interfaces in this case would be much appreciated. Answer: This library is a SOAP client (<http://godoc.org/github.com/vmware/govmomi/vim25/soap#Client>). Abstract at the HTTP layer with net/http/httptest (<http://golang.org/pkg/net/http/httptest/>) or by using your own HTTPRoundtripper to mock the response.
Best way to constantly request http data? Question: Which is the best way to request constant data from a server in Python? I've tried with Urllib3 but for some reason after a while the python script stops. And I am also trying urllib2 (see below the code), but I notice there's a huge delay sometimes (that did not happen as frequently with urllib3) and the response is not every 0.5 seconds (sometimes it's every 6 seconds). What can I do to solve this? import socket import urllib2 import time # timeout in seconds timeout = 10 socket.setdefaulttimeout(timeout) while True: try: # this call to urllib2.urlopen now uses the default timeout # we have set in the socket module req = urllib2.Request('https://www.okcoin.com/api/v1/future_ticker.do?symbol=btc_usd&contract_type=this_week') response = urllib2.urlopen(req) r = response.read() req2 = urllib2.Request('http://market.bitvc.com/futures/ticker_btc_week.js') response2 = urllib2.urlopen(req2) r2 = response2.read() except: continue print r + str(time.time()) print r2 + str(time.time()) time.sleep(0.5) Answer: I think I found the problem. I needed to keep an open http session. That way I get the data more continuously. What's the best way of doing this? I did "http = requests.Session()" and using requests now.
make imported modules accessible for further imported modules Question: There is a main program importing a module with classes or something usefull that another submodule shall use too. For example: main.py: ` `import datetime` `datetime.now()` `import mod` ` mod.py: ` `datetime.today()` ` When importing 'mod' module python gives an error that 'datetime' is not defined. `datetime.today()` cant be executed. What should I do if I need to create a modular app in python instead of one- file apllication program? Should I always repeat my imports at the head of each module file ? Or can I make imported modules accessible from further imported modules? Answer: > Should I always repeat my imports at the head of each module file? Yes. Every module needs to import what it needs to use. As two great minds noted in the comments, the actual loading of the module only takes place once. Multiple imports will reuse the already-loaded module, so it won't have any significant performance impact.
Multiprocessing pool 'apply_async' only seems to call function once Question: I've been following the docs to try to understand multiprocessing pools. I came up with this: import time from multiprocessing import Pool def f(a): print 'f(' + str(a) + ')' return True t = time.time() pool = Pool(processes=10) result = pool.apply_async(f, (1,)) print result.get() pool.close() print ' [i] Time elapsed ' + str(time.time() - t) I'm trying to use 10 processes to evaluate the function `f(a)`. I've put a print statement in `f`. This is the output I'm getting: $ python pooltest.py f(1) True [i] Time elapsed 0.0270888805389 It appears to me that the function `f` is only getting evaluated once. I'm likely not using the right method but the end result I'm looking for is to run `f` with 10 processes simultaneously, and get the result returned by each one of those process. So I would end with a list of 10 results (which may or may not be identical). The docs on multiprocessing are quite confusing and it's not trivial to figure out which approach I should be taking and it seems to me that `f` should be run 10 times in the example I provided above. Answer: apply_async isn't meant to launch _multiple_ processes; it's just meant to call the function with the arguments in one of the processes of the pool. You'll need to make 10 calls if you want the function to be called 10 times. First, note the docs on [`apply()`](https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.pool.Pool.apply) (emphasis added): > > apply(func[, args[, kwds]]) > > > Call func with arguments args and keyword arguments kwds. It blocks until > the result is ready. Given this blocks, apply_async() is better suited for > performing work in parallel. **Additionally, func is only executed in one of > the workers of the pool.** Now, in the docs for [`apply_async()`](https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.pool.Pool.apply_async): > > apply_async(func[, args[, kwds[, callback[, error_callback]]]]) > > > A variant of the apply() method which returns a result object. The difference between the two is just that apply_async returns immediately. You can use `map()` to call a function multiple times, though if you're calling with the same inputs, then it's a little redudant to create the list of _the same_ argument just to have a sequence of the right length. However, if you're calling different functions with the _same_ input, then you're really just calling a higher order function, and you could do it with `map` or [`map_async()`](https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.pool.Pool.map_async) like this: multiprocessing.map(lambda f: f(1), functions) except that lambda functions aren't pickleable, so you'd need to use a defined function (see [How to let Pool.map take a lambda function](http://stackoverflow.com/q/4827432/1281433)). You can actually use the builtin `apply()` (not the multiprocessing one) (although it's deprecated): multiprocessing.map(apply,[(f,1) for f in functions]) It's easy enough to write your own, too: def apply_(f,*args,**kwargs): return f(*args,**kwargs) multiprocessing.map(apply_,[(f,1) for f in functions])
How to pass keyword arguments in reduce over Pandas merge function Question: I have the following list of data frames: import pandas as pd rep1 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux']), ('RP1',[1.00,23.22,11.12])], orient='columns') rep2 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'w']), ('Gene', ['foo', 'bar', 'wux']), ('RP2',[11.33,31.25,22.12])], orient='columns') rep3 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux'])], orient='columns') tmp = [] tmp.append(rep1) tmp.append(rep2) tmp.append(rep3) With this list output: In [35]: tmp Out[35]: [ Probe Gene RP1 0 x foo 1.00 1 y bar 23.22 2 z qux 11.12, Probe Gene RP2 0 x foo 11.33 1 y bar 31.25 2 w wux 22.12, Probe Gene 0 x foo 1 y bar 2 z qux] Note the following: * Each DF will contain 3 columns, but last column could have different names * `rep3` contain no value at 3rd column we'd like to discard it automatically * The row `w wux` only exist in `rep2`, we'd like to include that and give the value 0 for other data frame that doesn't contain it. What I want to do is to perform outer merge so that it produce the following result: Probe Gene RP1 RP2 0 x foo 1.00 11.33 1 y bar 23.22 31.25 2 z qux 11.12 22.12 3 w wux 22.12 0 I tried this but doesn't work In [25]: reduce(pd.merge,how="outer",tmp) File "<ipython-input-25-1b2a5f2dd378>", line 1 reduce(pd.merge,how="outer",tmp) SyntaxError: non-keyword arg after keyword arg What's the right way to do it? Answer: +1 for functional programming style. Yay! One way is to use `functools.partial` to partially apply the merge function. import functools outer_merge = functools.partial(pd.merge, how="outer") reduce(outer_merge, tmp) On a first try this gives: In [25]: reduce(outer_merge, tmp) Out[25]: Probe Gene RP1 RP2 0 x foo 1.00 11.33 1 y bar 23.22 31.25 2 z qux 11.12 NaN 3 w wux NaN 22.12 [4 rows x 4 columns] It reveals some inconsistencies in what you say about your desired result. You can see that there are actually two locations where the outer merge must supply a missing value, not just one. As a last step, you can use `fillna` to put in the zero value: In [26]: reduce(outer_merge, tmp).fillna(0) Out[26]: Probe Gene RP1 RP2 0 x foo 1.00 11.33 1 y bar 23.22 31.25 2 z qux 11.12 0.00 3 w wux 0.00 22.12 [4 rows x 4 columns]
Can't silence warnings that django-cms produces Question: I installed Django-cms with the `djangocms-installer` script, and all works fine except that I get a bunch of `RemovedInDjango18Warning` warnings in the shell every time I start the server, do anything with manage.py, or even do a manage.py tab-autocomplete (most annoying)! So thought I'd silence the warnings, using `warnings` module: # in manage.py, just after `import os; import sys`: import warnings warnings.filterwarnings("ignore") I would like to get more specific with the silencing, but it turns out that even this simple case does not do anything, the warnings are still displayed! What am I doing wrong?! The warnings: /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/cms/publisher/manager.py:5: RemovedInDjango18Warning: `PublisherManager.get_query_set` method should be renamed `get_queryset`. class PublisherManager(models.Manager): /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/cms/models/managers.py:15: RemovedInDjango18Warning: `PageManager.get_query_set` method should be renamed `get_queryset`. class PageManager(PublisherManager): /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/cms/admin/change_list.py:39: RemovedInDjango18Warning: `CMSChangeList.get_query_set` method should be renamed `get_queryset`. class CMSChangeList(ChangeList): /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/cms/admin/forms.py:340: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form PagePermissionInlineAdminForm needs updating class PagePermissionInlineAdminForm(forms.ModelForm): /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/cms/admin/forms.py:442: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form ViewRestrictionInlineAdminForm needs updating class ViewRestrictionInlineAdminForm(PagePermissionInlineAdminForm): /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/cms/admin/forms.py:491: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form PageUserForm needs updating class PageUserForm(UserCreationForm, GenericCmsPermissionForm): /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: `PagePermissionInlineAdmin.queryset` method should be renamed `get_queryset`. .__new__(mcs, name, bases, attrs)) /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: `ViewRestrictionInlineAdmin.queryset` method should be renamed `get_queryset`. .__new__(mcs, name, bases, attrs)) /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: `PageUserAdmin.queryset` method should be renamed `get_queryset`. .__new__(mcs, name, bases, attrs)) Answer: The surgical way to solve this is to create a **logging filter** that will only filter out warnings that are explicitly specified to be silenced. You know: > Errors should never pass silently. > Unless explicitly silenced. * * * With that in mind, here is my filter machinery, all in `settings.py` (for now anyways): MY_IGNORED_WARNINGS = { 'RemovedInDjango18Warning: `PublisherManager.get_query_set`', 'RemovedInDjango18Warning: `PageManager.get_query_set`', 'RemovedInDjango18Warning: `CMSChangeList.get_query_set`', 'form PagePermissionInlineAdminForm needs updating', 'form ViewRestrictionInlineAdminForm needs updating', 'form PageUserForm needs updating', '/cms/admin/placeholderadmin.py:133: RemovedInDjango18Warning: Options.module_name has been deprecated', '/cms/admin/settingsadmin.py:28: RemovedInDjango18Warning: Options.module_name has been deprecated', '/cms/admin/pageadmin.py:111: RemovedInDjango18Warning: Options.module_name has been deprecated', 'RemovedInDjango18Warning: `PagePermissionInlineAdmin.queryset', 'RemovedInDjango18Warning: `ViewRestrictionInlineAdmin.queryset`', 'RemovedInDjango18Warning: `PageUserAdmin.queryset`', } def filter_djangocms_warnings(record): for ignored in MY_IGNORED_WARNINGS: if ignored in record.args[0]: return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'filters': { 'ignore_djangocms_warnings': { '()': 'django.utils.log.CallbackFilter', 'callback': filter_djangocms_warnings, }, }, 'loggers': { 'py.warnings': { 'handlers': ['console', ], 'filters': ['ignore_djangocms_warnings', ], } }, } I imagine it can be further refined... any ideas? * * * Why bother? For one, I can use now (again) use [django bash autocomplete](https://github.com/django/django/blob/master/extras/django_bash_completion) without a bunch of warnings echoed every time I press [tab]. Also, now that I don't have 20+ warnings form DjangoCMS, I can actually see what warnings come from my own code and fix it.
Parsing code used in loop only once Question: I'm writing a code in Python which can be used to solve equations. The user must first input a code via a raw_input(), which will then be used to calculate y for every x in a loop with eval(), like so: #some imports (math) and other irrelevant code Code = raw_input('please enter your equation') Low = raw_input('please enter the lowest number in the domain') High = raw_input('please enter the highest number in the domain') X = Low While X <= High: Y = eval(code) #complicated code to solve equation X += #number depending on the amount of decimals #simpler code to print the result The problem is that parsing the input code using eval() for every loop is extremely slow. Is there a way to parse the code only once and then use it as a function in the rest of the program? Answer: You can compile the expression in advance using [`compiler.compile()`](https://docs.python.org/2/library/compiler.html#compiler.compile) ([deprecated](https://mail.python.org/pipermail/python-3000/2008-January/011693.html) since Python v2.6). With Python 3.x: * the [`compile`](https://docs.python.org/3/library/functions.html#compile) functionality is built-in * the [AST module](https://docs.python.org/3.3/library/ast.html) offers similar functions Also take a look at: [Python: Way to speed up a repeatedly executed eval statement?](http://stackoverflow.com/q/12467570/3235496) EDIT Some examples: >>> expr = 'x*x + 2*x + 1' >>> expr_obj = compile(expr, '', 'eval') >>> x = 1 >>> y = eval(expr) and now >>> y 4 >>> x = 2 >>> y = eval(expr) >>> y 9 `compile` is a lower level version of `eval` (and `exec`). It doesn't evaluate/execute your expression/statement but returns a code object that can do it. * * * PS as a general rule when using `eval` on user submitted strings you must be very careful about what you accept (it's a potential security hole).
Python: multiple string test for standard Uk reg, why not working? Question: The following is a section that has been separated from the main program to just test the snippet if it works. The "yes" output was for testing each string method required to see where errors arises. This does not seem to work and I cant figure out why as I have put all tests for standard UK reg, checking characters as they appear from an input. As you can see im a very low level (new to python) programmer, please consider that as you are providing solutions. Many thanks def main(): reg_number=input("What is your reg number?: ") correct_length = False first_two_char_capital = False next_two_char_digits= False next_char_space = False last_three_char_capital= False first_two_char_capital =reg_number[0:2] print(first_two_char_capital) next_two_char_digits=reg_number[2:4] print (next_two_char_digits) next_char_space=reg_number[4:5] print(next_char_space) last_three_char_capital=reg_number[5:8] print (last_three_char_capital) if len (reg_number) >= 8: correct_length = True print("yes1") for ch in reg_number: if first_two_char_capital.isupper(): first_two_char_capital = True print("yes2") if next_two_char_digits.isdigit(): next_two_char_digits = True print("yes3") if next_char_space.isspace(): next_char_space = True print("yes4") if last_three_char_capital.isupper(): last_three_char_capital = True print("yes5") if correct_length and first_two_char_capital and next_two_char_digits and next_char_space and last_three_char_capital: is_valid = False print(reg_number, "is a non-standard_registration") else: is_valid = True print(reg_number, "is a standard registration") return is_valid main() Answer: It's much easier to just use a regular expression here, eg: import re if re.match('[A-Z]{2}\d{2} [A-Z]{3}$', input('What is your regnumber:')): print('yeah it matches...')
Insert only populated entry python tkinter Question: for va in entries: outputmsg = va.get() es.JournalOut(outputmsg) selected_ch_name.insert(i,outputmsg) I have a series of tkinter Entry box's that take user input to select channels for some data analysis (see below),currently it reads out all of the values including empty ones, How can I only output to console ( es.JournalOut - this is an nCode command), and only insert the number in line with the relevant channel name position in list ? The software has it's own output pipes and I want to produce lists of the users selection to specify what data to output. Not sure I am going about it the correct way, If I have a list of channel names and the accompanying channels numbers ( not sequential channel numbers) how can I specify a subset of those into another list/other object to capture both the name and the channel number? # Display collumns of current channel numbers and Titles i = 0 # loops through all channel numbers to get print table value. while i < nchan: # prints out all present channels with index and channel number and title #populates tables ch_name = tsin.GetChanTitle(i) # loops through channel title values ch_num = tsin.GetChanNumber(i) # looop through channel number titles ch_name_list = Label(frame, text=ch_name) # assign values ch_num_list = Label(frame, text=str(ch_num)) # assign values ch_name_list.grid(row=i + 1, column=2) # set label to row in grid ch_num_list.grid(row=i + 1, column=0) # set label to row in grid # Display Input boxes to get new channel numbers va = StringVar() # declare a variable as type string with .get methods en = Entry(frame, textvariable=va) # set en to equal an entry box within fram with input variable to store input equal to va en.grid(row=i + 1, column=4) # display entry in grid variables.append(va) entries.append(en) i = i + 1 Answer: You don't even need the StringVars. Simply use `entry.get()`. To only print lines that are not empty, you can use `if outputmsg:` to check if `outputmsg` is not an empty string. Here's a small example of a program which can print the index and contents of all non-empty entries: import Tkinter as tk def print_non_empty(): for i, entry in enumerate(entries): output = entry.get() if output: print 'Entry {}: {}'.format(i, output) print '' root = tk.Tk() entries=[] for i in range(5): entries.append(tk.Entry(root)) entries[-1].pack() tk.Button(root, text='show non-empty entries', command=print_non_empty).pack() root.mainloop()
Lambda and multiple statements in Python Question: Can anyone explaine that behavior of lambda functions? import sys X = lambda: sys.stdout.write('first');sys.stdout.write("second") X() Returns: -> secondfirst And one more problem: lambda: sys.stdout.write("...");sys.exit(0) Or lambda: sys.exit(0);sys.stdout.write("...") Doesn't execute correctly. And one more question, why in first primer execution flow goes from right to left? Trying with: Python3+(3.4, 3.2) OS: Linux (Ubuntu), OSX Answer: sys.stdout.write("second") is not part of the lambda. 'second' is always printed even if you don't call X. In other words calling X only prints 'first'. Your code can be rewritten as; import sys X = lambda: sys.stdout.write('first') sys.stdout.write("second") print X() If you want two statements executed by the lambda place them in a tuple; lambda: (sys.stdout.write('first'),sys.stdout.write("second"))
How to get information from an xlsx file in Python? Question: I have to create a mailing list of people belonging to a certain institution. The information is only available in .xlsx file. The columns of xlsx are as follows: institution, DOB, Program, ..., EmailID. How do I do this, instead of reading each entry myself and then typing the email into Google contacts? I know I am asking a lot, especially since I have no idea how to operate Google sheets; like I am not sure if there is a way in Google sheets to do that. All I need are some directions. Answer: You can read/write .xlsx files using openpyxl. Here is the link to the [documentation](http://openpyxl.readthedocs.org/en/latest/). You can read from the .xlsx as follows: from openpyxl import load_workbook wb2 = load_workbook('email_contacts.xlsx') print wb2.get_sheet_names() To add the details into Google Contacts you can use the Google Contacts API. Just read the official documentation on how to use the API.
Create Bayesian Network and learn parameters with Python3.x Question: I'm searching for the most appropriate tool for python3.x on Windows to create a Bayesian Network, learn its parameters from data and perform the inference. The network structure I want to define myself as follows: ![enter image description here](http://i.stack.imgur.com/iscKX.jpg) It is taken from [this](http://ieeexplore.ieee.org/xpl/login.jsp?tp=&arnumber=6697180&url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D6697180) paper. All the variables are discrete (and can take only 2 possible states) except "Size" and "GraspPose", which are continuous and should be modeled as Mixture of Gaussians. Authors use _Expectation-Maximization algorithm_ to learn the parameters for conditional probability tables and _Junction-Tree algorithm_ to compute the exact inference. As I understand all is realised in MatLab with Bayes Net Toolbox by Murphy. I tried to search something similar in python and here are my results: 1. Python Bayesian Network Toolbox <http://sourceforge.net/projects/pbnt.berlios/> (<http://pbnt.berlios.de/>). Web-site doesn't work, project doesn't seem to be supported. 2. BayesPy <https://github.com/bayespy/bayespy> I think this is what I actually need, but I fail to find some examples similar to my case, to understand how to approach construction of the network structure. 3. PyMC seems to be a powerful module, but I have problems with importing it on Windows 64, python 3.3. I get error when I install development version WARNING (theano.configdefaults): g++ not detected ! Theano will be unable to execute optimized C-implementations (for both CPU and GPU) and will default to Python implementations. Performance will be severely degraded. To remove this warning, set Theano flags cxx to an empty string. UPDATE: 4. libpgm (<http://pythonhosted.org/libpgm/>). Exactly what I need, unfortunately not supported by python 3.x 5. Very interesting actively developing library: PGMPY. Unfortunately continuous variables and learning from data is not supported yet. <https://github.com/pgmpy/pgmpy/> Any advices and concrete examples will be highly appreciated. Answer: It looks like [pomegranate](https://github.com/jmschrei/pomegranate) was recently updated to include Bayesian Networks. I haven't tried it myself, but the interface looks nice and sklearn-ish.