text
stringlengths
226
34.5k
Merge Sort on Python: Unusual pattern of result obtained Question: I have a unsorted array of 10,000 integers from 0 to 9,999. I wanted to apply merge sort on this unsorted array and I wrote the following code- import sys def merge_sort(data): result = [] if len(data) <= 1: return data else: mid = int(len(data)/2) left = data[:mid] right = data[mid:] sorted_left = merge_sort(left) sorted_right = merge_sort(right) i = j = k = 0 total_len = len(sorted_left) + len(sorted_right) for k in range(0, total_len): if i < len(sorted_left) and j < len(sorted_right): if sorted_left[i] < sorted_right[j]: result.append(sorted_left[i]) i = i+1 k = k+1 elif sorted_left[i] > sorted_right[j]: result.append(sorted_right[j]) j = j+1 k = k+1 elif i < len(sorted_left): result.append(sorted_left[i]) i = i+1 k = k+1 elif j < len(sorted_right): result.append(sorted_right[j]) j = j+1 k = k+1 else: sys.exit("There is some issue with the code") return result print merge_sort(data) So when I sort this data, I get a correct sort order except for a few entries. For example- towards the end I get this kind of result- [...'9989', '999', '9990', '9991', '9992', '9993', '9994', '9995', '9996', '9997', '9998', '9999'] As you might observe, number '999' is at the wrong place. Not just in this snippet but it happens in other places too like '995' appearing between '9949' and '9950'.So anybody has any idea why this is happening? P.S.- I ran this code for debug and it ran without errors producing these results Answer: You are ordering strings: `'9989' < '999' < '9990'`. If you want to order integers, you'll have to convert your input list to integers.
Read vertically all the values of all the possible combinations of an unknown number of lists with different sizes in Python Question: I want implement a function that combines **vertically** all the elements of an **unknown number of lists** in Python. Each list has a **different size**. E.g., this is the list of list and each row is a list: A0, A1 B0 C0, C1, C2 Then I would like to print A0, B0, C0 A0, B0, C1 A0, B0, C2 A1, B0, C0 A1, B0, C1 A1, B0, C2 Note that in the example there are 3 lists but they could also more or less, not necessary 3. My problem is that I don't have idea how to solve it. I tough to implement a recursive method, in which if some condition is satisfied then print the value, else call recursively the function. Here the pseudo-code: def printVertically(my_list_of_list, level, index): if SOME_CONDITION: print str(my_list_of_list[index]) else: for i in range (0, int(len(my_list_of_list[index]))): printVertically(my_list_of_list, level-1, index) Here the main code: list_zero = [] list_zero.append("A0") list_zero.append("B0") list_zero.append("C0") list_one = [] list_one.append("A1") list_two = [] list_two.append("A2") list_two.append("B2") list_three = [] list_three.append("A3") list_three.append("B3") list_three.append("C3") list_three.append("D3") my_list_of_list = [] my_list_of_list.append(list_zero) my_list_of_list.append(list_one) my_list_of_list.append(list_two) my_list_of_list.append(list_three) level=int(len(my_list_of_list)) index=0 printVertically(my_list_of_list, level, index) _level_ is the length of the list of list and _index_ should represent the index of a specific list used when I want to print a specific element. Well, no idea how to proceed. Any hint? I have searched but in all solutions, people knew the number of lists or the number of elements in each list, like these links: [Link 1](http://stackoverflow.com/questions/34143934/using-zip-to-read-a-file- vertically-and-search-through-the-zipped-list) [Link 2](http://stackoverflow.com/questions/15707433/reading-files-as-both- vertical-lists-and-horizental-listspython-3-2) [Link 3](http://stackoverflow.com/questions/2990003/how-can-i-find-all-the- possible-combinations-of-a-list-of-lists-in-python) Answer: I believe that what you want here is the cross-product of the various sets. You can do this with Python's **itertools.product** method. Documentation is [here](https://docs.python.org/2/library/itertools.html#itertools.product). Something like: import itertools a_list = ["A0", "A1"] b_list = ["B0"] c_list = ["C0", "C1", "C2"] for combo in itertools.product(a_list, b_list, c_list): print combo Output: ('A0', 'B0', 'C0') ('A0', 'B0', 'C1') ('A0', 'B0', 'C2') ('A1', 'B0', 'C0') ('A1', 'B0', 'C1') ('A1', 'B0', 'C2') Does that get you moving? * * * Example with one overarching list: my_list_list = [a_list, b_list, c_list] for combo in itertools.product(*my_list_list): print combo ... and we get the same output
Python-how to calculate the highest tf-idf value of the first 100 words in different tweeets Question: I have tens of thounds of tweets saved in one .txt file, I want to calculate calculate the highest tf-idf value of the first 100 words in these tweeets, in other words, I want to compare the word's tf-idf value between different tweets, presently,the only thing that I could complete is comparing word's tf- idf value in the same tweets, I cannot find a way to compare word's tf-idf value between different tweets. Please help me,I have been upset for a long time because of this problem. /(ㄒoㄒ)/~~ Blow is my code:(only able to calculate the term's tfidf value in same tweets) with open('D:/Data/ows/ows_sample.txt','rb') as f: tweet=f.readlines() lines = csv.reader((line.replace('\x00','') for line in tweet), delimiter=',', quotechar='"') wordterm=[] for i in lines: i[1]= re.sub(r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+|(?:@[\w_]+)', "", i[1]) tweets=re.split(r"\W+",i[1]) tweets=[w.lower() for w in tweets if w!=""] stopwords = open("D:/Data/ows/stopwords.txt", "r").read().split() terms = [t for t in tweets if not t in stopwords] wordterm.append(terms) word=[' '.join(t) for t in wordterm] tfidf_vectorizer = TfidfVectorizer(min_df = 1,use_idf=True) tfidf_matrix = tfidf_vectorizer.fit_transform(word) terms_name = tfidf_vectorizer.get_feature_names() toarry=tfidf_matrix.todense() #below code will output the tf-idf value of each tweets' terms. for ii in range(0,len(toarry)): print u"第"+ ii +u"个tweets" for jj in range(0,len(terms_name)): print terms_name[jj],'-',tfidf_matrix[ii,jj] Answer: Now that I understand your question, I will try to answer your question a little better. To get the top 100 'tf-idf' scores in a way that is comparable across all tweets would either mean that you are letting go of the notion that there are distinct tweets, or you want to be able to compare the same words to each other by tf-idf score. So for the first scenario, imagine that all your words are in 1 'document'. This would essentially eliminate the 'idf' aspect of tf-idf, and what you'll get is basically a word count vectorizer, which can be compared with one another and you can get the top 100 words this way. words = ['the cat sat on the mat cat cat'] tfidf_vectorizer = TfidfVectorizer(min_df = 1,use_idf=True) tfidf_matrix = tfidf_vectorizer.fit_transform(words) terms_name = tfidf_vectorizer.get_feature_names() toarry=tfidf_matrix.todense() toarry: matrix([ .75, 0.25, 0.25, 0.25, 0.5]) The other scenario is that you take each tweet separately, and then you compare the scores by their tf-idf scores. This would result in the same words having different scores, because that's what tf-idf does - **it calculates the importance of the word in the document relative to the corpus**. words = ['the cat sat on the mat cat', 'the fat rat sat on a mat', 'the bat and a rat sat on a mat'] tfidf_vectorizer = TfidfVectorizer(min_df = 1,use_idf=True) tfidf_matrix = tfidf_vectorizer.fit_transform(words) terms_name = tfidf_vectorizer.get_feature_names() toarry=tfidf_matrix.todense() for i in tfidf_matrix.toarray(): print zip(terms_name, i) [(u'and', 0.0), (u'bat', 0.0), (u'cat', 0.78800079617844954), (u'fat', 0.0), (u'mat', 0.23270298212286766), (u'on', 0.23270298212286766), (u'rat', 0.0), (u'sat', 0.23270298212286766), (u'the', 0.46540596424573533)] [(u'and', 0.0), (u'bat', 0.0), (u'cat', 0.0), (u'fat', 0.57989687146162439), (u'mat', 0.34249643393071422), (u'on', 0.34249643393071422), (u'rat', 0.44102651785124652), (u'sat', 0.34249643393071422), (u'the', 0.34249643393071422)] [(u'and', 0.50165133177159349), (u'bat', 0.50165133177159349), (u'cat', 0.0), (u'fat', 0.0), (u'mat', 0.29628335772067432), (u'on', 0.29628335772067432), (u'rat', 0.38151876810273028), (u'sat', 0.29628335772067432), (u'the', 0.29628335772067432)] As you can see in the results, the same words will have different scores in each document, because tf-idf is a score of that term within each document. So these are the two methods available to you, so depending on what you want, you can choose what's better for your purposes.
Pandas and matplotlib doing linear graph Question: Any idea whats missing in my code to avoid part of the graph/canvas and dates being out of the PNG image? Is it possible to have the dates written in 180 degrees or in vertical to not use so much space of the grapth? My data set is: 15/03/16 3000 300 200 12/04/16 3000 300 300 10/05/16 500 500 400 12/06/16 1000 600 500 14/07/16 1250 300 500 21/07/16 2000 300 50 15/08/16 3000 300 200 12/09/16 3000 300 300 10/10/16 500 500 400 12/11/16 1000 600 500 15/11/16 1250 300 500 21/12/16 1000 500 50 Python code is: import pandas import matplotlib.pyplot as plt df = pandas.read_csv('data.csv', delimiter=';', index_col=0, parse_dates=[0], dayfirst=True, names=['date','a','b','c']) df.plot() df.plot(subplots=True, figsize=(6, 6)) plt.savefig('sampledata1.png') And png looks like (missing data): [![enter image description here](http://i.stack.imgur.com/Bom4X.png)](http://i.stack.imgur.com/Bom4X.png) Thank you! Answer: The data is there, it is just being plotted on the edge of the plot. You can change the y-limits globally with df.plot(ylim=(0,3500)) df.plot(subplots=True, figsize=(6, 6), ylim=(0,3500)) To change them for each plot, I think you'll need to plot the curves individually. To do it individually, I typically do something like this (there are a zillion ways do it): fig, axes = plt.subplots(3,1) axes[0].set_ylim([df.a.min()*0.9, df.a.max()*1.1]) axes[0].set_xticklabels([]) axes[1].set_ylim([df.b.min()*0.9, df.b.max()*1.1]) axes[1].set_xticklabels([]) axes[2].set_ylim([df.c.min()*0.9, df.c.max()*1.1]) axes[0].plot(df.a) axes[1].plot(df.b) axes[2].plot(df.c) [![jupyter screenshot](http://i.stack.imgur.com/l2LJW.jpg)](http://i.stack.imgur.com/l2LJW.jpg) The axis labels can be adjusted to be readable, etc. - checkout matplotlib.org for lots of examples.
Removing accents with Python - Unicode doesn't work Question: I'm trying to clean a spanish text with the following code: import re import unicodedata file = open("dirty.txt").readlines() archivo = open("cleanText.txt", "w") textLowerCase = file[i].lower() unicodeText = textLowerCase.decode('unicode-escape') textWithoutAccents = unicodedata.normalize('NFKD', unicodeText).encode('ASCII', 'ignore') textWithoutSymbols = re.sub(r'[^\w]', ' ', textWithoutAccents) archivo.write(textWithoutSymbols) My input text is like: "anunciarán la realización de una interpelación" My desire output is: "anunciaran la realizacion de una interpelacion" But with my code i'm getting the next result: "anunciarAn la realizaciA3n de una interpelaciA3n" Do you know how can I solve this? Answer: This is exactly what **unidecode** package does: <https://pypi.python.org/pypi/Unidecode> From the readme: > The module exports a function that takes an Unicode object (Python 2.x) or > string (Python 3.x) and returns a string (that can be encoded to ASCII bytes > in Python 3.x): >>> from unidecode import unidecode >>> unidecode(u'ko\u017eu\u0161\u010dek') 'kozuscek' >>> unidecode(u'30 \U0001d5c4\U0001d5c6/\U0001d5c1') '30 km/h' >>> unidecode(u"\u5317\u4EB0") 'Bei Jing ' EDIT: Your exact example: >>> from unidecode import unidecode >>> unidecode("anunciarán la realización de una interpelación") 'anunciaran la realizacion de una interpelacion' EDIT 2: If you are using Python 2, don't forget to either: * `from __future__ import unicode_literals`, or: * use `u` prefix before string quotes: `unidecode(u"anu...`
Unknown CUDA error when importing theano Question: In python, after importing theano, I get the following: In [1]: import theano WARNING (theano.sandbox.cuda): CUDA is installed, but device gpu is not available (error: Unable to get the number of gpus available: unknown error) I'm running this on ubuntu 14.04 and I have an old gpu: GeForce GTX280 And my nvidia driver: $ nvidia-smi Wed Jul 13 21:25:58 2016 +------------------------------------------------------+ | NVIDIA-SMI 340.96 Driver Version: 340.96 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX 280 Off | 0000:02:00.0 N/A | N/A | | 40% 65C P0 N/A / N/A | 638MiB / 1023MiB | N/A Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Compute processes: GPU Memory | | GPU PID Process name Usage | |=============================================================================| | 0 Not Supported | +-----------------------------------------------------------------------------+ I'm not sure why it's saying it's 'Not Supported' but it seems as though that might not be an issue as said [here](https://devtalk.nvidia.com/default/topic/697308/compute-processes-not- supported/) Also, the CUDA version: $ nvcc -V nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2014 NVIDIA Corporation Built on Thu_Jul_17_21:41:27_CDT_2014 Cuda compilation tools, release 6.5, V6.5.12 Any help I can get would be awesome. I've been at this all day... Answer: I feel your pain. I spent a few days ploughing through all the CUDA related errors. Firstly, update to a more recent driver. eg, 361. (CLEAN INSTALL IT!) Then completely wipe cuda and cudnn from your harddrive with sudo rm -rf /usr/local/cuda or wherever else you installed it, then install cuda 7.5 (seriously, this specific version) and cuDNN v4 (again, this specific version) You can run the following commands to settle CUDA. wget http://developer.download.nvidia.com/compute/cuda/7.5/Prod/local_installers/cuda_7.5.18_linux.run bash cuda_7.5.18_linux.run --override Follow the instructions, **say NO when they ask you to install the 350 driver**. And you should be set. For cudnn, there's no direct link to wget, so you have to get the installer from <https://developer.nvidia.com/cudnn> and run the following commands: tar xvzf cudnn-7.0-linux-x64-v4.0-prod.tgz sudo cp cuda/include/cudnn.h /usr/local/cuda-7.5/include sudo cp -r cuda/lib64/. /usr/local/cuda-7.5/lib64 echo -e 'export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/cuda-7.5/lib64"\nexport CUDA_HOME=/usr/local/cuda-7.5' >> ~/.bash_profile source ~/.bash_profile Now to handle Theano on GPU: nano ~/.theanorc add these lines: [global] floatX = float32 device = gpu0 If you get an nvcc error, make it so instead: [global] floatX = float32 device = gpu0 [nvcc] flags=-D_FORCE_INLINES
Scatter plot with a slider in python Question: Hey I am trying to create a scatter plot with a slider that updates the plot as I slide across. This is my code so far. It draws a scatter plot and a slider but as I move it around, nothing happens. I suspect that the problem is with the `.set_ydata`bit but I can't seem to find how to do it otherwise on the Internet. import numpy as np from matplotlib.widgets import Slider from pylab import plot, show, figure, scatter, axes, draw fig = figure() ax = fig.add_subplot(111) x, y = np.random.rand(2,100) scat = scatter(x,y) axcolor = 'lightgoldenrodyellow' axamp = axes([0.2, 0.01, 0.65, 0.03], axisbg=axcolor) scorr = Slider(axamp, 'corr', -2,2, valinit=1) def update(val): corr = scorr.val for i in range(len(x)): x[i]=x[i]+corr*np.random.randn() for i in range(len(y)): y[i]=y[i]+corr*np.random.randn() scat.set_xdata(x) scat.set_ydata(y) draw() scorr.on_changed(update) show(scat) This is just a test script in fairness. I have to do the same thing with a much more complicated script but realized it would be easier to try it out on a simpler problem. I really just care about `scat.set_ydata` and what to put there instead so that it works. Thanks in advance. Answer: You need to use `set_offsets` and `set_array` in stead: # make sure you get the right dimensions and direction of arrays here xx = np.vstack ((x, y)) scat.set_offsets (xx.T) # set colors scat.set_array (y) Probably duplicate of: [matplotlib animating a scatter plot](http://stackoverflow.com/questions/9401658/matplotlib-animating-a- scatter-plot)
How to parse a list in python using re Question: I am trying to parse a list to get the individual images returned by the bash script (stored in the list errors in py script). How can I do this with "re" ? **bash script** #!/bin/bash value(){ for entry in * do if expr "$(file -b $entry)" : 'JPEG ' >/dev/null; then echo -e "$entry" fi done } value **python code** import subprocess errors = [subprocess.check_output(['/black.sh'])] print errors **Output** 11_37_24.jpeg 11_38_02.jpeg 11_39_56.jpeg 11_40_20.jpeg 11_40_32.jpeg 11_45_03.jpeg The list `"errors"` is getting assigned a string of length 1: errors = ["11_37_24.jpeg 11_38_02.jpeg 11_39_56.jpeg 11_40_20.jpeg 11_40_32.jpeg 11_45_03.jpeg"] However, I want to get those images separately to use it in an html page. How can I do that with "re"? Is there any other alternative? Answer: I make a few assumptions (based on the example input you give): * file names only contain digits and underscores (so I can use `\w` in regex) * words in a file name are always concatenated by underscores (no spaces) * every file is a jpeg file The code: import re errors = ["11_37_24.jpeg 11_38_02.jpeg 11_39_56.jpeg 11_40_20.jpeg 11_40_32.jpeg 11_45_03.jpeg"] re.findall('\w+\.jpeg', errors[0]) ['11_37_24.jpeg', '11_38_02.jpeg', '11_39_56.jpeg', '11_40_20.jpeg', '11_40_32.jpeg', '11_45_03.jpeg'] If my assumptions are wrong for your project, `re` is probably not the way to go. **EDIT** The OP used the following code (which was given in the comments): errors[0].split('\n')
Using python language to acces a cmd window Question: It is possible to make a python script which opens a cmd window and enters 5 commands one by one, and after waits for an external trigger to continue entering another 2 commands in the same window. It is posibble? I hope You understand what I ask. PS: maybe you can share with me a sample code or something. Thank you in advance. M. Answer: What i have done in the past is use Python to write a `.bat` file and run it. And this does produce the result you describe. You can do this like that: import subprocess with open(r'my_bat_file.bat','w') as fout: fout.write('command no1') fout.write('command no2') ... fout.write('command non') fout.write('pause') subprocess.run(r'my_bat_file.bat', creationflags=subprocess.CREATE_NEW_CONSOLE) The `pause` command keeps the cmd open and waiting for a key stroke. When the key even logs, execution of the bat file will continue. If the pause is the last line in your batch file, cmd will close.
Node disappears after restart server. Neo4j 3.0 Cypher 3 Question: I'm trying to add a node to my base, but every time I restart the server, the node disappears along with their relationships. I started my base by importing a CSV using the ./neo4j-import script in the bin folder. The node in question is a node that connects to all subgraphs of my base (like a root node), turning the base into a connected graph. I already added through the shell (./neo4j-shell) through the web application and using python (using `from neo4j.v1 driver import GraphDatabase`), in all cases when I restart the server, the node disappears. The command I am using in all approaches is this: neo4j-sh (?)$ create(r:PDB{name: 'root', resolution: 'less than 2.0', method: 'x-ray diffraction'}); neo4j-sh (?)$ match(r:PDB{name:'root'}) match(p:PDB_FILE) merge(r)-[:HAS_PDB]->(p); In the latest attempt used differently (using `commit`): neo4j-sh (?)$ begin neo4j-sh (?)$ create(r:PDB{name: 'root', resolution: 'less than 2.0', method: 'x-ray diffraction'}); neo4j-sh (?)$ match(r:PDB{name:'root'}) match(p:PDB_FILE) merge(r)-[:HAS_PDB]->(p); neo4j-sh (?)$ commit But without success. I'm using version 3.0. * of Neo4j, Cypher 3.0, Ubuntu 4.14 server. Answer: I have no idea on why this is happening to you, but what I would definitely try is using the super batch importer for huge datasets: `neo4j-import`. There is some instruction on how to use the tool [in neo4j documentation](https://neo4j.com/developer/guide-import- csv/#_super_fast_batch_importer_for_huge_datasets). To use the tool you have to put your data in special formats, individual csv files each corresponding to a type of node or a type of edge in your dataset. It is well explained in the given link, and, even though it does not explain _why_ this is happening to you, it is surely worth a try. Another things that you could try are: * to install _neo4j_ in another machine. Maybe there is some weird problem with your installation/your system; * try another version of neo4j. I'm not totally aware, but I imagine the latter 2.X.X versions should be more stable than the newer ones, as _Neo4j v3_ has been release recently. It is easy to install any version using [this debian repositories](http://debian.neo4j.org/) (via apt-get in Ubuntu).
Python automatically generating variables Question: # Question I have a question about Python creating new variables derived from other variables. I am struggling to understand how Python automatically knows how to generate variables even when I do not explicitly tell it to. # Details I am a new Python user, and am following along in the tutorials in: [Joel Grus, "Data Science From Scratch"](http://shop.oreilly.com/product/0636920033400.do). In the tutorial, I create three list variables: 1. `friends` contains the number of friends that someone has on a given social networking site 2. `minutes` refers to the number of minutes that they spend on the site 3. `labels` is simply an alphabetic label for each user. Part of the tutorial is graphically plotting labels next to the points when I create a scatterplot. In doing so, Python seems to automatically generate three new variables: `label`, `friend_count`, and `minute_count`. In short - _how_? How does Python know to create these variables? And what do they do? They do not correspond to the mean, median, or mode of any of the lists. # Code import matplotlib.pyplot as plt from collections import Counter def make_chart_scatter_plot(plt): friends = [ 70, 65, 72, 63, 71, 64, 60, 64, 67] minutes = [175, 170, 205, 120, 220, 130, 105, 145, 190] labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] plt.scatter(friends, minutes) # label each point for label, friend_count, minute_count in zip(labels, friends, minutes): plt.annotate(label, xy=(friend_count, minute_count), xytext=(5, -5), # but slightly offset textcoords='offset points') plt.title("Daily Minutes vs. Number of Friends") plt.xlabel("# of friends") plt.ylabel("daily minutes spent on the site") plt.show() Thank you! Answer: So you're actually creating the variables in the `for` loop: for label, friend_count, minute_count in zip(labels, friends, minutes): When you `zip` those together you're grouping them by the index, so the first item it iterates to is `(70, 175, 'a')`, the second is `(65, 175, 'b')`, and so on. Python then _unpacks_ those three results, because you ask it to assign to three variables, `label`, `friend_count` and `minute_count`. If you were trying to unpack four variables and only supplied three names, for example, it would raise an error. Then each time it iterates through the loop it reassigns the next values to those three variables. Another way to think about this: if you wrote that line as: for values in zip(labels, friends, minutes): then `values` would just be the three items together every time, and those variables would not exist. You could then unpack them within the loop if you wanted. The way you posted is just a neater way to do it. One more example of unpacking that you can play with yourself: x = [1, 2, 3, 4] a, b, c, d = x would assign `a=1`, `b=2` and so on. However: a, b = x returns an error: > ValueError Traceback (most recent call last) in () \----> 1 a, b = x > > ValueError: too many values to unpack (expected 2) This gets more interesting using the `*` operator: a, *b = x results in: > In [38]: a > Out[38]: 1 > > In [39]: b > Out[39]: [2, 3, 4] That is, the `*` tells Python that the last value is the place to dump whatever is left. This behavior is again used a lot in functions, but can be used in for loops as well. Actually note that this `*` operator only works with lists, as I illustrated above, in Python 3.x. In 2.x you can still use it in functions this way, but not in assignment.
Why is idle skipping over f = open('filename' , 'r') Question: I'm writing a program in python and I am having issues getting idle to read my file out. If I use improper syntax it tells me, so it is being read by the compiler but not printing it for the user. Any help would be appreciated. Here is my code. #! python3.5.2 import sys if input() == ('im bored'): print('What season is it?') if input() == ('summer'): f = open('callfilesummer.txt', 'r') Answer: This doesn't do anything. Maybe take a look at the Python documentation? <https://docs.python.org/3/tutorial/inputoutput.html> That's a start. If you want to display the file, you can _very_ easily iterate over a file in Python like this: f = open('hurdurr', 'r') for line in f: print line
My WSGI application cannot be loaded as Python module. What am I doing wrong Question: I have been trying to get a WebAPI to run on the server. However I keep getting this error everytime I log into the site via the web browser > Internal Server Error > > The server encountered an internal error or misconfiguration and was unable > to complete your request. > > Please contact the server administrator, [email protected] and inform > them of the time the error occurred, and anything you might have done that > may have caused the error. > > More information about this error may be available in the server error log. > Apache/2.2.22 (Ubuntu) Server at complex.ffn.ub.es Port 80 I check the error log file and I have the following. > [Thu Jul 14 17:16:08 2016] [error] [client 161.116.80.82] mod_wsgi > (pid=21450): Target WSGI script '/home/xarxes_ub/python_code/configure.wsgi' > cannot be loaded as Python module. > > [Thu Jul 14 17:16:08 2016] [error] [client 161.116.80.82] mod_wsgi > (pid=21450): Exception occurred processing WSGI script > '/home/xarxes_ub/python_code/configure.wsgi'. > > [Thu Jul 14 17:16:08 2016] [error] [client 161.116.80.82] Traceback (most > recent call last): > > [Thu Jul 14 17:16:08 2016] [error] [client 161.116.80.82] File > "/home/xarxes_ub/python_code/configure.wsgi", line 10, in > > [Thu Jul 14 17:16:08 2016] [error] [client 161.116.80.82] from MenuUB2 > import app as application > > [Thu Jul 14 17:16:08 2016] [error] [client 161.116.80.82] ImportError: No > module named MenuUB2 I configured my .wsgi file based on the directions given on this site <http://flask.pocoo.org/docs/0.11/deploying/mod_wsgi/> It mentions specifically "Keep in mind that you will have to actually install your application into the virtualenv as well. Alternatively there is the option to just patch the path in the .wsgi file before the import: ` import sys sys.path.insert(0, '/path/to/the/application')`" Which is what I did Here is the configure.wsgi file import sys sys.path.insert(0, '/home/xarxes_ub/python_code/MenuUB2.py') from MenuUB2 import app as application In addition here is my apache configuration file that I edited. I highlighted the lines I added with ###. <VirtualHost *:80> DocumentRoot /var/www/web_del_grup/ ################Added lines############### WSGIScriptAlias /submitFrame /home/xarxes_ub/python_code/configure.wsgi WSGIDaemonProcess MenuUB2 user=www-data group=www-data threads=5 ################Added lines############### #####################Added Directory#################### <Directory /home/xarxes_ub/python_code> WSGIScriptReloading On WSGIProcessGroup MenuUB2 WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> #####################Added Directory#################### ErrorLog /var/log/apache2/error.log # Options -Indexes +FollowSymLinks MultiViews # RewriteEngine on # RewriteCond %{HTTP_REFERER} !^$ # RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?complex.ffn.ub.edu [NC] # RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?complex.ffn.ub.es [NC] # RewriteRule ^/xarxesub/(.json)$ - [F,NC,L] # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined Please tell me what needs to be done. If I can get this to work I'd be so relieved. Also note that I tried changing the "configure.wsgi" file to return a static and it works Example is here def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] Answer: Alright turns out I had a mistake in my configure.wsgi file I should name the folder that has the application and not the absolute path to the application so `/home/xarxes_ub/python_code` not `/home/xarxes_ub/python_code/MenuUB2.py` Here is the edited configure.wsgi file import sys sys.path.insert(0, '/home/xarxes_ub/python_code') from MenuUB2 import app as application
Django test DB returning nothing Question: I'm getting the exact same issue as [when does the database is being destroy in django tests?](http://stackoverflow.com/questions/30232963/when-does-the- database-is-being-destroy-in-django-tests?rq=1) , where my test DB seems to be getting deleted between each method. I know it's being cleared out each time I re-run **python3 manage.py test** , but it shouldn't be deleted in the middle of the test. I'm running Python 3.4.3, Postgresql 9.5.3, Django 1.9 from django.test import TestCase class myTestCases(TestCase): def test_1_load_regions(self): MyMethods._updateRegions() self.assertEqual(True, len(Region.objects.all()) >= minRegionsExpected) print("Regions: %s Languages: %s"%(len(Region.objects.all()), len(Language.objects.all()))) def test_2_load_languages(self): # Generated by _updateRegions, just check that a few languages exist print("Regions: %s Languages: %s"%(len(Region.objects.all()), len(Language.objects.all()))) self.assertEqual(True, len(Language.objects.all()) >= minLanguagesExpected) And I'm get an output like this: Regions: 11 Languages: 19 .Regions: 0 Languages: 0 F That makes me think everything is saving when the first test ends, but somehow when the second test starts everything is cleared out. I would rather avoid re-running everything at the start of each test, but right now I'm stumped at how to get the test DB to actually keep my results... **Edit/Results:** So after some poking in the right direction from the comments and answers, I found what I was looking for. <https://docs.djangoproject.com/en/1.9/topics/testing/overview/> > **Warning** > > If your tests rely on database access such as creating or querying models, > be sure to create your test classes as subclasses of > **django.test.TestCase** rather than **unittest.TestCase**. > > Using **unittest.TestCase** avoids the cost of running each test in a > transaction and flushing the database, but if your tests interact with the > database their behavior will vary based on the order that the test runner > executes them. This can lead to unit tests that pass when run in isolation > but fail when run in a suite. I was using test_1, test_2, test_3 as my names to ensure the order of operations, so that wasn't a problem. By swapping from django.test.TestCase to unittest.TestCase I got the results I wanted, with my database persisting between each test case. Answer: Actually, according to the [Django tutorial](https://docs.djangoproject.com/en/1.9/intro/tutorial05/#testing-our- new-view), the database is rolled back between each test. (See the bottom of the linked section.) If you're looking to have a common setup between tests, you should consider overriding the `TestCase` method `setUp`. This is run before each test function. The [`unittest` documentation](https://docs.python.org/3/library/unittest.html#unittest.TestCase) should be helpful for this, and Django has an [example](https://docs.djangoproject.com/en/1.9/topics/testing/overview/) in their documentation as well.
How to randomly choose a string from a list, and insert it into a new one? Question: I've recently made this program to simulate the concept of random generation with my example being trees, however I don't understand why I can't find an element within the list with a randomly generated number. I tried `Leaves.index()` but It doesn't seem to be working. Are there any ways to randomly take a string from one of my lists and add it into another list? import random Leaves=["Pointy","Rounded","Maple","Pine","Sticks"] Trunk=["Oak","Birch","Maple","Ash","Beech","Spruce"] Size=["Extra Large","Large","Medium","Small","Tiny"] Tree=[] while len(Tree)<len(Leaves)*len(Trunk)*len(Size): NewCombination=Leaves.index(random.randrange(len(Leaves)))+Trunk.index(random.randrange(len(Trunk)))+Size.index(random.randrange(len(Size))) if Tree != NewCombination: Tree=Tree+NewCombination print(Tree) Error: `Traceback (most recent call last): File "C:/Users/invis_000/Documents/Coding/Python/Generation.py", line 8, in <module>` Answer: From what I can tell, it seems like you want to create a list of a bunch of random features. The way I would personally go about this is by using the random method `Choice` Choice allows us to pick a string from a list, then we use a function called `.append` that lets us include it in another list from random import choice Leaves=["(Pointy ","(Rounded ","(Maple ","(Pine ","(Sticks "] Trunk=["Oak ","Birch ","Maple ","Ash ","Beech ","Spruce "] Size=["Extra Large)","Large)","Medium)","Small)","Tiny)"] Tree=[] NewCombination = [] while len(Tree)<len(Leaves)*len(Trunk)*len(Size): NewCombination.append((choice(Leaves)) + (choice(Trunk) + (choice(Size)))) if Tree != NewCombination: Tree=Tree+NewCombination print(Tree) I have also made it much easier to see the printed list by including brackets and spaces in your original three lists
How to do arithmetic on imported array in python? Question: I am new to python and only a student so if this question is extremely trivial I apologize I've imported a .csv file and indexed 2 columns using panda using the following: data_AM = pd.read_csv(name_AM, header = None, names = None, usecols = [2,4]) I want to subtract column 4 from column 2 but when I use np.subtract I get an error telling me that it is a string. When I attempt to convert the whole column into floats it only converts the column index header to a float. For example, if I use: x = [float(i) for i in time_AM] where time_AM is column 2, the output is [2.0] If I do the same thing for column 4, the output is [4.0] Here is what the output time_AM looks like: 2 3 0 4 2.83237624 5 7.64838266 6 11.6987 7 15.60853 8 19.3890476 9 25.1548729 10 30.15414 11 33.55736 12 37.2666435 13 41.67488 14 45.19324 15 50.327446 16 54.7211761 17 61.7345772 18 65.96731 19 72.20469 20 76.48047 21 80.90832 22 84.74452 Any advice on how to do arithmetic with this? Basically I am trying to automate something that would be extremely simple in excel because I'm gonna have to do it a bunch of times. Answer: Try this: data_AM.iloc[:, 2].astype('float64').subtract(data_AM.iloc[:,4].astype('float64')) [`.astype('float64')`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.astype.html) will convert the datatype of the column to float. And [`subtract`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.subtract.html) is the function you are looking for. [`.iloc`](http://pandas.pydata.org/pandas- docs/stable/indexing.html) is an indexer that indexes by position rather than label. I understand that the learning curve can be quite steep, Pandas is quite feature rich and there are lots of things in it. But do take a look at [the docs](http://pandas.pydata.org/pandas-docs/stable/index.html) for help.
Python3: ftp file upload throws TypeError: Type str doesn't support the buffer API Question: I'm using python 3.4.2 to upload a logfile to an ftp server (I removed the try and with statements for simplicity's sake): import ftplib ftp = ftplib.FTP(url) ftp.login(name, password) ftp.storlines("STOR " + "mylog.log", open("log/mylog.log")) ftp.close() The mylog.log file has a "text/plain; charset=us-ascii" encoding. ~~On my macbook everything works fine.~~ When I execute my little program on a raspberry pi (via ssh), I get the following error message: Traceback (most recent call last): File "./ftptest.py", line 7, in <module> ftp.storlines("STOR " + "mylog.log", open("log/mylog.log")) File "/usr/lib/python3.4/ftplib.py", line 537, in storlines if buf[-1] in B_CRLF: buf = buf[:-1] TypeError: Type str doesn't support the buffer API I guess it's some encoding and/or local settings issue. What am I doing wrong? What is the best practice here? Answer: From my reading of <http://bugs.python.org/issue6822>, I think for Python 3.x, you'll need `open("log/mylog.log", "rb")`.
Why am I getting TypeError: an integer is required? Question: This is my code snippet for where the traceback call shows an error: def categorize(title): with conn: cur= conn.cursor() title_str= str(title) title_words= re.split('; |, |\*|\n',title_str) key_list= list(dictionary.keys()) flag2= 1 for word in title_words: title_letters= list(word) flag1= 1 for key in key_list: if key==title_letters[0]: flag1= 0 break if flag1== 0: start=dictionary.get(title_letters[0]) end= next_val(title_letters[0]) for i in xrange (start,end): if word==transfer_bag_of_words[i]: flag2= 0 break if flag2== 0: cur.execute("select Id from articles where title=title") row_id= cur.fetchone() value= (row_id,'1') s= str(value) f.write(s) f.write("\n") break return def next_val(text): for i,v in enumerate(keyList): if text=='t': return len(transfer_bag_of_words) elif v==text: return dictionary[keyList[i+1]] This is the traceback call: Traceback (most recent call last): File "categorize_words.py", line 93, in <module> query_database() File "categorize_words.py", line 45, in query_database categorize(row) File "categorize_words.py", line 67, in categorize for i in xrange (start,end): TypeError: an integer is required I have not given the whole code here. But I will explain what I am trying to do. I am trying to import a particular field from a sqlite database and checking if a single word of the field matches with a particular bag of words I already have in my program. I have sorted the bag of words aphabetically and assigned every starting of a new letter to it's index using python dictionary. This I have done so that everytime I check a word of the field being present in the bag of words, I do not have to loop through the entire bag of words. Rather I can just start looping from the index of the first letter of the word. I have checked that the return type of get() in dictionary is int and the function nextVal also should return an int since both len() and dictionary[keylist[i+1]] are int types. Please help. **EDIT** This is my entire code: import sqlite3 as sql import re conn= sql.connect('football_corpus/corpus2.db') transfer_bag_of_words=['transfer','Transfer','transfers','Transfers','deal','signs','contract','rejects','bid','rumours','swap','moves', 'negotiation','negotiations','fee','subject','signings','agreement','personal','terms','pens','agent','in','for', 'joins','sell','buy','confirms','confirm','confirmed','signing','renew','joined','hunt','excited','move','sign', 'loan','loaned','loans','switch','complete','offer','offered','interest','price','tag','miss','signed','sniffing', 'remain','plug','pull','race','targeting','targets','target','eye','sale','clause','rejected', 'interested'] dictionary={} dictionary['a']=0; keyList=[] f= open('/home/surya/Twitter/corpus-builder/transfer.txt','w') def map_letter_to_pos(): pos=0 transfer_bag_of_words.sort() for word in transfer_bag_of_words: flag=1 letters= list(word) key_list= list(dictionary.keys()) for key in key_list: if key==letters[0]: flag=0 break if flag==1: dictionary[letters[0]]=pos pos+=1 else: pos+=1 keyList= sorted(dictionary.keys()) def query_database(): with conn: cur= conn.cursor() cur.execute("select title from articles") row_titles= cur.fetchall() for row in row_titles: categorize(row) def categorize(title): with conn: cur= conn.cursor() title_str= str(title) title_words= re.split('; |, |\*|\n',title_str) key_list= list(dictionary.keys()) flag2= 1 for word in title_words: title_letters= list(word) flag1= 1 for key in key_list: if key==title_letters[0]: flag1= 0 break if flag1== 0: start=dictionary.get(title_letters[0]) end= next_val(title_letters[0]) for i in xrange (start,end): if word==transfer_bag_of_words[i]: flag2= 0 break if flag2== 0: cur.execute("select Id from articles where title=title") row_id= cur.fetchone() value= (row_id,'1') s= str(value) f.write(s) f.write("\n") break return def next_val(text): for i,v in enumerate(keyList): if text=='t': return len(transfer_bag_of_words) elif v==text: return dictionary[keyList[i+1]] if __name__=='__main__': map_letter_to_pos() query_database() And this is the downloadable link to the database file <http://wikisend.com/download/702374/corpus2.db> Answer: map_letter_to_pos attempts to modify the global variable keyList without specifying it as a global variable, therefore it only modifies a local copy of keyList and then discards it. This causes next_val to have nothing to iterate, so it never reaches the if elif, and returns None. end = None range(start,end) # None is not an int
How do I filter incoming data from a socket in Python? Question: I am using a UDP socket program for one of my projects to read in incoming data from an EEG headset. I then use this data to control servo motors in a robotic arm. The code that I am using to create the socket and print out the data works fine. import socket import subprocess UDP_IP = "169.254.110.133" UDP_PORT = 50000 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT)) while True: (data,addr) = sock.recvfrom(1024) print(data) The data that is coming in is raw EEG data from the headset and it looks like this in the terminal: SourceTime 31972 TargetCode 1 ResultCode 0 Feedback 1 PauseApplication 0 CursorPosX 717 CursorPosY 2047 CursorPosZ 2047 This data has 33 different sections each few milliseconds. The data always comes in the same order. For my code, I only need a few pieces of information from the data (TargetCode, ResultCode, and Feedback). How do I filter out these sections and use them in my code. Is there a way to look for TargetCode and copy the number? Or since TargetCode is always number 24 in the stream of 33 sections can I extract it that way? Answer: This might help. **Server** import socket s = socket.socket() UDP_IP = "169.254.110.133" UDP_PORT = 50000 sock.bind((UDP_IP, UDP_PORT)) s.listen(5) while True: c, addr = s.accept() c.send('Connected to server.') c.close() **Client** import socket UDP_IP = "169.254.110.133" UDP_PORT = 50000 s = socket.socket() s.connect((UDP_IP,UDP_PORT)) print (s.recv(1024)) s.close
How to pass multiple parameters to python function Question: I have a numpy array with 300 entries. Within each entry is another numpy array [2048 x 2048]. Each entry is a "tiff" entry (in matrix form) which corresponds to the pixel position in a detector. Now, what I want to do is centralize this so that I have an [2048 x 2048] array with each entry having 300 entries corresponding to the pixels from the 300 frames. I think I have found a way using the `zip` function. But, each time I get back either a [300 x 2048 x 2048] or [2048 x 300 x 2048]. I want a [2048 x 2048 x 300]. I'm trying to do this in a rather economical and pythonic way beyond simply reloading into a new array and reindexing. T_prime = zip(([list(t) for t in zip(*Tiffs)])) Where `Tiffs` is the array as described above. Answer: In numpy we often add dimmensions to an array instead of using nested arrays (which is the norm with lists for examples). Once you have all your data in a single array, it's easy to operate on it. In your case it looks like you're looking to transpose the array. An example: import numpy as np example_data = np.empty(30, dtype=object) for i in range(30): example_data[i] = np.zeros((100, 101)) structured = np.array(list(example_data)) print structured.shape # (30, 100, 101) print structured.transpose([1, 2, 0]).shape # (100, 101, 30)
python handling DictReader missing keys Question: This script is working fine, until I hit a cell that is empty: import csv,time,string,os,requests dw = "\\\\network\\folder\\btc.csv" inv_fields = ["id", "rsl", "number", "GP%"] with open(dw) as infile, open("c:\\upload\\log.csv", "wb") as outfile: r = csv.DictReader(infile) w = csv.DictWriter(outfile, inv_fields, extrasaction="ignore") r = (dict((k, v.strip()) for k, v in row.items() if v) for row in r) wtr = csv.writer( outfile ) wtr.writerow(["id", "resale", "number", "percentage"]) for i, row in enumerate(r, start=1): row['id'] = i row['GP%'] = row['GP%'].replace("%","") w.writerow(row) print "file successfully saved" The script is failing on this line: row['GP%'] = row['GP%'].replace("%","") and by adding `print i` to the loop I can see it is failing on the line of the .csv file where this input value is blank. How do I take cells with no value into this equation? The python error: Traceback (most recent call last): File "backlog.py", line 80, in <module> row['GP%'] = row['GP%'].replace("%","") KeyError: 'GP%' Answer: You can check if key `'GP%'` is the in the `row` dictionary before attempting to update its value. If it isn't you could assign a default value so the entry related to that `id` is blank in the output file: for i, row in enumerate(r, start=1): row['id'] = i if 'GP%' in row: row['GP%'] = row['GP%'].replace('%','') else: row['GP%'] = '' w.writerow(row) Or use the `get` method of `row` to set the default value: for i, row in enumerate(r, start=1): row['id'] = i row['GP%'] = row.get('GP%', '').replace('%','') w.writerow(row)
Confusing error when attempting to start the Jupyter notebook Question: The following output appeared when I was attempting to start an instance of the Jupyter botebook: C:\Users\CaitlinG>jupyter notebook Traceback (most recent call last): File "c:\users\caitling\appdata\local\programs\python\python35\lib\runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "c:\users\caitling\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\CaitlinG\AppData\Local\Programs\Python\Python35\Scripts\jupyter -notebook.exe\__main__.py", line 5, in <module> File "c:\users\caitling\appdata\local\programs\python\python35\lib\site-packag es\notebook\notebookapp.py", line 31, in <module> from zmq.eventloop import ioloop File "c:\users\caitling\appdata\local\programs\python\python35\lib\site-packag es\zmq\__init__.py", line 37, in <module> _libzmq = ctypes.cdll.LoadLibrary(bundled[0]) File "c:\users\caitling\appdata\local\programs\python\python35\lib\ctypes\__in it__.py", line 425, in LoadLibrary return self._dlltype(name) File "c:\users\caitling\appdata\local\programs\python\python35\lib\ctypes\__in it__.py", line 347, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found I am using Windows 10 and Python 3.5.2. I installed the package, along with its dependencies, via: pip3 install "ipython[notebook]" --upgrade The aforementioned process proceeded without incident but I am confused why the issue has appeared. Thanks. Answer: It seems to be an issue with pyzmq 15.3. Installing a previous version worked for me: pip install pyzmq==15.2 See: <https://github.com/jupyter/help/issues/62> Good luck!
iPython debugger not providing any insight Question: Let's say I have the following function: def simple_func(): a = 4 b = 5 c = a * b print c Here's what I get when I run `%debug simple_func()`: NOTE: Enter 'c' at the ipdb> prompt to continue execution. None > <string>(1)<module>() ipdb> If I enter `n` the debugger spits 20 back out at me and returns `None`. This is a simplified version of what's happening across functions, interpreters, machines, etc. What's going on? Why can't I get any of my debuggers to do what I want, when all I need is to do some very simple line- by-line stepping through? Answer: It doesn't look like `debug` works with a function that's simply defined in the `ipython` session. It needs to be imported from a file (that is, the `--breakpoint` parameter takes a file name and line). If I create a file `test.py` In [9]: cat test.py def simple_func(): a = 4 b = 5 c = a * b print(c) I can do: In [10]: import test In [11]: %debug --breakpoint test.py:1 test.simple_func() Breakpoint 1 at /home/paul/mypy/test.py:1 NOTE: Enter 'c' at the ipdb> prompt to continue execution. > /home/paul/mypy/test.py(2)simple_func() 1 1 def simple_func(): ----> 2 a = 4 3 b = 5 4 c = a * b 5 print(c) ipdb> n > /home/paul/mypy/test.py(3)simple_func() 1 1 def simple_func(): 2 a = 4 ----> 3 b = 5 4 c = a * b 5 print(c) ipdb> n > /home/paul/mypy/test.py(4)simple_func() 2 a = 4 3 b = 5 ----> 4 c = a * b 5 print(c) 6 ipdb> a,b (4, 5) ipdb> n > /home/paul/mypy/test.py(5)simple_func() 2 a = 4 3 b = 5 4 c = a * b ----> 5 print(c) 6 ipdb> c 20 ipdb> c 20 ipdb> q There may be other ways of using this, but this seems to be simplest, most straight forward one. I rarely use the debugger. Instead I test code snippets interactively in Ipython, and sprinkle my scripts with debugging `prints`.
python logging - message not showing up in child Question: I am having some difficulties using python's logging. I have two files, main.py and mymodule.py. Generally main.py is run, and it will import mymodule.py and use some functions from there. But sometimes, I will run mymodule.py directly. I tried to make it so that logging is configured in only 1 location, but something seems wrong. Here is the code. # main.py import logging import mymodule logger = logging.getLogger(__name__) def setup_logging(): # only cofnigure logger if script is main module # configuring logger in multiple places is bad # only top-level module should configure logger if not len(logger.handlers): logger.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S') ch.setFormatter(formatter) logger.addHandler(ch) if __name__ == '__main__': setup_logging() logger.info('calling mymodule.myfunc()') mymodule.myfunc() and the imported module: # mymodule.py import logging logger = logging.getLogger(__name__) def myfunc(): msg = 'myfunc is being called' logger.info(msg) print('done with myfunc') if __name__ == '__main__': # only cofnigure logger if script is main module # configuring logger in multiple places is bad # only top-level module should configure logger if not len(logger.handlers): logger.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S') ch.setFormatter(formatter) logger.addHandler(ch) logger.info('myfunc was executed directly') myfunc() When I run the code, I see this output: $>python main.py INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc() done with myfunc But I expect to see this: $>python main.py INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc() INFO: 2016-07-14 18:15:09 myfunc(8) -- myfunc is being called done with myfunc Anybody have any idea why the second logging.info call doesn't print to screen? thanks in advance! Answer: Loggers exist in a hierarchy, with a root logger (retrieved with `logging.getLogger()`, no arguments) at the top. Each logger inherits configuration from its parent, with any configuration on the logger itself overriding the inherited configuration. In this case, you are never configuring the root logger, only the module-specific logger in `main.py`. As a result, the module-specific logger in `mymodule.py` is never configured. The simplest fix is probably to use `logging.basicConfig` in `main.py` to set options you want shared by _all_ loggers.
z3opt python -- minimizing square Question: I was considering using z3 to minimize problems involving squares. But when I write this simple example (z3opt in python 3) : from z3 import * a = Real('a') b = Real('b') cost = Real('cost') opt = Optimize() opt.add(a + b == 3) opt.add(And(a >= 0, a <= 10)) opt.add(And(b >= 0, b <= 10)) opt.add(cost == a * 10.0 + b ** 2.0) h = opt.minimize(cost) print(opt.check()) print(opt.reason_unknown()) print(opt.lower(h)) print(opt.model()) The check returns "unknown": unknown (incomplete (theory arithmetic)) -1*oo [b = 0, cost = 30, a = 3] Am I defining the problem in the wrong way or is this an intrinsic limitation of z3? Answer: Both [νZ - An Optimizing SMT Solver](https://www.microsoft.com/en- us/research/wp-content/uploads/2016/02/nbjorner-nuz.pdf) and [νZ - Maximal Satisfaction with Z3](https://www.microsoft.com/en-us/research/wp- content/uploads/2016/02/nbjorner-scss2014.pdf) explicitly mention that **Linear Arithmetic Optimization** is supported, whereas you are trying to optimise a _non-linear objective_. I guess the authors would mention it if _non-linear objectives_ were supported, since it is not a minor feature. * * * **Workaround.** In your example you can obviously use a workaround to get past this issue since _cost_ is given by the sum of two _positive and independent addends_ , e.g. turn the problem into a lexicographic optimization problem in which you first minimize `a` and then `b`: (declare-fun a () Real) (declare-fun b () Real) (declare-fun cost () Real) (assert (= (+ a b) 3)) (assert (<= 0 a)) (assert (<= a 10)) (assert (<= 0 b)) (assert (<= b 10)) (assert (= cost (+ (* 10 a) (* b b)))) (minimize a) (minimize b) (check-sat) (get-model) and get sat (objectives (a 0) (b 3) ) (model (define-fun b () Real 3.0) (define-fun cost () Real 9.0) (define-fun a () Real 0.0) ) But I guess this is a _minimal example_ for a larger problem, thus it might not be of much help.
InvalidTemplateLibraryError on initial runserver using wagtail Question: Everytime i do `python manage.py runserver` an error said > Invalid template library specified. > > ImportError raised when trying to load > 'wagtail.wagtailcore.templatetags.wagtailcore_tags': cannot import name > _htmlparser Answer: There is some bug with new version of html5lib. I found two solutions for this problem: 1. Downgrade html5lib (I tried with version 0.9999999) > pip uninstall html5lib > pip install html5lib==0.9999999 After downgrade everything seems to work perfectly. 2. Temporary fix by editing beautifulsoup4 package file > <path_to_your_virtualenv>/lib/python2.7/site- > packages/bs4/builder/__init__.py At the end of a file you need to comment out next lines: from . import _htmlparser register_treebuilders_from(_htmlparser) try: from . import _html5lib register_treebuilders_from(_html5lib) except ImportError: # They don't have html5lib installed. pass After you comment them out wagtail will properly start. _P.S. I prefer first option._ **Edit 1:** Found open GitHub issue: <https://github.com/html5lib/html5lib- python/issues/276>
How to round a number to n decimal places in Python Question: I want, what I enter in the entry field should be automatic rounded to n decimal points. import Tkinter as Tk root = Tk.Tk() class InterfaceApp(): def __init__(self,parent): self.parent = parent root.title("P") self.initialize() def initialize(self): frPic = Tk.Frame(bg='', colormap='new') frPic.grid(row=0) a= Tk.DoubleVar() self.entry = Tk.Entry(frPic, textvariable=a) a.set(round(self.entry.get(), 2)) self.entry.grid(row=0) if __name__ == '__main__': app = InterfaceApp(root) root.mainloop() Answer: You do not get the expected result because when you run `a.set(round(self.entry, 2))` inside `initialize()` , the value of `self.entry.get()` is always `0` (the default value after creation) You rather need to attach a [callback](http://effbot.org/zone/tkinter- callbacks.htm) to a button widget on which, after pressing, the behavior you are looking for will be executed: import Tkinter as Tk root = Tk.Tk() class InterfaceApp(): def __init__(self,parent): self.parent = parent root.title("P") self.initialize() def initialize(self): frPic = Tk.Frame(bg='', colormap='new') frPic.grid(row=0, column=0) self.a = Tk.DoubleVar() self.entry = Tk.Entry(frPic, textvariable=self.a) self.entry.insert(Tk.INSERT,0) self.entry.grid(row=0, column=0) # Add a button widget with a callback self.button = Tk.Button(frPic, text='Press', command=self.round_n_decimal) self.button.grid(row=1, column=0) # Callback def round_n_decimal(self): self.a.set(round(float(self.entry.get()), 2)) if __name__ == '__main__': app = InterfaceApp(root) root.mainloop()
How can I get to String "no comm" instead of null value using pandas in python ? Question: How can I get to string "no comm" instead of null value using pandas ? emp.csv index empno ename job mgr hiredate sal comm deptno 0, 7839, KING, PRESIDENT, 0, 1981-11-17, 5000, , 10 1, 7698, BLAKE, MANAGER, 7839, 1981-05-01, 2850, , 30 2, 7782, CLARK, MANAGER, 7839, 1981-05-09, 2450, , 10 3, 7566, JONES, MANAGER, 7839, 1981-04-01, 2975, , 20 4, 7654, MARTIN, SALESMAN, 7698, 1981-09-10, 1250, 1400, 30 5, 7499, ALLEN, SALESMAN, 7698, 1981-02-11, 1600, 300, 30 6, 7844, TURNER, SALESMAN, 7698, 1981-08-21, 1500, 0, 30 7, 7900, JAMES, CLERK, 7698, 1981-12-11, 950, , 30 8, 7521, WARD, SALESMAN, 7698, 1981-02-23, 1250, 500, 30 9, 7902, FORD, ANALYST, 7566, 1981-12-11, 3000, , 20 10, 7369, SMITH, CLERK, 7902, 1980-12-09, 800, , 20 11, 7788, SCOTT, ANALYST, 7566, 1982-12-22, 3000, , 20 12, 7876, ADAMS, CLERK, 7788, 1983-01-15, 1100, , 20 13, 7934, MILLER, CLERK, 7782, 1982-01-11, 1300, , 10 I want to get the below result about column comm using pandas. result : no comm no comm no comm no comm 1400 300 0 no comm 500 no comm no comm no comm no comm no comm I want to get above result using bleow code. code : import sys import pandas as pd import dateutil import pandas as pd import io temp=u"""index empno ename job mgr hiredate sal comm deptno 0, 7839, KING, PRESIDENT, 0, 1981-11-17, 5000, , 10 1, 7698, BLAKE, MANAGER, 7839, 1981-05-01, 2850, , 30 2, 7782, CLARK, MANAGER, 7839, 1981-05-09, 2450, , 10 3, 7566, JONES, MANAGER, 7839, 1981-04-01, 2975, , 20 4, 7654, MARTIN, SALESMAN, 7698, 1981-09-10, 1250, 1400, 30 5, 7499, ALLEN, SALESMAN, 7698, 1981-02-11, 1600, 300, 30 6, 7844, TURNER, SALESMAN, 7698, 1981-08-21, 1500, 0, 30 7, 7900, JAMES, CLERK, 7698, 1981-12-11, 950, , 30 8, 7521, WARD, SALESMAN, 7698, 1981-02-23, 1250, 500, 30 9, 7902, FORD, ANALYST, 7566, 1981-12-11, 3000, , 20 10, 7369, SMITH, CLERK, 7902, 1980-12-09, 800, , 20 11, 7788, SCOTT, ANALYST, 7566, 1982-12-22, 3000, , 20 12, 7876, ADAMS, CLERK, 7788, 1983-01-15, 1100, , 20 13, 7934, MILLER, CLERK, 7782, 1982-01-11, 1300, , 10""" #after testing replace io.StringIO(temp) to filename emp = pd.read_csv(io.StringIO(temp), skipinitialspace=True, skiprows=1, parse_dates=[5], names=['index','empno','ename', 'job','mgr','hiredate','sal','comm','deptno']) <-------------- ? print( emp['comm']) Answer: this could just be the formatting on this site, but it looks like 1400, 300, 0 and 500 are in a different level of indentation to the rest of the numbers, which is why it would return no comm
How to replace keywords in dict values in list of dicts (with case insensitivity)? Question: I have a list of keywords: keywords = ["test", "Ok", "great stuff", "PaaS", "mydata"] And a list of dicts: statements = [ {"id":"1","text":"Test, this is OK, great stuff, PaaS."}, {"id":"2","text":"I would like to test this, Great stuff."} ] **Desired Behavior** When the `keyword` is present in `statement['text']` (regardless of case), I want to replace the keyword with a "marked up" version of the keyword, ie the matched keyword `Test` would become: <span class="my_class" data-mydata="<a href=&quot;#&quot;>test</a>">Test</span> **What I've Tried** Below is what I've tried, the observations/considerations being: **01)** It is not replacing the keywords. **02)** If it was, once the markup is applied, I do not want matches occuring within the markup - ie the `mydata` within the markup should not be matched. **03)** I may have started out in the wrong direction with this, and need to redesign the logic from the start. **Python 2.7 Code** import re keywords = ["test", "ok", "great stuff", "paas"] statements = [ {"id":"1","text":"Test, this is OK, great stuff, PaaS."}, {"id":"2","text":"I would like to test this, Great stuff."} ] keyword_markup = {} print "\nKEYWORDS (all lowercase):\n" for i in keywords: print "\"" + i + "\" " print "\nORIGINAL STATEMENTS:\n" for statement in statements: print statement['text'] + "\n" statement_counter = 1 # for each statement for statement in statements: print "\nIN STATEMENT " + str(statement_counter) + ": \n" # get the original statement original_statement = statement['text'] # for each keyword in the keyword list for keyword in keywords: # if the keyword is not in the keyword_markup dict # add it (with a lowercase key) if keyword.lower() not in keyword_markup: keyword_markup[keyword.lower()] = "<span class=\"my_class\" data-mydata=\"<a href=&quot;#&quot;>" + keyword + "</a>\">" + keyword + "</span>" print "The key added to the keyword_markup dict is: " + keyword.lower() # if the keyword is in a lowercase version of the statement if keyword in original_statement.lower(): # sanity check - print the matched keyword print "The keyword matched in the statement is: " + keyword # change the text value of the statement "in place" # by replacing the keyword, with its marked up equivalent. # using the original_statement as the source string statement['text'] = re.sub(keyword,keyword_markup[keyword.lower()],original_statement) statement_counter += 1 print "\nMARKED UP KEYWORDS AVAILABLE:\n" for i in keyword_markup: print keyword_markup[i] print "\nNEW STATEMENTS:\n" for statement in statements: print statement['text'] + "\n" **Results** KEYWORDS (all lowercase): "test" "ok" "great stuff" "paas" ORIGINAL STATEMENTS: Test, this is OK, great stuff, PaaS. I would like to test this, Great stuff. IN STATEMENT 1: The key added to the keyword_markup dict is: test The keyword matched in the statement is: test The key added to the keyword_markup dict is: ok The keyword matched in the statement is: ok The key added to the keyword_markup dict is: great stuff The keyword matched in the statement is: great stuff The key added to the keyword_markup dict is: paas The keyword matched in the statement is: paas IN STATEMENT 2: The keyword matched in the statement is: test The keyword matched in the statement is: great stuff MARKED UP KEYWORDS AVAILABLE: <span class="my_class" data-mydata="<a href=&quot;#&quot;>test</a>">test</span> <span class="my_class" data-mydata="<a href=&quot;#&quot;>paas</a>">paas</span> <span class="my_class" data-mydata="<a href=&quot;#&quot;>ok</a>">ok</span> <span class="my_class" data-mydata="<a href=&quot;#&quot;>great stuff</a>">great stuff</span> NEW STATEMENTS: Test, this is OK, great stuff, PaaS. I would like to test this, Great stuff. Answer: I was able to do this without regular expressions, though re.sub or re.findall with re.IGNORECASE would be a good place to start (as you discovered) if that's the direction you want to go. I also started thinking about writing a one-pass tokenizer, but decided a multi-pass system was simpler to understand and maintain than some ugly state machine. The code below is optimized for readability, not performance. def main(): keywords = ["test", "ok", "great stuff", "paas"] statements = [ {"id":"1","text":"Test, this is OK, great stuff, PaaS."}, {"id":"2","text":"I would like to test this, Great stuff."} ] for statement in statements: m = markup_statement(statement['text'], keywords) print('id={}, text={}'.format(statement['id'], m)) Produces the following output: id=1, text=<a href="#">Test</a>, this is <a href="#">OK</a>, <a href="#">great stuff</a>, <a href="#">PaaS</a>. id=2, text=I would like to <a href="#">test</a> this, <a href="#">Great stuff</a>. Here are the supporting functions: def markup_statement(statement, keywords): """Returns a string where keywords in statement are marked up >>> markup_statement('ThIs is a tEst stAtement', ['is', 'test']) 'Th<a href="#">Is</a> <a href="#">is</a> a <a href="#">tEst</a> stAtement' """ markedup_statement = [] keywords_lower = {k.lower() for k in keywords} for token in tokenize(statement, keywords): if token.lower() in keywords_lower: markedup_statement.append(markup(token)) else: markedup_statement.append(token) return ''.join(markedup_statement) def markup(keyword): """returns the marked up version of a keyword/token (retains the original case) This function provides the same markup regardless of keyword, but it could be modified to provide keyword-specific markup >>> markup("tEst") '<a href="#">tEst</a>' """ return '<a href="#">{}</a>'.format(keyword) This tokenizer makes multiple passes over the statement, one pass for each keyword. The order of keywords may affect the tokens returned by `tokenize`. For example, if the markup replacement function is `markup = {'at': lambda x: '@', 'statement': lambda x: '<code>{}</code>'.format(x)}.get` then `'This is a statement statement'` could either be `'This is a st@ement'` or `'This is a <code>statement</code>'`. def tokenize(statement, keywords): """Adapted from https://docs.python.org/3/library/re.html#writing-a-tokenizer Splits statement on keywords Assumes that there is no overlap between keywords in statement >>> tokenize('ThIs is a tEst stAtement', ['is', 'test']) ['Th', 'Is', ' ', 'is', ' a ', 'tEst', ' stAtement'] >>> ''.join(tokenize(statement, keywords)) == statement True """ statement_fragments = [statement] for keyword in keywords: statement_fragments = list(split(statement_fragments, keyword)) return statement_fragments This is not a particularly fast splitter, but is simple enough to explain the idea. I could have used `re.split(pattern, string, flags=re.IGNORECASE)` here, but I avoid regular expressions when vanilla python logic works, since regex code is seldom readable and not particularly fast. def split(statement_fragments, keyword): """Split each statement fragment by keywords statement_fragments: list of strings keyword: string returns list of strings, which may be the same length or longer than statement_fragments This repeatedly trims and lowercases strings. If it's a bottleneck, rewrite it with a start and end index slices >>> split(['ThIs is a tEst stAtement'], 'is') ['Th', 'Is', ' ', 'is', ' a tEst stAtement'] """ keyword_lower = keyword.lower() length = len(keyword) for fragment in statement_fragments: i = fragment.lower().find(keyword_lower) while i != -1: yield fragment[:i] yield fragment[i:i+length] fragment = fragment[i+length:] i = fragment.lower().find(keyword_lower) # yield whatever is left over yield fragment Without comments, that's around 30 lines of code with no imports.
Uploading a file via pyCurl Question: I am trying to convert the following curl code into pycurl. I do not want to use requests. I need to use pycurl because requests is not fully working in my old python version. curl -X POST -H "Accept-Language: en" -F "[email protected]" -F "[email protected]" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={api-key}&version=2016-05-20" Can someone please show me how to write it out in PyCurl? Answer: import pycurl c = pycurl.Curl() c.setopt(c.URL, 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={api-key}&version=2016-05-20') c.setopt(c.POST, 1) c.setopt(c.HTTPPOST, [("images_file", (c.FORM_FILE, "fruitbowl.jpg"))]) c.setopt(c.HTTPPOST, [("parameters", (c.FORM_FILE, "myparams.json"))]) c.setopt(pycurl.HTTPHEADER, ['Accept-Language: en']) c.perform() c.close()
Tkinter createfilehandler with socket not working Question: I found a working example for Tkinter createfilehandler with socket in Chapter 18 from "Python and Tkinter Programming" (of John Grayson) client_server.py I have tested it on Linux Mint 14.04, with python 2.7.6, and the program seems to work without errors, but ... The problem is that: server sends date and hour, but client does not display this. I do not understand why. Can you help me to understand the problem? Here is the code: from Tkinter import * import sys, socket, time class Server: def __init__(self): host = 'localhost' #socket.gethostbyname(socket.gethostname()) addr = host, 18000 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(addr) while 1: time.sleep(5) print time.asctime(time.localtime(time.time())) s.sendto(time.asctime(time.localtime(time.time())), addr) class GUIClient: def __init__(self, master=None): self.master = master self.master.title('Time Service Client') self.frame = Frame(master, relief=RAISED, borderwidth=2) self.text = Text(self.frame, height=26, width=50) self.scroll = Scrollbar(self.frame, command=self.text.yview) self.text.configure(yscrollcommand=self.scroll.set) self.text.pack(side=LEFT) self.scroll.pack(side=RIGHT, fill=Y) self.frame.pack(padx=4, pady=4) Button(master, text='Close', command=self.master.quit).pack(side=TOP) self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.bind(('localhost', 18000)) self.master.createfilehandler(self.socket, READABLE, self.ihandler) self.master.after(5000, self.doMark) def ihandler(self, sock, mask): data, addr = sock.recvfrom(256) self.text.insert(END, '%s\n' % data) def doMark(self): self.text.insert(END, 'waiting...\n') self.master.after(5000, self.doMark) if len(sys.argv) < 2: print 'select -s (server) or -c (client)' sys.exit(2) if sys.argv[1] == '-s': server=Server() elif sys.argv[1] == '-c': root = Tk() root.option_readfile('optionDB') example = GUIClient(root) root.mainloop() I have modified code to work without problems. Answer: The host variable in `Server.__init__` is quite likely different than IP address `127.0.0.1` used by `GUIClient` class Server: def __init__(self): host = socket.gethostbyname(socket.gethostname()) ... # addr probably != 127.0.0.1 s.sendto(time.asctime(time.localtime(time.time())), addr) class GUIClient: def __init__(self, master=None): ... self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # change port if necessary self.socket.bind(('127.0.0.1', 18000))
Django - Get item from iterable in django template Question: When iterating through a list in one of my Django templates, I'm trying to put in some if logic to say 'if the last items 'type' value is equal to the current item in the loops 'type' value, but it seems that python syntax for doing that is not allowed in a Django template. I know I can use {{ forloop.counter }}, but I can't seem to use that counter to get an item from my list at a specific index. HTML {% for repair in repairs %} {% if repairs[{{ forloop.counter - 1}}].type == repair.type %}<div class="col-sm-12" style="border-top: 1px solid grey; border-bottom: 1px solid grey;"><h2>{{ repair.type }}</h2></div>{% endif %} <div class="col-sm-6"> <label> <input type="checkbox" name="{{ repair }}"> {{ repair }}</label> </div> {% endfor %} or also {% for index, repair in enumerate(repairs) %} {% if repairs[index - 1].type == repair.type%}<div class="col-sm-12" style="border-top: 1px solid grey; border-bottom: 1px solid grey;"><h2>{{ repair.type }}</h2></div>{% endif %} <div class="col-sm-6"> <label> <input type="checkbox" name="{{ repair }}"> {{ repair }}</label> </div> {% endfor %} Answer: There are multiple issues with your code. As noted by [Justin](http://stackoverflow.com/questions/38399570/django-get- item-from-iterable-in-django-template/38399707#comment64207644_38399570), Django templates do not allow you to access a list element using something like `list[index]`. Instead you should do `list.index` Django template Engine have no way to determine the type of a variable. You can, though, implement a template filter and use it to determine the type of a variable as explained in [this](http://stackoverflow.com/a/12028864/2801699) answer. Also, instead of `{{ forloop.counter - 1}}`, you should do `{{ forloop.counter0 - 1}}`. `forloop.counter` gives a 1-indexed iteration of the loop whereas `forloop.counter0` gives a 0-indexed iteration of the loop. So your final code should look something like: from django import template register = template.Library() @register.filter def get_type(value): return type(value) {% for repair in repairs %} {% if repairs.{{ forloop.counter0 - 1}}|get_type == repair|get_type %} <div class="col-sm-12" style="border-top: 1px solid grey; border-bottom: 1px solid grey;"> <h2>{{ repair|get_type }}</h2> </div> {% endif %} <div class="col-sm-6"> <label> <input type="checkbox" name="{{ repair }}"> {{ repair }} </label> </div> {% endfor %} **Edit:** After you clarified, that 'type' is actually an attribute of the variable, here is what your code should be: {% for repair in repairs %} {% if repairs.{{ forloop.counter0 - 1}}.type == repair.type %} <div class="col-sm-12" style="border-top: 1px solid grey; border-bottom: 1px solid grey;"> <h2>{{ repair.type }}</h2> </div> {% endif %} <div class="col-sm-6"> <label> <input type="checkbox" name="{{ repair }}"> {{ repair }} </label> </div> {% endfor %} Of course, the method suggested by [Daniel](http://stackoverflow.com/questions/38399570/django-get-item-from- iterable-in-django-template/38399799#38399799) is a better way to do this.
Working with tensorflow's shuffle_batch method Question: I'm experimenting with [tensorflow](https://www.tensorflow.org/) and I'm trying to read from a `csv` file and print out a batch of its data via `shuffle_batch`. I've gone throw the [decode_csv docs](https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#decode_csv) and the [shuffle_batch docs](https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#shuffle_batch), but I'm still unable to get it working. Here's what I have: import tensorflow as tf sess = tf.InteractiveSession() filename_queue = tf.train.string_input_producer( ["./data/train.csv"], num_epochs=1, shuffle=True) # total record count in csv is 30K reader = tf.TextLineReader() key, value = reader.read(filename_queue) record_defaults = [["1"], ["2"]] # irrelevant for this discussion input, outcome = tf.decode_csv(value, record_defaults=record_defaults) min_after_dequeue = 1000 batch_size = 10 capacity = min_after_dequeue + 3 * batch_size example_batch = tf.train.shuffle_batch([outcome], batch_size, capacity, min_after_dequeue) coord = tf.train.Coordinator() tf.train.start_queue_runners(sess, coord=coord) example_batch.eval(session = sess) Running this will generate this exception: OutOfRangeError: RandomShuffleQueue '_3_shuffle_batch_1/random_shuffle_queue' is closed and has insufficient elements (requested 10, current size 0) I'm not sure what the issue is. I have a feeling it's due to the session and the way I'm handling it; I'm probably not doing it properly. Answer: Try removing the `num_epochs=1` from your `string_input_producer` initializer.
"python myscript" ignores "#!/usr/bin/env pythonX" where pythonX doesn't exist Question: **Why doesn't`test.py` throw error `env: python3: No such file or directory` when Python 3 is not installed?** My system (Mac OS X) has Python 2.7 installed, but not Python 3: $ /usr/bin/env python -V Python 2.7.12 $ /usr/bin/env python3 -V env: python3: No such file or directory File **test.py:** #!/usr/bin/env python3 import sys print sys.executable Executing **test.py:** $ python test.py /usr/local/opt/python/bin/python2.7 I thought that since Python 3 does not exist on my system, having the shebang line `#!/usr/bin/env python3` will throw an error and terminate the script. But `env` actually selected the Python 2.7 interpreter. Answer: The shebang is interpreted by OS when it tries to execute the script. Whey you type `python test.py`, the OS executes `python` and `python` executes the script (and `python` is found based on the current `PATH`) as opposed to being processed by the OS. If you make the script executable (`chmod +x test.py`) and then try to execute it directly (e.g. `./test.py`), the OS will be responsible for running the script so it will look at the shebang to figure out what program is responsible to run the script. In this case, it is `/usr/bin/env` which will look for `python3` and try to use that. Since `python3` isn't there (or not findable on your `PATH`) you'll see the error.
Python/Pygame Title Rendering Question: I'm trying to render a title for a little project I'm working on. I've replicated the same code which was used to create the options set (merely for ease) yet it isn't working. I was wondering if anyone knows where I'm going wrong? it's probably something really obvious but I'm not experienced when it comes to python. Here's the code: import pygame class Option: hovered = False def __init__(self, text, pos): self.text = text self.pos = pos self.set_rect() self.draw() def draw(self): self.set_rend() screen.blit(self.rend, self.rect) def set_rend(self): self.rend = menu_font.render(self.text, True, self.get_color()) def get_color(self): if self.hovered: return (255, 255, 255) else: return (100, 100, 100) def set_rect(self): self.set_rend() self.rect = self.rend.get_rect() self.rect.topleft = self.pos class Title: hovered = False def __init__(self, text, pos): self.text = text self.pos = pos self.set_rect() self.draw() def draw(self): self.set_rend() screen.blit(self.rend, self.rect) def set_rend(self): self.rend = title_font.render(self.text, True, self.get_color()) def get_color(self): if self.hovered: return (255, 255, 255) else: return (255, 255, 255) def set_rect(self): self.set_rend() self.rect = self.rend.get_rect() self.rect.topleft = self.pos pygame.init() screen = pygame.display.set_mode((480, 320)) menu_font = pygame.font.Font(None, 40) options = [Option("PLAY GAME", (140, 105)), Option("OPTIONS", (155, 155)), Option("QUIT", (180, 205)), Option("NOTPONG", (150,20))] title_font = pygame.display.font.Font(None, 42) title = [Title("NOTPONG", (150,20)) while True: pygame.event.pump() screen.fill((0, 0, 0)) for option in options: if option.rect.collidepoint(pygame.mouse.get_pos()): option.hovered = True else: option.hovered = False option.draw() pygame.display.update() while True: pygame.event.pump() screen.fill((0, 0, 0)) for Title in title: if title.rect.collidepoint(pygame.mouse.get_pos()): title.hovered = True else: title.hovered = False title.draw() pygame.display.update() Answer: I do not know what exactly you want to happen. But I think you simple have some typos. The line `title = [Title("NOTPONG", (150,20))` needs to be `title = [Title("NOTPONG", (150,20))]` with the closing bracket. And the line `title_font = pygame.display.font.Font(None, 42)` needs to be `title_font = pygame.font.Font(None, 42)` without the `.display` part. After fixing those errors your menu screen appears but does not do anything. I'm not sure if you were just trying to get the menu to show or you can't get the menu to do anything or show. hope this helps fix your problem. ~Mr.Python
Creating Grouped bars in Matplotlib Question: I have just started learning python and I am using the Titanic data set to practice I am not able to create a grouped bar chart and it it giving me an error 'incompatible sizes: argument 'height' must be length 2 or scalar' import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("Titanic/train.csv") top_five = df.head(5) print(top_five) column_no = df.columns print(column_no) female_count = len([p for p in df["Sex"] if p == 'female']) male_count = len([i for i in df["Sex"] if i == 'male']) have_survived= len([m for m in df["Survived"] if m == 1]) not_survived = len([n for n in df["Survived"] if n == 0]) plt.bar([0],female_count, color ='b') plt.bar([1],male_count,color = 'y') plt.xticks([0+0.2,1+0.2],['females','males']) plt.show() plt.bar([0],not_survived, color ='r') plt.bar([1],have_survived, color ='g') plt.xticks([0+0.2,1+0.2],['not_survived','have_survived']) plt.show() it works fine until here and I get two individual charts Instead i want one chart that displays bars for male and female and color code the bars based on survival. This does not seem to work N = 2 index = np.arange(N) bar_width = 0.35 plt.bar(index, have_survived, bar_width, color ='b') plt.bar(index + bar_width, not_survived, bar_width,color ='r',) plt.xticks([0+0.2,1+0.2],['females','males']) plt.legend() Thanks in advance!! Answer: How about replacing your second block of code (the one that returns a `ValueError`) with this bar_width = 0.35 tot_people_count = (female_count + male_count) * 1.0 plt.bar(0, female_count, bar_width, color ='b') plt.bar(1, male_count, bar_width, color ='y',) plt.bar(0, have_survived/tot_people_count*female_count, bar_width, color='r') plt.bar(1, have_survived/tot_people_count*male_count, bar_width, color='g') plt.xticks([0+0.2,1+0.2],['females','males']) plt.legend(['female deceased', 'male deceased', 'female survivors', 'male survivors'], loc='best') I get this bar graph as an output, [![enter image description here](http://i.stack.imgur.com/PiiNu.png)](http://i.stack.imgur.com/PiiNu.png) The reason for the error you get is that the `left` and `height` parameters of `plt.bar` must either have the same length as each other or one (or both) of them must be a scalar. That is why changing `index` in your code to the simple scalars `0` and `1` fixes the error.
How to pass Variable from Python to VBA Sub Question: I am trying to call a VBA sub from my Python code to convert all excel files in a specified folder from the xls to xlsm format. I can use the following code when I am not using a variable in the VBA and it works well. **Python Code:** import os import win32com.client xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1) xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal" xl.Application.Quit() # Comment this out if your excel script closes del xl **VBA Code:** Public Sub xlstoxlsmFinal() ' goes through all the sub folders of a specified folder and created an xlsm(macro enabled version) of any xls documents Dim fso, oFolder, oSubfolder, oFile, queue As Collection Set fso = CreateObject("Scripting.FileSystemObject") Set queue = New Collection Path = "C:\Users\Name\Documents\Monthly Reports\16.06 Reports\Agent Reports" queue.Add fso.GetFolder(Path) Do While queue.Count > 0 Set oFolder = queue(1) queue.Remove 1 'dequeue '...insert any folder processing code here... For Each oSubfolder In oFolder.SubFolders queue.Add oSubfolder 'enqueue Next oSubfolder For Each oFile In oFolder.Files If Right(oFile, 4) <> "xlsm" And Right(oFile, 3) <> "pdf" Then Workbooks.Open Filename:=oFile ActiveWorkbook.SaveAs Filename:=oFile & "m", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False ActiveWorkbook.Close End If Next oFile Loop However, I am unable to call the function when I try to pass a variable from python to VBA. Below is what I have tried so far. **Python code with variable:** import os import win32com.client Datev = """16.06 """ xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1) xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal(" + Datev + ")") ## xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function. xl.Application.Quit() # Comment this out if your excel script closes del xl **VBA code with Variable:** Public Sub xlstoxlsmFinal(Datev As String) ' goes through all the sub folders of a specified folder and created an xlsm(macro enabled version) of any xls documents Dim fso, oFolder, oSubfolder, oFile, queue As Collection Set fso = CreateObject("Scripting.FileSystemObject") Set queue = New Collection Path = "C:\Users\Name\Documents\Monthly Reports\" & Datev & "Reports\Agent Reports" queue.Add fso.GetFolder(Path) Do While queue.Count > 0 Set oFolder = queue(1) queue.Remove 1 'dequeue '...insert any folder processing code here... For Each oSubfolder In oFolder.SubFolders queue.Add oSubfolder 'enqueue Next oSubfolder For Each oFile In oFolder.Files If Right(oFile, 4) <> "xlsm" And Right(oFile, 3) <> "pdf" Then Workbooks.Open Filename:=oFile ActiveWorkbook.SaveAs Filename:=oFile & "m", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False ActiveWorkbook.Close End If Next oFile Loop When I run this in python I get the error message: pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'PERSONAL.XLSB!Module1.xlstoxlsmFinal(16.06 )'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None) Would anybody know how to succesfully pass a Python variable to a VBA sub? Thanks! Answer: Go to Macro Security under the developer tag and choose the Enable all macros option
Python How Can I Make a Counter To Cycle Through a Dictionary Inside a For Loop? Question: I have just started coding and don't know much about it. This is my bit of code that tries to cycle through numbers from the for loop to assign num1 and num2. Instead it make a new one called num0. WHAT?! import random numbers = {'num1': '', 'num2': ''} counter = 0 for i in range(0, 2): number = random.randint(0, 5) counter + 1 numbers['num' + str(counter)] = number; print(numbers) Answer: `counter + 1` isn't assigned to anything. You have to do `counter += 1`. `counter + 1` returns a new number but doesn't assign it to anything. `counter += 1` returns a new number _counter + 1_ and assigns it to the variable _counter_. It's the same as `counter = counter + 1`.
Python - Multiprocessing Pool Class: Can the Thread Function contain arguments? Question: I want to know if it is possible to pass arguments into the threading pool funktion? from multiprocessing.dummy import Pool as ThreadPool def mainFunc(): myArray = ["A", "B", "C"] pool = ThreadPool(8) pool.map(threadFunc, myArray) # how is it possible to give >>threadFunc<< another argument >>text1<< pool.close() pool.join() def threadFunc(text2): text1 = "Hello " # this should be given as a argument of the function print text1 + text2 mainFunc() This is a simple example of what i want to do.. How can I give text1 as a second argument to the threadFunc function? **Solved:** I solved the problem with a simple global accessible variable ... but it was only a solution for the problem I had right now ... it is a greater idea to use the `multiprocessing.Process` instead ... import sys from multiprocessing.dummy import Pool as ThreadPool this = sys.modules[__name__] def mainFunc(): myArray = ["A", "B", "C"] this.text1 = "Hello " pool = ThreadPool(8) pool.map(threadFunc, myArray) # how is it possible to give >>threadFunc<< another argument >>text1<< pool.close() pool.join() def threadFunc(text2): print this.text1 + text2 mainFunc() Answer: 1. The official python docs says > A parallel equivalent of the map() built-in function (it supports only one > iterable argument though). It blocks until the result is ready. Therefore it is impossible to add another argument, but you can always add text1 as the last element of your `myArray` and pop it out once you use it. 2. You can also use `multiprocessing.Process` other than pool. In this case you can add another argument easily. def f(name): print 'hello', name if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join()
Python : Most efficient way to get list of combinations? Question: I have a dictionary : diff_params = {0: [a, b], 1: [c, d]} Each key is a setting_name, and each value is a specific setting. I would like to be able to make a list like: [[a, c], [a, d], [b, c], [b, d]] I can't figure out how to do cleanly when I have 3 or 4 or 5 settings and each setting has several options. Answer: It seems that you are more specifically looking for [`itertools.product()`](https://docs.python.org/3/library/itertools.html#itertools.product) which can be used like this with [unpacking](https://docs.python.org/3/tutorial/controlflow.html#unpacking- argument-lists): from itertools import product result = product(*diff_params.values()) You may need to cast the result if you really want a list of list (surrounding `list` is useless if you are using Python 2 because `map()` return a list): result = list(map(list, result))
Google's Python Course wordcount.py Question: I am taking Google's Python Course, which uses Python 2.7. I am running 3.5.2. The script functions. This was one of my exercises. #!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class The main() below is already defined and complete. It calls print_words() and print_top() functions which you write. 1. For the --count flag, implement a print_words(filename) function that counts how often each word appears in the text and prints: word1 count1 word2 count2 ... Print the above list in order sorted by word (python will sort punctuation to come before letters -- that's fine). Store all the words as lowercase, so 'The' and 'the' count as the same word. 2. For the --topcount flag, implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common, and so on. Use str.split() (no arguments) to split on all whitespace. Workflow: don't build the whole program at once. Get it to an intermediate milestone and print your data structure and sys.exit(0). When that's working, try for the next milestone. Optional: define a helper function to avoid code duplication inside print_words() and print_top(). """ import sys # +++your code here+++ # Define print_words(filename) and print_top(filename) functions. # You could write a helper utility function that reads a fcd ile # and builds and returns a word/count dict for it. # Then print_words() and print_top() can just call the utility function. ### def word_count_dict(filename): """Returns a word/count dict for this filename.""" # Utility used by count() and Topcount(). word_count={} #Map each word to its count input_file=open(filename, 'r') for line in input_file: words=line.split() for word in words: word=word.lower() # Special case if we're seeing this word for the first time. if not word in word_count: word_count[word]=1 else: word_count[word]=word_count[word] + 1 input_file.close() # Not strictly required, but good form. return word_count def print_words(filename): """Prints one per line '<word> <count>' sorted by word for the given file.""" word_count=word_count_dict(filename) words=sorted(word_count.keys()) for word in words: print(word,word_count[word]) def get_count(word_count_tuple): """Returns the count from a dict word/count tuple -- used for custom sort.""" return word_count_tuple[1] def print_top(filename): """Prints the top count listing for the given file.""" word_count=word_count_dict(filename) # Each it is a (word, count) tuple. # Sort the so the big counts are first using key=get_count() to extract count. items=sorted(word_count.items(), key=get_count, reverse=True) # Print the first 20 for item in items[:20]: print(item[0], item[1]) # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def main(): if len(sys.argv) != 3: print('usage: ./wordcount.py {--count | --topcount} file') sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print ('unknown option: ' + option) sys.exit(1) if __name__ == '__main__': main() Here are my questions that course is not answering: 1. Where is says the following, I am unsure of what the `1` and `+1` mean. Does that mean `if the word is not in the list, add it to the list? (word_count[word]=1)`? And, I don't understand what each part of this means, where it says `word_count[word]=word_count[word] + 1`. if not word in word_count: word_count[word]=1 else: word_count[word]=word_count[word] + 1 2. When it says `word_count.keys()`, I am not sure what that does other than it calls to the key in the dictionary we defined and loaded keys and values into. I just want to understand why the `word_count.keys()` is there. words=sorted(word_count.keys()) 3. `word_count` is redefined in a couple of locations, and I would like to know why instead of creating a new variable name such as `word_count1`. word_count={} word_count=word_count_dict(filename) ...and also in places outlined in my 1st question. 4. Does `if len(sys.argv) != 3:` mean that if my arguments are not 3, or my characters not 3 (e.g. `sys.argv[1]`, `sys.argv[2]`, `sys.argv[3]`? Thank you for your help! Answer: 1. If `word` is not already in the dictionary, we create a new entry in the dictionary for it, and set the value to the number `1`, since we've so far just found 1 occurrence of the word. Otherwise, we retrieve the old value from the dictionary, use `+ 1` to add 1 to that value, and then put it back in the dictionary entry by assigning back to `word_count[word]`. This could also be written as: word_count[word] += 1 2. `word_count.keys()` returns a list of all the keys in the `word_count` dictionary. This is being used so that the contents of the dictionary can be printed in alphabetical order, by using `sort()`. If you just printed the dictionary the way it is, the words will be in some unpredictable order. 3. The variable is not being redefined. Variables are local to each function, so each `word_count` is a different variable. They just happen to use the same name in each function, because it's a good name for what the variable contains. 4. List indexes start a `0`, so `if (len(sys.argv) != 3` checks that you have `argv[0]`, `argv[1]`, and `argv[2]`. `argv[0]` always contains the script name, so this is checking that you gave 2 arguments to the script. The first argument must be either `--count` or `--topcount` and the second argument must be the filename to count the words in.
Iterate python list and sum equal items Question: Considering a endpoint on my backend, that returns the following response: class Arc_Edges_Data(Resource): def get(self): #Connect to databse conn = connectDB() cur = conn.cursor() #Perform query and return JSON data try: cur.execute("select json_build_object('source', start_location, 'target', end_location, 'frequency', 1) from trips") except: print("Error executing select") ArcList = list (i[0] for i in cur.fetchall()) return ArcList The frequency here is supposed to be always of 1 for each trip. So this `ArcList` originates a response like this: [ { "frequency": 1, "source": "c", "target": "c" }, { "frequency": 1, "source": "a", "target": "b" }, { "frequency": 1, "source": "a", "target": "b" }, ... ] How can I iterate this response and sum the items that have the same `source` and `target`? In this case, the resulting list would have only one pair source/target with "a" and "b", but the frequency would be 2, because of the sum. I know that for Javascript I could use something like `Array.reduce`, but I don't think it exists for Python. Answer: How about this? import collections data = [ { "frequency": 1, "source": "c", "target": "c", }, { "frequency": 1, "source": "a", "target": "b", }, { "frequency": 1, "source": "a", "target": "b", }, ] counter = collections.Counter() for datum in data: counter[(datum['source'], datum['target'])] += datum['frequency'] print(counter) # Output: # Counter({('a', 'b'): 2, ('c', 'c'): 1}) Oh, if you want to put the data back into the same format again, add this code: newdata = [{ 'source': k[0], 'target': k[1], 'frequency': v, } for k, v in counter.items()] print(newdata) # Output: # [{'frequency': 1, 'target': 'c', 'source': 'c'}, {'frequency': 2, 'target': 'b', 'source': 'a'}]
python regular expression error Question: I am trying do a pattern search and if match then set a bitarray on the counter value. runOutput = device[router].execute (cmd) runOutput = output.split('\n') print(runOutput) for this_line,counter in enumerate(runOutput): print(counter) if re.search(r'dev_router', this_line) : #want to use the counter to set something Getting the following error: > if re.search(r'dev_router', this_line) : > > 2016-07-15T16:27:13: %ERROR: File > "/auto/pysw/cel55/python/3.4.1/lib/python3.4/re.py", line 166, > > in search 2016-07-15T16:27:13: %-ERROR: return _compile(pattern, > flags).search(string) > > 2016-07-15T16:27:13: %-ERROR: TypeError: expected string or buffer Answer: You mixed up the arguments for [`enumerate()`](https://docs.python.org/2/library/functions.html#enumerate) \- first goes the index, then the item itself. Replace: for this_line,counter in enumerate(runOutput): with: for counter, this_line in enumerate(runOutput): * * * You are getting a `TypeError` in this case because `this_line` is an integer and [`re.search()`](https://docs.python.org/2/library/re.html#re.search) expects a string as a second argument. To demonstrate: >>> import re >>> >>> this_line = 0 >>> re.search(r'dev_router', this_line) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 146, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer * * * By the way, modern IDEs like [PyCharm](https://www.jetbrains.com/pycharm/) can detect this kind of problems statically: [![enter image description here](http://i.stack.imgur.com/q1uFa.png)](http://i.stack.imgur.com/q1uFa.png) (Python 3.5 is used for this screenshot)
How to solve ImportError on import cv2 without uninstalling Question: I've installed OpenCV3 from source and after running `import cv2` I get the error: ImportError: dlopen(/Users/Victor/.virtualenvs/cv/lib/python3.5/cv2.so, 2): Symbol not found: _PyCObject_Type Referenced from: /Users/Victor/.virtualenvs/cv/lib/python3.5/cv2.so Expected in: flat namespace in /Users/Victor/.virtualenvs/cv/lib/python3.5/cv2.so I really want to do this without reinstalling OpenCV, because I don't want to go through that again. If it helps at all I'm on my path is `PYTHONPATH="/usr/local/Cellar/python3/3.5.1/" ` Answer: The way I solved this was taking the cv2.cpython-35m-darwin.so file from the opencv/build/lib directory and putting it in place of cv2.so in my virtualenv folder
Not loading entire txt file into dictionary Question: Im a python noob to get that out of the way and I am writing these functions using the OOP method just a FYI. My save_roster function works correctly, it saves all of the dictionary player roster to my text file 'roster'. I confirmed this by looking in the text file making sure it is all there. Now when I go to load_roster function it only loads the first key and value and none of the rest and I cant figure out why. Any help as to how I can load the entire dictionary or what I am doing wrong would be greatly appreciated. def save_roster(player_roster): print("Saving data...") file = open("roster.txt", "wt") import csv w = csv.writer(open("roster.txt", "w")) for key, val in player_roster.items(): w.writerow([key, val]) print("Data saved.") file.close() def load_roster(player_roster): print("Loading data...") import csv file = open("roster.txt", "rt") for key, val in csv.reader(file): player_roster[key] = eval(val) file.close() print("Data Loaded Successfully.") return (player_roster) Answer: Your `return (player_roster)` statement is inside of the `for` loop, which means it only reads the first line before returning. You need to put the statement outside the loop like so: def load_roster(player_roster): print("Loading data...") import csv file = open("roster.txt", "rt") for key, val in csv.reader(file): player_roster[key] = eval(val) file.close() print("Data Loaded Successfully.") return (player_roster)
Logging to python file doesn't overwrite file when using the mode='w' argument to FileHandler Question: I have some code to set up a log in Python 2.7 (using the logging module): import os import logging logger=logging.getLogger('CopasiTools') logger.setLevel(logging.DEBUG) log_filename=os.path.join(os.path.dirname(copasi_file),os.path.split(copasi_file)[1][:-4]+'_log.log') handler=logging.FileHandler(log_filename,mode='w') formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) logger.debug('debugging message') This code works and I am getting the output, however I intend to use this log to do a lot of debugging so I want to overwrite the log file each time its run. In the [docs](https://docs.python.org/3/library/logging.handlers.html) say to use the `mode` keyword argument to the 'FileHandler`. It doesn't specify precisely *which* mode to use for overwrite file each time but I think a reasonable assumption would be`mode='w'`. This however doesn't work. Can anybody tell me why? Answer: I am not familiar with this to much, and I did not really see anything that stuck out in google. Have you tried just using: handler=logging.FileHandler(log_filename, 'w')
Removing trailing zero after decimal point in python Question: import math math.floor(85.21) returns `85.0` I want to save the number as a file name and I don't want to see the zero! I would like the output to be `85` Answer: Then you should consider _casting_ to `int` which does the same thing but without the trailing `.0` instead of `math.floor`: >>> int(85.21) 85 > I want to save the number as a file name Since OP will not be working with negative numbers, they could keep this, or use `int(math.floor(...))` that works also for negative numbers.
Can't import module with importlib.import_module Question: I want to use `importlib.import_module` to import modules dynamically. My code like this: import os import importlib os.chdir('D:\\Python27\\Lib\\bsddb') m = importlib.import_module('db') print dir(m) I can to this successfully in the Python console. But if I run these code in a file`C:\Users\Administrator\Desktop>python test.py`, it can't work: Traceback (most recent call last): File "test.py", line 5, in <module> m = importlib.import_module("db") File "D:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named db But if I copy the db.py file to the directory the same as the script file, it works. I can't figure out why. Answer: EDIT: I had tested the earlier code in console and it worked. However, I have modified the code again. I kept the `bsddb` module directly in `D drive` and changed the code again to: import os os.chdir("D:\\") import importlib m = importlib.import_module("bsddb.db") print len(dir(m)) print dir(m) This results in `319` and the `list of functions and variables` exponsed by the module. It seems you may need to import module using the `dot (.) notation` like above. Hope this works. Please accept the answer if it works for you.
Is it possible to insert import statements with jedi-vim? Question: I've just started looking at the Vim jedi plugin, and it seems pretty impressive. One feature of some of the Java IDEs I've used is the ability to automatically add required imports. Can Jedi do that? For example, if I enter a line such as arg1 = sys.argv[1] and then invoke some Jedi command, is it possible for the plugin to automatically insert an `import sys` line at the top of the source file (if sys is not already being imported)? I've looked through the Jedi help, and can't see anything like this - but it's possible I missed something. Alternatively, is there another Vim plugin that would do this? (It needs a certain level of understanding of Python syntax to get it right, which is why I looked to Jedi to be able to do it). Answer: Currently Jedi doesn't do refactoringing. This includes import additions. There's an issue for the whole subject: <https://github.com/davidhalter/jedi/issues/667>. It's not that easy to implement this command with good performance. However any help is appreciated. :)
Convert TKinter Into an Exe File Question: As I was creating a program using python (tkinter), I am unable to convert it into executable form (`.exe)`. My program uses several images, a bitmap icon and widgets. I tried `cx_freeze`. It compiles well and generates `exe` and other files but doesn't run. I tried `cx_freeze` with several setup codes but it displays the error related to those images (maybe it don't support images compilation) when I execute it. I tried searching for an answer, but the solution was related to those tkinter programs that uses only basic widgets but not images in it. So is there any way or method to convert the tkinter program (that uses images also) into exe file ? My script for `exe` is: import sys from cx_Freeze import setup, Executable sys.argv.append("build") filename = "program.py" base = None if sys.platform == "win32": base = "Win32GUI" setup( name = "Unick Locker", version = "2.0", description = "a GUI app that helps you securing your files and data with many functions", executables = [Executable(filename, base=base)]) Answer: I would highly recommend py2exe, I use it and it works flawlessly. This is a youtube video that explains how to use it. (i cant insert links as im on a mobile) <http://m.youtube.com/watch?v=VKQ1Ph81Gps> Any errors just ask, I use it quite enough to know.
PHP passthru: unable to get full response from python script Question: I'm trying to get data from Python script: import pymorphy2 import json import sys morph = pymorphy2.MorphAnalyzer() butyavka = morph.parse(sys.argv[1])[0] for item in butyavka.lexeme: print(item.word) PHP code: <?php chdir('C:\\Users\Michael-PC\AppData\Local\Programs\Python\Python35-32'); $out; passthru('python WordAnalizator.py "слово"', $out); echo($out); ?> If I use console, it make correct response, like: [![enter image description here](http://i.stack.imgur.com/S7T1o.png)](http://i.stack.imgur.com/S7T1o.png) But in PHP I have only first word: [![enter image description here](http://i.stack.imgur.com/IVrZD.png)](http://i.stack.imgur.com/IVrZD.png) Whats wrong? Answer: This is obvious encoding problem (Russian letters become unreadable). So, try to set (i.e. change default) encoding in the PHP code, e.g. add to header usage of Unicode: header('Content-Type: text/html; charset=utf-8'); If `charset=utf-8` does not help, try `charset=windows-1251` instead. **UPDATE:** Do not forget to save your file (PHP code in UTF encoding for utf-8, or ANSI for windows-1251)
Multilinear maps in python using numpy Question: In python I have a three dimensional array `T` with size `(n,n,n)`, and a 2-D array, with size `(n,k)`. In linear algebra, the multilinear map defined by `T` and applied to `W`, in code would be: X3 = np.zeros((k,k,k)) for i in xrange(k): for j in xrange(k): for t in xrange(k): for l in xrange(n): for m in xrange(n) for h in xrange(n): X3[i, j, t] += M3[l, m, h] * W[l, i] * W[m, j] * W[h, t] See <https://en.wikipedia.org/wiki/Multilinear_map> For a reference. This is very slow. I am wondering if there exist any alternative or any pre build function in numpy that can speed up the operations. Answer: Einstein summation convention? Use [`np.einsum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html)! X3 = np.einsum('lmh,li,mj,ht->ijt', M3, W, W, W) EDIT: Out of curiosity, I just ran some benchmarks comparing `np.einsum` to Divakar's approach. The difference is hugely against `np.einsum`! import numpy as np def approach1(a, b): x = np.einsum('lmh,li,mj,ht->ijt', a, b, b, b) def approach2(a, b): p1 = np.tensordot(b, a, axes=(0,0)) p2 = np.tensordot(p1, b, axes=(1,0)) x = np.tensordot(p2, b, axes=(1,0)) n = 100 k = 10 a = np.random.random((n, n, n)) b = np.random.random((n, k)) %timeit approach1(a, b) # => 1 loop, best of 3: 26 s per loop %timeit approach2(a, b) # => 100 loops, best of 3: 4.23 ms per loop There's some discussion about it in [this question](http://stackoverflow.com/questions/20149201/why-is-numpys-einsum- slower-than-numpys-built-in-functions). It all seems to come down to the generality that `np.einsum` tries to achieve -- at the cost of being able to offload computations to low-level linear algebra packages.
Should i do math in Django ORM or in Python Question: I work with Django and have big database with around 30.000 records. My job is to do some simple math with all of the records. Data in the database is related to 50 persons. I have to filter rows for each person and then to calculate the average value for each of the 10 columns. So i would have to filter the data for 50 times (because i have to calculate and present data for each of the 50 persons separately) and to do the math. I have done this task with just one line of code (that is looped over 50 times): qs = Mymodel.objects.filter(person=person).values() records[i] = qs.aggregate(Avg('question-1'),Avg('question-2'),...Avg('question-10')) # Heavy SQL operation but django debug toolbar says it takes around 6.6 seconds for this request to be done (with around 55 sql queries, which i expected). This is only one task and i will have to do additional 7-8 similar mathematical tasks, so the whole job could easily sum up to 400 - 500 sql queries. I am concerned about performance issues so i would like to know what would be better and faster approach - should i do the math directly in the database with row filtering and aggregate queries or it would be better to prefetch whole database table with 30.000 rows (but it is expected to grow in future with 30.000 rows per year) and to do the math in python? Answer: I don't know anything about django, but I do know SQL. I have an outline of a solution for you. 30,000 records isn't big; it's hardly a warmup. The reason your code is slow is that you're issuing one query per person. Your DBMS can produce multiple aggregations for _all_ persons much faster using the GROUP BY feature of SQL: select person, avg(question-1), avg(question-2) from tablename group by person The important rule is that every non-aggregate in the `select` set must appear in the `group by` set. If all your aggregates are about `person` and all come from the same table, you need only a single query. I bet it will take longer to process the results than it will take the DBMS to produce them.
Python script to give input to exe Question: I am able to open cmd.exe using script import subprocess subprocess.call("C:\Windows\System32\cmd.exe",shell=True) But I am unable to send input command to cmd.exe open. I want to achieve something like below mentioned using script 1) script give input command like `python` to cmd.exe open [![enter image description here](http://i.stack.imgur.com/FH3MJ.png)](http://i.stack.imgur.com/FH3MJ.png) 2) After that script give input command like `print "hello"` to python prompt comes [![enter image description here](http://i.stack.imgur.com/DvteW.png)](http://i.stack.imgur.com/DvteW.png) Answer: Why not use Python to create a batch file that prints what you want, then execute that batch file? You could either return immediately or keep the command interpreter open: it depends on the command switches you use to run the batch file.
Python : bad handshake error on get request when executed on windows but not linux Question: I'm wrote a python script to download the content of a website and it is working perfectly fine when i execute it on a linux machine, but not on windows (and it needs to be executed on windows). Here is the code generating the error : import requests c = requests.Session() url = 'https://ted.jeancoutu.com/action/login' c.get(url) Here is the error message i get when i execute the code on a windows machine: Traceback (most recent call last): File "C:\Python34\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py", line 348, in ssl_wrap_socket cnx.do_handshake() File "C:\Python34\lib\site-packages\OpenSSL\SSL.py", line 1443, in do_handshake self._raise_ssl_error(self._ssl, result) File "C:\Python34\lib\site-packages\OpenSSL\SSL.py", line 1191, in _raise_ssl_error _raise_current_error() File "C:\Python34\lib\site-packages\OpenSSL\_util.py", line 48, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'SSL23_GET_SERVER_HELLO', 'sslv3 alert handshake failure')] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 578, in urlopen chunked=chunked) File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 351, in _make_request self._validate_conn(conn) File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 814, in _validate_conn conn.connect() File "C:\Python34\lib\site-packages\requests\packages\urllib3\connection.py", line 289, in connect ssl_version=resolved_ssl_version) File "C:\Python34\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py", line 355, in ssl_wrap_socket raise ssl.SSLError('bad handshake: %r' % e) ssl.SSLError: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'sslv3 alert handshake failure')],)",) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\requests\adapters.py", line 403, in send timeout=timeout File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 604, in urlopen raise SSLError(e) requests.packages.urllib3.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'sslv3 alert handshake failure')],)",) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python34\lib\site-packages\requests\sessions.py", line 487, in get return self.request('GET', url, **kwargs) File "C:\Python34\lib\site-packages\requests\sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "C:\Python34\lib\site-packages\requests\sessions.py", line 585, in send r = adapter.send(request, **kwargs) File "C:\Python34\lib\site-packages\requests\adapters.py", line 477, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'sslv3 alert handshake failure')],)",) I couldn't find a solution to this problem. I tried many suggestions i found online but nothing worked. I installed pyOpenSSL, ndg-httpsclient and pyasn1 with no result. I also upgraded ssl but still nothing. Thank you for your suggestions Answer: The site ted.jeancoutu.com only supports RC4-SHA and RC4-MD5 ciphers (see [SSLLabs report](https://www.ssllabs.com/ssltest/analyze.html?d=ted.jeancoutu.com). RC4 ciphers are considered insecure and therefore got removed from the default cipher set in requests in [version 2.5.2 in 02/2015](https://pypi.python.org/pypi/requests/2.5.2). You are probably using an older version of requests on Linux so it still works, but it fails with the newer version on Windows. See <http://stackoverflow.com/a/32651967/3081018> for how to work around the problem by enabling the insecure cipher.
Problems updating digital clock widget in PyQt4 - calling slot and signal Question: Ok so this is an edited version of my previous post. I am trying to place a digital clock onto a home window. I am having difficulty updating the value. I saw a tutorial [1](http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?key=QLCDNumberDigitalClock&index=409) that called a method with @pyqtSlot() in a different class but because I am working in the main window class, I was not able to call this and the clock did not appear at all. The following code below brings up the current time but the clock is not updated: from PyQt4.QtGui import * from PyQt4.QtCore import * import sys class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50,50,500,300) self.home() def home(self): lcdNumber = QLCDNumber(self) timer = QTimer() lcdNumber.setDigitCount(8) self.showTime(lcdNumber) lcdNumber.connect(timer,SIGNAL("timeout()"),lcdNumber,SLOT("showTime()")) timer.start(1000) self.show() @pyqtSlot() def showTime(self,lcdNumber): lcdNumber.display(QTime.currentTime().toString("hh:mm:ss")) def run(): app=QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run() Answer: Ok so I found a work around using some code I found [here](http://thecodeinn.blogspot.co.uk/2013/07/tutorial-pyqt-digital- clock.html) but I am still unsure how to get the signal and slot functions operational. from PyQt4.QtGui import * from PyQt4.QtCore import * import sys from time import strftime class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50,50,700,300) self.home() def home(self): self.timer =QTimer(self) self.timer.timeout.connect(self.Time) self.timer.start(1000) self.lcd = QLCDNumber(self) self.lcd.display(strftime("%H"+":"+"%M"+":"+"%S")) self.lcd.setDigitCount(8) self.show() def Time(self): self.lcd.display(strftime("%H"+":"+"%M"+":"+"%S")) def run(): app=QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run()
Running Flask app from cli gives "no module named flaskr" Question: I am trying to run the example flaskr app using the Flask 0.11 cli. However, I get `ImportError: no module named flaskr`. I have set `FLASK_APP` and `import flaskr` works in a Python shell. How do I run the flaskr app with the cli? export FLASK_APP=flaskr flask run # gives ImportError Answer: If you have not installed your app in your virtualenv, add `.py` at the end of the module name. export FLASK_APP=flaskr.py
Django Will Not Pull CSS Static File (404 Error) Even Though File Paths Look Correct Question: When I load my local site I cannot get the CSS files to load. I'm running Django 1.9 and python 3.4.2. Here is my structure: apps/ app1/ app2/ etc. clients/ media/ #css, js, images, etc. static/ #static files templates/ #html templates __init__.py manage.py settings.py etc. In my settings.py file I have: STATIC_ROOT = os.path.join(BASE_DIR, 'clients', 'static') STATIC_URL = 'clients/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'clients', 'media'), ] MEDIA_ROOT = os.path.join(PROJECT_PATH, 'clients', 'media') And my html template that is calling the css files is as so: {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/primary_stylesheet.css' %}" /> I continue to get a 404 error that says it can't find the css file in:/clients/static/css/primary_stylesheet.css In my settings.py file I have printed out my STATICFILES_DIRS and STATIC_ROOT and they both lead directly where they should. I've read through the documentation and tried multiple variations of DIRS and ROOT and don't understand why the css file is not pulling correctly - even "collectstatic" is collecting correctly. I greatly appreciate any help and wisdom someone else has to give. Thank you! Answer: If you are running your server with `python ./manage.py runserver`, you need to set urls for both `static` and `media` files, check here: <https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static- files-during-development> When I am starting a new project, I generally set my `urls.py` like this: from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin url_patterns = [ url(r'^admin/', admin.site.urls), # your url patterns go here ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This requires you to set `STATIC_ROOT`, `STATIC_URL`, `MEDIA_ROOT` and `MEDIA_URL` in your `settings.py`: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_files'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
What does !r do in str() and repr()? Question: According to the [Python 2.7.12 documentation](https://docs.python.org/2/tutorial/inputoutput.html#fancier- output-formatting): > `!s` (apply `str()`) and `!r` (apply `repr()`) can be used to convert the > value before it is formatted. > > > >>> import math > >>> print 'The value of PI is approximately {}.'.format(math.pi) > The value of PI is approximately 3.14159265359. > >>> print 'The value of PI is approximately {!r}.'.format(math.pi) > The value of PI is approximately 3.141592653589793. > Interestingly, the converted value is the output of `repr()`, rather than `str()`. >>> str(math.pi) '3.14159265359' >>> repr(math.pi) '3.141592653589793' So what does "convert the value" mean here? Making it less human-readable? Answer: In order to format something _in_ a string, a string representation of that something must first be created. "convert the value" is basically talking about how the string representation is to be constructed. In python, there are two fairly natural choices to get a string representation of something ... `str` and `repr`. `str` is generally a little more human friendly, `repr` is generally more precise. Perhaps the [official documentation](https://docs.python.org/3/reference/datamodel.html#object.__repr__) is the best place to go looking for the difference: > `object.__repr__(self)` > > > * Called by the `repr()` built-in function to compute the “official” > string representation of an object. If at all possible, this should look > like a valid Python expression that could be used to recreate an object with > the same value (given an appropriate environment). If this is not possible, > a string of the form `<...some useful description...>` should be returned. > The return value must be a string object. If a class defines `__repr__()` > but not `__str__()`, then `__repr__()` is also used when an “informal” > string representation of instances of that class is required. > > * This is typically used for debugging, so it is important that the > representation is information-rich and unambiguous. > > > > `object.__str__(self)` > > > * Called by str(object) and the built-in functions format() and print() to > compute the “informal” or nicely printable string representation of an > object. The return value must be a string object. > > * This method differs from `object.__repr__()` in that there is no > expectation that `__str__()` return a valid Python expression: a more > convenient or concise representation can be used. > > * The default implementation defined by the built-in type object calls > `object.__repr__()`. > > In `str.format`, `!s` chooses to use `str` to format the object whereas `!r` chooses `repr` to format the value. The difference can easily be seen with strings (as `repr` for a string will include outer quotes).: >>> 'foo {}'.format('bar') 'foo bar' >>> 'foo {!r}'.format('bar') "foo 'bar'" What the difference between these two methods really depends critically on the objects being formatted. For many objects (e.g. those that don't override the `__str__` method), there will be no difference in the formatted output.
Generate unique non repeating pairs in a list in O(n) Question: How do we generate unique non repeating pairs such that (x,y) = (y,x) are not repeated. Say we have a list `[3,6,9]`. Then, answer is `(3, 6) (3, 9) (6, 9)` If the list is `[3,6]`. Then answer is `(3,6)` This can be done using 2 for loops, but we want to be preferably done in `O(n)` (using max one loop) Is there a pythonic way of doing this? Answer: The Pythonic way to do it is to use the standard library generator (<https://docs.python.org/2.7/library/itertools.html#itertools.combinations>): from itertools import combinations for comb in combinations([3,6,9], 2): print(comb) As the docs say, the number of combinations is `n! / (2 * (n-2)!)`, which I guess is `O(n^2)`. So it can't be done in O(n) time.
(fields.E331) Field specifies a many-to-many relation through model 'models_groups', which has not been installed Question: > ERRORS: login.Freelancer.groups: (fields.E331) Field specifies a many-to- > many relation through model 'login.Freelancer_groups', which has not been > installed. login.Freelancer.user_permissions: (fields.E331) Field specifies > a many-to-many relation through model 'login.Freelancer_user_permissions', > which has not been installed. message_board.Post.author: (fields.E301) Field > defines a relation with the model 'auth.User', which has been swapped out. > HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. **models.py** from django.contrib.auth.tests.custom_user import CustomUserManager from django.db import models from django.utils import timezone from django.utils.http import urlquote from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from crm import settings class FreelancerManager(BaseUserManager): def create_user(self, name, skills, password=None): if not name: raise ValueError('Users must have a unique name ') user = self.model( name=self.name, skills=skills, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, skills, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( name, password=password, skills=skills, ) user.is_admin = True user.save(using=self._db) return user class Freelancer(AbstractBaseUser, PermissionsMixin): name = models.CharField(verbose_name='name', max_length=20, unique=True, ) field_of_interest = models.CharField(max_length=200) skills = models.TextField() experience = models.TextField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = FreelancerManager() USERNAME_FIELD = 'name' REQUIRED_FIELDS = ['skills'] class Meta: db_table = 'auth_user' verbose_name = _('user') verbose_name_plural = _('users') def get_absolute_url(self): return "/users/%s/" % urlquote(self.name) def get_short_name(self): return self.name def get_full_name(self): return self.name def __str__(self): # __unicode__ on Python 2 return self.name def has_perm(self, perm, obj=None): # "Does the user have a specific permission?" # # Simplest possible answer: Yes, always return True def has_module_perms(self, applabel): # "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): # "Is the user a member of staff?" # "Simplest possible answer: All admins are staf" return self.is_admin **admin.py** from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import Freelancer class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = Freelancer fields = ('name', 'skills') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = Freelancer fields = ('name', 'password', 'skills','is_admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] class FreelancerAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('name', 'skills', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('name', 'password')}), ('Personal info', {'fields': ('skills',)}), ('Permissions', {'fields': ('is_admin',)}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('name', 'skills', 'password1', 'password2')} ), ) search_fields = ('name',) ordering = ('name',) filter_horizontal = () # Now register the new UserAdmin... admin.site.register(Freelancer, FreelancerAdmin) admin.site.unregister(Group) **settings.py** import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&_j_tz#06jbpo5shiy62x$qxa*t68_n@q4@$pee4(a()5vyt#9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'auth.User' AUTH_USER_MODEL = 'login.Freelancer' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', 'message_board' ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crm.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') > _And i have one more named app message_board which models.py is here_ **models.py of message_board App** class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Answer: Its already clear from the error that there is no `auth.User` and you are pointing `author` to it. Change that. Either use `Freelance` or `settings.AUTH_USER_MODEL` from login.models import Freelancer class Post(models.Model): author = models.ForeignKey('settings.AUTH_USER_MODEL', on_delete=models.CASCADE)
Ordering a GROUP BY query Question: I'm using sqlite3 database in my very simple program written in python. Table I have a problem with contains three columns: id, software_version, place Now I would like to count the frequency of a particular software version, so I created this query: SELECT software_ssh, COUNT (software_ssh) FROM simple_table group by software_ssh As a result I have got: program_version_1.1, 2 program_version_1.2, 2 program_version_1.3, 20 program_version_2.1, 7 Unfortunately the output is not sorted by frequency. How can I fix the query to make it work better? Answer: Add an `ORDER BY` on the `COUNT` results; give that result an alias: SELECT software_ssh, COUNT (software_ssh) as freq FROM simple_table GROUP BY software_ssh ORDER BY freq Use `ORDER BY freq DESC` if you need the rows ordered from most frequent to least. Demo: >>> from pprint import pprint >>> c.execute('SELECT software_ssh, COUNT (software_ssh) FROM simple_table group by software_ssh') <sqlite3.Cursor object at 0x102034490> >>> pprint(list(c)) [(u'program_version_1.1', 2), (u'program_version_1.2', 2), (u'program_version_1.3', 20), (u'program_version_2.1', 7)] >>> c.execute(''' ... SELECT ... software_ssh, ... COUNT (software_ssh) as freq ... FROM simple_table ... GROUP BY software_ssh ... ORDER BY freq ... ''') <sqlite3.Cursor object at 0x102034490> >>> pprint(list(c)) [(u'program_version_1.1', 2), (u'program_version_1.2', 2), (u'program_version_2.1', 7), (u'program_version_1.3', 20)]
Discrepancy between formatted numeric value and rounded value Question: I found this weird behavior using python and numpy: print('%10.3f' %0.4975) returns 0.497, while numpy.round(0.4975,3) returns 0.498 as expected. With other similar numbers I always get the print statement to deliver the correctly rounded value (for example: 0.5975 --> 0.598). Why is this? I'm using python 3.4 and numpy 1.9.2 on windows 7. Answer: In double precision, 0.4975 is 8962163258467287/18014398509481984 which is slightly **less** than the real number 0.4975. Hence, Python's `round` function rounds it to 0.497. In contrast, 0.5975 becomes 5381801554707743/9007199254740992 which is slightly **more** than the real number 0.5975. So we get the expected 0.598 when rounding. Why does NumPy round 0.4975 to 0.498? Its algorithm is a bit different: to round to N digits, it multiplies the given number by the Nth power of 10, rounds to nearest integer (preferring even), and then divides by 10^N. In the process of multiplication by powers of 10, the direction of truncation changes; often one will get exactly a half-integer as a result. (Example: 0.15*10 = 1.5 which is exactly 3/2, although 0.15 is not exactly 3/20). Simply put, `np.round(x, 3)` is the same as `round(x*1000)/1000`. You can check that both return 0.498 when applied to x = 0.4975. Indeed, in double precision 0.4975*1000 is _exactly_ 497.5 (that is, 995/2), and the direction of rounding is then picked correctly. Here is a comparison of how 0.05, 0.15, 0.25, ... are rounded: ### Python >>> [round((2*i+1)/20, 1) for i in range(10)] [0.1, 0.1, 0.2, 0.3, 0.5, 0.6, 0.7, 0.8, 0.8, 0.9] ### NumPy >>> import numpy as np >>> np.around([(2*i+1)/20 for i in range(10)], 1) array([ 0. , 0.2, 0.2, 0.4, 0.4, 0.6, 0.6, 0.8, 0.8, 1. ]) Here NumPy output is what one'd expect without thinking of binary representation. However, `np.around([(2*i+1)/200 for i in range(100)], 2)` shows that NumPy's algorithm won't always match the expectation, either: there are two numbers (0.55 and 0.57) with an odd digit at the end. The problem is that, for example, 0.545*100 is not exactly 109/2; rather, it is 7670193115365377/140737488355328.
Unable to login to Github or Facebook or any such site using Python requests? Question: I am using the following code: import requests s = requests.session() login_data = dict(login='username', password='my_password') s.post('https://github.com/login/', data=login_data) r = s.get('https://github.com/') print(r.text) The content printed is from the login page and not the page after that. I have also tried: import requests url = 'http://facebook.com' values = {'email': 'username', 'pass': 'my_password'} r = requests.post(url, data=values) print(r.text) Both times, the data printed is from the login page and not the p[age after that what am I doing wrong? Answer: The `requests` module isn't a web browser. Although you _can_ do some pretty cool stuff with it there are situations where it isn't an appropriate tool. Many websites use security on their forms to reduce abuse. A popular strategy is to use a [cross-site request forgery token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Prevention). This is a hidden field whose value is generated server-side and then included in the form. When the form gets submitted the server can make sure that the hidden input is present and valid. This is one strategy for preventing submission of the form from somewhere else. If you look at the source for GitHub's login page you'll see a hidden input inside the form named `authenticity_token` which is probably used for exactly that. If you want to play with `requests`' POST feature you can use something like <https://httpbin.org/>. Here, you should be able to POST a message and get an appropriate response. For interacting with GitHub or Facebook you should use a [library](https://developer.github.com/libraries/) or a [published API](https://developer.github.com/v3/).
Can someone explain this bitwise array-wrap-around expression? Question: I've been researching on the Diamond-square algorithm and I came across [this website](http://www.bluh.org/code-the-diamond-square-algorithm/) which pointed me to the source code of Notch's Minicraft, and does a conversion of the algorithm as was implemented by Notch. For the most part I understand the algorithm, but I can get my head around the specific expression found in these two functions: private double sample(int x, int y) { return values[ (x & (w - 1)) + (y & (h - 1)) * w ]; } private void setSample(int x, int y, double value) { values[ (x & (w - 1)) + (y & (h - 1)) * w ] = value; } I do understand `x + y * w`, but not `(x & (w - 1)) + (y & (h - 1)) * w`, and the article doesn't explain this besides stating that it serves to wrap- around. I'm coding in python, but I don't think there's any difference between Java's bitwise `&` and python's, so I fiddled with it a bit but I still can't get it. One of the things I did was a loop that simulates varying `x` and `y` values and feeds them to that calculation: import random w = h = 257 # 2^8 + 1 for i in xrange(10): x = int(random.uniform(0, 1) *255) y = int(random.uniform(0, 1) *255) print x, y, '|', (x & (w-1)) + (y & (h-1)) *w # I used a less readable right-aligning version of the above to display the output: # print str( x ).rjust(3), str( y ).rjust(3), '|', str( (x & (w-1)) + (y & (h-1)) * w ).rjust(3) Output: 112 213 | 0 181 117 | 0 1 105 | 0 216 223 | 0 170 185 | 0 158 32 | 0 124 225 | 0 62 153 | 0 90 147 | 0 196 69 | 0 Unless I'm doing something fundamentally wrong here, it always gives me zero, unless `x` and/or `y` are equal to `w-1`, in which case: 256 15 | 256 21 256 | 65792 256 256 | 66048 In the actual algorithm the value of `x` and `y` seems to always be (if I understand correctly) somewhere between `0` and `halfStep`, where `halfStep = stepSize/2`, `stepSize = featureSise` which seems to be (in Minicraft's code) always hardcoded as `16` or `32`. So according to my current understanding that expression would always evaluate to `0`. So I'm confused. I don't see how this is useful or how it actually works in practice... I know it works, but it seems like sorcery... I understand how the bitwise `&` works, but that doesn't seem to help. Answer: `w` and `h` must be powers of 2 (and represent the local bounds for `x` and `y`, respectively). Then, `w-1` and `h-1` are sequences of ones. One for each bit of information which could possibly contribute to a value lower than `w` and `h` (and still be `>= 0`), respectively. When you now evaluate the bit-wise _and_ (`&`), e.g. `x & (w-1)`, this will actually yield `x % w`, where `%` is the modulo operation in python, for `x >= 0`. Thus, `x` is mapped to `x` if `w > x >= 0` and otherwise `x` is truncated (zeroing higher bits), such that `w > x >= 0` is satisfied. The same applies to `y` and `h`. Consequently, these logical operations are nothing more than evaluating _mod_ on a bit-level. For your code: Set `w=h=256` and everything should work out.
Automated filling of web form from a list in Python using Selenium Question: This is the Selenium code in Python "sel.py" :- from selenium import webdriver driver = webdriver.Chrome() driver.get('http://127.0.0.1:8000/employee/register/') employes = ['1', '2016-1-1', 'Tarun', 'Gupta', 'Male', '1995-12-7', 'Indian', 'Hinduism', 'General', 'O+', 'Single', '1122334455', 'diploma', 'Btech', 'HMRITM','GGSIPU', '2016', 'distinction', '95', 'full time', 'Web Developer', 'Comp Science', '2017', '95000', '8700925621', '44087062', '[email protected]', 'Vasant Vihar', 'East delhi', 'Delhi', '110056'] input = [] input = driver.find_elements_by_xpath('//*[@id]') i = 0 for xpaths in input: xpaths.send_keys(employes[i]) print(employee[i]) i += 1 driver.find_element_by_xpath('//*[@id="Submit"]').click() This is the Registration Form:- [![enter image description here](http://i.stack.imgur.com/DW68o.png)](http://i.stack.imgur.com/DW68o.png) This is the HTML code but here the input tags are python variables as made this in Django :- <form action="/employee/register/" method="post">{% csrf_token %} <div class="col-md-12 col-lg-12"> <div id="col1" class="col-md-2 col-lg-2"></div> <div id="col2" class="col-md-4 col-lg-4"> <h4 class="text-center">Application Details</h4> <fieldset class="form-group"> <label for="Applicationno">Application No.</label> <!--<input type="number" class="form-control" id="Applicationno" name="Applicationno" placeholder="Application No.">--> {{appform.ApplicationNo}} </fieldset> <fieldset class="form-group"> <label for="applyon">Apply On</label> <!--<input type="date" class="form-control" id="applyon" name="applyon">--> {{appform.ApplyOn}} </fieldset> </div> <div id="col3" class="col-md-6 col-lg-6"> <h4 class="text-center">Personal Details</h4> <div class="form-inline"> <!--<select id="title1" name="title1" class="form-control">--> <!--<option selected>Title</option>--> <!--<option>Mr.</option>--> <!--<option>Mrs.</option>--> <!--<option>Ms.</option>--> <!--</select>--> <label for="firstName1"></label> <!--<input id="firstName1" class="form-control" name="firstName1" type="text" placeholder="First name" >--> {{empform.FirstName}} <label for="lastName1"></label> <!--<input id="lastName1" class="form-control" name="lastName1" type="text" placeholder="Last name" >--> {{empform.LastName}} </div> <br> <div class="form-inline"> <label>Gender: {{empform.Gender}}</label> <!--<label for="Male" class="radio-inline">--> <!--<input id="Male" name="Male" type="radio">Male</label>--> <!--<label for="Female" class="radio-inline">--> <!--<input id="Female" name="Female" type="radio">Female</label>--> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label for="BirthDate"> Birth Date: <!--<input id="BirthDate" name="BirthDate" type="date" class="form-control">--> {{empform.BirthDate}} </label> </div> <br> <div class="form-inline"> <label for="Nationality"> Nationality: <!--<input id="Nationality" class="form-control" name="Nationality" type="text" placeholder="Nationality" >--> {{empform.Nationality}} </label> &nbsp; &nbsp; &nbsp; <label for="Religion"> Religion: <!--<input id="Religion" class="form-control" name="Religion" type="text" placeholder="Religion" >--> {{empform.Religion}} </label> </div> <br> <div class="form-inline"> <label class="Category" for="Category"> {{empform.Category}} <!--Category:--> <!--<select id="Category" name="Category" class="form-control">--> <!--<option selected="selected">GEN</option>--> <!--<option>OBC</option>--> <!--<option>SC</option>--> <!--<option>ST</option>--> <!--</select>--> </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; <label for="BloodGroup"> Blood Group: <!--<input id="BloodGroup" class="form-control" name="BloodGroup" type="text" placeholder="Blood Group" >--> {{empform.BloodGroup}} </label> </div> <br> <div class="form-inline"> <label class="MaritalStatus" for="MaritalStatus"> {{empform.MaritalStatus}} <!--Marital Status:--> <!--<select id="MaritalStatus" name="MaritalStatus" class="form-control">--> <!--<option selected="selected">Single</option>--> <!--<option>Married</option>--> <!--</select>--> </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label class="AdhaarCardNo" for="AdhaarCardNo"> Adhaar Card No.: <!--<input type="number" class="form-control" id="AdhaarCardNo" name="AdhaarCardNo" placeholder="Adhaar card No.">--> {{empform.AdhaarCardNo}} </label> </div> </div> </div> <div class="col-md-12 col-lg-12" style="margin-top:5px;"> <div class="col-md-5 col-lg-5"> <div class="row" style="padding:5px 5px 5px 5px;"> <div id="col4" class="col-md-12 col-lg-12"> <h4 class="text-center">Education & Qualification Details</h4> <div class="form-inline"> <label class="Level" for="Level"> Level: {{eduform.Level}} <!--<select id="Level" name="Level" class="form-control">--> <!--<option selected="selected">Diploma</option>--> <!--<option>Bachelors</option>--> <!--<option>Masters</option>--> <!--<option>Professional</option>--> <!--</select>--> </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label class="Degree"> Degree: <!--<input type="text" id="Degree" name="Degree" placeholder="Degree" class="form-control">--> {{eduform.Degree}} </label> </div> <br> <div class="form-inline"> <label class="College"> College: <!--<input type="text" id="College" name="College" placeholder="College" style="width:350px;" class="form-control">--> {{eduform.College}} </label> </div> <br> <div class="form-inline"> <label class="University"> University: <!--<input type="text" id="University" name="University" placeholder="University" style="width:350px;" class="form-control">--> {{eduform.University}} </label> </div> <br> <div class="form-inline"> <label class="YearOfQualification"> Year Of Qualification: <!--<input type="date" id="YearOfQualification" name="YearOfQualification" class="form-control">--> {{eduform.YearOfPassing}} </label> </div> <br> <div class="form-inline"> <label class="Class" for="Class"> Class: {{eduform.Class}} <!--<select id="Class" name="Class" class="form-control">--> <!--<option selected="selected">Distinction</option>--> <!--<option>First</option>--> <!--<option>Second</option>--> <!--<option>Third</option>--> <!--</select>--> </label> &nbsp; <label class="Percentage"> Percentage %: <!--<input type="number" id="Percentage" name="Percentage" placeholder="Percentage" class="form-control">--> {{eduform.Percentage}} </label> </div> </div> </div> <div class="row" style="padding:5px 5px 5px 5px;"> <div id="col5" class="col-md-12 col-lg-12"> <h4 class="text-center">Official Details</h4> <!--<label class="EmpCode">--> <!--Emp Code:--> <!--<input type="number" id="EmpCode" name="EmpCode" placeholder="Emp Code" class="form-control">--> <!--</label>--> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label class="EmpType" for="EmpType"> Emp Type: {{offform.EmpType}} <!--<select id="EmpType" name="EmpType" class="form-control">--> <!--<option selected="selected">Full Time</option>--> <!--<option>Part Time</option>--> <!--</select>--> </label> <br><br> <label class="Designation"> Designation: <!--<input type="text" id="Designation" name="Designation" placeholder="Designation" class="form-control">--> {{offform.Designation}} </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label class="Department"> Department: <!--<input type="text" id="Department" name="Department" placeholder="Department" class="form-control">--> {{offform.Department}} </label> <br><br> <label class="JoiningOn"> Joining On: <!--<input type="date" id="JoiningOn" name="JoiningOn" class="form-control">--> {{offform.JoiningOn}} </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label class="Salary"> Salary: <!--<input type="number" id="Salary" name="Salary" class="form-control">--> {{offform.Salary}} </label> </div> </div> </div> <div class="col-md-7 col-lg-7"> <div class="row" style="padding:5px 5px 5px 5px;"> <div id="col6" class="col-md-12 col-lg-12"> <h4 class="text-center">Contact Details</h4> <div class="form-inline"> <label class="Mobile"> Mobile: <!--<input type="number" id="Mobile" name="Mobile" placeholder="Mobile" class="form-control">--> {{contform.MobileNo}} </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; <label class="PhoneNo" for="PhoneNo"> Phone No.: <!--<input type="number" id="PhoneNo" name="PhoneNo" placeholder="Phone No." class="form-control">--> {{contform.PhoneNo}} </label> </div> <br><br> <div class="form-inline"> <label class="Email" for="Email"> Email: <!--<input type="email" id="Email" name="Email" placeholder="Email" class="form-control">--> {{contform.EmailId}} </label> </div> <br><br> <label class="Address" for="Address"> Address: <!--<textarea id="Address" name="Address" placeholder="Address" rows="5" cols="70" class="form-control"></textarea>--> {{contform.AddressLine}} </label> <br><br> <div class="form-inline"> <label class="City" for="City"> City: <!--<input type="text" id="City" name="City" placeholder="City" class="form-control">--> {{contform.City}} </label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label class="State"> State: <!--<input type="text" id="State" name="State" placeholder="State" class="form-control">--> {{contform.State}} </label> </div> <br> <div class="form-inline"> <label class="PinCode"> PinCode: <!--<input type="number" id="PinCode" name="PinCode" placeholder="PinCode" class="form-control">--> {{contform.PinCode}} </label> </div> </div> </div> <div class="row" style="padding:5px 5px 5px 5px;"> <div class="col-md-12 col-lg-12" style="margin:60px 10px 10px 10px;"> <div class="form-inline text-right"> <input type="submit" id="Submit" name="Submit" class="btn btn-success btn-lg" > <input type="submit" id="Clear" name="Clear" value="Clear" class="btn btn-warning btn-lg" style="margin-left:20px;"> <input type="submit" id="Cancel" name="Cancel" value="Cancel" class="btn btn-danger btn-lg" style="margin-left:20px;"> </div> </div> </div> </div> </div> </form> I want to fill all the WebElements in form from the text in the list "employes" in "sel.py" file , but i am getting this error :- [![enter image description here](http://i.stack.imgur.com/aD1uj.png)](http://i.stack.imgur.com/aD1uj.png) I don't know how to fix this error , any help is appreciated ! thanks in advance. Answer: from selenium import webdriver from selenium.webdriver.support.select import Select driver = webdriver.Chrome() driver.get('http://127.0.0.1:8000/employee/register/') employees = { 'id_ApplicationNo':'1', 'id_ApplyOn':'2016-1-1', 'id_FirstName':'Tarun', 'id_LastName':'Gupta', 'id_Gender':'Male', 'id_BirthDate':'1995-12-7', 'id_Nationality':'Indian', 'id_Religion':'Hinduism', 'id_Category':'General', 'id_BloodGroup':'O+', 'id_MaritalStatus':'single', 'id_AdhaarCardNo':'1122334455', 'id_Level':'diploma', 'id_Degree':'Btech', 'id_College':'HMRITM', 'id_University':'GGSIPU', 'id_YearOfPassing':'2016', 'id_Class':'first', 'id_Percentage':'95', 'id_EmpType':'part time', 'id_Designation':'Web Developer', 'id_Department':'Comp Science', 'id_JoiningOn':'2017-3-3', 'id_Salary':'95000', 'id_MobileNo':'8700925621', 'id_PhoneNo':'44087062', 'id_EmailId':'[email protected]', 'id_AddressLine':'Vasant Vihar', 'id_City':'East delhi', 'id_State':'Delhi', 'id_PinCode':'110056' } for key, value in employees.items(): element = driver.find_element_by_id(key) if element.tag_name == "select": select = Select(element) select.select_by_visible_text(value) else: element.send_keys(value) driver.find_element_by_id('Submit').click()
'u' at the beginning of output (Sqlite, Python) Question: I'm really confused about the sqlite part, where I print out my database, because I keep getting an 'u' at the beginning of every line, it doesn't have ' ' around though, which I assume is not accepted as a string? This only happens on this one programme (I tested it on other as well). I checked the code many times (it doesn't appear in the database when I open it with 'SQLite database browser') So this is the code: #!/usr/bin/python import sqlite3 import os def list_n_convert(way): if way == 'mov':#movie search output = os.popen("find '/home/fugo/' -name '*.mp4' -printf '%f\n'").read() word = '' lyst = [] for letter in output: if letter != '\n': word += str(letter) else: lyst.append(word) word = '' return lyst #Loop to create entries def entry_maker(lyst, column): for count in range(len(lyst)): cur.execute("INSERT OR IGNORE INTO myliltable ({}) VALUES (?)".format(column), (lyst[count],)) con.commit() if __name__ == '__main__': #necessities for start-up of sql-lite con = sqlite3.connect('movie.db') cur = con.cursor() #Create a table, if it's non-existent cur.execute('CREATE TABLE IF NOT EXISTS myliltable (name TEXT PRIMARY KEY, cover TEXT, genre TEXT)') entry_maker(list_n_convert('mov'), 'name') cur.execute('SELECT * FROM myliltable') for row in cur.fetchall(): print(row) #print each row in a line <--- 'ERROR' happens here cur.close() con.close() This is what the output looks like: (u'Umbra.mp4', None, None) (u'xd.mp4', None, None) (u'Nice.mp4', None, None) (u'Haha.mp4', None, None) I'll explain what the programme does, maybe it helps to find the error: The first function 'list_n_convert' searches on my home folder for any files with the ending '.mp4' and then converts the result of the search into strings and adds them on a list. The second one does entries into the database for each element in the list (each mp4 file). At the end I call the functions and let each row get printed out; this is where the error happens. Answer: The u' is basically syntax for 'this is unicode'. Use `str()` to get a string. See: [Unicode Strings on the python docs](https://docs.python.org/2.7/tutorial/introduction.html#unicode-strings)
add labels to sklearn k-means Question: I am trying to use kmeans in python. data = [[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]] Each of this data have a label. Example: [1,2,3,4,5] -> Fiat1 [1,0,3,2,4] -> Fiat2 [4,3,234,5,5] -> Mercedes [23,4,5,1,4] -> Opel [23,5,2,3,5] -> bmw kmeans = KMeans(init='k-means++', n_clusters=3, n_init=10) kmeans.fit(data) My objective is after I run the KMeans, I want to obtain the labels of each cluster. A fake example: Cluster 1: Fiat1, Fiat2 Cluster 2: Mercedes Cluster 3: bmw, Opel How can I do that ? Answer: ### Code from sklearn.cluster import KMeans import numpy as np data = np.array([[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]]) labels = np.array(['Fiat1', 'Fiat2', 'Mercedes', 'Opel', 'BMW']) N_CLUSTERS = 3 kmeans = KMeans(init='k-means++', n_clusters=N_CLUSTERS, n_init=10) kmeans.fit(data) pred_classes = kmeans.predict(data) for cluster in range(N_CLUSTERS): print('cluster: ', cluster) print(labels[np.where(pred_classes == cluster)]) ### Output: cluster: 0 ['Opel' 'BMW'] cluster: 1 ['Mercedes'] cluster: 2 ['Fiat1' 'Fiat2']
Expand macros & retrieve macro values Question: I am trying to use **libclang** python bindings to parse my c++ source files. I am unable to get the value of macro or expand a macro. Here is my sample c++ code #define FOO 6001 #define EXPAND_MACR \ int \ foo = 61 int main() { EXPAND_MACR; cout << foo; return 0; } This is my python script import sys import clang.cindex def visit(node): if node.kind in (clang.cindex.CursorKind.MACRO_INSTANTIATION, clang.cindex.CursorKind.MACRO_DEFINITION): print 'Found %s Type %s DATA %s Extent %s [line=%s, col=%s]' % (node.displayname, node.kind, node.data, node.extent, node.location.line, node.location.column) for c in node.get_children(): visit(c) if __name__ == '__main__': index = clang.cindex.Index.create() tu = index.parse(sys.argv[1], options=clang.cindex.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD) print 'Translation unit:', tu.spelling visit(tu.cursor) This is info I get back from clang: Found FOO Type CursorKind.MACRO_DEFINITION DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950> Extent <SourceRange start <SourceLocation file 'sample.cpp', line 4, column 9>, end <SourceLocation file 'sample.cpp', line 4, column 17>> [line=4, col=9] Found EXPAND_MACR Type CursorKind.MACRO_DEFINITION DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950> Extent <SourceRange start <SourceLocation file 'sample.cpp', line 6, column 9>, end <SourceLocation file 'sample.cpp', line 8, column 11>> [line=6, col=9] Found EXPAND_MACR Type CursorKind.MACRO_INSTANTIATION DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950> Extent <SourceRange start <SourceLocation file 'sample.cpp', line 12, column 2>, end <SourceLocation file 'sample.cpp', line 12, column 13>> [line=12, col=2] If you observe my python script, **node.data** gives out DATA <clang.cindex.c_void_p_Array_3 object at 0x10b86d950> I can read **Extent** data returned by clang & then parse the file from **start** to **end** positions to get the value. I want to know if, there exists a better way to get macro values? I want to get the value of macro(**6001** in the sample) directly(without using Extent). How can I get that? Additionally for **EXPAND_MACR** is want to get `int foo = 61` I have already seen these post: [Link-1](http://stackoverflow.com/questions/10113586/how-can-i-parse-macros- in-c-code-using-clang-as-the-parser-and-python-as-the) & [Link-2](http://clang-developers.42468.n3.nabble.com/Extracting-macro- information-using-libclang-the-C-Interface-to-Clang-td4042648.html). Any help will be highly appreciated Answer: No, line-by-line expansion using the extents seems to be the only way to extract the (expanded macros). I suspect that the problem is that by the time libclang sees your code, the macros have already been removed by the preprocessor - the nodes you're seeing in the AST are more like annotations rather than true nodes. #define FOO 6001 #define EXPAND_MACR \ int \ foo = 61 int main() { EXPAND_MACR; return 0; } Is really the AST TRANSLATION_UNIT sample.cpp +-- ... *some nodes removed for brevity* +--MACRO_DEFINITION FOO +--MACRO_DEFINITION EXPAND_MACR +--MACRO_INSTANTIATION EXPAND_MACR +--FUNCTION_DECL main +--COMPOUND_STMT +--DECL_STMT | +--VAR_DECL foo | +--INTEGER_LITERAL +--RETURN_STMT +--INTEGER_LITERAL This is equivalent to running the preprocessor only (and telling it to give you a listing of all the preprocessor directives). You can see something similar by running: clang -E -Wp,-dD src.cc Which gives: # 1 "<command line>" 1 # 1 "<built-in>" 2 # 1 "src.cc" 2 #define FOO 6001 #define EXPAND_MACR int foo = 61 int main() { int foo = 61; return 0; }
List of tuple like independent data access Question: I have some paired objects linked together in a same level priority basis. They can be grouped as fixed length tuples, all have to be in a list. Some objects type are unique, other can be common). For example, in this data structure i have an object, an object name (both unique), an object type and a bool (both common). [(Banana, myBanana, fruit, True), (Water, myWater, liquid, True), (Car, myCar, vehicle, False)] Then I need to find an easy way to access to the other data knowing the unique objects. If I pick up "Banana" I'd get (myBanana, fruit, True), if I pick "myCar" I get (Car, vehicle, False). I don't need to access by the common values, they're just there to show that the data structure can have common values and they might change. The order might not be important, I used a list for simplicity. Obviously, I can create 2 dictionaries using one of the unique objects each as keys, but I could actually have a more complex situation with more unique objects types and some related data (e.g. the last bool) might change, which would force me to change all the other dictionaries. One idea could be create a class which contains separate lists for each data type, use index() for a selected "column" and return a tuple of the other list[index] values. Is there a better/faster/nicer/more elegant and pythonic way to do this? Answer: I tried the solution in making a class. It does work and I believe it's fairly pythonic. It uses two dicts: one where each unique is a key for the commons and one dict containing the keys. Since no one has given an answer I thought I might as well share it. class Foo(object): # Didn't know how to name it. def __init__(self): self.value = dict() self.key = dict() def add(self, keys, values): for key in keys: self.value[key] = values # Each key reference the values. self.key[key] = keys # Each key reference to all the keys that reference the values. def remove(self, key): keys = self.key[key] # Get all the keys that reference the same values as key. for key in keys: del self.key[key] # Delete all keys associated with the key. del self.value[key] # Delete all values associated with the key. def __getitem__(self, key): return self.value[key] def __setitem__(self, key, value): keys = self.key[key] # Get all the keys that reference the same values as key. for key in keys: self.value[key] = value # Make all the keys reference the new value. def __repr__(self): output = [] temp = [] for key in self.key: if key not in temp: temp.extend(self.key[key]) output.append("{}: {}".format(self.key[key], self.value[key])) return "{" + ", ".join(output) + "}" I tried it out and it does work as expected. a = Foo() a.add(["Car", "My_car"], [0, True]) print(a["Car"]) # OUTPUT: [0, True] print(a["My_car"]) # OUTPUT: [0, True] a["Car"][0] = -1 print(a["Car"]) # OUTPUT: [-1, True] print(a["My_car"]) # OUTPUT: [-1, True] a["Car"][1] = False print(a["Car"]) # OUTPUT: [-1, False] print(a["My_car"]) # OUTPUT: [-1, False] a["Car"] = [100, None] print(a["Car"]) # OUTPUT: [100, None] print(a["My_car"]) # OUTPUT: [100, None] a["My_car"][0] = -1 print(a["My_car"]) # OUTPUT: [-1, None] print(a["Car"]) # OUTPUT: [-1, None] a["My_car"][1] = False print(a["My_car"]) # OUTPUT: [-1, False] print(a["Car"]) # OUTPUT: [-1, False] a["My_car"] = [100, None] print(a["My_car"]) # OUTPUT: [100, None] print(a["Car"]) # OUTPUT: [100, None] print(a) # OUTPUT: {['Car', 'My_car']: [100, None]} a.remove("My_car") print(a) # OUTPUT: {} a.add(["Car", "My_car"], [0, True]) print(a) # OUTPUT: {['Car', 'My_car']: [0, True]} a.remove("Car") print(a) # OUTPUT: {} It works for multiple keys and multiple values as well: a.add(["Car", "My_car"], [0, True]) a.add(["Boat", "My_boat", "Sea"], [1, False, "testing"]) a.add(["Soap", "My_soap", "Bath", "Water"], [3]) print(a["Car"]) # OUTPUT: [0, True] print(a["My_boat"]) # OUTPUT: [1, False, 'testing'] print(a["Soap"]) # OUTPUT: [3] print(a["Water"]) # OUTPUT: [3] The problem is that it'll might use up some memory when it grows in size.
Error installing quandl with pip on ubuntu 14.04 Question: here is the error that I keep getting. I keep trying to install the quandl modulen and keep running into this same error. I have tried looking into some other questions but they do not provide any good solutions. I tried looking through the errors but I already have openssl installed. Collecting quandl Downloading Quandl-3.0.1-py2.py3-none-any.whl Collecting pyOpenSSL (from quandl) Downloading pyOpenSSL-16.0.0-py2.py3-none-any.whl (45kB) 100% |################################| 51kB 1.9MB/s Requirement already satisfied (use --upgrade to upgrade): six in /usr/local/lib/python3.4/dist-packages (from quandl) Requirement already satisfied (use --upgrade to upgrade): pandas>=0.14 in /usr/local/lib/python3.4/dist-packages (from quandl) Requirement already satisfied (use --upgrade to upgrade): numpy>=1.8 in /usr/local/lib/python3.4/dist-packages (from quandl) Collecting more-itertools (from quandl) Downloading more-itertools-2.2.tar.gz Collecting ndg-httpsclient (from quandl) Downloading ndg_httpsclient-0.4.1.tar.gz Requirement already satisfied (use --upgrade to upgrade): python-dateutil in /usr/local/lib/python3.4/dist-packages (from quandl) Requirement already satisfied (use --upgrade to upgrade): requests>=2.7.0 in /usr/local/lib/python3.4/dist-packages (from quandl) Requirement already satisfied (use --upgrade to upgrade): pyasn1 in /usr/local/lib/python3.4/dist-packages (from quandl) Collecting inflection>=0.3.1 (from quandl) Downloading inflection-0.3.1.tar.gz Collecting cryptography>=1.3 (from pyOpenSSL->quandl) Downloading cryptography-1.4.tar.gz (399kB) 100% |################################| 409kB 906kB/s Requirement already satisfied (use --upgrade to upgrade): pytz>=2011k in /usr/local/lib/python3.4/dist-packages (from pandas>=0.14->quandl) Requirement already satisfied (use --upgrade to upgrade): idna>=2.0 in /usr/local/lib/python3.4/dist-packages (from cryptography>=1.3->pyOpenSSL->quandl) Requirement already satisfied (use --upgrade to upgrade): setuptools>=11.3 in /usr/local/lib/python3.4/dist-packages (from cryptography>=1.3->pyOpenSSL->quandl) Requirement already satisfied (use --upgrade to upgrade): cffi>=1.4.1 in /usr/local/lib/python3.4/dist-packages (from cryptography>=1.3->pyOpenSSL->quandl) Requirement already satisfied (use --upgrade to upgrade): pycparser in /usr/local/lib/python3.4/dist-packages (from cffi>=1.4.1->cryptography>=1.3->pyOpenSSL->quandl) Installing collected packages: cryptography, pyOpenSSL, more-itertools, ndg-httpsclient, inflection, quandl Running setup.py install for cryptography ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-wm_qxhdb/cryptography/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-hyncpopk-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-3.4 creating build/lib.linux-x86_64-3.4/cryptography copying src/cryptography/utils.py -> build/lib.linux-x86_64-3.4/cryptography copying src/cryptography/fernet.py -> build/lib.linux-x86_64-3.4/cryptography copying src/cryptography/exceptions.py -> build/lib.linux-x86_64-3.4/cryptography copying src/cryptography/__init__.py -> build/lib.linux-x86_64-3.4/cryptography copying src/cryptography/__about__.py -> build/lib.linux-x86_64-3.4/cryptography creating build/lib.linux-x86_64-3.4/cryptography/x509 copying src/cryptography/x509/oid.py -> build/lib.linux-x86_64-3.4/cryptography/x509 copying src/cryptography/x509/name.py -> build/lib.linux-x86_64-3.4/cryptography/x509 copying src/cryptography/x509/general_name.py -> build/lib.linux-x86_64-3.4/cryptography/x509 copying src/cryptography/x509/extensions.py -> build/lib.linux-x86_64-3.4/cryptography/x509 copying src/cryptography/x509/base.py -> build/lib.linux-x86_64-3.4/cryptography/x509 copying src/cryptography/x509/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/x509 creating build/lib.linux-x86_64-3.4/cryptography/hazmat copying src/cryptography/hazmat/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat creating build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/serialization.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/padding.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/keywrap.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/hmac.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/hashes.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/constant_time.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/cmac.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives creating build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings copying src/cryptography/hazmat/bindings/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings creating build/lib.linux-x86_64-3.4/cryptography/hazmat/backends copying src/cryptography/hazmat/backends/multibackend.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends copying src/cryptography/hazmat/backends/interfaces.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends copying src/cryptography/hazmat/backends/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends creating build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/utils.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/totp.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/hotp.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/twofactor creating build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/x963kdf.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/pbkdf2.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/kbkdf.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/hkdf.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/concatkdf.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/kdf creating build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/interfaces copying src/cryptography/hazmat/primitives/interfaces/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/interfaces creating build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/modes.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/base.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/algorithms.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/ciphers creating build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/utils.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/rsa.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/padding.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/ec.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/dsa.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/dh.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/primitives/asymmetric creating build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings/openssl copying src/cryptography/hazmat/bindings/openssl/binding.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings/openssl copying src/cryptography/hazmat/bindings/openssl/_conditional.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings/openssl copying src/cryptography/hazmat/bindings/openssl/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings/openssl creating build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings/commoncrypto copying src/cryptography/hazmat/bindings/commoncrypto/binding.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings/commoncrypto copying src/cryptography/hazmat/bindings/commoncrypto/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/bindings/commoncrypto creating build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/x509.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/utils.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/rsa.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/hmac.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/hashes.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/encode_asn1.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/ec.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/dsa.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/decode_asn1.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/cmac.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/ciphers.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/backend.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/openssl creating build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/hmac.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/hashes.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/ciphers.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/backend.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/__init__.py -> build/lib.linux-x86_64-3.4/cryptography/hazmat/backends/commoncrypto running egg_info writing requirements to src/cryptography.egg-info/requires.txt writing src/cryptography.egg-info/PKG-INFO writing top-level names to src/cryptography.egg-info/top_level.txt writing dependency_links to src/cryptography.egg-info/dependency_links.txt writing entry points to src/cryptography.egg-info/entry_points.txt warning: manifest_maker: standard file '-c' not found reading manifest file 'src/cryptography.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' warning: no previously-included files matching '*' found under directory 'vectors' writing manifest file 'src/cryptography.egg-info/SOURCES.txt' running build_ext generating cffi module 'build/temp.linux-x86_64-3.4/_padding.c' creating build/temp.linux-x86_64-3.4 generating cffi module 'build/temp.linux-x86_64-3.4/_constant_time.c' generating cffi module 'build/temp.linux-x86_64-3.4/_openssl.c' building '_openssl' extension creating build/temp.linux-x86_64-3.4/build creating build/temp.linux-x86_64-3.4/build/temp.linux-x86_64-3.4 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.4m -c build/temp.linux-x86_64-3.4/_openssl.c -o build/temp.linux-x86_64-3.4/build/temp.linux-x86_64-3.4/_openssl.o build/temp.linux-x86_64-3.4/_openssl.c:429:30: fatal error: openssl/opensslv.h: No such file or directory #include <openssl/opensslv.h> ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-wm_qxhdb/cryptography/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-hyncpopk-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-wm_qxhdb/cryptography/ I am new to ubuntu and linux so I dont know if there is something vital that I am missing Answer: I think you are just missing openssl sudo apt-get install libssl-dev I don't think pip can get that dependency
Python Error Calling Function Within Function Question: I am a novice in python. I just extended the Hello World program: import sys def first(n): print "Hi Man"+" Huuuuuu" if len(sys.argv)>1: print sys.argv[1] def second(): print "Huuuuuuuuuuu" first(7) if __name__=='__main__': second() I get the error: File "first.py", line 11 first(7) ^ IndentationError: unexpected indent I read [What to do with "Unexpected indent" in python?](http://stackoverflow.com/questions/1016814/what-to-do-with- unexpected-indent-in-python), but I can't find the error. I ran with python -t command: python -t first.py first.py: inconsistent use of tabs and spaces in indentation File "first.py", line 12 first(7) ^ IndentationError: unexpected indent Thanks for your help. Answer: Python generally works by the indentation instead of curly braces block. In your case check the blank spaces in front of `first(7)` statement are matching with the blank spaces with the first `print` statement. Check if you have putted the tab character in one of the statement. generally we put the 4 blank spaces in front of the statement.
How to omitt newlines in Phython? Question: I know..... one way to omitting new lines in Python with concatenation: a = 'strin' b = 2 print str(b)+a how many ways we can this be done? Answer: I believe, you are using Python2.x. You can try following: 1. use a trailing comma. print a, # no new line will be printed 2. use print function from future from __future__ import print_function print(a,end='') # no new line will be printed And for Python3.x following will do. `Do not need to import print function` print(a,end='')
Environmental variables from .env file not available during local migrations in django, heroku Question: I have been developing on Heroku, using the `config` variables to store sensitive and other environmental variables. While developing locally, I have mirrored these variables in the `.env` file. What I am finding now is the variables from the `.env` file do not load during migrations. They ARE loading while running the local web server with `heroku local`, but NOT loading for migrations. This was not a problem while my local app was still using the default sqlite3 database, because the sqlite default DB was "hard-coded" in the settings file. However recently I want to use my local Postgresql DB for local dev. OK so I added the `DATABASE_URL` variable to my `.env` file. I cannot get my local app to migrate to the DB. I have found out that this is because the `.env` file contents are not added to the `os.environ` mapping duing migrations. To test, I added a test variable to the `.env` file: TEST="teeeest" Then in `settings.py`: import os import dj_database_url if "TEST" not in os.environ: raise Exception("No .env vars found.") I tried `python manage.py migrate`: > File "/Users/apple/heroku/b/b/settings.py", line 16, in raise Exception("No > .env vars found.") Exception: No .env vars found. However I can run `heroku local` and there is no error. I have also done further testing to ensure that the `.env` variables ARE available during `heroku local`. For various reason I want to set my local DB connection string in the `.env` file, but doesn't seem possible at the moment. Is this the correct behavior for django on heroku? `.env` file variables are only accessible when you run the server, and not for migrations? Answer: `manage.py` doesn't know anything about your .env file. You'll need to run the command under something that does; either [Foreman](https://github.com/ddollar/foreman), which is what Heroku itself uses, or [Honcho](https://github.com/nickstenning/honcho), which is a Python implementation.
Django nose giving "ImportError: cannot import name setup"? Question: Django-nose installed in virtualenv is giving "ImportError: cannot import name setup" in runner.py when I run default server. On doing traceback I get this: File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/core/management/base.py", line 222, in run_from_argv self.execute(*args, **options.__dict__) File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/core/management/base.py", line 250, in execute translation.activate('en-us') File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 90, in activate return _trans.activate(language) File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 183, in activate _active.value = translation(language) File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 172, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 154, in _fetch app = import_module(appname) File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django_nose/__init__.py", line 5, in <module> from django_nose.runner import BasicNoseRunner, NoseTestSuiteRunner File "/home/sid/.virtualenvs/workbench/local/lib/python2.7/site-packages/django_nose/runner.py", line 19, in <module> from django import setup ImportError: cannot import name setup ` I found this about [django.setup()](https://docs.djangoproject.com/en/1.9/topics/settings/#calling- django-setup-is-required-for-standalone-django-usage) on django documentation, though most of problems like this have pythonic issues rather than with Django Answer: Django 1.5 hasn't been supported for quite a while now, and django-nose has dropped compatibility in their more recent versions. `django.setup()` was added in Django 1.7. You need to upgrade Django or downgrade django-nose to a compatible version. I would recommend to upgrade Django to a [supported version](https://www.djangoproject.com/download/#supported-versions) so you'll receive bugfixes and security updates.
python pandas merge/vlookup tables Question: I was writing the Python code below to merge two tables, which could be done in Excel using Vlookup, but wanted to automate this process for a larger data set. However, it seems the output data is too big and contains all columns from both tables. I just wanted to use the second table, df_pos to lookup some columns. Would you take a look if my code is efficient or feasible to perform this task? Thank you! def weighted(mwa="mwa.csv",mwa2="mwa.csv",output="WeightedMWA.csv"): df=pd.read_csv(mwa, thousands=",") df['Keyword']=df['Keyword'].replace('+','') df_pos=pd.read_csv("mwa.csv", thousands=",") df_pos['Keyword']=df_pos['Keyword'].replace('+','') sumImp=df_pos['Impr.'].sum() sumPos=df_pos.groupby(by=['Keyword'])['Avg. Pos.'].sum() df_pos['WeightedPos']=sumPos/sumImp mergedDF=pd.merge(left=df, right=df_pos, how="left", left_on="Keyword",right_on="Keyword") mergedDF.to_csv(output) Answer: You didn't provide us with enough information. You are outputting the merged dataframe but you have not told up which columns are necessary in the output. Ideally, you'd want to keep only the columns that are needed in the output plus the columns needed for the merge. You can limit the columns that you import via the `read_csv` function and its `usecols` parameter. The [documentation](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.read_csv.html) says: > > usecols : array-like, default None > Return a subset of the columns. All elements in this array must > either > be positional (i.e. integer indices into the document columns) or > strings > that correspond to column names provided either by the user in > `names` or > inferred from the document header row(s). For example, a valid > `usecols` > parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Using this > parameter > results in much faster parsing time and lower memory usage. >
Python SQLAlchemy - Error IM001 reflecting table Question: first of all, sorry if I'm not writing in the right place or I'm not providing enough info about the issue. Using SQL Alchemy, with pyodbc. I'm trying to reflect a table. When I try to do that, i get this message > DBAPIError: (pyodbc.Error) ('IM001', '[IM001] [unixODBC][Driver > Manager]Driver does not support this function (0) (SQLNumParams)') [SQL: > u'SELECT [COLUMNS_1].[TABLE_SCHEMA], [COLUMNS_1].[TABLE_NAME], > [COLUMNS_1].[COLUMN_NAME], [COLUMNS_1].[IS_NULLABLE], > [COLUMNS_1].[DATA_TYPE], [COLUMNS_1].[ORDINAL_POSITION], > [COLUMNS_1].[CHARACTER_MAXIMUM_LENGTH], [COLUMNS_1].[NUMERIC_PRECISION], > [COLUMNS_1].[NUMERIC_SCALE], [COLUMNS_1].[COLUMN_DEFAULT], > [COLUMNS_1].[COLLATION_NAME] \nFROM [INFORMATION_SCHEMA].[COLUMNS] AS > [COLUMNS_1] \nWHERE [COLUMNS_1].[TABLE_NAME] = CAST(? AS NVARCHAR(max)) AND > [COLUMNS_1].[TABLE_SCHEMA] = CAST(? AS NVARCHAR(max)) ORDER BY > [COLUMNS_1].[ORDINAL_POSITION]'] [parameters: ('Order', 'dbo')] Here is the code.. >>> from sqlalchemy.orm.session import Session >>> from sqlalchemy.schema import MetaData >>> import sqlalchemy as SQLA >>> eng = SQLA.create_engine(connection_string) >>> session = Session(eng.connect()) >>> class DB: ... pass ... >>> db = DB() >>> db.session = session >>> db.engine = eng >>> db.metadata = MetaData(bind=db.engine, schema='dbo') >>> db.session.execute("select * from information_schema.columns") <sqlalchemy.engine.result.ResultProxy object at 0x7f76eb770890> >>> t = SQLA.Table('Order', db.metadata, autoload=True, extend_existing=True, autoload_with=db.engine) >>> Traceback (most recent call last): ... File "<stdin>", line 1, in <module> ... See the error above The code is running on a RHEL 7.x with unixODBC, Microsoft SQL Server Native clinet 11 for Linux. Python 2.7.11 Here are the pip requirements * click (6.6) db-connection-maker (1.2.0) * Flask (0.11.1) * itsdangerous (0.24) * Jinja2 (2.8) * MarkupSafe (0.23) * pip (8.0.2) * pyaml (15.8.2) * pyodbc (3.0.10) * PyYAML (3.11) * setuptools (19.6.2) * simplejson (3.8.2) * SQLAlchemy (1.0.14) * Werkzeug (0.11.10) Note that the same code works without issues on windows. Answer: I do a try with **pymmsql** and it works without issues. The problem was on _pyodbc_ , maybe it still have some problems with **ms sql odbc drivers on Linux**.
Python, best way to find out location of a color Question: A black and white image showing a smile face inside a frame. [![enter image description here](http://i.stack.imgur.com/sbqcu.jpg)](http://i.stack.imgur.com/sbqcu.jpg) What I want is to find out the location of most right point of the smile face. (in this case, color black shall be at around “184,91” of the image) By using below I hope to list the colors in the image, then see what can look for further. from PIL import Image im = Image.open("face.jpg") print im.convert('RGB').getcolors() # or print im.getcolors() However it returns “None”, and I am stuck. How can I get the most right point of the face? Thanks. Answer: As an indirect way, maybe I can: 1\. remove the frame 2\. trim the white What’s left is the core image itself. The dimension of the image can tell the coordinates if the core image is of regular pattern. from PIL import Image img = Image.open("c:\\smile.jpg") img2 = img.crop((30, 26, 218, 165)) # remove the frame img2.save("c:\\cropped-smile.jpg") [Trim whitespace using PIL](http://stackoverflow.com/questions/10615901/trim- whitespace-using-pil) teaches how to remove the circle white portions. def trim(im): bg = Image.new(im.mode, im.size, im.getpixel((0,0))) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: return im.crop(bbox) im = Image.open("c:\\cropped-smile.jpg") im = trim(im) im.save("c:\\final-smile.jpg") now to get the dimension of the core image. im = Image.open("c:\\final-sbqcu.jpg") w, h = im.size I got it as 131,132. So 131,66 shall be the most right point of the image.
Convert python timezone aware datetime string to utc time Question: I have a Python datetime string that is timezone aware and need to convert it to UTC timestamp. '2016-07-15T10:00:00-06:00' Most of the SO links talks about getting the current datetime in UTC but not on converting the given datetime to UTC. Answer: Hi this was a bit tricky, but here is my, probably far from perfect, answer: [IN] import datetime import pytz date_str = '2016-07-15T10:00:00-06:00' # Have to get rid of that bothersome final colon for %z to work datetime_object = datetime.datetime.strptime(date_str[:-3] + date_str[-2:], '%Y-%m-%dT%H:%M:%S%z') datetime_object.astimezone(pytz.utc) [OUT] datetime.datetime(2016, 7, 15, 16, 0, tzinfo=<UTC>)
Check if Python (3.4) Tkinter Entry is Full Question: I am using a standard tkinter entry to input a directory path. When the user presses enter - if the physical length of the string exceeds that of the entry, I want the program to modify the displayed text to ...[end of directory]. I have the logistics of this figured out but as of yet **I have no accurate way to test whether the entry box is full, or how full** Things I have tried: * Using 'PIL.ImageFont.truetype("font.otp",fontsize).size' - cannot calculate the point at which to cut the directory * Simply using the length of the string against the length of the entry- inaccurate as the font I am using (which I don't want to change if possible) varies in length with each character Another compromise behaviour which I tried was to make the entry "look" at the start of the path. I tried inserting at, selecting at and moving the cursor to position 0 but none of these worked Any suggestions? Answer: You can use [`xview`](http://effbot.org/tkinterbook/entry.htm#Tkinter.Entry.xview-method) method of `Entry`. `xview` return the visible part of the text displayed in the entry. You can use it to interactively create a text that fit the entry. Here is a quick and dirty proof of concept from tkinter import * root = Tk() v = StringVar(root) e = Entry(root,textvariable=v) e.pack(fill=BOTH) v.set('abcdefghijklmnopqrstuvwxyz0123456789') new_s = None def check_length(): global new_s original_s = v.get() def shorten(): global new_s e.xview(0) if e.xview()[1] != 1.0: new_s = new_s[:-4] + '...' v.set(new_s) print("new_s: " + new_s) e.xview(0) e.after(0,shorten) print(e.xview()[1]) if e.xview() != (0.0,1.0): new_s = original_s + '...' shorten() b = Button(root,text="hop",command=check_length) b.pack() e.mainloop()
Error converting GUI to standalone executable using Py2exe Question: I am using `py2exe` to convert my program with multiple GUIs to a standalone executable. I used PyQt to create the GUIs. The main script I run instantiates the main UI, which contains buttons, tabs, etc. that can open sub-UIs. The main script is `main_ui.py`. I followed the tutorial on how to use `py2exe`, so I have the following `setup.py`: from distutils.core import setup import py2exe setup(windows=['main_ui.py']) Then, in the CMD: `> python setup.py py2exe`. I tried creating a practice exe with a simple script and everything worked. However, I got an error when I tried creating the exe from `main_ui.py`. Here is the output: L:\internal\(path)>python setup.py py2exe running py2exe creating L:\internal\(path)\build creating L:\internal\(path)\build\bdist.win32 creating L:\internal\(path)\build\bdist.win32\winexe creating L:\internal\(path)\build\bdist.win32\winexe\collect-2.7 creating L:\internal\(path)\build\bdist.win32\winexe\bundle-2.7 creating L:\internal\(path)\build\bdist.win32\winexe\temp creating L:\internal\(path)\dist *** searching for required modules *** error: compiling 'C:\Python27\lib\site-packages\PyQt4\uic\port_v3\proxy_base.py' failed SyntaxError: invalid syntax <proxy_base.py, line 26> Here's `proxy_base.py`: from PyQt4.uic.Compiler.proxy_metaclass import ProxyMetaclass class ProxyBase(metaclass=ProxyMetaclass): """ A base class for proxies using Python v3 syntax for setting the meta-class. """ This came with PyQt4; does anyone know what's going on? Is this the right way to make my program into an executable? Answer: I have encountered the same problem. There is very probably a better way, but removing the folder "PyQt4\uic\port_v3" solves the issue. (see <http://python.6.x6.nabble.com/PyQt-4-7-and-py2exe-error-td1922933.html>)
How to parse only specific tag values Question: I'm new to Python, and i've written some code for parsing data from the [ESPN site](http://espn.go.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2)! #importing packages/modules from bs4 import BeautifulSoup import pandas as pd import urllib #additional data for scraping url = 'http://espn.go.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/' #scraping the site page = urllib.request.urlopen(url + str(2)).read() soup = BeautifulSoup(page) #the header of the table table_header = [ td.get_text() for td in soup.find_all('td')[:20] ] table_header[-1] = 'SH A' table_header[-2] = 'SH G' table_header[-3] = 'PP A' table_header[-4] = 'PP G' table_header.remove('') table_header.remove('PP') table_header.remove('SH') #the data for table #print(player_names = [ a.get_text() for a in soup.find_all('tr') ]) player_name = [ a.get_text() for a in soup.find_all('tr')[2:12] ] the question is - how to get only the data that is located between `<a>` tag, because if I `print()` out a list **player_name** : ['1Jamie Benn, LWDAL823552871641.0625313.86101323', '2John Tavares, C NYI823848865461.0527813.78131801', '3Sidney Crosby, C PIT772856845471.0923711.83102100', '4Alex Ovechkin, LWWSH8153288110581.0039513.41125900', '\xa0Jakub Voracek, RWPHI822259811780.9922110.03112200', '6Nicklas Backstrom, C WSH821860785400.9515311.8333000', '7Tyler Seguin, C DAL71374077-1201.0828013.25131600', '8Jiri Hudler, LWCGY7831457617140.9715819.6561000', '\xa0Daniel Sedin, LWVAN822056765180.932268.9542100', '10Vladimir Tarasenko, RWSTL7737367327310.9526414.0681000'] Thank you very much with your help! Answer: I would use a [CSS selector](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css- selectors) to locate only data-rows (with players data): for tr in soup.select("#my-players-table tr[class*=player]"): player_name = tr('td')[1].get_text(strip=True) print(player_name) The `class*=player` means "class attribute _contains_ player". Prints: Jamie Benn, LW John Tavares, C Sidney Crosby, C Alex Ovechkin, LW ... Jordan Eberle, RW Ondrej Palat, LW Zach Parise, LW
None column in csv (csv python module) Question: An instrument create a CVS with this on the file header : XLabel,Wavenumber YLabel,Response FileType,Single Beam DisplayDirection,20300 PeakDirection,20312 0.000000,-1.149420,-1.177183,-1.174535 0.964406,-1.053002,-1.083787,-1.069919 1.928811,-0.629619,-0.652436,-0.628358 I want to read this value with cvs python module. import csv expfile='test.csv' with open(expfile) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if (i<4): i += 1 else: print(row) The output is : {None: ['-1.025449', '-1.049773'], 'XLabel': '0.000000', 'Wavenumber': '-1.012466'} {None: ['-1.256103', '-1.297049'], 'XLabel': '0.964406', 'Wavenumber': '-1.254550'} {None: ['-0.722499', '-0.754096'], 'XLabel': '1.928811', 'Wavenumber': '-0.735748'} It is easy to get `Xlabel` or `Wavenumber` value : print(row['XLabel']) But how can I get the `None` value? Answer: Just use `None` as the key: print(row[None]) `None` is simply the value for the `restkey` argument to `DictReader()`, and `None` is the default. You could set it to something else. It is the key into which any _extra_ columns that don't have a fieldname are collected into, and in your case the fieldnames are taken from the first row in the file, which has only two fields. A better option would be to explicitly pass in some fieldnames: reader = csv.DictReader(csvfile, fieldnames=('Field1', 'Field2', 'Field3', 'Field4')) because the first row of that format is not really suitable to act as labels for the columns past the first 5 rows. You can pick names that make sense for those 4 columns. Note you'd have to skip _5_ rows then, not 4. See [Python CSV reader to skip 9 headers](http://stackoverflow.com/questions/28603014/python-csv-reader-to- skip-9-headers) for an alternative technique where you don't have to keep a counter: from itertools import islice import csv expfile='test.csv' with open(expfile) as csvfile: reader = csv.DictReader(csvfile, fieldnames=('Field1', 'Field2', 'Field3', 'Field4')) next(islice(reader, 5, 5), None) for row in reader: print(row)
Python search and replace Question: I have written two functions in Python. When I run replace(), it looks at the data structure named replacements. It takes the key, iterates through the document and when it matches a key to a word in the document, it replaces the word with the value. Now it seems what is happening, because i also have the reverse ('stopped' changes to 'suspended' and 'suspended' changes to 'stopped', depending on what is in the text file), it seems that as it goes through the file, some words are changed, and then changed back (i.e so no changes are made) when I run replace2() i take each word from the text document, and see if this is a key in replacements. If it is, I replace it. What I have noticed though, when I run this, suspended (contains the substring "ended") ends up as "suspfinished"? Is there an easier way to iterate through the text file and only change the word once, if found? I think replace2() does what I want it to do, although I'm losing phrases, but it also seems to pick up substrings, which it should not, as i did use the split() function. def replace(): fileinput = open('tennis.txt').read() out = open('tennis.txt', 'w') for i in replacements.keys(): fileinput = fileinput.replace(i, replacements[i]) print(i, " : ", replacements[i]) out.write(fileinput) out.close def replace2(): fileinput = open('tennis.txt').read() out = open('tennis.txt', 'w') #for line in fileinput: for word in fileinput.split(): for i in replacements.keys(): print(i) if word == i: fileinput = fileinput.replace(word, replacements[i]) out.write(fileinput) out.close replacements = { 'suspended' : 'stopped', 'stopped' : 'suspended', 'due to' : 'because of', 'ended' : 'finished', 'finished' : 'ended', '40' : 'forty', 'forty' : '40', 'because of' : 'due to' } > the match ended due to rain a mere 40 minutes after it started. it was > suspended because of rain. Answer: Improved version of rawbeans answer. It didn't work as expected since some of your replacement keys contain multiple words. Tested with your example line and it outputs: `the match finished because of rain a mere forty minutes after it started. it was stopped due to rain.` import re def replace2(): fileinput = open('tennis.txt').read() out = open('tennisout.txt', 'w') #for line in fileinput: wordpats = '|'.join(replacements.keys()) pattern = r'({0}|\w+|\W|[.,!?;-_])'.format(wordpats) words = re.findall(pattern, fileinput) output = "".join(replacements.get(x, x) for x in words) out.write(output) out.close() replacements = { 'suspended' : 'stopped', 'stopped' : 'suspended', 'due to' : 'because of', 'ended' : 'finished', 'finished' : 'ended', '40' : 'forty', 'forty' : '40', 'because of' : 'due to' } if __name__ == '__main__': replace2()
Cannot import pandas after pip install pandas Question: I run the following command to install `pandas` via `pip`: sudo pip install pandas --upgrade which outputs Requirement already up-to-date: pandas in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages Requirement already up-to-date: numpy>=1.7.0 in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages (from pandas) Requirement already up-to-date: python-dateutil>=2 in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages (from pandas) Requirement already up-to-date: pytz>=2011k in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages (from pandas) Requirement already up-to-date: six>=1.5 in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages (from python-dateutil>=2->pandas) However, when I use `python3` in the command line, I cannot import `pandas`: $ python3 >>> import pandas >>> Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'pandas' It appears that this is in the correct location, as which python3 is in the following location: /opt/local/bin/python3 Executing within python3 >>> import sys >>> print(sys.version) outputs '3.4.5 (default, Jun 27 2016, 04:57:21) \n[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)]' Why can't I import pandas? EDIT: I'm using pip version pip3: pip --version outputs pip 8.1.2 from /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages (python 3.4) Answer: Looks like your OS uses pip2 by default. This could be checked by typing: $ pip --version pip 8.1.2 from /usr/local/lib/python2.7/dist-packages (python 2.7) Try to use `pip3` command like that: sudo pip3 install pandas --upgrade
Reverse for 'post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Question: I get this traceback when browsing to <https://monajalal.pythonanywhere.com/> and the complete code can be found here <https://github.com/monajalal/FirstDjangoApp> : NoReverseMatch at / Reverse for 'post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: https://monajalal.pythonanywhere.com/ Django Version: 1.9.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Exception Location: /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 508 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.1 Python Path: ['/var/www', '.', '', '/var/www', '/home/monajalal/FirstDjangoApp/myvenv/lib/python3.5', '/home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/plat-x86_64-linux-gnu', '/home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages', '/home/monajalal/FirstDjangoApp'] Server time: Mon, 18 Jul 2016 20:31:01 -0500 Error during template rendering In template /home/monajalal/FirstDjangoApp/blog/templates/blog/post_list.html, error at line 0 Reverse for 'post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 1 {% extends 'blog/base.html' %} 2 3 {% block content %} 4 {% for post in posts %} 5 <div class="post"> 6 <div class="date"> 7 {{ post.published_date }} 8 </div> 9 <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> 10 <p>{{ post.text|linebreaksbr }}</p> Traceback Switch to copy-and-paste view /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/defaulttags.py in render current_app=current_app) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/core/urlresolvers.py in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/core/urlresolvers.py in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) ... ▶ Local vars During handling of the above exception (Reverse for 'mysite.post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []), another exception occurred: /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py in get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /home/monajalal/FirstDjangoApp/blog/views.py in post_list ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/shortcuts.py in render template_name, context, request=request, using=using) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/loader.py in render_to_string return template.render(context, request) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/backends/django.py in render return self.template.render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in render return self._render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in _render return self.nodelist.render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in render bit = node.render_annotated(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in render_annotated return self.render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/loader_tags.py in render return compiled_parent._render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in _render return self.nodelist.render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in render bit = node.render_annotated(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in render_annotated return self.render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/defaulttags.py in render return nodelist.render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in render bit = node.render_annotated(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/base.py in render_annotated return self.render(context) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/defaulttags.py in render six.reraise(*exc_info) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/utils/six.py in reraise raise value ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/template/defaulttags.py in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/core/urlresolvers.py in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) ... ▶ Local vars /home/monajalal/FirstDjangoApp/myvenv/lib/python3.5/site-packages/django/core/urlresolvers.py in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) ... ▶ Local vars I have this in views.py: from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post from .forms import PostForm # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form': form}) And the following in urls.py in blog folder: from django.conf.urls import url from django.core.urlresolvers import reverse from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'), ] Can you please hint what the problem is? Answer: Either you need to specify the app name in the url namespace: See this -> <https://docs.djangoproject.com/en/1.9/topics/http/urls/#url- namespaces> Or else you need to write your URLs in your html templates like this: <h1><a href="{% url 'app_name:post_detail' pk=post.pk %}">{{ post.title }}</a></h1> i.e., you'll have to specify the app name in the url in html while reversing, if you have not specified the app name in your namespace for URLs. Hope this will resolve the issue.
Couldn't run the python application based on TKinter Question: import Tkinter as tk from functools import partial pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["C", 0, "S"]] passcode = "" def append_passcode(value): global passcode if len(passcode) == 4: passcode = passcode[1:] passcode += value def clear(): global passcode passcode = "" def submit(): global passcode if passcode == "1234": msgBox.showinfo("Login Attempt", "Successful") passcode = "" else: msgBox.showinfo("Login Attempt", "Failed") passcode = "" main_window = tk.Tk() btns = [] row_placement = 0 for line in pad: col_placement = 0 for number in line: btn_command = partial(append_passcode, str(number)) btn = tk.Button(main_window, text=str(number), width=10, command=btn_command) btns.append(btn) btn.grid(row=row_placement, column=col_placement) col_placement += 1 row_placement += 1 #Setting C to clear the passcode function btns[-3].config(command=clear) #Setting S to submit passcode btns[-1].config(command=submit) I'm writing an numpad application where user must enter the correct 4 digit code to access application. when the test code runs, the GUI does not appear. What needs to be done to get this code to function? Answer: Here's what you've done wrong: * Misspelled tkinter * Not included main_window.mainloop() Try this code import tkinter as tk from functools import partial pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["C", 0, "S"]] passcode = "" def append_passcode(value): global passcode if len(passcode) == 4: passcode = passcode[1:] passcode += value def clear(): global passcode passcode = "" def submit(): global passcode if passcode == "1234": msgBox.showinfo("Login Attempt", "Successful") passcode = "" else: msgBox.showinfo("Login Attempt", "Failed") passcode = "" main_window = tk.Tk() btns = [] row_placement = 0 for line in pad: col_placement = 0 for number in line: btn_command = partial(append_passcode, str(number)) btn = tk.Button(main_window, text=str(number), width=10, command=btn_command) btns.append(btn) btn.grid(row=row_placement, column=col_placement) col_placement += 1 row_placement += 1 #Setting C to clear the passcode function btns[-3].config(command=clear) #Setting S to submit passcode btns[-1].config(command=submit) main_window.mainloop() Now your window should appear. Hope this helps and feel free to comment any questions.
Compare adjacent values in numpy array Question: I have a Numpy one-dimensional array of data, something like this a = [1.9, 2.3, 2.1, 2.5, 2.7, 3.0, 3.3, 3.2, 3.1] I want to create a new array, where the values are composed of the greater of the adjacent values. For the above example, the output would be: b = [2.3, 2.3, 2.5, 2.7, 3.0, 3.3, 3.3, 3.2] I can do this by looping through the input array, comparing the neighbouring values, eg: import numpy as np a = np.array([1.9, 2.3, 2.1, 2.5, 2.7, 3.0, 3.3, 3.2, 3.1]) b = np.zeros(len(a)-1) for i in range(len(a)-1): if (a[i] > a[i+1]): b[i] = a[i] else: b[i] = a[i+1] but I'd like to do this in a more elegant "pythonic" vectorised fashion. I've searched and read about np.zip, np.where, np.diff etc but haven't yet found a way to do this (or more likely, I haven't understood what is possible). Any suggestions ? Answer: You want element-wise maximum of `a[1:]` and `a[:-1]`: >>> a array([ 1.9, 2.3, 2.1, 2.5, 2.7, 3. , 3.3, 3.2, 3.1]) >>> a[1:] array([ 2.3, 2.1, 2.5, 2.7, 3. , 3.3, 3.2, 3.1]) >>> a[:-1] array([ 1.9, 2.3, 2.1, 2.5, 2.7, 3. , 3.3, 3.2]) >>> np.maximum(a[1:], a[:-1]) array([ 2.3, 2.3, 2.5, 2.7, 3. , 3.3, 3.3, 3.2])
File does not upload and save in the database Question: I've been having problem in saving and uploading files in django. I've been reading the entire tutorial to get this up and running. I've been stuck with this: 'tuple' does not support the buffer interface The problem seems to be coming from views.py, it stops somewhere between saving. I hope you could point me in the right direction.. My upload/views.py # -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from upload.models import Files from upload.forms import DocumentForm # import sys, traceback def index(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Files(file_path = request.FILES['file_path']) newdoc.save() # print(request) # Redirect to the document list after POST return HttpResponseRedirect(reverse('upload.views.index')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Files.objects.all() # print(form) print(documents) # Render list page with the documents and the form return render_to_response( 'upload/index.html', {'documents': documents, 'form': form}, RequestContext(request) ) my uploads/models.py from django.db import models # Create your models here. class Files(models.Model): user_id = models.IntegerField() project_id = models.IntegerField() file_path = models.FileField(upload_to='documents/%Y/%m/%d') file_name = models.CharField(max_length=255) file_size = models.CharField(max_length=45) file_type = models.CharField(max_length=45) file_ext = models.CharField(max_length=10) file_width = models.SmallIntegerField() file_height = models.SmallIntegerField() file_tag = models.CharField(max_length=45) location = models.TextField() approved = models.IntegerField() archived = models.IntegerField() restored = models.IntegerField() backup = models.IntegerField() date_upload = models.DateTimeField() date_modified = models.DateTimeField() def __str__(self): return 'file_name:{0}'.format(self.file_name) class Meta: managed = False db_table = 'files' upload/forms.py # -*- coding: utf-8 -*- from django import forms class DocumentForm(forms.Form): file_path = forms.FileField( label='Select a file', help_text='max. 42 megabytes' ) Here is the full traceback: Environment: Request Method: POST Request URL: http://localhost:8000/upload/ Django Version: 1.9 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gallery', 'upload'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\python\testify\upload\views.py" in index 18. newdoc.save() File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in save 697. force_update=force_update, update_fields=update_fields) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in save_base 725. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in _save_table 809. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\base.py" in _do_insert 848. using=using, raw=raw) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\manager.py" in manager_method 122. return getattr(self.get_queryset(), name)(*args, **kwargs) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\query.py" in _insert 1037. return query.get_compiler(using=using).execute_sql(return_id) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in execute_sql 985. for sql, params in self.as_sql(): File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in as_sql 943. for obj in self.query.objs File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in <listcomp> 943. for obj in self.query.objs File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\sql\compiler.py" in <listcomp> 941. ) for f in fields File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in pre_save 311. file.save(file.name, file, save=False) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in save 90. name = self.field.generate_filename(self.instance, name) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in generate_filename 332. return os.path.join(self.get_directory_name(), self.get_filename(filename)) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\db\models\fields\files.py" in get_filename 322. return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename))) File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\utils\functional.py" in inner 205. self._setup() File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\files\storage.py" in _setup 333. self._wrapped = get_storage_class()() File "c:\python\lib\site-packages\django-1.9.dev20150917232253-py3.4.egg\django\core\files\storage.py" in __init__ 185. self.location = abspathu(self.base_location) File "c:\python\lib\ntpath.py" in abspath 547. path = _getfullpathname(path) Exception Type: TypeError at /upload/ Exception Value: 'tuple' does not support the buffer interface * Update: It now saves in the database, I have just added all the fields in newdoc. My table does not allow NULL values, the problem however is in: file_path = request.FILES['file_path'] Answer: The `FileField` represents an uploaded file object. So you need to pass it a _file_ and not a _path_. def index(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Files(file_path = form.cleaned_data['file_path']) newdoc.save() # print(request) The [documentation on file uploads](https://docs.djangoproject.com/en/1.9/topics/http/file-uploads/) goes into great detail on this.
How to plot a Python Dataframe with category values like this picture? Question: ![enter image description here](http://i.stack.imgur.com/sXOdd.png) How can I achieve that using matplotlib? Answer: Here is my code with the data you provided. As there's no class [they are all different, despite your first example in your question does have classes], I gave colors based on the numbers. You can definitely start alone from here, whatever result you want to achieve. You just need `pandas`, `seaborn` and `matplotlib`: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # import xls df=pd.read_excel('data.xlsx') # exclude Ranking values df1 = df.ix[:,1:-1] # for each element it takes the value of the xls cell df2=df1.applymap(lambda x: float(x.split('\n')[1])) # now plot it df_heatmap = df2 fig, ax = plt.subplots(figsize=(15,15)) sns.heatmap(df_heatmap, square=True, ax=ax, annot=True, fmt="1.3f") plt.yticks(rotation=0,fontsize=16); plt.xticks(fontsize=12); plt.tight_layout() plt.savefig('dfcolorgraph.png') Which produces the following picture. [![result](http://i.stack.imgur.com/sWdEK.png)](http://i.stack.imgur.com/sWdEK.png)
Python, Tk and OptionMenu: how to sort a drop down list? Question: I want to make a drop down list with tk and OptionMenu. I want to show a string to the user ("10 us", "40 us"...) and return a number (0, 1,...) which is a parameter that I send to a variable. It works well, but it's not sorted. I want to sort the list like the variable "lst1". [![enter image description here](http://i.stack.imgur.com/IIRu9.png)](http://i.stack.imgur.com/IIRu9.png) It should be: * 10 us * 20 us * 40 us * 80 us lst1 = {"10 us": 0, "20 us": 1, "40 us": 2, "80 us": 3, "160 us": 4, "320 us": 5, "640 us": 6, "1.28 ms": 7, "2.56 ms": 8, "5.12 ms": 9, "10.24 ms": 10} var_tc = StringVar() var_tc.set("40 us") list_tc = OptionMenu(frame, var_tc, *lst1.keys()) list_tc.config(takefocus=1) list_tc.grid(row=10, column=1, padx=2, pady=10) param.tc = lst1[var_tc.get()] Could you help me, please? :) Answer: The issue is that you're using a dictionary as a list, and dictionaries don't have any notion of order. Two ways you could do it; both are pretty straightforward. # Way 1: Just use sorted keys You don't have to change much, just when you pass in `lst1.keys()`, you instead pass in `sorted(lst1.keys())`, since `keys()` returns a list and you can give a sorted one of those. # Way 2: Use a dictionary that keeps order One of the python standard libraries is `collections`, which contains many containers of varying usefulness. One of these is the `OrderedDict`, a dictionary that keeps the order in which you enter things. You would import it as `from collections import OrderedDict`, and initialize it as any other object - `lst1 = OrderedDict([("10us",0), ("20us",1), ...])`
SwiftConfigurationException: Invalid host name when accessing Swift from Bluemix Spark Question: I've stored a file in Swift (Bluemix Objectstore) and I'm trying to access it from a Python application running on Spark within Bluemix. I can successfully access the file in a Python notebook running in the same environment, but the access fails when done within a submitted Python application with an `org.apache.hadoop.fs.swift.exceptions.SwiftConfigurationException: Invalid host name` error. Here's the Python code: # Added to the Python job but not part of the notebook from pyspark import SparkContext, SparkConf from pyspark.sql import SQLContext sc = SparkContext() sqlContext = SQLContext(sc) # Verified in the notebook from pyspark.sql import SQLContext from pyspark.sql.types import * from pyspark.sql import Row from pyspark.mllib.regression import LabeledPoint from pyspark.sql.functions import udf from pyspark.mllib.linalg import Vectors from pyspark.ml.classification import LogisticRegression from pyspark.ml.param import Param, Params from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.stat import Statistics from pyspark.ml.feature import OneHotEncoder, StringIndexer from pyspark.mllib.linalg import Vectors from pyspark.ml.feature import VectorAssembler import sys import numpy as np import pandas as pd import time import datetime def set_hadoop_config(credentials): """This function sets the Hadoop configuration with given credentials, so it is possible to access data using SparkContext""" prefix = "fs.swift.service." + credentials['name'] hconf = sc._jsc.hadoopConfiguration() hconf.set(prefix + ".auth.url", credentials['auth_url']+'/v3/auth/tokens') hconf.set(prefix + ".auth.endpoint.prefix", "endpoints") hconf.set(prefix + ".tenant", credentials['project_id']) hconf.set(prefix + ".username", credentials['user_id']) hconf.set(prefix + ".password", credentials['password']) hconf.setInt(prefix + ".http.port", 8080) hconf.set(prefix + ".region", credentials['region']) hconf.setBoolean(prefix + ".public", True) credentials = { 'auth_url':'https://identity.open.softlayer.com', 'project':'object_storage_bcc6ba38_7399_4aed_a47c_e6bcdc959163', 'project_id':'f26ba12177c44e59adbe243b430b3bf5', 'region':'dallas', 'user_id':'bb973e5a84da4fce8c62d95f2e1e5d19', 'domain_id':'bd9453b2e5e2424388e25677cd26a7cf', 'domain_name':'1062145', 'username':'admin_a16bbb9d8d1d051ba505b6e7e76867f61c9d1ac1', 'password':"""...""", 'filename':'2001-2008-merged.csv', 'container':'notebooks', 'tenantId':'s090-be5845bf9646f1-3ef81b4dcb61' } credentials['name'] = 'FlightDelay_demo2' set_hadoop_config(credentials) textFile = sc.textFile("swift://" + credentials['container'] + "." + credentials['name'] + credentials['filename']) textFileRDD=textFile.map(lambda x: x.split(',')) # Line that throws the error: header = textFileRDD.first() I'm submitting the Python application to Spark as follows: ./spark-submit.sh \ --vcap ./vcap.json \ --deploy-mode cluster \ --master https://spark.bluemix.net \ /resources/FlightDelay_demo2.py Here's my vcap.json: { "credentials": { "tenant_id": "s090-be5845bf9646f1-3ef81b4dcb61", "tenant_id_full": "2f61d7ef-955a-41f2-9090-be5845bf9646_dd570054-525b-4659-9af1-3ef81b4dcb61", "cluster_master_url": "https://spark.bluemix.net", "instance_id": "2f61d7ef-955a-41f2-9090-be5845bf9646", "tenant_secret": "...", "plan": "ibm.SparkService.PayGoPersonal" } } Here's the full error: Traceback (most recent call last): File "/gpfs/fs01/user/s090-be5845bf9646f1-3ef81b4dcb61/data/workdir/spark-driver-b2f25278-f8b4-40e3-8d53-9e8a64228197/FlightDelay_demo2.py", line 94, in <module> header = textFileRDD.first() File "/usr/local/src/spark160master/spark-1.6.0-bin-2.6.0/python/lib/pyspark.zip/pyspark/rdd.py", line 1315, in first File "/usr/local/src/spark160master/spark-1.6.0-bin-2.6.0/python/lib/pyspark.zip/pyspark/rdd.py", line 1267, in take File "/usr/local/src/spark160master/spark-1.6.0-bin-2.6.0/python/lib/pyspark.zip/pyspark/rdd.py", line 2363, in getNumPartitions File "/usr/local/src/spark160master/spark-1.6.0-bin-2.6.0/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__ File "/usr/local/src/spark160master/spark-1.6.0-bin-2.6.0/python/lib/pyspark.zip/pyspark/sql/utils.py", line 45, in deco File "/usr/local/src/spark160master/spark-1.6.0-bin-2.6.0/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o33.partitions. : org.apache.hadoop.fs.swift.exceptions.SwiftConfigurationException: Invalid host name at org.apache.hadoop.fs.swift.util.SwiftUtils.validSchema(SwiftUtils.java:222) at org.apache.hadoop.fs.swift.http.SwiftRestClient.<init>(SwiftRestClient.java:510) at org.apache.hadoop.fs.swift.http.SwiftRestClient.getInstance(SwiftRestClient.java:1914) at org.apache.hadoop.fs.swift.snative.SwiftNativeFileSystemStore.initialize(SwiftNativeFileSystemStore.java:81) at org.apache.hadoop.fs.swift.snative.SwiftNativeFileSystem.initialize(SwiftNativeFileSystem.java:129) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2596) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:91) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2630) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2612) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:370) at org.apache.hadoop.fs.Path.getFileSystem(Path.java:296) at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:256) at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228) at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313) at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:199) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:120) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:120) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.api.java.JavaRDDLike$class.partitions(JavaRDDLike.scala:64) at org.apache.spark.api.java.AbstractJavaRDDLike.partitions(JavaRDDLike.scala:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55) at java.lang.reflect.Method.invoke(Method.java:507) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381) at py4j.Gateway.invoke(Gateway.java:259) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:209) at java.lang.Thread.run(Thread.java:785) I thought it might be relevant, so here's what the Spark configuration (`sorted(sc._conf.getAll())`) looks like within the Python application: [(u'spark.app.name', u'/resources/FlightDelay_demo2.py'), (u'spark.driver.extraClassPath', u'/gpfs/fs01/user/s090-be5845bf9646f1-3ef81b4dcb61/data/libs/*:'), (u'spark.driver.extraLibraryPath', u'/gpfs/fs01/user/s090-be5845bf9646f1-3ef81b4dcb61/data/libs/*:'), (u'spark.eventLog.dir', u'/gpfs/fs01/user/s090-be5845bf9646f1-3ef81b4dcb61/events'), (u'spark.eventLog.enabled', u'true'), (u'spark.executor.extraClassPath', u'/gpfs/fs01/user/s090-be5845bf9646f1-3ef81b4dcb61/data/libs/*:'), (u'spark.executor.extraLibraryPath', u'/gpfs/fs01/user/s090-be5845bf9646f1-3ef81b4dcb61/data/libs/*:'), (u'spark.executor.instances', u'2'), (u'spark.executor.memory', u'1024m'), (u'spark.files', u'/gpfs/fs01/user/s090-be5845bf9646f1-3ef81b4dcb61/data/128249272b758216b946308d5f6ea43ca033a85a/FlightDelay_demo2.py'), (u'spark.files.useFetchCache', u'false'), (u'spark.master', u'spark://yp-spark-dal09-env5-0020:7083'), (u'spark.rdd.compress', u'True'), (u'spark.serializer.objectStreamReset', u'100'), (u'spark.service.hashed_tenant_id', u'25vT74pNDbLRr98mnGe81k9FmiS9NRiyELS04g=='), (u'spark.service.plan_name', u'ibm.SparkService.PayGoPersonal'), (u'spark.service.spark_version', u'1.6.0'), (u'spark.shuffle.service.port', u'7340'), (u'spark.submit.pyFiles', u'null'), (u'spark.ui.port', u'0')] Answer: There are two issues, both relating to the swift URL: 1. `credentials['name']` cannot contain characters that are illegal in a hostname like underscores. Remove the underscore as follows: credentials['name'] = 'FlightDelayDemo2' 2. There's a missing slash between the hostname and the filename. It needs to be added: textFile = sc.textFile("swift://" + credentials['container'] + "." + credentials['name'] + "/" + credentials['filename']) Since I'm answering my own question, I want to mention that another obscure error that you might see while debugging something similar is: `pyspark.sql.utils.IllegalArgumentException: u'Host name may not be null'`
getting the average of serial port data Question: i have a python code which reads serial data through RS232 import serial import time ser = serial.Serial('/dev/ttyUSB0', 2400, timeout=1) while True: str1 = ser.read(1) if str1 == '': print 'no data on line' else: print str1 this returns me no data on line no data on line no data on line no data on line 206 210 212 200 it's mic-reading values let's assume those numbers are degrees to move a motor i want to get the avarage number to move the motor to it. Answer: import serial import time data_sum = [] ser = serial.Serial('/dev/ttyUSB0', 2400, timeout=1) while True: str1 = ser.read(1) if str1 == '': print 'no data on line' else: data_sum.append(int(str1) ave = sum(data_sum)/len(data_sum)
Zipline: using pandas-datareader to feed in Google Finance dataframe for non-US based financial markets Question: **PLEASE NOTE:** This question was successfully answered ptrj below. I have also written a blog post on my blog about my experiences with zipline which you can find here: <https://financialzipline.wordpress.com> * * * I'm based in South Africa and I'm trying to load South African shares into a dataframe so that it will feed zipline with share price information. Let's say I'm looking at **AdCorp Holdings Limited** as listed on the JSE (Johannesburg Stock Exchange): **Google Finance** gives me the historical price info: [https://www.google.com/finance/historical?q=JSE%3AADR&ei=5G6OV4ibBIi8UcP- nfgB](https://www.google.com/finance/historical?q=JSE%3AADR&ei=5G6OV4ibBIi8UcP- nfgB) **Yahoo Finance** has no information on the company. <https://finance.yahoo.com/quote/adcorp?ltr=1> Typing in the following code within iPython Notebook gets me the dataframe for the information from Google Finance: start = datetime.datetime(2016,7,1) end = datetime.datetime(2016,7,18) f = web.DataReader('JSE:ADR', 'google',start,end) If I display f, I see that the information actually corresponds to the info off Google Finance as well: [![enter image description here](http://i.stack.imgur.com/C3Xqg.png)](http://i.stack.imgur.com/C3Xqg.png) This is the price exactly off Google Finance, you can see the info for the 2016-07-18 on the Google Finance website matches exactly to my dataframe. [![enter image description here](http://i.stack.imgur.com/5hFpy.png)](http://i.stack.imgur.com/5hFpy.png) However, I'm not sure how to load this dataframe so that it can be used by zipline as a data bundle. If you look at the example given for `buyapple.py`, you can see that it just pulls the data of apple shares (APPL) from the ingested data bundle `quantopian-quandl`. The challenge here is to replace `APPL` with `JSE:ADR` so that it will order 10 `JSE:ADR` shares a day as fed from the dataframe instead of the data bundle `quantopian-quandl` and plot it on a graph. Does anyone know how to do this? There are almost no examples on the net that deals with this... This is the `buyapple.py` code as supplied in zipline's example folder: from zipline.api import order, record, symbol def initialize(context): pass def handle_data(context, data): order(symbol('AAPL'), 10) record(AAPL=data.current(symbol('AAPL'), 'price')) # Note: this function can be removed if running # this algorithm on quantopian.com def analyze(context=None, results=None): import matplotlib.pyplot as plt # Plot the portfolio and asset data. ax1 = plt.subplot(211) results.portfolio_value.plot(ax=ax1) ax1.set_ylabel('Portfolio value (USD)') ax2 = plt.subplot(212, sharex=ax1) results.AAPL.plot(ax=ax2) ax2.set_ylabel('AAPL price (USD)') # Show the plot. plt.gcf().set_size_inches(18, 8) plt.show() def _test_args(): """Extra arguments to use when zipline's automated tests run this example. """ import pandas as pd return { 'start': pd.Timestamp('2014-01-01', tz='utc'), 'end': pd.Timestamp('2014-11-01', tz='utc'), } **EDIT:** I looked at the code for ingesting the data from Yahoo Finance and modified it a little to make it take on Google Finance data. The code for the Yahoo Finance can be found here: <http://www.zipline.io/_modules/zipline/data/bundles/yahoo.html>. This is my code to ingest Google Finance - sadly it is not working. Can someone more fluent in python assist me?: import os import numpy as np import pandas as pd from pandas_datareader.data import DataReader import requests from zipline.utils.cli import maybe_show_progress def _cachpath(symbol, type_): return '-'.join((symbol.replace(os.path.sep, '_'), type_)) def google_equities(symbols, start=None, end=None): """Create a data bundle ingest function from a set of symbols loaded from yahoo. Parameters ---------- symbols : iterable[str] The ticker symbols to load data for. start : datetime, optional The start date to query for. By default this pulls the full history for the calendar. end : datetime, optional The end date to query for. By default this pulls the full history for the calendar. Returns ------- ingest : callable The bundle ingest function for the given set of symbols. Examples -------- This code should be added to ~/.zipline/extension.py .. code-block:: python from zipline.data.bundles import yahoo_equities, register symbols = ( 'AAPL', 'IBM', 'MSFT', ) register('my_bundle', yahoo_equities(symbols)) Notes ----- The sids for each symbol will be the index into the symbols sequence. """ # strict this in memory so that we can reiterate over it symbols = tuple(symbols) def ingest(environ, asset_db_writer, minute_bar_writer, # unused daily_bar_writer, adjustment_writer, calendar, cache, show_progress, output_dir, # pass these as defaults to make them 'nonlocal' in py2 start=start, end=end): if start is None: start = calendar[0] if end is None: end = None metadata = pd.DataFrame(np.empty(len(symbols), dtype=[ ('start_date', 'datetime64[ns]'), ('end_date', 'datetime64[ns]'), ('auto_close_date', 'datetime64[ns]'), ('symbol', 'object'), ])) def _pricing_iter(): sid = 0 with maybe_show_progress( symbols, show_progress, label='Downloading Google pricing data: ') as it, \ requests.Session() as session: for symbol in it: path = _cachpath(symbol, 'ohlcv') try: df = cache[path] except KeyError: df = cache[path] = DataReader( symbol, 'google', start, end, session=session, ).sort_index() # the start date is the date of the first trade and # the end date is the date of the last trade start_date = df.index[0] end_date = df.index[-1] # The auto_close date is the day after the last trade. ac_date = end_date + pd.Timedelta(days=1) metadata.iloc[sid] = start_date, end_date, ac_date, symbol df.rename( columns={ 'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume': 'volume', }, inplace=True, ) yield sid, df sid += 1 daily_bar_writer.write(_pricing_iter(), show_progress=True) symbol_map = pd.Series(metadata.symbol.index, metadata.symbol) asset_db_writer.write(equities=metadata) adjustment_writer.write(splits=pd.DataFrame(), dividends=pd.DataFrame()) # adjustments = [] # with maybe_show_progress( # symbols, # show_progress, # label='Downloading Google adjustment data: ') as it, \ # requests.Session() as session: # for symbol in it: # path = _cachpath(symbol, 'adjustment') # try: # df = cache[path] # except KeyError: # df = cache[path] = DataReader( # symbol, # 'google-actions', # start, # end, # session=session, # ).sort_index() # df['sid'] = symbol_map[symbol] # adjustments.append(df) # adj_df = pd.concat(adjustments) # adj_df.index.name = 'date' # adj_df.reset_index(inplace=True) # splits = adj_df[adj_df.action == 'SPLIT'] # splits = splits.rename( # columns={'value': 'ratio', 'date': 'effective_date'}, # ) # splits.drop('action', axis=1, inplace=True) # dividends = adj_df[adj_df.action == 'DIVIDEND'] # dividends = dividends.rename( # columns={'value': 'amount', 'date': 'ex_date'}, # ) # dividends.drop('action', axis=1, inplace=True) # # we do not have this data in the yahoo dataset # dividends['record_date'] = pd.NaT # dividends['declared_date'] = pd.NaT # dividends['pay_date'] = pd.NaT # adjustment_writer.write(splits=splits, dividends=dividends) return ingest Answer: I followed tutorials on <http://www.zipline.io/> and I made it work with the following steps: 1. Prepare an ingestion function for google equities. The same code you pasted (based on file [yahoo.py](http://www.zipline.io/_modules/zipline/data/bundles/yahoo.html)) with the following modification: # Replace line # adjustment_writer.write(splits=pd.DataFrame(), dividends=pd.DataFrame()) # with line adjustment_writer.write() I named the file `google.py` and copied it to subdirectory `zipline/data/bundle` of the zipline install directory. (It can be placed anywhere on the python path. Or you can modify `zipline/data/bundle/__init__.py` to be able to call it the same way as `yahoo_equities`.) 2. Ingest (see <http://www.zipline.io/bundles.html>) Add the following lines to file `.zipline/extension.py` in the home directory - the home directory is your User directory on Windows (C:\Users\your username). The .zipline folder is a hidden folder, you will have to unhide the files to see it. from zipline.data.bundles import register from zipline.data.bundles.google import google_equities equities2 = { 'JSE:ADR', } register( 'my-google-equities-bundle', # name this whatever you like google_equities(equities2), ) And run zipline ingest -b my-google-equities-bundle 3. Test (as in <http://www.zipline.io/beginner-tutorial.html>) I took an example file `zipline/examples/buyapple.py` (the same you pasted), replaced both occurences of symbol `'AAPL'` with `'JSE:ADR'`, renamed to `buyadcorp.py` and ran python -m zipline run -f buyadcorp.py --bundle my-google-equities-bundle --start 2000-1-1 --end 2014-1-1 The outcome was consistent with the data downloaded directly from Google Finance.
Python - Transposing a list (rows with different length) using numpy fails Question: When the list contains only rows with same length the transposition works: numpy.array([[1, 2], [3, 4]]).T.tolist(); >>> [[1, 3], [2, 4]] But, in my case the list contains rows with different length: numpy.array([[1, 2, 3], [4, 5]]).T.tolist(); which fails. Any possible solution? Answer: If you're not having `numpy` as a compulsory requirement, you can use [`itertools.zip_longest`](https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest) to do the transpose: from itertools import zip_longest l = [[1, 2, 3], [4, 5]] r = [list(filter(None,i)) for i in zip_longest(*l)] print(r) # [[1, 4], [2, 5], [3]] `zip_longest` pads the results with `None` due to _unmatching_ lengths, so the list comprehension and `filter(None, ...)` is used to remove the `None` values In python 2.x it would be [`itertools.izip_longest`](https://docs.python.org/2.7/library/itertools.html#itertools.izip_longest)
moving a file in python using shutil Question: I know there have been some posts on how to move a file in python but I am a little confused. I am working on a program that has a file called test.txt The file path is this: `C:\Users\user\Desktop\Project1\Project1` I want to move it to: `C:\Users\user\Documents\ProjectMoved` I tried different variations of what I have below src="C:\\Users\\user\\Desktop\\Project1\\Project1\\test.txt" dst="C:\\Users\\user\\Documents\\ProjectMoved" shutil.move(src, dst) I keep getting the error no such file in directory. I was wondering if someone could help me out with the correct way to move the file. Answer: Might be worth checking the file exists and then trying to specify paths using `os.path.join`: import shutil import os from os.path import join src = join('/', 'Users', 'username', 'Desktop', 'a.pdf') dst = join('/', 'Users', 'username', 'Documents', 'a.pdf') shutil.move(src, dst) You can first verify if the `src` actually exists: os.path.exists(src) >>> True
Why does sorted()'s key parameter require a keyword argument Question: If you inspect the signature of Python's built-in `sorted()` function like this: import inspect print(inspect.signature(sorted)) The signature is: `(iterable, key=None, reverse=False)`. Based on my understanding of positional and optional arguments acquired [here](https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments), it would seem like you could provide an `iterable` argument and then a `key` argument without needing a keyword `key=` for the `key` argument. But you always need to specify `key=` when passing a `key` argument. Why is that? I understand that if you wanted to specify `reverse=True`, but without any `key` argument, you'd need a keyword for that, but I don't understand why you'd need to specify `key=` when you're providing a `key`. Answer: This is [Python issue 26729](https://bugs.python.org/issue26729), an error in `sorted.__text_signature__`, which is missing the `/` and `*` required to indicate that `iterable` is positional-only and `key` and `reverse` are keyword-only. The patch is in patch review, assigned to Raymond Hettinger. Once the patched version is released, the signature should display as (iterable, /, *, key=None, reverse=False)
Looking for a way to de-reference a bash var wrapped in a python command call Question: I'm trying to find a way to de-reference goldenClusterID to use it in an AWS CLI command to terminate my cluster. This program is to compensate for dynamic Job-Flow Numbers generated each day so normal Data Pipeline shutdown via schedule is applicable. I can os.system("less goldenClusterID") all day and it gives me the right answer. However, it won't give up the goodies with a straight de-ref. Suggestions? from __future__ import print_function import json import urllib import boto3 import commands import os import re import datetime import awscli foundCluster = "" rawClusterNum = "" mainClusterNum = "" goldenClusterID = "" # Next, we populate the list file with clusters currently active os.system("aws emr list-clusters --active >> foundCluster") # We search for a specific Cluster Name os.system("fgrep 'AnAWSEMRCluster' foundCluster") os.system("grep -B 1 DrMikesEMRCluster foundCluster >> rawClusterNum") # Look for the specific Cluster ID in context with it's Cluster Name os.system("fgrep 'j-' rawClusterNum >> mainClusterNum") # Regex the Cluster ID from the line os.system("grep -o '\j-[0-9a-zA-Z]*' mainClusterNum >> goldenClusterID") # Read the Cluster ID from the file and run AWS Terminate on it os.system("aws emr describe-cluster --cluster-id %s" % goldenClusterID") os.system("aws emr terminate-clusters --cluster-ids goldenClusterID") os.system("rm *") Answer: Never mind, I figured it out. Too much coffee and not enough sleep. The answer is to use: goldkeyID=open('goldenClusterID', 'r').read() os.system("aws emr describe-cluster --cluster-id %s" % goldkeyID)
Tweepy: can´t print tweets in file Question: I'm new to python (and programming in general) and I'm trying to write a script to collect tweets. I can´t get the script to print the tweets in the file. The tweets appeared in Idle with the error "failed ondata, global name 'saveFile' is not defined" and they don't get printed in the file i ran this code: from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import time ckey = ??? csecret = ??? atoken = ???? asecret = "??? class listener(StreamListener): def on_data(self, data): try: print data savefile = open('twitDB.json','a') saveFile.write(data) savefile.write('\n') saveFile.close() return True except BaseException, e: print "failed ondata,",str(e) time.sleep(5) def on_error(self, status): print status auth = OAuthHandler(ckey,csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=["movistar"]) from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener Any kind of help is welcomed Answer: Take a look at the **saveFile** variable. First time you used it as save**f** ile, then you used save**F** ile (note the letter **f** and capital **F**) Change all occurrences to the same name and it should work. Also, be careful when doing that in the **on_data** method. As far as I know, it will be called for every single tweet you receive. That is, you will open the file, write the tweet, close the file and then again for each tweet.
Realtime plotting with PyQt PlotWidget - error message PlotWidget object is not callable Question: I am trying to create a real time data plot using a PyQt plot widget. I read that PyQt is the best option for plotting real time graphs but so far I am not having any success. I have tried to plot random data using the method [followed here](http://stackoverflow.com/questions/18080170/what-is-the-easiest-way-to- achieve-realtime-plotting-in-pyqtgraph) however it seems that this method does not apply to the PyQt plot widget. I have compiled the following code to generate a GUI which plots random points on the x and y axis; however I get the error: > **PlotWidget object is not callable** from PyQt4.QtGui import * from PyQt4.QtCore import * import numpy as np import pyqtgraph as pg import sys class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setWindowIcon(QIcon('pythonlogo.png')) self.setGeometry(50,50,700,300) self.home() def home(self): #Timer for Plot calls the update function self.plot = pg.PlotWidget(self) self.timer2 = pg.QtCore.QTimer() self.timer2.timeout.connect(self.update) self.timer2.start(16) #Plot widget postion self.plot.move(200,50) self.plot.resize(450,200) self.show() def update(self): x = np.random.normal(size=1000) y = np.random.normal(size=1000) self.plot(x,y,clear=True) def run(): app=QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run() Answer: I have been confronted with similar issues. But in the end I got my realtime plot working! I have taken a look at my code, and thrown out all the things that are not relevant for you. So what you will find here is the basic code that you need to display a live graph: ################################################################### # # # PLOTTING A LIVE GRAPH # # ---------------------------- # # EMBED A MATPLOTLIB ANIMATION INSIDE YOUR # # OWN GUI! # # # ################################################################### import sys import os from PyQt4 import QtGui from PyQt4 import QtCore import functools import numpy as np import random as rd import matplotlib matplotlib.use("Qt4Agg") from matplotlib.figure import Figure from matplotlib.animation import TimedAnimation from matplotlib.lines import Line2D from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas import time import threading def setCustomSize(x, width, height): sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(x.sizePolicy().hasHeightForWidth()) x.setSizePolicy(sizePolicy) x.setMinimumSize(QtCore.QSize(width, height)) x.setMaximumSize(QtCore.QSize(width, height)) '''''' class CustomMainWindow(QtGui.QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # Define the geometry of the main window self.setGeometry(300, 300, 800, 400) self.setWindowTitle("my first window") # Create FRAME_A self.FRAME_A = QtGui.QFrame(self) self.FRAME_A.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(210,210,235,255).name()) self.LAYOUT_A = QtGui.QGridLayout() self.FRAME_A.setLayout(self.LAYOUT_A) self.setCentralWidget(self.FRAME_A) # Place the zoom button self.zoomBtn = QtGui.QPushButton(text = 'zoom') setCustomSize(self.zoomBtn, 100, 50) self.zoomBtn.clicked.connect(self.zoomBtnAction) self.LAYOUT_A.addWidget(self.zoomBtn, *(0,0)) # Place the matplotlib figure self.myFig = CustomFigCanvas() self.LAYOUT_A.addWidget(self.myFig, *(0,1)) # Add the callbackfunc to .. myDataLoop = threading.Thread(name = 'myDataLoop', target = dataSendLoop, daemon = True, args = (self.addData_callbackFunc,)) myDataLoop.start() self.show() '''''' def zoomBtnAction(self): print("zoom in") self.myFig.zoomIn(5) '''''' def addData_callbackFunc(self, value): # print("Add data: " + str(value)) self.myFig.addData(value) ''' End Class ''' class CustomFigCanvas(FigureCanvas, TimedAnimation): def __init__(self): self.addedData = [] print(matplotlib.__version__) # The data self.xlim = 200 self.n = np.linspace(0, self.xlim - 1, self.xlim) a = [] b = [] a.append(2.0) a.append(4.0) a.append(2.0) b.append(4.0) b.append(3.0) b.append(4.0) self.y = (self.n * 0.0) + 50 # The window self.fig = Figure(figsize=(5,5), dpi=100) self.ax1 = self.fig.add_subplot(111) # self.ax1 settings self.ax1.set_xlabel('time') self.ax1.set_ylabel('raw data') self.line1 = Line2D([], [], color='blue') self.line1_tail = Line2D([], [], color='red', linewidth=2) self.line1_head = Line2D([], [], color='red', marker='o', markeredgecolor='r') self.ax1.add_line(self.line1) self.ax1.add_line(self.line1_tail) self.ax1.add_line(self.line1_head) self.ax1.set_xlim(0, self.xlim - 1) self.ax1.set_ylim(0, 100) FigureCanvas.__init__(self, self.fig) TimedAnimation.__init__(self, self.fig, interval = 50, blit = True) def new_frame_seq(self): return iter(range(self.n.size)) def _init_draw(self): lines = [self.line1, self.line1_tail, self.line1_head] for l in lines: l.set_data([], []) def addData(self, value): self.addedData.append(value) def zoomIn(self, value): bottom = self.ax1.get_ylim()[0] top = self.ax1.get_ylim()[1] bottom += value top -= value self.ax1.set_ylim(bottom,top) self.draw() def _step(self, *args): # Extends the _step() method for the TimedAnimation class. try: TimedAnimation._step(self, *args) except Exception as e: self.abc += 1 print(str(self.abc)) TimedAnimation._stop(self) pass def _draw_frame(self, framedata): margin = 2 while(len(self.addedData) > 0): self.y = np.roll(self.y, -1) self.y[-1] = self.addedData[0] del(self.addedData[0]) self.line1.set_data(self.n[ 0 : self.n.size - margin ], self.y[ 0 : self.n.size - margin ]) self.line1_tail.set_data(np.append(self.n[-10:-1 - margin], self.n[-1 - margin]), np.append(self.y[-10:-1 - margin], self.y[-1 - margin])) self.line1_head.set_data(self.n[-1 - margin], self.y[-1 - margin]) self._drawn_artists = [self.line1, self.line1_tail, self.line1_head] ''' End Class ''' # You need to setup a signal slot mechanism, to # send data to your GUI in a thread-safe way. # Believe me, if you don't do this right, things # go very very wrong.. class Communicate(QtCore.QObject): data_signal = QtCore.pyqtSignal(float) ''' End Class ''' def dataSendLoop(addData_callbackFunc): # Setup the signal-slot mechanism. mySrc = Communicate() mySrc.data_signal.connect(addData_callbackFunc) # Simulate some data n = np.linspace(0, 499, 500) y = 50 + 25*(np.sin(n / 8.3)) + 10*(np.sin(n / 7.5)) - 5*(np.sin(n / 1.5)) i = 0 while(True): if(i > 499): i = 0 time.sleep(0.1) mySrc.data_signal.emit(y[i]) # <- Here you emit a signal! i += 1 ### ### if __name__== '__main__': app = QtGui.QApplication(sys.argv) QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique')) myGUI = CustomMainWindow() sys.exit(app.exec_()) '''''' Just try it out. Copy-paste this code in a new python-file, and run it. You should get a beautiful smooth live graph: [![enter image description here](http://i.stack.imgur.com/lAB3N.png)](http://i.stack.imgur.com/lAB3N.png)