Q_CreationDate
stringlengths
23
23
Title
stringlengths
11
149
Question
stringlengths
25
6.53k
Answer
stringlengths
15
5.1k
Score
float64
-1
1.2
Is_accepted
bool
2 classes
N_answers
int64
1
17
Q_Id
int64
0
6.76k
2010-11-24 06:35:49.397
How to see generated source from an URL page with python script and not anly source?
I have some url to parse, and they used some javascript to create it dynamicly. So if i want to parse the result generated page with python... how can i do that ? Firefox do that well with web developer... so i think it possible ... but i don't know where to start... Thx for help lo
I've done this by doing a POST of document.body.innerHTML, after the page is loaded, to a CGI script in Python. For the parsing, BeautifulSoup is a good choice.
1.2
true
2
928
2010-11-24 15:19:24.357
Gtk loop or Cron for timer
Well, I have created a python script, which checks the number of uncompleted tasks of tasque and displays it using pynotify periodically. My question is how do I implement this timer. I can think of two things. A Cron job to execute a python script periodically or using a python script which uses a gtk loop to call the specified function for checking periodically.
Cron job. It's more likely to be "in line" with actual time, since it's a more stable and time-tested choice. It's also less demanding on resources than using a loop in Python since it doesn't require a constant Python interpreter process, and is probably better optimized than pyGTK (choice is mature, stable software vs. less mature, less stable).
1.2
true
1
929
2010-11-28 22:15:04.157
In Tkinter how do i remove focus from a widget?
I'd like to remove focus from a widget manually.
Set focus to another widget to remove focus from the target widget is a good idea. There are two methods for this: w.focus_set() and w.focus_force(). However, method w.focus_force() is impolite. It's better to wait for the window manager to give you the focus. Setting focus to parent widget or to the root window removes focus from the target widget. Some widgets have takefocus option. Set takefocus to 0 to take your widget out of focus traversal (when user hits <Tab> key).
0.327599
false
2
930
2010-11-28 22:15:04.157
In Tkinter how do i remove focus from a widget?
I'd like to remove focus from a widget manually.
My solution is root.focus() it will remove widget focus.
0.135221
false
2
930
2010-11-29 12:49:31.810
3d game with Python, starting from nothing
So we want to program a 3d game for school, we can probably use blender for the 3d models, however we are totally clueless as to how to use them in a game/application. Are there any recommended guides/documents we should read on general 3d game programming and perhaps python specific stuff. We are also possibly considering programming it in C++ but for now I think it's easier to use Python as we can fully focus on the 3d mechanics that way.
I would implement the time-critical stuff as 3D and its object handling + rendering in raw C/C++ and let an embedded Python with external modules handle the game logic (object movement, object properties, scripting and so on).
0
false
3
931
2010-11-29 12:49:31.810
3d game with Python, starting from nothing
So we want to program a 3d game for school, we can probably use blender for the 3d models, however we are totally clueless as to how to use them in a game/application. Are there any recommended guides/documents we should read on general 3d game programming and perhaps python specific stuff. We are also possibly considering programming it in C++ but for now I think it's easier to use Python as we can fully focus on the 3d mechanics that way.
If you want to write a 3D game you might want to start by understanding the basics of programming and computer science. Starting with the top and learning a language, then find yourself a good graphics library for example Panda, Pygame are all good choices, then there are other parts to consider like networking with twisted for example or a physics engine. It might also be a good choice to consider using a working engine like the unreal engine as often game designers get too wrapped up in game mechanics and not the game itself
0.101688
false
3
931
2010-11-29 12:49:31.810
3d game with Python, starting from nothing
So we want to program a 3d game for school, we can probably use blender for the 3d models, however we are totally clueless as to how to use them in a game/application. Are there any recommended guides/documents we should read on general 3d game programming and perhaps python specific stuff. We are also possibly considering programming it in C++ but for now I think it's easier to use Python as we can fully focus on the 3d mechanics that way.
You should be aware that 3D game consists of animated 3D models 3D environment (including NPCs and objects) simulation of interaction between the environment and the models (game logic and game mechanics) user interface (starting, saving and game settings) The game logic and mechanics is going to usually the biggest and most complicated part and you should try to wrap your head against that first. Modeling 3D objects and environment should be much easier after that.
0.101688
false
3
931
2010-11-29 12:54:23.433
How can i access the current user outside a request in django
I'm working on a medium sized project in django and i want to be able to access the current user from within my query manager. I need to be able to design a custom manager to limit the results and querysets so that the current user only get's information related to him/her. I've received a few suggestions, I've also seen the not so supported example of using threadlocals from a django middleware. However, i'm very confused as this seems to be most promising solution now. I am looking for a better way to do this, so i can gain access to the current user from within a model manager.
There is no sane way to get the user outside of the request. If the current user matters then pass it to any functions that need it.
0.545705
false
1
932
2010-12-01 08:45:49.970
How to get started with Big Data Analysis
I've been a long time user of R and have recently started working with Python. Using conventional RDBMS systems for data warehousing, and R/Python for number-crunching, I feel the need now to get my hands dirty with Big Data Analysis. I'd like to know how to get started with Big Data crunching. - How to start simple with Map/Reduce and the use of Hadoop How can I leverage my skills in R and Python to get started with Big Data analysis. Using the Python Disco project for example. Using the RHIPE package and finding toy datasets and problem areas. Finding the right information to allow me to decide if I need to move to NoSQL from RDBMS type databases All in all, I'd like to know how to start small and gradually build up my skills and know-how in Big Data Analysis. Thank you for your suggestions and recommendations. I apologize for the generic nature of this query, but I'm looking to gain more perspective regarding this topic. Harsh
Using the Python Disco project for example. Good. Play with that. Using the RHIPE package and finding toy datasets and problem areas. Fine. Play with that, too. Don't sweat finding "big" datasets. Even small datasets present very interesting problems. Indeed, any dataset is a starting-off point. I once built a small star-schema to analyze the $60M budget of an organization. The source data was in spreadsheets, and essentially incomprehensible. So I unloaded it into a star schema and wrote several analytical programs in Python to create simplified reports of the relevant numbers. Finding the right information to allow me to decide if I need to move to NoSQL from RDBMS type databases This is easy. First, get a book on data warehousing (Ralph Kimball's The Data Warehouse Toolkit) for example. Second, study the "Star Schema" carefully -- particularly all the variants and special cases that Kimball explains (in depth) Third, realize the following: SQL is for Updates and Transactions. When doing "analytical" processing (big or small) there's almost no update of any kind. SQL (and related normalization) don't really matter much any more. Kimball's point (and others, too) is that most of your data warehouse is not in SQL, it's in simple Flat Files. A data mart (for ad-hoc, slice-and-dice analysis) may be in a relational database to permit easy, flexible processing with SQL. So the "decision" is trivial. If it's transactional ("OLTP") it must be in a Relational or OO DB. If it's analytical ("OLAP") it doesn't require SQL except for slice-and-dice analytics; and even then the DB is loaded from the official files as needed.
1.2
true
1
933
2010-12-01 14:10:30.557
Extracting Date and Time info from a string.
I have a database full of data, including a date and time string, e.g. Tue, 21 Sep 2010 14:16:17 +0000 What I would like to be able to do is extract various documents (records) from the database based on the time contained within the date string, Tue, 21 Sep 2010 14:16:17 +0000. From the above date string, how would I use python and regex to extract documents that have the time 15:00:00? I'm using MongoDB by the way, in conjunction with Python.
I agree with the other poster. Though this doesn't solve your immediate problem, if you have any control over the database, you should seriously consider creating a time/column, with either a DATE or TIMESTAMP datatype. That would make your system much more robust, & completely avoid the problem of trying to parse dates from string (an inherently fragile technique).
0.101688
false
1
934
2010-12-01 21:28:23.443
how to install a python package to windows?
I would like to install a python package to windows. I have tried to run setup.py install on command prompt but it returned an error: could not create 'C:\Program Files\Python...': access is denied. Please, help. Špela
My first question would be, do you have administration rights when you try to run setup.py?
0.673066
false
1
935
2010-12-02 00:31:55.600
python unicode support
I'm trying to figure out how to use the unicode support in python; I would like to convert this string to unicode : "ABCDE" --> "\x00A\x00B\x00C\x00D\x00E" Any built-in functionnality can do that, or shall i use join() ? Thanks !
The key to understanding unicode in python is that unicode means UNICODE. A unicode object is an idealized representation to the characters, not actual bytes.
0.265586
false
2
936
2010-12-02 00:31:55.600
python unicode support
I'm trying to figure out how to use the unicode support in python; I would like to convert this string to unicode : "ABCDE" --> "\x00A\x00B\x00C\x00D\x00E" Any built-in functionnality can do that, or shall i use join() ? Thanks !
the str object should be firstly converted to unicode object by decode method. then convert the unicode object to str object using encode method with character-encoding you want.
0
false
2
936
2010-12-02 06:26:17.483
how to show mime data using python cgi in windows+apache
I met a problem while using python(2.6) cgi to show a mime data in windows(apache). For example, to show a image, here is my code: image.py #!E:/program files/Python26/python.exe # -*- coding: UTF-8 -*- data = open('logo.png','rb').read() print 'Content-Type:image/png;Content-Disposition:attachment;filename=logo.png\n' print data But it dose not work in windows(xp or 7)+apache or IIS. (I try to write these code in diferent way, and also try other file format, jpg and rar, but no correct output, the output data seems to be disorder in the begining lines.) And I test these code in linux+apache, and it is Ok! #!/usr/bin/env python # -*- coding: UTF-8 -*- data = open('logo.png','rb').read() print 'Content-Type:image/png;Content-Disposition:attachment;filename=logo.png\n' print data I just feel confused why it does not work in windows. Could anybody give me some help and advice?
Now I know how to solve this problem: For windows+IIS: While adding the application mapping(IIS), write C:\Python20\python.exe -u %s %s. I used to write like this c:\Python26\python.exe %s %s, that will create wrong mime data. And "-u" means unbuffered binary stdout and stderr. For windows+Apache: Add #!E:/program files/Python26/python.exe -u to the first line of the python script. Thank Ignacio Vazquez-Abrams all the same!
1.2
true
1
937
2010-12-02 10:05:48.543
What is the best practice for registering a new user in my case?
I am going to let new users register on my service. Here is the way I think it should go: 1. User enters his email in a field and clicks Register button. 2. User receives a confirmation email with a link containing a verification code. 3. User goes by that link from the email message where he sees a message that his account is activated now. So, the main point I am to figure out how to implement is the second one. How do I better generate that code? Should I generate it when the user clicks Register button and save it in the field, say "verification_code" near the field "email" and then when he goes to the verification link, compare the values? Then, if that's fine, clear the "verification_code" field and set "user_is_active" field to "True". Or may be I don't have to keep that code in the database at all, but make a just in time verification with some algorithm? May be there are other things I should consider?
I've found it useful to put a verification code in the database and use it as you've suggested. The same field can do double duty for e.g. password reset requests. I also use an expiry timeout field, where registrations or password resets need to be dealt with by the user in a timely fashion.
1.2
true
1
938
2010-12-02 17:11:11.110
Declaring types for complex data structures in python
I am quite new to python programming (C/C++ background). I'm writing code where I need to use complex data structures like dictionaries of dictionaries of lists. The issue is that when I must use these objects I barely remember their structure and so how to access them. This makes it difficult to resume working on code that was untouched for days. A very poor solution is to use comments for each variable, but that's very inflexible. So, given that python variables are just pointers to memory and they cannot be statically type-declared, is there any convention or rule that I could follow to ease complex data structures usage?
Include an example somewhere in your code, or in your tests.
0
false
2
939
2010-12-02 17:11:11.110
Declaring types for complex data structures in python
I am quite new to python programming (C/C++ background). I'm writing code where I need to use complex data structures like dictionaries of dictionaries of lists. The issue is that when I must use these objects I barely remember their structure and so how to access them. This makes it difficult to resume working on code that was untouched for days. A very poor solution is to use comments for each variable, but that's very inflexible. So, given that python variables are just pointers to memory and they cannot be statically type-declared, is there any convention or rule that I could follow to ease complex data structures usage?
I believe you should take a good look some of your complex structures, what you are doing with them, and ask... Is This Pythonic? Ask here on SO. I think you will find some cases where the complexity is an artifact of C/C++.
0.101688
false
2
939
2010-12-02 20:53:52.887
ARP missing from the module scapy
i am trying to use scapy in python while i try to import the scapy import scapy its just fine but the line scapy.ARP() causes a Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'ARP' a dir(scapy) produces '['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']' what might be the problem here ? do i need to install the packages separately if yes how to do it ?
got it , from the version v.2 onward the it should be used as from scapy.all import *
1.2
true
1
940
2010-12-03 12:04:51.757
Python Imaging, how to quantize an image to 16bit depth?
I would like to quantize a 24bit image to 16bit color depth using Python Imaging. PIL used to provide a method im.quantize(colors, **options) however this has been deprecated for out = im.convert("P", palette=Image.ADAPTIVE, colors=256) Unfortunately 256 is the MAXIMUM number of colors that im.convert() will quantize to (8 bit only). How can I quantize a 24bit image down to 16bit using PIL (or similar)? thanks
You might want to look into converting your image to a numpy array, performing your quantisation, then converting back to PIL. There are modules in numpy to convert to/from PIL images.
1.2
true
1
941
2010-12-03 17:15:46.817
How to use python urllib2 to send json data for login
I want to use python urllib2 to simulate a login action, I use Fiddler to catch the packets and got that the login action is just an ajax request and the username and password is sent as json data, but I have no idea how to use urllib2 to send json data, help...
For Python 3.x Note the following In Python 3.x the urllib and urllib2 modules have been combined. The module is named urllib. So, remember that urllib in Python 2.x and urllib in Python 3.x are DIFFERENT modules. The POST data for urllib.request.Request in Python 3 does NOT accept a string (str) -- you have to pass a bytes object (or an iterable of bytes) Example pass json data with POST in Python 3.x import urllib.request import json json_dict = { 'name': 'some name', 'value': 'some value' } # convert json_dict to JSON json_data = json.dumps(json_dict) # convert str to bytes (ensure encoding is OK) post_data = json_data.encode('utf-8') # we should also say the JSON content type header headers = {} headers['Content-Type'] = 'application/json' # now do the request for a url req = urllib.request.Request(url, post_data, headers) # send the request res = urllib.request.urlopen(req) # res is a file-like object # ... Finally note that you can ONLY send a POST request if you have SOME data to send. If you want to do an HTTP POST without sending any data, you should send an empty dict as data. data_dict = {} post_data = json.dumps(data_dict).encode() req = urllib.request.Request(url, post_data) res = urllib.request.urlopen(req)
0.999945
false
1
942
2010-12-03 18:30:41.187
How to create tables in sqlite 3?
I just downloaded sqlite3.exe. It opens up as a command prompt. I created a table test & inserted a few entries in it. I used .backup test just in case. After I exit the program using .exit and reopened it I don't find the table listed under .tables nor can I run any query on it. I need to quickly run an open source python program that makes use of this table & although I have worked with MySQL, I have no clue about sqlite. I need the minimal basics of sqlite. Can someone guide me through this or at least tell me how to permanently store my tables. I have put this sqlite3.exe in Python folder assuming that python would then be able to read the sqlite files. Any ideas on this?
Just execute sqlite3 foo.db? This will permanently store everything you do afterwards in this file. (No need for .backup.)
0
false
1
943
2010-12-03 20:46:45.010
How is a Python project set up?
I am doing some heavy commandline stuff (not really web based) and am new to Python, so I was wondering how to set up my files/folders/etc. Are there "header" files where I can keep all the DB connection stuff? How/where do I define classes and objects?
You can organize it in whatever way makes the most sense for your application. I don't exactly know what you're doing so I can't be certain what the best organization would be for you, but you can pretty much split it up as you see fit and just import what you need. You can define classes in any file, and you can define as many classes as you would like in a script (unlike Java). There are no official header files (not like C or C++), but you can use config files to store info about connecting to a DB, whatever, and use configparser (a standard library function) to organize them. It makes sense to keep like things in the same file, so if you have a GUI, you might have one file for the interface, and if you have a CLI, you might keep that in a file by itself. It's less important how your files are organized and more important how the source is organized into classes and functions.
0
false
1
944
2010-12-04 10:08:05.110
In Python's PIL, how do I change the quality of an image?
I want to degrade the quality of the image to a few kilobytes. What's the best way to do this? Thanks!
a) change the size: Image.resize(size, filter) b) explicitly convert it to JPEG (if it is not) and set the desired quality. c) use a combination of a) and b) Whatever you do, there is a trade-off between size and quality.
0.101688
false
1
945
2010-12-04 22:43:28.443
how to create a user interface that a user can signup and login using django
i love gae(google app engine),because it is easy to create a user interface for user login and signup, but now , my boss want me to create a site use django , so the first is to create a site that someone can be login , which is the esaist way to create a user interface ? thanks
Django auth also provide generic views for login/logout etc. You can use build-in templates or expand it. See in documentation for generic views: django.contrib.auth.views.login, django.contrib.auth.views.logout
0.201295
false
1
946
2010-12-06 03:20:41.123
Why don't django templates just use python code?
I mean I understand that these templates are aimed at designers and other less code-savvy people, but for developers I feel the template language is just a hassle. I need to re-learn how to do very simple things like iterate through dictionaries or lists that I pass into the template, and it doesn't even seem to work very well. I'm still having trouble getting the whole "dot" notation working as I would expect (for example, {{mydict.dictkey}} inside a for loop doesn't work :S -- I might ask this as a separate question), and I don't see why it wouldn't be possible to just use python code in a template system. In particular, I feel that if templates are meant to be simple, then the level of python code that would need to be employed in these templates would be of a caliber not more complicated than the current templating language. So these designer peeps wouldn't have more trouble learning that much python than they would learning the Django template language (and there's more places you can go with this knowledge of basic python as opposed to DTL) And the added advantage would be that people who already know python would be in familiar territory with all the usual syntax and power available to them and can just get going. Am I missing something? If so I plead django noob and would love for you to enlighten me on the many merits of the current system. But otherwise, any recommendations on other template systems that may be more what I'm looking for?
Don't forget that you aren't limited to Django's template language. You're free to use whatever templating system you like in your view functions. However you want to create the HTML to return from your view function is fine. There are many templating implementations in the Python world: choose one that suits you better, and use it.
0.201295
false
3
947
2010-12-06 03:20:41.123
Why don't django templates just use python code?
I mean I understand that these templates are aimed at designers and other less code-savvy people, but for developers I feel the template language is just a hassle. I need to re-learn how to do very simple things like iterate through dictionaries or lists that I pass into the template, and it doesn't even seem to work very well. I'm still having trouble getting the whole "dot" notation working as I would expect (for example, {{mydict.dictkey}} inside a for loop doesn't work :S -- I might ask this as a separate question), and I don't see why it wouldn't be possible to just use python code in a template system. In particular, I feel that if templates are meant to be simple, then the level of python code that would need to be employed in these templates would be of a caliber not more complicated than the current templating language. So these designer peeps wouldn't have more trouble learning that much python than they would learning the Django template language (and there's more places you can go with this knowledge of basic python as opposed to DTL) And the added advantage would be that people who already know python would be in familiar territory with all the usual syntax and power available to them and can just get going. Am I missing something? If so I plead django noob and would love for you to enlighten me on the many merits of the current system. But otherwise, any recommendations on other template systems that may be more what I'm looking for?
Django templates don’t just use Python code for the same reason Django uses the MVC paradigm:     No particular reason.     (ie: The same reason anyone utilizes MVC at all, and that reason is just that certain people prefer this rigid philosophical pattern.) In general I’d suggest you avoid Django if you don’t like things like this, because the Django people won’t be changing this approach. You could also, however, do something silly (in that it’d be contradictory to the philosophy of the chosen software), like put all the markup and anything else you can into the "view" files, turning Django from its "MVC" (or "MTV" ) paradigm into roughly what everything else is (a boring but straightforward lump).
0.101688
false
3
947
2010-12-06 03:20:41.123
Why don't django templates just use python code?
I mean I understand that these templates are aimed at designers and other less code-savvy people, but for developers I feel the template language is just a hassle. I need to re-learn how to do very simple things like iterate through dictionaries or lists that I pass into the template, and it doesn't even seem to work very well. I'm still having trouble getting the whole "dot" notation working as I would expect (for example, {{mydict.dictkey}} inside a for loop doesn't work :S -- I might ask this as a separate question), and I don't see why it wouldn't be possible to just use python code in a template system. In particular, I feel that if templates are meant to be simple, then the level of python code that would need to be employed in these templates would be of a caliber not more complicated than the current templating language. So these designer peeps wouldn't have more trouble learning that much python than they would learning the Django template language (and there's more places you can go with this knowledge of basic python as opposed to DTL) And the added advantage would be that people who already know python would be in familiar territory with all the usual syntax and power available to them and can just get going. Am I missing something? If so I plead django noob and would love for you to enlighten me on the many merits of the current system. But otherwise, any recommendations on other template systems that may be more what I'm looking for?
Seperation of concerns. Designer does design. Developer does development. Templates are written by the designers. Design and development are independent and different areas of work typically handled by different people. I guess having template code in python would work very well if one is a developer and their spouse is a designer. Otherwise, let each do his job, with least interference.
0.101688
false
3
947
2010-12-07 16:42:51.677
Download Manager: How to re-construct chunks fetched by multiple connections
so i am developing my own download manager for educational purpose. I have multiple connections/threads downloading a file, each connection works on a particular range of the file. Now after they have all fetched their chunks, i dont exact know how to i bring this chunks together to re-make the original file. What i did: First, i created a temporary file in 'wb' mode, and allowed each connections/threads to dump their chunks. But everytime a connection does this, it overwrites previously saved chunks. I figured this was because i used the 'wb' file descriptor. I changed it to 'ab', but i can no longer perform seek() operations What i am looking for: I need an elegant way of re-packaging this chunk to the original file. I would like to know how other download managers do it. Thank in advance.
You need to write chunks it different temporary files and then join them in the original order. If you open one file for all the threads, you should make the access to it sequential to preserve to correct order of data, which discards thread usage since a thread should wait for the previous one. BTW, you should open files in wb mode.
0.386912
false
2
948
2010-12-07 16:42:51.677
Download Manager: How to re-construct chunks fetched by multiple connections
so i am developing my own download manager for educational purpose. I have multiple connections/threads downloading a file, each connection works on a particular range of the file. Now after they have all fetched their chunks, i dont exact know how to i bring this chunks together to re-make the original file. What i did: First, i created a temporary file in 'wb' mode, and allowed each connections/threads to dump their chunks. But everytime a connection does this, it overwrites previously saved chunks. I figured this was because i used the 'wb' file descriptor. I changed it to 'ab', but i can no longer perform seek() operations What i am looking for: I need an elegant way of re-packaging this chunk to the original file. I would like to know how other download managers do it. Thank in advance.
You were doing it just fine: seek() and write(). That should work! Now, if you want a cleaner structure, without so many threads moving their hands all over a file, you might want to consider having downloader threads and a disk-writing thread. This last one may just sleep until woken by one of the others, write some kb to disk, and go back to sleep.
1.2
true
2
948
2010-12-07 16:46:51.507
how to bring a background task to foreground in google app engine?
Currently I have tasks running in background. After the tasks are done executing I need to show output. How do I do this in Google App Engine? Once the tasks are done the only thing I can do is create another task which is supposed to show output or is there any other way?
This won't work directly as you describe it. Once a background task is started, it's a background task for its entire existence. If you want to return some information from the background task to the user, you'll have to add it to the datastore, and have a foreground handler check the datastore for that information. You may also be able to use the Channel API to have a background task send messages directly to the browser, but I'm not sure if this will work or not (I haven't tried it). If you give a little more information about exactly what you're trying to accomplish I can try to give more details about how to get it done.
0
false
1
949
2010-12-08 02:15:20.790
(Py)GTK: How can I force my window to be repainted / call expose-event?
Currently I'm drawing some things in a subclass of DrawingArea, where I get a cairo context inside an expose-event and call a draw method from there. (according to some PyGTK tutorial I found) I'm used to doing a repaint() with java, but how can I get the same effect here?
I found a solution that uses the queue_draw() method (callable from the Gtk.DrawingArea but seems like a method every gtk widget must have), but there are probably alternatives since this one implies it might get delayed, even though in my tests it didn't happen.
0
false
1
950
2010-12-09 19:58:46.997
How do you avoid leaving debugger print/pdb statements in python open source apps when you're debugging them and just finish?
Sometimes when developing using open source software, you need to read it's source code (specially zope/plone). A lot of times I need to write print statements, or debug calls (import pdb), or comment try/except clauses, you name it. Sometimes I have a lot of files opened when trying to find an issue, and sometimes I forget to remove these print/debug alterations. So, my question is: how do you keep yourself organized when doing it? Do you write "TODOs" along the modifications and search for them later, do you keep everything opened in your editor and when you find what you were looking for you just revert the files (This approach isn't useful when you're searching for a really big problem that needs days, you need to turn off your computer and return the other day)? Or you just don't do nothing since print statements in development environment is nothing to worry about? I'm using Vim. I'm just interested to know how other programmers treat this issue.
In case of my own projects, the source code is always in version control. Before committing, I always check the graphical diff so that I can see what has changed, what the commit message should be and whether I can split up into smaller commits. That way, I almost always recognize temporary garbage like print statements. If not, I usually notice it shortly afterwards and can do an uncommit if I haven't yet pushed (works for DVCS like git and bzr, not with subversion). Concerning problems that take multiple days, it's just the same thing. I don't commit until the problem is solved and then look at the diff again. A text editor that allows editing within the graphical diff view would be really helpful in these cases, but I'm mostly using Eclipse, which doesn't support that.
0.3154
false
3
951
2010-12-09 19:58:46.997
How do you avoid leaving debugger print/pdb statements in python open source apps when you're debugging them and just finish?
Sometimes when developing using open source software, you need to read it's source code (specially zope/plone). A lot of times I need to write print statements, or debug calls (import pdb), or comment try/except clauses, you name it. Sometimes I have a lot of files opened when trying to find an issue, and sometimes I forget to remove these print/debug alterations. So, my question is: how do you keep yourself organized when doing it? Do you write "TODOs" along the modifications and search for them later, do you keep everything opened in your editor and when you find what you were looking for you just revert the files (This approach isn't useful when you're searching for a really big problem that needs days, you need to turn off your computer and return the other day)? Or you just don't do nothing since print statements in development environment is nothing to worry about? I'm using Vim. I'm just interested to know how other programmers treat this issue.
I also develop Python with Vim. I have never had to substantially modify the source code for debugging. I do sometimes put debugging print statements, and I have the habit of putting "# XXX" after every one. Then when I want to remove them (before a commit), and just search for the XXX and delete those lines. For exceptions, I have arranged to run my code in the Vim buffer with an external interpreter that is set up to automatically enter the debugger on any uncaught exception. Then I'm placed automatically in the code at the point the exception occured. I use a modified debugger that can also signal Vim (actually GTK Gvim) to open that source at that line. Caught exceptions should report meaningful errors, anyway. It is considered by many to be bad practice to do things like: try: ... some code except: handle everything Since you probably aren't actually handling every possible error case. By not doing that you also enable the automatic debugging.
0.081452
false
3
951
2010-12-09 19:58:46.997
How do you avoid leaving debugger print/pdb statements in python open source apps when you're debugging them and just finish?
Sometimes when developing using open source software, you need to read it's source code (specially zope/plone). A lot of times I need to write print statements, or debug calls (import pdb), or comment try/except clauses, you name it. Sometimes I have a lot of files opened when trying to find an issue, and sometimes I forget to remove these print/debug alterations. So, my question is: how do you keep yourself organized when doing it? Do you write "TODOs" along the modifications and search for them later, do you keep everything opened in your editor and when you find what you were looking for you just revert the files (This approach isn't useful when you're searching for a really big problem that needs days, you need to turn off your computer and return the other day)? Or you just don't do nothing since print statements in development environment is nothing to worry about? I'm using Vim. I'm just interested to know how other programmers treat this issue.
Well +1 for starting this discussion. Yes sometime this happen to me. I left those pdb and commit the code to the central code base, git. I use 'emacs'. So, Before commit the code I usually search for pdb in the file. But it is hectic checking each file.So, Before committing the code I usually check the diff very carefully. I am also finding the better way to resolve this issue.
0.16183
false
3
951
2010-12-11 01:07:46.273
Python, BaseHTTPRequestHandler: how to read what's available on file from socket?
I'm using Python's BaseHTTPRequestHandler class to build a web server. I want to add an endpoint for WebSockets. This means that I need to read whatever is available from the handler's rfile, so that I can process messages one by one, as I'm receiving them (instead of having to read the while input). I tried using different combinations of 'read' (eg. with a big buffer, thinking that it'd return early with less data if less data was available; with no parameter, but then it just means to read until EOF) but couldn't get this to work. I can think of two solutions: To call read(1): to read bytes one by one. I'd rather not do this, as I'm not sure what the buffering semantics are (eg. I wouldn't want a syscall per byte read). To temporally make the file non-blocking, then attempt a read for a chunk of data, then make it blocking, then attempt a read for 1 byte. This seems rather messy. Another option I can think of is to just use non-blocking sockets, but this wouldn't seem to work so well with my current threaded framework. Any ideas of how to get read to return whatever data is available?
WebSockets aren't HTTP, so you can't really handle them with an HTTP request handler. However, using BaseHTTPRequestHandler with HTTP, you would normally be reading only the exact amount of data you expect (for instance, as specified in the Content-length header.)
0.386912
false
1
952
2010-12-11 12:17:05.983
Change background color of python shell
Is it possible to change background color of the Python Shell from white to black for example. I did find how to change text color, but can't figure out how to change background color. I'm running it under the Windows. Any suggestions?
just go through simple steps - go to options - configure IDLE - highlighting - then select background and click on choose color for: - you can change the color to any color but becareful if u change only the background color the foreground color may not be visible because they both might be black Enjoy
0.16183
false
3
953
2010-12-11 12:17:05.983
Change background color of python shell
Is it possible to change background color of the Python Shell from white to black for example. I did find how to change text color, but can't figure out how to change background color. I'm running it under the Windows. Any suggestions?
If you are reffering to the window idle for example for version 2.6 there is now way to change the background color from withe to another one. But you can change the background color of your text if you go to options. Another thing you can do is to use other gui for python which could be more elaborated such as eclipse pydev or to use a text editor you like and configure it the way you want to write your scripts and then run them into the idle.
0.16183
false
3
953
2010-12-11 12:17:05.983
Change background color of python shell
Is it possible to change background color of the Python Shell from white to black for example. I did find how to change text color, but can't figure out how to change background color. I'm running it under the Windows. Any suggestions?
You can,,go to options then configure IDE, then on the settings window select highlights, on the rightside press the button below a builtin theme, then choose your choice theme
-0.081452
false
3
953
2010-12-11 18:30:43.653
comparing batch to python commands?
Ok i have these commands used in batch and i wanted to know the commands in python that would have a similar affect, just to be clear i dont want to just use os.system("command here") for each of them. For example in batch if you wanted a list of commands you would type help but in python you would type help() and then modules... I am not trying to use batch in a python script, i just wanna know the similarities in both languages. Like in english you say " Hello" but in french you say "Bonjour" not mix the two languages. (heres the list of commands/functions id like to know: change the current directory clear the screen in the console change the prompt to something other than >>> how to make a loop function redirections/pipes start an exteral program (like notepad or paint) from within a script how to call or import another python script how to get help with a specific module without having to type help() @8: (in batch it would be command /?) EDITED COMPLETELY Thanks in Adnvance!
Python is not a system shell, Python is a multi-paradigm programming language. If you want to compare .bat with anything, compare it with sh or bash. (You can have those on various platforms too - for example, sh for windows is in the MinGW package).
0.081452
false
2
954
2010-12-11 18:30:43.653
comparing batch to python commands?
Ok i have these commands used in batch and i wanted to know the commands in python that would have a similar affect, just to be clear i dont want to just use os.system("command here") for each of them. For example in batch if you wanted a list of commands you would type help but in python you would type help() and then modules... I am not trying to use batch in a python script, i just wanna know the similarities in both languages. Like in english you say " Hello" but in french you say "Bonjour" not mix the two languages. (heres the list of commands/functions id like to know: change the current directory clear the screen in the console change the prompt to something other than >>> how to make a loop function redirections/pipes start an exteral program (like notepad or paint) from within a script how to call or import another python script how to get help with a specific module without having to type help() @8: (in batch it would be command /?) EDITED COMPLETELY Thanks in Adnvance!
I am pretty much facing the same problem as you, daniel11. As a solution, I am learning BATCH commands and their meaning. After I understand those, I am going to write a program in Python that does the same or accomplishes the same task. Thanks to Adam V. and katrielatex for their insight and suggestions.
0
false
2
954
2010-12-11 19:17:03.457
How to maintain order of paragraphs in a Django document revision system?
I'm having trouble figuring out how to best implement a document (paragraph-) revision system in Django. I want to save a revision history of a document, paragraph-by-paragraph. In other words, there will be a class Document, which has a ManyToManyField to Paragraph. To maintain the order of the paragraphs, a third class ParagraphContainer can be created. My question is, what is a good way to implement this in Django so that the order of paragraphs is maintained when someone adds a new paragraph in-between existing paragraphs? One obvious way would be to have a position attribute in the ParagraphContainer class, but then this field will have to be updated in all paragraphs following the inserted (or deleted) paragraph. A linked list is another option, but I'm scared that might be very slow for retrieval of the whole document. Any advice?
Editors often solve this problem with a Piece Table. The table is a list of objects that point to spans of characters that are a) contiguous in memory, and b) share common attributes. The order of the pieces in the table is used for mapping character-in-document addresses to memory and vice versa. By reordering the piece table you effectively reorder the document without moving anything around. The key point is that the piece table itself is independent of the objects that make up the content of the document. So one way of mapping your paragraph order would be to have a simplified version of a peice table. This could be as simple as a list of para-ids in document order. When you need to change something, you fetch the list, unpickle it, make you edits on the list, pickle and save. Another advantage of the table is that it greatly simplifies implementing undo. The history file is a simple list of edits to the table, and undoing/redoing is a matter of reversing or reapplying a particular edit to the table, the data itself doesn't change. This should play well with any versioning you want to do.
1.2
true
1
955
2010-12-11 20:40:14.770
WingIDE brace matching colours
Has anyone figured out a way to change the brace matching colours in WingIDE? I have managed to manually port my favourite colour scheme across from my text editor and the default green just doesn't do it for me. I've been unable to find instructions on how to do this in the UI, user manual and mailing lists.
I've contacted Wingware support and they have confirmed that there is no way to set the brace matching colour.
1.2
true
1
956
2010-12-12 17:35:00.617
How to find x in a string in Python
I was wondering how to go about finding a string you don't know what is, in a string. I am writing an IRC bot and i need this function. I want to be able to write: !greet Greg and then my bot is supposed to say "Hi, Greg!". So what comes after greet is variable. And if i wrote !greet Matthew it would say "Hi, Matthew!". Is this possible? Thanks a lot. Andesay
if "Greg" in greet: doSomething("Hi Greg") the key is that strings take the in operator
-0.081452
false
1
957
2010-12-13 15:10:53.330
python on win32: how to get absolute timing / CPU cycle-count
I have a python script that calls a USB-based data-acquisition C# dotnet executable. The main python script does many other things, e.g. it controls a stepper motor. We would like to check the relative timing of various operations, for that purpose the dotnet exe generates a log with timestamps from C# Stopwatch.GetTimestamp(), which as far as I know yields the same number as calls to win32 API QueryPerformanceCounter(). Now I would like to get similar numbers from the python script. time.clock() returns such values, unfortunately it subtracts the value obtained at the time of 1st call to time.clock(). How can I get around this? Is it easy to call QueryPerformanceCounter() from some existing python module or do I have to write my own python extension in C? I forgot to mention, the python WMI module by Tim Golden does this: wmi.WMI().Win32_PerfRawData_PerfOS_System()[0].Timestamp_PerfTime , but it is too slow, some 48ms overhead. I need something with <=1ms overhead. time.clock() seems to be fast enough, as is c# Stopwatch.GetTimestamp(). TIA, Radim
You could just call the C# StopWatch class directly from Python couldn't you? Maybe a small wrapper is needed (don't know Python/C# interop details - sorry) - if you are already using C# for data acquisition, doing the same for timings via Stopwatch should be simpler than anything else you can do.
0
false
1
958
2010-12-13 15:26:57.187
View Script Output Over SSH?
I have a script, called test.py, that does the following: while (1): ....print "hello world" (this script simply prints 'hello world' continuously). Now, I am using two machines (machine A and machine B). Same user is used for both machines. I would like to do the following: (1) [working with machine A] run test.py programatically on machine A { meaning, a local python script will be running test.py using say os.system(....) } ( at this point, the script test.py is printing "hello world" to the screen of machine A ) (2) [working with machine B] I now want to log in into machine A using ssh and 'view' the output of the script that we ran in (1) How do I achieve this? I know how to write the script that will be running and starting test.py on machine A. I also know how to ssh from machine B to machine A. What I don't know is: (*) What command should I use in (1) in order to run the python script so that its output can be easily viewed while logging from a different machine (machine B) to machine A? (*) Following the ssh from machine B to machine A, how do I 'navigate' to the screen that shows the output of test.py?
A very quick alternative is to pipe the output of your python program to a file, and then simply using tail with the second user to see the output as it's being written to the file. However, with a program like you have there, the file will very quickly become massive.
0.201295
false
1
959
2010-12-14 17:06:14.033
Best practice for running a daily Python screen-scraping script 50 times (8.3 minutes total) per user?
On the front-end, I have a PHP webapp that allows users to create a list of their websites (5 max). On the back-end, a Python script runs daily (and has ~10 iterations) for each website that the user registers. Each script per website takes about 10 seconds to run through all iterations and finish its scraping. It then makes a CSV file with its findings. So, in total, that's up to (5 websites * 10 iterations =) 50 iterations at 8.3 total minutes per user. Right now, the script works when I manually feed it a URL, so I'm wondering how to make it dynamically part of the webapp. How do I programmatically add and remove scripts that run daily depending on the number of users and the websites each user has each day? How would I schedule this script to run for each website of each user, passing in the appropriate parameters? I'm somewhat acquainted with cronjobs, as it's the only thing I know of that is made for routine processes.
Do you need to run the script 50 times per user, or only when the user has logged into your service to check on things?
0
false
2
960
2010-12-14 17:06:14.033
Best practice for running a daily Python screen-scraping script 50 times (8.3 minutes total) per user?
On the front-end, I have a PHP webapp that allows users to create a list of their websites (5 max). On the back-end, a Python script runs daily (and has ~10 iterations) for each website that the user registers. Each script per website takes about 10 seconds to run through all iterations and finish its scraping. It then makes a CSV file with its findings. So, in total, that's up to (5 websites * 10 iterations =) 50 iterations at 8.3 total minutes per user. Right now, the script works when I manually feed it a URL, so I'm wondering how to make it dynamically part of the webapp. How do I programmatically add and remove scripts that run daily depending on the number of users and the websites each user has each day? How would I schedule this script to run for each website of each user, passing in the appropriate parameters? I'm somewhat acquainted with cronjobs, as it's the only thing I know of that is made for routine processes.
Assuming you're using a database to store the users' web sites, you can have just 1 script that runs as a daily cron job and queries the database for the list of sites to process.
0
false
2
960
2010-12-15 14:50:29.110
Keyboard interface to wxPython listbox
I'm using a wxPython listbox on Windows to get a choice from the user, and I would like them to be able to select an item using the ENTER key, as if they had double-clicked. I know how to do this in C or C++ using the Windows API directly, but can't seem to find how to do it using wxPython. Anyone know how? It seems like an obvious thing to want to do.
The simple answer is that the wx.ListBox doesn't support that. Try using a one column wx.ListCtrl (in Report mode) instead.
0.135221
false
2
961
2010-12-15 14:50:29.110
Keyboard interface to wxPython listbox
I'm using a wxPython listbox on Windows to get a choice from the user, and I would like them to be able to select an item using the ENTER key, as if they had double-clicked. I know how to do this in C or C++ using the Windows API directly, but can't seem to find how to do it using wxPython. Anyone know how? It seems like an obvious thing to want to do.
Maybe I'm missing some nuance, there wasn't much info to go on, but it sounds like you could accomplish this by catching the keydown event, matching for enter and then calling your on_doubleclick function. Unless there's an implicit double-click handling you should be good to go.
0.135221
false
2
961
2010-12-16 01:14:58.910
Django: correct way to group a bunch of media's
I send several forms to a template, and I want to put all required media in the <head> tag. Some forms might require the same media (for instance, the same JS file), so I would like to unify all medias before putting them in the <head>. Question is, how do I do that? I know you can unify two medias by doing m1 + m2, but this will look ugly in the generic case where I have an unknown number of forms. Is there some shortcut?
What happens if you just use {{ form.media }} for each form, and link up the media in the form's Meta? I seem to remember that making sure that it didn't insert anything twice, but it's been a while. Have you tried that yet?
0
false
1
962
2010-12-16 08:24:28.850
How to get the list of all initialized objects and function definitions alive in python?
Say that in the python shell (IDLE) I have defined some classes, functions, variables. Also created objects of the classes. Then I deleted some of the objects and created some others. At a later point in time, how can I get to know what are the currently active objects, variables, and methods definitions active in the memory?
How about dir() which will output instantiated objects as a list? I just used this just now: [x for x in dir() if x.lower().startswith('y')]
0.673066
false
1
963
2010-12-16 15:00:20.960
Lookup table for unhashable in Python
I need to create a mapping from objects of my own custom class (derived from dict) to objects of another custom class. As I see it there are two ways of doing this: I can make the objects hashable. I'm not sure how I would do this. I know I can implement __hash__() but I'm unsure how to actually calculate the hash (which should be an integer). Since my objects can be compared I can make a list [(myobj, myotherobj)] and then implement a lookup which finds the tuple where the first item in the tuple is the same as the lookup key. Implementing this is trivial (the number of objects is small) but I want to avoid reinventing the wheel if something like this already exists in the standard library. It seems to me that wanting to look up unhashables would be a common problem so I assume someone has already solved this problem. Any suggestions on how to implement __hash()__ for a dict-like object or if there is some other standard way of making lookup tables of unhashables?
A simple solution seems to be to do lookup[id(myobj)] = myotherobj instead of lookup[myobj] = myotherobj. Any commente on this approach?
0.201295
false
1
964
2010-12-17 12:02:01.140
Processing buffers bigger than 65536 in Clyther/OpenCL
I am currently in the process of discovering OpenCL via the Python binding Clyther. So far I am messing with a very simple script to get the sin or cos of a buffer of 65536. Apparently 65536 is the limit for buffers on my card but say I'd have 16 million numbers in my buffer how would I go about it without constantly bringing the CPU into it to retrieve/send data? What I have do so far is, fill buffer, run kernel, retrieve buffer, in a loop but that also hits the CPU badly. I looked a bit at OpenCL docs but I just failed to understand how that is achieved. Thank you
This awfully looks like you are using __constant memory. The solution is to use __global memory instead, but you have to be careful about how you access it for best performance. __constant memory is a special address space for often used constant values, but is restricted in size on current GPUs.
1.2
true
1
965
2010-12-18 03:19:43.770
Inside Django's models.py, if I am validating a form, how do I get the user's IP?
I know how to get it in views.py.... request.META['REMOTE_ADDR'] However, how do I get it in models.py when one of my forms is being validateD?
If you are validating at form level or at model level, both instances know nothing about the HTTP request (where the client IP info is stored). I can think of two options: Validate at the view level where you can insert errors into the form error list. You can put the user IP (may be encrypted) in a hidden field at your form.
0
false
2
966
2010-12-18 03:19:43.770
Inside Django's models.py, if I am validating a form, how do I get the user's IP?
I know how to get it in views.py.... request.META['REMOTE_ADDR'] However, how do I get it in models.py when one of my forms is being validateD?
You can pass the request object to the form/model code that is being called: this will then provide access to request.META['REMOTE_ADDR']. Alternatively, just pass that in.
0.135221
false
2
966
2010-12-20 10:32:22.863
Python usage of breadth-first search on social graph
I've been reading a lot of stackoverflow questions about how to use the breadth-first search, dfs, A*, etc, the question is what is the optimal usage and how to implement it in reality verse simulated graphs. E.g. Consider you have a social graph of Twitter/Facebook/Some social networking site, to me it seems a search algorithm would work as follows: If user A had 10 friends, then one of those had 2 friends and another 3. The search would first figure out who user A's friends were, then it would have to look up who the friends where to each of the ten users. To me this seems like bfs? However, I'm not sure if that's the way to go about implementing the algorithm. Thanks,
I have around 300 friends in facebook and some of my friends also have 300 friends on an average. If you gonna build a graph out of it , it's gonna be huge . Correct me , if I am wrong ? . A BFS will be quit lot demanding in this scenario ? Thanks J
0
false
1
967
2010-12-20 20:55:57.780
Has anybody been able to install PyWeka?
I need to install in python 2.6 or 2.7 for windows the library PyWeka0.3dev, It says it requires setuptools, which I installed but then they told me it was a deprecated instalation library and I installed distribute, then I downloaded the PyWeka compressed package and each time I try to install it neither with setup.py nor with easy_install (where it says something like no module ez_setup). Can anybody give me a clue about how to do this?
A punk/goth approach to programming probably has the right to be.. To get the C-compliation part to work on windows you either need (1) to have Visual Studio of the same version that was used to compile the python version you are using, or (2) mingw which is a bit trickier to set up.
0
false
1
968
2010-12-22 00:01:58.563
wxPython Whole Window Focus Event
With wxPython, how does one trigger an event whenever the whole window goes into/out of focus? To elaborate, I'm building a serial terminal GUI and would like to close down the connection whenever the user doesn't have my application selected, and re-open the connection whenever the user brings my app back into the foreground. My application is just a single window derived from wx.Frame.
In addition to what these fellows are saying, you might also want to try EVT_ENTER_WINDOW and EVT_LEAVE_WINDOW. I think these are fired when you move the mouse into and out of the frame widget, although I don't think the frame has to be in focus for those events to fire. @ Hugh - thanks for the readership!
0.201295
false
3
969
2010-12-22 00:01:58.563
wxPython Whole Window Focus Event
With wxPython, how does one trigger an event whenever the whole window goes into/out of focus? To elaborate, I'm building a serial terminal GUI and would like to close down the connection whenever the user doesn't have my application selected, and re-open the connection whenever the user brings my app back into the foreground. My application is just a single window derived from wx.Frame.
as WxPerl programmer i know there is EVT_SET_FOCUS( EVT_KILL_FOCUS( if you initialize this event by listening to the frame as first parameter it should work as in Perl since the API is almost the same
0.201295
false
3
969
2010-12-22 00:01:58.563
wxPython Whole Window Focus Event
With wxPython, how does one trigger an event whenever the whole window goes into/out of focus? To elaborate, I'm building a serial terminal GUI and would like to close down the connection whenever the user doesn't have my application selected, and re-open the connection whenever the user brings my app back into the foreground. My application is just a single window derived from wx.Frame.
The correct answer for this case is to use an EVT_ACTIVATE handler bound to the frame. There will be an event whenever the frame is activated (brought into the foreground relative to other windows currently open) or deactivated. You can use the event object's GetActive method to tell which just happened.
1.2
true
3
969
2010-12-22 03:47:46.270
How important is it to use short names for Python packages and modules?
PEP 8 says that Python package and module names should be short, since some file systems will truncate long names. And I'm trying to follow Python conventions in a new project. But I really like long, descriptive names. So I'm wondering, how short do names need to be to comply with PEP 8. And does anyone really worry about this anymore? I'm tempted to ignore this recommendation, and use longer names, thinking this isn't all that relevant anymore. Does anyone think this recommendation is still worth following? If yes, why? And how short is short enough? edit: Thanks for all the helpful answers. I'm not going to worry about making my names real short, since I don't think anyone will be running my system on a really old computer. And if it did happen, I could always shorten some of the names later. But I will limit them to 32 characters. And now I understand that PEP 8 is specifically meant for the standard library, and the name length thing does make sense in that case. But I think longer names will be better for the application I'm working on. I don't think there's one best answer here, so I'm going to flip a coin to help me decide.
The common Python platforms all support directory and file names of 32 characters or more, but I personally feel that if you find yourself breaking 11 characters often that you need to rethink things.
1.2
true
4
970
2010-12-22 03:47:46.270
How important is it to use short names for Python packages and modules?
PEP 8 says that Python package and module names should be short, since some file systems will truncate long names. And I'm trying to follow Python conventions in a new project. But I really like long, descriptive names. So I'm wondering, how short do names need to be to comply with PEP 8. And does anyone really worry about this anymore? I'm tempted to ignore this recommendation, and use longer names, thinking this isn't all that relevant anymore. Does anyone think this recommendation is still worth following? If yes, why? And how short is short enough? edit: Thanks for all the helpful answers. I'm not going to worry about making my names real short, since I don't think anyone will be running my system on a really old computer. And if it did happen, I could always shorten some of the names later. But I will limit them to 32 characters. And now I understand that PEP 8 is specifically meant for the standard library, and the name length thing does make sense in that case. But I think longer names will be better for the application I'm working on. I don't think there's one best answer here, so I'm going to flip a coin to help me decide.
Long names make it easy to make stupid typing mistakes later on. Any modern computer shouldn't have a problem with long filenames, but it's good practice to pick short, descriptive names. Abbreviations are your friend, especially when you like knowing what a function does off the bat,etc.
0
false
4
970
2010-12-22 03:47:46.270
How important is it to use short names for Python packages and modules?
PEP 8 says that Python package and module names should be short, since some file systems will truncate long names. And I'm trying to follow Python conventions in a new project. But I really like long, descriptive names. So I'm wondering, how short do names need to be to comply with PEP 8. And does anyone really worry about this anymore? I'm tempted to ignore this recommendation, and use longer names, thinking this isn't all that relevant anymore. Does anyone think this recommendation is still worth following? If yes, why? And how short is short enough? edit: Thanks for all the helpful answers. I'm not going to worry about making my names real short, since I don't think anyone will be running my system on a really old computer. And if it did happen, I could always shorten some of the names later. But I will limit them to 32 characters. And now I understand that PEP 8 is specifically meant for the standard library, and the name length thing does make sense in that case. But I think longer names will be better for the application I'm working on. I don't think there's one best answer here, so I'm going to flip a coin to help me decide.
The issue is with old(er) file systems (used before Windows 95 and fat16) that don't support names larger than, say, 32 characters (it varies with the file system). It's only an issue if your scripts need to run on old computers.
0.101688
false
4
970
2010-12-22 03:47:46.270
How important is it to use short names for Python packages and modules?
PEP 8 says that Python package and module names should be short, since some file systems will truncate long names. And I'm trying to follow Python conventions in a new project. But I really like long, descriptive names. So I'm wondering, how short do names need to be to comply with PEP 8. And does anyone really worry about this anymore? I'm tempted to ignore this recommendation, and use longer names, thinking this isn't all that relevant anymore. Does anyone think this recommendation is still worth following? If yes, why? And how short is short enough? edit: Thanks for all the helpful answers. I'm not going to worry about making my names real short, since I don't think anyone will be running my system on a really old computer. And if it did happen, I could always shorten some of the names later. But I will limit them to 32 characters. And now I understand that PEP 8 is specifically meant for the standard library, and the name length thing does make sense in that case. But I think longer names will be better for the application I'm working on. I don't think there's one best answer here, so I'm going to flip a coin to help me decide.
If you need to make sure your code works on DOS, use 8 characters. :p Otherwise, it's a free world. But nobody likes to type insanely long strings. (See powershell = fail). So use your best judgement, and be reasonable.
0.201295
false
4
970
2010-12-22 18:23:07.670
Best way to get user nearest city? Python/Django
I have a website with a limited number of cities in the database, and need to show the user the nearest city to his current location. I can get the location by MaxMind API, but I want to get the nearest city in my database to user city. For example, if I have these cities in the database: Los Angeles, San Francisco and New York City, and I'm accessing from other city like Miami, I should see NYC selected because it's the nearest geographically. What's the best way to do this quick and performance aware?
Have it such that whenever you add a city to your database, a piece of code is run (off-line) that calculates the closest city to every city that you have. You can have each city point to another city as its closest city with a foreignkey. Now that you have everything pre-calculated, whenever there is a live request, with a name of a city, you just hit the database with the city name and you can get to the closest city by the foreignkey you have specified. (city ---foreignkey---> city ) Now that is going to be very fast as you have pre-calculated the closest city off-line and can return the result right away on each live request. But how often do you plan to add a city? Probably not that often. So, the off-line pre-calculation would be rare even if it takes a bit of time to do. But live requests are responded to very fast. (others have already recommend the formula to use to calculate the distance, so I am going to skip that part!)
0
false
1
971
2010-12-23 09:26:14.703
Print statements on server give IOError: failed to write data
I am running Pylons on my local machine with paster, and on a Debian server using WSGI. I want to add some print statements to debug a problem: am not a Pylons or Python expert. On my local machine this works fine: print statements go to the terminal. On the server, the statements don't print to the log files: instead the log file says "IOError: failed to write data" whenever a print statement is called. Until I can fix this, I can't debug anything on the server. Could someone advise how to get printing running on the server? Thanks!
It's wrong for a WSGI application to use sys.stdout or sys.stderr. If you want to spit debug to a server error log, use environ['wsgi.errors'].write().
0.545705
false
2
972
2010-12-23 09:26:14.703
Print statements on server give IOError: failed to write data
I am running Pylons on my local machine with paster, and on a Debian server using WSGI. I want to add some print statements to debug a problem: am not a Pylons or Python expert. On my local machine this works fine: print statements go to the terminal. On the server, the statements don't print to the log files: instead the log file says "IOError: failed to write data" whenever a print statement is called. Until I can fix this, I can't debug anything on the server. Could someone advise how to get printing running on the server? Thanks!
Don't use print statements, use the logging module. We can't help you without knowing the setup of the server.
1.2
true
2
972
2010-12-23 19:56:34.043
Line endings and reading and writing to text files
I am writing a small script that will need to read and write to text files on Windows and Linux and perhaps Mac even. The script will be used by users on all perhaps all of these platforms (Windows for sure) and interchangeably - so a user who wrote to a file X on Windows, may read the file on Linux with the script. What precautions should I take or how should I implement my code that it is able to handle line endings across various platforms? (reading and writing) Or this is a non-issue and Python handles everything?
It's a non-issue, Python is smart like that. It handles line endings across platforms very well.
1.2
true
1
973
2010-12-23 20:24:43.637
Python - Separate program logic and GUI code?
What would be the best way of separating program logic to the GUI code? I wanted different GUI (GTK, KDE, CLI) code using the same program logic. I was thinking of using different python module (winecellar-common, winecellar-gtk, winecellar-cli) not sure how I would do this and if its the best way. *EDITED* Just to add to my question what would be the best way to organize the projects file structure and build platform with different modules. Keep in mind its mainly being used on Ubuntu.
Define functions or classes for your business logic in one module, and define your presentation in another, using those functions to get your presentation. You should almost entirely be using functions and classes from the main module in the GUI module. You should do the same thing for your CLI. That way, you can have different distributions with different interfaces, and not have to create a different "logic" file for each one. Basically, you have the right idea. Just keep them as separate as possibility so that a.) you can support multiple interfaces easily and b.) you can easily make changes to the interfaces.
1.2
true
1
974
2010-12-24 09:58:33.287
how can I use python to build dynamic web sites?
I'm PHP/MySQL developper I studied python well as a desktop programming two years ago but I don't use it on the web how can I use python to build dynamic web sites and easily uploads these sites to any hosting providers
there are many web frameworks such as Django & web2py , you should check them out
1.2
true
2
975
2010-12-24 09:58:33.287
how can I use python to build dynamic web sites?
I'm PHP/MySQL developper I studied python well as a desktop programming two years ago but I don't use it on the web how can I use python to build dynamic web sites and easily uploads these sites to any hosting providers
You cant' upload python files and use it on any webhosting. You can use them if the host allows it. Some frameworks are Django or Pylons.
0.135221
false
2
975
2010-12-24 16:28:40.857
parsing objdump output
I was wondering if someone here had written/uses a script which parses the output of objdump and extracts opcodes from it? I have a very very trivial implementation but I'm looking for something better. The problem I am facing with this script is simply that it does simple string parsing; this is more of a utility script, and thats why I haven't written tests for these. I was wondering if the same could be done by writing a custom made parser or a simple yet efficient regular expression. This query is for the purpose of learning, so that I can approach such a problem in a (hopefully)better manner next time. I don't mind the specifics of the implementation(shell,ruby,python,perl; anything would do). The code does not even matter that much, really, I'd like a few hints on how you would do it.
The BEST solution would be to build objdump from source and make a python or other language swig wrapper that gets the output directly. You CAN do it with string parsing, but that's often buggy(read as implemented poorly). It is definitely possible to do the string parsing properly...I have a utility that relies on this.
0.201295
false
1
976
2010-12-26 12:52:06.543
Handling reCaptcha forms?
I'm trying to write a simple program that logs on to a site, does something and logs out. The problem is that the login form has three inputs: username, password and a recaptcha. I input all of them manually. The problem is I don't know how to display the captcha image or how to send the text. Can someone explain how to do it?
It is unreasonable to except that someone will post a complete solution for your problem. Here are the steps, just start by trying to complete them, post questions if you get stuck. very generally speaking: Get the content of the site (use the urllib2 to fetch the page) Parse the recaptcha image link and download the image (BeautifulSoup for parsing the link, urllib2 again for downloading the image) prompt yourself with the image and input for the code (use Tkinter for example) send login info & captcha( urllib2) do stuff (urllib2 again) There's probably some token that you also have to fetch that identifies your Captcha image. Use firebug to watch for the requests sent when submitting the Captcha.
0.545705
false
1
977
2010-12-26 23:43:24.027
Python: Best practice for including a version number in an app?
I have a PyQt application that reads and writes data files. I am including a 'version number' in each file written. This is a simple number similar to: 1.2 or something (major and minor versions). I am doing this so that I can change the format of these data files in future versions and then still correctly parse them simply by checking to see what the version is inside the file. My question is what is the best practice for keeping this number stored inside the app itself. I.e. do I just hard-code the app version number into the class that is responsible for reading and writing files? Or should I have some sort of object/variable stored at the top-level of the app and somehow access it from the class responsible for reading and writing these files. If the latter, how do I store it and how do I access it? Thanks.
Personally, I wouldn't do it manually this way. I'd save my code in Subversion and let it maintain the revision numbers for me.
0
false
1
978
2010-12-27 08:21:21.957
how to communicate with ror program in python
i have a application which use rails to do the CRUD operation,it's handy now i want to write a crawler use python,after that i want to save the data to db, so my question is how to python communicate with ror program?
I don't have any idea about python or rails (only grails :) but the easiest solution (if you don't want the python script to touch the DB) would be to implement a controller action for the REST PUT method in your rails application and call it from your python crawler with the crawled data. Now, all the rails controller has to do is to inster the data into your database.
0.201295
false
2
979
2010-12-27 08:21:21.957
how to communicate with ror program in python
i have a application which use rails to do the CRUD operation,it's handy now i want to write a crawler use python,after that i want to save the data to db, so my question is how to python communicate with ror program?
Via the CRUD interface, seems the obvious solution.
0
false
2
979
2010-12-27 10:14:15.277
add a python module with out root permission
I meet a problem when I try to install module omniORB&omniORBpy to a system, I don't have the root permission so I use --prefix to installed them to my user dir. my question is : how can I make python load this module? I try add my user path to sys.path, but it still doesn't work. Br, J.K.
I usually use the --user option instead of --prefix, since it installs it in ${HOME}/.local/lib/pythonx/site-packages and thus it does not require to add the path to sys.path. I think this option is available only for python 2.6 + but I am not sure. If you have to install it in an other place, then you have no choice and I don't know what could be wrong. By the way, maybe posting some sample code(just to see where exactly are the files and how you try to import them) would make clearer the "error".
0.201295
false
2
980
2010-12-27 10:14:15.277
add a python module with out root permission
I meet a problem when I try to install module omniORB&omniORBpy to a system, I don't have the root permission so I use --prefix to installed them to my user dir. my question is : how can I make python load this module? I try add my user path to sys.path, but it still doesn't work. Br, J.K.
You can add it to the search path by adding the directory to the environment variable PYTHONPATH or by adding it to sys.path in your Python script. Both work; if they don't, then you're using the wrong path.
1.2
true
2
980
2010-12-27 20:29:38.720
Python client/server project code layout
Suppose you have a client/server application, say a webserver component and a qt gui. How do you layout your python code? Packages foo.server and foo.client? Packages fooserver and fooclient, with both importing from foocommon? Everything together with no clear distinction? Having subpackages for server and client code (foo.server and foo.client) seems the best approach to me, but then how do you handle your distutils setup if you don't want the server code to be shipped along with the client code? If you use setuptools (I would rather not), how do you create separate eggs?
I like namespaces, so yes. foo.client and foo.server and foo.common and foo.anythingelsethatcanbeusedseparately. But it's all a matter of taste, really. And I'd release them as separate packages, and yes, I'd use Distribute.
0
false
2
981
2010-12-27 20:29:38.720
Python client/server project code layout
Suppose you have a client/server application, say a webserver component and a qt gui. How do you layout your python code? Packages foo.server and foo.client? Packages fooserver and fooclient, with both importing from foocommon? Everything together with no clear distinction? Having subpackages for server and client code (foo.server and foo.client) seems the best approach to me, but then how do you handle your distutils setup if you don't want the server code to be shipped along with the client code? If you use setuptools (I would rather not), how do you create separate eggs?
Having subpackages for server and client code (foo.server and foo.client) seems the best approach to me, Why? No single user (except you the developer) will ever use both sides. They're completely separate. but then how do you handle your distutils setup if you don't want the server code to be shipped along with the client code? Precisely. They're almost completely unrelated. For guidance, look at other client-server applications. The World Wide Web, for example. The Apache HTTPD server and the Firefox browser do not have any common code that I can see. Maybe a few underlying libraries, but they're clearly not htttpd.client and httpd.server. They're clearly utterly separate. The Sendmail server and the pop/imap libraries in Python seem to be utterly separated with almost nothing in common. The MySQL database server and the MySQLDB interface in Python seem to be utterly and completely separated with almost nothing in common. I can't see any examples of foo.server and foo.client anywhere. Perhaps you could share an example as part of your question to help clarify your thinking on this subject.
1.2
true
2
981
2010-12-27 21:07:40.637
twisted deferred/callbacks and asynchronous execution
I'm trying to figure out how can i make my code more asynchronous using twisted. A function returns a deferred object then i add a list of callbacks the first callback will be called after the deferred function provides some result through deferred_obj.callback then, in the chain of callbacks, the first callback will do something with the data and call the second callback and etc. however chained callbacks will not be considered asynchronous because they're chained and the event loop will keep firing each one of them concurrently until there is no more, right? However, if I have a deferred object, and I attach as its callback the deferred_obj.callback as in d.addCallback(deferred_obj.callback) then this will be considered asynchronous, because the deferred_obj is waiting for the data, and then the method that will pass the data is waiting on data as well, however once i d.callback 'd' object processes the data then it call deferred_obj.callback however since this object is deferred, unlike the case of chained callbacks, it will execute asynchronously... correct? Assuming all of my code is non-blocking, this means that chained callbacks are NOT asynchronous while chained deferreds are, correct?
Sort of, but there is no concurrency in this type of event processing. No new callback will be called until the code gets back to the event loop. So the chain of callbacks is synchronous. It's only asynchronous in the event loop. This is one caveat of this type of programming, the handlers most execute quickly, and get back to the event loop ASAP. It should not do any time consuming task in a handler.
0.201295
false
1
982
2010-12-27 21:38:07.663
Updated Python from disk image, want to make it available in terminal
I have Python 2.6.1 which came on the Mac I have, but I'd recently downloaded and installed the disk image of 3.1.3 and I'd like to have it available in Terminal, how can I do this? For instance when I do $ python -V in Terminal I get 2.6.1. Thanks for any help.
The default Python version in Mac OS X needs to stay the default Python version, or things will break. You want to install it alongside with Python 2. This is most likely exactly what happened, but you start Python 3 with python3.
0.101688
false
2
983
2010-12-27 21:38:07.663
Updated Python from disk image, want to make it available in terminal
I have Python 2.6.1 which came on the Mac I have, but I'd recently downloaded and installed the disk image of 3.1.3 and I'd like to have it available in Terminal, how can I do this? For instance when I do $ python -V in Terminal I get 2.6.1. Thanks for any help.
First, I'm not a Mac user, so I don't know a couple of specifics (default PATH, etc). Also, a bit of clarity - when you use the installer, it lets you customize the installation to install in a specific location - do you know where that is. If you didn't select a location, it defaults to /usr/local/bin. From Terminal, try "python3". If that fails, try "/usr/local/bin/python3". Outside of that, wherever it's found, you'll want that in your path statement if it isn't there already. It's not recommended that you "replace" the system python with python 3.x, as you'll definitely have problems.
0
false
2
983
2010-12-28 15:24:35.027
Removing code dependency on Greenlets
I have some code which depends on Greenlets, and need to remove this dependency. Can anyone explain to me exactly what I'll need to do? They would preferably be replaced with threads or (better yet) processes from the multiprocessing module, but anything that relies solely on the Python standard library would be sufficient for my needs. Functionality can be sacrificed, as I don't need asynchronous code, nor does the code that I am converting (for my uses, not the original implementation). UPDATE: Specifically, I need to know of alternatives to Greenlet.spawn()
It really depends on the structure of your code and high level architecture of your system. If you think that whatever you are using greenlets for can be done using multiprocessing module in the Python Standard library, then you can do that. I think, if you post specific instances than you can get the specific ways to those using multiprocessing. But beware these are two different ways to solve a generic problem of concurrency.
1.2
true
1
984
2010-12-29 19:12:52.233
Easiest non-Java way to write HBase MapReduce on CDH3?
I've been working on this for a long time, and I feel very worn out; I'm hoping for an [obvious?] insight from SO community that might get my pet project back on the move, so I can stop kicking myself. I'm using Cloudera CDH3, HBase .89 and Hadoop .20. I have a Python/Django app that writes data to a single HBase table using the Thrift interface, and that works great. Now I want to Map/Reduce it into some more HBase tables. The obvious answer here is either Dumbo or Apache PIG, but with Pig, the HBaseStorage adapter support isn't available for my version yet (Pig is able to load the classes and definitions, but freezes at the "Map" step, complaining about "Input Splits"; Pig mailing lists suggest this is fixed in Pig 0.8, which is incompatible with CDH3 Hadoop, so I'd have to use edge versions of everything [i think]). I can't find any information on how to make Dumbo use HBaseStorage as a data sink. I don't care if it's Python, Ruby, Scala, Clojure, Jython, JRuby or even PHP, I just really don't want to write Java (for lots of reasons, most of them involving the sinking feeling I get every time I have to convert an Int() to IntWritable() etc). I've tried literally every last solution and example I can find (for the last 4 weeks) for writing HBase Map/Reduce jobs in alternative languages, but everything seems to be either outdated or incomplete. Please, Stack Overflow, save me from my own devices!
It's not precisely an answer, but it's the closest I got -- I asked in #hbase on irc.freenode.net yesterday, and one of the Cloudera employees responded. The "Input Splits" problem I'm having with Pig is specific to Pig 0.7, and Pig 0.8 will be bundled with Cloudera CDH3 Beta 4 (no ETA on that). Therefore, what I want to do (easily write M/R jobs using HBase tables as both sink and source) will be possible in their next release. It also seems that the HBaseStorage class will be generally improved to help with read/write operations from ANY JVM language, as well, making Jython, JRuby, Scala and Clojure all much more feasible as well. So the answer to the question, at this time, is "Wait for CDH3 Beta 4", or if you're impatient, "Download the latest version of Pig and pray that it's compatible with your HBase"
1.2
true
1
985
2010-12-30 23:20:04.700
Creating readable html with django templates
When using Django for html templating how do I create good html markup formatting. I am trying to make use of content blocks. But the content blocks show up at different levels of indentation in different templates. How do I get the content blocks to show indented like it would be if someone was to hand write the html. I am having the same problem with newlines; I can smash all the blocks together in the template. At that point the html looks better, but the templates are unmaintainable. I guess the question is how to you create pretty html markup with the django templating system? I am surprised by the answers so far. I find that nicely formatted HTML aids in writing the corresponding CSS and JavaScript. As well as making it easier to add content later on.
The readability of HTML doesn't matter. In a system like Django or Rails, HTML is an output format, not a source format. When people edit HTML by hand, they are right to be concerned about indentation and spacing, because it is a source format, and someone will have to edit it in the future. But the output of templates is just that: output. The browser doesn't care about the indentation. At this point the only people who read the HTML are people looking at View - Source.
0
false
1
986
2010-12-31 02:30:23.963
Multiple inheritance in Python; how to do so in Java?
I'm porting some Python code to Java, and I am having trouble dealing with the following problem: I have some classes which need to have abilities A, B, or C. Class 1 needs ability A, class 2 needs A, B and C, and class 3 needs B and C. Most importantly, I want to easily be able to change what class can have what ability in the future. I solved this problem pretty easily with multiple inheritance in Python. I'm trying to figure out the best way to do it in Java, but I can't come up with as good of a solution. I know multiple inheritance is frowned-upon, so I'd appreciate being taught a better way. Thanks!
This is a bit tangential, but you can have python code running in Java via Jython (http://www.jython.org/). This addresses the porting to Java part, not the solving multiple inheritance part (I think you need to determine which is relevant)
0
false
4
987
2010-12-31 02:30:23.963
Multiple inheritance in Python; how to do so in Java?
I'm porting some Python code to Java, and I am having trouble dealing with the following problem: I have some classes which need to have abilities A, B, or C. Class 1 needs ability A, class 2 needs A, B and C, and class 3 needs B and C. Most importantly, I want to easily be able to change what class can have what ability in the future. I solved this problem pretty easily with multiple inheritance in Python. I'm trying to figure out the best way to do it in Java, but I can't come up with as good of a solution. I know multiple inheritance is frowned-upon, so I'd appreciate being taught a better way. Thanks!
If what you need is interface inheritance, then as mentioned before, you can always implement multiple interfaces. If you're looking for implementation inheritance, you're somewhat out of luck. The best solution is probably to use delegation — replace the extra superclasses with fields, and implement methods that just delegate to those fields. It does require writing a lot of repetitive delegation methods, but it's rather unavoidable in Java (without resorting to AspectJ or other bytecode-munging tricks; careful, this way madness lies …).
0
false
4
987
2010-12-31 02:30:23.963
Multiple inheritance in Python; how to do so in Java?
I'm porting some Python code to Java, and I am having trouble dealing with the following problem: I have some classes which need to have abilities A, B, or C. Class 1 needs ability A, class 2 needs A, B and C, and class 3 needs B and C. Most importantly, I want to easily be able to change what class can have what ability in the future. I solved this problem pretty easily with multiple inheritance in Python. I'm trying to figure out the best way to do it in Java, but I can't come up with as good of a solution. I know multiple inheritance is frowned-upon, so I'd appreciate being taught a better way. Thanks!
In java you don't have multiple inheritance, instead you can implement multiple interfaces. So your class 1 will implement interface A and B. Class 2 will implement interface A, B and C. Class 3 will implement B and C.
0
false
4
987
2010-12-31 02:30:23.963
Multiple inheritance in Python; how to do so in Java?
I'm porting some Python code to Java, and I am having trouble dealing with the following problem: I have some classes which need to have abilities A, B, or C. Class 1 needs ability A, class 2 needs A, B and C, and class 3 needs B and C. Most importantly, I want to easily be able to change what class can have what ability in the future. I solved this problem pretty easily with multiple inheritance in Python. I'm trying to figure out the best way to do it in Java, but I can't come up with as good of a solution. I know multiple inheritance is frowned-upon, so I'd appreciate being taught a better way. Thanks!
You can define the abilities in interfaces and implement them in your classes.
0
false
4
987
2010-12-31 04:17:25.633
python socket programming error
i got this error while running my function. "socket.error: [Errno 98] Address already in use" how can i close the address already in use and start new connection with port in python?
Stop the program or the service which is the port which you are trying to use. Alternatively, for whatever program which you are trying to write, use a PORT number which is a sufficiently high number (> 1024 for sure) and is unused.
0
false
2
988
2010-12-31 04:17:25.633
python socket programming error
i got this error while running my function. "socket.error: [Errno 98] Address already in use" how can i close the address already in use and start new connection with port in python?
These scenarios will raise error "[Errno 98] Address already in use" when you create a socket at certain port: The port was't closed. When you created a socket, but forgot to close it, or annother program hold that. You have close the socket(or kill the process), but the port stay at TIME_WAIT status in 2 MSL(about 2 minutes). Try "netstat" command to view port usage such as netstat -na or netstat -na |grep 54321
0.545705
false
2
988
2010-12-31 18:52:10.017
Is there a standard set of libraries for dynamic strings, lists, and dictionaries in C?
I'm interested in getting into C to get close to the metal performance, but would like to write in a Pythonic style and don't want to roll my own dynamic strings, lists, and dictionaries. Cython is pretty good, but would like to know how to use dynamic variables in straight C if possible. With C++ there is of course the STL, which will give you String, Vector, and Map. Certainly one possibility is to program in a C-like style in C++, using only those features. Is that the standard practice if you need dynamic variables in C?
Use C++; it has standard and highly-optimized versions of all of these. There's absolutely no reason or benefit to limit yourself to C. (ed: In other words, yes, that's a very standard practice. Remember, there's no requirement to use any of C++'s features when using C++; by design, you can pick and choose. I often disable exceptions, for example, since it leads to massively bloated executables. There's simply no reason to write code in C.)
1.2
true
1
989
2011-01-01 07:34:55.490
What is good practice for writing web applications that control daemons (and their config files)
Can someone suggest some basic advice on dealing with web applications that interact with configuration files like httpd.conf, bind zone files, etc. I understand that it's bad practice, in fact very dangerous to allow arbitrary execution of code without fully validating it and so on. But say you are tasked to write a small app that allows one to add vhosts to an apache configuration. Do you have your code execute with full privileges, do you write future variables into a database and have a cron job (with full privileges) execute a script that pulls the vars from the database and throws them into a template config file, etc. Some thoughts & contributions on this issue would be appreciated. tl;dr - how can you securely write a web app to update/create entries in a config file like apache's httpd.conf, etc.
I'm not a Unix security guru, but some basic things to think of: Make sure your web app runs as a specific user, and make sure that user has privileged rights only to those files which it is supposed to modify. Do not allow arbitrary inputs to be added to the files, have strict forms where each field is validated to contain only things it should contain, like a-z and 0-9 only, etc. Use HTTPS to access the site. I'm sure there is more to come from the real gurus.
0.201295
false
1
990
2011-01-03 01:05:55.813
Edit text using Python and curses Textbox widget?
Has anybody got a working example of using the curses.textpad.Textbox widget to edit existing text? This is, of course, in a Linux terminal (e.g. xterm).
textpad.Textbox(win, insert_mode=True) provides basic insert support. Backspace needs to be added though.
0.545705
false
1
991
2011-01-03 14:25:35.030
problems in Python Sched
I have created the number of schedulers using python in windows which are running in background. Can anyone tell me any command to check how many schedulers running on windows and also how can I remove them?
All your schedulers are part of your a single Python process, then you won't be able to count the the individual timers which are scheduled. As the python schedulers are something you write, you can choose to keep a file which would be updated periodically. If each scheduler is a separate python process, then count the many python processes from your Windows task manager.
0
false
1
992
2011-01-03 20:24:25.880
PyQt & Python2.3
Is there a PyQt3 (Or 4) Windows binary installer for Python 2.3? I've googled around for an hour now but to no avail. Why am I using version 2.3? With my project file size is paramount. Without the interface, un-needed modules and compressing using UPX the resulting .exe size is a mear 750KB's. Just need to add the interface which will beaf the size up considerably I know but it will still be a good size. So anyone know how I can install PyQt3 or 4 with Python2.3?
Python 2.3 is extremely old. You really shouldn't be using it at all. I seriously doubt there's any qt bindings for it that would even compile. Why do you think using python 2.3 will save you so much file size? Adding pyqt will probably increase your file size by 10s of megabytes at least. Just use python at least 2.6. This is definitely a case of premature optimization. And optimizing something stupid like file size.
0.545705
false
1
993
2011-01-04 14:12:02.740
Django Python Garbage Collection woes
After 2 days of debug, I nailed down my time-hog: the Python garbage collector. My application holds a lot of objects in memory. And it works well. The GC does the usual rounds (I have not played with the default thresholds of (700, 10, 10)). Once in a while, in the middle of an important transaction, the 2nd generation sweep kicks in and reviews my ~1.5M generation 2 objects. This takes 2 seconds! The nominal transaction takes less than 0.1 seconds. My question is what should I do? I can turn off generation 2 sweeps (by setting a very high threshold - is this the right way?) and the GC is obedient. When should I turn them on? We implemented a web service using Django, and each user request takes about 0.1 seconds. Optimally, I will run these GC gen 2 cycles between user API requests. But how do I do that? My view ends with return HttpResponse(), AFTER which I would like to run a gen 2 GC sweep. How do I do that? Does this approach even make sense? Can I mark the object that NEVER need to be garbage collected so the GC will not test them every 2nd gen cycle? How can I configure the GC to run full sweeps when the Django server is relatively idle? Python 2.6.6 on multiple platforms (Windows / Linux).
An alternative might be to disable GC altogether, and configure mod_wsgi (or whatever you're using) to kill and restart processes more frequently.
0.081452
false
1
994
2011-01-04 15:19:53.133
How to grab the lines AFTER a matched line in python
I am an amateur using Python on and off for some time now. Sorry if this is a silly question, but I was wondering if anyone knew an easy way to grab a bunch of lines if the format in the input file is like this: " Heading 1 Line 1 Line 2 Line 3 Heading 2 Line 1 Line 2 Line 3 " I won't know how many lines are after each heading, but I want to grab them all. All I know is the name, or a regular expression pattern for the heading. The only way I know to read a file is the "for line in file:" way, but I don't know how to grab the lines AFTER the line I'm currently on. Hope this makes sense, and thanks for the help! *Thanks for all the responses! I have tried to implement some of the solutions, but my problem is that not all the headings are the same name, and I'm not sure how to work around it. I need a different regular expression for each... any suggestions?*
I don't really know Python, but here's a bit of pseudocode. int header_found=0; [start where loop where you're looping through lines of file] if(header_found==1) [grab line]; header_found=0; if(line=~/[regexp for header]/) header_found=1; The idea is to have a variable that keeps track of whether or not you've found a header, and if you have, to grab the next line.
-0.101688
false
1
995
2011-01-05 14:37:12.057
Is it possible to use different technologies in one website
I was watching the tutorials for python and the guy told that he coded the Address books and spell checker for yahoo mail in python. Now initially i was thinking that if i build the website then i have to use one language either php or java or asp or anything. But i am confused how can we make make separate modules in diff languages and combine to make one website Any ideas
You can use any language to provide a web service, so you can for example provide a REST/SOAP web service that returns JSON or XML. The web service can be written in any language, and the language used to interact with the web service can be any language, as all languages nowadays have JSON and XML parsers. You can setup different subdomains to be used by different servers and setup those applications in any language you'd like.
0.067922
false
4
996