text
stringlengths
226
34.5k
Python module won't install Question: This is my `setup.py` file #!/usr/bin/env python from setuptools import setup from sys import path setup(name= 'conundrum', version= '0.1.0', author= 'elssar', author_email= '[email protected]', py_modules= ['conundrum'], url= 'https://github.com/elssar/conundrum', license= 'MIT', description= 'A framework agnostic blog generator.', long_description= open(path[0]+'/README.md', 'r').read(), install_requires= [ 'PyYAML >= 3.0.9', 'Markdown >= 2.2.0', 'requests >= 1.0.4', ], ) I have tried using both `setuptools` and `distutils`, but this won't install my module. Instead I get file module.py (for module module) not found This is my directory structure /module |--/test |--README.md |--license.txt |--module.py |--setup.py Just to be clear, module is the root directory. Can anyone tell me what I'm doing wrong? This is the output when I try to install elssar@elssar-laptop:/usr/local/src/conundrum$ sudo python /home/elssar/code/conundrum/setup.py install /usr/lib/python2.6/distutils/dist.py:250: UserWarning: 'licence' distribution option is deprecated; use 'license' warnings.warn(msg) running install running bdist_egg running egg_info writing requirements to conundrum.egg-info/requires.txt writing conundrum.egg-info/PKG-INFO writing top-level names to conundrum.egg-info/top_level.txt writing dependency_links to conundrum.egg-info/dependency_links.txt warning: manifest_maker: standard file 'setup.py' not found file conundrum.py (for module conundrum) not found reading manifest file 'conundrum.egg-info/SOURCES.txt' writing manifest file 'conundrum.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib running build_py file conundrum.py (for module conundrum) not found file conundrum.py (for module conundrum) not found warning: install_lib: 'build/lib.linux-x86_64-2.6' does not exist -- no Python modules to install creating build/bdist.linux-x86_64/egg creating build/bdist.linux-x86_64/egg/EGG-INFO copying conundrum.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO copying conundrum.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying conundrum.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying conundrum.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying conundrum.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO zip_safe flag not set; analyzing archive contents... creating 'dist/conundrum-0.1.0-py2.6.egg' and adding 'build/bdist.linux-x86_64/egg' to it removing 'build/bdist.linux-x86_64/egg' (and everything under it) Processing conundrum-0.1.0-py2.6.egg removing '/usr/local/lib/python2.6/dist-packages/conundrum-0.1.0-py2.6.egg' (and everything under it) creating /usr/local/lib/python2.6/dist-packages/conundrum-0.1.0-py2.6.egg Extracting conundrum-0.1.0-py2.6.egg to /usr/local/lib/python2.6/dist-packages conundrum 0.1.0 is already the active version in easy-install.pth Installed /usr/local/lib/python2.6/dist-packages/conundrum-0.1.0-py2.6.egg Processing dependencies for conundrum==0.1.0 Searching for requests==1.0.4 Best match: requests 1.0.4 Adding requests 1.0.4 to easy-install.pth file Using /usr/local/lib/python2.6/dist-packages Searching for Markdown==2.2.0 Best match: Markdown 2.2.0 Processing Markdown-2.2.0-py2.6.egg Markdown 2.2.0 is already the active version in easy-install.pth Installing markdown_py script to /usr/local/bin Using /usr/local/lib/python2.6/dist-packages/Markdown-2.2.0-py2.6.egg Searching for PyYAML==3.10 Best match: PyYAML 3.10 Adding PyYAML 3.10 to easy-install.pth file Using /usr/local/lib/python2.6/dist-packages Finished processing dependencies for conundrum==0.1.0 Just to be sure there isn't something wrong my my system, I downloaded two packages from github with a similar `setup.py` and installed them. Installed without any problems. Answer: I cannot run `setup.py` from a different directory. It needs to be run from the directory it is in. That was the problem here. Fixed.
SyntaxError in Python handler Question: I am using urlfetch available from Google App Engine to fetch URLs content. But I am getting 500 Internal Server Error. Here is the complete app code that I am using :- **compare-hatke.py** import urllib2 from google.appengine.api import urlfetch from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import datetime class MainPage(webapp.RequestHandler): def curlTry: url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: print(result.content) application = webapp.WSGIApplication([('/', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main() **app.yaml** application: compare-hatke version: 3 runtime: python27 api_version: 1 threadsafe: false handlers: - url: /.* script: compare-hatke.app Here is the **error log**. I am not able to understand the syntax error they are mentioning Traceback (most recent call last): File "/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 196, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 269, in _LoadHandler raise ImportError('%s has no attribute %s' % (handler, name)) ImportError: <module 'compare-hatke' from '/base/data/home/apps/s~compare-hatke/3.365290288779373200/compare-hatke.pyc'> has no attribute app Please tell me where I am missing. Thanks ! Answer: A Python method in a class needs to refer to the self parameter in the function definition in order to identify the instance that it belongs to. This is your basic syntax error. Correcting that, you still need to set up a routing so that your MainPage class can handle the GET request. This is most easily done by having a get method in GAE. The documentation shows you other methods once you have this working. Try this: class MainPage(webapp.RequestHandler): def get(self): # responds to http GET, and adds self parameter url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: print(result.content)
How to parse XML hierarchies with python? Question: I'm new to python and have been taking on various projects to get up to speed. At the moment, I'm working on a routine that will read through the Code of Federal Regulations and for each paragraph, print the organizational hierarchy for that paragraph. For example, a simplified version of the CFR's XML scheme would look like: <CHAPTER> <HD SOURCE="HED">PART 229—NONDISCRIMINATION ON THE BASIS OF SEX IN EDUCATION PROGRAMS OR ACTIVITIES RECEIVING FEDERAL FINANCIAL ASSISTANCE</HD> <SECTION> <SECTNO>### 229.120</SECTNO> <SUBJECT>Transfers of property.</SUBJECT> <P>If a recipient sells or otherwise transfers property (…) subject to the provisions of ### 229.205 through 229.235(a).</P> </SECTION> I'd like to be able to print this to a CSV so that I can run text analysis: Title 22, Volume 2, Part 229, Section 228.120, If a recipient sells or otherwise transfers property (…) subject to the provisions of ### 229.205 through 229.235(a). Note that I'm not taking the Title and Volume numbers from the XML, because they are actually included in the file name in a much more standardized format. Because I'm such a Python newbie, the code is mostly based on the search- engine code from Udacity's computer science course. Here's the Python I've written/adapted so far: import os import urllib2 from xml.dom.minidom import parseString file_path = '/Users/owner1/Downloads/CFR-2012/title-22/CFR-2012-title22-vol1.xml' file_name = os.path.basename(file_path) #Gets the filename from the path. doc = open(file_path) page = doc.read() def clean_title(file_name): #Gets the title number from the filename. start_title = file_name.find('title') end_title = file_name.find("-", start_title+1) title = file_name[start_title+5:end_title] return title def clean_volume(file_name): #Gets the volume number from the filename. start_volume = file_name.find('vol') end_volume = file_name.find('.xml', start_volume) volume = file_name[start_volume+3:end_volume] return volume def get_next_section(page): #Gets all of the text between <SECTION> tags. start_section = page.find('<SECTION') if start_section == -1: return None, 0 start_text = page.find('>', start_section) end_quote = page.find('</SECTION>', start_text + 1) section = page[start_text + 1:end_quote] return section, end_quote def get_section_number(section): #Within the <SECTION> tag, find the section number based on the <SECTNO> tag. start_section_number = section.find('<SECTNO>###') if start_section_number == -1: return None, 0 end_section_number = section.find('</SECTNO>', start_section_number) section_number = section[start_section_number+11:end_section_number] return section_number, end_section_number def get_paragraph(section): #Within the <SECTION> tag, finds <P> paragraphs. start_paragraph = section.find('<P>') if start_paragraph == -1: return None, 0 end_paragraph = section.find('</P>', start_paragraph) paragraph = section[start_paragraph+3:end_paragraph] return start_paragraph, paragraph, end_paragraph def print_all_paragraphs(page): #This is the section that I would *like* to have print each paragraph and the citation hierarchy. section, endpos = get_next_section(page) for pragraph in section: title = clean_title(file_name) volume = clean_volume(file_name) section, endpos = get_next_section(page) section_number, end_section_number = get_section_number(section) start_paragraph, paragraph, end_paragraph = get_paragraph(section) if paragraph: print "Title: "+ title + " Volume: "+ volume +" Section Number: "+ section_number + " Text: "+ paragraph page = page[end_paragraph:] else: break print print_all_paragraphs(page) doc.close() At the moment, this code has the following issues (example output to follow): 1. It prints the first paragraph multiple times. How can I print each tag with its own title number, volume number, etc? 2. The CFR has empty sections that are "Reserved". These sections don't have tags, so the if loop breaks. I've tried implementing for/while loops, but for some reason when I do this the code then just prints the first paragraph it finds repeatedly. Here's an example of the output: Title: 22 Volume: 1 Section Number: 9.10 Text: All requests to the Department by a member of the public, a government employee, or an agency to declassify and release information shall result in a prompt declassification review of the information in accordance with procedures set forth in 22 CFR 171.20-25. Mandatory declassification review requests should be directed to the Information and Privacy Coordinator, U.S. Department of State, SA-2, 515 22nd St., NW., Washington, DC 20522-6001. Title: 22 Volume: 1 Section Number: 9.10 Text: All requests to the Department by a member of the public, a government employee, or an agency to declassify and release information shall result in a prompt declassification review of the information in accordance with procedures set forth in 22 CFR 171.20-25. Mandatory declassification review requests should be directed to the Information and Privacy Coordinator, U.S. Department of State, SA-2, 515 22nd St., NW., Washington, DC 20522-6001. Title: 22 Volume: 1 Section Number: 9.10 Text: All requests to the Department by a member of the public, a government employee, or an agency to declassify and release information shall result in a prompt declassification review of the information in accordance with procedures set forth in 22 CFR 171.20-25. Mandatory declassification review requests should be directed to the Information and Privacy Coordinator, U.S. Department of State, SA-2, 515 22nd St., NW., Washington, DC 20522-6001. Title: 22 Volume: 1 Section Number: 9.11 Text: The Information and Privacy Coordinator shall be responsible for conducting a program for systematic declassification review of historically valuable records that were exempted from the automatic declassification provisions of section 3.3 of the Executive Order. The Information and Privacy Coordinator shall prioritize such review on the basis of researcher interest and the likelihood of declassification upon review. Title: 22 Volume: 1 Section Number: 9.12 Text: For Department procedures regarding the access to classified information by historical researchers and certain former government personnel, see Sec. 171.24 of this Title. Title: 22 Volume: 1 Section Number: 9.13 Text: Specific controls on the use, processing, storage, reproduction, and transmittal of classified information within the Department to provide protection for such information and to prevent access by unauthorized persons are contained in Volume 12 of the Department's Foreign Affairs Manual. Title: 22 Volume: 1 Section Number: 9a.1 Text: These regulations implement Executive Order 11932 dated August 4, 1976 (41 FR 32691, August 5, 1976) entitled ‚ÄúClassification of Certain Information and Material Obtained from Advisory Bodies Created to Implement the International Energy Program.‚Äù Title: 22 Volume: 1 Section Number: 9a.1 Text: These regulations implement Executive Order 11932 dated August 4, 1976 (41 FR 32691, August 5, 1976) entitled ‚ÄúClassification of Certain Information and Material Obtained from Advisory Bodies Created to Implement the International Energy Program.‚Äù None Ideally, each of the entries after the citation information would be different. What kind of loop should I run to print this properly? Is there a more "pythonic" way of doing this kind of text extraction? I understand that I am a complete novice, and one of the major problems I'm facing is that I simply don't have the vocabulary or topic knowledge to really find detailed answers about parsing XML with this level of detail. Any recommended reading would also be welcome. Answer: I like to solve problems like this with XPATH or XSLT. You can find a great implementation in lxml (not in standard distro, needs to be installed). For instance, the XPATH //CHAPTER/HD/SECTION[SECTNO] selects all sections with data. You use relative XPATH statements to grab the values you want from there. Multiple nested for loops disappear. XPATH has a bit of a learning curve, but there many examples out there.
Django Error "Caught SyntaxError while rendering: invalid syntax " Question: I'm creating an django app via this tutorial <https://docs.djangoproject.com/en/dev/intro/tutorial04/> I'm trying to access admin page but it display this error which I don't know how to fix. TemplateSyntaxError at /admin/ Caught SyntaxError while rendering: invalid syntax (views.py, line 34)Request Method: GET Request URL: http://cat.pythonanywhere.com/admin/ Django Version: 1.3.5 Exception Type: TemplateSyntaxError Exception Value: Caught SyntaxError while rendering: invalid syntax (views.py, line 34) Exception Location: /home/cat/mysite/myapp/urls.py in <module>, line 2 Python Executable: /usr/local/bin/uwsgi Python Version: 2.7.3 Python Path: ['/var/www', my views.py are : from django.http import HttpResponse ,HttpResponseRedirect from mysite.myapp.models import Poll from django.http import Http404 from django.template import Context, loader from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from polls.models import Choice, Poll def index(request): return HttpResponse("Hello, world. You're at the poll index.") def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) def results(request, poll_id): return HttpResponse("You're looking at the results of poll %s." % poll_id) def vote(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the poll voting form. return render(request, 'myapp/detail.html', { 'poll': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('myapp:results', args=(p.id,)))) def index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] template = loader.get_template('myapp/index.html') context = Context({ 'latest_poll_list': latest_poll_list, }) return HttpResponse(template.render(context)) def detail(request, poll_id): poll = get_object_or_404(Poll, pk=poll_id) return render(request, 'myapp/detail.html', {'poll': poll}) def results(request, poll_id): poll = get_object_or_404(Poll, pk=poll_id) return render(request, 'myapp/results.html', {'poll': poll}) Line 34 is here return HttpResponseRedirect(reverse('myapp:results', args=(p.id,)))) Can you please help me! Answer: return HttpResponseRedirect(reverse('results', args=p.id))
Python macro in regular expression Question: In the below case i have used `"|"` condition in matching multiple search patterns and replacing all the search patterns with the value. It worked fine. But Does python has any MACRO type of thing where i can write all the patterns in it and call that in the search pattern? and replace all the patterns at once. Because i have to write almost 20 to 30 search patterns. Please help me in implementing this. Thanks in Advance. import re st = '''<h5>Reglar</h5> <h5>Lateral</h5> <h5>Daily</h5> <h5>Weekly</h5> <h5>Monthly</h5> <h5>Quaterly</h5> <h5>Yearly</h5> <h5>Halfyearly</h5>''' vr = re.sub(r'(?i)<h5>(Lateral|Halfyearly|Monthly)</h5>', "<h5>FINAL</h5>", st) print vr Answer: Python does not have macros. I am not certain to understand for sure what you are after but: Strings containing the regular expression can be build programmatically: frequncy_str = ('Lateral', 'Daily', 'Weekly', 'Monthly') re_str = '(?i)<h5>(' + '|'.join(frequency_str) + ')</h5>' For better performances, if the match is going to be performed several times one should compile the regular expression: re_pat = re.compile(re_str)
Pygame 'LEFT' is not defined Question: I'm working on a game. I have pygame imported. I am using Python 3.3 and Pygame 3.3. The same error message all the time "LEFT" is not defined. I did exact copies of what were on the internet as I already did a search for the problem. Here is my code. I have tried a few different ways and neither seem to work. method 1: import pygame event = pygame.event.poll() if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: ....command method 2: (basically going all in) from pygame import * from pygame.locals import * import pygame event = pygame.event.poll() if event.type == MOUSEBUTTONDOWN and event.button == LEFT: ......command Before telling me, on both those methods I tried switching between "LEFT" and "pygame.LEFT", and so on. Any ideas? Hugely appreciated. Answer: Define `LEFT` yourself: LEFT = 1 The [Pygame tutorial](http://lorenzod8n.wordpress.com/2007/05/30/pygame- tutorial-3-mouse-events/) I think you are following does exactly that. In other words, the `pygame` library has no constants for this value, it's just an integer.
Date and Time string parse Question: I have a date time string formatted as follows: **2012-12-03T02:00:00Z** I want to split the date and time up and display it as follows: 03/12/2012 02:00:00 How can I do this in python in as few a lines as possible?? (The 'T' and 'Z' will be removed) Answer: This goes through the `datetime` library and will throw an exception if the input string is not correctly formatted or contains an invalid datetime information (leap years included!). from datetime import datetime datetime.strptime("2012-12-03T02:00:00Z", "%Y-%m-%dT%H:%M:%SZ").strftime("%d/%m/%Y %H:%M:%S")
Python Flask, how to set 'Content-Type' for static files (js)? Question: For my Flask app I use 'windows-1251' encoding. To draw a template I set 'Content-Type' as follows: from flask.helpers import make_response def render_tmpl_dummy(): response = make_response("Some Russian text here") response.headers['Content-Type'] = 'text/html; charset=windows-1251' return response And all fine here. But my static js-files also in 'windows-1251'. So, is there any way to set `'Content-Type=application/x-javascript; charset=windows-1251'` for all static files? (PS: I do not want to convert them to UTF-8 manually in advance, this method is not suitable for me) Answer: Your static files shouldn't be served by the web server other than in development, so converting the file encoding is the **correct** method. If your reason for not converting the files first is due to volume, see [How to convert a file to utf-8 in Python?](http://stackoverflow.com/questions/191359/how-to-convert-a-file-to- utf-8-in-python) to see how to automate it.
Can I create a subclass derived from metaclass like this? Question: I tried to create a class that inherit from a metaclass declared in the superclass, I did like that: from sqlalchemy import Column, String, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker class Database(object): """ Class that holds all data models classes and functions """ def __init__(self, wenDbPath = "test.db"): self.engine = create_engine('sqlite:///' + "c:/"+wenDbPath, echo=False) self.Session = sessionmaker(bind=self.engine) **self.Base** = declarative_base() # This returns a metaclass. self.Base.metadata.create_all(self.engine) self.session = self.Session() class Element(**self.Base**): __tablename__ = 'elements' idNumber = Column(String(255), primary_key=True) smallDiscription = Column(String(50), nullable=False) longDiscription = Column(String()) webLink = Column(String()) def __init__(self, idNumber, smallDiscription, longDiscription, webLink): self.idNumber = idNumber self.longDiscription = longDiscription self.smallDiscription = smallDiscription self.webLink = webLink def __repr__(self): return "<Element ('%s : %s')>" % (self.idNumber, self.smallDiscription) Python gives me the following message > class Element(self.Base): NameError: name 'self' is not defined How can I do something like this? Thank you in advance. Answer: A class body is evaluated before `__init__` runs. Since `Base` doesn't depend on `__init__` parameters, you can evaluate it at class evaluation time: class Database(object): ... Base = declarative_base() # This returns a metaclass. class Element(Base): ... Note that you're using `Base` as a superclass, not a metaclass; metaclass syntax is `__metaclass__ = Base` or `(metaclass=Base)` depending on version. See [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in- python)
Python Coin Toss Question: I am VERY new to Python and I have to create a game that simulates flipping a coin and ask the user to enter the number of times that a coin should be tossed. Based on that response the program has to choose a random number that is either 0 or 1 (and decide which represents “heads” and which represents “tails”) for that specified number of times. Count the number of “heads” and the number of “tails” produced, and present the following information to the user: a list consisting of the simulated coin tosses, and a summary of the number of heads and the number of tails produced. For example, if a user enters 5, the coin toss simulation may result in [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]. The program should print something like the following: “ [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’] This is what I have so far, and it isn't working at all... import random def coinToss(): number = input("Number of times to flip coin: ") recordList = [] heads = 0 tails = 0 flip = random.randint(0, 1) if (flip == 0): print("Heads") recordList.append("Heads") else: print("Tails") recordList.append("Tails") print(str(recordList)) print(str(recordList.count("Heads")) + str(recordList.count("Tails"))) Answer: You are nearly there: 1) You need to call the function: coinToss() 2) You need to set up a loop to call `random.randint()` repeatedly.
How to specify the dimensions of a Tkinter text box in pixels? Question: **Question** How would I specify the dimensions of a Tkinter text box using pixels? I am not trying to change the font size - I am using this to help me scale it to the size of the window. **Tech Specs** OS: Windows 7 Python 2.7.3 Answer: You can do it by putting it inside a frame, forcing the frame to a fixed size by deactivating size propagation and configuring the entry to stick to the frame borders. Should work in a similar way with pack, too. import Tkinter # tkinter with small t for python 3 #import ttk # nicer widgets root = Tkinter.Tk() mainFrame = Tkinter.Frame(root) mainFrame.grid() button = Tkinter.Button(mainFrame, text="dummy") button.grid() entryFrame = Tkinter.Frame(mainFrame, width=454, height=20) entryFrame.grid(row=0, column=1) # allow the column inside the entryFrame to grow entryFrame.columnconfigure(0, weight=10) # By default the frame will shrink to whatever is inside of it and # ignore width & height. We change that: entryFrame.grid_propagate(False) # as far as I know you can not set this for x / y separately so you # have to choose a proper height for the frame or do something more sophisticated # input entry inValue = Tkinter.StringVar() inValueEntry = Tkinter.Entry(entryFrame, textvariable=inValue) inValueEntry.grid(sticky="we") root.mainloop()
python local scope Question: Running this code: import re regex = re.compile("hello") number = 0 def test(): if regex.match("hello"): number += 1 test() Produces this error: Traceback (most recent call last): File "test.py", line 12, in <module> test() File "test.py", line 10, in test number += 1 UnboundLocalError: local variable 'number' referenced before assignment Why can i reference `regex` from inside the function, but not `number`? Answer: Because you're defining a new variable called `number` inside the function. Here's what your code effectively does: def test(): if regex.match("hello"): number = number + 1 When Python first compiles this function, as soon as it sees `number =`, that makes `number` into a local. Any reference to `number` inside that function, _no matter where it appears_ , will refer to the new local. The global is shadowed. So when the function actually executes and you try to compute `number + 1`, Python consults the _local_ `number`, which hasn't been assigned a value yet. This is all due to Python's lack of variable declaration: because you don't declare locals explicitly, they're all declared implicitly at the _top_ of the function. In this case, you can use `global number` (on its own line) to tell Python you always want to refer to the global `number`. But it's often better to avoid needing this in the first place. You want to combine some kind of behavior with some kind of state, and that's exactly what objects are for, so you could just write a small class and only instantiate it once.
C Code Link Errors with an iPhone App Question: I am having link errors when integrating a small number of C source files into an objective-c iOS project. The C files were given to me by another developer who successfully used the code in c projects and in python projects. When I add the c source code into the XCode project, the code compiles, but I get link errors after adding code in the objective c files to reference to C code. I get "duplicate symbol errors" for variables in the C code. This is when the objective c code has the .m extension. When I change the objective c file to the .mm extension, I get "symbols not found for architecture i386" errors for the C functions I am calling from the objective c code. There are many questions about C and objective C on forums, and I haven't found a solution yet. Any quick things to check? Code snippets: File: res.h float Max_Std_Amp = 50; void RD_Dispose(void); File: res.c void RD_Dispose(void) { Max_Std_Amp = 0; } File: Import.mm #import "res.h" void process(UInt32* data, UInt32 dataLength) { RD_Dispose(); } Link errors: When Import.m has a .m extension: duplicate symbol _Max_Std_Amp in: /Users/dayhacker/Library/Developer/Xcode/DerivedData/My_Project-dbvpktweqzliaefgbqbebtdgyrey/Build/Intermediates/My Project.build/Debug-iphonesimulator/Respitory Rate.build/Objects-normal/i386/Import.o When Import.mm has a .mm extension: Undefined symbols for architecture i386: "RD_Dispose()", referenced from: process(unsigned long*, unsigned long) in Import.o Answer: res.h: float Max_Std_Amp = 50; That should be: extern float Max_Std_Amp; and the actual `float` defined in a source file (`res.c`): float Max_Std_Amp = 50; Otherwise `Max_Std_Amp` will be part of every source module that includes `res.h`, which is not what was intended. If you want to use a C-function from C++ (`.mm` is Objective-C++), you need to declare the function as having C-linkage, like this: res.h: #ifdef __cplusplus extern "C" { #endif void RD_Dispose(void); #ifdef __cplusplus } // extern "C" #endif The above use of guard macros and C-linkage definition will allow the `res.h` header file to be included in both C and C++ (Objective-C and Objective-C++) source modules.
Run a Python Script from the Web Question: I've been stumbling along with the same problem for almost a year now. I always find a way to work around it, but I'm tired of finding work arounds. What I need is to create a button on a Web Page (preferable HTML, not PHP or ASP) that runs a python script on the server. I'd also like the ability to have this button send information from a form to the script. I need to do this on a local host and through a web service hosted on the Amazon Cloud. I won't be able to install anything extra on the Amazon Cloud service, such as PHP or CGI. I'd really like an easy solution, I'm an expert with python and I can write webpages that whistle, but I just can't find a simple solution to this problem. My ideal solution would be something like the mail to tag: <a href="mailto:[email protected]?Subject=Hello%20again">Send Mail</a> Except: <a href="myscript.py?Subject=1234">Run Script</a> Now I highly doubt a solution like that exists, but well I can dream right. The script I am trying to run: 1. Returns a Unique ID from the user 2. Sends the ID to a GIS program that creates a map based on the ID (the ID selects the area of the map) 3. The map is then exported to a PNG, wrote into an HTML document and then displayed for the user in a new tab. EDIT --------------------------- Thanks to @Ketouem answer I was able to find a great solution to my issue. I'll post some of the code here so that others can benefit. Make sure you download the Bottle Module for python, its great. # 01 - Import System Modules from bottle import get, post, request, Bottle, run, template # 02 - Script Variables app = Bottle() # 03 - Build Temporary Webpage @app.route('/SLR') def login_form(): return '''<form method="POST" action="/SLR"> Parcel Fabric ID: <input name="UID" type="text" /><br /> Save Location: <input name="SaveLocation" type="text" value="D:/Python27/BottleTest/SLR_TestOutputs"/><br /> Air Photo On: <input name="AirPhoto" type="checkbox"/><br /> Open on Completion: <input name="Open" type="checkbox"/><br /> Scale: <input name="Scale" type="text" value="10000"/><br /> <input type="submit" /> </form>''' # 04 - Return to GIS App @app.route('/SLR', method='POST') def PHPH_SLR_Script(): # I won't bother adding the GIS Section of the code, but at this point it send the variables to a program that makes a map. This map then saves as an XML and opens up in a new tab. # 04 - Create and Run Page run(app, host='localhost', port=8080) Answer: You could use Bottle : <http://bottlepy.org/docs/dev/index.html> which is a light web framework
Can't connect to JIRA Python through REST api https url Question: I try to connect to a jira dev sandbox through https but it comes up with an SSL23_GET_SERVER_HELLO:unknown protocol error This is the error log/stack trace. I try both ports 8080 and 443 but no joy. >>> from jira.client import JIRA >>> options = {'server':'localhost:8080'} >>> auth = ('username', 'password') >>> jira = JIRA(options, auth) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ve/lib/python2.6/site-packages/jira/client.py", line 88, in __init__ self._create_http_basic_session(*basic_auth) File "/home/ve/lib/python2.6/site-packages/jira/client.py", line 1369, in _create_http_basic_session r = self._session.post(url, data=json.dumps(payload)) File "/home/ve/lib/python2.6/site-packages/requests/sessions.py", line 284, in post return self.request('post', url, data=data, **kwargs) File "/home/ve/lib/python2.6/site-packages/requests/sessions.py", line 241, in request r.send(prefetch=prefetch) File "/home/ve/lib/python2.6/site-packages/requests/models.py", line 638, in send raise SSLError(e) requests.exceptions.SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol >>> options = {'server':'localhost:443'} >>> auth = ('username', 'password') >>> jira = JIRA(options, auth) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ve/lib/python2.6/site-packages/jira/client.py", line 88, in __init__ self._create_http_basic_session(*basic_auth) File "/home/ve/lib/python2.6/site-packages/jira/client.py", line 1369, in _create_http_basic_session r = self._session.post(url, data=json.dumps(payload)) File "/home/ve/lib/python2.6/site-packages/requests/sessions.py", line 284, in post return self.request('post', url, data=data, **kwargs) File "/home/ve/lib/python2.6/site-packages/requests/sessions.py", line 241, in request r.send(prefetch=prefetch) File "/home/ve/lib/python2.6/site-packages/requests/models.py", line 631, in send raise ConnectionError(sockerr) requests.exceptions.ConnectionError: [Errno 110] Connection timed out >>> Answer: Try this: from jira.client import JIRA options = {'server':'localhost:8080'} jira = JIRA(options) jira = JIRA(basic_auth=('username', 'password')) If it doesn't help, any chance the have [`OpenSSL` conflicts](http://sourceforge.net/p/curl/bugs/990/)? > When curl is linked against OpenSSL 0.9.8 and tries to access a server > running OpenSSL 1.0.0, the SSL handshake fails with: curl: (35) > error:14077458:SSL routines:SSL23_GET_SERVER_HELLO:reason(1112)
Getting a "TypeError: an integer is required" when trying to connect to MySQL Question: Total Python newb here. I'm following the tutorial from [this page](http://zetcode.com/db/mysqlpython/). But when I run my code I get the following error in the console. Traceback (most recent call last): File "/Users/tejenshrestha/Documents/ProjectAccess/access/trunk/analysis/src/json_xml/Database.py", line 37, in <module> con = MySQLdb.connect(socket, dbhost, dbuser, dbpass, dbname); File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQLdb/connections.py", line 187, in __init__ super(Connection, self).__init__(*args, **kwargs2) TypeError: an integer is required Searching some solutions I found required that the unix_socket path to be include, which I did as you can see. I'm also using **XAMPP** and the socket path I'm using is the one specified in XAMPP's my.cnf file. I have MySQL running and the port it is 3306. Please help out this noob. The Python code: import MySQLdb import sys con = None dbhost = "localhost" port = "3306" dbuser = "root" dbpass = "password" dbname = "name" socket = "/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock" try: con = MySQLdb.connect(socket, dbhost, dbuser, dbpass, dbname); cur = con.cursor() cur.execute("SELECT VERSION()") data = cur.fetchone() print "Database version : %s " % data except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) finally: if con: con.close() Answer: Take the quotes from around port and see if that works. * * * <brilliant code> port = 3306 <brilliant code> * * * I think you need to label the arguments in your connect function, see the top answer here: [How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a- mysql-database-in-python)
Learn SQL The Hard way - Creating .sql with .db in SQL Lite 3 - Why and How? Question: As a beginning programmer with +20 hours of Python coding and novice familiarity with the command-line, I opened up Zed Shaw's "Learn SQL The Hard Way" and was quickly stumped. In [exercise 01](http://sql.learncodethehardway.org/book/ex1.html), Zed has you create your first table with this first command: sqlite3 ex1.db < ex1.sql However this fails to run in my command-line, giving the error message, "-bash: ex1.sql: No such file or directory." Initially, I ignored this recommended code and proceeded with: sqlite3 ex1.db SQLite version 3.7.15.1 2012-12-19 20:39:10 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> CREATE TABLE person ( ...> id INTEGER PRIMARY KEY, ...> first_name TEXT, ...> last_name TEXT, ...> age INTEGER ...> ); Running "ls -l" in the command-line shows: -rw-r--r-- 1 thefifth staff 2048 Feb 15 15:23 ex1.db But what I want and am failing to get is: $ ls -l -rw-r--r-- 1 zedshaw staff 2048 Nov 8 16:18 ex1.db -rw-r--r-- 1 zedshaw staff 92 Nov 8 16:14 ex1.sql I Googled around and found [this blog](http://www.adamjonas.com/blog/learn- sql-the-hard-way/) that implements the same "name.db < name.sql" syntax, but following along the code here didn't work for me either. This [Stack Overflow](http://stackoverflow.com/questions/2049109/how-to-import-sql-into- sqlite3) also has a similar syntax, but in the context of converting .sql to sqlite3. Specifically, I'm wondering if this is the "<" for use in the native bash terminal, and that I'm failing to meet certain criteria for its correct use. Also, I don't know the purpose of creating both a .sql and .db file, although apparently one is much smaller than the other. Perhaps I've installed sqlite3 incorrectly, but it seems to be working fine. Thanks for your help! Answer: sqlite3 ex1.db < ex1.sql For the above to work, `ex1.sql` should already exist. `<` is a character used in shells for input redirection. `sqlite3` is started here with a new or existing database (it will create the database as needed), and gets SQL statements from `ex1.sql`, executing them and modifying `ex1.db` accordingly. Now let's generate `ex1.sql` from `ex1.db`, which you apparently want to do: sqlite3 ex1.db .dump > ex1.sql We use shell redirection facility again, now redirecting the _output_ to `ex1.sql`. The `.dump` command makes `sqlite` write out SQL statements that will recreate similar database when they are executed in an empty database: tables are recreated and populated with `INSERT`, etc. Now you can go to step 1: sqlite3 ex1copy.db < ex1.sql
Benchmarking with Python Question: I am looking to use Python as a system to benchmark other process's time, data I/O, correctness, etc. What I am really interested in is the accuracy of the time. For example start = time() subprocess.call('md5sum', somelist) end = time() print("%d s", end-start) Would the sub process add a considerable overhead to the function being called. EDIT Well after a few quick tests it appears my best option is to use `subprocess` however I have noted by included stdout/stderr WITH the communicate call it adds about `0.002338 s` extra time to the execution. Answer: Use [timeit](http://docs.python.org/2/library/timeit.html) import timeit timeit.timeit('yourfunction') **Update** If you are in linux, then you can use `time` command, like this: import subprocess result = subprocess.Popen(['time', 'md5sum', somelist], shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate() print result
"Error generating the Discovery document for this api" when trying to build a drive service, starting 2/14/2013 Question: I am intermittently getting this error when calling build on a drive service. I am able to reproduce this with a simple program which has the JSON credentials stored to a file. #!/usr/bin/python import httplib2 import sys from apiclient.discovery import build from oauth2client.client import Credentials json_creds = open('creds.txt', 'r').read() creds = Credentials.new_from_json(json_creds) http = httplib2.Http() http = creds.authorize(http) try: drive_service = build('drive', 'v2', http=http) except Exception: sys.exit(-1) When I run this in a loop, I am seeing a rather high number of errors, this code in a loop fails 15-25% of the time for me. i=0; while [ $i -lt 100 ]; do python jsoncred.py || echo FAIL ; i=$(( $i + 1 )); done | grep FAIL | wc -l Now when I take this same code, and just replace 'drive' by 'oauth2', the code runs without problems I have confirmed that the OAuth token that I am using is valid and have the correct scopes: "expires_in": 2258, "scope": "<https://www.googleapis.com/auth/userinfo.profile> <https://www.googleapis.com/auth/drive> <https://www.googleapis.com/auth/userinfo.email>", Looking at my app logs, this seems to have started 2/14/2013 1PM PST. I did not push any new code, so I wonder if this a problem with the API. Is there a bug in the API causing this ? Answer: Google are seeing some reports of increased error rates for the discovery document. Please just retry on 500 error for now, and you should be successful. One could argue that you should have retry logic for this call anyway, since it is good practice, but the current levels are too high, so, sorry about that. _Update:_ this should now be fixed.
lxml on python-3.3.0 ImportError: undefined symbol: xmlBufContent Question: I am having a hard time installing lxml(3.1.0) on python-3.3.0. It installs without errors and I can see the lxml-3.1.0-py3.3-linux-i686.egg in the correct folder (/usr/local/lib/python3.3/site-packages/), but when I try to import etree, I get this: > > > from lxml import etree Traceback (most recent call last): File "", line > 1, in ImportError: /usr/local/lib/python3.3/site- > packages/lxml-3.1.0-py3.3-linux-i686.egg/lxml/etree.cpython-33m.so: > undefined symbol: xmlBufContent I did try to install with apt-get, I tried "python3 setup.py install" and I did via easy_install. I have to mention that I have 3 versions installed (2.7, 3.2.3 and 3.3.0.), but I am too much of a beginner to tell if this has to do with it. I did search all over, but I could not find any solution to this. Any help is greatly appreciated! best, Uhru Answer: You should probably mention the specific operating system you're trying to install on, but I'll assume it's some form of Linux, perhaps Ubuntu or Debian since you mention apt-get. The error message you mention is typical on `lxml` when the `libxml2` and/or `libxslt` libraries are not installed for it to link with. For whatever reason, the install procedure does not detect when these are not present and can give the sense the install has succeeded even though those dependencies are not satisfied. If you issue `apt-get install libxml2 libxml2-dev libxslt libxslt-dev` that should eliminate this error.
Can you loop through pixels in an image without loading the whole image? Question: I have some very large images. I don't want to load the whole image into memory, I just want to make a single pass through the image in row order. Is it possible to do this in Python/scipy? EDIT: I'm using .PNG, but I could convert them to PPM, BMP or something else lossless. Answer: [GDAL](http://www.gdal.org/) (with Python bindings) offers some very good drivers for this. Although its a geospatial package, it works fine with BMP and PNG for example. This example show how to load a PNG row by row: import gdal # only loads the dataset ds = gdal.Open('D:\\my_large_image.png') # read 1 row at the time for row in range(ds.RasterYSize): row_data = ds.ReadAsArray(0,row,ds.RasterXSize,1) ds = None # this closes the file It gives you a Numpy array as a result, so ready for procesing. You could write any result in a similar fashion. print type(row_data) <type 'numpy.ndarray'> print row_data.shape (3, 1, 763) print row_data [[[ 0 0 255 ..., 230 230 0]] [[ 0 0 252 ..., 232 233 0]] [[ 0 0 252 ..., 232 233 0]]] Installing a package specific for reading might be a bit overkill if PIL or something else can do it. But its a robust option, i have processed images of 30000*30000 pixels like this.
Set Gtk.ComboBoxText default item? Question: I would like to make an item in my ComboBoxText the default value, instead of a blank combo box until the user selects something. Apparently, this is set by changing Active value in Glade to [the item I want to be default]. This does not work. Here is my code: #! /usr/bin/env python3 from gi.repository import Gtk builder = Gtk.Builder() builder.add_from_file("./personalinfo.ui") win = builder.get_object("window") cancel = builder.get_object("cancel") ok = builder.get_object("ok") win.set_title("Persona") win.connect("destroy", Gtk.main_quit) cancel.connect("clicked", Gtk.main_quit) ok.connect("clicked", Gtk.main_quit) win.show_all() Gtk.main() Here is the combo box in Glade: ![comboboxtext](http://i.stack.imgur.com/d19Jz.png) Answer: This is actually a bug in Glade. You can manually set this by using: combo.set_active(int) # 1st item is 0, 2nd is 1 and such.
how to write setup.py for this application structure? Question: I have written an application with python (2.7). The structure looks like: kent$ tree myApp myApp |-- foo.py |-- gui | |-- g1.py | |-- g2.py | |-- g3.py | `-- __init__.py |-- icons | |-- a.png | `-- e.png |-- logic | |-- __init__.py | |-- l1 | | |-- __init__.py | | |-- la.py | | `-- lc.py | |-- l2 | | |-- __init__.py | | |-- ld.py | | `-- lf.py | |-- logic1.py | |-- logic2.py | `-- logic3.py |-- myApp.py `-- resources |-- x.data `-- z.data Now I am about to write a `setup.py` to distribute my application. I am new to this. After reading the py doc and doing some testing. a few questions come up: 1. **how can I (or should I) package my root package (myApp) under`/lib/python/site-package` ?** since in my py file, I reference resources/icons by relative path. for example, in `foo.py` there could be `icons/a.png` and in `gui/g1.py` there could be `../icons/e.png` and so on 2. **how can I package`icons` and `resources` directory?** It seems that `package_data` and `data_files` won't copy the two directories to right place. 3. **is this the right way?** packages = [''], package_dir = {'': ''}, package_data= {'': ['icons/*.*', 'resources/*.*']}, after install, my files will be: /usr/lib/python2.7/site-packages/icons/*.png /usr/lib/python2.7/site-packages/resources/*.data /usr/lib/python2.7/site-packages/gui/... /usr/lib/python2.7/site-packages/logic/... 4. **Is there problem of my application structure?** should those resources/icons/whatever files go to certain python package, not under the project root? so that in setup.py I can use `package_data` to copy them to right place. Answer: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup(name="somename", version="1.0", description="description string", long_description="""\ long description """, author="Foo", author_email="[email protected]", url="http://nowhere.com", include_package_data=True, license="MIT", packages=["gui", "logic"], package_dir={ "gui": "myApp/gui", "logic": "myApp/logic", }, classifiers=[ "Development Status :: 5 - Production/Stable", "Topic :: Utilities", "License :: OSI Approved :: MIT License" ], data_files=[ ('/path/to/resources', ['resources/x.data', 'resources/y.data']), ('/path/to/icons', ['myApp/icons/a.ico', 'myApp/icons/e.ico']) ] )
Python Client-server problems Question: I am making a chat program. I have a (TCP) server which creates a new thread for every connection request it gets. 1. I'm having problems when the client quits/terminates connection. The server raises an error(below). How do I handle it? 2. And, the server has to send the 'data' it receives from one client to another (changeable) client. How do I implement this?? I receive this error when the client quits : Exception in thread Thread-1: Traceback (most recent call last): File "C:\Python2.7 For Chintoo\lib\threading.py", line 552, in __bootstrap_inner self.run() File "C:\Python2.7 For Chintoo\lib\threading.py", line 505, in run self.__target(*self.__args, **self.__kwargs) File "C:\Users\karuna\Desktop\Jython\Python\My Modules\Network\Multi-server.py", line 23, in recv_loop data = client.recv(1024) error: [Errno 10054] An existing connection was forcibly closed by the remote host My scripts: **Multi-server.py** import os, socket, time, threading, random class Server: def __init__(self,host,port,user): self.port = port self.host = host self.user = user self.bufsize = 1024 self.addr = (host,port) self.socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM) self.socket.bind(self.addr) print "Server running on",host,"at port",port self.socket.listen(5) def recv_loop(server,client,caddr): print 'Connected To',caddr while True: global clients name = clients[client] data = client.recv(1024) if not data: break print name + " said: " + data client.close() host = 'localhost' port = random.randint(1025,60000) user = 'No one' server = Server(host, port, user) clients = {} threads = [] while True: client, caddr = server.socket.accept() # name extraction name = client.recv(1024) clients[client] = name thread = threading.Thread(target=recv_loop, args=(server,client, caddr)) thread.start() **client.py** from socket import * host = 'localhost' name = raw_input('Enter name: ') port = int(raw_input('Enter server port: ')) bufsiz = 1024 addr = (host, port) tcpClient = socket(AF_INET , SOCK_STREAM) tcpClient.connect(addr) # sending name tcpClient.send(name) while True: data = raw_input('> ') if not data: break tcpClient.send(data) raw_input('Enter to Quit') Answer: I haven't done socket programming in Python, but you might want to cleanly close your socket connection before the client quits. I would use `close` method in the client.
Django - how to collapse forms like in the django admin Question: I use [django-form-utils](http://pypi.python.org/pypi/django-form-utils) to generate BetterModelForm with fieldsets similar to the django admin. With BetterModelForm its possible to associate CSS with fieldset with the 'classes' option. I would like to know how I could collapse the fieldset of my form like we can do it in Django-Admin. forms.py: class ezAppOptionFormSet(BetterModelForm): class Meta: model = EzApp fieldsets = [('App options:', {'fields': ['level', 'center_1', 'center_2', 'width', 'height'], 'classes': ['collapse']}), ('Colors:', {'fields': ['color'], 'classes': ['collapse']}) ] template.html: <form method="post" action="." encrypt="multipart/form-data">{% csrf_token %} <b>App name: {{ App_title }}</b> {% if formset.non_field_errors %}{{ formset.non_field_errors }}{% endif %} {% for fieldset in formset.fieldsets %} <fieldset class="{{ fieldset.classes }}"> {% if fieldset.legend %} <legend>{{ fieldset.legend }}</legend> {% endif %} {% if fieldset.description %} <p class="description">{{ fieldset.description }}</p> {% endif %} <ul> {% for field in fieldset %} {% if field.is_hidden %} {{ field }} {% else %} <li{{ field.row_attrs }}> {{ field.errors }} {{ field.label_tag }}<br> {{ field }} </li> {% endif %} {% endfor %} </ul> </fieldset> {% endfor %} Answer: The way I did it is simply use the collapse.js script of django admin. In the template, import the script: <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/actions.js"></script> <script type="text/javascript" src="/static/js/collapse.js"></script> Then change the tag `<legend>` for `<h2>` and bingo, you have the same collapse. <form method="post" action="." encrypt="multipart/form-data">{% csrf_token %} <b>App name: {{ App_title }}</b> {% if formset.non_field_errors %}{{ formset.non_field_errors }}{% endif %} {% for fieldset in formset.fieldsets %} <fieldset class="{{ fieldset.classes }}"> {% if fieldset.legend %} <h2>{{ fieldset.legend }}</h2> {% endif %} {% if fieldset.description %} <p class="description">{{ fieldset.description }}</p> {% endif %} <ul> {% for field in fieldset %} {% if field.is_hidden %} {{ field }} {% else %} <li{{ field.row_attrs }}> {{ field.errors }} {{ field.label_tag }}<br> {{ field }} </li> {% endif %} {% endfor %} </ul> </fieldset> {% endfor %}
Python, tkinter: How to select a directory then load the path as a variable to an imported class? Question: I am developing a gui in which the user has to browse choose the a directory. Then I need the directory path to be saved as a variable and used by an imported class. So far I have written the code that enables a user to pick a directory but am not stuck as what to do next. The code I have so far is below: def loadDirectory(): directory = filedialog.askdirectory() the function is called by pushing a button. Thanks in advance Answer: This is relatively simple. import chrome def loadDirectory(): chrome.directory = filedialog.askdirectory() This should do what you want.
Loading huge XML files and dealing with MemoryError Question: I have a very large XML file (20GB to be exact, and yes, I need all of it). When I attempt to load the file, I receive this error: Python(23358) malloc: *** mmap(size=140736680968192) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug Traceback (most recent call last): File "file.py", line 5, in <module> code = xml.read() MemoryError This is the current code I have, to read the XML file: from bs4 import BeautifulSoup xml = open('pages_full.xml', 'r') code = xml.read() xml.close() soup = BeautifulSoup(code) Now, how would I go about to eliminating this error and be able to continue working on the script. I would try splitting the file into separate files, but as I don't know how that would affect BeautifulSoup as well as the XML data, I'd rather not do this. (The XML data is a database dump from a wiki I volunteer on, using it to import data from different time-periods, using the direct information from many pages) Answer: Do _not_ use BeautifulSoup to try and such a large parse XML file. Use the [ElementTree API](http://docs.python.org/2/library/xml.etree.elementtree.html) instead. Specifically, use the [`iterparse()` function](http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse) to parse your file as a stream, handle information as you are notified of elements, then _delete_ the elements again: from xml.etree import ElementTree as ET parser = ET.iterparse(filename) for event, element in parser: # element is a whole element if element.tag == 'yourelement' # do something with this element # then clean up element.clear() By using a event-driven approach, you never need to hold the _whole_ XML document in memory, you only extract what you need and discard the rest. See the [`iterparse()` tutorial and documentation](http://effbot.org/zone/element-iterparse.htm). Alternatively, you can also use the [lxml library](http://lxml.de/); it offers the same API in a faster and more featurefull package.
Setting process name (as seen by `ps`) in Go Question: The following (rightfully) doesn't work: package main import ( "os" "time" ) func main() { os.Args[0] = "custom name" println("sleeping") time.Sleep(1000 * time.Second) println("done") } Some languages provide this feature of [setting process name](http://www.steve.org.uk/Reference/Unix/faq_2.html#SEC22) as a built-in functionality (in Ruby, for instance, it is only a matter of [assigning to](https://github.com/mperham/sidekiq/blob/master/lib/sidekiq/launcher.rb#L27) `$0`) or as a third-party library ([Python](http://pypi.python.org/pypi/setproctitle)). I'm looking for a solution that works, at least, on Linux. Answer: There are multiple ways to accomplish this, and many of them only work in certain situations. I don't really recommend doing it, as (for one thing) it can result in your process showing up with different names in different situations. They require using syscall and/or unsafe, and so you're deliberately subverting the safety of the Go language. That said, however, your options seem to be: ## Modify argv[0] func SetProcessName(name string) error { argv0str := (*reflect.StringHeader)(unsafe.Pointer(&os.Args[0])) argv0 := (*[1 << 30]byte)(unsafe.Pointer(argv0str.Data))[:argv0str.Len] n := copy(argv0, name) if n < len(argv0) { argv0[n] = 0 } return nil } In Go, you don't have access to the actual argv array itself (without calling internal runtime functions), so you are limited to a new name no longer than the length of the current process name. This seems to mostly work on both Darwin and Linux. ## Call PR_SET_NAME func SetProcessName(name string) error { bytes := append([]byte(name), 0) ptr := unsafe.Pointer(&bytes[0]) if _, _, errno := syscall.RawSyscall6(syscall.SYS_PRCTL, syscall.PR_SET_NAME, uintptr(ptr), 0, 0, 0, 0); errno != 0 { return syscall.Errno(errno) } return nil } The new name can be at most 16 bytes. This doesn't work on Darwin, and doesn't seem to do much on Linux, though it succeeds and PR_GET_NAME reports the correct name afterward. This may be something peculiar about my Linux VM, though.
working with lynx in python terminal +displaying spanish characters not working Question: I am querying lynx browser with a URL and getting the output from the terminal, but the problem is the output is from a peruvian website and the spanish characters are not being displayed correctly on the terminal. I am passing the -assume_charset and -assume_unrec_charset flags along with my call to the url so it should replace the character set with the one I specify if the website does not specify one. And for both these parameters I have tried Latin 1, Latin 3 and Latin 4 and none of them seem to work. I would like to know how I can fix this problem. I am using python subprocess module and passing the lynx query as a parameter to subprocess.Popen(...) and then reading the output from STDOUT. My code is the following: import subprocess def get_urlData(url): cmd = "lynx -dump -nolist -notitle -assume_charset =\"ISO-8859-1\" -assume_unrec_charset=\"ISO-8859-1\" "+url lynx = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) file_data = lynx.stdout.read() #file_data = file_data.decode('ISO-8859-1','replace') return file_data When I store the returned file_data in an object and attempt to print it on the python terminal, the following is a part of the output I get which I am including to clarify the problem: Per\xedodo: Periodo de Gobierno 2006- 2011. Legislatura: Primera\n Legislatura Ordinaria 2010\n N\xfamero: 04903/2010-CR Fecha Presentaci\u0137n: 07/13/2011\n Proponente: Congreso\n Grupo Parlamentario: Multipartidario\n T\xedtulo: LEY QUE EXTINGUE LA DEUDA TRIBUTARIA PROVENIENTE DE LA\n IMPORTACI\u0136N Y/O VENTA DE COMBUSTIBLE TURBO A1\n clearly the character \u0137 needs to be some other spanish character but I dont know how to get that to display on my terminal. Any help would be appreciated. Answer: \u0136 and \u0137 are UTF characters , your charset in cmd is ISO-8859-1... you must have the same character enconding.
Histogram based probability density estimation Question: How do I make a histogram based probability density estimate of each of the marginal distributions p(x1 ) and p(x2 ) of this data set: import numpy as np import matplotlib.pyplot as plt linalg = np.linalg N = 100 mean = [1,1] cov = [[0.3, 0.2],[0.2, 0.2]] data = np.random.multivariate_normal(mean, cov, N) L = linalg.cholesky(cov) # print(L.shape) # (2, 2) uncorrelated = np.random.standard_normal((2,N)) data2 = np.dot(L,uncorrelated) + np.array(mean).reshape(2,1) # print(data2.shape) # (2, 1000) plt.scatter(data2[0,:], data2[1,:], c='green') plt.scatter(data[:,0], data[:,1], c='yellow') plt.show() For this you can use the hist function in Matlab or R. How does changing the bin width (or equivalently, the number of bins) affect the plot and the estimate of p(x1 ) and p(x2 )? I'm using Python, is there something similar to the hist function from Matlab and how to implement it? Answer: The Matlab `hist` function is implemented in matplotlib as (you guessed it) [`matplotlib.pyplot.hist`](http://matplotlib.org/api/pyplot_api.html). It plots the histogram, taking the number of bins as a parameter. To calculate a histogram without plotting it, use Numpy's [`numpy.histogram`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html) function. To estimate a probability distribution, you can use the distributions in [`scipy.stats`](http://docs.scipy.org/doc/scipy/reference/stats.html). You generated the data above from a normal distribution. To fit a normal distribution to this data you would use [`scipy.stats.norm.fit`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm). Below is a code example that plots histograms of your data and fits normal distribution to it: import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm linalg = np.linalg N = 100 mean = [1,1] cov = [[0.3, 0.2],[0.2, 0.2]] data = np.random.multivariate_normal(mean, cov, N) L = linalg.cholesky(cov) # print(L.shape) # (2, 2) uncorrelated = np.random.standard_normal((2,N)) data2 = np.dot(L,uncorrelated) + np.array(mean).reshape(2,1) # print(data2.shape) # (2, 1000) plt.figure() plt.scatter(data2[0,:], data2[1,:], c='green') plt.scatter(data[:,0], data[:,1], c='yellow') plt.show() # Plotting histograms and fitting normal distributions plt.subplot(211) plt.hist(data[:,0], bins=20, normed=1, alpha=0.5, color='green') plt.hist(data2[0,:], bins=20, normed=1, alpha=0.5, color='yellow') x = np.arange(-1, 3, 0.001) plt.plot(x, norm.pdf(x, *norm.fit(data[:,0])), color='green') plt.plot(x, norm.pdf(x, *norm.fit(data2[0,:])), color='yellow') plt.title('Var 1') plt.subplot(212) plt.hist(data[:,1], bins=20, normed=1, alpha=0.5, color='green') plt.hist(data2[1,:], bins=20, normed=1, alpha=0.5, color='yellow') x = np.arange(-1, 3, 0.001) plt.plot(x, norm.pdf(x, *norm.fit(data[:,1])), color='green') plt.plot(x, norm.pdf(x, *norm.fit(data2[1,:])), color='yellow') plt.title('Var 2') plt.tight_layout()
Date 6 months into the future Question: I am using the datetime Python module in django. I am looking to calculate the date if the expiry date is less than or equal to 6 months from the current date. The reason I want to generate a date 6 months from the current date is to set an alert that will highlight the field/column in which that event occurs. I dont know if my question is clear. I have been reading about timedelta function but cant really get my head round it. I am trying to write an if statement to statisfy this condition. Anyone able to help me please? Am a newbie to django and python. Answer: There are two approaches, one only slightly inaccurate, one inaccurate in a different way: * Add a `datetime.timedelta()` of 365.25 / 2 days (average year length divided by two): import datetime sixmonths = datetime.datetime.now() + datetime.timedelta(days=365.25/2) This method will give you a datetime stamp 6 months into the future, where we define 6 monhs as exactly half a year (on average). * Use the external [`dateutil` library](http://labix.org/python-dateutil), it has a excellent [`relativedelta`](http://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454) class that will add 6 months based on calendar calculations to your current date: import datetime from dateutil.relativedelat import relativedelta sixmonths = datetime.datetime.now() + relativedelta(months=6) This method will give you a datetime stamp 6 months into the future, where the month component of the date has been forwarded by 6, and it'll take into account month boundaries, making sure not to cross them. August 30th plus 6 months becomes February 28th or 29th (leap years permitting), for example. A demonstration could be helpful. In my timezone, at the time of posting, this translates to: >>> import datetime >>> from dateutil.relativedelta import relativedelta >>> now = datetime.datetime.now() >>> now datetime.datetime(2013, 2, 18, 12, 16, 0, 547567) >>> now + datetime.timedelta(days=365.25/2) datetime.datetime(2013, 8, 20, 3, 16, 0, 547567) >>> now + relativedelta(months=6) datetime.datetime(2013, 8, 18, 12, 16, 0, 547567) So there is a 1 day and 15 hour difference between the two methods. The same methods work fine with `datetime.date` objects too: >>> today = datetime.date.today() >>> today datetime.date(2013, 2, 18) >>> today + datetime.timedelta(days=365.25/2) datetime.date(2013, 8, 19) >>> today + relativedelta(months=6) datetime.date(2013, 8, 18) The half-year timedelta becomes a teensy less accurate when applied to dates only (the 5/8th day component of the delta is ignored now).
Django - Uncaught IndentationError while rendering Question: The error occurs in the following line of the template, and I couldn't manage to understand why? In template /usr/local/django/app/templates/main.html, error at line 51 <script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script> And the precise error is: **Caught IndentationError while rendering: unindent does not match any outer indentation level (views.py, line 272)** The line 272 in views.py is: elif request.POST.get('hiddenField') == 'ad' and SettingsManager.get().ad_integ == 1: form = ADSettingsForm(request.POST) # <-----line 272 if form.is_valid(): form.save() Any ideas? **EDIT1** There is not any indendation errors in any of the files in the project. I controlled it with python's `py_compile` lib. **UPDATE1** Alright, this is very, very awkward: Now, I'm getting whole different error in another machine I have (where I installed a copy of my project) **Caught ViewDoesNotExist while rendering: Could not import wauthportal.wauthapp.views. Error was: No module named views** In template /usr/local/django/wauthadmin/templates/main.html, error at line 51 <script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script> Answer: This generally happens if you mix up tab and spaces. Please see that you have used four spaces in every indentation. If you are using text editor like Sublime Text pressing ctrl+A will show the spaces.
Convert string to list in python Question: I need to convert an string to a list in python, The string format is as follows, '[{"name":"Tom","adress":"adress1"},{"name":"Mari","adress":"adress2"}]' I need to convert this **string** in to python **list** data type and want to get the dictionaries by iterating that generated list. I have tried json library and no luck. > correction (**json.loads is working**.) Can you please tell me the correct way to do so ? Answer: You can `ast.literal_eval` it without any problem. >>> s = '[{"name":"Tom","adress":"adress1"},{"name":"Mari","adress":"adress2"}]' >>> import ast >>> ast.literal_eval(s) [{'adress': 'adress1', 'name': 'Tom'}, {'adress': 'adress2', 'name': 'Mari'}] but `json.loads` doesn't seem to have any problem with it either ... >>> import json >>> json.loads(s) [{u'adress': u'adress1', u'name': u'Tom'}, {u'adress': u'adress2', u'name': u'Mari'}] >>>
request.environ['HTTP_REFERER'] is None Question: i want to get `HTTP_REFERER` in python flask framework. My route is this: @app.route('/login') def login(): if authenticateForPanel(): return redirect(url_for("panel")) else: ref = request.environ['HTTP_REFERER'] return render_template('login.html',blogOptions = g.blogOptions,ref=ref) When i execute this,i got `KeyError: 'HTTP_REFERER'` with the traceback: Traceback (most recent call last): File "/Users/ozcan/flask/flask/app.py", line 1823, in __call__ return self.wsgi_app(environ, start_response) File "/Users/ozcan/flask/flask/app.py", line 1811, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/Users/ozcan/flask/flask/app.py", line 1809, in wsgi_app response = self.full_dispatch_request() File "/Users/ozcan/flask/flask/app.py", line 1482, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/ozcan/flask/flask/app.py", line 1480, in full_dispatch_request rv = self.dispatch_request() File "/Users/ozcan/flask/flask/app.py", line 1466, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/Users/ozcan/Documents/python/app.py", line 318, in login ref = request.environ['HTTP_REFERER'] KeyError: 'HTTP_REFERER' When i first wrote this code it was working.I do not directly call this url.I call `localhost:5000/panel` and it redirects me to the `login` method.So basically there should be a referer,am i wrong? When i print the `request.environ['HTTP_REFERER']` it prints `None` I also tried with the `ref = request.referrer` but it is `None` Why it can be happen?Thanks a lot. Answer: The werkzeug Request wrapper, which flask uses by default, does this work for you: [request.referrer](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.CommonRequestDescriptorsMixin.referrer) from flask import Flask, request import unittest app = Flask(__name__) @app.route('/') def index(): return unicode(request.referrer) class Test(unittest.TestCase): def test(self): c = app.test_client() resp = c.get('/', headers={'Referer': '/somethingelse'}) self.assertEqual('/somethingelse', resp.data) if __name__ == '__main__': unittest.main() But in the more general case, to retrieve the value of a dictionary key specifying a default if the key is not present, use [dict.get](http://docs.python.org/2/library/stdtypes.html#dict.get)
Automake, GNU make, check, and (ignored) pattern rules Question: I have the following Makefile.am which is supposed to create `foo.hdb` and `foo.cdb` from `foo.h` (via the Python script): TESTS = check_foo check_PROGRAMS = check_foo check_foo_SOURCES = check_foo.c $(top_builddir)/src/isti.h \ foo.cdb foo.h foo.hdb check_foo_CFLAGS = @CHECK_CFLAGS@ $(all_includes) -I../../clib/src/ check_foo_LDADD = $(top_builddir)/src/libcorm.la @CHECK_LIBS@ -lsqlite3 %.hdb %.cdb: %.h PYTHONPATH=$(top_builddir)/cgen/src python $(top_builddir)/cgen/src/isti/cgen/run.py $< clean-local: rm -f *.hdb *.cdb However, although `make foo.hdb` and `make foo.cdb` work (call the Python code and generates the `foo.hdb` and `foo.cdb` files from `foo.h`), `make clean check` (or the two separately) does not (missing `foo.hdb` \- no such file) - the pattern rule is not called to generate `foo.hdb` from `foo.h`. In other words: **the pattern rule is not being called for the files listed in check_foo_SOURCES**. How can I make this work? The rest of the autotools infrastructure is working fine. From looking at the Makefile I suspect the issue is with how autotools expands the check sources. This is all on Linux with Gnu make. Here is [the Makefile](http://pastebin.com/jLmQs33r). [Updated slightly to reflect the help from MadScientist]. **Later update** The following Makefile (just make, not autotools) works fine, so the issue seems to be related to autotools and check support. all: check_foo CFLAGS=-I../../clib/src LDFLAGS=-L../../clib/src/.libs check_foo: check_foo.c foo.h corm_foo.h corm_foo.c gcc $(CFLAGS) $(LDFLAGS) $^ -o $@ -lcorm -lsqlite3 corm_%.h corm_%.c: %.h PYTHONPATH=../../cgen/src python ../../cgen/src/isti/cgen/run.py $< clean: rm -f corm_*.h corm_*.c rm -f *.o (Note that I've switched from xxx.hdb to corm_xxx.h, etc, so that file extensions remain OK). **More Details** Since it seems to be related to the CHECK macros, this is configure.ac: AC_INIT([corm], [0.1], [[email protected]]) AC_CONFIG_MACRO_DIR([m4]) PKG_CHECK_MODULES([CHECK], [check >= 0.9.4]) AM_INIT_AUTOMAKE([-Wall foreign -Werror]) AC_PROG_CC_C99 AM_PROG_CC_C_O LT_INIT AC_CONFIG_HEADERS([config.h]) AC_CONFIG_FILES([Makefile clib/Makefile clib/src/Makefile clib/tests/Makefile clib/docs/Makefile cgen/Makefile cgen/docs/Makefile example/Makefile example/src/Makefile]) AC_CHECK_PROGS([DOXYGEN], [doxygen], AC_MSG_WARN([Doxygen not found - continuing without Doxygen support])) AM_CONDITIONAL([HAVE_DOXYGEN], [test -n "$DOXYGEN"]) AM_COND_IF([HAVE_DOXYGEN], [AC_CONFIG_FILES([clib/docs/Doxyfile cgen/docs/Doxyfile])]) **SOLUTION** OK, so summarizing the various things below, there were two important issues (once I had fixed file extensions - see the "plain" makefile and fceller's answer), either one of which was sufficient to make things work: 1. (The handling of) Header files is complicated. Because of auto-dependencies, programatically generated header files break things. The solution is to use [BUILT_SOURCES](http://www.gnu.org/software/automake/manual/html_node/Sources.html) 2. But (the handling of) .c files is not complicated. So putting the corm_foo.c in front of check_foo.c would trigger the generation of that file. Since that also generates corm_foo.h, everything works (because check_foo.c now can include corm_foo.h). Also, fceller has some good general points about tidy makefiles and explains why the "plain" makefile works. Answer: The line %.cdb: %.hdb does not do anything. Check the GNU make manual and you'll see that a pattern rule without a command line is used to DELETE a previously defined rule with that same pattern. Since there's no previous rule, this is essentially a no- op. If you have a command that creates TWO output files with ONE invocation of a rule, then you need to put both patterns in the same rule, like this: %.cdb %.hdb: %.h PYTHONPATH=$(top_builddir)/cgen/src python $(top_builddir)/cgen/src/isti/cgen/run.py $< This will tell GNU make that both targets are generated from one invocation of the rule. BE AWARE! This syntax only has this behavior for pattern rules. Explicit rules with multiple targets do something entirely different (confusingly enough). As for the `make clean` behavior, I'm not sure. The makefile generated by automake is too complex for me to just read it; it would require some debugging (run it and trace what happens). However, I suspect that the rules there are not designed properly to allow a `clean` target and a build target to both be run in the same invocation of make. Run the two commands separately and see if that works better: make clean make check
Equals not being equals Question: Can't get python quiz program to work, when the 'useranswer' is 'correctanswer' if loop doesn't work properly and states they aren't equal even when they are. I'm wondering if this is a problem with comparing strings saved in lists, but I am really stuck for what to do to fix it. Any help would be much appreciated. Thank you import sys print ("Game started") questions = ["What does RAD stand for?", "Why is RAD faster than other development methods?", "Name one of the 3 requirements for a user friendly system", "What is an efficient design?", "What is the definition of a validation method?"] answers = ["A - Random Applications Development, B - Recently Available Diskspace, C - Rapid Applications Development", "A - Prototyping is faster than creating a finished product, B - Through the use of CASE tools, C - As end user evaluates before the dev team", "A - Efficient design, B - Intonated design, C - Aesthetic design", "A - One which makes best use of available facilities, B - One which allows the user to input data accurately, C - One which the end user is comfortable with", "A - A rejection of data which occurs because input breaks predetermined criteria, B - A double entry of data to ensure it is accurate, C - An adaption to cope with a change external to the system"] correctanswers = ["C", "B", "A", "A", "A"] score = 0 lives = 4 z = 0 for i in range(len(questions)): if lives > 0: print (questions[z]) print (answers[z]) useranswer = (input("Please enter the correct answer's letter here: ")) correctanswer = correctanswers[z] if (useranswer) is (correctanswer): //line im guessing the problem occurs on print("Correct, well done!") score = score + 1 else: print("Incorrect, sorry. The correct answer was; " + correctanswer) lives = lives - 1 print("You have, " + str(lives) + " lives remaining") z = z + 1 else: print("End of game, no lives remaining") sys.exit() print("Well done, you scored" + int(score) + "//" + int(len(questions))) Answer: You should use `==` for comparison: if useranswer == correctanswer: `is` operator does _identity comparison_. And `==`, `>`, operators do _value comparison_ , and that is what you need. * * * For two objects, `obj1` and `obj2`: obj1 is obj2 iff id(obj1) == id(obj2) # iff means `if and only if`.
Searching a file with the contents of another file python Question: I have a file that has a unique ID number on each line. I am trying to search a different file for the occurrences of these ID numbers and return the line where these id numbers are in the second file, in this case into an output file. I am new to programming and this is what I have so far. outlist = [] with open('readID.txt', 'r') as readID, \ open('GOlines.txt', 'w') as output, \ open('GO.txt', 'r') as GO: x = readID.readlines() print x for line in GO: if x[1:-1] in line: outlist.append(line) outlist.append('\n') if x[1:-1] in line: outlist.append(line) outlist.append('\n') print outlist output.writelines(outlist) The files look like this: readID.txt 00073810.1 00082422.1 00018647.1 00063072.1 GO.txt #query GO reference DB reference family HumanDistalGut_READ_00048904.2 GO:0006412 TIGRFAM TIGR00001 HumanDistalGut_READ_00043244.3 GO:0022625 TIGRFAM TIGR00001 HumanDistalGut_READ_00048644.4 GO:0000315 TIGRFAM TIGR00001 HumanDistalGut_READ_00067264.5 GO:0003735 TIGRFAM TIGR00001 The read ids match up with some but not all of the ids after _READ_... Answer: #!/usr/bin/env python # encoding: utf-8 import sys import re def extract_id(line): """ input: HumanDistalGut_READ_00048904.2 GO:0006412 TIGRFAM TIGR00001 returns: 00048904.2 """ result = re.search(r'READ_(\d{8}\.\d)', line) if result != None: return result.group(1) else: return None def extract_go_num(line): """ input: HumanDistalGut_READ_00048904.2 GO:0006412 TIGRFAM TIGR00001 returns: 0006412 """ result = re.search(r'GO:(\d{7})', line) if result != None: return result.group(1) else: return None def main(argv = None): if argv is None: argv = sys.argv with open('readID.txt', 'r') as f: ids = frozenset(f.readlines()) with open('GO.txt', 'r') as haystack, \ open('GOLines.txt', 'w') as output: for line in haystack: if extract_id(line) in ids: output.write(extract_go_num(line) + '\n') if __name__ == "__main__": sys.exit(main()) I'm trading memory overhead for an O(n) solution rather than O(n^2). I'm using regular expressions to extract the ids and go numbers, but it's brittle if the number of digits change.
Python: two questions about a "numpy.ndarray" Question: I created a numpy.ndarray with value import numpy as np from numpy import nonzero data = np.zeros((5, 5)) data array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) i wish to change some values with 1 data[0,0] = 1 data[4,4] = 1 data array([[ 1., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1.]]) if i change 0 with 5 using negative values i have data[-5,-5] = 5 data[-4,-4] = 5 >>> data array([[ 5., 0., 0., 0., 0.], [ 0., 5., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) 1- I don't understand why i have not an error message as >>> data[10,10] = 5 Traceback (most recent call last): File "<interactive input>", line 1, in <module> IndexError: index (10) out of range (0<=index<5) in dimension 0 2- it's not clear why with data[-5,-5] = 5 and data[-4,-4] = 5 the value 5 is inserted in position 0,0 and 1,1 Answer: From [the documentation](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic- slicing): > Negative indices are interpreted as counting from the end of the array This is the standard Python indexing behavior (used in Python lists, etc.).
How to disable Google App Engine python SDK import hook? Question: I am playing around with local deployment of GAE python SDK. The code that I am trying to run contains many external libraries which are not part of GAE import whitelist. I want to disable the import restrictions and let GAE app import any locally installed module. After walking through the code, I figured out that they use custom **import hooks** for restricting imports. However, I have not been able to figure out how to disable the overridden import hook. Let me know if you have any idea how this can be accomplished. Answer: Easiest thing is to modify google/appengine/tools/dev_appserver_import_hook.py and add the module you want to the whitelist. This will allow you to import whatever you want. Now there's a good reason that the imports are restricted in the development server. The restricted imports match what's available on the production environment. So if you add libraries to the whitelist, your code may run on your local development server, but it will not run on the production environment. And no, you can't import restricted modules on production.
Python: copying a repeating dictionary into a list - last dict item being duped to all list items Question: Considering the following: import re sequence = 'FFFFFF{7}FFFFFF' patterns = [ ('([0-9a-fA-F]+)', 'Sequence'), ('(\\([0-9a-fA-F]+\\|[0-9a-fA-F]+\\))', 'Option'), ('({[0-9a-fA-F]+})', 'Range'), ('(\\[[0-9a-fA-F]+:([0-9a-fA-F]+|\*)\\])', 'Slice'), ('(\\?\\?)+', 'Byte_value_Wildcard'), ('(\\*)+', 'Byte_length_wildcard') ] fragment_counter = 0 fragment_dict= {} fragments_list = [] while sequence: found = False for pattern, name in patterns: m = re.match (pattern,sequence) if m: fragment_counter+=1 m = m.groups () [0] fragment_dict["index"]=fragment_counter fragment_dict["fragment_type"]=name fragment_dict["value"]=m print fragment_dict fragments_list.append(fragment_dict) sequence = sequence [len (m):] found = True break if not found: raise Exception ('Unrecognized sequence') print fragments_list Each time it hits the "print fragment_dict"line, I get the correct (expected) output: {'index': 1, 'fragment_type': 'Sequence', 'value': 'FFFFFF'} {'index': 2, 'fragment_type': 'Range', 'value': '{7}'} {'index': 3, 'fragment_type': 'Sequence', 'value': 'FFFFFF'} however, the list item `fragments_list` is 3 copies of the final dict, not each of the lines as I expect: [{'index': 3, 'fragment_type': 'Sequence', 'value': 'FFFFFF'}, {'index': 3, 'fragment_type': 'Sequence', 'value': 'FFFFFF'}, {'index': 3, 'fragment_type': 'Sequence', 'value': 'FFFFFF'}] I am assuming this is because the `append` is referencing the instance of the dict, not copying each iteration of the dict. I looked at using the `list()` function, but on the dict item it just gives me a list of the dict keys. What am I doing wrong? I'm not wedded to data type, I just needed a way to hold 3 data elements (and maybe a 4th) for each fragment I find. Answer: You're very close. Instead of the `list()` function, which generates a new `list` from any sequence (in this case, a `dict` as a sequence is a sequence of its keys), use the `dict()` function, which generates a new `dict` from any mapping. Or, maybe more simply, just use the `copy` method. Or, even more simply, just move the `fragment_dict= {}` into the loop, so you build up a new `dict` instead of continuing to reuse the same one.
Convert unicode string dictionary into dictionary in python Question: I have unicode `u"{'code1':1,'code2':1}"` and I want it in dictionary format. I want it in `{'code1':1,'code2':1}` format. I tried `unicodedata.normalize('NFKD', my_data).encode('ascii','ignore')` but it returns string not dictionary. Can anyone help me? Answer: You can use built-in `ast` package: import ast d = ast.literal_eval("{'code1':1,'code2':1}") Help on function literal_eval in module ast: > literal_eval(node_or_string) > > Safely evaluate an expression node or a string containing a Python > expression. The string or node provided may only consist of the following > Python literal structures: strings, numbers, tuples, lists, dicts, booleans, > and None.
methods inheritance in python Question: class Field(object): def __init__(self): self.drunks = {} def addDrunk(self, drunk, loc): if drunk in self.drunks: raise ValueError('Duplicate drunk') else: self.drunks[drunk] = loc def moveDrunk(self, drunk): if not drunk in self.drunks: raise ValueError('Drunk not in field') xDist, yDist = drunk.takeStep() currentLocation = self.drunks[drunk] #use move method of Location to get new location self.drunks[drunk] = currentLocation.move(xDist, yDist) def getLoc(self, drunk): if not drunk in self.drunks: raise ValueError('Drunk not in field') return self.drunks[drunk] import random def walk(f, d, numSteps): start = f.getLoc(d) for s in range(numSteps): f.moveDrunk(d) return(start.distFrom(f.getLoc(d))) i'm learning python.I saw this code and i couldn't understand why the walk function can use the moveDrunk() method? shouldn't raise an error because moveDrunk() is from Field class? Answer: You pass an instance of the `Field` class (`f`) as an argument: def walk(f, d, numSteps): ^
FastCGI Dynamic Server Config. for Django/Apache Question: I'm trying to run Django 1.4 with Pyton 2.7, Flup and mod_fastcgi on Apache. So what I did was: 1. Add mod_fastcgi to httpd.conf 2. Create two files : .htaccess and index.fcgi in my public web root inside a directory called portal - `c:\xampp\htdocs\portal` \- the actual Django project is in `d:\projects\portal` so inside index.fcgi I have the following: #!C:/Python27/python.exe import sys, os from django.core.servers.fastcgi import runfastcgi sys.path.append("D:/projects/portal") os.environ['DJANGO_SETTINGS_MODULE'] = "portal.settings" runfastcgi(method="threaded", daemonize="false") But when running `localhost/portal/` I get the following error in my Apache error.log File "C:\Python27\lib\site-packages\flup\server\fcgi_base.py", line 1020, in _setupSocket 'If you want FCGI, please create an external FCGI server ' It's telling me to create an external FCGI server which I could but I need it to be on a dynamic server. Any ideas? **Update:** My setup is on a Windows server. I can also start a Linux server so the question is more of Apache, FastCGI and adding sites witout changing any config on the server - Apache/FastCGI Server Answer: You did not [start your fcgi server](https://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#starting- your-fastcgi-server).
Developing behave steps with PyDev Question: [Behave](http://pythonhosted.org/behave/) is a great tool for behavior driven development in Python. However, in combination with PyDev I've got two Problems: 1. PyDev can't resolve behave's `@given`, `@when` and `@then` annotations. This probably happens because behave does some name magic the `behave` package. 2. behave suggests to name all methods `step` as every method has an annotation which defines the "real" name. PyDev complains about these "duplicate" methods. Example: from behave import given, when, then @given('I navigate to Google') def step(context): # ... @when('I enter coffee into the search field') def step(context): # ... By now, I work around both Problems by including `#@PydevCodeAnalysisIgnore`, which turns off any PyDev analysis. I'd like to keep PyDev analysis for all other parts of the code. Any suggestions how to solve this? Answer: 1. Just a guess. Have You tried with import redefinitions? from behave import given as given_behaviour, when as when_behaviour, then as then_behaviour @given_behaviour('I navigate to Google') You can also check the eclipse settings: menu Window -> Preferences -> PyDev -> Interpreters -> Python Interpreters. Sometimes it might help to remove and re-add the python interpreter if new libraries has been added after that the interpreter was configured in order to include those in the System `PYTHONPATH` in eclipse. 2. Try adding `#@` followed by the message in camel case to the end of the method name to turn off the warning message in PyDev. Something like: def step(context): #@DuplicatedSignature
Using sockets with wxpython Question: I have a TCP server and a TCP client. I want to make a GUI version of the code below, using [wxpython](/questions/tagged/wxpython "show questions tagged 'wxpython'"). I have the GUI interface script ready, but, I am having problems merging the two scripts. How do I merge my socket script(s) and my GUI? **My socket server** from socket import * from time import ctime import random bufsiz = 1024 port = random.randint(1025,36000) host = 'localhost' addr = (host, port) print 'Port:',port tcpServer = socket(AF_INET , SOCK_STREAM) tcpServer.bind(addr) tcpServer.listen(5) try: while True: print 'Waiting for connection..' tcpClient, caddr = tcpServer.accept() print 'Connected To',caddr while True: data = tcpClient.recv(bufsiz) if not data: break tcpClient.send('[%s]\nData\n%s' % (ctime(),data)) print data tcpClient.close() except KeyboardInterrupt: tcpServer.close() raw_input('Enter to Quit') **My GUI script** (made using wxglade) #!/usr/bin/env python # -*- coding: iso-8859-15 -*- # generated by wxGlade 0.6.5 (standalone edition) on Mon Feb 18 19:50:59 2013 import wx # begin wxGlade: extracode # end wxGlade class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.chat_log = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY) self.text_send = wx.TextCtrl(self, -1, "") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_TEXT_ENTER, self.text_e, self.text_send) # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("frame_1") self.SetSize((653, 467)) self.chat_log.SetMinSize((635, 400)) self.text_send.SetMinSize((635, -1)) self.text_send.SetFocus() # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.FlexGridSizer(1, 1, 1, 1) sizer_1.Add(self.chat_log, 0, 0, 0) sizer_1.Add(self.text_send, 0, wx.ALL, 1) self.SetSizer(sizer_1) self.Layout() # end wxGlade def text_e(self, event): # wxGlade: MyFrame.<event_handler> text = self.text_send.GetValue() self.chat_log.AppendText("\n"+text) self.text_send.SetValue("") event.Skip() # end of class MyFrame class MyMenuBar(wx.MenuBar): def __init__(self, *args, **kwds): # begin wxGlade: MyMenuBar.__init__ wx.MenuBar.__init__(self, *args, **kwds) self.File = wx.Menu() self.Append(self.File, "File") self.View = wx.Menu() self.Append(self.View, "View") self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyMenuBar.__set_properties pass # end wxGlade def __do_layout(self): # begin wxGlade: MyMenuBar.__do_layout pass # end wxGlade # end of class MyMenuBar if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() Answer: In a nutshell: Encapsulate your first script into a function. Import your function into the wxPython app. Call the function from some event handler. Communicate back your function response to the GUI. However, you would need to redesign your software so it does not contain infinite loop. Event handlers should run for short time only. Another way would be to run your function in a separate thread, communicate the response with GUI and add ability to terminate the thread from your main GUI thread. Something along these lines: import wx from socket import * from time import ctime import random import threading bufsiz = 1024 port = random.randint(1025,36000) host = 'localhost' addr = (host, port) class MainWindow(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.panel = wx.Panel(self) self.text = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE) self.sizer = wx.BoxSizer() self.sizer.Add(self.text, 1, wx.ALL | wx.EXPAND, 5) self.panel.SetSizerAndFit(self.sizer) self.Show() self.thread = threading.Thread(target=self.Server) self.thread.start() def Print(self, text): wx.CallAfter(self.text.AppendText, text + "\n") def Server(self): self.Print("Port: {}".format(port)) tcpServer = socket(AF_INET , SOCK_STREAM) tcpServer.bind(addr) tcpServer.listen(5) try: while True: self.Print("Waiting for connection...") tcpClient, caddr = tcpServer.accept() self.Print("Connected To {}".format(caddr)) while True: data = tcpClient.recv(bufsiz) if not data: break tcpClient.send('[%s]\nData\n%s' % (ctime(), data)) self.Print(data) tcpClient.close() except KeyboardInterrupt: tcpServer.close() app = wx.App(False) win = MainWindow(None) app.MainLoop() This however does not terminate another thread upon exit. `tcpServer.accept()` is blocking operation. You may want to look into this [answer](http://stackoverflow.com/questions/5308080/python-socket-accept- nonblocking) how to connect to socket in a non-blocking way. Then you would be able to easily terminate your thread using some kins of shared flag.
How can I read /etc/config.d/... with python? Question: I want distros to pick up my python app so they can make a /etc/myapp config file and a /etc/myapp.d/ folder, where users can put their configs over overwrite settings in /etc/myapp. It should support the following (more or less standard) configuration style. # settingx does ... settingx=1 settingy = 0 settingz = "--this x --that y" And in my python app I want to use settingx, settingy etc. What's the best way to do it? Answer: Use [`ConfigParser`](http://docs.python.org/2/library/configparser.html) as this is an accepted settings exchange format that is baked into the python distribution. import ConfigParser config = ConfigParser.RawConfigParser() config.add_section('myapp') config.set('myapp', 'settingx', 1) config.set('myapp', 'settingy ', 0) config.set('myapp', 'settingz ', '--this x --that y') # Writing our configuration file to 'example.cfg' with open('/etc/myapp/example.cfg', 'wb') as configfile: config.write(configfile)
Python While Loop CPU demanding Question: I don't want to bother people here with a simple question and also tell that I googled for information but I would like to get input from the people who as faced the same. It is stated that while loops in python slow down (<http://wiki.python.org/moin/WhileLoop>). I have a script which employs only one loop but that is quite important and in fact it really slows down. My first program was using 100 % CPU (Dual core!!!). I introduced a sleep() function on the loop and the CPU usage went down to 50 %. I cannot just keep increasing the sleep time, actually I would like to decrease it. Anyway, is there any 'trick' to make this while loop faster? (The condition is whether a button is pressed or not on a user interface build on pyQt4) Answer: The reference you linked to is misleading. The speed difference between the two samples will be minimal and usually not even noticeable if any real work is being done inside the loop. It is the nature of _any_ loop that it will use 100% of its allocated time until it's done. It doesn't matter if the loop is wickedly efficient or wildly inefficient. The only way around this is to call some OS function that makes it wait, such as the `sleep` that you tried. The reason that modern OS GUI's are event driven is so that you don't have to wait in a loop for an event - you call a single function to wait for a message, and the OS gives the CPU to someone else until a message arrives. With a framework such as Qt this will be buried in what's called a message loop, and you'll need to provide the proper framework hooks to get the event routed to your own function.
Is there a Python equivalent to HighLine? Question: [HighLine](http://highline.rubyforge.org) is a Ruby library for easing console input and output. It provides methods that lets you request input and validate it. Is there something that provides functionality similar to it in Python? To show what HighLine does see the following example: require 'highline/import' input = ask("Yes or no? ") do |q| q.responses[:not_valid] = "Answer y or n for yes or no" q.default = 'y' q.validate = /\A[yn]\Z/i end It asks "Yes or no? " and lets the user input something. As long as the user does not input y or n (case-insensitive) it prints "Answer y or n for yes or no" and lets the user type an answer again. Also if the user press Enter it defaults to y. Finally, when it is done the input is stored in `input`. Here is an example result where the user first input "EH???" and then "y": Yes or no? |y| EH??? Answer y or n for yes or no ? y Is there similarly simple way to do the same in Python? Answer: The following _should_ work similarly for you, although it will not be exactly the same style of asking as it is in Ruby. class ValidInput(object): def __init__(self,prompt,default="",regex_validate="", invalid_response="",correct_response=""): self.prompt=prompt self.default=default self.regex_validate=regex_validate self.invalid_response=invalid_response self.correct_response=correct_response def ask(self): fin="" while True: v_in=raw_input(self.prompt) if re.match(v_in,self.regex_validate): fin=v_in print self.correct_response break else: print self.invalid_response if self.default=="break": break continue return fin And you would use it like: my_input=ValidInput("My prompt (Y/N): ",regex_validate="your regex matching string here", invalid_response="The response to be printed when it does not match the regex", correct_response="The response to be printed when it is matched to the regex.") my_input.ask()
Mayavi: interpolate face colors in triangular_mesh Question: I have pieced together the following code to plot a triangular mesh with the colors specified by an additional scalar function: #! /usr/bin/env python import numpy as np from mayavi import mlab # Create cone n = 8 t = np.linspace(-np.pi, np.pi, n) z = np.exp(1j*t) x = z.real.copy() y = z.imag.copy() z = np.zeros_like(x) triangles = [(0, i, i+1) for i in range(n)] x = np.r_[0, x] y = np.r_[0, y] z = np.r_[1, z] t = np.r_[0, t] # These are the scalar values for each triangle f = np.mean(t[np.array(triangles)], axis=1) # Plot it mesh = mlab.triangular_mesh(x, y, z, triangles, representation='wireframe', opacity=0) cell_data = mesh.mlab_source.dataset.cell_data cell_data.scalars = f cell_data.scalars.name = 'Cell data' cell_data.update() mesh2 = mlab.pipeline.set_active_attribute(mesh, cell_scalars='Cell data') mlab.pipeline.surface(mesh2) mlab.show() This works reasonably well. However, instead of having every triangle with a uniform color and sharp transitions between the triangles, I'd much rather have a smooth interpolation over the entire surface. Is there a way to do that? Answer: I think you want to use point data instead of cell data. With cell data, a single scalar value is not localized to any point. It is assigned to the entire face. It looks like you just want to assign the `t` data to the vertices instead. The default rendering of point scalars will smoothly interpolate across each face. point_data = mesh.mlab_source.dataset.point_data point_data.scalars = t point_data.scalars.name = 'Point data' point_data.update() mesh2 = mlab.pipeline.set_active_attribute(mesh, point_scalars='Point data')
Python - make script loop until condition met and use a different proxy address for each loop Question: I'm the definition of a noob. I know next to nothing about python and am looking for help. I can read just enough code to alter variables to suit my wants/needs but I when it comes to doing something the original code didn't call for... I'm lost. So here is the deal, I found a craigslist(CL) flagging script that originally searched ALL CL sites and flagged posts that contained a specific keyword (it was written to flag all posts that mentioned scientology). I altered it to only search CL sites in my general area (15 sites instead of 437) but it still looks for specific keywords that have have changed. I want to automatically flag people that continuously spam CL and make it hard to sort through as I do a lot of business on CL from sorting through postings. What I want the script to do is loop until it can no longer find posts that meet the criteria changing proxy servers after each loop. And a place inside the script where I would put in the proxy/s ip adress I look forward to your replies. Here is the altered code I have: #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib from twill.commands import * # gives us go() areas = ['sfbay', 'chico', 'fresno', 'goldcountry', 'humboldt', 'mendocino', 'modesto', 'monterey', 'redding', 'reno', 'sacramento', 'siskiyou', 'stockton', 'yubasutter', 'reno'] def expunge(url, area): page = urllib.urlopen(url).read() # <-- and v and vv gets you urls of ind. postings page = page[page.index('<hr>'):].split('\n')[0] page = [i[:i.index('">')] for i in page.split('href="')[1:-1] if '<font size="-1">' in i] for u in page: num = u[u.rfind('/')+1:u.index('.html')] # the number of the posting (like 34235235252) spam = 'https://post.craigslist.org/flag?flagCode=15&amppostingID='+num # url for flagging as spam go(spam) # flag it print 'Checking ' + str(len(areas)) + ' areas...' for area in ['http://' + a + '.craigslist.org/' for a in areas]: ujam = area + 'search/?query=james+"916+821+0590"+&catAbb=hhh' udre = area + 'search/?query="DRE+%23+01902542+"&catAbb=hhh' try: jam = urllib.urlopen(ujam).read() dre = urllib.urlopen(udre).read() except: print 'tl;dr error for ' + area if 'Found: ' in jam: print 'Found results for "James 916 821 0590" in ' + area expunge(ujam, area) print 'All "James 916 821 0590" listings marked as spam for area' if 'Found: ' in dre: print 'Found results for "DRE # 01902542" in ' + area expunge(udre, area) print 'All "DRE # 01902542" listings marked as spam for area' Answer: you can create a constant loop like this: while True: if condition : break Itertools has a handful of tricks for iterating <http://docs.python.org/2/library/itertools.html> notably, check out `itertools.cycle` ( these are meant as pointers in the right direction. you could craft a solution with one, the other , or even both )
Japanese Numerals to Arabic Numerals converter in Python Question: Is there an open source library in Python which does Kanji Numeral to Arabic Numeral conversion/translation? Input : 10億2千9百万 Output: 1,029,000,000 Input : 1億6,717万2,600 Output: 167,172,600 Input : 3,139百万 Output: 3,139,000,000 Japanese Numeral Systems : <http://en.wikipedia.org/wiki/Japanese_numerals> Web Based Converter : <http://www.sljfaq.org/cgi/kanjinumbers.cgi> Answer: This should work: import kanjinums kanjinums.kanji2num("五百十一") After downloading and installing [kanjinums](http://ginstrom.com/scribbles/2009/04/28/converting-kanji-numbers- to-integers-with-python/), which is unfortunately not available through pip. **EDIT:** This will only work for basic numbers, not the complex cases like mentioned. With minor modifications this will actually work, for instance: 3139*kanjinums.kanji2num("百万") 3139000000
SQLAlchemy & PassLib Question: _**tl;dr -- How do I use a Python-side library such as PassLib to hash passwords before inserting them into a MySQL DB with SQLAlchemy?_** Alright, so I've been banging my head on my desk for a day or two trying to figure this out, so here it goes: I am writing a web application using Pyramid/SQLAlchemy and I'm trying to interface with my MySQL database's Users table. Ultimately, I want to do something like the following: Compare a password to the hash: if user1.password == 'supersecret' Insert a new password: user2.password = 'supersecret' I'd like to be able to use PassLib to hash my passwords before they go to the database, and I'm not really a fan of using the built-in MySQL SHA2 function since it's not salted. However, just to try it, I do have this working using the SQL-side function: from sqlalchemy import func, TypeDecorator, type_coerce from sqlalchemy.dialects.mysql import CHAR, VARCHAR, INTEGER from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column class SHA2Password(TypeDecorator): """Applies the SHA2 function to incoming passwords.""" impl = CHAR(64) def bind_expression(self, bindvalue): return func.sha2(bindvalue, 256) class comparator_factory(CHAR.comparator_factory): def __eq__(self, other): local_pw = type_coerce(self.expr, CHAR) return local_pw == func.sha2(other, 256) class User(Base): __tablename__ = 'Users' _id = Column('userID', INTEGER(unsigned=True), primary_key=True) username = Column(VARCHAR(length=64)) password = Column(SHA2Password(length=64)) def __init__(self, username, password): self.username = username self.password = password This was copied from the example 2 at <http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DatabaseCrypt> So that works and allows me to use the built-in MySQL SHA2 function (by calling `func.sha2()`) and do exactly what I want. However, now I'm trying to replace this with PassLib on the Python side. PassLib presents two functions: one to create a new password hash, and one to verify a password: from passlib.hash import sha256_crypt new_password = sha256_crypt.encrypt("supersecret") sha256_crypt.verify("supersecret", new_password) I can't quite figure out how to actually implement this. Having read all the documentation, I think it is either a different form of TypeDecorator, a custom type declaration, a hybrid value, or a hybrid property. I tried following [this](http://stackoverflow.com/questions/12212636/sql-alchemy- overriding), but it doesn't really make sense to me nor does the code suggested there actually run. So, to sum up my question -- how do I overload the `=` and `==` operators so that they run things through the appropriate hash functions? Answer: [PasswordType](http://sqlalchemy- utils.readthedocs.org/en/latest/data_types.html#module- sqlalchemy_utils.types.password) from [sqlalchemy- utils](https://github.com/kvesteri/sqlalchemy-utils) should be the best fit for this issue. It uses passlib. Snipped from the docs: > The following usage will create a password column that will automatically > hash new passwords as pbkdf2_sha512 but still compare passwords against pre- > existing md5_crypt hashes. As passwords are compared; the password hash in > the database will be updated to be pbkdf2_sha512. class Model(Base): password = sa.Column(PasswordType( schemes=[ 'pbkdf2_sha512', 'md5_crypt' ], deprecated=['md5_crypt'] )) > Verifying password is as easy as: target = Model() target.password = 'b' # '$5$rounds=80000$H.............' target.password == 'b' # True
python how to keep one thread executing till other threading finished Question: I hope to record app(eg.com.clov4r.android.nil) the CPU occupancy when I operate the app(eg.doing monkey test) and finish recording when I eixt the app(eg.finishing monkey test). How to realise it with python? Some codes: packagename = 'com.clov4r.android.nil' cmd1 = 'adb shell top -d 5 | grep com.clov4r.android.nil' cmd2 = 'adb shell monkey -v -p com.clov4r.android.nil --throttle 500 --ignore-crashes --ignore-timeouts --ignore-security-exceptions --monitor-native-crashes -s 2345 100' t1 = threading.Thread(target=subprocess.call(cmd1, stdout=open(r'123.txt', 'w'))) t2 = threading.Thread(target=subprocess.call(cmd2)) Answer: You can use [Thread.join()](http://docs.python.org/2/library/threading.html#threading.Thread.join) : import threading, time def worker(): time.sleep(5) t = threading.Thread(target=worker) t.start() t.join() print('finished')
Missing text in GUI (PyGObject) Question: I have created a GUI with pyGObject using a xml description file and I'm trying to create a sidebar with `GtkTreeView`. `GtkTreeView` doesn't show _any_ text in the headers and children in my GUI even though I have added some. Why is that? How can I fix it? The sidebar should have shown the following: Parent 1 Child 1 Child 2 Child 3 etc. A short version of my code is shown below. **App.py** #!/usr/bin/env python2 from gi.repository import Gtk class AppUI: def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file("app.xml") self.window = self.builder.get_object("main-window") self.sidebarStore = self.builder.get_object("sidebar-store") for parent in range(4): piter = self.sidebarStore.append(None, ['parent %i' % parent]) for child in range(3): self.sidebarStore.append(piter, ['child %i of parent %i' % (child, parent)]) self.handlers = { "onDeleteWindow": Gtk.main_quit, } self.builder.connect_signals(self.handlers) self.window.show_all() UI = AppUI() Gtk.main() **app.xml: UI description** <?xml version="1.0" encoding="UTF-8"?> <interface> <object class="GtkTreeStore" id="sidebar-store"> <columns> <column type="gchararray"/> </columns> </object> <object class="GtkWindow" id="main-window"> <property name="title"></property> <signal name="delete-event" handler="onDeleteWindow"/> <child> <object class="GtkBox" id="container"> <property name="orientation">horizontal</property> <child> <object class="GtkTreeView" id="sidebar"> <property name="model">sidebar-store</property> <property name="headers-visible">false</property> <child> <object class="GtkTreeViewColumn" id="test-column"> <child> <object class="GtkCellRendererText" id="test-renderer"/> </child> </object> </child> </object> </child> <child> <object class="GtkBox" id="right-container"> <property name="orientation">vertical</property> <child> <object class="GtkButtonBox" id="top-buttonbox"> <child> <object class="GtkButton" id="add-button"> <property name="label">Add</property> </object> </child> <child> <object class="GtkButton" id="delete-button"> <property name="label">Delete</property> </object> </child> </object> </child> </object> </child> </object> </child> </object> </interface> Answer: Quite easy, you didn't mapped any column to the text renderer. BTW, what editor are you using for creating the UI? Are you writting it by hand? Use Glade, life is easier that way. In Glade, right click the TreeView -> Edit -> Hierarchy -> Select Cell Renderer -> Text mapped to the column in the model. Following is the corrected version of the XML edited through Glade. The most relevant part is: <attributes> <attribute name="text">0</attribute> </attributes> When you defined the text cell renderer. <?xml version="1.0" encoding="UTF-8"?> <interface> <!-- interface-requires gtk+ 3.0 --> <object class="GtkTreeStore" id="sidebar-store"> <columns> <!-- column-name gchararray --> <column type="gchararray"/> </columns> </object> <object class="GtkWindow" id="main-window"> <property name="can_focus">False</property> <signal name="delete-event" handler="onDeleteWindow" swapped="no"/> <child> <object class="GtkBox" id="container"> <property name="can_focus">False</property> <child> <object class="GtkTreeView" id="sidebar"> <property name="width_request">100</property> <property name="can_focus">False</property> <property name="model">sidebar-store</property> <property name="headers_visible">False</property> <child internal-child="selection"> <object class="GtkTreeSelection" id="treeview-selection1"/> </child> <child> <object class="GtkTreeViewColumn" id="test-column"> <child> <object class="GtkCellRendererText" id="test-renderer"/> <attributes> <attribute name="text">0</attribute> </attributes> </child> </object> </child> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkBox" id="right-container"> <property name="can_focus">False</property> <property name="orientation">vertical</property> <child> <object class="GtkButtonBox" id="top-buttonbox"> <property name="can_focus">False</property> <child> <object class="GtkButton" id="add-button"> <property name="label">Add</property> <property name="use_action_appearance">False</property> <property name="can_focus">False</property> <property name="receives_default">False</property> <property name="use_action_appearance">False</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkButton" id="delete-button"> <property name="label">Delete</property> <property name="use_action_appearance">False</property> <property name="can_focus">False</property> <property name="receives_default">False</property> <property name="use_action_appearance">False</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> </object> </child> </object> </interface>
Storing an encrypted password to mysql in python Question: import sys import hashlib import getpass from passlib.hash import sha256_crypt import MySQLdb, random, os def SQLAddPass(username, password): SQL = 'insert into user values ("%s", "%s")' % (username, password) try: db = MySQLdb.connect (host='localhost', user='root', db='vedio') c = db.cursor() c.execute(SQL) db.commit() c.close() db.close() raw_input('Record Added - press enter to continue: ') except: print 'There was a problem adding the record' raw_input ('press enter to continue') def main(argv): print '\nUser & Password Storage Program v.01\n' username = raw_input('Please Enter a User Name: ') password = sha256_crypt.encrypt(getpass.getpass('Please Enter a Password: ')) try: SQLAddPass(username, password) except: sys.exit('There was a problem saving Record!') print '\nPassword safely stored in ' + sys.argv[1] + '\n' if __name__ == "__main__": main(sys.argv[1:]) My problem is that the script works but with the following error ** > (C:\Users\Elsie\Desktop\example.py:14: Warning: Data truncated for column > 'passwo rd' at row 1 c.execute(SQL) Record Added - press enter to continue: ** Password safely stored in database. What am i doing wrong any ideas or changes to the code are welcome) Answer: > Data truncated for column 'passwo rd' at row 1 Mean your table has a password column with a length of for example 10 and you are inserting a record of let's say 20. The record you inserted will be truncated. And passwords will be broken. Increase length of column in the table
Python threads, thread is not informed to stop Question: I would like to stop a Python thread when the main program stops. It is for a class that connects to a server. The connection is maintained by the background thread, the foreground thread answers to callbacks. The following is a minimal example. #!/usr/bin/python import time, threading class test(): running = False def __init__(self): print "init" self.running = True self.thread = threading.Thread(target = self.startThread) self.thread.start() def __del__(self): running = False print "del" def startThread(self): print "thread start" while self.running: time.sleep(1) print "thread running" a = test() When the program ends, I would naively expect __del__() to be called so that the background thread can be informed to stop, but i is not called untill after the background thread stops. Explicitly calling some function is not an option since the class is used by other people, whom I do not want to force to use some extra lines of code. Answer: `__del__` is not called as long as there are references to `self`, and you have one such reference in the background thread itself: in the `self` argument of `def startThread(self):`. You need to move the function that runs the background thread outside of the class. And rather than a `__del__` I would recommend for example using a weakref, as follows. This code should work without the `__del__()` method and without using a `self.running` attribute. self.thread = threading.Thread(target=run_me, args=(weakref.ref(self),)) ... def run_me(weak_self): "Global function" while True: self = weak_self() if self is None: break # no more reference to self ... del self # forget this reference for now time.sleep(1)
How to dynamically replace contents of HTML tags with Python on Google App Engine with lxml? Question: I am using Google app engine and python to build an application. I am incredibly new to python as well as GAE. I have a index.html file with the basic template for my site. However I would like to replace the contents of a few tags depending on the URL. For example update the title tag for each individual pages. From what I can tell the recommended way to do this is using the lxml library. And so... Tonight is my first time I have ever worked with lxml and I am having a really hard time wrapping my head around it. I have been fooling around with several permutations of the basic syntax and have not had much success understanding how it works. I have looked for different tutorials and the documentation is few and far between. When I try the following code I get a 'lxml.etree._ElementTree' object has no attribute 'find_class' error, however the documentation here: <http://lxml.de/lxmlhtml.html#parsing-html> it sure looks like it should have that class Am I on the right path? Is this the most efficient/best way to replace the content of html tags? import os import webapp2 import lxml.html doc = lxml.html.parse('index.html') doc.find_class("title") == 'About Page' self.response.write(lxml.html.tostring(doc)) Answer: This is definitely not the way to that on Google App Engine. You should use some kind of template framework like Jinja2 or Django to achieve your goal. But before all that you will have to make sure that you completed the [Getting Started Tutorial](https://developers.google.com/appengine/docs/python/gettingstartedpython27/), where you can see these things in action.
Installing Setuptools with root - Getting a PythonPath error Question: I already did the virtual python enviroment. When I'm trying to install setuptools I get the following: python setup.py install --prefix=/home/dgomez/ Error: TEST FAILED: /home/dgomez//lib/python2.7/site-packages/ does NOT support .pth files error: bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /home/dgomez//lib/python2.7/site-packages/ and your PYTHONPATH environment variable currently contains: '' When I check the system path, I received the following output: >>> import sys >>> import sys /usr/lib/python27.zip /usr/lib64/python2.7 /usr/lib64/python2.7/plat-linux2 /usr/lib64/python2.7/lib-tk /usr/lib64/python2.7/lib-old /usr/lib64/python2.7/lib-dynload /usr/lib64/python2.7/site-packages /usr/local/lib64/python2.7/site-packages /usr/local/lib/python2.7/site-packages /usr/lib64/python2.7/site-packages/gst-0.10 /usr/lib64/python2.7/site-packages/gtk-2.0 /usr/lib/python2.7/site-packages How can I fix this issue? ### UPDATE I fix this issue by edit the .bashrc and I add the following line: PYTHONPATH="${PYTHONPATH}:/home/dgomez/lib/python2.7/site-packages/" export PYTHONPATH Answer: Try putting /home/dgomez/lib/python2.7/site-packages in your PYTHONPATH environment variable.
pymongo operation error Question: I am getting a lot of records from my MongoDB and along the way I get an error File "C:\database\models\mongodb.py", line 228, in __iter__ for result in self.results: File "C:\Python27\Lib\site-packages\pymongo\cursor.py", line 814, in next if len(self.__data) or self._refresh(): File "C:\Python27\Lib\site-packages\pymongo\cursor.py", line 776, in _refresh limit, self.__id)) File "C:\Python27\Lib\site-packages\pymongo\cursor.py", line 720, in __send_message self.__uuid_subtype) File "C:\Python27\Lib\site-packages\pymongo\helpers.py", line 99, in _unpack_response cursor_id) pymongo.errors.OperationFailure: cursor id '866472135294727793' not valid at server Exception KeyError: KeyError(38556896,) in <module 'threading' from 'C:\Python27\lib\threading.pyc'> ignored What does this mean and how do I fix it. I don't know if it matters but I did use `from gevent import monkey; monkey.patch_all()` when I opened the connection Answer: When the cursor has been open for a long time with no operations on it, it(the cursor) can timeout -> this leads to the error you can set timeout=False in your find query to turn the timeout off [reference](http://api.mongodb.org/python/current/faq.html#what-does- operationfailure-cursor-id-not-valid-at-server-mean)
python: change sys.stdout print to custom print function Question: Im trying to understand how to create a custom print function. (using python 2.7) import sys class CustomPrint(): def __init__(self): self.old_stdout=sys.stdout #save stdout def write(self, text): sys.stdout = self.old_stdout #restore normal stdout and print print 'custom Print--->' + text sys.stdout= self # make stdout use CustomPrint on next 'print' # this is the line that trigers the problem # how to avoid this?? myPrint = CustomPrint() sys.stdout = myPrint print 'why you make 2 lines??...' The code above prints this to console: >>> custom Print--->why you make 2 lines??... custom Print---> >>> and i want to print only one line: >>> 1custom Print--->why you make 2 lines??... >>> But cant figure out how to make this custom print work , i understand that there's some kind of recursion that triggers the second output to the console (i use self.write , to assign stdout to self.write himself !) how can i make this work ? or is my approach just completely wrong... Answer: One solution may be to use a context manager if it's localised. #!/usr/bin/env python from contextlib import contextmanager ################################################################################ @contextmanager def no_stdout(): import sys old_stdout = sys.stdout class CustomPrint(): def __init__(self, stdout): self.old_stdout = stdout def write(self, text): if len(text.rstrip()): self.old_stdout.write('custom Print--->'+ text) sys.stdout = CustomPrint(old_stdout) try: yield finally: sys.stdout = old_stdout ################################################################################ print "BEFORE" with no_stdout(): print "WHY HELLO!\n" print "DING DONG!\n" print "AFTER" The above produces: BEFORE custom Print--->WHY HELLO! custom Print--->DING DONG! AFTER The code would need tidying up esp. around what the class should do WRT setting stdout back to what it was.
How to stop Python from checking for files upon execution Question: I've got a script I've put together that generates a number of files full of json data by calling another python module. I then want to be able to import those after they are generated and do things with the data they contain. The problem is, when I try to run this script, it complains about the files not existing. I guess because Python checks for all files to be opened before executing the code, regardless of where the open statements fall within the code. Is there a way around this, so it won't try to open the files until after the generator has called the module to create them? Example code below: #!/usr/bin/python import os, sys import json import random import ships_levels_stats_generator def main(): number = 10 ships_levels_stats_generator.interface(str(number)) for i in range(0, number): with open('../Test/attack%s.json' % i) as attack_json: attack_data = json.load(attack_json) with open('../Test/hp%s.json' % i) as hp_json: hp_data = json.load(hp_json) with open('../Test/repair%s.json' % i) as repair_json: repair_data = json.load(repair_json) for key in attack_data.iterkeys(): if len(attack_data[key]) < 20: print "Under 20." elif len(attack_data[key]) < 30: print "Under 30." elif len(attack_data[key]) < 60: print "Under 50." elif len(attack_data[key]) < 80: print "Under 80." else: print "Over 80." Answer: It's just an indentation issue: the for loop needs to be indented to be part of your main function. As it is now, it runs when the file is loaded each time.
Django, TemplateDoesNotExist error: Heroku can't find template directory. How to show it where to look? Question: I've done much clicking and syncdb'ing and have yet to find a solution. I get this error: TemplateDoesNotExist at /quotes/ quotes/index.html Request Method: GET Request URL: http://quoteboard94.herokuapp.com/quotes/ Django Version: 1.4.4 Exception Type: TemplateDoesNotExist Exception Value: quotes/index.html Exception Location: /app/.heroku/python/lib/python2.7/site-packages/django/template/loader.py in find_template, line 138 Python Executable: /app/.heroku/python/bin/python Python Version: 2.7.3 Python Path: ['/app', '/app/.heroku/python/lib/python2.7/site-packages/pip-1.1-py2.7.egg', '/app', '/app/.heroku/python/lib/python27.zip', '/app/.heroku/python/lib/python2.7', '/app/.heroku/python/lib/python2.7/plat-linux2', '/app/.heroku/python/lib/python2.7/lib-tk', '/app/.heroku/python/lib/python2.7/lib-old', '/app/.heroku/python/lib/python2.7/lib-dynload', '/app/.heroku/python/lib/python2.7/site-packages', '/app/.heroku/python/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info'] My settings have this: PROJECT_DIR = os.path.dirname(__file__) #for heroku TEMPLATE_DIRS = ( os.path.join(PROJECT_DIR, '/templates/'), # for heroku '/Users/jacksongonzales/projects/QuoteBoard/templates/', ) `import os.path` is up top as well. That path under TEMPLATE_DIRS is the absolute path to my templates. Am I not punching in the right stuff for PROJECT_DIR and TEMPLATE_DIRS variables? Answer: Here is my set up for a heroku project. # here() gives us file paths from the root of the system to the directory # holding the current file. here = lambda * x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x) PROJECT_ROOT = here("..") # root() gives us file paths from the root of the system to whatever # folder(s) we pass it starting at the parent directory of the current file. root = lambda * x: os.path.join(os.path.abspath(PROJECT_ROOT), *x) .... TEMPLATE_DIRS = ( root('templates'), ) UPDATE: My project has the same local template structure as the one it's deployed with, so I don't need to add a direct path in my templates directory. You have one in yours: '/Users/jacksongonzales/projects/QuoteBoard/templates/', If your first entry in your `TEMPLATE_DIRS` is correct, do you need the second one?
Python/CGI/Ajax: cgi.FieldStorage does not receive arguments Question: I am trying to get a Python, cgi module, ajax/javascript combination to work. Due to the nature of my server access (essentially rented webspace), I cannot install things like django or any other webframework. I am stuck with cgi for now. I am able to call the python file to simply print out something, but once it comes to passing an argument to the python file the cgi.FieldStorage() does not receive any input. When I add a print statement for the FieldStorage, the output is as follows: FieldStorage(None, None, []) You can find all the necessary code below. Essentially, all I am trying to do (for testing purposes) is to get a string from a text input, add a "1" to the end of it and return it. Interestingly, when I use a simple php file that does the exact same thing and use it in the otherwise exact same script, the script works without any issues. Here's a typical php script that I tried: <?php $user = urldecode(implode(file('php://input'))); $adj_user = $user . "1"; echo $adj_user; ?> (Please note that I want to use python, because I am far more comfortable with it and I dislike php quite a bit.) I have the feeling that I am just a little bit dense and it is something very simple. Any help in finding what I am doing wrong is very appreciated. Thanks a lot in advance! P.S. I have scoured stackoverflow and the web quite some time before I posted on here. There are many related topics, but nothing quite as (seemingly) simple as what I am asking. If there is an answered duplicate to this question then I apologise and would be grateful for a link. Thanks again. The traceback is: Traceback (most recent call last): File "/home/www/xxxxx/html/cgi-bin/hello.py", line 14, in &lt;module&gt; adj_user = form['user'] + "1" File "/usr/lib/python2.5/cgi.py", line 567, in __getitem__ raise KeyError, key KeyError: 'user' Here is the "index.html" <!DOCTYPE html> <html> <head> <title>Report</title> <script type='text/javascript' src='test.js'></script> </head> <body> <form method="post" action=""> <p>Please enter your name here: <input type="text" name="user"> <input type="submit" name="submit" value="Submit" onClick="return hello(this.form.user.value);"> </p> </form> </body> </html> This is the "test.js" file: function hello(user) { // Mozilla version if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } // IE version else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } //user=encodeURIComponent(user); xhr.open("POST", "../cgi-bin/hello.py"); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(user); xhr.onreadystatechange=function() { if (xhr.readyState===4) { adj_user = xhr.responseText; alert ("Hello " + adj_user); } } return false; } and lastly "hello.py" in my server's cgi-bin #!/usr/bin/env python # -*- coding: UTF-8 -*- import cgi form = cgi.FieldStorage() # enable debugging import cgitb cgitb.enable() print "Content-Type: text/html;charset=utf-8" print adj_user = form['user'] + "1" print adj_user * * * _EDIT_ I made some progress, but it still isn't what I am hoping for. I changed the following block as follows: xhr.open("GET", "../cgi-bin/hello.py?user=" + user, true); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(); Please note the change from POST to GET and the suffix ' "?user=" + user ', as well as the removal of the 'user' argument in the send() method. Now this does, what I want, but it just shouldn't "be" that way. There must be a way to get this to work the classical way... As usual, any attempt or suggestion is welcome. I really don't know what else to try. Thanks fellas. Answer: The format of `application/x-www-form-urlencoded` data is: key=value&key2=value2 … where the keys and values are URL encoded. You are posting just the value of a field, with no keys. var postData = encodeURIComponent('user') + '=' + encodeURIComponent(user); xhr.send(postData); The reason that the PHP code was working was because you was reading the raw POST data instead of `$_POST['user']` (which is what your Python was equivalent to). You also need to access `form['user'].value` rather than `form['user']`. That will return a `str` so you can't concatenate it with `+ 1` without performing type conversion.
python and statement Question: import random def main(): number = random.randint(0,100) print(number) guess = int(input("Enter your guess: ")) if guess == number : print("You win $10,000!") elif guess // 10 == number // 10 or guess % 10 == number % 10 : print("You win 1,000$!") elif guess // 10 == number // 10 and guess % 10 == number % 10 : print("You win $3,000!") else : print("You win $0.") main() This program works except for the `and` statement. Does anyone know why? Answer: The reason is `or` covers `and`. Use `!=` which gives exclusive or, aka xor. import random def main(): number = random.randint(0,100) print(number) guess = int(input("Enter your guess: ")) if guess == number : print("You win $10,000!") elif (guess // 10 == number // 10) != (guess % 10 == number % 10) : print("You win 1,000$!") elif guess // 10 == number // 10 and guess % 10 == number % 10 : print("You win $3,000!") else : print("You win $0.") main()
How to make a 4d plot with matplotlib using arbitrary data Question: This question is related to this [one](http://stackoverflow.com/questions/7855229/how-to-make-a-4d-plot-using- python-with-matplotlib). What I would like to know is how to apply the suggested solution to a bunch of data (4 columns), e.g.: 0.1 0 0.1 2.0 0.1 0 1.1 -0.498121712998 0.1 0 2.1 -0.49973005075 0.1 0 3.1 -0.499916082038 0.1 0 4.1 -0.499963726586 0.1 1 0.1 -0.0181405895692 0.1 1 1.1 -0.490774988618 0.1 1 2.1 -0.498653742846 0.1 1 3.1 -0.499580747953 0.1 1 4.1 -0.499818696063 0.1 2 0.1 -0.0107079119572 0.1 2 1.1 -0.483641823093 0.1 2 2.1 -0.497582061233 0.1 2 3.1 -0.499245863438 0.1 2 4.1 -0.499673749657 0.1 3 0.1 -0.0075248589089 0.1 3 1.1 -0.476713038166 0.1 3 2.1 -0.49651497615 0.1 3 3.1 -0.498911427589 0.1 3 4.1 -0.499528887295 0.1 4 0.1 -0.00579180003048 0.1 4 1.1 -0.469979974092 0.1 4 2.1 -0.495452458086 0.1 4 3.1 -0.498577439505 0.1 4 4.1 -0.499384108904 1.1 0 0.1 302.0 1.1 0 1.1 -0.272727272727 1.1 0 2.1 -0.467336140806 1.1 0 3.1 -0.489845926622 1.1 0 4.1 -0.495610916847 1.1 1 0.1 -0.000154915998165 1.1 1 1.1 -0.148803329865 1.1 1 2.1 -0.375881358454 1.1 1 3.1 -0.453749548548 1.1 1 4.1 -0.478942841849 1.1 2 0.1 -9.03765566114e-05 1.1 2 1.1 -0.0972702806613 1.1 2 2.1 -0.314291859842 1.1 2 3.1 -0.422606253083 1.1 2 4.1 -0.463359353084 1.1 3 0.1 -6.31234088628e-05 1.1 3 1.1 -0.0720095219203 1.1 3 2.1 -0.270015786897 1.1 3 3.1 -0.395462300716 1.1 3 4.1 -0.44875793248 1.1 4 0.1 -4.84199181874e-05 1.1 4 1.1 -0.0571187054704 1.1 4 2.1 -0.236660992042 1.1 4 3.1 -0.371593983211 1.1 4 4.1 -0.4350485869 2.1 0 0.1 1102.0 2.1 0 1.1 0.328324567994 2.1 0 2.1 -0.380952380952 2.1 0 3.1 -0.462992178846 2.1 0 4.1 -0.48400342421 2.1 1 0.1 -4.25137933034e-05 2.1 1 1.1 -0.0513190921508 2.1 1 2.1 -0.224866151101 2.1 1 3.1 -0.363752470126 2.1 1 4.1 -0.430700436658 2.1 2 0.1 -2.48003822279e-05 2.1 2 1.1 -0.0310025255124 2.1 2 2.1 -0.158022037087 2.1 2 3.1 -0.29944612818 2.1 2 4.1 -0.387965424205 2.1 3 0.1 -1.73211484062e-05 2.1 3 1.1 -0.0220466245862 2.1 3 2.1 -0.12162780064 2.1 3 3.1 -0.254424041889 2.1 3 4.1 -0.35294082311 2.1 4 0.1 -1.32862131387e-05 2.1 4 1.1 -0.0170828002197 2.1 4 2.1 -0.0988138417802 2.1 4 3.1 -0.221154587294 2.1 4 4.1 -0.323713596671 3.1 0 0.1 2402.0 3.1 0 1.1 1.30503380917 3.1 0 2.1 -0.240578771191 3.1 0 3.1 -0.41935483871 3.1 0 4.1 -0.465141248676 3.1 1 0.1 -1.95102493785e-05 3.1 1 1.1 -0.0248114638773 3.1 1 2.1 -0.135153019304 3.1 1 3.1 -0.274125336409 3.1 1 4.1 -0.36965644171 3.1 2 0.1 -1.13811197906e-05 3.1 2 1.1 -0.0147116366819 3.1 2 2.1 -0.0872950700627 3.1 2 3.1 -0.202935925412 3.1 2 4.1 -0.306612285308 3.1 3 0.1 -7.94877050259e-06 3.1 3 1.1 -0.0103624783432 3.1 3 2.1 -0.0642253568271 3.1 3 3.1 -0.160970897235 3.1 3 4.1 -0.261906474418 3.1 4 0.1 -6.09709039262e-06 3.1 4 1.1 -0.00798626913355 3.1 4 2.1 -0.0507564081263 3.1 4 3.1 -0.133349565782 3.1 4 4.1 -0.228563754423 4.1 0 0.1 4202.0 4.1 0 1.1 2.65740045079 4.1 0 2.1 -0.0462153115214 4.1 0 3.1 -0.358933906213 4.1 0 4.1 -0.439024390244 4.1 1 0.1 -1.11538537794e-05 4.1 1 1.1 -0.0144619860317 4.1 1 2.1 -0.0868190343718 4.1 1 3.1 -0.203767982755 4.1 1 4.1 -0.308519215265 4.1 2 0.1 -6.50646078271e-06 4.1 2 1.1 -0.0085156584289 4.1 2 2.1 -0.0538784714494 4.1 2 3.1 -0.140215240068 4.1 2 4.1 -0.23746380125 4.1 3 0.1 -4.54421180079e-06 4.1 3 1.1 -0.00597669061814 4.1 3 2.1 -0.038839789599 4.1 3 3.1 -0.106675396816 4.1 3 4.1 -0.192922262523 4.1 4 0.1 -3.48562423225e-06 4.1 4 1.1 -0.00459693165308 4.1 4 2.1 -0.0303305231375 4.1 4 3.1 -0.0860368842133 4.1 4 4.1 -0.162420599686 The solution to the initial problem is: # Python-matplotlib Commands from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') X = np.arange(-5, 5, .25) Y = np.arange(-5, 5, .25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) Gx, Gy = np.gradient(Z) # gradients with respect to x and y G = (Gx**2+Gy**2)**.5 # gradient magnitude N = G/G.max() # normalize 0..1 surf = ax.plot_surface( X, Y, Z, rstride=1, cstride=1, facecolors=cm.jet(N), linewidth=0, antialiased=False, shade=False) plt.show() As far as I can see, and this applies to all matplotlib-demos, the variables X, Y and Z are nicely prepared. In practical cases this is not always the case. Ideas how to reuse the given solution with arbitrary data? Answer: Great question Tengis, all the math folks love to show off the flashy surface plots with functions given, while leaving out dealing with real world data. The sample code you provided uses gradients since the relationships of a variables are modeled using functions. For this example I will generate random data using a standard normal distribution. Anyways here is how you can quickly plot 4D random (arbitrary) data with first three variables are on the axis and the fourth being color: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = np.random.standard_normal(100) y = np.random.standard_normal(100) z = np.random.standard_normal(100) c = np.random.standard_normal(100) ax.scatter(x, y, z, c=c, cmap=plt.hot()) plt.show() Note: A heatmap with the hot color scheme (yellow to red) was used for the 4th dimension Result: [![enter image description here](http://i.stack.imgur.com/DCywo.png)](http://i.stack.imgur.com/DCywo.png)
output operand requires a reduction, but reduction is not enabled Python Question: import numpy as np from numpy.linalg import solve,norm,cond,inv,pinv import math import matplotlib.pyplot as plt from scipy.linalg import toeplitz from numpy.random import rand c = np.zeros(512) c[0] = 2 c[1] = -1 a = c A = toeplitz(c,a) cond_A = cond(A,2) # creating 10 random vectors 512 x 1 b = rand(10,512) # making b into unit vector for i in range (10): b[i]= b[i]/norm(b[i],2) # creating 10 random del_b vectors del_b = [rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512)] # del_b = 10 sets of 10 vectors (512x1) whose norm is 0.01,0.02 ~0.1 for i in range(10): for j in range(10): del_b[i][j] = del_b[i][j]/(norm(del_b[i][j],2)/((float(j+1)/100))) x_in = [np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512)] x2 = np.zeros((10,10,512)) for i in range(10): x_in[i] = A.transpose()*b[i] for i in range(10): for j in range(10): x2[i][j] = ((A.transpose()*(b[i]+del_b[i][j])) LAST line is giving me the error. ( output operand requires a reduction, but reduction is not enabled) How do i fix it? I'm new to python and please let me know if there is easier way to do this Thanks Answer: The error you're seeing is because of a mismatch in the dimensions of what you have created, but your code is also quite inefficient with all the looping and not making use of Numpy's automatic broadcasting optimally. I've rewritten the code to do what it seems you want: import numpy as np from numpy.linalg import solve,norm,cond,inv,pinv import math import matplotlib.pyplot as plt from scipy.linalg import toeplitz from numpy.random import rand # These should probably get more sensible names Nvec = 10 # number of vectors in b Nlevels = 11 # number of perturbation norm levels Nd = 512 # dimension of the vector space c = np.zeros(Nd) c[0] = 2 c[1] = -1 a = c # NOTE: I'm assuming you want A to be a matrix A = np.asmatrix(toeplitz(c, a)) cond_A = cond(A,2) # create Nvec random vectors Nd x 1 # Note: packing the vectors in the columns makes the next step easier b = rand(Nd, Nvec) # normalise each column of b to be a unit vector b /= norm(b, axis=0) # create Nlevels of Nd x Nvec random del_b vectors del_b = rand(Nd, Nvec, Nlevels) # del_b = 10 sets of 10 vectors (512x1) whose norm is 0.01,0.02 ~0.1 targetnorms = np.linspace(0.01, 0.1, Nlevels) # cause the norms in the Nlevels dimension to be equal to the target norms del_b /= norm(del_b, axis=0)[None, :, :]/targetnorms[None, None, :] # Straight linear transformation - make sure you actually want the transpose x_in = A.T*b # same linear transformation on perturbed versions of b x2 = np.zeros((Nd, Nvec, Nlevels)) for i in range(Nlevels): x2[:, :, i] = A.T*(b + del_b[:, :, i])
Error in python griddata: "builtins.IndexError: index 0 is out of bounds for axis 0 with size 0" Question: ## Griddata error (adapted from: [Matplotlib contour from xyz data: griddata invalid index](http://stackoverflow.com/questions/13781025/matplotlib-contour-from- xyz-data-griddata-invalid-index)) I have a matrix of some values corresponding to a set of coordinates. I want to load the data from an external file and use a griddata object to interpolate between the points. However when running the code i get the error: "builtins.IndexError: index 0 is out of bounds for axis 0 with size 0" from griddata. I have no idea what this means? A piece of sample code: def main(): #http://stackoverflow.com/questions/13781025/matplotlib-contour-from-xyz-data-griddata-invalid-index import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as ml ndata = 121 ny, nx = 100, 200 xmin, xmax = 0, 10 ymin, ymax = 0, 10 Data = np.loadtxt('Data.dat') Data = Data.flatten(1) x = np.array([j for i in np.arange(0,11,1) for j in np.arange(0,11,1)]) y = np.array([j for i in np.arange(0,11,1) for j in np.arange(0,11,1)]) #x = np.random.randint(xmin, xmax, ndata) #y = np.random.randint(ymin, ymax, ndata) xi = np.linspace(xmin, xmax, nx) yi = np.linspace(ymin, ymax, ny) zi = ml.griddata(x, y, Data, xi, yi) plt.contour(xi, yi, zi, 15, linewidths = 0.5, colors = 'k') plt.pcolormesh(xi, yi, zi, cmap = plt.get_cmap('rainbow')) plt.scatter(x, y, marker = 'o', c = 'b', s = 5, zorder = 10) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.show() Data.dat may be obtained from: <http://pastebin.com/Uk8SHA1F> Notice how it works with the comprehensions supplying either x or y in combination with the other coordinate being the random coordinate (commented), but not when using comprehensions for both x and y? Answer: "builtins.IndexError: index 0 is out of bounds for axis 0 with size 0" from griddata. I have no idea what this means? `index 0 is out of bounds for axis 0 with size 0` You would get this error, when 1-D array is supplied when 2-D is expected, and the first index is out of bounds. For example: >>> np.array([])[0,:] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: index 0 is out of bounds for axis 0 with size 0 >>> np.array([2,4])[3,:] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: index 3 is out of bounds for axis 0 with size 2 Note that if you didn't specify any value for 2nd axis, you would get a different error: >>> np.array([])[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: index out of bounds
How to achieve pagination with results from a list in web.py python Question: I am using python `web.py` to design a small web app , here actually i am not using any database for fetching results/records, i will have a list of records(which i will get from some where according to requirement :) ) Below is my code **code.py** import web from web import form urls = ( '/', 'index', '/urls', 'urls_result', ) app = web.application(urls, globals()) render = web.template.render('templates/') class index: def GET(self): return render.home() def POST(self): result_list = [('Images', 'http://www.google.co.in/imghp?hl=en&tab=wi'), ('Maps', 'http://maps.google.co.in/maps?hl=en&tab=wl'), ('Play', 'https://play.google.com/?hl=en&tab=w8'), ('YouTube', 'http://www.youtube.com/?gl=IN&tab=w1'), ('News', 'http://news.google.co.in/nwshp?hl=en&tab=wn'), ('Gmail', 'https://mail.google.com/mail/?tab=wm'), ('Drive', 'https://drive.google.com/?tab=wo'), ('More&raquo;', 'http://www.google.co.in/intl/en/options/'), ('Web History', 'http://www.google.co.in/history/optout?hl=en'), ('Settings', 'http://www.google.co.in/preferences?hl=en'), ('Sign in', 'https://accounts.google.com/ServiceLogin?hl=en&continue=http://www.google.co.in/'), ('Advanced search', 'http://www.google.co.in/advanced_search?hl=en-IN&authuser=0'), .............. .............. .............. so on until 200 records ] return render.recordslist(result_list) if __name__ == "__main__": app.run() **home.html** $def with() <html> <head> <title>Home Page</title> <body alink="green" link="blue" > <div class="main"> <center> <form method="POST" action='urls'> <input class="button" type="submit" name="submit" value="Submit" /> </form> </center> </div> </body> </html> **recordslist.html** $def with(result_list) <html> <head> <title>List of records</title> </head> <body> <table> $for link in result_list: <tr> <td>$link[0]</td> <td>$link[1]</td> </tr> </table> </body> So from the above code what i am doing is, when i run the server and hit the browser with ip returned from `web.py`, it is redirected to home page (with url `/` and template as `home.html`) which consists of form with a single button. Now here i am not using any `database` to fetch the records, simply i have hardcored records which are in the form of `list of tuples` as you can see above. So when the user clicks the submit button i displaying the records in the form of the `table` by directing to the `/url` that renders template `recordslist.html` now the above process is working fine. But here the `list of tuples/records` may up to `200 or more`, so i want to implement `pagination` for `/url` page. I have googled a lot and all hits are found for retreiving the records from database, but not from the list, i am really confused on how to paginate the results with `10 pages for page`. So can anyone please let me now how to paginate the results/records from list from the above code. Answer: ### Get the Page Firstly, you would have to pull the page out of the request from the user. Assuming that you will use a page querystring parameter, you can use this to determine the page number: params = web.input() page = params.page if hasattr(params, 'page') else 1 ### Use the Page Once you have a page, all that pagination involves is returning a slice of results. The following function should give you the slices required (assuming that pages are 1-indexed): def get_slices(page, page_size=10): return (page_size * (page - 1), (page_size * page) This will return the lower and upper bound that you can use to slice your results list. So where you currently `return render.recordslist(result_list)`, you could instead use: lower, upper = get_slices(page) return render.recordslist(result_list[lower:upper])
Connecting to a protected WiFi from Python on Linux Question: I'm creating a software for Ubuntu Linux that needs to connect to a WiFi AP. The WiFi network is not predefined and can change several times during a single run of the software (the user is the one who orders the change). The idea is this: given a set of SSIDs and their WPA or WEP passphrases, the software should be able to switch between the networks on the whim, without the need to change any configuration files anywhere in the system. The huge problem, as it seems, is to pass the passphrase to the connection. Here's what I've been operating with so far: * Ubuntu 12.10 machine equipped with a WiFi dongle. * Python, which runs the software, and which will be used to request the connections * connman 0.79 * wpa_supplicant v1.0 * d-bus At first I thought it would be possible to pass the passphrase to connman through d-bus, but neither this version of connman, nor 1.11, seem to expose any method for that. Then I found out that it's possible to dump a `service_<SSID>.conf` file to the `/var/lib/connman/` directory. Contents of the file are very simple and look like this: [service_SSID] Type=wifi Name=Network-SSID Passphrase=here-goes-the-passphrase Once this file is created, connecting to the network requires a simple call to net.connman.Service.Connect() method in appropriate service. The problem is that connman won't parse the config file unless it's restarted. This requires sudo privileges, additional time, and raises risk for all the "what can go wrong now" things to occur. Then I figured that passphrase could be somehow passed to the wpa_supplicant d-bus API, but I failed to find anything. Google searches have failed me too. It is as if no one ever tried to do this before. Command `sudo iwconfig wlan0 essid <SSID> key s:<PASSPHRASE>` results in a `SET failed on device wlan0 ; Invalid argument.` error. Also, it requires sudo which I would like to avoid. I tried to figure out how the wpa_gui program does its magic. First of all I discovered that it also requires sudo, and that it sends a bunch of commands directly to `/var/run/wpa_supplicant/wlan0`. Replicating this behavior would be a last resort for me if I don't figure out anything simplier. So, the big question is this: How to use Python in order to connect to a WEP/WPA protected WiFi network? I'm also wondering if using connman is a good approach here and if I shouldn't revert to the Network Manager, which is Ubuntu's default. Answer: This shows how to do this for WPA. First of all, ditch connman and use NetworkManager. The example script below shows how to enable wireless support, check if network with given SSID is available, connect to that SSID using a WPA passphrase, and then disconnect from the network and disable wireless. I'm fairly sure that this script can be improved, but the current version serves enough as an example: #!/usr/bin/python # This script shows how to connect to a WPA protected WiFi network # by communicating through D-Bus to NetworkManager 0.9. # # Reference URLs: # http://projects.gnome.org/NetworkManager/developers/ # http://projects.gnome.org/NetworkManager/developers/settings-spec-08.html import dbus import time SEEKED_SSID = "skynet" SEEKED_PASSPHRASE = "qwertyuiop" if __name__ == "__main__": bus = dbus.SystemBus() # Obtain handles to manager objects. manager_bus_object = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") manager = dbus.Interface(manager_bus_object, "org.freedesktop.NetworkManager") manager_props = dbus.Interface(manager_bus_object, "org.freedesktop.DBus.Properties") # Enable Wireless. If Wireless is already enabled, this does nothing. was_wifi_enabled = manager_props.Get("org.freedesktop.NetworkManager", "WirelessEnabled") if not was_wifi_enabled: print "Enabling WiFi and sleeping for 10 seconds ..." manager_props.Set("org.freedesktop.NetworkManager", "WirelessEnabled", True) # Give the WiFi adapter some time to scan for APs. This is absolutely # the wrong way to do it, and the program should listen for # AccessPointAdded() signals, but it will do. time.sleep(10) # Get path to the 'wlan0' device. If you're uncertain whether your WiFi # device is wlan0 or something else, you may utilize manager.GetDevices() # method to obtain a list of all devices, and then iterate over these # devices to check if DeviceType property equals NM_DEVICE_TYPE_WIFI (2). device_path = manager.GetDeviceByIpIface("wlan0") print "wlan0 path: ", device_path # Connect to the device's Wireless interface and obtain list of access # points. device = dbus.Interface(bus.get_object("org.freedesktop.NetworkManager", device_path), "org.freedesktop.NetworkManager.Device.Wireless") accesspoints_paths_list = device.GetAccessPoints() # Identify our access point. We do this by comparing our desired SSID # to the SSID reported by the AP. our_ap_path = None for ap_path in accesspoints_paths_list: ap_props = dbus.Interface( bus.get_object("org.freedesktop.NetworkManager", ap_path), "org.freedesktop.DBus.Properties") ap_ssid = ap_props.Get("org.freedesktop.NetworkManager.AccessPoint", "Ssid") # Returned SSID is a list of ASCII values. Let's convert it to a proper # string. str_ap_ssid = "".join(chr(i) for i in ap_ssid) print ap_path, ": SSID =", str_ap_ssid if str_ap_ssid == SEEKED_SSID: our_ap_path = ap_path break if not our_ap_path: print "AP not found :(" exit(2) print "Our AP: ", our_ap_path # At this point we have all the data we need. Let's prepare our connection # parameters so that we can tell the NetworkManager what is the passphrase. connection_params = { "802-11-wireless": { "security": "802-11-wireless-security", }, "802-11-wireless-security": { "key-mgmt": "wpa-psk", "psk": SEEKED_PASSPHRASE }, } # Establish the connection. settings_path, connection_path = manager.AddAndActivateConnection( connection_params, device_path, our_ap_path) print "settings_path =", settings_path print "connection_path =", connection_path # Wait until connection is established. This may take a few seconds. NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2 print """Waiting for connection to reach """ \ """NM_ACTIVE_CONNECTION_STATE_ACTIVATED state ...""" connection_props = dbus.Interface( bus.get_object("org.freedesktop.NetworkManager", connection_path), "org.freedesktop.DBus.Properties") state = 0 while True: # Loop forever until desired state is detected. # # A timeout should be implemented here, otherwise the program will # get stuck if connection fails. # # IF PASSWORD IS BAD, NETWORK MANAGER WILL DISPLAY A QUERY DIALOG! # This is something that should be avoided, but I don't know how, yet. # # Also, if connection is disconnected at this point, the Get() # method will raise an org.freedesktop.DBus.Error.UnknownMethod # exception. This should also be anticipated. state = connection_props.Get( "org.freedesktop.NetworkManager.Connection.Active", "State") if state == NM_ACTIVE_CONNECTION_STATE_ACTIVATED: break time.sleep(0.001) print "Connection established!" # # Connection is established. Do whatever is necessary. # ... # print "Sleeping for 5 seconds ..." time.sleep(5) print "Disconnecting ..." # Clean up: disconnect and delete connection settings. If program crashes # before this point is reached then connection settings will be stored # forever. # Some pre-init cleanup feature should be devised to deal with this problem, # but this is an issue for another topic. manager.DeactivateConnection(connection_path) settings = dbus.Interface( bus.get_object("org.freedesktop.NetworkManager", settings_path), "org.freedesktop.NetworkManager.Settings.Connection") settings.Delete() # Disable Wireless (optional step) if not was_wifi_enabled: manager_props.Set("org.freedesktop.NetworkManager", "WirelessEnabled", False) print "DONE!" exit(0)
Way to read first few lines for pandas dataframe Question: Is there a built-in way to use `read_csv` to read only the first `n` lines of a file without knowing the length of the lines ahead of time? I have a large file that takes a long time to read, and occasionally only want to use the first, say, 20 lines to get a sample of it (and prefer not to load the full thing and take the head of it). If I knew the total number of lines I could do something like `footer_lines = total_lines - n` and pass this to the `skipfooter` keyword arg. My current solution is to manually grab the first `n` lines with python and StringIO it to pandas: import pandas as pd from StringIO import StringIO n = 20 with open('big_file.csv', 'r') as f: head = ''.join(f.readlines(n)) df = pd.read_csv(StringIO(head)) It's not that bad, but is there a more concise, 'pandasic' (?) way to do it with keywords or something? Answer: I think you can use the `nrows` parameter. From [the docs](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.read_csv.html): nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines): In [1]: import pandas as pd In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20) CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s Wall time: 0.00 s In [3]: len(z) Out[3]: 20 In [4]: time z = pd.read_csv("P00000001-ALL.csv") CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s Wall time: 30.23 s
pylab troubles with EPD version of ipython Question: I recently switched to the EPD version of ipython (I have the 64-bit student edition), and now I'm having trouble with pylab. When I type "import pylab" it gives me the following error ImportError Traceback (most recent call last) <ipython-input-1-0c66bb86b884> in <module>() ----> 1 import pylab /Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/pylab.py in <module>() ----> 1 from matplotlib.pylab import * 2 import matplotlib.pylab 3 __doc__ = matplotlib.pylab.__doc__ /Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/pylab.py in <module>() 219 silent_list, iterable, dedent 220 --> 221 from matplotlib import mpl # pulls in most modules 222 223 from matplotlib.dates import date2num, num2date,\ /Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/mpl.py in <module>() 1 from matplotlib import artist ----> 2 from matplotlib import axis 3 from matplotlib import axes 4 from matplotlib import cbook 5 from matplotlib import collections /Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/axis.py in <module>() 8 from matplotlib.artist import allow_rasterization 9 import matplotlib.cbook as cbook ---> 10 import matplotlib.font_manager as font_manager 11 import matplotlib.lines as mlines 12 import matplotlib.patches as mpatches /Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/font_manager.py in <module>() 50 import matplotlib 51 from matplotlib import afm ---> 52 from matplotlib import ft2font 53 from matplotlib import rcParams, get_configdir 54 from matplotlib.cbook import is_string_like ImportError: dlopen(/Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/ft2font.so, 2): Symbol not found: _FT_Attach_File Referenced from: /Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/ft2font.so Expected in: flat namespace in /Library/Python/2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/ft2font.so I need pylab/matplotlib to live, so this is bad. Interestingly enough, when I double click on PyLab (64-bit).app in my /Applications/Enthought/ folder it opens up a terminal and pylab runs fine, it just doesn't work when I call it from the command line, or when I use notebook. If I could get python to use the version of pylab that I got from EPD then everything would be fine, but by default it imports the thing from /Library/Python/2.7/site- packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg/matplotlib/ where something is wrong with ft2font.so. Answer: Looks like a conflict between your EPD python and the packages that you installed with Apple's python. 1) As tsyu80 indicates, your PATH may be pointing you to Apple's python, so you may be starting its ipython rather than EPD's. If this is the case, adding the following lines to your ~/.bash_profile file should fix this (though these lines should already have been added during EPD installation) # Setting PATH for EPD-7 PATH="/Library/Frameworks/EPD64.framework/Versions/Current/bin:${PATH}" export PATH Note that you should a new Terminal session to have these settings take effect. 2) Even if you start EPD's (i)python, it may be importing from packages installed in Apple's. See <https://support.enthought.com/entries/22094157-OS- X-Conflict-with-installed-packages-in-earlier-Python-installation> 3) Once you resolve this issue, be sure to update to the latest version of ipython: <https://support.enthought.com/entries/22415022-Using-enpkg-to- update-EPD-packages>
How can I interact with an application on mac through python subprocess? Question: I know there are similar questions posted already, but non of the methods I have seen seems to work. I want to launch the application xfoil, on mac, with python subprocess, and send xfoil a bunch of commands with a script (xfoil is an application that runs in a terminal window and you interact with it through text commands). I am able to launch xfoil with the script, but I can't seem to find out how to send commands to it. This is the code I am currently trying: import subprocess as sp xfoil = sp.Popen(['open', '-a', '/Applications/Xfoil.app/Contents/MacOS/Xfoil'], stdin=sp.PIPE, stdout=sp.PIPE) stdout_data = xfoil.communicate(input='NACA 0012') I have also tried xfoil.stdin.write('NACA 0012\n') in order to send commands to xfoil. Answer: As the [man page](http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/open.1.html) says, > The **open** command opens a file (or a directory or URL), just as if you > had double-clicked the file's icon. Ultimately, the application gets started by LaunchServices, but that's not important—what's important is that it's not a child of your shell, or Python script. Also, the whole point of `open` is to open the app itself, so you don't have to dig into it and find the Unix executable file. If you already have that, and want to run it as a Unix executable… just run it: xfoil = sp.Popen(['/Applications/Xfoil.app/Contents/MacOS/Xfoil'], stdin=sp.PIPE, stdout=sp.PIPE) As it turns out, in this case, `MacOS/Xfoil` isn't even the right program; it's apparently some kind of wrapper around `Resources/xfoil`, which is the actual equivalent to what you get as `/usr/local/bin/xfoil` on linux. So you want to do this: xfoil = sp.Popen(['/Applications/Xfoil.app/Contents/Resouces/xfoil'], stdin=sp.PIPE, stdout=sp.PIPE) (Also, technically, your command line shouldn't even work at all; the `-a` specifies an application, not a Unix executable, and you're supposed to pass at least one file to open. But because LaunchServices can launch Unix executables as if they were applications, and `open` doesn't check that the arguments are valid, `open -a /Applications/Xfoil.app/Contents/MacOS/Xfoil` ends up doing effectively the same thing as `open /Applications/Xfoil.app/Contents/MacOS/Xfoil`.) * * * For the benefit of future readers, I'll include this information from the comments: If you just write a line to `stdin` and then return from the function/fall off the end of the main script/etc., the `Popen` object will get garbage collected, closing both of its pipes. If `xfoil` hasn't finished running yet, it will get an error the next time it tries to write any output, and apparently it handles this by printing `Fortran runtime error: end of file` (to stderr?) and bailing. You need to call [`xfoil.wait()`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait) (or something else that implicitly `wait`s) to prevent this from happening.
Is it possible to replace schema locations in Suds/python? Question: I'm trying to hit a WCF service that's being hosted behind a reverse proxy/redirect. The WCF service is reporting the wrong `schemaLocation`, based on which machine it's actually being served from. For instance, I get something like this: <wsdl:types> <xsd:schema targetNamespace="http://tempuri.org/Imports"> <xsd:import schemaLocation="http://badhost1.com/service.svc?xsd=xsd0" namespace="http://tempuri.org/"/> <xsd:import schemaLocation="http://badhost1.com/service.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/"/> </xsd:schema> </wsdl:types> Now, it shouldn't be `http://badhost1.com`, it should be `http://goodhost.com`. I can open the xsd in my browser if I point it to the goodhost version - obviously the badhost one doesn't work. Is there a way to replace these bad endpoints with the correct one? Answer: It turns out the one can create [plugins](https://fedorahosted.org/suds/wiki/Documentation#PLUGINS). This one is an easy one: import re from suds.plugin import DocumentPlugin class FixUrls(DocumentPlugin): def loaded(self, context): context.document = re.sub(r'badhost\d', 'goodhost', context.document) And then it's called a la: client = Client(url, plugins=[plugin]) That's all it takes!
Why is there no xrange function in Python3? Question: Recently I started using Python3 and it's lack of xrange hurts. Simple example: **1)** Python2: from time import time as t def count(): st = t() [x for x in xrange(10000000) if x%4 == 0] et = t() print et-st count() **2)** Python3: from time import time as t def xrange(x): return iter(range(x)) def count(): st = t() [x for x in xrange(10000000) if x%4 == 0] et = t() print (et-st) count() The results are, respectively: **1)** 1.53888392448 **2)** 3.215819835662842 Why is that? I mean, why xrange's been removed? It's such a great tool to learn. For the beginners, just like myself, like we all were at some point. Why remove it? Can somebody point me to the proper PEP, I can't find it. Cheers. Answer: Some performance measurements, using `timeit` instead of trying to do it manually with `time`. First, Apple 2.7.2 64-bit: In [37]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0) 1 loops, best of 3: 1.05 s per loop Now, python.org 3.3.0 64-bit: In [83]: %timeit collections.deque((x for x in range(10000000) if x%4 == 0), maxlen=0) 1 loops, best of 3: 1.32 s per loop In [84]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0) 1 loops, best of 3: 1.31 s per loop In [85]: %timeit collections.deque((x for x in iter(range(10000000)) if x%4 == 0), maxlen=0) 1 loops, best of 3: 1.33 s per loop Apparently, 3.x `range` really is a bit slower than 2.x `xrange`. And the OP's `xrange` function has nothing to do with it. (Not surprising, as a one-time call to the `__iter__` slot isn't likely to be visible among 10000000 calls to whatever happens in the loop, but someone brought it up as a possibility.) But it's only 30% slower. How did the OP get 2x as slow? Well, if I repeat the same tests with 32-bit Python, I get 1.58 vs. 3.12. So my guess is that this is yet another of those cases where 3.x has been optimized for 64-bit performance in ways that hurt 32-bit. But does it really matter? Check this out, with 3.3.0 64-bit again: In [86]: %timeit [x for x in range(10000000) if x%4 == 0] 1 loops, best of 3: 3.65 s per loop So, building the `list` takes more than twice as long than the entire iteration. And as for "consumes much more resources than Python 2.6+", from my tests, it looks like a 3.x `range` is exactly the same size as a 2.x `xrange`—and, even if it were 10x as big, building the unnecessary list is still about 10000000x more of a problem than anything the range iteration could possibly do. And what about an explicit `for` loop instead of the C loop inside `deque`? In [87]: def consume(x): ....: for i in x: ....: pass In [88]: %timeit consume(x for x in range(10000000) if x%4 == 0) 1 loops, best of 3: 1.85 s per loop So, almost as much time wasted in the `for` statement as in the actual work of iterating the `range`. If you're worried about optimizing the iteration of a range object, you're probably looking in the wrong place. * * * Meanwhile, you keep asking why `xrange` was removed, no matter how many times people tell you the same thing, but I'll repeat it again: It was not removed: it was renamed to `range`, and the 2.x `range` is what was removed. Here's some proof that the 3.3 `range` object is a direct descendant of the 2.x `xrange` object (and not of the 2.x `range` function): the source to [3.3 `range`](http://hg.python.org/cpython/file/3.3/Objects/rangeobject.c) and [2.7 `xrange`](http://hg.python.org/cpython/file/2.7/Objects/rangeobject.c). You can even see the [change history](http://hg.python.org/cpython/diff/a6eb6acfe04a/Objects/rangeobject.c) (linked to, I believe, the change that replaced the last instance of the string "xrange" anywhere in the file). So, why is it slower? Well, for one, they've added a lot of new features. For another, they've done all kinds of changes all over the place (especially inside iteration) that have minor side effects. And there'd been a lot of work to dramatically optimize various important cases, even if it sometimes slightly pessimizes less important cases. Add this all up, and I'm not surprised that iterating a `range` as fast as possible is now a bit slower. It's one of those less- important cases that nobody would ever care enough to focus on. No one is likely to ever have a real-life use case where this performance difference is the hotspot in their code.
Python, how to send output to both file and terminal Question: I want to use Python to send output to both a file `log.txt` and STDOUT on the terminal. Here is what I have: import sys class Logger(object): def __init__(self, filename="Default.log"): self.terminal = sys.stdout self.log = open(filename, "a") def write(self, message): self.terminal.write(message) self.log.write(message) sys.stdout = Logger("log.txt") print "Hello world !" #This line is saved in log.txt and STDOUT This program sends output to the file and stdout. My question is: How did the write function to the file get called? Answer: From the [documentation](http://docs.python.org/2/library/sys.html#sys.stdout) for sys.stdout: > stdout and stderr needn’t be built-in file objects: any object is acceptable > as long as it has a write() method that takes a string argument.
How to Construct JSON string django view? Question: I want to construct json like this in the `django` view: { "Skills": [ { "Name": "Java", "Value": "Java" }, { "Name": "J2ee", "Value": "J2ee" }, { "Name": "Python", "Value": "Python" }, { "Name": "Django", "Value": "Django" } ] } The python simplejson does not create it like the above, any suggestions please. Basically I am sending response to the select2 tag. I am invoking the view method from the Jquery ajax .. def populateSkills(request): print "Inside Populate Skills" preload_data = '{"Skills":[{"Name":"Java","Value":"Java"},{"Name":"J2ee","Value":"J2ee"},{"Name":"Python","Value":"Python"},{"Name":"Django","Value":"Django"}]}' return HttpResponse(simplejson.dumps(preload_data), content_type="application/json") I have the preload_data hard-coded as I could not construct it. So how do I construct it? is there a JSONObject to do it? Answer: Using [simplejson](https://pypi.python.org/pypi/simplejson/): import simplejson simplejson.dumps({'Skills': [{'Name': 'Java', 'Value': 'Java'}, {'Name': 'J2ee', 'Value': 'J2ee'}, {'Name': 'Python', 'Value': 'Python'}, {'Name': 'Django', 'Value': 'Django'}] })
How are import statements in plpython handled? Question: I have a plypython function which does some json magic. For this it obviously imports the json library. Is the import called on every call to the function? Are there any performance implication I have to be aware of? Answer: The `import` is executed on every function call. This is the same behavior you would get if you wrote a normal Python module with the `import` statement inside a function body as oppposed to at the module level. Yes, this will affect performance. You can work around this by caching your imports like this: CREATE FUNCTION test() RETURNS text LANGUAGE plpythonu AS $$ if 'json' in SD: json = SD['json'] else: import json SD['json'] = json return json.dumps(...) $$; This is admittedly not very pretty, and better ways to do this are being discussed, but they won't happen before PostgreSQL 9.4.
Keyboards event on coco2d (python) and pyglet Question: second question here, my first one was answer and really helped, so I'll try again. Here is the code and the explanation: import cocos from cocos.actions import * import pyglet from pyglet.window import key from pyglet.window.key import KeyStateHandler from cocos.director import director keys = KeyStateHandler() class ScaleTestLayer(cocos.layer.Layer): is_event_handler = True def __init__(self): super( ScaleTestLayer, self ).__init__() self.sprite = cocos.sprite.Sprite('grossini.png') self.sprite.position = 320,240 self.drag = False self.add(self.sprite) self.rect = self.sprite.get_rect() def on_mouse_release(self, x, y, buttons, modifiers): if self.rect.contains(x, y) == True: if self.drag == False: scale = ScaleBy(5, duration=1) if buttons == pyglet.window.mouse.LEFT: self.sprite.do(scale) if buttons == pyglet.window.mouse.MIDDLE: rotate = RotateBy(180, 1) self.sprite.do(rotate) if buttons == pyglet.window.mouse.RIGHT: scale = (Reverse(scale)) self.sprite.do(scale) else: self.drag = False def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if self.rect.contains(x, y): self.drag = True self.sprite.position = director.get_virtual_coordinates (x, y) self.rect.center = self.sprite.position def on_key_press(self, symbol, modifiers): if keys[key.SPACE]: jump = JumpBy((5,0), duration=0.5) self.sprite.do(jump) if keys[key.RIGHT]: move = MoveBy((10,0), 0.5) self.sprite.do(move) if __name__ == "__main__": cocos.director.director.init() test_layer = ScaleTestLayer () main_scene = cocos.scene.Scene (test_layer) cocos.director.director.run (main_scene) So here's my problem. When I press SPACE or RIGHT it does not execute the action. I printed the value and keys[key.SPACE] is return False, even though I do press those buttons. What am I missing? maybe some push_handlers? I don't know how to use it. Thanks beforehand. Answer: Yes, you need to use push_handlers on the `KeyStateHandler` so that it is updated. I have not used cocos2d myself, only pyglet, so this may not be the best or proper way to do it, but it should get you going. if __name__ == '__main__': cocos.director.director.init() cocos.director.director.window.push_handlers(keys) # Create layer, run, etc. [Here is the page](http://www.pyglet.org/doc/api/pyglet.window.key.KeyStateHandler- class.html) on using a `KeyStateHandler` in the pyglet documentation. In pyglet you create the window yourself and attach it there, but in cocos2d the window is handled by the director. I also found [this page](http://cocos2d.org/doc/programming_guide/handling_events.html) in the cocos2d documentation, which may, or may not be, the proper way of handling key presses with cocos2d.
Unwrapping t.co link that links to bit.ly Question: I'm trying to get the URL that has been already shortened by bit.ly and again by twitter. I have already tried: import urllib.request r = urllib.request.urlopen(url) r.url Also by using libraries such as [requests](http://docs.python- requests.org/en/latest/) and [httplib2](http://code.google.com/p/httplib2/). All these solutions would work if i wanted the final destination for the t.co link, however, I do need the intermediate shortener, which I now I can get via a HEAD request but I can't get Python 3 http.client working in order to get the location. Any ideas? Answer: >>> c = http.client.HTTPConnection('t.co') >>> c.request('GET', '/7fGoazTYpc') # or HEAD, but body is empty anyway >>> r = c.getresponse() >>> r.getheader('Location') 'http://bit.ly/900913'
JPype won't compile properly Question: So I am having trouble compiling a very simple python script using [JPype](http://jpype.sourceforge.net/). My code goes like: from jpype import * startJVM(getDefaultJVMPath(), "-ea") java.lang.System.out.println("hello world") shutdownJVM() and when I run it I receive an error saying: Traceback (most recent call last): File "test.py", line 2, in <module> startJVM(getDefaultJVMPath(), "-ea") File "/usr/lib/pymodules/python2.7/jpype/_core.py", line 44, in startJVM _jpype.startup(jvm, tuple(args), True) RuntimeError: Unable to load DLL [/usr/java/jre1.5.0_05/lib/i386/client/libjvm.so], error = /usr/java/jre1.5.0_05/lib/i386/client/libjvm.so: cannot open shared object file: No such file or directory at src/native/common/include/jp_platform_linux.h:45 I'm stuck and I really need help. Thanks! Answer: I had the same problem RuntimeError: Unable to load DLL [/usr/java/jre1.5.0_05/lib/i386/client/libjvm.so], error = /usr/java/jre1.5.0_05/lib/i386/client/libjvm.so: cannot open shared object file: No such file or directory at src/native/common/include/jp_platform_linux.h:45 In my case wrong JAVA_HOME path was set /profile/etc export JAVA_HOME JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64 PATH="$JAVA_HOME/bin:$PATH" export PATH
Python Program is Terminating on Handled Exception Question: I am editing the question for clarity. I created a class in a module that imports MySQLdb. I have found that MySQLdb will raise an Exception if the table the user passes to my class does not exist. I am catching that exception, and passing a new one to the client. But even if the client catches my exception, the program still terminates. I have also tried passing to the client the same Exception MySQLdb is giving my class. Since the client will be calling my method in a loop, passing in various table names, I don't want the program to choke if the table name is bad. I'd like the client's iterations to continue to the next valid table name. Here is a snippet (tableName is an arg pass in to the method): In my class/module: self.tableName = tableName try: self.cursor.execute("select * from " + self.tableName + ";") #Will raise Exception if the table does not exist. except: raise MyException("\n*** " + self.tableName + " does not exist. ***") In the client: tables = ["BadTableName", "GoodTableNameA", "GoodTableNameB","GoodTableNameC"] try: for table in tables: my_method(table) #Exception message gets passed in with BadTableName, but the program ends. Subsequest iterations of this loop never happen except Exception, e: print e I would like the client to continue even after calling my_method(BadTableName). By the way, my_method() is part of a class defined in its own module which the client is importing. Thank you. Answer: Exceptions do not always cause the program to end. From the [docs](http://docs.python.org/2/tutorial/errors.html#exceptions): > Errors detected during execution are called exceptions and are not > unconditionally fatal: If an exception is raised in a try: except block and the `except` clause is specifying the exception or a super class of the exception it will be handled. When handling an exception you can inspect it and find out all information related to it. I have never used the [`traceback`](http://docs.python.org/2/library/traceback.html#traceback- examples) module before but it looks like it contains everything you need. I guess your second question depends on what you want your user to see. Should the exception be shown? (you have access to the traceback). Should just the message be shown? SHould you log the traceback?
Cannot set up Google App Engine for Python 2.7 on OSX 10.6 Question: Trying to run the Python 2.7 dev environment for Google App Engine on Mac OSX (10.6.8), but I cannot get the helloworld example won't run. I cannot import webapp2 in a Python shell. When I try to run from the GUI, the log reports that my "Python command" is /usr/bin/python2.6, though my system default is 2.7. When I try to visit localhost:8080 I get "ImportError: No module named urllib". Tried launching from the command line with /usr/local/google_appengine/dev_appserver.py helloworld/. Got error: fancy_urllib.InvalidCertificateException: Host appengine.google.com returned an invalid certificate (_ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed): To learn more, see http://code.google.com/appengine/kb/general.html#rpcssl. Thinking the application might be using 2.5, and per the "learn more" link, I installed ssl to Python2.5 (downloaded code, << sudo python2.5 setup.py install >>). While I could now import ssl into a Python 2.5 shell, I still got the same error when running the dev server. I did do my own install of Python 2.7 on this computer, so it is possible that in doing so I broke / missed something subtle. Also, the software README refers only to 2.5, and has a latest date of April 2008. I see only one Python download at the [downloads page](https://developers.google.com/appengine/downloads) Any help would be appreciated. Answer: You shouldn't be able to `import webapp2` in Python shell since webapp2 is not in the default packages. Make sure that you have the latest Launcher for MacOS running on your computer and try the following: * Run the **GoogleAppEngineLauncher** * **File** > **New Application...** * Choose a name and press **Create** * Press **Run** * Press **Browse** If following the above steps you will see the **Hello, world!** in the browser then you are good to continue with your Hello, world! application. If not make sure that you're running the `dev_appserver.py` from a command line by using the correct version of Python, or if you're running using the Launcher in the **preferences** you might need to add the **Python Path** to point to the `python2.7`.
Parsing out single column from csv into text file using python Question: I finally got my dbf file to be a csv but now I am confused as to how to parse this out into a text file for further editing. I have been reading up on the csv module but to be honest my head began to spin. So much of it seemed Greek to me. However, I would like the code for using module this if possible. My car.csv file looks like this: Name,Total,Freq Toyota,2,2 Mazda,1,1 Kia,2,1 Volkswagon,3,1 I want to output the following sentence into a text file (or csv): Within this neighborhood there is a Toyota, Mazda, Kia, and Volkswagon parked on the street. If the results are two I do not want commas: Cars.dbf Toyota,2,2 Mazda,2,1 Within this neighborhood there is a Toyota and Mazda parked on the street. Cars.dbf empty There are no cars parked on the street within this neighborhood. I got a good suggestion from a previous post on constructing the if-else sentences but am lost on how to parse columns (they didn't show up in Excel for some reason, I thought I only had one column) python 2.7 BTW. Anyone know of a good web site that explains the csv module in terms a total newbie can understand? Thanks. Answer: The [Python doc examples](http://docs.python.org/2/library/csv.html#examples) are always a go to place. You want something like this: import csv makes = [] with open('cars.csv', 'rb') as f: reader = csv.reader(f) next(reader) # Ignore first row for row in reader: makes.append(row[0]) print makes
Flask-Mail breaks Celery Question: I've got a Flask app where celery works fine and Flask-Mail on its own works fine as well. from celery import Celery from flask_mail import Mail, Message app = Flask(__name__) mail = Mail(app) celery = Celery('main_app', broker='mongodb://localhost', backend='mongodb://localhost') @celery.task def cel_test(): return 'cel_test' @app.route('/works_maybe') def works_maybe(): return cel_test.delay() # SO FAR, SO GOOD cel_test works fine with the celery worker; everything shows up in mongo. But here's where it gets weird. The "signup" plus mail method works 100% without `@celery.task`, but blows up when it becomes a task. @celery.task def send_email(some_arg, name, email): msg = Message(…message details..) return mail.send(msg) @app.route("/signup", methods=['POST']) def signup(): return send_email.delay(...stuff for the message…) # THE TRACE R = retval = fun(*args, **kwargs) File "/Users/username/pymods/virtualenvs/directory/lib/python2.7/site-packages/celery-3.0.15-py2.7.egg/celery/task/trace.py", line 415, in __protected_call__ return self.run(*args, **kwargs) File "/Users/username/pymods/directory/directory/main_app/main_app.py", line 43, in send_email something = 'a string in the Message'), File "/Users/username/pymods/virtualenvs/directory/lib/python2.7/site-packages/flask/templating.py", line 123, in render_template ctx.app.update_template_context(context) AttributeError: 'NoneType' object has no attribute 'app' Could someone explain why in one case celery works great but when I involve mail.send(msg) it breaks? Perhaps there is something I need to learn with python more generally? Any thoughts, if at least as to approach to this type of issue would be greatly appreciated. Answer: # Update The bug is in the render_template portion of the `send_email` task. @celery.task def send_email(some_arg, name, email): msg = Message( subject='hello', body=render_template('email.txt', name=name, some_arg=some_arg), recipients=[email] ) return mail.send(msg) When I remove `body=render_template`, _kablaam_ , it works. I've got `from flask import render_template`. Perhaps `render_template` can't work like this? Strangely, _without_ Celery, the `send_email` plus `render_template` works perfect. # Hackish Success When I force the `app_context` with another function everything works: def create_email(some_arg, name, email): with app.test_request_context('/send_email'): return render_template('email.txt', name=name, some_arg=some_arg) and then toss it in the `send_email` task so body = render_template('email.txt'… becomes body= create_email(some_arg, name) And we're home free.
If RAM isn't a concern, is reading line by line faster or reading everything into RAM and access it? - Python Question: If RAM isn't a concern (I have close to 200GB on the server), is reading line by line faster or reading everything into RAM and access it? Each line will be a string of around 200-500 unicode characters. There are close to 2 million lines for each file. **Line-by-line** import codecs for i in codecs.open('unicodefile','r','utf8'): print i **Reading into RAM** import codecs for i in codecs.open('unicodefile','r','utf8').readlines(): print i Answer: I used cProfile on a ~1MB dictionary words file. I read the same file 3 times. The first reads tho whole file in just to even the playing field in terms of it being stored in cache. Here is the simple code: def first_read(): codecs.open(file, 'r', 'utf8').readlines() def line_by_line(): for i in codecs.open(file, 'r', 'utf8'): pass def at_once(): for i in codecs.open(file, 'r', 'utf8').readlines(): pass first_read() cProfile.run('line_by_line()') cProfile.run('at_once()') And here are the results: **Line by line:** 366959 function calls in 1.762 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 1.762 1.762 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 codecs.py:322(__init__) 1 0.000 0.000 0.000 0.000 codecs.py:395(__init__) 14093 0.087 0.000 0.131 0.000 codecs.py:424(read) 57448 0.285 0.000 0.566 0.000 codecs.py:503(readline) 57448 0.444 0.000 1.010 0.000 codecs.py:612(next) 1 0.000 0.000 0.000 0.000 codecs.py:651(__init__) 57448 0.381 0.000 1.390 0.000 codecs.py:681(next) 1 0.000 0.000 0.000 0.000 codecs.py:686(__iter__) 1 0.000 0.000 0.000 0.000 codecs.py:841(open) 1 0.372 0.372 1.762 1.762 test.py:9(line_by_line) 13316 0.011 0.000 0.023 0.000 utf_8.py:15(decode) 1 0.000 0.000 0.000 0.000 {_codecs.lookup} 27385 0.027 0.000 0.027 0.000 {_codecs.utf_8_decode} 98895 0.011 0.000 0.011 0.000 {len} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 13316 0.099 0.000 0.122 0.000 {method 'endswith' of 'unicode' objects} 27 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects} 14069 0.027 0.000 0.027 0.000 {method 'read' of 'file' objects} 13504 0.020 0.000 0.020 0.000 {method 'splitlines' of 'unicode' objects} 1 0.000 0.000 0.000 0.000 {open} **All at once:** 15 function calls in 0.023 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.023 0.023 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 codecs.py:322(__init__) 1 0.000 0.000 0.000 0.000 codecs.py:395(__init__) 1 0.000 0.000 0.003 0.003 codecs.py:424(read) 1 0.000 0.000 0.014 0.014 codecs.py:576(readlines) 1 0.000 0.000 0.000 0.000 codecs.py:651(__init__) 1 0.000 0.000 0.014 0.014 codecs.py:677(readlines) 1 0.000 0.000 0.000 0.000 codecs.py:841(open) 1 0.009 0.009 0.023 0.023 test.py:13(at_once) 1 0.000 0.000 0.000 0.000 {_codecs.lookup} 1 0.003 0.003 0.003 0.003 {_codecs.utf_8_decode} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.001 0.001 0.001 0.001 {method 'read' of 'file' objects} 1 0.010 0.010 0.010 0.010 {method 'splitlines' of 'unicode' objects} 1 0.000 0.000 0.000 0.000 {open} As you can see from the results, reading the whole file in at once is much faster, but you run the risk of a MemoryError being thrown in the file is too large.
How to continuously display python output in a webpage? Question: I want to be able to visit a webpage and it will run a python function and display the progress in the webpage. So when you visit the webpage you can see the output of the script as if you ran it from the command line and see the output in the command line. What do I need to do in the function? What do I need to do in the template? EDIT: I am trying to use Markus Unterwaditzer's code with a template. {% extends "base.html" %} {% block content %} {% autoescape false %} {{word}} {% endautoescape %} {% endblock %} Python code import flask from flask import render_template import subprocess import time app = flask.Flask(__name__) @app.route('/yield') def index(): def inner(): for x in range(1000): yield '%s<br/>\n' % x time.sleep(1) return render_template('simple.html', word=inner()) #return flask.Response(inner(), mimetype='text/html') # text/html is required for most browsers to show the partial page immediately app.run(debug=True, port=8080) And it runs but I don't see anything in the browser. Answer: Here is a very simple app that streams a process' output with normal HTTP: import flask import time app = flask.Flask(__name__) @app.route('/yield') def index(): def inner(): for x in range(100): time.sleep(1) yield '%s<br/>\n' % x return flask.Response(inner(), mimetype='text/html') # text/html is required for most browsers to show the partial page immediately app.run(debug=True)
Hebrew calendar in python Question: I have to work with Jewish Calendar in Python. I want to know if there is a Jewish Calendar in Python or if there is import in python Hope for answers Answer: You could use [the Python Date Utilities module](http://sourceforge.net/projects/pythondateutil/), which claims to convert between different date systems, including Hebrew. There is more info on this site ([Jewish calendar calculation in Python](http://www.david-greve.de/luach-code/jewish-python.html)), which covers the manual implementation of some utilities such as the calculation of Jewish holidays and the weekly Torah sessions.
ImportError: No module named prop2part (TuLiP) Question: Using TuLiP module in Python, an error message always appears when I try to compile a code I have : `ImportError: No module named prop2part` In the code, initialization contains : import sys, os import matplotlib as mpl import matplotlib.pyplot as plt sys.path.append(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), '..')) from prop2part import Region, PropPreservingPartition Any ideas why the error appears ? Answer: Download prop2part module from this link `http://tulip- control.sourceforge.net/doc/_modules/prop2part.html` Then append the downloaded path either in sys.path list or you can move the downloaded module in any of the path available in the sys.path.
Weird behavior in Python Question: I wrote a simple program to translate DNA to RNA. Basically, you input a string, it separates the string into characters and sends them to a list, shifts the letter and returns a string from the resulting list. This program correctly translates a to u, and to to a, but does not change g to c and c to g. This is the program: def trad(x): h=[] for letter in x: h.append(letter) for letter in h: if letter=="a": h[h.index(letter)]="u" continue if letter=="t": h[h.index(letter)]="a" continue if letter=="g": h[h.index(letter)]="c" continue if letter=="c": h[h.index(letter)]="g" continue ret="" for letter in h: ret+=letter return ret while True: stry=raw_input("String?") print trad(stry) Now, just altering the program by not iterating over elements, but on positions, it works as expected. This is the resulting code: def trad(x): h=[] for letter in x: h.append(letter) for letter in xrange (0, len(h)): if h[letter]=="a": h[letter]="u" continue if h[letter]=="t": h[letter]="a" continue if h[letter]=="g": h[letter]="c" continue if h[letter]=="c": h[letter]="g" continue ret="" for letter in h: ret+=letter return ret while True: stry=raw_input("String?") print trad(stry) Why does this strange behaviour occur, and how can I resolve it? Answer: You are going about this a much harder way than is necessary, this could easily be done using [`str.translate()`](http://docs.python.org/2.7/library/stdtypes.html#str.translate) \- a method on `str` instances that translates instances of one character to another, which is exactly what you want: import string replacements = string.maketrans("atgc", "uacg") while True: stry=raw_input("String?") print stry.translate(replacements) This is an answer for 2.x, in 3.x, use `str.maketrans()` instead.
Python and RFC 3339 timestamps Question: Where can I find a routine for building an RFC 3339 time? Answer: This was based on the examples on page 10 of the RFC. The only difference is that I am showing a microseconds value of six digits, conformant to Google Drive's timestamps. from math import floor def build_rfc3339_phrase(datetime_obj): datetime_phrase = datetime_obj.strftime('%Y-%m-%dT%H:%M:%S') us = datetime_obj.strftime('%f') seconds = datetime_obj.utcoffset().total_seconds() if seconds is None: datetime_phrase += 'Z' else: # Append: decimal, 6-digit uS, -/+, hours, minutes datetime_phrase += ('.%.6s%s%02d:%02d' % ( us, ('-' if seconds < 0 else '+'), abs(int(floor(seconds / 3600))), abs(seconds % 3600) )) return datetime_phrase
PyQt4 nested classes - "RuntimeError: underlying C/C++ object has been deleted" Question: I'm trying to build a cool app, but it seems I lack some knowledge. Read lots of infos and examples in internet, but it doesn't help: [Understanding the "underlying C/C++ object has been deleted" error](http://stackoverflow.com/questions/6002895/understanding-the- underlying-c-c-object-has-been-deleted-error) * * * Ok, here what I do: I create central widget from my _main.py_ , which works fine and I don't post it here fully: self.rw = ReportWidget() self.setCentralWidget(self.rw) And here is my central widget - _report.py_ : #! /usr/bin/env python # -*- coding: utf-8 -*- from PyQt4 import QtGui, QtCore class ReportWidget(QtGui.QWidget): def __init__(self, parent=None): super(ReportWidget, self).__init__(parent) self.setup_ui() def setup_ui(self): report = QtGui.QVBoxLayout(self) report.setAlignment(QtCore.Qt.AlignTop) head = QtGui.QHBoxLayout() add_label = QtGui.QLabel(u"Add") head.addWidget(add_label) report.addLayout(head) area = QtGui.QScrollArea() area.setWidgetResizable(True) area.setEnabled(True) layout = QtGui.QVBoxLayout() layout.setAlignment(QtCore.Qt.AlignTop) widget = QtGui.QWidget() widget.setLayout(layout) area.setWidget(widget) report.addWidget(area) self.s = layout # trying to create first line: first_line = Line(self) self.s.addWidget(first_line) first_line.set_controls(True, False) head = QtGui.QHBoxLayout() ok = QtGui.QPushButton(u"Calculate") head.addWidget(ok) report.addLayout(head) Continued from the same file _report.py_ : class Line(QtGui.QWidget): def __init__(self, parent=None): super(Line, self).__init__(parent) self.setup_ui(parent) def setup_ui(self, parent): add_button = QtGui.QPushButton() add_button.setObjectName("add_button") self.add_button = add_button self.layout = QtGui.QHBoxLayout(line) self.layout.addWidget(add_button) def set_controls(self, add_button=True, remove_button=True): self.add_button.setEnabled(add_button) Thus, running _main.py_ raises `RuntimeError: underlying C/C++ object has been deleted` error on the last piece of code where I try to `setEnabled` parameter to new button, as if it was never created or bound anywhere. It seems I have some design flaw. Maybe it's wrong idea to have different classes in one file or else? Or maybe I don't quite control which widget has which parent and how layouts work. * * * Thank you for reading. Have a nice day! Answer: Thanks to everyone who tried to answer! Unfortunately no one said what a bunch of crap I wrote! *smile* My `line` is already a widget and I don't need to create itself inside itself. All I had to do is to create layout inside `setup_ui` and add widgets to it. Finally it looks like: class Line(QtGui.QWidget): def __init__(self, parent=None): super(Line, self).__init__(parent) self.setup_ui(parent) def setup_ui(self, parent): line = QtGui.QHBoxLayout(self) add_button = QtGui.QPushButton() add_button.setObjectName("add_button") line.addWidget(add_button) # to get reference from outside self.add_button = add_button def set_controls(self, add_button=True, remove_button=True): self.add_button.setEnabled(add_button) Special thanks to [nymk](http://stackoverflow.com/users/779412/nymk) and [Avaris](http://stackoverflow.com/users/843822/avaris)!
Python - sort wrt second argument Question: I have a list, which I wish to sort. List is made of items with two elements each. I wish to sort wrt to second element only. Thus, I am almost sure that L = [[4,2],[5,2]] sorted(L) won't do the job. How to proceed? I come through answers but did not understand what could apply to problem. Thansk! Answer: from operator import itemgetter sorted(L, key=itemgetter(1)) Returns the sorted list `L`, sorted by `key` the second item in each element of `L`.
Python - how to check system load? Question: I am writing a script to check if the given urls are proper and resolve an IP. I'd like to fasten things up so I decided to put it into multiple threads. However, I want to make sure that the scripts does not overload the server it runs on. The question is: how can I check system load in the script? Or is there some way to determine how much threads can be run simultanously? Answer: As suggested in [this answer](http://stackoverflow.com/a/4153901/616317) maybe using: >>> import os >>> os.getloadavg() (0.66, 0.69, 0.58) It's more what you're looking for since that's the server load, not just the cpu usage.
Using python modules in node.js Question: Is it possible to create a glue that makes it possible for python modules (more specifically, library bindings) to be used in node.js? Some of the data structures can be directly mapped to V8 objects - e.g. array, dict. More importantly - would that be a more elegant way to create bindings than manually or through FFI. In short, would it be worth it? Answer: Try this node.js module, that is a bridge: [Node- Python](https://npmjs.org/package/node-python),
Embedded python module import errors Question: Here's a simplest of simple python interpreter in C. What I want to is to use .py files as a scripting language for engine hardcoded in C - running this code (with python27.dll/lib) runs fine on machine with python. #pragma comment(lib,"python27.lib") #include <Python27/Python.h> static PyObject* emb_numargs(PyObject *self, PyObject *args) { if(!PyArg_ParseTuple(args, ":numargs")) return NULL; return Py_BuildValue("i", 1); } static PyMethodDef EmbMethods[] = { {"numargs", emb_numargs, METH_VARARGS, "Return 1 you dumb person."}, {NULL, NULL, 0, NULL} }; int main(int argc, char *argv[]) { FILE *fp; Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); { int i; PyObject* sys = PyImport_ImportModule("sys"); PyObject* path = PyObject_GetAttrString(sys, "path"); // Add current project path to sys.path PyList_Append(path, PyString_FromString(".")); for (i = 0; i < PyList_Size(path); i++) { PyString_AsString(PyList_GetItem(path, i)); } Py_DECREF(sys); } Py_InitModule("emb", EmbMethods); fp = fopen("a.py", "r"); PyRun_SimpleFile(fp, "a.py"); Py_Finalize(); system("pause"); return 0; } (a.py is just calling emb.numargs) Problem is, when I port the executable to a computer without python installed, I get that ImportError : No Module named site. There were some advice about setting PYTHONPATH and like, but id doesn't work. What am I doing wrong? Answer: Okay, I found the problem lied with having to distribute the Lib folder from python main folder along with the executable
Scipy map_coordinates bilinear interpolation compared to interp and IDL interpolate Question: I'm in the process of rewriting a coworkers IDL code into python and am coming up with some differences that I'm confused about. According to other SO questions and mailing list threads I've found if you use `scipy.ndimage.interpolation.map_coordinates` and specify `order=1` it is supposed to do bilinear interpolation. When comparing results between the IDL code (run in GDL) and python (map_coordinates) I got different results. Then I tried using `mpl_toolkits.basemap.interp` and I got the same result as the IDL code. Below is a simple example that shows what is wrong. Could someone help me figure out what I am doing wrong with `map_coordinates` or is `order=1` not bilinear? from scipy.ndimage.interpolation import map_coordinates from mpl_toolkits.basemap import interp import numpy in_data = numpy.array([[ 25.89125824, 25.88840675],[ 25.90930748, 25.90640068]], dtype=numpy.float32) map_coordinates(in_data, [[0.0],[0.125]], order=1, mode='nearest') # map_coordinates results in "25.89090157" interp(in_data, numpy.array([0,1]), numpy.array([0,1]), numpy.array([0.0]), numpy.array([0.125]), order=1) # interp results in "25.89351439", same as GDL's "25.8935" when printed I am perfectly fine using `interp`, but I was curious why `map_coordinates` didn't return the same result. I noticed that the `map_coordinates` documentation doesn't mention bilinear, is it actually bilinear? What am I missing? Answer: When use `map_coordinates`, you need transpose the array or change you coordinates to (y, x) format, because the shape of the array is `(height, width)`. from scipy.ndimage.interpolation import map_coordinates from mpl_toolkits.basemap import interp import numpy in_data = numpy.array([[ 25.89125824, 25.88840675],[ 25.90930748, 25.90640068]], dtype=numpy.float32) print map_coordinates(in_data.T, [[0.0],[0.125]], order=1, mode='nearest') print interp(in_data, numpy.array([0,1]), numpy.array([0,1]), numpy.array([0.0]), numpy.array([0.125]), order=1) This will output: [ 25.89351463] [ 25.89351439]
How to run a python script with options Question: I'm looking for an efficient way to write a python script that can be called using the hyphen-single-letter-space-parameter convention (e.g. `python script.py -f /filename -t type -n 27`, where `f`, `t`, and `n` are the single letters corresponding to option types and `/filename`, `type`, and `27` are their values). I am aware of the `sys` library and its `sys.argv` function as a means of grabbing the space-delimited strings following the call (see [call program with arguments](http://stackoverflow.com/questions/3316961/call- program-with-arguments/3317004#3317004)), but is there a sophisticated way to process these strings when they follow the convention mentioned above? Answer: You want the [`argparse` module](http://docs.python.org/2/library/argparse.html#module-argparse) in the python standard library. The argparse module contains an `ArgumentParser` class which you can use to parse the arguments provided by `sys.argv` Usage example: import argparse import sys parser = argparse.ArgumentParser(description="Does some awesome things.") parser.add_argument('message', type=str, help="pass a message into the script") if __name__ == '__main__': args = parser.parse_args(sys.argv[1:]) print args.message For more details, such as how to incorporate optional, default, and multiple arguments, [see the documentation](http://docs.python.org/2/library/argparse.html#module- argparse).
Are there Python code for Scalar Multiplication, Dot Product, Norm (length) without using external library, function? Question: Here vectors are used as Python tuples. Like the vector `[3;1;1]` is represented in Python as `(3,2,1)`. 1. Write a Python function sca(s,v) that takes 2 arguments: Scalar s and vector v. The function should find result of multiplying the vector by the scalar. sca(3, (1,2,3)) # Returns (3,6,9) Answer may not import any modules or employ any external library functions. Answer: There are no builtin functions specifically for this purpose - you will have to write `sca(s, v)` yourself as the question states. The good news is that as long as you are familiar with the mathematical definition of scalar multiplication, this can be implemented in a very short amount of code (4 lines, 1 with some knowledge of Python's more advanced features). Think about how to write that definition in terms of the components of the vector, instead of the entire vector and then think about how to write that in Python.
Read .net pajek file using python igraph library Question: I am trying to load a .net file using python igraph library. Here is the sample code: import igraph g = igraph.read("s.net",format="pajek") But when I tried to run this script I got the following errors: Traceback (most recent call last): File "demo.py", line 2, in <module> g = igraph.read('s.net',format="pajek") File "C:\Python27\lib\site-packages\igraph\__init__.py", line 3703, in read return Graph.Read(filename, *args, **kwds) File "C:\Python27\lib\site-packages\igraph\__init__.py", line 2062, in Read return reader(f, *args, **kwds) igraph._igraph.InternalError: Error at .\src\foreign.c:574: Parse error in Pajek file, line 1 (syntax error, unexpected ARCSLINE, expecting VERTICESLINE), Parse error Kindly provide some hint over it. Answer: Either your file is not a regular Pajek file or igraph's Pajek parser is not able to read this particular Pajek file. (Writing a Pajek parser is a bit of hit-and-miss since the Pajek file format has no formal specification). If you send me your Pajek file via email, I'll take a look at it. **Update** : you were missing the `*Vertices` section of the Pajek file. Adding a line like `*Vertices N` (where `N` is the number of vertices in the graph) resolves your problem. I cannot state that this line is mandatory in Pajek files because of lack of formal specification for the file format, but all the Pajek files I have seen so far included this line so I guess it's pretty standard.
python: select a sublist with a list length limit Question: > players = [ a long list of (id, float) tuples with each id unique, order by > highest float] > > on_teams = [ a list of unique ids, every on_teams id is also in the players > list] picked = set(on_teams) best_remaining = [] for best_player in players: if best_player[0] not in picked: best_remaining.append(best_player) if len(best_remaining) == 5: break When I use six lines of code to do a simple thing, such as "get the five best remaining players", I wonder if there isn't a more elegant, pythonic solution. It's a simple problem, no doubt, but is there a better way to code it? UPDATE: My code run 100,000 times, runs in 0.24 secs. When I run: best_remaining = [(id, float) for id, float in players if id not in picked][:5] The code runs in 4.61 secs (100,000x). So the code looks and scans nicer, but it create the whole list then slices it. So now my question is a little different. With speed as a constraint, is there a better way to code up the search for the '5 best remaining players`? UPDATE: best_remaining = list(islice((p for p in players if p[0] not in picked), 5)) This code runs trivially longer than my code. To me at least, it has the value of a list comprehension. And best of all, it shows me a good place to work on my code habits. Thanks Answer: Use a generator, and then `islice` it to a max of 5 results... from itertools import islice picked = set(on_teams) players = list(islice((p for p in players if p[0] not in picked), 5))