text
stringlengths
226
34.5k
Getting "AttributeError" while printing stopwords from nltk toolbox in python Question: from nltk import stopwords print(stopwords.words('english')) Second line is giving error which is Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> print(stopwords.words('english')) AttributeError: 'module' object has no attribute 'words' I have installed nltk using pip install nltk then i downloaded stopwords using command nltk.download('stopwords'), after unzipping that "stopwords" folder I placed that in python34/lib/site-packeges/nltk/stopwords How can i get stopwords from this? Answer: As mentioned in the comment, try from nltk.corpus import stopwords That should fix the error.
Django AttributeError: 'CharField' object has no attribute 'model' after migration Question: **Note: I'm using Django 1.9 and Python 3.4.2** I'm getting a strange error when I make a change to one of my models, make a migration (`./manage.py makemigrations`) and then try to apply the migration (`./manage.py migrate`). There is a similar question [here](http://stackoverflow.com/questions/28743021/attributeerror-charfield- object-has-no-attribute-model), but there is no answer, people are asking for more information and the only possible solution in the comments seems to be delete the migration files and start again - but I would really like to find out what is causing this issue and how to fix it properly. ### The error: Operations to perform: Apply all migrations: contenttypes, admin, auth, blog, sessions Running migrations: Rendering model states... DONE Applying blog.0004_auto_20160103_1321...Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 482, in alter_field old_db_params, new_db_params, strict) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 564, in _alter_field old_default = self.effective_default(old_field) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 210, in effective_default default = field.get_db_prep_save(default, self.connection) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save prepared=False) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 720, in get_db_prep_value value = self.get_prep_value(value) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1112, in get_prep_value return self.to_python(value) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1108, in to_python return smart_text(value) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/utils/encoding.py", line 42, in smart_text return force_text(s, encoding, strings_only, errors) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/utils/encoding.py", line 76, in force_text s = six.text_type(s) File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 188, in __str__ model = self.model AttributeError: 'CharField' object has no attribute 'model' ### My models before the change: from django.db import models from django.utils import timezone class Category(models.Model): title = models.CharField(max_length=100, unique=True) def __str__(self): return self.title def number_of_articles(self): articles = Article.objects.filter(categories__pk=self.id) return articles.count() class Article(models.Model): title = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True, default=title) pub_date = models.DateTimeField('date published', default=timezone.now) intro_text = models.TextField(blank=True) body_copy = models.TextField(blank=False) votes_helpful = models.IntegerField(default=0, blank=True) votes_unhelpful = models.IntegerField(default=0, blank=True) categories = models.ManyToManyField(Category, blank=True) class Meta: ordering = ('-pub_date',) def __str__(self): return self.title def has_votes(self): total_num_votes = self.votes_helpful + self.votes_unhelpful return total_num_votes > 0 ### The change to my model: slug = models.SlugField(max_length=255, blank=True) The change is that I have removed `unique=True, default=title` from **Article** and added `blank=False`. ### My migration file: # -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-03 13:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0003_auto_20151230_1643'), ] operations = [ migrations.AlterField( model_name='article', name='slug', field=models.SlugField(blank=True, max_length=255), ), ] Answer: slug = models.SlugField(max_length=255, unique=True, default=title) This sets the default for your `slug` field to _a`CharField` instance_. That's not correct, I'm surprised this didn't give you an error earlier on. I think the only solution is to change the migration file that introduced the the old default, and change the default to a valid value.
Read in a CSV file in lower case with Python Question: I'm reading a CSV file into a namedtuple as so: import csv from collections import namedtuple #So we can handle bad CSV files gracefully def unfussy_reader(reader): while True: try: yield next(reader.lower()) # This is a bad row that has an error in it (csv.Error) # Alternately it may be a line that doesn't map to the structure we've been given (TypeError) except (csv.Error, TypeError): pass continue # Create the CSV reader object csv_reader = csv.reader(file_stream, delimiter=' ', quotechar='"', escapechar='^') # Set up the named tuple csvline = namedtuple('csv_line', 'field1, field2, field3') # Create the named tuple mapping object map_to_tuple = map(csvline._make, csv_reader) for line in unfussy_reader(map_to_tuple): # do stuff This works well, but my problem is - I want all of the content of the CSV to be read in lower-case. As per [this question](http://stackoverflow.com/questions/1801668/convert-a-python-list- with-strings-all-to-lowercase-or-uppercase), a simple lambda would do it: `map(lambda x:x.lower(),["A","B","C"])` but I can't find anywhere to put it before the data ends up in the tuple (and thus unchaneable). Is there a way to do this within this structure (Python 3.5)? Answer: You can apply the `lower` transform to the stream before you create a CSV reader for it. lower_stream = (line.lower() for line in file_stream) csv_reader = csv.reader(lower_stream, delimiter=' ', quotechar='"', escapechar='^') The parentheses around the `lower_stream` assignment target designate a [generator expression](https://www.python.org/dev/peps/pep-0289/). It will not use up `file_stream` and will not pull all of `file_stream` into memory.
Convert excel-file to pdf-file Question: I have used openpyxl to autogenerate 154 excel files. Everything worked like a charm! Now I need to convert the excel-files into pdf-files. Can this be done automatically or do I need to do it manually? Note: It is important that I have the option to define margins and horizontal orientation. A solution in python in preferred. I'm using OS X or Ubuntu. Answer: I have solved the issue by using a combination of Java, [UNO, and OpenOffice](https://www.openoffice.org/udk/). Thank you lazy1 for your advise. For any interested peers: My implementation can be found [on GitHub](https://github.com/Vingtoft/UNO-excel-to-pdf-converter)
Why I get error from pip installing getch? Question: I'm doing a small file checker, and I need to do a (character pressed?) command. So I used getch. I get this error when trying to pip install it: Command "c:\python27\python.exe -c "import setuptools, tokenize;__file__='c:\\us ers\\manolo\\appdata\\local\\temp\\pip-build-ehxrw3\\getch\\setup.py';exec(compi le(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __fil e__, 'exec'))" install --record c:\users\manolo\appdata\local\temp\pip-flekfr-re cord\install-record.txt --single-version-externally-managed --compile" failed wi th error code 1 in c:\users\manolo\appdata\local\temp\pip-build-ehxrw3\getch Can someone say to me how to fix this? Also, I have python 2.7 running on win32, windows 7. Answer: You can change getch for msvcrt, and it's pre-installed on Windows.
3-Layer Neural Network Getting Stuck in Local Minima Question: I've programmed a 3-Layer Neural Network in Python, based on [this tutorial](http://iamtrask.github.io/2015/07/12/basic-python-network/), to play Rock, Paper, Scissors, with sample data using _-1 for rock_ , _0 for paper_ , and _1 for scissors_ , and similar arrays to that which are in the tutorial. My function seems to be getting stuck in a relative minima with every run, and I'm looking for a way to to remedy this. The program is below. #math module import numpy as np #sigmoid function converts numbers to percentages(between 0 and 1) def nonlin(x, deriv = False): if (deriv == True): #sigmoid derivative is just return x*(1-x)#output * (output - 1) return 1/(1+np.exp(-x)) #print the sigmoid function #input data: using MOCK RPS DATA, -1:ROCK, 0:PAPER, 1:SCISSORS input_data = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1], [-1, 1, -1]]) #also for training output_data = np.array([[1], [0], [-1], [1]]) #random numbers to not get stuck in local minima for fitness np.random.seed(1) #create random weights to be trained in loop firstLayer_weights = 2*np.random.random((3, 4)) - 1 #size of matrix secondLayer_weights = 2*np.random.random((4, 1)) - 1 for value in xrange(60000): # loops through training #pass input through weights to output: three layers layer0 = input_data #layer1 takes dot product of the input and weight matrices, then maps them to sigmoid function layer1 = nonlin(np.dot(layer0, firstLayer_weights)) #layer2 takes dot product of layer1 result and weight matrices, then maps the to sigmoid function layer2 = nonlin(np.dot(layer1, secondLayer_weights)) #check computer predicted result against actual data layer2_error = output_data - layer2 #if value is a factor of 10,000, so six times (out of 60,000), #print how far off the predicted value was from the data if value % 10000 == 0: print "Error:" + str(np.mean(np.abs(layer2_error))) #average error #find out how much to re-adjust weights based on how far off and how confident the estimate layer2_change = layer2_error * nonlin(layer2, deriv = True) #find out how layer1 led to error in layer 2, to attack root of problem layer1_error = layer2_change.dot(secondLayer_weights.T) #^^sends error on layer2 backwards across weights(dividing) to find original error: BACKPROPAGATION #same thing as layer2 change, change based on accuracy and confidence layer1_change = layer1_error * nonlin(layer1, deriv=True) #modify weights based on multiplication of error between two layers secondLayer_weights = secondLayer_weights + layer1.T.dot(layer2_change) firstLayer_weights = firstLayer_weights + layer0.T.dot(layer1_change) As you can see, this section is the data involved: input_data = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1], [-1, 1, -1]]) #also for training output_data = np.array([[1], [0], [-1], [1]]) And the weights are here: firstLayer_weights = 2*np.random.random((3, 4)) - 1 #size of matrix secondLayer_weights = 2*np.random.random((4, 1)) - 1 **It seems that after the first thousand generations, the weights correct with minimal efficiency for the remainder of the compiling, leading me to believe they've reached a relative minima, as shown here:** [![Relative minima point for weights](http://i.stack.imgur.com/868Vy.png)](http://i.stack.imgur.com/868Vy.png) **What is an quick and efficient alternative to rectify this issue?** Answer: One issue with your network is that the output (the value of the elements of `layer2`) can only vary between 0 and 1, because you're using a sigmoid nonlinearity. Since one of your four target values is -1 and the closest possible prediction is 0, there will always be at least 25% error. Here are a few suggestions: 1. Use a one-hot encoding for the outputs: i.e. have three output nodes--one for each of `ROCK`, `PAPER` and `SCISSORS`--and train the network to compute a probability distribution across these outputs (typically using softmax and cross-entropy loss). 2. Make the output layer of your network a linear layer (apply weights and biases, but not a nonlinearity). Either add another layer, or remove the nonlinearity from your current output layer. Other things you could try, but are less likely to work reliably, since really you are dealing with categorical data rather than a continuous output: 3. Scale your data so that all of the outputs in the training data are between 0 and 1. 4. Use a non-linearity that produces values between -1 and 1 (such as tanh).
Extraxt & save all text() with Scrapy Question: I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. To solve this problem I need to use the framework. As an example, take a page <https://en.wikipedia.org/wiki/Main_Page>, thus extract 100 pages without leaving the domain en.wikipedia.org Answer: Simple basic code sample doing what you need. from scrapy import Spider class Foo(Spider): # start urls executed at the beginning # with default callback "parse" start_urls = ["https://en.wikipedia.org/wiki/Main_Page"] name = "basic_spider" def parse(self, response): # use css or xpath selectors to extract text print(response.css("::text").extract()) Save above as spider.py and run it with scrapy runspider spider.py Start with [Scrapy tutorial](http://doc.scrapy.org/en/latest/intro/tutorial.html) if you feel something is not clear or needs improving feel free to improve the docs, they are hosted on github. Of course you must learn [Python first](https://docs.python.org/2/), so start with learning Python if you dont know it already.
Interpolation of 3D data in Python Question: I have data in 3D. I would like to interpolate this data layer by layer (in the plane X, Y) because calculating each layer takes a lot of time. I try to use the interp2D function and loop through the layers but f seems to apply only to the last value of i0. X = np.linspace(10., 15., 21) Y = np.linspace(0.05, 1.85, 10) for i0 in np.arange(N): f = interpolate.interp2d(X, Y, data[:,:,i0], kind='linear') Xnew = np.linspace(10., 15., 41) Ynew = np.linspace(0.05, 1.85, 20) datanew = f(Xnew,Ynew) How can I interpolate each layer of my data? Thanks Answer: > I try to use the interp2D function and loop through the layers but f seems > to apply only to the last value of i0. You are overwriting the value of your interpolant, `f`, on each iteration of your `for` loop, so by the time you have finished looping over `i0` values `f` will correspond only to the last Z-plane of `data`. Using your current approach, you would need to call `f` inside the `for` loop, e.g.: # some example data for test purposes N = 64 data = np.random.randn(10, 21, N) X = np.linspace(10., 15., 21) Y = np.linspace(0.05, 1.85, 10) Xnew = np.linspace(10., 15., 41) Ynew = np.linspace(0.05, 1.85, 20) # initialize output array datanew = np.empty((Ynew.shape[0], Xnew.shape[0], N), data.dtype) for i0 in np.arange(N): f = interpolate.interp2d(X, Y, data[:,:,i0], kind='linear') # fill in this Z-slice datanew[:,:,i0] = f(Xnew,Ynew) * * * You could eliminate the `for` loop by interpolating over all of your Z-planes simultaneously. One way to do this would be using [`scipy.interpolate.RegularGridInterpolator`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html#scipy.interpolate.RegularGridInterpolator): from scipy.interpolate import RegularGridInterpolator Z = np.arange(N) itp = RegularGridInterpolator((Y, X, Z), data, method='linear') grid = np.ix_(Ynew, Xnew, Z) datanew2 = itp(grid) Here I also use [`np.ix_`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ix_.html) to construct an 'open mesh' from the coordinates that you want to interpolate `data` at.
Read pdf page by page Question: I searched for my question and did not get my answer in the two available questions 1. [Extract text per page with Python pdfMiner?](http://stackoverflow.com/questions/12605170/extract-text-per-page-with-python-pdfminer) 2. [PDFMiner - Iterating through pages and converting them to text](http://stackoverflow.com/questions/21113773/pdfminer-iterating-through-pages-and-converting-them-to-text) Basically I want to iterate over each page because I want to select only that page which has a **certain text**. I have used `pyPdf`. It works for almost i can say 90% of the `pdfs` but sometimes it does not extract the information from a page. I have used the below code: import pyPdf extract = "" pdf = pyPdf.PdfFileReader(open('filename.pdf', "rb")) num_of_pages = pdf.getNumPages() for p in range(num_of_pages): ex = pdf.getPage(6) ex = ex.extractText() if re.search(r"to be held (at|on)",ex.lower()): print 'yes' print ex ,"\n" extract = extract + ex + "\n" continue The above code works but sometimes some pages don't get extracted. I also tried using `pdfminer`, but i could not find how to iterate the pdf in it page by page. `pdfminer` returns the entire text of the pdf. I used the below code: def convert_pdf_to_txt(path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = file(path, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos=set() for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): interpreter.process_page(page) text = retstr.getvalue() fp.close() device.close() retstr.close() return text In the above code the text from the pdf comes from the `for` loop for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): interpreter.process_page(page) text = retstr.getvalue() In this how can I iterated on one page at a time. The documentation on `pdfminer` is not understandable. Also there are many versions of the same. So are there any other packages available for my question or can `pdfminer` be used for it? Answer: I know it is not good to answer your own question but i think i may have figured out an answer for this question. I think it is not the best way to do it, but still it helps me. I used a combination of `pypdf` and `pdfminer` The code is as below: import pyPdf from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO path = "filename.pdf" pdf = pyPdf.PdfFileReader(open(path, "rb")) fp = file(path, 'rb') num_of_pages = pdf.getNumPages() extract = "" for i in range(num_of_pages): inside = [i] pagenos=set(inside) rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True text = "" for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): interpreter.process_page(page) text = retstr.getvalue() text = text.decode("ascii","replace") if re.search(r"to be held (at|on)",text.lower()): print text extract = extract + text + "\n" continue There may be a better way to do it, but currently i found out this to be pretty good.
Python 3.4 Tkinter, Understanding code/setting window size Question: I'm trying to make a tkinter GUI using classes, which I'm pretty new to (I have watched all of TNB's tutorials on it), and I'm having some issues with implementing features into my code and understanding it. I'm trying to adapt code I found on this site to get the basic structure and I can't figure out how/why some of it works and how to add some things in. This is my code so far: import tkinter as tk class Application(tk.Tk): # Inheriting tkinter classes etc. def __init__(self): tk.Tk.__init__(self) # Creates window? container = tk.Frame(self) # Creates frame object container.pack(side="top", fill="both", expand=True) # Places container/frame inside window container.grid_rowconfigure(0, weight=1) # ? container.grid_columnconfigure(0, weight=1) # ? self.frames = {} # What does this do? for F in (MenuPage, StartPage, InfoPage, SettingsPage): page_name = F.__name__ # What is __name__ for? frame = F(container, self) self.frames[page_name] = frame # Creating dictionary entries? frame.grid(row=0, column=0, sticky="NSEW") self.show_frame("MenuPage") # Pushes menu page to top when initialised def show_frame(self, page_name): frame = self.frames[page_name] frame.tkraise() # Raises frame to top of stack class MenuPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is the menu page") label.pack(side="top", fill="x", pady=10) # Begins quiz start_btn = tk.Button(self, text="Start", command=lambda : controller.show_frame("StartPage")) start_btn.pack() # Takes user to information page info_btn = tk.Button(self, text="Information", command=lambda: controller.show_frame("InfoPage")) info_btn.pack() # Takes user to settings page settings_btn = tk.Button(self, text="Settings", command=lambda: controller.show_frame("SettingsPage")) settings_btn.pack() # Quits program/closes all GUIs quit_btn = tk.Button(self, text="Quit", command=self.controller.destroy) quit_btn.pack() # First page of quiz, will need to inherit from settings? class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is the start") label.pack(side="top", fill="x", pady=10) class InfoPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is the info page") label.pack(side="top", fill="x", pady=10) # Takes user back to main menu menu_btn = tk.Button(self, text="Go to the menu page", command=lambda: controller.show_frame("MenuPage")) menu_btn.pack() class SettingsPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is the settings page") label.pack(side="top", fill="x", pady=10) # Takes user back to main menu menu_btn = tk.Button(self, text="Go to the menu page", command=lambda: controller.show_frame("MenuPage")) menu_btn.pack() if __name__ == "__main__": # What does this do? app = Application() app.mainloop() (I want to add in functionality for the quit button where it actually closes the whole GUI program. So far I have tried various methods of using .destroy() as the button command and just the quit command, but I'm having no luck. I also tried having the destroy function inside the Application() class, and calling it from the command but that didn't work either. I'm not sure whether I'm using it right or not.) - Fixed, thanks to Bryan Oakley and furas. Another thing I have no clue how to do is changing the size parameters of the windows, so that every window is say (500x200). This is easy when not using classes, but I don't even know where to begin when using them, and having multiple frames. I have also marked/labelled some lines of code that it would be great if someone could explain to me. There has been a post before going through some parts of the original code explaining, but they only addressed specific parts requested by that user. Thanks in advance :) (Hoping all the indentation has copied over right now) Answer: This code was designed so that the main program (the "controller") is the central point for controlling the GUI. That is why `self` (the application itself) is passed in as the `controller` parameter to the other frames. Thus, to call any function on the controller from one of the other pages you would call `self.controller.destroy()`. To associate that with the quit button you would do it like this: quit_btn = tk.Button(self, text="Quit", command=self.controller.destroy) quit_btn.pack() Note: it's a very bad habit to create widgets and lay them out -- calling `pack` or `grid` or `place` \-- in a single statement. You should always separate the creation of widgets from arranging them on the screen. When you do it in a single statement, your variable will always be set to `None`, which is useless.
python checking surrounding points list of lists index out of range Question: I'm working on a school project and i'm trying to go through list of lists containing numbers. I'm trying to check all 8 surrounding "block" but i'm getting index out of range exception filling the list: for i in range(0, self.sizeX): temp = [] for j in range(0, self.sizeY): temp.append(random.randint(0, 100)) self.map.append(temp) checking the surrounding def check(self, i, j): count = 0 if j-1 >= 0 & self.map[i][j-1] > 50: count += 1 if (j+1) < len(self.map[i]) & self.map[i][j+1] > 50: count += 1 if i-1 >= 0 & self.map[i-1][j] > 50: count += 1 if i+1 < self.sizeX & self.map[i+1][j] > 50: count += 1 if i-1 >= 0 & j-1 >= 0 & self.map[i-1][j-1] > 50: count += 1 if i+1 < self.sizeX & j-1 >= 0 & self.map[i+1][j-1] > 50: count += 1 if i-1 >= 0 & j+1 < self.sizeY & self.map[i-1][j+1] > 50: count += 1 if i+1 < self.sizeX & j+1 < self.sizeY & self.map[i+1][j+1] > 50: count += 1 return count it looks like the conditions which check >=0 work but the once which check the size limit don't btw i had this exact thing working in php with no problem Answer: Your conditions seem to be correct, apart from substituting `&` (bitwise and) for `and` (logical and). I also suggest pulling the tests out as variables; it helps make your code easier to read. Also note that you are using columnar indexing, ie `map[x][y]`; it is more common to use row-aligned indexing ie `map[y][x]`. It is not "wrong" per se, but may be a bit clumsier to work with. from random import randint class Map: def __init__(self, width, height): self.width = width self.height = height self.map = [[randint(0, 100) for y in range(height)] for x in range(width)] def neighbor_fn(self, i, j, fn=lambda x: x > 50): left = i - 1 right = i + 1 above = j - 1 below = j + 1 do_left = left >= 0 do_right = right < self.width do_above = above >= 0 do_below = below < self.height return ( (do_left and do_above and fn(self.map[left][above])) + (do_above and fn(self.map[i][above])) + (do_right and do_above and fn(self.map[right][above])) + (do_left and fn(self.map[left][j])) + (do_right and fn(self.map[right][j])) + (do_left and do_below and fn(self.map[left][below])) + (do_below and fn(self.map[i][below])) + (do_right and do_below and fn(self.map[right][below])) )
Error while installing oursql in virtualenv Question: When I try to install oursql under virtual environment using pip install oursql I get following error: Collecting oursql Using cached oursql-0.9.3.1.tar.bz2 Building wheels for collected packages: oursql Running setup.py bdist_wheel for oursql Complete output from command /home/raghav/janpro/release_1/venv/bin/python2 -c "import setuptools;__file__='/tmp/pip-build-ndxBoY/oursql/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpe4k7ejpip-wheel-: cython not found, using previously-cython'd .c file. running bdist_wheel running build running build_ext warning: no usable mysql_config and no _winreg module to try; hopefully you have usable CFLAGS/LDFLAGS set. building 'oursql' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/oursqlx x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c oursqlx/oursql.c -o build/temp.linux-x86_64-2.7/oursqlx/oursql.o oursqlx/oursql.c:4:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for oursql Failed to build oursql Installing collected packages: oursql Running setup.py install for oursql Complete output from command /home/raghav/janpro/release_1/venv/bin/python2 -c "import setuptools, tokenize;__file__='/tmp/pip-build-ndxBoY/oursql/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-awH5dT-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/raghav/janpro/release_1/venv/include/site/python2.7/oursql: cython not found, using previously-cython'd .c file. running install running build running build_ext warning: no usable mysql_config and no _winreg module to try; hopefully you have usable CFLAGS/LDFLAGS set. building 'oursql' extension x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c oursqlx/oursql.c -o build/temp.linux-x86_64-2.7/oursqlx/oursql.o oursqlx/oursql.c:4:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/home/raghav/janpro/release_1/venv/bin/python2 -c "import setuptools, tokenize;__file__='/tmp/pip-build-ndxBoY/oursql/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-awH5dT-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/raghav/janpro/release_1/venv/include/site/python2.7/oursql" failed with error code 1 in /tmp/pip-build-ndxBoY/oursql Then I installed MySQL C++ connectors sudo apt-get install libmysqlcppconn-dev but still error was coming. So I tried sudo pip install oursql and got following output: The directory '/home/raghav/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/raghav/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting oursql Downloading oursql-0.9.3.1.tar.bz2 (119kB) 100% |████████████████████████████████| 122kB 986kB/s Installing collected packages: oursql Running setup.py install for oursql Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-GbfPiA/oursql/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-avSCME-record/install-record.txt --single-version-externally-managed --compile: cython not found, using previously-cython'd .c file. running install running build running build_ext warning: no usable mysql_config and no _winreg module to try; hopefully you have usable CFLAGS/LDFLAGS set. building 'oursql' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/oursqlx x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c oursqlx/oursql.c -o build/temp.linux-x86_64-2.7/oursqlx/oursql.o oursqlx/oursql.c:4:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-GbfPiA/oursql/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-avSCME-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-GbfPiA/oursql What is going wrong? I am unable to find out. Answer: the directory '/home/raghav/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. I think you installed some library into your virtualenv using `sudo pip`. So now some files are owned by the `root` user and your user cannot write there. You never should use virtualenv as root. If you have a `requirements.txt` file I think the easiest way is to create a new virtualenv and install everything again. If you don't want/can't do this try to change the permissions with `chown`
How to give path for file passed through command line Question: I got answer for how to pass file as argument here [How to access variables from file passed through command line](http://stackoverflow.com/questions/34596823/how-to-access-variables- from-file-passed-through-command-line) But I am asking separately since don't wanna mix two. I am able to access variables in passed file as `__import__(sys.argv[1])` and called `python test.py config`. But can I call config.py file by giving pythonpath? e/g/ `python test.py ~/Desktop/config` or `PYTHONPATH='~/Desktop/' python test.py config`? Because if I do this I get `no module error`. Answer: You're trying to import a python module using the `__import__` call. It only accepts the module name. If you need to add a directory to the `PYTHONPATH`, you can add it to `sys.path` and then import the module: #File: ~/Projects/py/main.py import sys python_path = sys.argv[1] module_name = sys.argv[2] sys.path.insert(1, python_path) print "Importing {} from {}".format(module_name, python_path) __import__(module_name) Now I created another file named `masnun.py` on `~/Desktop`: # File: ~/Desktop/masnun.py print "Thanks for importing masnun.py" Now I try to run `main.py` like this: python main.py ~/Desktop masnun So I am passing the Python path as `argv[1]` and the module name as `argv[2]`. Now it works. I get this output: [![enter image description here](http://i.stack.imgur.com/1AZ0o.png)](http://i.stack.imgur.com/1AZ0o.png)
how can I convert a binary float to a base 10 float and vice versa? Question: I have a binary float like '10.1' and want to convert it to a decimal float. Then I want to do some operations on it and convert it back to a binary float. Are there builtins in python 2 to do this? If not, what is the shortest (in bytes) way to do this? Answer: There's no built-in way to do this for binary (though there is from [hexadecimal](https://docs.python.org/2/library/stdtypes.html#float.fromhex)). The easiest way would be to strip out the `.`, parse as an integer, and scale appropriately: import math x = "10.1" p = len(x) - x.index(".") - 1 i = int(x.replace(".",""),2) math.ldexp(i,-p) This assumes your string consists of nothing but `0`s, `1`s and a single `.` (i.e. no whitespace or exponent).
How to return to my main program from an imported function in python? Question: I'm trying to go back to my main program from an imported function. My situation is something like this: main program || \/ imported function || \/ imported function (2) now I want to go back from the second imported function to the main program. main program <=========\\ || || \/ || imported function || || || \/ || imported function (2) ==// my program looks like this: import pygame, sys from pygame import* def main(): while True: events = pygame.event.get() for event in events: if event.type == pygame.MOUSEBUTTONUP: import function my function looks like this: print('something') #do stuff import function2 my second function is almost the same: print('something') #do stuff ''' now I want to go back to the main program ''' Answer: I'm guessing that u mean your are calling a function in your main program that is from your imported code, the subroutine will carry out and then your code in the main program will continue running for example if i import the time libary then call a function for example, var = datetime.datetime.today().weekday() That will return an integer that will represent the day of the week and then the code after that in the main program where i have called the time subroutine will carry on running. To get more imported functions just call them(first time answering a question so sorry in advance).
Python connect o Access error Question: I am using Python 2.7.8 32-bit to call MS Access 2007. Below is the code I use: import sys import pypyodbc import os import pyodbc conn = pyodbc.connect(r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=D:\Access\Geocoding.accdb;") cnxn = pyodbc.connect(conn) I get the error message: Traceback (most recent call last): File "D:\Access\get_Access.py", line 13, in conn = pyodbc.connect(r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=D:\Access\Geocoding.accdb;") Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I searched online for a while and couldn't find anything wrong with the code. Answer: I solved the problem. The Access database is created in Access 2013. I am try to use Python to connect it in Access 2007, that is the problem. I created a Access 2007 database and copy all the data into it. Python can connect to it without problem.
Python - Requests module, getting the domain name? Question: I'm trying to build a web crawler using the `requests` module, and basically what I want it to do is go to a webpage, get all the `href`'s and then write them to a text file. So far my code looks like this: def getLinks(url): response = requests.get(url).text soup = BeautifulSoup(response,"html.parser") for link in soup.findAll("a"): print("Link:"+str(link.get("href"))) which work on some sites but the one that I'm trying to use it on the `href`'s isn't full domain names like "www.google.com" instead they're like...paths to a directory that redirects to the link? looks like this: href="/out/101" and if i try to write that in to a file it looks like this 1. /out/101 2. /out/102 3. /out/103 4. /out/104 which isn't really what I wanted. soo how do I go about getting the domain names from these links? Answer: This means that the URLs are _relative_ to the current. To get the full URLs, use [`urljoin()`](https://docs.python.org/2/library/urlparse.html#urlparse.urljoin): from urlparse import urljoin for link in soup.findAll("a"): full_url = urljoin(url, link.get("href")) print("Link:" + full_url)
MySQL export to CSV file as UTF-8 via Python script Question: I'm able to export a MySQL table into a CSV file via Python `csv` module but there are no utf-8 characters. (example: `????` chars insted of `ąöę`). The table data is in utf-8 format (phpMyAdmin let me see correct data). I found some information that in Python all data should be decoded in utf-8 and then encoded into CSV in utf-8 via for example `unicodewritter` (because the native `csv` module doesn't support Unicode correctly). I tried a lot but no success. Question : Is there any example script to export MySQL database in utf-8 to CSV file in utf-8 format in Python? I use ubuntu 14.04 and there is a problem with mysql.connector so I use MySQLdb with Gord Thompson code : # -*- coding: utf-8 -*- import csv import MySQLdb from UnicodeSupportForCsv import UnicodeWriter import sys reload(sys) sys.setdefaultencoding('utf8') #sys.setdefaultencoding('Cp1252') conn = MySQLdb.Connection(db='sampledb', host='localhost', user='sampleuser', passwd='samplepass') crsr = conn.cursor() crsr.execute("SELECT * FROM rfid") with open(r'test.csv', 'wb') as csvfile: uw = UnicodeWriter( csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in crsr.fetchall(): uw.writerow([unicode(col) for col in row]) Error still exist : UnicodeDecodeError: 'utf8' codec can't decode byte 0xf3 in position 2: invalid continuation byte Answer: This works for me with Python 2.7.5 and MySQL Connector/Python 2.0.4: # -*- coding: utf-8 -*- import csv import mysql.connector from UnicodeSupportForCsv import UnicodeWriter conn = mysql.connector.connect( host='localhost', port=3307, user='root', password='whatever', database='mydb') crsr = conn.cursor() crsr.execute("SELECT * FROM vocabulary") with open(r'C:\Users\Gord\Desktop\test.csv', 'wb') as csvfile: uw = UnicodeWriter( csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in crsr.fetchall(): uw.writerow([unicode(col) for col in row]) The `UnicodeWriter` class is taken directly from the last example on the [documentation page for the csv module](https://docs.python.org/2/library/csv.html), which I stored in a file named "UnicodeSupportForCsv.py": import csv, codecs, cStringIO class UTF8Recoder: """ Iterator that reads an encoded stream and reencodes the input to UTF-8 """ def __init__(self, f, encoding): self.reader = codecs.getreader(encoding)(f) def __iter__(self): return self def next(self): return self.reader.next().encode("utf-8") class UnicodeReader: """ A CSV reader which will iterate over lines in the CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): f = UTF8Recoder(f, encoding) self.reader = csv.reader(f, dialect=dialect, **kwds) def next(self): row = self.reader.next() return [unicode(s, "utf-8") for s in row] def __iter__(self): return self class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row)
Python problems with background image Question: I've been trying to insert a background image to python in pygame, I'm a beginner in pygame and I know how to do some simple tasks with pygame, however, when I try to add an image to the background, I'm kind of lost on this, I've been trying to apply this on a tutorial I found on the internet but no luck. Here is the code: import pygame, random, sys from pygame.locals import * TEXTCOLOR = (255, 255, 255) screen = pygame.display.set_mode([1280, 780]) FPS = 60 BADDIEMINSIZE = 18 BADDIEMAXSIZE = 70 BADDIEMINSPEED = 2 BADDIEMAXSPEED = 12 ADDNEWBADDIERATE = 1 PLAYERMOVERATE = 3 def terminate(): pygame.quit() sys.exit() def waitForPlayerToPressKey(): while True: for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYDOWN: if event.key == K_ESCAPE: # pressing escape quits terminate() return def playerHasHitBaddie(playerRect, baddies): for b in baddies: if playerRect.colliderect(b['rect']): return True return False def drawText(text, font, surface, x, y): textobj = font.render(text, 1, TEXTCOLOR) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) # set up pygame, the window, and the mouse cursor pygame.init() mainClock = pygame.time.Clock() windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Dodger') pygame.mouse.set_visible(False) # set up fonts font = pygame.font.SysFont(None, 48) # set up sounds gameOverSound = pygame.mixer.Sound('gameover.wav') # set up images playerImage = pygame.image.load('player.png') playerRect = playerImage.get_rect() baddieImage = pygame.image.load('baddie.png') background_image = pygame.image.load("background.png") .convert() # Copy image to screen screen.blit(background_image, background_position) # show the "Start" screen drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)) drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50) pygame.display.update() waitForPlayerToPressKey() topScore = 0 while True: # set up the start of the game baddies = [] score = 0 playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50) moveLeft = moveRight = moveUp = moveDown = False reverseCheat = slowCheat = False baddieAddCounter = 0 while True: # the game loop runs while the game part is playing score += 1 # increase score for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYDOWN: if event.key == ord('z'): reverseCheat = True if event.key == ord('x'): slowCheat = True if event.key == K_LEFT or event.key == ord('a'): moveRight = False moveLeft = True if event.key == K_RIGHT or event.key == ord('d'): moveLeft = False moveRight = True if event.key == K_UP or event.key == ord('w'): moveDown = False moveUp = True if event.key == K_DOWN or event.key == ord('s'): moveUp = False moveDown = True if event.type == KEYUP: if event.key == ord('z'): reverseCheat = False score = 0 if event.key == ord('x'): slowCheat = False score = 0 if event.key == K_ESCAPE: terminate() if event.key == K_LEFT or event.key == ord('a'): moveLeft = False if event.key == K_RIGHT or event.key == ord('d'): moveRight = False if event.key == K_UP or event.key == ord('w'): moveUp = False if event.key == K_DOWN or event.key == ord('s'): moveDown = False if event.type == MOUSEMOTION: # If the mouse moves, move the player where the cursor is. playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery) # Add new baddies at the top of the screen, if needed. if not reverseCheat and not slowCheat: baddieAddCounter += 1 if baddieAddCounter == ADDNEWBADDIERATE: baddieAddCounter = 0 baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE) newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize), 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)), } baddies.append(newBaddie) # Move the player around. if moveLeft and playerRect.left > 0: playerRect.move_ip(-1 * PLAYERMOVERATE, 0) if moveRight and playerRect.right < WINDOWWIDTH: playerRect.move_ip(PLAYERMOVERATE, 0) if moveUp and playerRect.top > 0: playerRect.move_ip(0, -1 * PLAYERMOVERATE) if moveDown and playerRect.bottom < WINDOWHEIGHT: playerRect.move_ip(0, PLAYERMOVERATE) # Move the mouse cursor to match the player. pygame.mouse.set_pos(playerRect.centerx, playerRect.centery) # Move the baddies down. for b in baddies: if not reverseCheat and not slowCheat: b['rect'].move_ip(0, b['speed']) elif reverseCheat: b['rect'].move_ip(0, -5) elif slowCheat: b['rect'].move_ip(0, 1) # Delete baddies that have fallen past the bottom. for b in baddies[:]: if b['rect'].top > WINDOWHEIGHT: baddies.remove(b) # Draw the game world on the window. windowSurface.fill(BACKGROUNDCOLOR) # Draw the score and top score. drawText('Score: %s' % (score), font, windowSurface, 10, 0) drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40) # Draw the player's rectangle windowSurface.blit(playerImage, playerRect) # Draw each baddie for b in baddies: windowSurface.blit(b['surface'], b['rect']) pygame.display.update() # Check if any of the baddies have hit the player. if playerHasHitBaddie(playerRect, baddies): if score > topScore: topScore = score # set new top score break mainClock.tick(FPS) # Stop the game and show the "Game Over" screen. gameOverSound.play() drawText('You lose', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)) drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50) pygame.display.update() waitForPlayerToPressKey() gameOverSound.stop() I know what the WINDOWWIDTH is not defined error is but I'm stuck on adding background images,My goal is to be able to insert background images on my sample game. Please help Me! I would greatly appreciate assistance on this.The link to the tutorial is <http://programarcadegames.com/index.php?chapter=bitmapped_graphics_and_sound>. Answer: You have to `blit` background image in mainloop (`while True`) You can blit it in place of # Draw the game world on the window. windowSurface.fill(BACKGROUNDCOLOR) (which removes all elements from screen). So you get: # Draw the game world on the window. screen.blit(background_image, background_position) # Draw the score and top score. drawText('Score: %s' % (score), font, windowSurface, 10, 0) * * * by the way: you forgot to assign value to `background_position`. * * * You have all this information in your tutorial in `11.5 Full Listing`
Reference Excel in Python Question: I am writing a python code for beam sizing. I have an Excel workbook from AISC that has all the data of the shapes and other various information on the cross-sections. I would like to be able to reference data in particular cells in this Excel workbook in my python code. For example if the width of rectangle is 2in and stored in cell A1 and the height is 10in and stored in cell B1 I want to write a code in python that somehow pulls in cell A1 and B1 and multiply them. I do not need to export back into excel I just want to make python do all the work and use excel purely as reference material. Thank you in advance for all your advice and input!! Answer: Try `pandas` as well...might be easier to work with than lists in this case **DATA** : Width Height 4 2 4 4 1 1 4 5 **Code** import pandas as pd #read the file beam = pd.read_csv('cross_section.csv') beam['BeamSize'] = beam['Width']*beam['Height'] #do your calculations **Output** : >>> beam Width Height BeamSize 0 4 2 8 1 4 4 16 2 1 1 1 3 4 5 20 4 2 2 4 You can slice and dice the data as you wish. For eg, lets say you want the fifth beam : >>> beam.ix[4] Width 2 Height 2 BeamSize 4 Name: 4, dtype: int64 Check this for more info: <http://pandas.pydata.org/pandas-docs/stable/> You can read directly from excel as well..
Reading and Writing data in CSV files in Python Question: I am new to Python and I am having some problems with CSV files in Python. Please help me out 1. How do I open and read csv files in Python which are present in some other directory? I know we can do import csv f = open('attendees1.csv') As long as my program file and csv file is in the same directory. But how do I provide a link to the csv file sitting in another directory? 2. I have a list with multiple rows and columns, how do I transfer this data to a csv file and save it down in a particular location? Please help me out Answer: First argument of [`open()`](https://docs.python.org/3/library/functions.html#open) is file, which can be an absolute path like `C:\Program Files\file.csv` or a relative one like `../../file.csv` here `..` refers to the directory above the current directory and `.` refers to the current directory. import csv with open('../path/to/file.csv', 'w') as f: csv_writer = csv.writer(f) csv_writer.writerows(your_row_data) Where `your_row_data` is a list of lists.
Unable to send email from python Question: I am using the following code to send email from python program in localhost, import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText me = "[email protected]" you = "[email protected]" msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) s = smtplib.SMTP('localhost',5000) s.sendmail(me, you, msg.as_string()) s.quit() This code is from python documentation. When I run this code, it is running continuously but no email is sent. I would like to know, do I have to make some other configurations anywhere else other than this code. I am not seeing any error. I am using `python 2.7` This is given as a solution in [Sending HTML email using Python](http://stackoverflow.com/a/882770/5039470) Answer: It seems that you're using a gmail id. Now, the SMTP server is not your tornado server. it is the server of the email provider. You can search online for the smtp settings for the gmail server and get the following: * Server name : smtp.gmail.com * Server port for SSL : 465 * Server port for TLS : 587 I've gotten them from <http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm> Also, you need to ensure you do not enable gmail's 2 step authentication when doing this, otherwise it will fail. Also, gmail specifically may require you to send other things like ehlo and starttls. You can find a previous answer with a complete example here : [How to send an email with Gmail as provider using Python?](http://stackoverflow.com/questions/10147455/how-to-send-an- email-with-gmail-as-provider-using-python) import smtplib gmail_user = user gmail_pwd = pwd FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """\From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, message) server.close() print 'successfully sent the mail' except: print "failed to send mail"
How to plot two values as a histogram using Python script? Question: I have to plot two length of the values in histogram using python script. File=[1,2,3] File1=[3,4,5,6] files=len(File) files1=len(File1) I want to plot the length of the values . The files and files 1 in x axis. The y- axis need to have the count like 0,10,20.... Like the below diagram using python script i need [![enter image description here](http://i.stack.imgur.com/n0bBW.png)](http://i.stack.imgur.com/n0bBW.png) Thanks in Advance Answer: I guess you want a [bar plot](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar) like this: import matplotlib.pyplot as plt plt.bar([0, 1], [files, files1]) plt.show() Check out the [matplotlib examples](http://matplotlib.org/1.4.1/gallery.html) if you want to find out how to format and change labels, axis limits, etc. [![results](http://i.stack.imgur.com/okxWx.png)](http://i.stack.imgur.com/okxWx.png)
How to get xml output in a file with new line using python xml.etree? Question: I am generating xml file using "from xml.etree import ElementTree" and placing the generated output in to a new file "test.xml". The output is getting placed inside the test.xml but there is no new line its a big big line. So, what shall i do to have new line inside "test.xml" . Following is the script: from xml.etree import ElementTree from xml.dom import minidom from lxml import etree def prettify(elem): """Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") top = Element('my_document') comment = Comment('Practising') top.append(comment) child = SubElement(top, 'my_information') childs = SubElement(child,'my_name') childs.text = 'This child contains text.' print prettify(top) file = open("test.xml", 'w') xml.ElementTree(top).write(file) file.close() Answer: Why don't you use the return value of the `prettify`? Writing the return value of the function will solve your problem. ... top = Element('my_document') comment = Comment('Practising') top.append(comment) child = SubElement(top, 'my_information') childs = SubElement(child,'my_name') childs.text = 'This child contains text.' with open("test.xml", 'w') as f: # <-- f.write(prettify(top)) # <--
Is it possible to keep the same window for every class in python's tkinter? Question: I am trying to create a program in tkinter which allows me to open an initial window then to keep it throughout all classes used. For example, if I was to create a button in a window then when I click this button, it would exuecute a method that destroys the widget, and then executes a new class that builds a new screen within the same window, such as text opposed to a button. from tkinter import * class Window1: def __init__(self, master): self.master = master self.label = Button(self.master, text = "Example", command = self.load_new) self.label.pack() def load_new(self): self.label.destroy() ## Code to execute next class class Window2: def __init__(self, master): self.master = master self.label = Label(self.master, text = "Example") self.label.pack() def main(): root = Tk() run = Window1(root) root.mainloop() if __name__ == '__main__': main() I understand this is less practical, but I am curious. Cheers. Answer: `Tk()` creates main window and variable `root` gives you access to this window. You can use `root` as argument for `Window2` and you will have access to main window inside `Window2` from tkinter import * class Window1: def __init__(self, master): # keep `root` in `self.master` self.master = master self.label = Button(self.master, text="Example", command=self.load_new) self.label.pack() def load_new(self): self.label.destroy() # use `root` with another class self.another = Window2(self.master) class Window2: def __init__(self, master): # keep `root` in `self.master` self.master = master self.label = Label(self.master, text="Example") self.label.pack() root = Tk() run = Window1(root) root.mainloop() \-- Probably nobody use another class to create `Label` in place of `Button` ;) \-- **EDIT:** In this example using names `Window1` and `Windows2` is misleading because there is only one window and two classes which use this window. I would rather use names `FirstOwner`, `SecondOwner`
Translate argparse's internal strings Question: How can I translate Python's argparse module strings? For example, when you display the help, it says `"usage: "`, string that is translatable but I don't know how to do it in my program. This is the source code part of `argparse.py`: def _format_usage(self, usage, actions, groups, prefix): if prefix is None: prefix = _('usage: ') I couldn't trace the way to set this prefix, I think this is internal. I don't want to have to append a .mo file to somewhere in the system. Ideally the translation should live in my program directory, or better in the source code. Any help would be much appreciated. Answer: Running the following: import argparse class MyHelpFormatter(argparse.HelpFormatter): def __init__(self, *args, **kwargs): super(MyHelpFormatter, self).__init__(*args, **kwargs) def _format_usage(self, usage, actions, groups, prefix): return super(MyHelpFormatter, self)._format_usage( usage, actions, groups, prefix if prefix else "bla: ") class MyArgumentParser(argparse.ArgumentParser): def __init__(self, *args, **kwargs): kwargs['formatter_class']=MyHelpFormatter super(MyArgumentParser, self).__init__(*args, **kwargs) p = MyArgumentParser(description='Foo') p.add_argument('foo', type=str) print p.parse_args() prints python myargparse.py --help bla: myargparse.py [-h] foo Foo positional arguments: foo optional arguments: -h, --help show this help message and exit `_('usage: ')` references [`gettext`](https://docs.python.org/2/library/gettext.html). In `argparse.py`, at the top, you have: from gettext import gettext as _ You can muck around with `gettext` a bit. Given a `.po` file: msgid "usage: " msgstr "foobar: " You can convert it to a `.mo` file (for example [here](http://po2mo.net/)). Afterwards (where `./foo/LC_MESSAGES/messages.mo` is the result of compiling the `.po`): ~/Desktop> find . -name *mo ./foo/LC_MESSAGES/messages.mo ~/Desktop> cat myargparse2.py import argparse import gettext gettext.bindtextdomain(gettext.textdomain(), '.') p = argparse.ArgumentParser(description='Foo') p.add_argument('foo', type=str) print p.parse_args() ~/Desktop> LANGUAGE=foo python myargparse2.py foobar: myargparse2.py [-h] foo myargparse2.py: error: too few arguments Use your desired languages instead of `foo`.
Python: flip a bit in a float Question: I would like to flip a specific bit in a float in Python. It seems to be quite difficult, because the operand | works only for int. For now I have tried to convert a float into a int: [Get the "bits" of a float in Python?](http://stackoverflow.com/questions/14431170/get-the-bits-of-a- float-in-python) But the proposed solution seems not working for too large float. Answer: Use `struct.pack` and `struct.unpack`. This is tested under Python 3. There may be differences for Python 2, consult the doc. >>> from struct import pack,unpack >>> fs = pack('f',1.0) # pack float ('f') into binary string >>> fs b'\x00\x00\x80?' >>> bval = list( unpack('BBBB', fs)) # use list() so mutable list >>> bval [0, 0, 128, 63] >>> bval[1]=12 # mutate it (byte in middle of mantissa bits) >>> fs = pack('BBBB', *bval) # back to a binary string after mutation >>> fs b'\x00\x0c\x80?' >>> fnew=unpack('f',fs) # and let's look at that slightly altered float value >>> fnew # NB it is a tuple of values, just one in this case (1.0003662109375,) unpack requires the exact right length of string for the format. If you are working along a buffer you can use `unpack_from( fmt, buffer, offset)` where `offset` defaults to 0 and the requirement is that `buffer` is _at least_ long enough.
Modifying built-in function Question: Let's consider any user-defined pythonic class. If I call `dir(obect_of_class)`, I get the list of its attributes: ['__class__', '__delattr__', '__dict__', '__dir__', ... '__weakref__', 'bases', 'build_full_name', 'candidates', ... 'update_name']. You can see 2 types of attributes in this list: * built-in attributes, * user defined. I need to override `__dir__` so, that it will return only user defined attribltes. How I can do that? It is clear, that if in overridden function I call itself, it gives me infinite recursion. So, I want to do somethig like this: def __dir__(self): return list(filter(lambda x: not re.match('__\S*__', x), dir(self))) but evade the infinite recursion. In general, how can I modify a built-in function if I don't want to write it from scratch but want to modify the existing function? Answer: Use [`super`](https://docs.python.org/3/library/functions.html#super) to call parent's implementation of `__dir__`; avoid the recursion: import re class AClass: def __dir__(self): return [x for x in super().__dir__() if not re.match(r'__\S+__$', x)] def method(self): pass * * * >>> dir(AClass()) ['method']
How to expand matrix expression in sympy Question: Hi I'm trying to do a matrix multiplication and expand it afterwards. However, `sympy` does not seem to support expansion of matrix equations. For example Runge-Kutta 4 for matrices: from sympy import init_session init_session() from sympy import * A = MatrixSymbol('A', 3, 3) x = MatrixSymbol('x', 3, 1) dt = symbols('dt') k1 = A*x k2 = A*(x + S(1)/2*k1*dt) k3 = A*(x + S(1)/2*k2*dt) k4 = A*(x + k3*dt) final = dt*S(1)/6*(k1 + 2*k2 + 2*k3 + k4) final.expand() With result Traceback (most recent call last) <ipython-input-38-b3ff67883c61> in <module>() 12 final = dt*1/6*(k1+2*k2+2*k3+k4) 13 ---> 14 final.expand() AttributeError: 'MatMul' object has no attribute 'expand' I hope the expression can be expanded just like the scalar variant: A,x,dt = symbols('A x dt') k1 = A*x k2 = A*(x+k1*dt*S(1)/2) k3 = A*(x+k2*dt*S(1)/2) k4 = A*(x+k3*dt) final = x+dt*(S(1)/6)*(k1+k2+k3+k4) collect(expand((final)),x) With result: x*(A**4*dt**4/24 + A**3*dt**3/8 + A**2*dt**2/3 + 2*A*dt/3 + 1) Is it possible to alter a matrix expression likewise? nicoguaro's answer takes the error away, but expands the the whole expression into one matrix. As illustrated with the scalar example, not what I'm looking for Answer: I think that you can expand Matrix expressions. But what you have is not a matrix but the multiplication of two symbolic matrices (Matsymbols). If you turn your expression to a matrix you can get the expansion you wanted. See the extra line below from sympy import init_session init_session() from sympy import * A = MatrixSymbol('A', 3, 3) x = MatrixSymbol('x', 3, 1) dt = symbols('dt') k1 = A*x k2 = A*(x + S(1)/2*k1*dt) k3 = A*(x + S(1)/2*k2*dt) k4 = A*(x + k3*dt) final = dt*S(1)/6*(k1 + k2 + k3 + k4) Matrix(final).expand()
Python: FFT parallel computing Question: I have a cluster of few PC's with Ubuntu and MPICH server - I use them to parallel computing with C++ and MPI. Now I want to do similar with Python. My question is - is there any easy method to make Fast Fourier Transform on many CPU cores (on many computers)? Example of usage would be nice. Here is method I use on single thread: import numpy as np N=1024 tab=np.random.rand(N,N,N) #declare some matrix in 3d a=np.random.rand(N,N,N) #declare other matrix tab=np.fft.ifftn(a*np.fft.fftn(tab)) It's nice to have multithreaded solution when we have 2^30 numbers... Answer: [MPI4py](http://pythonhosted.org/mpi4py/) in connection with [pyFFTW](https://pypi.python.org/pypi/pyFFTW). FFTW is highly optimized and works well on multiple threads but the interface is a little different than your average FFT as it requires creating 'plans' outright. However, this was just done to optimize out processing of any static twiddle factors and such. Additionally, there are lots of options - forward/reverse, in/out-of-place, int, double, float, etc... See [benchmarks](http://www.fftw.org/speed/Pentium4-3.60GHz-icc/) for more info.
How to embed a plot directly into a Window (python; QT;) Question: I wanna embed a Matplotlib plot directly into a window, QMainWindow. It should be part of my program with a more complex GUI. ;) The only way I found was to add the figure as widget into a QTabWidget. See sample code below. I lost the link to the webpage what inspired me. Is there any way to embed the figure directly into the windows like other elements (buttons, textfield, textarea, ...)? import sys from PyQt4.QtGui import QApplication, QMainWindow, QDockWidget, QVBoxLayout,QTabWidget, QWidget from matplotlib import pyplot from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg a = QApplication(sys.argv) w = QMainWindow() t = QTabWidget(w) Tab1 = QWidget() t.addTab(Tab1, '1st Plot') t.resize(1280, 300) x = [1, 2, 3] Fig1 = pyplot.Figure(); Plot = Fig1.add_subplot(111); Plot.plot(x) Plot.grid(); layout = QVBoxLayout(); layout.addWidget(FigureCanvasQTAgg(Fig1)); Tab1.setLayout(layout); w.showMaximized() sys.exit(a.exec_()) Thank you very much. Answer: `FigureCanvasQtAgg` is just a `QWidget` like any of the other controls you mentioned. The main difference being it doesn't allow you to pass a parent in the constructor like when you write t = QTabWidget(w) You can achieve the same with `FigureCanvasQtAgg` by calling [`setParent`](http://doc.qt.io/qt-4.8/qwidget.html#setParent) canvas = FigureCanvasQtAgg(Fig1) canvas.setParent(w) You can also use `QMainWindow`'s [`setCentralWidget`](http://doc.qt.io/qt-4.8/qmainwindow.html#setCentralWidget) method to add the matplotlib `FigureCanvas` directly to your main window. However, if you want a more complex gui with other controls I don't see any real problems with your current approach. Lastly, you shouldn't really be using `pyplot` when embedding matplotlib. Stick with the object oriented API. Take a look at [this example](http://matplotlib.org/1.4.3/examples/user_interfaces/embedding_in_qt4.html).
Python: How to print my simple poem Question: I would like to know how I could print out sentences using my triplet poem program. My program randomly picks a list of nouns to use. My program: import random def nouns(): nounPersons = ["cow","crowd","hound","clown"]; nounPlace = ["town","pound","battleground","playground"]; rhymes = ["crowned","round","gowned","found","drowned"]; nounPersons2 = ["dog","frog","hog"]; nounPlace2 = ["fog","Prague","smog"]; rhymes2 = ["log","eggnog","hotdog"]; nounList1 = [nounPersons,nounPlace,rhymes] nounList2 = [nounPersons2,nounPlace2,rhymes2] nounsList = [nounList1, nounList2] randomPick = random.choice(nounsList) return(randomPick) verbs = ["walked","ran","rolled","biked","crawled"]; nouns() For example, I could have "The cow walked to the town. But then it was drowned." And just replace the nouns/rhyme(cow, town,drowned) and verb(walked) with my randomizer. Would I use random.randint in some way? I just basically need a general print statement like the example I showed using my randomizer to randomly pick between the nouns/rhymes. Answer: As usual (for me), there may be a more Pythonic approach, but to get what you have working, I did three things: 1. assigned your call to the nouns() function to 'chosen_list' variable. That way the returned 'randomPick' gets used. 2. built in a selection step to get individual words from the lists in 'chosen_list' and your verb list 3. added a final print statement with formatting to assemble the words in to a sentence the code: import random def nouns(): nounPersons = ["cow","crowd","hound","clown"]; nounPlace = ["town","pound","battleground","playground"]; rhymes = ["crowned","round","gowned","found","drowned"]; nounPersons2 = ["dog","frog","hog"]; nounPlace2 = ["fog","Prague","smog"]; rhymes2 = ["log","eggnog","hotdog"]; nounList1 = [nounPersons,nounPlace,rhymes] nounList2 = [nounPersons2,nounPlace2,rhymes2] nounsList = [nounList1, nounList2] randomPick = random.choice(nounsList) return randomPick verbs = ["walked","ran","rolled","biked","crawled"] # this is change 1. chosen_list = nouns() # select single words from lists - this is change 2. noun_subj = random.choice(chosen_list[0]) noun_obj = random.choice(chosen_list[1]) rhyme_word = random.choice(chosen_list[2]) verb_word = random.choice(verbs) # insert words in to text line - this is change 3. print ("The {} {} to the {}. But then it was {}.".format(noun_subj, verb_word, noun_obj, rhyme_word))
Theano simple linear regression runs on CPU instead of GPU Question: I created a simple python script (using Theano) performing linear regression which should be run on GPU. When code starts it says "using gpu device", but (according to the profiler) all operations are CPU-specific (ElemWise, instead of GpuElemWise, no GpuFromHost etc.). I checked the variables, THEANO_FLAGS, everything seems right and I cannot see the catch (especially when Theano tutorials with the same settings are correctly run on GPU :)). Here is the code: # linear regression import numpy import theano import theano.tensor as T input_data = numpy.matrix([[28, 1], [35, 2], [18, 1], [56, 2], [80, 3]]) output_data = numpy.matrix([1600, 2100, 1400, 2500, 3200]) TS = theano.shared(input_data, "training-set") E = theano.shared(output_data, "expected") W1 = theano.shared(numpy.zeros((1, 2))) O = T.dot(TS, W1.T) cost = T.mean(T.sqr(E - O.T)) gradient = T.grad(cost=cost, wrt=W1) update = [[W1, W1 - gradient * 0.0001]] train = theano.function([], cost, updates=update, allow_input_downcast=True) for i in range(1000): train() > * THEANO_FLAGS=cuda.root=/usr/local/cuda > * device=gpu > * floatX=float32 > * lib.cnmem=.5 > * profile=True > * CUDA_LAUNCH_BLOCKING=1 > Output: Using gpu device 0: GeForce GT 650M (CNMeM is enabled) Function profiling ================== Message: /home/mw/Documents/LiClipse Workspace/theano1/test2.py:18 Time in 1000 calls to Function.__call__: 3.348637e-02s Time in Function.fn.__call__: 2.419019e-02s (72.239%) Time in thunks: 1.839781e-02s (54.941%) Total compile time: 1.350801e-01s Number of Apply nodes: 18 Theano Optimizer time: 1.101730e-01s Theano validate time: 2.029657e-03s Theano Linker time (includes C, CUDA code generation/compiling): 1.491690e-02s Import time 2.320528e-03s Time in all call to theano.grad() 8.740902e-03s Time since theano import 0.881s Class --- <% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Class name> 71.7% 71.7% 0.013s 6.59e-06s Py 2000 2 theano.tensor.basic.Dot 12.3% 83.9% 0.002s 3.22e-07s C 7000 7 theano.tensor.elemwise.Elemwise 5.7% 89.6% 0.001s 3.50e-07s C 3000 3 theano.tensor.elemwise.DimShuffle 4.0% 93.6% 0.001s 3.65e-07s C 2000 2 theano.tensor.subtensor.Subtensor 3.6% 97.2% 0.001s 3.31e-07s C 2000 2 theano.compile.ops.Shape_i 1.7% 98.9% 0.000s 3.06e-07s C 1000 1 theano.tensor.opt.MakeVector 1.1% 100.0% 0.000s 2.10e-07s C 1000 1 theano.tensor.elemwise.Sum ... (remaining 0 Classes account for 0.00%(0.00s) of the runtime) Ops --- <% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Op name> 71.7% 71.7% 0.013s 6.59e-06s Py 2000 2 dot 4.0% 75.6% 0.001s 3.65e-07s C 2000 2 Subtensor{int64} 3.5% 79.1% 0.001s 6.35e-07s C 1000 1 InplaceDimShuffle{1,0} 3.3% 82.4% 0.001s 6.06e-07s C 1000 1 Elemwise{mul,no_inplace} 2.4% 84.8% 0.000s 4.38e-07s C 1000 1 Shape_i{0} 2.3% 87.1% 0.000s 4.29e-07s C 1000 1 Elemwise{Composite{((i0 * i1) / i2)}} 2.3% 89.3% 0.000s 2.08e-07s C 2000 2 InplaceDimShuffle{x,x} 1.8% 91.1% 0.000s 3.25e-07s C 1000 1 Elemwise{Cast{float64}} 1.7% 92.8% 0.000s 3.06e-07s C 1000 1 MakeVector{dtype='int64'} 1.5% 94.3% 0.000s 2.78e-07s C 1000 1 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)] 1.4% 95.7% 0.000s 2.53e-07s C 1000 1 Elemwise{Sub}[(0, 1)] 1.2% 96.9% 0.000s 2.24e-07s C 1000 1 Shape_i{1} 1.1% 98.0% 0.000s 2.10e-07s C 1000 1 Sum{acc_dtype=float64} 1.1% 99.1% 0.000s 1.98e-07s C 1000 1 Elemwise{Sqr}[(0, 0)] 0.9% 100.0% 0.000s 1.66e-07s C 1000 1 Elemwise{Composite{((i0 / i1) / i2)}}[(0, 0)] ... (remaining 0 Ops account for 0.00%(0.00s) of the runtime) Apply ------ <% time> <sum %> <apply time> <time per call> <#call> <id> <Apply name> 37.8% 37.8% 0.007s 6.95e-06s 1000 3 dot(<TensorType(float64, matrix)>, training-set.T) 33.9% 71.7% 0.006s 6.24e-06s 1000 14 dot(Elemwise{Composite{((i0 * i1) / i2)}}.0, training-set) 3.5% 75.1% 0.001s 6.35e-07s 1000 0 InplaceDimShuffle{1,0}(training-set) 3.3% 78.4% 0.001s 6.06e-07s 1000 11 Elemwise{mul,no_inplace}(InplaceDimShuffle{x,x}.0, InplaceDimShuffle{x,x}.0) 3.0% 81.4% 0.001s 5.58e-07s 1000 8 Subtensor{int64}(Elemwise{Cast{float64}}.0, Constant{1}) 2.4% 83.8% 0.000s 4.38e-07s 1000 2 Shape_i{0}(expected) 2.3% 86.2% 0.000s 4.29e-07s 1000 12 Elemwise{Composite{((i0 * i1) / i2)}}(TensorConstant{(1, 1) of -2.0}, Elemwise{Sub}[(0, 1)].0, Elemwise{mul,no_inplace}.0) 1.8% 87.9% 0.000s 3.25e-07s 1000 6 Elemwise{Cast{float64}}(MakeVector{dtype='int64'}.0) 1.7% 89.6% 0.000s 3.06e-07s 1000 4 MakeVector{dtype='int64'}(Shape_i{0}.0, Shape_i{1}.0) 1.6% 91.2% 0.000s 3.03e-07s 1000 10 InplaceDimShuffle{x,x}(Subtensor{int64}.0) 1.5% 92.7% 0.000s 2.78e-07s 1000 16 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)](<TensorType(float64, matrix)>, TensorConstant{(1, 1) of ..974738e-05}, dot.0) 1.4% 94.1% 0.000s 2.53e-07s 1000 5 Elemwise{Sub}[(0, 1)](expected, dot.0) 1.2% 95.3% 0.000s 2.24e-07s 1000 1 Shape_i{1}(expected) 1.1% 96.5% 0.000s 2.10e-07s 1000 15 Sum{acc_dtype=float64}(Elemwise{Sqr}[(0, 0)].0) 1.1% 97.6% 0.000s 1.98e-07s 1000 13 Elemwise{Sqr}[(0, 0)](Elemwise{Sub}[(0, 1)].0) 0.9% 98.5% 0.000s 1.72e-07s 1000 7 Subtensor{int64}(Elemwise{Cast{float64}}.0, Constant{0}) 0.9% 99.4% 0.000s 1.66e-07s 1000 17 Elemwise{Composite{((i0 / i1) / i2)}}[(0, 0)](Sum{acc_dtype=float64}.0, Subtensor{int64}.0, Subtensor{int64}.0) 0.6% 100.0% 0.000s 1.13e-07s 1000 9 InplaceDimShuffle{x,x}(Subtensor{int64}.0) ... (remaining 0 Apply instances account for 0.00%(0.00s) of the runtime) Answer: As mentioned in the comments although you have set the `allow_input_downcast` parameter to `True`, but you need to make sure all the data to be assigned to shared variables are in `float32`. As of **Jan. 06, 2016** Theano still **cannot** work with any other data type rather than `float32` to do the computations on GPU, as mentioned [here](http://stackoverflow.com/a/34520841/2838606) in a more details. So you have to have to cast your data into 'float32' format. Therefore, here should be the code you need to use: import numpy import theano import theano.tensor as T input_data = numpy.matrix([[28, 1], [35, 2], [18, 1], [56, 2], [80, 3]]) output_data = numpy.matrix([1600, 2100, 1400, 2500, 3200]) TS = theano.shared(input_data.astype('float32'), "training-set") E = theano.shared(output_data.astype('float32'), "expected") W1 = theano.shared(numpy.zeros((1, 2), dtype = 'float32')) O = T.dot(TS, W1.T) cost = T.mean(T.sqr(E - O.T)) gradient = T.grad(cost=cost, wrt=W1) update = [[W1, W1 - gradient * 0.0001]] train = theano.function([], cost, updates=update, allow_input_downcast=True, profile = True) for i in range(1000): train() train.profile.print_summary() And here will be the profiling result: Message: LearnTheano.py:18 Time in 1000 calls to Function.__call__: 2.642968e-01s Time in Function.fn.__call__: 2.460811e-01s (93.108%) Time in thunks: 1.877530e-01s (71.039%) Total compile time: 2.483290e+01s Number of Apply nodes: 17 Theano Optimizer time: 2.818849e-01s Theano validate time: 3.435850e-03s Theano Linker time (includes C, CUDA code generation/compiling): 2.453926e+01s Import time 1.241469e-02s Time in all call to theano.grad() 1.206994e-02s Class --- <% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Class name> 34.8% 34.8% 0.065s 3.27e-05s C 2000 2 theano.sandbox.cuda.blas.GpuGemm 28.8% 63.5% 0.054s 1.80e-05s C 3000 3 theano.sandbox.cuda.basic_ops.GpuElemwise 12.9% 76.4% 0.024s 2.42e-05s C 1000 1 theano.sandbox.cuda.basic_ops.GpuCAReduce 10.3% 86.7% 0.019s 1.93e-05s C 1000 1 theano.sandbox.cuda.basic_ops.GpuFromHost 7.2% 93.9% 0.014s 1.36e-05s C 1000 1 theano.sandbox.cuda.basic_ops.HostFromGpu 1.8% 95.7% 0.003s 1.13e-06s C 3000 3 theano.sandbox.cuda.basic_ops.GpuDimShuffle 1.5% 97.2% 0.003s 2.81e-06s C 1000 1 theano.tensor.elemwise.Elemwise 1.1% 98.4% 0.002s 1.08e-06s C 2000 2 theano.compile.ops.Shape_i 1.1% 99.5% 0.002s 1.02e-06s C 2000 2 theano.sandbox.cuda.basic_ops.GpuSubtensor 0.5% 100.0% 0.001s 9.96e-07s C 1000 1 theano.tensor.opt.MakeVector ... (remaining 0 Classes account for 0.00%(0.00s) of the runtime) Ops --- <% time> <sum %> <apply time> <time per call> <type> <#call> <#apply> <Op name> 25.3% 25.3% 0.047s 4.74e-05s C 1000 1 GpuGemm{no_inplace} 12.9% 38.1% 0.024s 2.42e-05s C 1000 1 GpuCAReduce{pre=sqr,red=add}{1,1} 12.8% 51.0% 0.024s 2.41e-05s C 1000 1 GpuElemwise{mul,no_inplace} 10.3% 61.3% 0.019s 1.93e-05s C 1000 1 GpuFromHost 9.5% 70.8% 0.018s 1.79e-05s C 1000 1 GpuGemm{inplace} 8.2% 79.0% 0.015s 1.55e-05s C 1000 1 GpuElemwise{Composite{((i0 / i1) / i2)}}[(0, 0)] 7.7% 86.7% 0.014s 1.44e-05s C 1000 1 GpuElemwise{Composite{((i0 * i1) / i2)}}[(0, 1)] 7.2% 93.9% 0.014s 1.36e-05s C 1000 1 HostFromGpu 1.5% 95.4% 0.003s 2.81e-06s C 1000 1 Elemwise{Cast{float32}} 1.1% 96.5% 0.002s 1.02e-06s C 2000 2 GpuSubtensor{int64} 1.0% 97.5% 0.002s 9.00e-07s C 2000 2 GpuDimShuffle{x,x} 0.8% 98.3% 0.002s 1.59e-06s C 1000 1 GpuDimShuffle{1,0} 0.7% 99.1% 0.001s 1.38e-06s C 1000 1 Shape_i{0} 0.5% 99.6% 0.001s 9.96e-07s C 1000 1 MakeVector 0.4% 100.0% 0.001s 7.76e-07s C 1000 1 Shape_i{1} ... (remaining 0 Ops account for 0.00%(0.00s) of the runtime) Apply ------ <% time> <sum %> <apply time> <time per call> <#call> <id> <Apply name> 25.3% 25.3% 0.047s 4.74e-05s 1000 3 GpuGemm{no_inplace}(expected, TensorConstant{-1.0}, <CudaNdarrayType(float32, matrix)>, GpuDimShuffle{1,0}.0, TensorConstant{1.0}) 12.9% 38.1% 0.024s 2.42e-05s 1000 5 GpuCAReduce{pre=sqr,red=add}{1,1}(GpuGemm{no_inplace}.0) 12.8% 51.0% 0.024s 2.41e-05s 1000 13 GpuElemwise{mul,no_inplace}(GpuDimShuffle{x,x}.0, GpuDimShuffle{x,x}.0) 10.3% 61.3% 0.019s 1.93e-05s 1000 7 GpuFromHost(Elemwise{Cast{float32}}.0) 9.5% 70.8% 0.018s 1.79e-05s 1000 16 GpuGemm{inplace}(<CudaNdarrayType(float32, matrix)>, TensorConstant{-9.99999974738e-05}, GpuElemwise{Composite{((i0 * i1) / i2)}}[(0, 1)].0, training-set, TensorConstant{1.0}) 8.2% 79.0% 0.015s 1.55e-05s 1000 12 GpuElemwise{Composite{((i0 / i1) / i2)}}[(0, 0)](GpuCAReduce{pre=sqr,red=add}{1,1}.0, GpuSubtensor{int64}.0, GpuSubtensor{int64}.0) 7.7% 86.7% 0.014s 1.44e-05s 1000 15 GpuElemwise{Composite{((i0 * i1) / i2)}}[(0, 1)](CudaNdarrayConstant{[[-2.]]}, GpuGemm{no_inplace}.0, GpuElemwise{mul,no_inplace}.0) 7.2% 93.9% 0.014s 1.36e-05s 1000 14 HostFromGpu(GpuElemwise{Composite{((i0 / i1) / i2)}}[(0, 0)].0) 1.5% 95.4% 0.003s 2.81e-06s 1000 6 Elemwise{Cast{float32}}(MakeVector.0) 0.8% 96.3% 0.002s 1.59e-06s 1000 0 GpuDimShuffle{1,0}(training-set) 0.7% 97.0% 0.001s 1.38e-06s 1000 2 Shape_i{0}(expected) 0.7% 97.7% 0.001s 1.30e-06s 1000 8 GpuSubtensor{int64}(GpuFromHost.0, Constant{0}) 0.6% 98.3% 0.001s 1.08e-06s 1000 11 GpuDimShuffle{x,x}(GpuSubtensor{int64}.0) 0.5% 98.8% 0.001s 9.96e-07s 1000 4 MakeVector(Shape_i{0}.0, Shape_i{1}.0) 0.4% 99.2% 0.001s 7.76e-07s 1000 1 Shape_i{1}(expected) 0.4% 99.6% 0.001s 7.40e-07s 1000 9 GpuSubtensor{int64}(GpuFromHost.0, Constant{1}) 0.4% 100.0% 0.001s 7.25e-07s 1000 10 GpuDimShuffle{x,x}(GpuSubtensor{int64}.0) ... (remaining 0 Apply instances account for 0.00%(0.00s) of the runtime)
OOP in python (related to scrapy) Question: The question is how to share data between objecs in a safe and maintainable manner. Example: I've build the scrapy application which spawns numerous spiders. Although each spider is connected to separate pipeline object, I need to compare and sort the data between different pipelines (e.g. I need outputs sorted by different item attributes: prices, date etc.), so I need some shared data area. The same applies to spiders themselves (e.g. I need to count maximum total requests). The first implementation used class variables to shared data between between spiders/pipelines and instance variables for each object. class MyPipeline(object): max_price = 0 def process_item(self, item, spider): if item['price'] > max_price : max_price = item['price'] (The actual structures are more complex) Then I thought out that having a bunch of statics is not OOP and the next solution is to have the private class data for each class and use to store values: class MyPipelineData: def __init__(self): self.max_price = 0 class SpidersData: def __init___(self, total_requests, pipeline_data): self.total_requests = total_requests self.pipeline_data = pipeline_data #the shared data between pipelines class MyPipeline(object): pipeline_data = None def process_item(self, item, spider): if _data is None: _data = spider.data.pipeline_data #the shared data between pipelines if item['price'] > _data.max_price : _data.max_price = item['price'] class Spider(scrapy.spider): def __init__(self, spider_data): self._data = spider_data # and the same object of SpiderData is passed to all spiders Now I have one instance of data shared between all pipeplines (and the same for spiders). Am I generally correct with this? Should I apply same OOP approaches in python as in C++ ? Answer: From what I understand, the approach you are proposing is to keep a reference from each object to a shared object that captures all of the shared data, and and I think this is perfectly fine, especially if you name it appropriately so that its name suggests it's being shared, for readability. Also, you're hiding the internals of the shared object and encapsulating them inside methods such as process_item(), which I think is really important for maintainability (because changes in the internals of the shared object don't have to affect any other object). But I'm not sure about the way you are bootstrapping (i.e. initializing) this shared object. You have these two lines if _data is None: _data = ... which are a little surprising. I didn't quite understand what _data is and where it is defined. Also pipeline_data is assigned to None and never assigned to anything else, so I'm not sure what you meant there. If possible, I would prefer to see a function called create_spiders() that creates the shared object, and then creates the different spiders one by one, giving them a reference to the shared object. This makes the logic very clear. * * * However, in the special case that you want the shared object to be a singleton, I would consider making it a static object in some module that you name appropriately, maybe Globals.py. And then inside your Spider code you would see things like import Globals class SpiderData: def update(self): self.data.price = 200 Globals.spiders_data_collector.process(self.data) Inside the module Globals you would initialize the object spiders_data_collector. I think this requires less code, and this is also important for maintainability.
Simple Python SMTP Enumeration script Question: I am trying to write a simple Python SMTP enumeration script, which reads usernames from a text file (filename supplied as the second argument - `sys.argv[2]`), and checks them against an SMTP server (hostname or ip supplied as the first argument - `sys.argv[1]`. I found something that is kind of close, and tweaked it a bit, like so: #!/usr/bin/python import socket import sys users = sys.argv[2] for line in users: line = line.strip() if line!='': users.append(line) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((sys.argv[1], 25)) fn = s.makefile('rwb') fn.readline() fn.write('HELO testing.com \r\n') fn.flush() fn.readline() for user in users: fn.write('VRFY %s\r\n' % user) fn.flush() print '%s: %s' % (user, fn.readline().strip()) fn.write('QUIT\r\n') fn.flush() s.close() However, when I run the script (for example): ./smtp-vrfy.py 192.168.1.9 users.txt It results in an error: **File "./smtp-vrfy.py", line 10, in users.append(line) AttributeError: 'str' object has no attribute 'append'** What am I doing wrong? How can I fix it? Perhaps there is an easier way to accomplish what I'm trying to do? Any help would be greatly appreciated. Thanks! Answer: `users` is a file name, but you're not reading it. Instead, see what happens: >>> users = "users.txt" >>> for line in users: ... print(line) ... u s e r s . t x t You probably want: with open(users) as f: for line in f: # ... Even better: filename = sys.argv[2] with open(filename) as f: users = [line.strip() for line in f.readlines() if line] Hope it helps!
How to fix unicode error while generating xml file using python xml.etree.ElementTree without misssing any data? Question: I am generating xml file using xml.etree.ElementTree in python and then writting the generated xml file into a file. One of the tag of the xml is regarding system installed software which will have all the details of the system installed software. The xml output on console which i get on execution of the script is perfect but when i try to place output into a file i encounter following error as: Traceback (most recent call last): File "C:\xmltry.py", line 65, in <module> f.write(prettify(top)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 4305: ordinal not in range(128) Following is the script: def prettify(elem): """Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") ##Here starts populating elements inside xml file top = Element('my_practice_document') comment = Comment('details') top.append(comment) child = SubElement(top, 'my_information') childs = SubElement(child,'my_name') childs.text = str(options.my_name) #Following section is for retrieving list of software installed on the system import wmi w = wmi.WMI() for p in w.Win32_Product(): if (p.Version is not None) and (p.Caption is not None): child = SubElement(top, 'sys_info') child.text = p.Caption + " version "+ p.Version ## Following portion places the xml output into test.xml file with open("test.xml", 'w') as f: f.write(prettify(top)) When the script is executed i get the unicode error . I searched on internet and tried out following also: import sys reload(sys) sys.setdefaultencoding('utf8') But this also did not resolved my issue. I want to have all the data which i am getting on console into the file without missing anything. So, how can i achieve that. Thanx in advance for your assistance. Answer: You need to specify an encoding for your output file; `sys.setdefaultencoding` doesn't do that for you. Try import codecs with codecs.open("test.xml", 'w', encoding='utf-8') as f: f.write(prettify(top))
Python: Retrieve the Mac Address of the client using bottle framework Question: I am looking to retrieve the Mac_Address of the user accessing my application. I have tried the following code: import uuid from uuid import getnode as get_mac mac_address = get_mac() mac_address = ':'.join(("%012X" % mac_address)[i:i+2] for i in range(0, 12, 2)) This works OK but returns the mac address of the server and not the client. Is there a way to retrieve the mac address of the client? Answer: The HTTP protocol does not send the MAC address of the client to the server, so there's no way for your server-side application to access it.
Python apply class method to row of data frame Question: My class takes a row of a dataframe to construct an object and I would like to create an array of objects by applying init to every row of a dataframe. Is there a way to vectorize this? My class definition looks like class A(object): def __init__(self,row): self.a = row['a'] self.b = row['b'] Any suggestion will be highly appreciated! I have one way which I am not that satisfied with to solve this problem. Define another function outside of class and then use apply. def InitA(row): return A(row) Assume df is the data frame I want to use as argument. xxx = df.apply(InitA,axis=1) gives what I want. However, I don't think InitA is necessary. My original problem is a bit more complicated. The class definition is class A(object): def __init__(self): return def add_parameter(self,row): self.a = row['a'] I intend to apply add_parameter to every row of a data frame. But I think defining another (lambda) function is necessary to solve this problem. Answer: Just use a lambda function? `xxx = df.apply(lambda x: A(x),axis=1)` edit: Another solution is to directly pass the class, the apply-function then calls the constructor: `xxx = df.apply(A,axis=1)` this works: import pandas as pd class C(object): def __init__(self,dat): return A = pd.DataFrame({'a':pd.Series([1,2,3])}) A.apply(lambda x: C(x),axis=1)
How to obtain all the links in a domain using Python? Question: I want to use Python to obtain all the links in a domain given the 'root' URL (in a list). Suppose given a URL <http://www.example.com> this should return all the links on this page of the same domain as the root URL, then recurse on each of these links visiting them and extracting all the links of the same domain and so on. What I mean by same domain is if given <http://www.example.com> the only links I want back are <http://www.example.com/something>, <http://www.example.com/somethingelse> ... Anything external such as <http://www.otherwebsite.com> should be discarded. How can I do this using Python? EDIT: I made an attempt using lxml. I don't think this works fully, and I am not sure how to take into account links to already processed pages (causing infinite loop). import urllib import lxml.html #given a url returns list of all sublinks within the same domain def getLinks(url): urlList = [] urlList.append(url) sublinks = getSubLinks(url) for link in sublinks: absolute = url+'/'+link urlList.extend(getLinks(absolute)) return urlList #determine whether two links are within the same domain def sameDomain(url, dom): return url.startswith(dom) #get tree of sublinks in same domain, url is root def getSubLinks(url): sublinks = [] connection = urllib.urlopen(url) dom = lxml.html.fromstring(connection.read()) for link in dom.xpath('//a/@href'): if not (link.startswith('#') or link.startswith('http') or link.startswith('mailto:')): sublinks.append(link) return sublinks ~ Answer: import sys import requests import hashlib from bs4 import BeautifulSoup from datetime import datetime def get_soup(link): """ Return the BeautifulSoup object for input link """ request_object = requests.get(link, auth=('user', 'pass')) soup = BeautifulSoup(request_object.content) return soup def get_status_code(link): """ Return the error code for any url param: link """ try: error_code = requests.get(link).status_code except requests.exceptions.ConnectionError: error_code = return error_code def find_internal_urls(lufthansa_url, depth=0, max_depth=2): all_urls_info = [] status_dict = {} soup = get_soup(lufthansa_url) a_tags = soup.findAll("a", href=True) if depth > max_depth: return {} else: for a_tag in a_tags: if "http" not in a_tag["href"] and "/" in a_tag["href"]: url = "http://www.lufthansa.com" + a_tag['href'] elif "http" in a_tag["href"]: url = a_tag["href"] else: continue status_dict["url"] = url status_dict["status_code"] = get_status_code(url) status_dict["timestamp"] = datetime.now() status_dict["depth"] = depth + 1 all_urls_info.append(status_dict) return all_urls_info if __name__ == "__main__": depth = 2 # suppose all_page_urls = find_internal_urls("someurl", 2, 2) if depth > 1: for status_dict in all_page_urls: find_internal_urls(status_dict['url']) The above snippet contains necessary modules for scrapping urls from lufthansa arlines website. The only thing additional here is you can specify depth to which you want to scrape recursively.
How to set PYTHONPATH differently for version 2 and 3? Question: Let's assume that I set PYTHONPATH in `.bashrc` as below: export PYTHONPATH=$PYTHONPATH:/ver2packages And when I check my python path in Python 3: $ python3 >>> import sys >>> print(sys.path) ['', '/home/user', '/ver2packages', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] In `ver2packages`, if there are packages having the same name with packages for version 3, there might be conflicts and errors. Is there a way to set pythonpath for each version of Python? Answer: You can set different `sys.path` for Python 2 and Python 3 using path configuration (`.pth`) files. For instance, to add a directory to `sys.path` for Python 2, create a `.pth` file in any of Python 2 site-packages directories (i.e. returned by [`site.getsitepackages()`](https://docs.python.org/2.7/library/site.html#site.getsitepackages) or [`site.getusersitepackages()`](https://docs.python.org/2.7/library/site.html#site.getusersitepackages)): Python 2.7.11 (default, Dec 6 2015, 15:43:46) [GCC 5.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import site >>> site.getsitepackages() ['/usr/lib/python2.7/site-packages', '/usr/lib/site-python'] Then create a `.pth` file (as root): echo "/ver2packages" > /usr/lib/python2.7/site-packages/ver2packages.pth See [`site`](https://docs.python.org/2.7/library/site.html) module documentation for more.
Python 3.4 AssertEqual() unpredicted behavior when using in a Django unit test Question: I faced some strange behavior of the AssertEquals() in a Django unit test (Python 3.4). The following test results in an **assertion error like this** : > line 113, in test_index_view_with_questions_without_choices > self.assertEqual(response.context['lastest_question_list'], []) > AssertionError: [] != [] **Here's the test itself:** def test_index_view_with_questions_without_choices(self): ''' If a question has no choices it should not be displayed on the questions index page no matter if it's a past or a future question. ''' create_question_with_no_choices(question_text='no choices q1', days=-5) create_question_with_no_choices(question_text='no choices q2', days=5) response = self.client.get(reverse('polls:index')) self.assertContains(response, 'No polls are available.', status_code=200) self.assertEqual(response.context['lastest_question_list'], []) Changing last line like so: self.assertEqual(len(response.context['lastest_question_list']), 0) **makes the test working properly** but I can't get the reason it refuses to work with the list itself. I also have a very similar test in the same app and project and it **works just fine** : def test_index_view_with_no_questions(self): ''' If no questions exist, an appropriate message should be displayed. ''' response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'No polls are available.') self.assertQuerysetEqual(response.context['lastest_question_list'], []) Here's **the view** itself to show how the Queryset defined: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'lastest_question_list' def get_queryset(self): ''' Returns last five published questions (not including those set to be published in the future) Also excludes the questions with an empty choice_set. ''' qset = Question.objects.annotate(choices_count=Count('choice')) qset = qset.filter(choices_count__gte=1, pub_date__lte=timezone.now()) qset = qset.order_by('-pub_date')[:5] return qset **P.S.:** I found a similar issue described [HERE](http://stackoverflow.com/questions/13078885/django-assertequals-test- failing-even-though-answer-is-equal), but I'm still confused of what is actually causing such a behavior. Even though I know how to make the test working in this particular example it still important for me to understand what's going on. :) Answer: First off, as I suspect and you inspected, `response.context['latest_question_list']` is a queryset, so you couldn't directly compare queryset object with list object. Also, `assertQuerysetEqual` is documented in [django doc](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.TransactionTestCase.assertQuerysetEqual), quoting here: > TransactionTestCase.assertQuerysetEqual(qs, values, transform=repr, > ordered=True, msg=None) > > The comparison of the contents of qs and values is performed using the > function transform; by default, this means that the repr() of each value is > compared. Any other callable can be used if repr() doesn’t provide a unique > or helpful comparison. You can see that the `assertQuerysetEqual` is comparing each value in the queryset with the list you provided, so it will loop through the whole thing and compare each one. That's why it would pass the test but fails `assertEqual`.
How to draw graph in python or convert python into java and Matlab? Question: Recently i need to do a project with digit recognition using data from UCI <https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits> I want to use source code fromhttps://github.com/khiner/Linear-Discrimination- with-Perceptrons. But i don't want to just copy his code. Because i don't know how to draw error graph in python,I expect to re-write it in java and Matlab. Does anyone know to how draw error graph and other statistic diagram in python or where i can find tutorial for re-write python in java and Matlab? source code: from optparse import OptionParser import random class Perceptron(object): def __init__(self, trainfile_string, testfile_string): train_lines = open(trainfile_string, 'r').readlines() test_lines = open(testfile_string, 'r').readlines() # these vectors map a class number to a list of its corresponding # train/test instances (int vectors) self.train_vectors = {} self.test_vectors = {} self.num_features = len(train_lines[0].strip().split(',')) - 1 self.weights = {} # initialize train_vectors and test_vectors. # initialize weight vectors to random values in (-1, 1) for n in xrange(10): if n != 8: self.train_vectors[n] = [] self.test_vectors[n] = [] self.weights[n] = [random.uniform(-1,1) for i in xrange(self.num_features)] self.weights[n].append(1.0) # input bias for line in train_lines: vector = [int(x) for x in line.strip().split(',')] if vector[-1] in (n, 8): self.train_vectors[n].append(vector) for line in test_lines: vector = [int(x) for x in line.strip().split(',')] if vector[-1] in (n, 8): self.test_vectors[n].append(vector) def run(self, max_epochs, rate, over_train=False, verbose=False): """For each class, train until there is no more improvement (or accuracy is a perfect 1.0), then test the class using the test file""" for cls in self.weights.keys(): improvement = 1 epoch = 0 train_accuracy = 0 over_train_epochs = max_epochs print '___________%dv%d____________' % (cls, 8) if verbose: print 'Training:' epochs_set = False while (not over_train and train_accuracy < 1.0 and \ improvement > 0.0 and epoch < max_epochs) \ or (over_train and epoch < over_train_epochs): if not epochs_set and (improvement <= 0.0 or train_accuracy >= 1.0): # if we're overtraining, train for twice as long as normal over_train_epochs = 2*epoch epochs_set = True print 'over-training. improvement stopped at %d' % epoch epoch = epoch + 1 self.train(cls, rate) (c1, i1, c2, i2) = self.test(cls, train=True) (old_accuracy, train_accuracy) = (train_accuracy, float(c1 + c2)/float(c1+ c2 + i1 + i2)) improvement = train_accuracy - old_accuracy if verbose: print 'Epoch %d, accuracy: %f, improvement: %f\n\n%s' % \ (epoch, train_accuracy, improvement, confusionMatrix(cls, c1, i1, c2, i2)) # done training. now test. (c1, i1, c2, i2) = self.test(cls, train=False) test_accuracy = float(c1 + c2)/float(c1+ c2 + i1 + i2) print "Epochs: %d\nTraining accuracy: %f\nTest accuracy: %f\n\n%s" \ % (epoch, train_accuracy, test_accuracy, confusionMatrix(cls, c1, i1, c2, i2)) def train(self, cls, learning_rate): """Train perceptron to differentiate between cls and 8, and return the trained weights weights""" for vector in self.train_vectors[cls]: (o, t) = self.getOandT(vector, cls) if o == None or t == None: continue # adjust the weights (+1 for bias) for i in xrange(self.num_features + 1): self.weights[cls][i] += learning_rate*(t - o)*vector[i] def test(self, cls, train): """Use the provided test data to test the trained weights for a given class number vs. 8. Returns a tuple representing a confusion matrix eg: (8-correct, 8-incorrect, cls-correct, cls-incorrect).""" if train: vectors = self.train_vectors[cls] else: vectors = self.test_vectors[cls] c1 = 0; # num examples classified correctly for 8 i1 = 0; # '' '' '' incorrectly for 8 c2 = 0; # '' '' '' correctly for cls i2 = 0; # '' '' '' incorrectly for cls for vector in vectors: (o, t) = self.getOandT(vector, cls) if o == None or t == None: continue elif o == 1 and t == 1: c1 = c1 + 1 elif o == -1 and t == -1: c2 = c2 + 1 elif o == -1 and t == 1: i1 = i1 + 1 elif o == 1 and t == -1: i2 = i2 + 1 return (c1, i1, c2, i2) def getOandT(self, vector, cls): """Returns a tuple of o and t values, comparing cls to 8 -1 = cls, 1 = 8 None = provided instance vector is not 8 or the provided class (cls)""" if vector[-1] == 8: t = 1 elif vector[-1] == cls: t = -1 else: return (None, None) total = 0.0 for i in xrange(self.num_features + 1): total += self.weights[cls][i]*vector[i] o = sgn(total) return (o, t) def confusionMatrix(cls, c1, i1, c2, i2): return "Class\tCorrect\tIncorrect\n%d\t%d\t%d\n%d\t%d\t%d" %\ (cls, c2, i2, 8, c1, i1) def sgn(val): """Returns 1 for val > 0 and -1 for val <= 0""" if val > 0: return 1 else: return -1 if __name__ == "__main__": parser = OptionParser() parser.add_option("-n", "--train", dest="train_file", default="data/optdigits.tra", help="file with training data. default: 'data/optdigits.tra'") parser.add_option("-t", "--test", dest="test_file", default="data/optdigits.tes", help="file with test data. default: 'data/optdigits.tes'") parser.add_option("-e", "--epochs", dest="max_epochs", default=30, help="maximum number of epochs. default: 30") parser.add_option("-r", "--rate", dest="rate", default=.2, help="learning rate. default: 0.2") parser.add_option("-v", "--verbose", dest="verbose", default=False, help="would you like to print more detailed output?") parser.add_option("-o", "--over-train", dest="over_train", default=False, help="if set to true, training will go for twice as many epochs as it takes to stop improving") (options, args) = parser.parse_args() verbose = options.verbose perceptron = Perceptron(options.train_file, options.test_file) perceptron.run(max_epochs=int(options.max_epochs), \ rate=float(options.rate), over_train=options.over_train, verbose=options.verbose) Answer: When I write errorbars in python I use the [matplotlib](http://matplotlib.org/1.2.1/examples/pylab_examples/errorbar_demo.html) resource. My code looks something like this: x = range(80) ax.errorbar(x, array_of_data, xerr=None,yerr=array_of_error_values) #plots the graph, x versus y. "xerr" stands for the errorgraph for #horizontal errorbars, and yerr for vertical errorbars. ax.set_title('Mean group size', fontsize = 10) #set title for axis fig.savefig('analysis/alltreatments.png', dpi=300) #save figure Basically I store my data in an array. Each value of that array is already an average of something else. I calculate the standard deviation and the standard error for each element, and from there I calculate the confidence intervals. These get stored in a confidence-interval array. Array_data : {2, 3, 5} Array_ConfidenceInterval: {0.3, 0.2, 0.3} #each element corresponds to Array_data elements And matplotlib plots the two arrays. Output looks something like this: [![output of the errorbar code in python](http://i.stack.imgur.com/Q0XGb.png)](http://i.stack.imgur.com/Q0XGb.png)
python script parsing multiple arguments Question: I have trouble passing parameters to my script. Script launch command line : myscript.py -c Random I'm using getopt in my code (given down there) but this code is not looping through the arguments because later on the program the tested_company varible is not defined, where did I go wrong? tested_company=None try: opts, args = getopt.getopt(sys.argv[1:], "hc:i", ['help', 'company', 'info']) #first argument ignored because zabbix giving it and being useless except getopt.GetoptError as e: print (e) usage() sys.exit(3) if not opts: #print ('No options supplied, only updating the database') print("3") sys.exit(3) else: for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-c', '--company'): tested_company = arg elif opt == '-i': displayInfos=1 Answer: I think you're missing an equals sign after `company` in your getopt call. This code works for me: import getopt import sys tested_company=None try: opts, args = getopt.getopt(sys.argv[1:], "hc:i", ['help', 'company=', 'info']) #first argument ignored because zabbix giving it and being useless print(opts) except getopt.GetoptError as e: print (e) usage() sys.exit(3) if not opts: #print ('No options supplied, only updating the database') print("3") sys.exit(3) else: for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-c', '--company'): tested_company = arg elif opt == '-i': displayInfos=1 print(tested_company) Calling this with > python .\script.py -c xxxx gives [('-c', 'xxxx')] xxxx Calling with > python .\script.py --company xxxx gives [('--company', 'xxxx')] xxxx
How insert in Cassandra without null value in Column Question: I'm trying to store some tweets in Cassandra Database using Python and DataStax driver ( Python -> Cassandra ). Everything works well, but there's something that I can't understand. How to insert a row without null value ? As example, CREATE TABLE tweets ( id_tweet text PRIMARY KEY, texttweet text, hashtag text, url text, ) If I want to insert a row without url value, it's working but in Cassandra I'll see "null" in url column. I check this doc : <http://datastax.github.io/python-driver/getting_started.html#passing- parameters-to-cql-queries> So I tried 2 differents ways : First one, I create the String as a full String, and execute it. requete = "insert into Tweets(id_tweet,texttweet,hashtag,url) values ('%s','%s','%s','%s')"%(id_tweet,texttweet,hashtag,url) session.execute(requete) Or I send parameters in the execute function. requete2 = "insert into Tweets(id_tweet,texttweet,hashtag,url) values ('%s','%s','%s','%s')" session.execute(requete2,(id_tweet,id_texttweet,hashtag,url)) Problem is, the 2differents ways give me null value if i get no URL or Hashtag in my tweet as example. Is it possible to not see the column if it's empty in a row, like I see in lot of tutorials ? [![enter image description here](http://i.stack.imgur.com/QHQVG.png)](http://i.stack.imgur.com/QHQVG.png) Thanks. Answer: This is something you can do if you are using Cassandra 2.2 or later. In Cassandra 2.2 the concept of 'UNSET' was introduced. This allows you to use the same statement to insert a row, even if you don't want to provide some of the values, here's how you would do it: from cassandra.query import UNSET_VALUE ps = session.prepare("insert into tweets(id_tweet,texttweet,hashtag,url) values (?,?,?,?)") session.execute(ps, ("id", "hello world!", UNSET_VALUE, UNSET_VALUE)); This would indicate to cassandra that you don't want to insert these values as null, rather they should be ommitted all together so no 'null' values (internally these are tombstones) are inserted into cassandra. On your side, I think you would need to do some preprocessing logic to convert any incoming `None` values into `UNSET_VALUE`. The pre 2.2 solution would be to adjust your query based on what columns are absent, i.e `insert into tweets(id_tweet,texttweet) values (?,?)` if hashtag and url are `None`. _On the retrieval end, there should technically be away to distinguish between null and unset values (I'll look into this), but I don't think such a mechanism exists in the python driver. I'll open up a ticket if its possible to do in the protocol but the feature isn't present in the driver._ **EDIT** : It doesn't look like cassandra differentiates between values that were explicitly set to null (which are marked internally as tombstones) and those that were never set when returning data. You can read more about 'UNSET' and other 2.2 features in the python driver in [this blog post](http://www.datastax.com/dev/blog/python- driver-2-6-0-rc1-with-cassandra-2-2-features).
wxPython - Prevent the same warning dialog from appearing twice Question: I have a textctrl accepting user input. I want to check the text after the user enters it to see if it is also in a predefined list of words. I can do this check when the textctrl loses focus. I can also set it to check when the enter key is pressed. However, if I do both, the input is checked twice (not a huge deal, but not necessary). If the input is incorrect (the word is not in the list) then 2 error dialogs pop up. This is not ideal. What is the best way around this? Edit: In case I wasn't clear, 2 warnings popup if the input is incorrect and Enter is hit. This causes one dialog to appear, which steals focus, causing the second to appear. Answer: This demo code meets your criteria. You should be able to test run it in its entirety in a separate file. import sys; print sys.version import wx; print wx.version() class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "hello frame") self.inspected = True self.txt = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER) self.txt.SetLabel("this box must contain the word 'hello' ") self.txt.Bind(wx.EVT_TEXT_ENTER, self.onEnter) self.txt.Bind(wx.EVT_KILL_FOCUS, self.onLostFocus) self.txt.Bind(wx.EVT_TEXT, self.onText) def onEnter(self, e): self.inspectText() def onLostFocus(self, e): self.inspectText() def onText(self, e): self.inspected = False def inspectText(self): if not self.inspected: self.inspected = not self.inspected if 'hello' not in self.txt.GetValue(): self.failedInspection() else: print "no need to inspect or warn user again" def failedInspection(self): dlg = wx.MessageDialog(self, "The word hello is required before hitting enter or changing focus", "Where's the hello?!", wx.OK | wx.CANCEL) result = dlg.ShowModal() dlg.Destroy() if result == wx.ID_OK: pass if result == wx.ID_CANCEL: self.txt.SetLabel("don't forget the 'hello' !") mySandbox = wx.App() myFrame = TestFrame() myFrame.Show() mySandbox.MainLoop() exit() The strategy used was to add a flag to the instance to indicate if it has already been inspected and to overwrite the flag if the text changes.
Plot arbitrary 2-D function in python/pyplot like Matlab's Ezplot Question: I'm looking for a way to generate a plot similar to how ezplot works in MATLAB in that I can type: ezplot('x^2 + y^2 = y + 5') and get a graph ready to go for any arbitrary function. I'm only worrying about the case where I have both a x and a y. I only have the function, and I'd really rather not go about trying to calculate all the y values for some given x range if I didn't have to. The few solutions I've seen suggested are either about decision boundaries (which this is not. There is no test data or anything, just an arbitrary function) or are all for functions already defined as y = some x equation which doesn't really help me. I would somewhat accept if there was a good way to mimic Wolfram|Alpha in their solve functionality("solve x^2 + y^2 = y + 5 for y" will give me two functions I could then graph separately), but rather prefer the ezplot as that's more or less instant within MATLAB. Answer: I think you could use `sympy` plotting and parse_expr for this For your example, this would work as follows from sympy.plotting import plot_implicit from sympy.parsing.sympy_parser import parse_expr def ezplot(s): #Parse doesn't parse = sign so split lhs, rhs = s.replace("^","**").split("=") eqn_lhs = parse_expr(lhs) eqn_rhs = parse_expr(rhs) plot_implicit(eqn_lhs-eqn_rhs) ezplot('x^2 + y^2 = y + 5') This can be made as general as needed
How to convert paragraphs to double quotes sentences in python Question: I have a text file having many paragraphs, i want to split it by sentences i.e. after every dot "." or ? it split and include the sentence in double Qoutes like: This is a sentence. This is an excited sentence! And do you think this is a question? so what then . "This is a sentence." "This is an excited sentence!" "And do you think this is a question?" "so what then." and save it in text file all the sentences. def splitParagraphIntoSentences(paragraph): import re sentenceEnders = re.compile('[.!?]') sentenceList = sentenceEnders.split(paragraph) return sentenceList if __name__ == '__main__': p = """This is a sentence. This is an excited sentence! And do you think this is a question? so what to do then because many people will say this ok. and then what ?""" sentences = splitParagraphIntoSentences(p) for s in sentences: sentence=(s.strip()) file = open("another.txt", "w") file.write(sentence) file.close() it doesn't work, and not sure how to make each sentence in double quotes, any help ??? Answer: If I understood correctly what you are asking, try to modify your code to the following one: import re def splitParagraphIntoSentences(paragraph): ''' break a paragraph into sentences and return a list ''' sentenceEnders = re.compile('[.!?]') sentenceList = sentenceEnders.split(paragraph) return sentenceList if __name__ == '__main__': p = "This is a sentence. This is an excited sentence! And do you think this is a question? so what to do then because many people will say this ok. and then what ?" sentences = splitParagraphIntoSentences(p) file = open('another.txt', "w") for s in sentences: if s.strip(): file.write('"' + s.strip() + '"\n') # Add a newline after each sentence file.close() In your case, instead of `p` you need first of course to read the file, since yours (I guess) was just a simplification.
How should the values of a list be scaled such that they meet standard deviation and mean requirements? Question: I have lists of values that I want to have scaled to meet certain standard deviation and mean requirements. Specifically, I want the datasets standardised to mean 0 with standard deviation 1, except for datasets for which all values are greater than 0; these I want scaled such that their mean is 1. What would be a good way to do this type of thing in Python? Answer: If you're working with data in Python, you're going to want to be using the science stack (see [here](http://www.scipy.org/about.html)), in particular `numpy`, `scipy`, and `pandas`. What you're looking for is the `zscore`, and that's a common enough operation that it's built-in to `scipy` as [`scipy.stats.zscore`](http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.stats.zscore.html). Starting from a random array with non-zero mean and non-unity stddev: >>> import numpy as np >>> import scipy.stats >>> data = np.random.uniform(0, 100, 10**5) >>> data.mean(), data.std() (49.950550280158893, 28.910154760235972) We can renormalize: >>> renormed = scipy.stats.zscore(data) >>> renormed.mean(), renormed.std() (2.0925483568134951e-16, 1.0) And shift if we want: >>> if (data > 0).all(): ... renormed += 1 ... >>> renormed.mean(), renormed.std() (1.0000000000000002, 1.0) We could do this manually, of course: >>> (data - data.mean())/data.std() array([-0.65558504, 0.24264144, -0.1112242 , ..., -0.40785103, -0.52998332, 0.10104563]) (Note that by default this uses a delta degrees of freedom of 0, i.e. the denominator is N. If you want N-1, pass `ddof=1`).
Convert categorical data into various columns for plotting in pandas Question: I'm new to `python` and `pandas` but I've used `R` in the past for data analysis. I have a simple dataset: df.head() Sequence Level Count 1 Easy 5 1 Medium 7 1 Hard 9 I would like to convert this to: Sequence Easy Medium Hard 1 5 7 9 In `R`, I could simply do this by using the `reshape2` package. In `python` it seems like one of my options is to create dummy variables using `get_dummies` but that would still generate multiple rows for the same `Sequence` in my case. Is there an easy way of achieving my resultset? I'm finally trying to plot it using: import matplotlib.pyplot as plt df.plot(kind='bar', stacked=True) plt.show() Any help would be appreciated. Answer: You could use pandas [`pivot_table`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.pivot_table.html): In [1436]: pd.pivot_table(df, index='Sequence', columns='Level', values='Count') Out[1436]: Level Easy Hard Medium Sequence 1 5 9 7 Then you could plot it: df1 = pd.pivot_table(df, index='Sequence', columns='Level', values='Count') df1.plot(kind='bar', stacked=True) [![enter image description here](http://i.stack.imgur.com/Zmtlh.png)](http://i.stack.imgur.com/Zmtlh.png)
Amazon + Django each 12 hours appears that [Errno 5] Input/output error Question: I recently setup and deploy an Amazon EC2 instance for deploy my django project. I was interacting with my application via browser when I get this error in the browser: errno 5 input/output error django [![enter image description here](http://i.stack.imgur.com/e7PvN.png)](http://i.stack.imgur.com/e7PvN.png) This error did reference to some function of my application Environment: Request Method: GET Request URL: http://localhost:8000/accounts/profile/ 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', 'crispy_forms', 'django_extensions', 'storages', 'userprofile'] 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 "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/ubuntu/workspace/neurorehabilitation-system/userprofile/mixins.py" in dispatch 7. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/ubuntu/.virtualenvs/nrb_dev/lib/python3.4/site-packages/django/views/generic/base.py" in get 157. context = self.get_context_data(**kwargs) File "/home/ubuntu/workspace/neurorehabilitation-system/userprofile/views.py" in get_context_data 50. print (user.is_physiotherapist) Exception Type: OSError at /accounts/profile/ Exception Value: [Errno 5] Input/output error At the end in the line 50 is referenced a `get_context_data()` function which is inside of a class based view that inherit of `TemplateView` CBV but in my console the server require restart and when I did this, the error was solved of a magic way .. I've search this error and I found this ticket reported <https://code.djangoproject.com/ticket/23284> This report is very similar to my error ... In addition I had this error yesterday, I restart my server, and today I have again the error. There is some problem with EC2 infraestructure with Django (I don't think so) or the problem is more for my application side? I don't think so that the function `get_context_data()` of my application be the problem ... Answer: I have been exploring, and I should say that the origin of this error were in my code I have two newbie errors: 1. `print` **sentence in production** In the traceback that I shown above in my question, I had a `print` sentence inside my `get_context_data()` function of this way: File "/home/ubuntu/workspace/neurorehabilitation-system/userprofile/views.py" in get_context_data 50. print (user.is_physiotherapist) Is possible that each time that this print sentence is executed, the process try write to the stdout file in my amazon ec2 machine instance. I remove this print sentence in that line, and retrieve the changes into my production servers via git and restart gunicorn server and all it's works perfect. 2. **I have the** `DEBUG=True` **in production** I have the following settings files: settings/ base.py # --- without DEBUG development.py # --- DEBUG=True testing.py # --- DEBUG=True production.py # --- DEBUG=False staging.py # --- DEBUG=False All files (`development.py, testing.py, production.py, staging.py`) inherit from `base.py` But I don't know how to make that in my ec2 instance, the production.py be executed, this inherit all from base.py and override DEBUG to False. I've been exploring and one possibility is change their value (True or False) according to the name of the host in which is running my application, [such as shown in this post](https://nicksergeant.com/automatically-setting-debug-in- your-django-app-based-on-server-hostname/) In my case this is the value of my hostname (nrb_dev)ubuntu@ip-172-31-27-249:~$ python Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> a=socket.gethostname() >>> a 'ip-172-31-27-249' >>> >>> if a != 'ip-172-31-27-249': ... DEBUG = print ('Caleno juiciocito') ... >>> DEBUG True >>> This mean, put into my base.py the following: import socket if socket.gethostname() == 'ip-172-31-27-249': DEBUG = False else: DEBUG = True Although I am hardcoding the hostname of the production server in my code. This mean that I am adding a point thar after will have modified manually when we want deploy my project in other machine with other hostname Is this a best practice despite to it's works? Another option which I think that it's the most suited alternative is fix the value of my `DJANGO_SETTINGS_MODULE` environment variables In my particular situation I am using `virtualenvwrapper` and I have two virtual environments so: `nrb_dev` for my development environment `nrb_test` for my testing environment . I have some hooks which are activated when the virtual environments are activated In `nrb_dev` in `$VIRTUAL_ENV/bin/postactivate` I have this: export DJANGO_SETTINGS_MODULE="neurorehabilitation.settings.development" In the same way, in `nrb_test` in `$VIRTUAL_ENV/bin/postactivate` I have this: export DJANGO_SETTINGS_MODULE="neurorehabilitation.settings.testing" This mean that in my amazon EC2 production machine I should change the hook in `$VIRTUAL_ENV/bin/postactivate` to choose the `settings/production.py` of this way: export DJANGO_SETTINGS_MODULE="neurorehabilitation.settings.production" Just for test effects and the temporal way, I print the `DEBUG` value in my `settings/production.py` from .base import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False print (DEBUG) # just for now. And when I start my gunicorn daemon server, I can see that DEBUG value is set to `False` (nrb_dev)ubuntu@ip-172-31-27-249:~/workspace/neurorehabilitation-system$ gunicorn -c neurorehabilitation/gunicorn_config.py neurorehabilitation.wsgi [2016-01-08 00:26:15 +0000] [6691] [INFO] Starting gunicorn 19.4.5 [2016-01-08 00:26:15 +0000] [6691] [INFO] Listening at: http://127.0.0.1:8000 (6691) [2016-01-08 00:26:15 +0000] [6691] [INFO] Using worker: sync [2016-01-08 00:26:15 +0000] [6694] [INFO] Booting worker with pid: 6694 False ^C[2016-01-08 00:26:19 +0000] [6691] [INFO] Handling signal: int **Additional Notes** I can explore the Django [Logging functionality](https://docs.djangoproject.com/en/1.9/topics/logging/) for register events and others things of my application. I should explore the [supervisor service](http://docs.gunicorn.org/en/latest/deploy.html#supervisor) for manage the gunicorn procees of a better way in production. Other resources for supervisor: [How to install and manage supervisor in Ubuntu](https://www.digitalocean.com/community/tutorials/how-to-install-and- manage-supervisor-on-ubuntu-and-debian-vps) [Setting up Django with Nginx, Gunicorn, virtualenv, supervisor and PostgreSQL](http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn- virtualenv-supervisor/)
Iterator produced by itertools.groupby() is consumed unexpectedly Question: I have written a small program based on iterators to display a multicolumn calendar. In that code I am using `itertools.groupby` to group the dates by month by the function `group_by_months()`. There I yield the month name and the grouped dates as a list for every month. However, when I let that function directly return the grouped dates as an iterator (instead of a list) the program leaves the days of all but the last column blank. I can't figure out why that might be. Am I using groupby wrong? Can anyone help me to spot the place where the iterator is consumed or its output is ignored? Why is it especially the last column that "survives"? Here's the code: import datetime from itertools import zip_longest, groupby def grouper(iterable, n, fillvalue=None): """\ copied from the docs: https://docs.python.org/3.4/library/itertools.html#itertools-recipes """ args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) def generate_dates(start_date, end_date, step=datetime.timedelta(days=1)): while start_date < end_date: yield start_date start_date += step def group_by_months(seq): for k,v in groupby(seq, key=lambda x:x.strftime("%B")): yield k, v # Why does it only work when list(v) is yielded here? def group_by_weeks(seq): yield from groupby(seq, key=lambda x:x.strftime("%2U")) def format_month(month, dates_of_month): def format_week(weeknum, dates_of_week): def format_day(d): return d.strftime("%3e") weekdays = {d.weekday(): format_day(d) for d in dates_of_week} return "{0} {7} {1} {2} {3} {4} {5} {6}".format( weeknum, *[weekdays.get(i, " ") for i in range(7)]) yield "{:^30}".format(month) weeks = group_by_weeks(dates_of_month) yield from map(lambda x:format_week(*x), weeks) start, end = datetime.date(2016,1,1), datetime.date(2017,1,1) dates = generate_dates(start, end) months = group_by_months(dates) formatted_months = map(lambda x: (format_month(*x)), months) ncolumns = 3 quarters = grouper(formatted_months, ncolumns) interleaved = map(lambda x: zip_longest(*x, fillvalue=" "*30), quarters) formatted = map(lambda x: "\n".join(map(" ".join, x)), interleaved) list(map(print, formatted)) This is the failing output: January February March 09 1 2 3 4 5 10 6 7 8 9 10 11 12 11 13 14 15 16 17 18 19 12 20 21 22 23 24 25 26 13 27 28 29 30 31 April May June 22 1 2 3 4 23 5 6 7 8 9 10 11 24 12 13 14 15 16 17 18 25 19 20 21 22 23 24 25 26 26 27 28 29 30 July August September 35 1 2 3 36 4 5 6 7 8 9 10 37 11 12 13 14 15 16 17 38 18 19 20 21 22 23 24 39 25 26 27 28 29 30 October November December 48 1 2 3 49 4 5 6 7 8 9 10 50 11 12 13 14 15 16 17 51 18 19 20 21 22 23 24 52 25 26 27 28 29 30 31 This is the expected output: January February March 00 1 2 05 1 2 3 4 5 6 09 1 2 3 4 5 01 3 4 5 6 7 8 9 06 7 8 9 10 11 12 13 10 6 7 8 9 10 11 12 02 10 11 12 13 14 15 16 07 14 15 16 17 18 19 20 11 13 14 15 16 17 18 19 03 17 18 19 20 21 22 23 08 21 22 23 24 25 26 27 12 20 21 22 23 24 25 26 04 24 25 26 27 28 29 30 09 28 29 13 27 28 29 30 31 05 31 April May June 13 1 2 18 1 2 3 4 5 6 7 22 1 2 3 4 14 3 4 5 6 7 8 9 19 8 9 10 11 12 13 14 23 5 6 7 8 9 10 11 15 10 11 12 13 14 15 16 20 15 16 17 18 19 20 21 24 12 13 14 15 16 17 18 16 17 18 19 20 21 22 23 21 22 23 24 25 26 27 28 25 19 20 21 22 23 24 25 17 24 25 26 27 28 29 30 22 29 30 31 26 26 27 28 29 30 July August September 26 1 2 31 1 2 3 4 5 6 35 1 2 3 27 3 4 5 6 7 8 9 32 7 8 9 10 11 12 13 36 4 5 6 7 8 9 10 28 10 11 12 13 14 15 16 33 14 15 16 17 18 19 20 37 11 12 13 14 15 16 17 29 17 18 19 20 21 22 23 34 21 22 23 24 25 26 27 38 18 19 20 21 22 23 24 30 24 25 26 27 28 29 30 35 28 29 30 31 39 25 26 27 28 29 30 31 31 October November December 39 1 44 1 2 3 4 5 48 1 2 3 40 2 3 4 5 6 7 8 45 6 7 8 9 10 11 12 49 4 5 6 7 8 9 10 41 9 10 11 12 13 14 15 46 13 14 15 16 17 18 19 50 11 12 13 14 15 16 17 42 16 17 18 19 20 21 22 47 20 21 22 23 24 25 26 51 18 19 20 21 22 23 24 43 23 24 25 26 27 28 29 48 27 28 29 30 52 25 26 27 28 29 30 31 Answer: As the docs state ([c.f.](https://docs.python.org/3.4/library/itertools.html#itertools.groupby)): > when the groupby() object is advanced, the previous group is no longer > visible. So, if that data is needed later, it should be stored as a list That means the iterators are consumed, when the code later accesses the returned iterators out of order, i.e., when the groupby is actually iterated. The iteration happens out of order because of the chunking and interleaving that is done here. We observe this specific pattern (i.e., only the last column is fully displayed) because of the way we iterate. That is: 1. The month names for the first line are printed. Thereby the iterators for up to the last column's month are consumed (and their content discarded). The groupby() object produces the last column's month name only after the first columns' data. 2. We print the first week line. Thereby the already exhausted iterators for the first columns are filled up automatically using the default value passed to `zip_longest()`. Only the last column still provides actual data. 3. The same happens for the next lines of month names.
Can't call multiple functions in the same time with multiprocessing Question: I'm trying to figure out how could I run the same function multiple times in the same time. I could implement something with the multiprocessing that based on other SO questions, but unfortunately it doesn't work as I wanted. Actually when I run it I get something like this (the functions are running after each osther): Worker1 0 1 1 1 2 1 Worker2 0 2 1 2 2 2 Worker3 0 3 1 3 2 3 And I would like to achieve this (or something like this): Worker1 Worker2 Worker3 0 1 0 2 0 3 1 1 1 2 1 3 2 1 2 2 2 3 I'm really new to Python so it's possible that've made some trivial mistakes, but unfortunately I can't figure out where's the problem, so I would really appreciate if somebody could show me the right solution. import multiprocessing def worker(): print ("Worker1") doSomething(1) return def worker2(): print ("Worker2") doSomething(2) return def worker3(): print ("Worker3") doSomething(3) return def doSomething (x): for num in range(3): print (num, x) def runInParallel(*fns): proc = [] for fn in fns: p = multiprocessing.Process(target=fn) p.start() proc.append(p) for p in proc: p.join() if __name__ == '__main__': runInParallel(worker, worker2, worker3) # 2. ATTEMPT - it does the same if __name__ == '__main__': p = multiprocessing.Process(target=worker) jobs.append(p) p.start() p2 = multiprocessing.Process(target=worker2) jobs.append(p2) p2.start() p3 = multiprocessing.Process(target=worker3) jobs.append(p3) p3.start() Answer: What is happening, is that the background thread is finishing even before the program can create and start the next thread, so that is why you are getting each worker separated. To get the output you want. You can add a sleep, like Evert mentioned: def doSomething (x): time.sleep(.01) for num in range(3): print (num, x)
Can I connect an external (R) process to each pyspark worker during setup Question: I want to have each python worker start an R shell using rpy2. Can I do this during some sort of setup phase similar to how I assume this would happen when you import a Python module to be used for later executor tasks? For example: import numpy as np df.mapPartitions(lambda x: np.zeros(x)) In my case I want to instead start an R shell on each executor and import R libraries, which would look something like this: import rpy2.robjects as robjects from rpy2.robjects.packages import importr rlibrary = importr('testrlibrary') df.mapPartitions(lambda x: rlibrary.rfunc(x)) But I don't want this to occur inside the call to `mapPartitions`, because then it would happen at the task-level as opposed to once per executor core. That approach works and looks more like the example below but is not useful for me. def model(partition): import rpy2.robjects as robjects from rpy2.robjects.packages import importr rlibrary = importr('testrlibrary') rlibrary.rfunc(partition) df.mapPartitions(model) Answer: Something like this should work just fine: import rpy2.robjects as robjects from rpy2.robjects.packages import importr def length_(s): stringi = importr("stringi") return stringi.stri_length(s)[0] sc.parallelize(["foo", "bar", "foobar"]).map(length_) [`R` object](https://bitbucket.org/rpy2/rpy2/src/fe7b154143bcc0316a036f2fef85cea90b2963ec/rpy/robjects/__init__.py?at=default&fileviewer=file- view-default#__init__.py-302), which represents R interpreter, [is a singleton](https://bitbucket.org/rpy2/rpy2/src/fe7b154143bcc0316a036f2fef85cea90b2963ec/rpy/robjects/__init__.py?at=default&fileviewer=file- view-default#__init__.py-347) so it will be initialized only once and R doesn't re-import already attached libraries. There is some overhead from calling `require` multiple times but it should be negligible compared to the cost of passing your data to and from R. If you want something more sophisticated you can create your own [singleton module](http://stackoverflow.com/q/10936709/1560062) or use [Borg pattern](http://stackoverflow.com/q/1318406/1560062) to handle imports but it could be an overkill. > I assume this would happen when you import a python module to be used for > later executor tasks It actually depends on a configuration. By default Spark reuses interpreters between tasks but this behavior can be modified. I've provided some examples as an answer to [In Apache spark, what is the difference between using mapPartitions and combine use of broadcast variable and map](http://stackoverflow.com/q/34501334/1560062). Maybe you'll find these useful.
How do I work with images in Bokeh (Python) Question: For example you can plot an image in matplotlib using this code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg img=mpimg.imread('image.png') plt.imshow(img) Is something like this possible with Bokeh(0.10)? Thanks in advance for your help. Answer: You can use the `ImageURL` glyph (`image_url` plot method)to load images locally or from the web. from bokeh.plotting import figure, show, output_file output_file('image.html') p = figure(x_range=(0,1), y_range=(0,1)) p.image_url(url=['tree.png'], x=0, y=1) show(p) [![Image Example](http://i.stack.imgur.com/Kj3P7.png)](http://i.stack.imgur.com/Kj3P7.png) One gotcha - if you graph only an image (and no other data), you'll have to explicitly set the plot ranges. Here's the docs: <http://bokeh.pydata.org/en/latest/docs/reference/models/glyphs.html#bokeh.models.glyphs.ImageURL>
Unknown characters fetching stock data from yahoo in csv format Question: When I try to get historical stock data from yahoo finance in python I'm getting correct output in html, but in csv, it returns unknown characters output of csv : 摁彪汣獯ⱥ汃獯ⱥ慄整䠬杩ⱨ潌ⱷ灏湥匬浹潢ⱬ潖畬敭㈊㄰ⴴ㐰㈭ⰵ䡙住ㄬ㐹㄰〶ⰰ㐳㐮ⰸ㔳〮㤹㤹ⰸ㐳㈮〹〰ⰱ㐳㐮ⰸ㔳〮㤲㤹ⰹ Here is my code : def run(): yahoo=Share('YHOO') file1=open("scripts/hisdata.csv","w") file1.write("Adj_close,Close,Date,High,Low,Open,Symbol,Volume\n") h= yahoo.get_historical('2014-04-25', '2014-04-29') h=h[0] a=h.values() a=','.join(a) a=a.split(',') vol=a[0] sym=a[1] adjcls=a[2] high=a[3] low = a[4] date = a[5] close = a[6] opn = a[7] file1.write(date+",") file1.write(sym+",") file1.write(vol+",") file1.write(adjcls+",") file1.write(high+",") file1.write(low+",") file1.write(close+",") file1.write(opn+",") print vol print date return (vol,adjcls,high,low,close,opn) Answer: You could try the following approach which makes use of Python's [`csv`](https://docs.python.org/2/library/csv.html#module-csv) module to automatically create the correct format for your output: from yahoo_finance import Share import csv def run(): yahoo = Share('YHOO') with open("scripts/hisdata.csv", 'wb') as file1: csv_output = csv.writer(file1) # First write the header row heading = ['Adj_Close', 'Close', 'Date', 'High', 'Low', 'Open', 'Symbol', 'Volume'] csv_output.writerow(heading) h = yahoo.get_historical('2014-04-25', '2014-04-29')[0] csv_output.writerow([h[value] for value in heading]) print h['Volume'] print h['Date'] return ([h[value] for value in ['Volume', 'Adj_Close', 'High', 'Low', 'Open']]) print run() The `yahoo_finance` module returns each entry as a dictionary, so it is easier and safer to extract each entry by name rather than trying to list the values. For me this creates an `output.csv` file containing the following: Adj_Close,Close,Date,High,Low,Open,Symbol,Volume 35.830002,35.830002,2014-04-29,35.889999,34.119999,34.369999,YHOO,28736000 And displays the following output: 28736000 2014-04-29 ['28736000', '35.830002', '35.889999', '34.119999', '34.369999'] The data you are seeing is probably due to the method you are using to view the file, it appears to be decoding it incorrectly. The file should be opened as bytes e.g. ASCII. You should try loading it into a spreadsheet application, e.g. Excel. For LibreOffice Calc try the following: [![LibraOffice import dialog](http://i.stack.imgur.com/C49Eg.png)](http://i.stack.imgur.com/C49Eg.png) To write all of the returned row data to the csv file, the following script could be used: from yahoo_finance import Share import csv def run(): yahoo = Share('YHOO') with open('scripts/hisdata.csv', 'wb') as file1: csv_output = csv.writer(file1) heading = ['Adj_Close', 'Close', 'Date', 'High', 'Low', 'Open', 'Symbol', 'Volume'] csv_output.writerow(heading) for row in yahoo.get_historical('2014-04-25', '2014-04-29'): csv_output.writerow([row[value] for value in heading]) run()
Why can't PhantomJS open my Web page? Question: I'm trying to load [this Web page](https://f8790d1e-aknuds1.node.tutum.io/) from PhantomJS 2 on Ubuntu 15.04, via Python 2/Selenium, but the request simply times out. Why is it unable to open the page? I've tried the following Python script: from selenium import webdriver timeout = 30 driver = webdriver.PhantomJS() driver.set_page_load_timeout(timeout) driver.set_window_size(1024, 768) driver.get('https://f8790d1e-aknuds1.node.tutum.io/') This eventually times out after 30 seconds. Answer: I've edited your script so that it now loads the site and succesfully produces a screenshot. I think the problem was that you've set a too short timeout. It taken out, site will eventually load. Also you have to account for the misconfigured SSL certificate on the demo. **Update:** added time measurements. From my geolocation script runs for 13-14 seconds. from selenium import webdriver import time # timeout = 10 # driver.set_page_load_timeout(timeout) start = time.time() driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=ANY']) driver.set_window_size(1024, 768) driver.get('https://f8790d1e-aknuds1.node.tutum.io/') driver.save_screenshot('screen.png') driver.quit() end = time.time() print(end - start)
pass data from java to python and back jython Question: I am using Jython to run a python script from Java. I am able to send data to the python script as command line arguments when I invoke the script using a `PythonInterpreter`. Now I want to call a Java method from within the Jython script, passing a `List` as a method argument. How do I do that? Answer: I am posting code for both passing of data from Java -> Python and Python -> Java. Hope this helps someone !! In this, String array "s" is passed to python script and from python, "city" list is passed from python to Java through function call getData(). JavaProg.java: import org.python.core.PyInstance; import org.python.util.PythonInterpreter; public class JavaProg { static PythonInterpreter interpreter; @SuppressWarnings("resource") public static void main( String gargs[] ) { String[] s = {"New York", "Chicago"}; PythonInterpreter.initialize(System.getProperties(),System.getProperties(), s); interpreter = new PythonInterpreter(); interpreter.execfile("PyScript.py"); PyInstance hello = (PyInstance) interpreter.eval("PyScript" + "(" + "None" + ")"); } public void getData(Object[] data) { for (int i = 0; i < data.length; i++) { System.out.print(data[i].toString()); } } } PyScript.py: import JavaProg class PyScript: def __init__(self,txt): city = [] for i in range(0,len(sys.argv)): city.append(str(sys.argv[i])) jObj = JavaProg() jObj.getData(city) print "Done!"
NetworkX: How to find the source and target nodes of a directed edge Question: dito above.. I couldn't find anything in the NetworkX docs... In Python Igraph, i can just use: import igraph as ig G = ig.Graph(directed=True) G.add_vertices(2) G.add_edge(0,1) eid = G.get_eid(0,1) edge = G.es[eid] nodes = (edge.source, edge.target) print nodes Answer: The ordering of the tuples is significant. The first element is the source and the second is the target. In [1]: import networkx as nx In [2]: G = nx.DiGraph() In [3]: G.add_edge(1,2) # 1->2 In [4]: G.add_edge(2,3) # 2->3 In [5]: list(G.edges()) Out[5]: [(1, 2), (2, 3)] # 1->2 and 2->3 In [6]: G.add_edge(42,17) # 42->17 In [7]: list(G.edges()) Out[7]: [(1, 2), (2, 3), (42, 17)] In [8]: for e in G.edges(): ...: source,target = e ...: print source ...: 1 2 42
Unwrapping Numpy "object" dtypes Question: Could someone please suggest a pythonic way to unwrap a numpy array with dtype=object? For example, if I started with: array([array([ 1, 2, 3]), array([ 4, 5, 6]), array([ 7])], dtype=object) I would like to return: array([ 1, 2, 3, 4, 5, 6, 7]) as quickly as possible. The order is important, and the actual numbers aren't just ascending integers. The backstory is that the arrays are being pulled from a several-GB ASCII file of varying length and structure, and the data tables have a variable number of columns on each line and I just need to preserve the row-then-column order of the floats as they appear. I'm also amenable to doing this with numpy.loadtxt if the functionality exists; I need to scan the file line-by-line and look for certain headers, then import an unknown number of columns and lines of data, and do this several times throughout the file. Thanks for your time. Answer: Assuming `A` as the input array, you can use [`np.concatenate`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.concatenate.html) to _unwrap_ it, like so - np.concatenate(A) Sample run - In [325]: A Out[325]: array([array([1, 2, 3]), array([4, 5, 6]), array([7])], dtype=object) In [326]: np.concatenate(A) Out[326]: array([1, 2, 3, 4, 5, 6, 7])
Evaluation of math formula in Python (with custom variable names and subscripts) Question: I need to evaluate a bunch of math formulas (string format) for a time series for example: " y = 0.5 * gdp[t] + 0.2 * ln( sp500[t-2] ) " The math formula has two elements I need to take care of: * Custom variable names (e.g. `gdp`) that refer to a time series / array * Variable subscripts to denote indices such as `t-1` or `t-2` for a time series Does anyone have an relatively robust/efficient way to evaluate this formula to a number for a given input (i.e. such as t = 5). Ideally a fast approach but that is a luxury item. Answer: I'm not sure how you want to use `gdp` and `sp500`, but this is an example with `eval` to get you started: import math s = "0.5 * gdp[t] + 0.2 * ln( sp500[t-2] ) " gdp = [0,1,2,3,4,5] sp500 = [0,1,2,3,4,5] t = 5 ln = lambda x: math.log(x) y = eval(s) print y # prints 2.71972245773
Refreshing or re-running a class in Python 2.7 Question: I have a class that retrieves values from a configuration file and a function that adds them. I call the class, change values then run the function to write them. When I call the class afterwards the values are not updated. I check the config file and the values have changed. Is there a way to get it to re-read the data every time I call it? Heres a simplified version... import ConfigParser class read_conf_values(): parser = ConfigParser.ConfigParser() parser.read('configuration.conf') a = parser.get('asection', 'a') def confwrite(newconfig): file = open("configuration.conf", "w") file.write(newconfig) file.close() conf = read_conf_values() print conf.a newvalue = raw_input('Enter a new value for a?') newconfig = '[asection]\na = '+newvalue confwrite(newconfig) conf = read_conf_values() print conf.a I have to write the file instead of using configparser to add values as the actual configuration doesn't have sections. I can read it with a fake section module but I have to write it like a text file. This example has the same problem though. Answer: Your `a` is a class attribute, so it is only created once, at the time you define the class. Do this instead: class read_conf_values(object): def __init__(self): parser = ConfigParser.ConfigParser() parser.read('configuration.conf') self.a = parser.get('asection', 'a') Then a new `a` attribute will be set every time you create an instance (with `read_conf_values()`). You can find many, many other questions on this site about the difference between class and instance attributes.
How to add all elements from python dictionary to database? Question: I'm trying to add the elements of a dictionary to the database. I'm completely new to working with databases and I'm just wondering if I'm doing it right or not, because it seems to me that not. If so, how can I do it ? And how can I print all the elements of the database then ? from sqlalchemy import Column, String, Integer, create_engine from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Person(Base): __tablename__ = 'person' id = Column(Integer, primary_key = True) name = Column(String(250), nullable=False) job = Column(String(250), nullable=False) engine = create_engine('sqlite:///persons.sqlite') session = sessionmaker() session.configure(bind=engine) Base.metadata.create_all(engine) dct = {'John':'doctor', 'Alice':'typist'} for el in dct: np = Person(name=el, job=dct[el]) s = session() s.add(np) s.commit() Answer: You don't need to create a new session for each item: s = session() for name, job in dct.iteritems(): np = Person(name=name, job=job) s.add(np) s.commit()
Closing all the opened chrome windows using selenium - python - osx Question: I have to download some files from a website, I'm using Python - Selenium - Chrome - Osx. I have his code so far: lnk = "www.foobar.com" CHROMEDRIVER=webdriver.Chrome() options = webdriver.ChromeOptions() profile = {"plugins.plugins_list": [{"enabled":False, "name":"Chrome PDF Viewer"}], "download.default_directory" : TEMP_DOWNLOAD} options.add_experimental_option("prefs",profile) driver = webdriver.Chrome(chrome_options = options) driver.get(lnk) while True: if filter(os.path.isfile, glob.glob(TEMP_DOWNLOAD+'/*.crdownload')): pass else: break driver.quit() This code starts the download of the file, waits the end of the download and then closes the webdriver. Everything is working properly except that it opens 2 Chrome windows, one to open the link and the other to download the file, and the quit() method closes only the latter. Is there a way to kill all the windows opened by Selenium (I'm trying to avoid firing a terminal command to kill the processes brute force)? EDIT: as Mukesh Takhtani said in comment in my code the problem is a pointless webdriver instance. Answer: Use this. This I used for Firefox. You can use this for Chrome. Call kill_waste() in your python code and it would kill idle useless Chrome. Please note that this would work for OSX or FreeBSD. For Linux distros you would have to change the way you are going to use grep and cut import commands def kill_waste(): (_,firefox_processes) = commands.getstatusoutput("ps -ax | grep '/usr/local/bin/firefox -foreground' | cut -c1-24") sleep(0.5) firefox_processes = firefox_processes.splitlines() for pid in firefox_processes: values = pid.split() time_value = values[3].split(':') if ((values[2] == 'I' or values[2] == 'I+') and time_value[0] == '1') or time_value[0] == '2': commands.getstatusoutput("kill -9 " + values[0])
python join/format possible hex values for regex Question: I'd like to create a template string as possible values for an expression: '\x1C,\x2C,\x3C,\x4C,\x5C,\x6C,\x7C,\x8C,\x9C,\xAC,\xBC,\xCC,\xDC,\xEC,\xFC' in a manner like this: from string import digits, ascii_uppercase ','.join(['\x'+i+'C' for i in digits+ascii_uppercase[:6]]) but unfortunately join does not treat '\x' litterally: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape Unlike, for example, double slashes: ','.join(['\\x'+i+'C' for i in digits+ascii_uppercase[:6]]) \\x0C,\\x1C,\\x2C,\\x3C,\\x4C,\\x5C,\\x6C,\\x7C,\\x8C,\\x9C,\\xAC,\\xBC,\\xCC,\\xDC,\\xEC,\\xFC' Any ideas around this? Maybe another encoding? Answer: Since you're dealing with characters, deal with characters. ','.join(chr(x) for x in range(0x1c, 0x100, 0x10))
Pattern Matching Tkinter child widgets (winfo_children) to determine type (Python) Question: I'm trying to automatically clear all Entry widgets in a parent widget. import Tkinter import re root=Tkinter.Tk() E1=Tkinter.Entry(root) E1.pack() E2=Tkinter.Entry(root) E2.pack() L1=Tkinter.Label(root,text='Label1') L1.pack() I'm running into 3 problems 1. While I can find out the children widget type, I can't seem to be able to use it in a pattern match. Printing out the wlist[0] below is different from the shell output ? Eg: >> wlist=root.winfo_children() >> wlist [<Tkinter.Entry instance at 0x00000000151911C8>, <Tkinter.Entry instance at 0x00000000151BAD88>, <Tkinter.Label instance at 0x00000000151B29C8>] >> wlist[0] # shell output <Tkinter.Entry instance at 0x00000000151911C8> >> print wlist[0] # print output here is different vs shell output above .353964488L 2. I think due to the differences between the print output & shell output above, my pattern match can't work? Eg >> re.search(r'Entry',wlist[0]) << No output >> 3. Assuming one is able to detemine via pattern match that a child widget is indeed an Entry widget, how would you get the widget object itself to perform a delete method call? Eg: ## Assuming I have a function to to clear the entry ## How would I pass the object from the pattern match in #2 to this function? def clear_entry(objEntry): objEntry.delete(0,Tkinter.END) Answer: Normally you store them in a list or some container. entry_list=[E1, E2] def clear_entry(): for id in entry_list: id.delete(0,Tkinter.END)
Email an attachment with non-ascii filename with python email Question: How can I send an email with a file attached where the file name contains unicode characters? Up to now, the file will arrive but with the filename _"noname"_. This is the part that works perfectly well for ASCII filenames: import smtplib from email.mime.text import MIMEText from email.MIMEBase imppart.add_header('Content-Disposition', 'attachment', filename=('utf-8', 'fr', os.path.basename(f).encode('utf-8')))ort MIMEBase from email.MIMEMultipart import MIMEMultipart from email.mime.application import MIMEApplication from email.Utils import formatdate from email import Encoders from email.Utils import encode_rfc2231 msg = MIMEMultipart() msg['Subject'] = "New magazine delivery!" msg['From'] = sender_email msg['To'] = ', '.join(kindle_emails) msg['Date'] = formatdate(localtime=True) message = "see attachment" msg.attach(MIMEText(message)) part = MIMEApplication(open(f, 'rb').read(), _subtype='application/x-mobipocket-ebook') part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename) msg.attach(part) **First try** Adding a tuple of encoding, language and encoded string and not only the filename. part.add_header('Content-Disposition', 'attachment', filename=('utf-8', 'fr', os.path.basename(f).encode('utf-8'))) **Second try:** Setting the charset globally like this: from email import Charset Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') **Third try** Using `utils.encode_rfc2231` from email.Utils import encode_rfc2231 utf8filename = encode_rfc2231(os.path.basename(f).encode('utf-8'), charset='utf-8') part.add_header('Content-Disposition', 'attachment', filename=('utf-8', 'fr', utf8filename)) **Fourth try** Using `urllib.quote()` to urlencode the filename. This has the same effect on the filename as the third method. utf8filename = urllib.quote(os.path.basename(f).encode('utf-8')) part.add_header('Content-Disposition', 'attachment', filename=('utf-8', 'fr', utf8filename)) Any ideas? Am I missing something essential about RFC2231 filename character encoding? I use Gmail's SMTP server and python 2.7. Answer: Instead of telling the server that it's UTF-8 like this: filename=('utf-8', 'fr', os.path.basename(f).encode('utf-8'))) ...it works when I just send UTF-8 without telling so: filename=os.path.basename(f).encode('utf-8')) The file name will be properly displayed. This seems to contradict the [documentation](https://docs.python.org/2/library/email.message.html) which states: > If the value contains non-ASCII characters, it must be specified as a three > tuple in the format (CHARSET, LANGUAGE, VALUE), where CHARSET is a string > naming the charset to be used to encode the value, LANGUAGE can usually be > set to None or the empty string (see RFC 2231 for other possibilities), and > VALUE is the string value containing non-ASCII code points. This doesn't work, however the [python 3 documentation](https://docs.python.org/3/library/email.message.html) adds: . > If a three tuple is not passed and the value contains non-ASCII characters, > it is automatically encoded in RFC 2231 format using a CHARSET of utf-8 and > a LANGUAGE of None. Only this works, even for python 2.7, though it's not mentioned in the docs.
"Placing" arbitrary number of values into Python Flask request_context? Question: So I have a Python Flask app such as the following: (it's actually a [Clay Flask](https://pypi.python.org/pypi/clay-flask/1.1 "Clay Flask") app, but whatever): `some_file.py`: @app.route('/v1/some/route', methods=['GET']) def some_method(): arg1 = request.args.get('arg1', None) arg2 = request.args.get('arg2', None) header1 = request.headers.get('header1', None) result = my_class.method_call(arg1, arg2, header1) `my_class.py`: ... def method_call(self, arg1, arg2): # need to access header1 here some_other_service.make_request(arg1, arg2, header1) The problem, is, I have a large number of headers, not just `header1`, that `method_call` needs to know about in its call to `some_other_service.make_request`. I could pass them all into `method_call`, or create a wrapper object that has all of the headers as attributes, but have been recommended to put the headers in the Flask/Clay `request_context`. Here is where I'm stuck. I've read documentation on Flask and request_contexts, but am still confused. How would I accomplish something like this? Answer: You can just use request in your Class. # from Flask import request def method_call(self, arg1, arg2): # need to access header1 here foo = request.headers.get('foo') bar = request.headers.get('bar') some_other_service.make_request(arg1, arg2, header1)
P4Python - Create a pending changelist and keep default pending Question: I use change = P4.fetch_change() change['Description'] = Description result = p4.save_change(change) but it will move my default file into this changelist. is there has any way to just create empty pending changelist and keep my file in the default? Answer: A numbered pending changelist is created by saving a changelist 'form', which in your program is identified by the Python 'change' variable. The contents of this changelist form are up to you, but in this particular snippet you are populating the changelist form by running the P4Python `fetch_change()` method. That is, you're asking Perforce to create a pending changelist form for you. When you ask Perforce to create a pending changelist form for you, it will automatically include all of the files that are open in your default changelist as part of the new changelist form. But that is not required; that is just the default behavior. Here, it is instructive to run `p4 change -o` from the command line, with several of your files already open in the default changelist. You will see that Perforce automatically includes those files in the generated pending changelist form. If, instead of running `P4.fetch_change()` to initialize your pending changelist form, you create your pending changelist form from scratch, you can create a pending changelist form which has **NO** files in the form, and then your new pending changelist will be empty (that is, it will contain no files). Or, you can run `P4.fetch_change()` to initialize your `change` variable, but then before you call `save_change` you can remove the files from the change variable, and leave only the description and other identifying information in the form. Either way, the important thing is that when you call `save_change()`, the files that will be included in the change are the ones which are in the form that you provide, so simply ensure that the `change` variable has the correct contents. Lastly, if you get the wrong files in the pending changelist, you can always change that later, prior to submit. For example, the `p4 reopen` command is a convenient way to move files from one pending changelist to another (or to and from the default changelist).
Initializing Python static class attributes in the constructor call Question: In some Google [documentation](https://cloud.google.com/appengine/docs/python/tools/protorpc/) there is the following code (abbreviated for clarity). The class `Note` is defined and then instantiated with a parameter in the constructor call. I wasn't aware that attributes could be initialized this way. Is this a native Python feature or some magic that is happening in the Message superclass? from protorpc import messages class Note(messages.Message): text = messages.StringField(1, required=True) # Import the standard time Python library to handle the timestamp. note_instance = Note(text = u'Hello guestbook!') Answer: It doesn't work the way you're thinking. The class `Note` inherits from `Message`. `Message` (or some other class it inherits from) has code in its `__init__()` method to do this. There's no magic.
running a django app on apache with SSL: pexpect spawn/expect doesn't work Question: I'm running a django app on apache 2.2 with SSL enabled. When I don't have the SSL enabled, all is well. But with security, there probably are some restrictions on how an os can fork off a process, etc. I'm not aware of those at all. OS used: Solaris (not sure if it matters, but it could) Django v1.4, Apache 2.2, Python 2.7 An outline of what I'm doing in one of my views: def run_step(request, action): if (action == "action1"): p = subprocess.Popen("command1", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) elif (action == "action2"): password = mylib.getpasswd() ## Method 1: with pexpect command = pexpect.spawn('su root -c \' command2 \'') command.expect('[pP]assword*') command.sendline(password) ## Method 2: with subprocess and a simple command #command = subprocess.Popen('ls > log.file', shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) ## Method 3: with subprocess stdin PIPE #command = subprocess.Popen('command2', shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,stdin=subprocess.PIPE) #command.stdin.write(password) #command.communicate() ## I tried with shell = False, ## with stdin.flush() and communicate(password) too. The command for 'Action1' gets executed very well. But the problem with those which need interaction like that of 'Action2'. I tried three different methods: * Method1: sent it using pexpect as usual but it fails - the command doesn't get executed at all. * Method2: tried a subprocess call wihtout an interaction - works. * Method3: tried a subprocess call with a stdin pipe to try interaction but failed again. I'm not sure how to go about this now. Any help would be very highly appreciated. Answer: Here is what worked for me: Spawned the pexpect call as a separate thread using the 'threading' module in python, and then sent the password using a sendline. import threading command = 'ls -l' #some_command t = threading.Thread(target=some_function,args=(command,)) t.start() def some_function(command): some_process = pexpect.spawn(command) some_process.expect('[pP]assword*') some_process.sendline(some_password) some_process.expect(pexpect.EOF,timeout=1000) I don't still understand why the pexpect module, as is, did not work on the main thread. Would still appreciate any answers, but I'm going with this solution for now.
Python import class simple example error Question: I wonder why my simple example building a class is not properly working: The tree-structure looks like the following class_project/ ├── class_project │   ├── __init__.py │   └── classtheclass.py └── tests ├── __init__.py └── test.py classtheclass.py looks like this: class ClassTheClass(object): def __init__(self): print "yeees" test.py looks like this: from class_project.classtheclass import ClassTheClass i = ClassTheClass() While **init**.py are empty so if i execute on the shell > python test.py its giving me > Traceback (most recent call last): File "test.py", line 1, in from > class_project.classtheclass import ClassTheClass ImportError: No module > named class_project.classtheclass Whats wrong with that. In Pycharm this even works...! Answer: When you run `python test.py`, the interpreter will look for Python code in standard library locations (e.g. `/usr/local/lib/python2.7/site-packages` and friends) and in the `tests` folder where you invoked the interpreter (this set of locations is known as the "Python Path", and you can view it with: `import sys; print sys.path`). None of those locations include `class_project.classtheclass`. There are a variety of ways to solve this problem. You can set the `PYTHONPATH` environment variable to include `class_project`: export PYTHONPATH="/path/to/class_project:$PYTHONPATH" # Note: this has to be the top-level class_project directory, you have two with this name here. python test.py # This will now work * * * You could probably also use a relative import, but I'd argue that's working around the problem not solving the problem.
matplotlib - How can I use MaxNLocator and specify a number which has to be in an axis? Question: I do have a question with matplotlib in python. I create different figures, where every figure should have the same height to print them in a publication/poster next to each other. If the y-axis has a label on the very top, this shrinks the height of the box with the plot. So I use MaxNLocator to remove the upper and lower y-tick. In some plots, I want to have the 1.0 as a number on the y-axis, because I have normalized data. So I need a solution, which expands in these cases the y-axis and ensures 1.0 is a y-Tick, but does not corrupt the size of the figure using tight_layout(). Here is a minimal example: import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator x = np.linspace(0,1,num=11) y = np.linspace(1,.42,num=11) fig,axs = plt.subplots(1,1) axs.plot(x,y) locator=MaxNLocator(prune='both',nbins=5) axs.yaxis.set_major_locator(locator) plt.tight_layout() fig.show() Here is a [link](https://depot.uni-konstanz.de/cgi- bin/exchange.pl?g=n4hq3y25kt) to a example-pdf, which shows the problems with height of upper boxline. I tried to work with adjust_subplots() but this is of no use for me, because I vary the size of the figures and want to have same the font size all the time, which changes the margins. Question is: How can I use MaxNLocator and specify a number which has to be in the y-axis? Hopefully someone of you has some advice. Greetings, Laenan Answer: Assuming that you know in advance how many plots there will be in 1 row on a page one way to solve this would be to put all those plots into one figure - `matplotlib` will make sure they are alinged on axes: import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator x = np.linspace(0, 1, num=11) y = np.linspace(1, .42, num=11) fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2}) ax1.plot(x,y) ax2.plot(x,y) locator=MaxNLocator(prune='both', nbins=5) ax1.yaxis.set_major_locator(locator) # You don't need to use tight_layout and using it might give an error # plt.tight_layout() fig.show() [![enter image description here](http://i.stack.imgur.com/94y9y.png)](http://i.stack.imgur.com/94y9y.png)
Premailer - UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position Question: I am trying to use `premailer` to transform an html document that I've created into something that I can email with inline css styling. However when I try make the transform I am getting the following error: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/Users/oldo/Python/virtual-environments/AMS-Journal/lib/python2.7/site-packages/premailer/__main__.py", line 142, in <module> sys.exit(main(sys.argv[1:])) File "/Users/oldo/Python/virtual-environments/AMS-Journal/lib/python2.7/site-packages/premailer/__main__.py", line 137, in main options.outfile.write(p.transform(pretty_print=options.pretty)) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 106688: ordinal not in range(128) I've seen that there a plethora of questions by people coming up with similar problems however I can't seem to make any progress with rectifying the fault. My file is encoded in `utf-8` and so I am confused as to why I'm getting this error. Would anyone have any suggestions on something that I can try to make some moves forward? Answer: Well after a lot of faffing around I was finally able to fix the source of the problem. Obviously I need to learn a bit more about the differences between text encodings and how to handle them in Python. The input file that I was handing premailer was encoded in `utf-8` and the program seems to require `ascii`. I am creating the input file using jinja2 linked with a mongodb and I forced the file to be written to `ascii` and to ignore errors. import io # stuff setting up jinja ready to render the template... renderedTemplate = template.render(context) email = io.open('email.html', 'w', encoding='ascii', errors="ignore") email.write(renderedTemplate) email.close() I realise that this is not an ideal solution because the `utf-8` characters that are not recognised by `ascii` will just be dropped, so there may be a couple of funny looking words, but hopefully this will not be too much of a problem. I'm just happy to be moving forwards again with my project!
Python: how to convert a string array to a factor list Question: Python 2.7, numpy, create levels in the form of a list of factors. I have a data file which list independent variables, the last column indicates the class. For example: 2.34,4.23,0.001, ... ,56.44,2.0,"cloudy with a chance of rain" Using numpy, I read all the numeric columns into a matrix, and the last column into an array which I call "classes". In fact, I don't know the class names in advance, so I do not want to use a dictionary. I also do not want to use Pandas. Here is an example of the problem: classes = ['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd'] type (classes) <type 'list'> classes = numpy.array(classes) type(classes) <type 'numpy.ndarray'> classes array(['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd'], dtype='|S1') # requirements call for a list like this: # [0, 1, 2, 2, 1, 0, 3] Note that the target class may be very sparse, for example, a 'z', in perhaps 1 out of 100,000 cases. Also note that the classes may be arbitrary strings of text, for example, scientific names. I'm using Python 2.7 with numpy, and I'm stuck with my environment. Also, the data has been preprocessed, so it's scaled and all values are valid - I do not want to preprocess the data a second time to extract the unique classes and build a dictionary before I process the data. What I'm really looking for was the Python equivalent to the `stringAsFactors` parameter in R that automatically converts a string vector to a factor vector when the script reads the data. Don't ask me why I'm using Python instead of R - I do what I'm told. Thanks, CC. Answer: You could use [`np.unique`](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html) with `return_inverse=True` to return both the unique class names and a set of corresponding integer indices: import numpy as np classes = np.array(['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd']) classnames, indices = np.unique(classes, return_inverse=True) print(classnames) # ['a' 'b' 'c' 'd'] print(indices) # [0 1 2 2 1 0 0 3] print(classnames[indices]) # ['a' 'b' 'c' 'c' 'b' 'a' 'a' 'd'] The class names will be sorted in lexical order.
Choose three different values from list in Python Question: I have a list of points with their coordinates, looking like this: [(0,1),(2,3),(7,-1) and so on.] What is the Pythonic way to iterate over them and choose three different every time? I can't find simpler solution than using three `for` loops like this: for point1 in a: for point2 in a: if not point1 == point2: for point3 in a: if not point1 == point3 and not point2 == point3: So I'm asking for help. Answer: import random lst = [(0, 1), (2, 3), (7, -1), (1, 2), (4, 5)] random.sample(lst, 3) This will just give you 3 points chosen at random from the list. It seems you may want something different. Can you clarify?
Python: setup() vs __init__ ()for a socketserver's handler class Question: I am trying to define a handler class for a `socketserver`. When the handler class had no `__init__()` method defined, my server worked. The message sent by the client was written to the output window. However, when I added an `__init__()` method to declare a class member, my program threw an exception because `RequestHandlerClass` required exactly one argument, and I was passing four arguments to it. After pounding my head into a brick wall for a while, I remembered that the `BaseRequestHandler` class has an override-able `setup()` method. I declared an override for it and declared my class member inside it, and it worked. While I have a solution to my immediate problem, I'd like to understand this. Should I never declare my own `__init__()` method in a request handler class? Or if I should, how should it be declared? Here's my code: import socketserver import logging import logging.config import json from TWMSMessageHandler import TWMSMessageHandler class SingleTCPHandler(socketserver.BaseRequestHandler): # def __init__(self): ## causes an error def setup(self): self.messageHandler = TWMSMessageHandler() # One instance per connection. Override handle(self) to customize action. def handle(self): # self.request is the client connection data = self.request.recv(1024) # clip input at 1Kb dataString = data.decode() print ("Received data: " + dataString) self.request.close() class MyTCPServer(socketserver.TCPServer): def __init__(self, serverAddress, handler): super().__init__(serverAddress, handler) def handle_timeout(self): print ("No message received in {0} seconds".format(self.timeout)) if __name__ == "__main__": with open('TWMSHandler_log_config.json', 'rt') as f: config = json.load(f) logging.config.dictConfig(config) tcpServer = MyTCPServer(("127.0.0.1", 5006), SingleTCPHandler) tcpServer.timeout = 30 loopCount = 0 while loopCount < 5: try: print ("About to wait for request") tcpServer.handle_request() print ("Back from handle_request") loopCount = loopCount + 1 except Exception as Value: print ("Oops! " + str(Value)) break Answer: I'm assuming python 2.7 since you haven't specified otherwise, this should apply to python 3.x too, however. If you take a look at the source code (<https://hg.python.org/cpython/file/2.7/Lib/SocketServer.py#l631>), the BaseRequestHandler class which you are overriding takes 3 arguments besides `self`: `request, client_address, server`. If you want to override `__init__` you must be compatible with this signature, unless you also override the callsite that calls `__init__` from within the TCPServer inheritance chain (You don't want to do this). Since all that function does is to save state you would otherwise have to save yourself (Or call the base function through a `super` call), you may as well just use `setup` as you are.
Python flask-sqlalchemy - windows functions query error? Question: I'm trying to use a windows function so that I can ultimately pull up just the last result frrom each eternal_id, and am getting stuck just trying to get a windows function to work. I see the error whether I connect to the engine and select from it, or initiate a session and query from it. Here's what I tried (the "intiate a session and query from it" method): engine = create_engine('sqlite:///../../app.db') sessionfactory = sessionmaker(bind=engine) s = sessionfactory() myquery = s.query(models.case.id, models.case.eternal_id, func.count().over( partition_by=models.case.eternal_id).label('cnt')) print myquery.all() Here's the error I get: OperationalError: (sqlite3.OperationalError) near "(": syntax error [SQL: u'SELECT "case".id AS case_id, "case".eternal_id AS case_eternal_id, count(*) OVER (PARTITION BY "case".eternal_id) AS cnt \nFROM "case"'] If I remove `func.count().over(partition_by=models.case.eternal_id).label('cnt')` from the query everything runs perfectly. Anyone have any idea why I'm getting an error?? Here's the model if it helps: from app import db class case(db.Model): id = db.Column(db.Integer, primary_key=True) eternal_id = db.Column(db.Integer, db.ForeignKey('case_eternal.id')) eternal = db.relationship('case_eternal', back_populates='case_sids') def __repr__(self): return '<Case %r>' % (self.id) class case_eternal(db.Model): id = db.Column(db.Integer, primary_key=True) case_sids = db.relationship('case', back_populates='eternal') Answer: SQLite does not have window functions.
How can I measure elapsed time between the press of buttons in python with tkinter? Question: I'm very new to python and I'm trying to do a little project for myself, but I don't understand how to use the initial time variable from the start function in the stop function where I can do math with it. This is my code currently: import time import Tkinter import tkMessageBox top = Tkinter.Tk() def start_time(): tkMessageBox.showinfo("Timer", "The timer will now begin") initial = time.time() return initial def stop_time(initial): final = time.time() tkMessageBox.showinfo("Timer", final - initial) Start = Tkinter.Button(top, text ="Start", command = start_time) Stop = Tkinter.Button(top, text ="Stop", command = stop_time) Start.pack() Stop.pack() top.mainloop() Answer: Your functions need to agree on a common place for shared data. For this simple example, the module's global namespace is a good choice. All you need to do is add `global initial` to the functions that update it. For larger projects you may move to objects that hold the variables and the functions that update it, but this is fine for your goals. import time import Tkinter import tkMessageBox initial = 0 top = Tkinter.Tk() def start_time(): global initial tkMessageBox.showinfo("Timer", "The timer will now begin") initial = time.time() return initial def stop_time(): # you could check for initial == 0 and display an error final = time.time() tkMessageBox.showinfo("Timer", final - initial) Start = Tkinter.Button(top, text ="Start", command = start_time) Stop = Tkinter.Button(top, text ="Stop", command = stop_time) Start.pack() Stop.pack() top.mainloop()
Not working in Python 2, Python 2 vs Python 3 Inheriting a wrapper Question: I am working on a Flask based OAuth project that has a single instance of `OAuthSignIn` class. This class has three subclasses for each OAuth client I support, Facebook, Twitter, and Google. There is only one instance of each on the server and they all contain an object called `oauth_session` used to make endpoint calls to the appropriate OAuth endpoint. To ensure these calls are on the behalf of the current user, before I make a call, I have to edit the `access_token` variable of the `oauth_session` object to the current user's `session['access_token']`. I want to do this via a wrapper found in the super class (OAuthObject). The following is a very basic model of what I am doing on the server just show the inheritance of it and what not. I made a wrapper to do edit the subclass's `oauth_session.access_token` and threw that in the super class of `OAuthObect` so I only have to write it once. from functools import wraps class OAuthSessionObject(): def __init__(self): self.access_token = "r424jt3g" class OAuthObject(): def __init__(self): pass def auth_request(f): @wraps(f) def wrapper(self): self.oauth_session.access_token = 444 #self.oauth_session.access_token = session['access_token'] return f(self) return wrapper class GoogleObject(OAuthObject): def __init__(self): self.oauth_session = OAuthSessionObject() @OAuthObject.auth_request def make_request(self): print("Making a request with updated access_token:", self.oauth_session.access_token) google = GoogleObject() google.make_request() ### Python 2 vs Python 3 Problem with this, it only [works](https://repl.it/Bcal) in Python 3, and I am currently running Python 2 server on heroku and locally, I get the following errors: @OAuthSignIn.auth_request TypeError: unbound method auth_request() must be called with OAuthSignIn instance as first argument (got function instance instead) How can I make this work in Python 2?? Answer: ### Figured out the solution but need explanation: All I had to do to get it to work in Python 2 was to modify the wrapper function to look like this: @classmethod def auth_request(self, f): @wraps(f) def wrapper(self): self.oauth_session.access_token = session['access_token'] return f(self) return wrapper Had to make it a `@classmethod` and just add `self` as the first parameter to the `auth_request` declaration. Not sure why though, if someone would like to explain why this is treated differently between the two versions of Python that would be great.
Error exporting symbol when building Python C Extension in Windows Question: I'm working on porting a Python module to Windows. I have a toy example as follows. The folder structure is: foo/ libfoo/ foo.c setup.py **setup.py** from setuptools import setup, Extension sources = ['libfoo/foo.c'] foo = Extension('libfoo', sources = sources, define_macros = None, include_dirs = ['./libfoo'], libraries = None, library_dirs = None, ) setup(name = 'foo', ext_modules = [foo], install_requires = ['setuptools'], ) **libfoo/foo.c** (for completeness) #include <stdio.h> void foo() { printf("Hello World!"); } When I attempt to install the package, I encounter an error. C:\Users\user\foo>python setup.py install running install running bdist_egg running egg_info creating foo.egg-info writing requirements to foo.egg-info\requires.txt writing foo.egg-info\PKG-INFO writing top-level names to foo.egg-info\top_level.txt writing dependency_links to foo.egg-info\dependency_links.txt writing manifest file 'foo.egg-info\SOURCES.txt' reading manifest file 'foo.egg-info\SOURCES.txt' writing manifest file 'foo.egg-info\SOURCES.txt' installing library code to build\bdist.win32\egg running install_lib running build_ext building 'libfoo' extension creating build creating build\temp.win32-2.7 creating build\temp.win32-2.7\Release creating build\temp.win32-2.7\Release\libfoo c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I./libfoo -IC:\Python27\include -IC:\Python27\PC /Tclibfo o/foo.c /Fobuild\temp.win32-2.7\Release\libfoo/foo.obj foo.c creating build\lib.win32-2.7 c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\Python27\libs /LIBPATH:C:\Python27\PCbuild /EXPORT:i nitlibfoo build\temp.win32-2.7\Release\libfoo/foo.obj /OUT:build\lib.win32-2.7\l ibfoo.pyd /IMPLIB:build\temp.win32-2.7\Release\libfoo\libfoo.lib /MANIFESTFILE:b uild\temp.win32-2.7\Release\libfoo\libfoo.pyd.manifest LINK : error LNK2001: unresolved external symbol initlibfoo build\temp.win32-2.7\Release\libfoo\libfoo.lib : fatal error LNK1120: 1 unresolv ed externals error: command 'c:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\BIN\\l ink.exe' failed with exit status 1120 It seems that the distutils package (in this case setuputils) will always export one symbol from a shared extension and that is "init + extension_name" [[Link]](https://docs.python.org/2/distutils/apiref.html#distutils.core.Extension). It is specified in the Windows Linker "EXPORT" option [[Link]](https://msdn.microsoft.com/en-us/library/7k30y2k5.aspx) but it can't find the symbol. Help? EDIT: The C code does not use the Python C API i.e. "#include ". This is because the goal of the project is to take an existing C library and encase in a Python wrapper via a Python extension. The package works on Unix/Linux. Answer: After lots of playing around, I was able to understand the issue. # Solution: in Windows, you _must_ define an initialization function for your extension because setuptools will build a .pyd file, not a DLL **To resolve this in Python 2, you define the`initlibfoo()` method in the source.** #include <Python.h> PyMODINIT_FUNC initlibfoo(void) { // do stuff... } **To resolve this in Python 3, you define the`PyInit_libfoo()` method in the source.** #include <Python.h> PyMODINIT_FUNC PyInit_libfoo(void) { // do stuff... } so now, **foo.c** will look like: #include <stdio.h> #include <Python.h> void foo() { printf("Hello World!"); } PyMODINIT_FUNC initlibfoo(void) // Python 2.7 //PyMODINIT_FUNC PyInit_libfoo(void) // Python 3.5 { // do stuff... } ## Explanation When compiling Python extensions for Windows, the [Extension](https://docs.python.org/2/distutils/apiref.html#distutils.core.Extension) class will tell the [linker to export a function](https://msdn.microsoft.com/en-us/library/7k30y2k5.aspx) for other programs to call. That can be seen in the terminal output: c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\Python27\libs /LIBPATH:C:\Python27\PCbuild /EXPORT:i nitlibfoo build\temp.win32-2.7\Release\libfoo/foo.obj /OUT:build\lib.win32-2.7\l ibfoo.pyd /IMPLIB:build\temp.win32-2.7\Release\libfoo\libfoo.lib /MANIFESTFILE:b uild\temp.win32-2.7\Release\libfoo\libfoo.pyd.manifest (emphasis on `/EXPORT:initlibfoo`) Now this is a required function for C/C++ Extensions so that they can be imported as modules. In other words, when you `import libfoo` Python will call the function `initlibfoo` on the .pyd as part of the initialization of the module. The error encountered here is due to the fact that the linker is told to export the function `initlibfoo` however it can't find the symbol in the C object files because it was never defined in the source! Surely, one should be able to decline the option of export a symbol right? Apparently not. Referring back to the Extension class documentation, there's an argument `export_symbols`. I tried passing `None` to it and the linker option was still being used. It seems there's no way to circumvent this linker option. **NOT RECOMMENDED** : if for some reason, needing to have `Python.h` bothers you, there's a way around this. You still need to define the "init" methods above but you can do: void initlibfoo() {} //Python 2.7 void PyInit_libfoo() {} //Python 3.5 But now, you **can't** use the library via `import libfoo`. You could use the **ctypes** module and load it with `ctypes.PyDLL('/path/to/pyd')`. Essentially, you used Python to build a DLL for you, in which case, it does but it builds a special DLL known as a .pyd file. Then to use it, you must load it in via **ctypes** module.
python xml.etree.ElementTree get everything inside element whether its text or children Question: I am using `xml.etree.ElementTree`, and if possible would like not to change XML parsing library. I can parse XML file without any problem. I have a speclial `<description>` tag which contains text and want to retrieve this text. Here is the code I am using for that purpose: import xml.etree.ElementTree as ET rss = ET.fromstring(rss_content) for node in rss[0].getchildren(): if node.tag == 'description': print node.text so far, so good. But I sometimes have as text another xml content and can't retrieve this as a text. I could retrieve this with methods as `getchildren` and make a switch case whether this is recognized as text or as XML; but I was wondering if I could directly retrieve the whole content, XML or not, as text, in a simpler way? Answer: There is the `itertext()` method on an ElementTree Element - it returns all the nested text, for example: xmltxt='''<?xml version="1.0"?> <TEXT> <Description> <V>played</V> <N>John</N> <PREP>with</PREP> <en x='PERS'>Adam</en> <PREP>in</PREP> <en x='LOC'> ASL school</en> </Description> <Description> <V y='0'>went</V> <en x='PERS'>Mark</en> <PREP>to</PREP> <en x='ORG'>United Nations</en> <PREP>for</PREP> <PREP>a</PREP> <N>visit</N> </Description> </TEXT> ''' root = ET.fromstring(xmltxt) for ch in root: print ch print "".join(ch.itertext()) print ET.tostring(ch) Output is: played John with Adam in ASL school <Description> <V>played</V> <N>John</N> <PREP>with</PREP> <en x="PERS">Adam</en> <PREP>in</PREP> <en x="LOC"> ASL school</en> </Description> went Mark to United Nations for a visit <Description> <V y="0">went</V> <en x="PERS">Mark</en> <PREP>to</PREP> <en x="ORG">United Nations</en> <PREP>for</PREP> <PREP>a</PREP> <N>visit</N> </Description> Or to recurse through nested elements, use `iter()` method, collecting .text for text within the tag, and .tail for text after a tag.
How to implement roulette wheel for picking random objects in python? Question: In python, I have a list of objects (size of list is >= 2), which have a property called `score` which has a value which is any float that's >= 0 (no upper bound). I want to randomly pick 2 different objects from the list, but make sure that there is a higher chance of picking a value that has a higher score. Basically the higher the score the more chance of being picked. I was thinking of doing a roulette style, where I take a sum of all scores, and then getting a perfect of each item where it's percent is its score divided by the total score. But how do I still pick the 2 objects? Thanks Answer: The question is not super clear, but I think I get what you mean. You should use a inverse CDF type approach. The below example will return you an index for your list of scores, then just use that to get the value you want. Obviously there are smarter ways to do this from a programming point of view, but you clearly need to understand the method, which I think this example will help a lot with. >>> import numpy as np >>> import pandas as pd >>> scores = [100, 200, 300, 400, 500] >>> scores = np.array(scores) >>> sum = scores.sum() >>> sum 1500 >>> percentages = scores/float(sum) >>> percentages array([ 0.06666667, 0.13333333, 0.2 , 0.26666667, 0.33333333]) >>> cdf = percentages.cumsum() >>> cdf array([ 0.06666667, 0.2 , 0.4 , 0.66666667, 1. ]) >>> cdf = np.concatenate([np.array([0]), cdf]) >>> cdf array([ 0. , 0.06666667, 0.2 , 0.4 , 0.66666667, 1. ]) >>>def returnobj(cdf, randnum): >>> for i in range(len(cdf)-1): >>> if((randnum>cdf[i])&(randnum<=cdf[i+1])): >>> return i ########## #This Bit is just to show how the results look, and to show it favours higher scores >>>for i in range(10000): >>> results.append(returnobj(cdf, np.random.random())) >>>results=pd.DataFrame(results) >>>results[results.columns[0]] = results[results.columns[0]].astype(str) >>>results['a'] = results[0] >>>print results.groupby(0).count() 0 639 1 1375 2 2039 3 2678 4 3269
Website scraping: python requests not downloading full site? Question: I'm having problems in scraping a website. The aim will be to scrape prices for hotels in London for certain days. For that I'm loading the below URL from booking.com and then try to search for keywords. But for some reason the requests.get doesn't download the full site. For example the URL below displays a list of hotels in my browser. Each of them showing 'Total' and the the price. However, in the below code site.find('Total') shows that no word 'Total' can be found in the string, even though it's visible in the browser. Any suggestions why this happens are appreciated. import requests url='http://www.booking.com/searchresults.en-gb.html?label=gen173nr-17CAEoggJCAlhYSDNiBW5vcmVmaFCIAQGYAS64AQTIAQTYAQHoAQH4AQs;sid=1a43e0952558ac0ad0061d5b6523a7bc;dcid=1;checkin_monthday=4;checkin_year_month=2016-2;checkout_monthday=11;checkout_year_month=2016-2;city=-2601889;class_interval=1;csflt=%7B%7D;group_adults=7;group_children=0;highlighted_hotels=1192837;hp_sbox=1;label_click=undef;no_rooms=1;review_score_group=empty;room1=A%2CA%2CA%2CA%2CA%2CA%2CA;sb_price_type=total;score_min=0;si=ai%2Cco%2Cci%2Cre%2Cdi;ss=London;ssafas=1;ssb=empty;ssne=London;ssne_untouched=London&;order=price_for_two' r=requests.get(url) site=r.text site.find('Total') Answer: The "Total" information you're talking about is generated with Javascript in the browser. The Requests library can't generate this HTML for you because it isn't a browser environment. To see what I'm talking about, try running that URL in a browser without Javascript. [![enter image description here](http://i.stack.imgur.com/WEVlm.png)](http://i.stack.imgur.com/WEVlm.png) If you want to scrape HTML that requires Javascript to run, you should look into a library that binds to a browser environment, like [Selenium](http://selenium-python.readthedocs.org/api.html).
Python 3.5 - Placing Buttons on Top of Buttons Question: So I am creating a piano program that plays sound when a button is pressed on the tkinter gui interface. When I place the buttons at the places I want them to be. The black keys for the piano are behind the white keys. [Image Link](http://i.stack.imgur.com/MjoHd.png). How can I make it so that the black keys are on top of the white keys. Code Below from tkinter import * import winsound Gui=Tk() Gui.title("Piano") Gui.geometry("400x400") def PianoF(): winsound.PlaySound("PianoF.wav",winsound.SND_ASYNC) def PianoGb(): winsound.PlaySound("PianoGb.wav",winsound.SND_ASYNC) def PianoG(): winsound.PlaySound("PianoG.wav",winsound.SND_ASYNC) def PianoAb(): winsound.PlaySound("PianoAb.wav",winsound.SND_ASYNC) def PianoA(): winsound.PlaySound("PianoA.wav",winsound.SND_ASYNC) def PianoBb(): winsound.PlaySound("PianoBb.wav",winsound.SND_ASYNC) def PianoB(): winsound.PlaySound("PianoB.wav",winsound.SND_ASYNC) def PianoC(): winsound.PlaySound("PianoC.wav",winsound.SND_ASYNC) def PianoDb(): winsound.PlaySound("PianoDb.wav",winsound.SND_ASYNC) def PianoD(): winsound.PlaySound("PianoD.wav",winsound.SND_ASYNC) def PianoEb(): winsound.PlaySound("PianoEb.wav",winsound.SND_ASYNC) def PianoE(): winsound.PlaySound("PianoE.wav",winsound.SND_ASYNC) FNote=Button(Gui,height=15,width=6,bg='white',command=PianoF) GbNote=Button(Gui,height=9,width=5,bg='black',command=PianoGb) GNote=Button(Gui,height=15,width=6,bg='white',command=PianoG) AbNote=Button(Gui,height=9,width=5,bg='black',command=PianoAb) ANote=Button(Gui,height=15,width=6,bg='white',command=PianoA) BbNote=Button(Gui,height=9,width=5,bg='black',command=PianoBb) BNote=Button(Gui,height=15,width=6,bg='white',command=PianoB) CNote=Button(Gui,height=15,width=6,bg='white',command=PianoC) DbNote=Button(Gui,height=9,width=5,bg='black',command=PianoDb) DNote=Button(Gui,height=15,width=6,bg='white',command=PianoD) EbNote=Button(Gui,height=9,width=5,bg='black',command=PianoEb) ENote=Button(Gui,height=15,width=6,bg='white',command=PianoE) GbNote.place(x=28,y=0) AbNote.place(x=84,y=0) BbNote.place(x=140,y=0) DbNote.place(x=252,y=0) EbNote.place(x=308,y=0) FNote.place(x=0,y=0) GNote.place(x=56,y=0) ANote.place(x=112,y=0) BNote.place(x=168,y=0) CNote.place(x=224,y=0) DNote.place(x=280,y=0) ENote.place(x=336,y=0) Answer: for w in (ANote, BNote, CNote, DNote, ENote, FNote, GNote): w.lower() Using a list instead of that type of names would be better.
Unable to locate english.txt file when trying to install Python Bitcoin module Question: When I try and import pybitcointools using "from bitcoin import *" from (<https://github.com/vbuterin/pybitcointools>) I get the following error, indicating the "english.txt" file is missing from one of the installation directories. How do I fix this? > > > from bitcoin import * Traceback (most recent call last): File "", line > 1, in File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- > packages/bitcoin-1.1.39-py2.7.egg/bitcoin/**init**.py", line 10, in from > bitcoin.mnemonic import * File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- > packages/bitcoin-1.1.39-py2.7.egg/bitcoin/mnemonic.py", line 7, in > wordlist_english=list(open(os.path.join(os.path.dirname(os.path.realpath(**file**)),'english.txt'),'r')) > IOError: [Errno 2] No such file or directory: > '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- > packages/bitcoin-1.1.39-py2.7.egg/bitcoin/english.txt' Answer: This is related to a `pybitcointools` bug where the Pypi bitcoin .tar did not include the newly referenced `english.txt` file. This has since been fixed in v1.1.42. The issue is described here: <https://github.com/vbuterin/pybitcointools/issues/138> To fix your installation, you can reinstall `pybitcointools` from [Pypi](https://pypi.python.org/pypi/bitcoin) or run `pip install --upgrade pybitcointools`
More efficient way to loop? Question: I have a small piece of code from a much larger script. I figured out that when the function `t_area` is called, it is responsible for most of the run time. I tested the function by itself, and it is not slow, it takes a lot of time because of the number of times that it has to be ran I believe. Here is the code where the function is called: tri_area = np.zeros((numx,numy),dtype=float) for jj in range(0,numy-1): for ii in range(0,numx-1): xp = x[ii,jj] yp = y[ii,jj] zp = surface[ii,jj] ap = np.array((xp,yp,zp)) xp = xp+dx zp = surface[ii+1,jj] bp = np.array((xp,yp,zp)) yp = yp+dx zp = surface[ii+1,jj+1] dp = np.array((xp,yp,zp)) xp = xp-dx zp = surface[ii,jj+1] cp = np.array((xp,yp,zp)) tri_area[ii,jj] = t_area(ap,bp,cp,dp) The size of the arrays in use here are `216 x 217`, and so are the values of `x` and `y`. I am pretty new to python coding, I have used MATLAB in the past. So my question is, is there a way to get around the two for-loops, or a more efficient way to run through this block of code in general? Looking for any help speeding this up! Thanks! EDIT: Thanks for the help everyone, this has cleared alot of confusion up. I was asked about the function t_area that is used in the loop, here is the code below: def t_area(a,b,c,d): ab=b-a ac=c-a tri_area_a = 0.5*linalg.norm(np.cross(ab,ac)) db=b-d dc=c-d tri_area_d = 0.5*linalg.norm(np.cross(db,dc)) ba=a-b bd=d-b tri_area_b = 0.5*linalg.norm(np.cross(ba,bd)) ca=a-c cd=d-c tri_area_c = 0.5*linalg.norm(np.cross(ca,cd)) av_area = (tri_area_a + tri_area_b + tri_area_c + tri_area_d)*0.5 return(av_area) Sorry for the confusing notation, at the time it made sense, looking back now I will probably change it. Thanks! Answer: A caveat before we start. `range(0, numy-1)`, which is equal to `range(numy-1)`, produces the numbers from 0 to numy-2, not including numy-1. That's because you have numy-1 values from 0 to numy-2. While MATLAB has 1-based indexing, Python has 0-based, so be a bit careful with your indexing in the transition. Considering you have `tri_area = np.zeros((numx, numy), dtype=float)`, `tri_area[ii,jj]` never accesses the last row or column with the way you have set up your loops. Therefore, I suspect the correct intention was to write `range(numy)`. Since the fuction `t_area()` is vectorisable, you can do away with the loops completely. Vectorisation means numpy applies some operations on a whole array at the same time by taking care of the loops under the hood, where they will be faster. First, we stack all the `ap`s for each (i, j) element in a (m, n, 3) array, where (m, n) is the size of `x`. If we take the cross product of two (m, n, 3) arrays, the operation will be applied on the last axis by default. This means that `np.cross(a, b)` will do _for every element (i, j) take the cross product of the 3 numbers in`a[i,j]` and `b[i,j]`_. Similarly, `np.linalg.norm(a, axis=2)` will do _for every element (i, j) calculate the norm of the 3 numbers in`a[i,j]`_. This will also effectively reduce our array to size (m, n). A bit of caution here though, as we need to explicitly state we want this operation done on the 2nd axis. Note that in the following example my indexing relationship may not correspond to yours. The bare minimum to make this work is for `surface` to have one extra row and column from `x` and `y`. import numpy as np def _t_area(a, b, c): ab = b - a ac = c - a return 0.5 * np.linalg.norm(np.cross(ab, ac), axis=2) def t_area(x, y, surface, dx): a = np.zeros((x.shape[0], y.shape[0], 3), dtype=float) b = np.zeros_like(a) c = np.zeros_like(a) d = np.zeros_like(a) a[...,0] = x a[...,1] = y a[...,2] = surface[:-1,:-1] b[...,0] = x + dx b[...,1] = y b[...,2] = surface[1:,:-1] c[...,0] = x c[...,1] = y + dx c[...,2] = surface[:-1,1:] d[...,0] = bp[...,0] d[...,1] = cp[...,1] d[...,2] = surface[1:,1:] # are you sure you didn't mean 0.25??? return 0.5 * (_t_area(a, b, c) + _t_area(d, b, c) + _t_area(b, a, d) + _t_area(c, a, d)) nx, ny = 250, 250 dx = np.random.random() x = np.random.random((nx, ny)) y = np.random.random((nx, ny)) surface = np.random.random((nx+1, ny+1)) tri_area = t_area(x, y, surface, dx) `x` in this example supports the indices 0-249, while `surface` 0-250. `surface[:-1]`, a shorthand for `surface[0:-1]`, will return all rows starting from 0 and up to the last one, but not including it. `-1` serves the same function and `end` in MATLAB. So, `surface[:-1]` will return the rows for indices 0-249. Similarly, `surface[1:]` will return the rows for indices 1-250, which achieves the same as your `surface[ii+1]`. * * * **Note** : I had written this section before it was known that `t_area()` could be fully vectorised. So while what is here is obsolete for the purposes of this answer, I'll leave it as legacy to show what optimisations could have been made had the function not be vectorisable. Instead of calling the function for each element, which is expensive, you should pass it `x`, `y,`, `surface` and `dx` and iterate internally. That means only one function call and less overhead. Furthermore, you shouldn't create an array for `ap`, `bp`, `cp` and `dp` every loop, which again, adds overhead. Allocate them once outside the loop and just update their values. One final change should be the order of loops. Numpy arrays are row major by default (while MATLAB is column major), so `ii` performs better as the outer loop. You wouldn't notice the difference for arrays of your size, but hey, why not? Overall, the modified function should look like this. def t_area(x, y, surface, dx): # I assume numx == x.shape[0]. If not, pass it as an extra argument. tri_area = np.zeros(x.shape, dtype=float) ap = np.zeros((3,), dtype=float) bp = np.zeros_like(ap) cp = np.zeros_like(ap) dp = np.zeros_like(ap) for ii in range(x.shape[0]-1): # do you really want range(numx-1) or just range(numx)? for jj in range(x.shape[1]-1): xp = x[ii,jj] yp = y[ii,jj] zp = surface[ii,jj] ap[:] = (xp, yp, zp) # get `bp`, `cp` and `dp` in a similar manner and compute `tri_area[ii,jj]`
run imposm commands from a python script Question: I'm just getting started using imposm to help get openstreetmap data into a postgis database. All the docs point to making all commands via Terminal. This is fine for one off imports but I plan to have many many imports of varying bounding boxes and would like to script the loading of the data in the database. Currently I use: imposm --overwrite-cache --read --write -d postgis_test --user postgres -p "" /Users/Me/MapnikTest/osmXML.osm Which works fine from the command line but as osmXML.osm is being created many times I would like somehow to import this at the point of creation. Putting the same thing in a python script as: os.system("imposm --overwrite-cache --read --write -d postgis_test --user postgres -p "" /Users/Ali\ Mac\ Pro/Desktop/MapnikTest/osmXML.osm") just returns: /bin/sh: imposm: command not found Solving this would be the final step to automate the acquisition of data to render small maps on demand but I'm falling at the final hurdle! ** Edit full path to imposm solved the first problem but imputing the password for the postgres user happens when prompted. Is there a way to send the password in the same single line command? (maybe this needs to be a new post?, happy if someone points me in the right direction)** Answer: This is probably because `os.system()` is calling `/bin/sh` which uses a different shell environment from the one you use when working on the command line. To work around this, in your script, get the full path to the `imposm` script and then use that in your command. Use can use [some code like this](http://stackoverflow.com/questions/377017/test-if-executable-exists-in- python) to find the executable. Or you can fix your shell definitions so that `/bin/sh` has the proper `PATH` defined, but that depends greatly on your setup...
Python yielding when not requested by an object method Question: I am trying to findout why I get a `generator` instead of getting item printed since the second time I instanciate the `Scrape()` i did not request for a `yield`ed result which I find strange that it returns one. I would like to avoid this assuming it is possible and would like to know why this happens. See comment in code if you find it hard to understand or comment out the very last `for loop` This is a working code that can be tested in python 2.7 without modification. The code a simulation of my actual problem which I didn't know I could recreate with a more simpler example compared to the original code. from Tkinter import * import ttk import threading class Gui(ttk.Frame): def __init__(self, master): ttk.Frame.__init__(self, master) self.master = master self.var = BooleanVar() self.numbers = IntVar() self.var.set(False) varbox = ttk.Checkbutton(self.master, text="On/OFF", variable=self.var, onvalue=True) varbox.pack() btn = Button(self.master, text="Start", command=self.start_scan) btn.pack() entry = Entry(self.master, textvariable=self.numbers) # normally user would enter a number for now we assume 100 entry.pack() self.numbers.set(25) def start_scan(self): # start scan with a thread true_here = self.var.get() # let us say this is True value numbers = self.numbers.get() t = ThreadIt(true_here, numbers) # gave thread True, 100 t.start() class Scrape(object): def __init__(self, numbers): self.numbers = numbers if self.numbers < 5: self.numbers = 20 def do_stuff(self, var=False): # do things to change the world for i in range(2, self.numbers): # -> 99 if var: yield i * 20 # increase the number to we can recall this function else: print i class ThreadIt(threading.Thread): def __init__(self, var, numbers): super(ThreadIt, self).__init__() self.var = var self.numbers = numbers def run(self): foo = Scrape(self.numbers) result = foo.do_stuff(var=self.var) # since numbers is 25 this would yield from 2 to 24 as var is sent to TRUE if result: # if var above is false below wouldn't have happen for i in result: yielded = Scrape(i) print yielded , "foo" # prints something line: <__main__.Scrape object at 0x112da4d90> res = yielded.do_stuff(var=False) print res # suppose no be None because its not suppose to yield since var is False but it prints generator as below # <generator object do_stuff at 0x10eef1aa0> for i in res: # this is not suppose to be a generator (Generator was done in result) print i print "Finished" root = Tk() app = Gui(root) root.mainloop() root.destroy() Answer: I think you would benefit greatly from reading [this answer](http://stackoverflow.com/a/231855/2911687) For your specific case, `yielded = Scrape(i)` indeed creates a object of type `Scrape`. And `yielded.do_stuff(var=False)` returns a generator because the yield statement is used in it's definition. Since `var` is `False`, it won't generate any element though and will just execute the line `print i` until exhaustion of the `for` loop. But yeah, takes the time to read the first link I gave, it's beautiful
Plotting points based on what value they end up being in matplotlib and numpy Question: I apologize, since I don't exactly know how to word my title. I'm brand new to Python and especially new to matplotlib. I am also using numpy for my arrays in this case. Currently, I have a set of data: `X` that has four properties. Each property is a column, and each row is a set of data points (lets just say they are represented by numbers for now). Here is a small example: X (height) (weight) (gender) (hair color) 6 32.1 0 12 1.112 6.12 1 9 4 2 0 6 2 3.2 0 11 I also have an array `Y` that corresponds to an integer value from 0 - 2. It is just an `np.array` but each element corresponds to that row of values in `X`. So for example if `Y = array([0,2,1,1])` then I have these pairs: Y X 0 -> (6, 32.1, 0, 12) 2 -> (1.112, 6.12, 1, 9) 1 -> (4, 2, 0, 6) 1 -> (2, 3.2, 0, 11) What I want to do is create **separate** scatter plots for each pair of these properties: (height, weight) -> (0,1) (height, gender) -> (0,2) (height, hair color) -> (0, 3) And I want each data point to have a color that corresponds with the `Y` value. So `y = 0 = 'b'`, `y = 1 = 'g'`, and `y = 2 = 'r'` I know how to create a scatter plot (in this case, just the height and weight column) that will map the pairs that I want using plt.plot(X[:,0], X[:,1], 'o', c='b') plt.show() However I don't know how I can then relate each of these points to the `Y` value that holds its color, since I can only input one color. I would appreciate any help, or tutorials that could guide me in the right direction. Answer: You could map Y to rgb colors and use "scatter" to plot points with different colors: import numpy from matplotlib import pyplot as plt X = numpy.array([[6, 32.1, 0, 12], [1.112, 6.12, 1, 9], [4, 2, 0, 6], [2, 3.2, 0, 11]]) Y = numpy.array([0, 1, 1, 2]) # map numbers to rgb colors Y_color = numpy.zeros(shape=(Y.size, 3)) Y_color[Y == 0] = (1,0,0) Y_color[Y == 1] = (0,1,0) Y_color[Y == 2] = (0,0,1) # use scatter instead of plot plt.scatter(X[:,0], X[:,1], c=Y_color) plt.show()
HTMLParser python turn data into string? Question: Hi I'm using this following python parser to read an html file <https://docs.python.org/2/library/htmlparser.html> class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inLink = False self.dataArray = [] self.countLanguages = 0 self.lasttag = None self.lastname = None self.lastvalue = None def handle_starttag(self, tag, attrs): self.inLink = False if tag == 'window': for name, value in attrs: if name == 'mode': #value = 0 #print(value) self.countLanguages += 1 self.inLink = True self.lasttag = tag def handle_endtag(self, tag): if tag == "window": self.inlink = False def handle_data(self, data): self.data = data #print(self.data) print data if data.strip(): self.inlink = False #print data parser = MyHTMLParser() input_file = open('xmlfile.xml') feed_data = input_file.read().strip() feed_data = parser.feed(feed_data) print(feed_data.data) input_file.close() However, I cant seem to find a way to turn the data returned from html parser into a string. I'm basically modyfing an attribute using html parser, then I want to turn the data into a string - any idea how to do that? I've tried adding a "self.data" to the "handle_data" function, but I cant seem to print any data coming back. Is there a way to just print everything held in the parser? Answer: This is another way that might suit your needs for this specific question: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import urllib.request url = "http://www.google.com" with urllib.request.urlopen(url) as response: html = response.read().decode('utf-8') print (html)
How to dynamically generate Kivy objects Question: So I figure out how to dynamically add labels to Kivy, but then I realized that Kivy has a listview module already, and that that would make things easier. I found this [Python Kivy ListView: How to delete selected ListItemButton?](http://stackoverflow.com/questions/25981827/python-kivy- listview-how-to-delete-selected-listitembutton) answer useful in learning about implementing a listview, but am wondering how I could add a two column listview that is updated with text from two textboxes. I edited the code in the example as a proof of concept for what I want to do and what I have so far is: # main.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.uix.listview import ListItemButton class TaskButton(ListItemButton): pass class TodoRoot(BoxLayout): task_input = ObjectProperty() task_list = ObjectProperty() def add_task(self): self.task_list.adapter.data.extend([self.task_input_1.text + " | " + self.task_input_2.text]) self.task_list._trigger_reset_populate() def del_task(self, *args): if self.task_list.adapter.selection: selection = self.task_list.adapter.selection[0].text self.task_list.adapter.data.remove(selection) self.task_list._trigger_reset_populate() class TodoApp(App): def build(self): return TodoRoot() if __name__ == '__main__': TodoApp().run() and # todo.kv #: import main main #: import ListAdapter kivy.adapters.listadapter.ListAdapter #: import ListItemButton kivy.uix.listview.ListItemButton TodoRoot: <TodoRoot>: orientation: "vertical" task_input_1: task_input_view_1 task_input_2: task_input_view_1 task_list: tasks_list_view BoxLayout: size_hint_y: None height: "40dp" TextInput: id: task_input_view_1 size_hint_x: 70 TextInput: id: task_input_view_2 size_hint_x: 70 Button: text: "Add" size_hint_x: 15 on_press: root.add_task() Button: text: "Del" size_hint_x: 15 on_press: root.del_task() ListView: id: tasks_list_view adapter: ListAdapter(data=[], cls=main.TaskButton) that sort of works, but its a bit clunky and I would like to have the text from the two text inputs go into separate columns of the listview but each row can still be selected as a row. Answer: Not sure if it is exactly what you asked for; if you need something else, write in comment: test.kv: #:kivy 1.9.1 Screen: GridLayout: size_hint_y: .7 pos_hint: {'y': .3} id: labels_grid cols: 2 canvas: # visualize grid layout Color: rgb: 0.3, 0.5, 0.3 Rectangle: size: self.size pos: self.pos GridLayout: size_hint_y: .3 cols: 1 TextInput: id: input_1 TextInput: id: input_2 MyButton: text: 'add labels to grid' text_1: input_1.text # binding labels text for easy use text_2: input_2.text # with self. on_press: self.add_labels(labels_grid) main.py: #!/usr/bin/env python # -*- coding: utf-8 -*- from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label class MyButton(Button): def add_labels(self, grid_handle): text_1 = self.text_1 text_2 = self.text_2 label_1 = Label(text=text_1) label_2 = Label(text=text_2) grid_handle.add_widget(label_1) grid_handle.add_widget(label_2) class Test(App): pass Test().run()
How can I import a .pyc compiled python file and use it Question: Im trying to figure out how to include a `.pyc` file in a python script. For example my script is called: myscript.py and the script I would like to include is called: included_script.pyc So, do I just use: import included_script And will that automatically execute the `included_script.pyc` ? Or is there something further I need to do, to get my `included_script.pyc` to run inside the `myscript.py`? Do I need to pass the variables used in `included_script.pyc` also? If so, how might this be achieved? Answer: Unfortunately, **no** , this cannot be done automatically. _You can, of course, do it manually**in a gritty ugly way._** * * * ### Setup: For demonstration purposes, I'll first generate a `.pyc` file. In order to do that, we first need a `.py` file for it. Our sample `test.py` file will look like: def foo(): print("In foo") if __name__ == "__main__": print("Hello World") Super simple. Generating the `.pyc` file can done with the **[`py_compile`](https://docs.python.org/2.7/library/py_compile.html)** module found in the standard library. We simply pass in the name of the `.py` file and the name for our `.pyc` file in the following way: py_compile.compile('test.py', 'mypyc.pyc') This will place `mypyc.pyc` in our current working directory. * * * ### Getting the code from `.pyc` files: Now, `.pyc` files contain bytes that are structured in the following way: * First 4 bytes signalling a 'magic number' * Next 4 bytes holding a modification timestamp * Rest of the contents are a _marshalled_ [`code`](https://docs.python.org/2/library/types.html#types.CodeType) object. What we're after is that marshalled `code` object, so we need to **[`import marshal`](https://docs.python.org/2.7/library/marshal.html)** to un-marshall it and execute it. Additionally, we really don't care/need the 8 first bytes, and un-marshalling the `.pyc` file with them is disallowed, so we'll ignore them (`seek` past them): import marshal s = open('mypyc.pyc', 'rb') s.seek(8) # go past first eight bytes code_obj = marshal.load(s) So, now we have our fancy `code` object for `test.py` which is valid and ready to be executed as we wish. _We have two options here_ : 1. Execute it in the current `global` namespace. This will bind all definitions inside our `.pyc` file in the current namespace and will act as a sort of: `from file import *` statement. 2. Create a new module object and execute the code inside the module. This will be like the `import file` statement. * * * ### Emulating `from file import *` like behaviour: Performing this is pretty simple, just do: exec(code_obj) This will execute the code contained inside `code_obj` in the current namespace and bind everything there. After the call we can call `foo` like any other funtion: foo() # prints: In foo! _Note_ : `exec()` is a built-in. * * * ### Emulating `import file` like behaviour: This includes another requirement, the **[`types`](https://docs.python.org/2/library/types.html)** module. This contains the type for **[`ModuleType`](https://docs.python.org/2/library/types.html#types.ModuleType)** which we can use to create a new module object. It takes two arguments, the name for the module (mandatory) and the documentation for it (optional): m = types.ModuleType("Fancy Name", "Fancy Documentation") print(m) <module 'Fancy Name' (built-in)> Now that we have our module object, we can again use `exec` to execute the code contained in `code_obj` inside the module namespace (namely, `m.__dict__`): exec(code_obj, m.__dict__) Now, our module `m` has everything defined in `code_obj`, you can verify this by running: m.foo() # prints: In foo * * * These are the ways you can 'include' a `.pyc` file in your module. At least, the ways I can think of. I don't really see the practicality in this but hey, I'm not here to judge.
Python is filtering out currency markers Question: **Objective** : Write a screenscraper that cycles through a selection of web pages containing old prices and new prices, reads in the prices, and writes them to a CSV file. **Method** : The config file urls.txt contains the list of pages. Open that file and cycle through the URLs. For each URL, use Beautiful Soup to extract the contents of any divs of class "current-price" and "old-price". Not all pages will have an old price, so I've made that optional. **Problem** : It's all working fine but with one curious exception. Where prices are in dollars, the price and the dollar sign are coming through. Where prices are in Euros or Pounds Sterling, the currency markers £ and € are being stripped off. I want the currency markers to come through in all cases. I suspect it's an encoding issue. (The lstrip calls below are to remove some errant spaces and tabs that were coming through.) **Contents of urls.txt:** http://uk.norton.com/norton-security-for-one-device http://uk.norton.com/norton-security-antivirus http://uk.norton.com/norton-security-with-backup http://us.norton.com/norton-security-for-one-device http://us.norton.com/norton-security-antivirus http://us.norton.com/norton-security-with-backup http://ie.norton.com/norton-security-for-one-device http://ie.norton.com/norton-security-antivirus http://ie.norton.com/norton-security-with-backup **Python code:** ############################################### # # PRICESCRAPE # Screenscraper that checks prices on PD pages # ############################################### # Import the modules we need import urllib.request import re import lxml from lxml import etree from lxml.html.soupparser import fromstring from lxml.etree import tostring from lxml.cssselect import CSSSelector from bs4 import BeautifulSoup, NavigableString # Open the files we need out = open('out.csv', 'w') urls=open('urls.txt','r') # function to take a URL, open the HTML, and return it def getPage(url): return urllib.request.urlopen(url).read().decode(encoding='UTF-8',errors='strict').encode('ascii','ignore') out.write('URL,Current Price,Strikethrough Price\n') #Loop through the URLs for url in urls: print('\nExamining ' + url) url=url.rstrip('\n') html=getPage(url) soup = BeautifulSoup(html,'lxml') currentPrice = soup.find('div', {'class': 'current-price'}).contents[0].lstrip('\n').lstrip(' ').lstrip('\t') oldPrice = soup.find('div', {'class': 'old-price'}).contents[0].lstrip(' ') out.write(url) out.write(',') out.write(str(currentPrice)) out.write(',') if oldPrice: out.write(str(oldPrice)) else: out.write('No strikethrough price') out.write('\n') if html =='': print('Problem reading page') print('Done. See out.csv for output') out.close() urls.close() Answer: I would use two modules to make it work and make the code simpler: * [`csv`](https://docs.python.org/2/library/csv.html) to export the results into `csv` output file * [`requests`](http://docs.python-requests.org/en/latest/) to make the encoding part transparent for you If you would `import requests` and replace `getPage` implementation with: def getPage(url): return requests.get(url).content You would get the prices with the Euro and Pound signs as well.
Selenium - Python - Select dropdown meun option - No ID or Name Question: I am trying to select and element in a dropdown menu: The HTML is: <div class="col-lg-6"> <select data-bind="options: indicator_type_list,value: indicatorType,optionsCaption: 'Choose...', disable: $root.mode().isReadOnly()"> <option value="">Choose...</option> <option value="Malicious E-mail">Malicious E-mail</option> <option value="IP Watchlist">IP Watchlist</option> <option value="File Hash Watchlist">File Hash Watchlist</option> <option value="Domain Watchlist">Domain Watchlist</option> <option value="URL Watchlist">URL Watchlist</option> <option value="Malware Artifacts">Malware Artifacts</option> <option value="C2">C2</option> <option value="Anonymization">Anonymization</option> <option value="Exfiltration">Exfiltration</option> <option value="Host Characteristics">Host Characteristics</option> <option value="Compromised PKI Certificate">Compromised PKI Certificate</option> <option value="Login Name">Login Name</option> <option value="IMEI Watchlist">IMEI Watchlist</option> <option value="IMSI Watchlist">IMSI Watchlist</option> </select> </div> I have tried: Select = Select(browser.find_element_by_xpath("//div[contains(.,'Choose...Malicious E-mailIP WatchlistFile Hash WatchlistDomain WatchlistURL WatchlistMalware ArtifactsC2AnonymizationExfiltrationHost CharacteristicsCompromised PKI CertificateLogin NameIMEI WatchlistIMSI Watchlist')]")) and test = browser.find_element_by_xpath("//option[@value='Malicious E-mail']") dropdown = test.find_element_by_xpath('..') select = Select(browser.dropdown) However I cannot seem to find the element to select the items in the dropdown. Any help is appreciated! Answer: There are multiple ways to locate this `select` element. Here is one way - locate the `select` element that has a specific `option` inside: from selenium.webdriver.support.select import Select option_value = "Malicious E-mail" select_element = browser.find_element_by_xpath("//select[option[@value = '%s']]" % option_value) select = Select(select_element) select.select_by_value(option_value)
extracting result text from xml using Python Question: I have the following xml : <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns3:result xmlns:ns2="http://ws.def.com/"> <ns3:value>QWESW12323D2412123S</ns3:value> </ns3:result> and want to parse it with python and extract this text i tried the following : from xml.etree import ElementTree as etree xml = etree.fromstring(data) item = xml.find('ns3:value') print item but i get empty item ,could someone help to achieve this with Python? Answer: Use the syntax '{ns3}value' to apply the namespace - although as ns3 isn't defined, I don't think this is actually valid xml.
Error tokenizing data. C error: EOF following escape character Question: I'm trying to load a csv text file that I created with an OS X app written in Objective-C (using XCode). The text file (temp2.csv) looks fine in an editor but there's something wrong with it and I get this error when reading it into a Pandas dataframe. If I copy the data into a fresh text file (temp.csv) and save that it works fine! The two text files are clearly different (one is 74 bytes the other is 150) - invisible characters perhaps? - but it's very annoying as I want the python code to load the text files produced by the C code. Files are attached for reference. temp.csv -3.132700,0.355885,9.000000,0.444416 -3.128256,0.444416,9.000000,0.532507 temp2.csv -3.132700,0.355885,9.000000,0.444416 -3.128256,0.444416,9.000000,0.532507 (I can't find any help on this specific error on StackExchange). Python 2.7.11 |Anaconda 2.2.0 (x86_64)| (default, Dec 6 2015, 18:57:58) [GCC 4.2.1 (Apple Inc. build 5577)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org >>> import pandas as pd >>> df = pd.read_csv("temp2.csv", header=None) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 498, in parser_f return _read(filepath_or_buffer, kwds) File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 275, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 590, in __init__ self._make_engine(self.engine) File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 731, in _make_engine self._engine = CParserWrapper(self.f, **self.options) File "/Users/billtubbs/anaconda/lib/python2.7/site-packages/pandas/io/parsers.py", line 1103, in __init__ self._reader = _parser.TextReader(src, **kwds) File "pandas/parser.pyx", line 515, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:4948) File "pandas/parser.pyx", line 717, in pandas.parser.TextReader._get_header (pandas/parser.c:7496) File "pandas/parser.pyx", line 829, in pandas.parser.TextReader._tokenize_rows (pandas/parser.c:8838) File "pandas/parser.pyx", line 1833, in pandas.parser.raise_parser_error (pandas/parser.c:22649) pandas.parser.CParserError: Error tokenizing data. C error: EOF following escape character >>> df = pd.read_csv("temp.csv", header=None) >>> df 0 1 2 3 0 -3.132700 0.355885 9 0.444416 1 -3.128256 0.444416 9 0.532507 Footnote: I think I located the problem. >>> f = open('temp2.csv') >>> contents = f.read() >>> print contents ??-3.132700,0.355885,9.000000,0.444416 -3.128256,0.444416,9.000000,0.532507 >>> contents '\xff\xfe-\x003\x00.\x001\x003\x002\x007\x000\x000\x00,\x000\x00.\x003\x005\x005\x008\x008\x005\x00,\x009\x00.\x000\x000\x000\x000\x000\x000\x00,\x000\x00.\x004\x004\x004\x004\x001\x006\x00\n\x00-\x003\x00.\x001\x002\x008\x002\x005\x006\x00,\x000\x00.\x004\x004\x004\x004\x001\x006\x00,\x009\x00.\x000\x000\x000\x000\x000\x000\x00,\x000\x00.\x005\x003\x002\x005\x000\x007\x00' It's full of escape characters! How to remove them? Answer: You need add parameter `encoding` to [`read_csv`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.read_csv.html), because file encoding is `UTF-16`: import pandas as pd contents = '\xff\xfe-\x003\x00.\x001\x003\x002\x007\x000\x000\x00,\x000\x00.\x003\x005\x005\x008\x008\x005\x00,\x009\x00.\x000\x000\x000\x000\x000\x000\x00,\x000\x00.\x004\x004\x004\x004\x001\x006\x00\n\x00-\x003\x00.\x001\x002\x008\x002\x005\x006\x00,\x000\x00.\x004\x004\x004\x004\x001\x006\x00,\x009\x00.\x000\x000\x000\x000\x000\x000\x00,\x000\x00.\x005\x003\x002\x005\x000\x007\x00' text_file = open("test/file1.csv", "wb") text_file.write(contents) text_file.close() df = pd.read_csv("test/file1.csv", header=None, encoding='utf-16') print df 0 1 2 3 0 -3.132700 0.355885 9 0.444416 1 -3.128256 0.444416 9 0.532507
Check for number of columns in each row of CSV Question: I have the following Python code: import os import csv import sys g = open('Consolidated.csv', "wb") for root, dirs, files in os.walk('D:\\XXX\\YYY\\S1'): for filename in files: pathname = os.path.join(root, filename) symbol = filename.rpartition('_')[-1].rpartition('.')[0] reader = csv.reader(open(pathname, 'rU')) writer = csv.writer(g, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: row.insert(0, symbol.upper()) if len(row[2]) == 3: row[2] = '0'+row[2] writer.writerow(row) The basic idea is that I have a couple of CSV files in S1 that I need to merge to a large CSV. The files are named in a funny way, which leads to the rpartition and row manipulations in the code. This code works fine, but my question is as follows: how does one check the number of columns in EACH row of the CSV file? An example: if an input CSV file is in the following format, expected to have five columns: 1,2,3,4,5, the code would display "1" "2" "3" "4" "5" (seperated by tabs) in the consolidated file. Now let's say for whatever reason one row entry in the CSV file is like: 6,7,8. So it stops abruptly without all the columns filled in. In this case, I want the code to ignore this line and not produce "6" "7" "8" into the consolidation. Could someone kindly provide code on how to do so? For each row in the input CSVs I want to check if it is a full row before manipulating it. Any help would be massively appreciated. Warm Regards. Answer: len(row) will give the number of columns in the row. You can do for row in reader: if not len(row)<desired_number_of_columns: # process the row here For example, if your csv file looks like this 1,2,3,4,5 a,b,c,d,e l1,l2 d,e,f,g,h running import csv reader = csv.reader(open("csvfile.csv","r")) for row in reader: if not len(row)<5: print(" ".join(row)) will produce the output 1 2 3 4 5 a b c d e d e f g h ignoring the row with length 2.
TypeError when passing a 'file' variable to a fuction Question: When I first coded this in to a single function, it worked. But I want to do more things when I am checking for files in to the directory, so I have divided the code in two functions : One checks for files on a directory that end with *.rar extension, if it finds a file that matches, it uncompresses it to a directory. import shutil, os, patoolib, fnmatch, glob def unrar(): patoolib.extract_archive(file, outdir="/root/tree/def") def chktree(): for file in glob.glob('/root/tree/down/*'): if fnmatch.fnmatch(file, '*.rar'): unrar() chktree() Executing `unrar()` after the `if` from the function `chktree():` does not work. I would like to know what I am doing wrong, this is the output : Traceback (most recent call last): File "autotube.py", line 16, in <module> chktree() File "autotube.py", line 14, in chktree unrar() File "autotube.py", line 6, in unrar patoolib.extract_archive(file, outdir="/root/tree/def") File "/usr/local/lib/python2.7/dist-packages/patoolib/__init__.py", line 676, in extract_archive util.check_existing_filename(archive) File "/usr/local/lib/python2.7/dist-packages/patoolib/util.py", line 389, in check_existing_filename if not os.path.exists(filename): File "/usr/lib/python2.7/genericpath.py", line 26, in exists os.stat(path) TypeError: coercing to Unicode: need string or buffer, type found Answer: You need to pass the variable `file` explicitly to the function you are calling. Also, `file` is a special name in Python, so you should probably use a different name, such as `my_file` or simply `f`. import shutil, os, patoolib, fnmatch, glob def unrar(my_file): patoolib.extract_archive(my_file, outdir="/root/tree/def") def chktree(): for f in glob.glob('/root/tree/down/*'): if fnmatch.fnmatch(f, '*.rar'): unrar(f) chktree() Additionally, as @mgilson noted, the reason for the actual error you are seeing is that Python thinks you are referring to the built-in name `file` since you did not pass a parameter which shadowed it. Had you used a different name, you would have gotten a `NameError` instead.
Subtract all items in a list against each other Question: I have a list in Python that looks like this: myList = [(1,1),(2,2),(3,3),(4,5)] And I want to subtract each item with the others, like this: (1,1) - (2,2) (1,1) - (3,3) (1,1) - (4,5) (2,2) - (3,3) (2,2) - (4,5) (3,3) - (4,5) The expected result would be a list with the answers: [(1,1), (2,2), (3,4), (1,1), (2,3), (1,2)] How can I do this? If I approach it with a `for` loop, I can maybe store the previous item and check it against the one that I'm working with at that moment, but it doesn't really work. Answer: Use `itertools.combinations` with tuple unpacking to generate the pairs of differences: >>> from itertools import combinations >>> [(y1-x1, y2-x2) for (x1, x2), (y1, y2) in combinations(myList, 2)] [(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]
python ordered_dict from json Question: I am using Python 2.6.6, and trying to generate a ordered_dict from json string. I could understand that I could use object_pairs_hook of json Decoder/loads, but unfortunately it's not supported in 2.6.6. Is there any way out? e.g. template_s = '{ "aa": {"_type": "T1"}, "bb": {"_type": "T11"}}' json.loads(template_s, object_pairs_hook=OrderedDict) >>> json.loads(json_str, object_pairs_hook=OrderedDict) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/json/__init__.py", line 318, in loads return cls(encoding=encoding, **kw).decode(s) TypeError: __init__() got an unexpected keyword argument 'object_pairs_hook' Thanks Answer: I was able to do the same with simplejson import simplejson as json json.loads(config_str, object_pairs_hook=json.OrderedDict)