content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python, SQLAlchemy: Query, filter and return value
Say I run a query with a filter,
Session.query(model.Place).join(model.Location).filter(model.Location.great_circle_distance(location) < r)
In order to get the results of this query, it had to have calculated model.Location.great_circle_distance(location). After ... | Python, SQLAlchemy: Query, filter and return value | Say I run a query with a filter,
Session.query(model.Place).join(model.Location).filter(model.Location.great_circle_distance(location) < r)
In order to get the results of this query, it had to have calculated model.Location.great_circle_distance(location). After running this query, I can get a list of Places which mat... | [
"You could use join, column_property and mapper to derive a class that is, essentially, a database view. But unless you intended to use that in more than one place, or the number of rows is huge, I would just do a separate query to get the Location objects and use map to compute the circle distances.\n"
] | [
0
] | [] | [] | [
"database_design",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0007667919_database_design_pylons_python_sqlalchemy.txt |
Q:
download a file properly with python if no Content-Length is provided
how can i properly download a file with python if the http response does not contain a Content-Length header?
im having this issue with appengine's send_blob() function which for some reason does not add the Content-Length header on bigger (20mb... | download a file properly with python if no Content-Length is provided | how can i properly download a file with python if the http response does not contain a Content-Length header?
im having this issue with appengine's send_blob() function which for some reason does not add the Content-Length header on bigger (20mb+) blobs.
right now im using urllib.urlretrieve() but sometimes it does not... | [
"If the server gives no indication of the length of the requested data, sends you some data and then closes the connection, then the HTTP client must assume that all of it has been successfully transferred.\nOnly using additional, non-HTTP information, such as a checksum or other error correction within the payload... | [
1,
0
] | [] | [] | [
"download",
"google_app_engine",
"python"
] | stackoverflow_0007662281_download_google_app_engine_python.txt |
Q:
Why does this image not displaying (broken image icon)?
I am trying to display an image that I saved to Datastore with DisplayImage handler below but I only see a broken image link. Do you know why? Thanks!
class HomePage(db.Model):
thumbnail = db.BlobProperty()
firm_name = db.StringProperty()
...
class I... | Why does this image not displaying (broken image icon)? | I am trying to display an image that I saved to Datastore with DisplayImage handler below but I only see a broken image link. Do you know why? Thanks!
class HomePage(db.Model):
thumbnail = db.BlobProperty()
firm_name = db.StringProperty()
...
class ImageUpload(webapp.RequestHandler):
def get(self):
... ... | [
"To serve an image from blobstore, use get_serving_urlor if you have a blobproperty you can have a look at my old code that used to serve my blobproperties from an image class back before when there was no blobstore:\nclass Image(db.Model):\n name = db.StringProperty()\n desc = db.StringProperty... | [
1,
0
] | [] | [] | [
"google_app_engine",
"image",
"python"
] | stackoverflow_0007545865_google_app_engine_image_python.txt |
Q:
Python: get list of characters inapplicable for file naming?
In a Python script I want to know which characters are inapplicable for use in file names under current OS/FileSystem. I'd like to create files without errors. Is there such feature in Python?
A:
I hate to answer a question with another question, but t... | Python: get list of characters inapplicable for file naming? | In a Python script I want to know which characters are inapplicable for use in file names under current OS/FileSystem. I'd like to create files without errors. Is there such feature in Python?
| [
"I hate to answer a question with another question, but this question seems to be what you are looking for: turn a string into a valid filename in Python. Otherwise, the list of reserved characters by OS is here.\n"
] | [
0
] | [] | [] | [
"filesystems",
"python"
] | stackoverflow_0007668659_filesystems_python.txt |
Q:
how to convert and subtract dates, times in python
I have the following date/time:
2011-09-27 13:42:16
I need to convert it to:
9/27/2011 13:42:16
I also need to be able to subtract one date from another and get the result in HH:MM:SS format. I have tried to use the dateutil.parser.parse function, and it parse... | how to convert and subtract dates, times in python | I have the following date/time:
2011-09-27 13:42:16
I need to convert it to:
9/27/2011 13:42:16
I also need to be able to subtract one date from another and get the result in HH:MM:SS format. I have tried to use the dateutil.parser.parse function, and it parses the date fine but sadly it doesn't seem to get the tim... | [
"You can use datetime's strptime function:\nfrom datetime import datetime\n\ndate = '2011-09-27 13:42:16'\nresult = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')\n\nYou were lucky, as I had that above line written for a project of mine.\nTo print it back out, try strftime:\nprint result.strftime('%m/%d/%Y %H:%M:%S')... | [
4,
1,
0
] | [] | [] | [
"date",
"datetime",
"python",
"python_dateutil",
"time"
] | stackoverflow_0007669338_date_datetime_python_python_dateutil_time.txt |
Q:
get Well Known Text from lat long
I can get easily a lat,long pair from the Google Maps API:
from googlemaps import GoogleMaps
gmaps = GoogleMaps(GOOGLEMAPS_API_KEY)
gmaps.address_to_latlng('Jose Javier Diaz 440 Cordoba Argentina')
>>>> (-31.4464489, -64.191219899999993)
And I have a model like this:
from django ... | get Well Known Text from lat long | I can get easily a lat,long pair from the Google Maps API:
from googlemaps import GoogleMaps
gmaps = GoogleMaps(GOOGLEMAPS_API_KEY)
gmaps.address_to_latlng('Jose Javier Diaz 440 Cordoba Argentina')
>>>> (-31.4464489, -64.191219899999993)
And I have a model like this:
from django import models
class MaapPoint(models.Mo... | [
"In django, contrib.gis there are helpers for this. \n>>> from django.contrib.gis.geos import Point\n>>> Point(0,1).wkt\n'POINT (0.0000000000000000 1.0000000000000000)'\n\n",
"Shapely provides a nice API for that:\n>>> import shapely\n>>> from shapely.wkt import dumps, loads\n>>> pt1 = loads('POINT (0.00000000000... | [
4,
3
] | [] | [] | [
"geodjango",
"latitude_longitude",
"postgis",
"python",
"wkt"
] | stackoverflow_0007605038_geodjango_latitude_longitude_postgis_python_wkt.txt |
Q:
Datetime difference to return Days only?
$ cat .t.py
import re
from datetime import datetime as dtt
oldestDate = dateComp = dtt.strptime('1.1.1001', '%d.%m.%Y')
dateComp = dtt.strptime('11.1.2011', '%d.%m.%Y')
ind = re.sub(" days,.*", "", str((dateComp - oldestDate)))
print ind
print dateComp - oldestDate
$ pyt... | Datetime difference to return Days only? | $ cat .t.py
import re
from datetime import datetime as dtt
oldestDate = dateComp = dtt.strptime('1.1.1001', '%d.%m.%Y')
dateComp = dtt.strptime('11.1.2011', '%d.%m.%Y')
ind = re.sub(" days,.*", "", str((dateComp - oldestDate)))
print ind
print dateComp - oldestDate
$ python .t.py
368905
368905 days, 0:00:00
How ca... | [
"Don't use str() so soon. The result you get back from subtracting one datetime from another is a timedelta object, which has a .days property that you can read.\n(dateComp - oldestDate).days\n\nNote that reading only the .days property will mean that it will round down the difference - if you instead want to round... | [
2
] | [] | [] | [
"datetime",
"python",
"regex"
] | stackoverflow_0007669420_datetime_python_regex.txt |
Q:
Why does put() not work when used with indexed element in Query?
I have an issue that put() does not appear to work if I access the model class as an indexed member of the Query directly; however, when I explicitly extract the class from the Query it seems to work fine. Why is this?
This code works:
class Record:
... | Why does put() not work when used with indexed element in Query? | I have an issue that put() does not appear to work if I access the model class as an indexed member of the Query directly; however, when I explicitly extract the class from the Query it seems to work fine. Why is this?
This code works:
class Record:
field = db.StringProperty()
rs = Record.all().filter('name = ', na... | [
"Every time you index a query like this, it performs the query all over again, fetches the relevant result, decodes it, and returns it to you. In your second snippet, you modify one instance of the entity, immediately discard it, then fetch and store (unmodified) a second copy.\nGenerally, you should avoid indexing... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007662385_google_app_engine_google_cloud_datastore_python.txt |
Q:
App Engine memcache speed "dict" vs "Class Object"
I have page handler with 95% traffic, it fetches model from DB using its key and then uses fields in the fetched model to fill a django template.
I want to memcache the fetched model so as to avoid DB reads. Not all fields of the model are used in template so i w... | App Engine memcache speed "dict" vs "Class Object" | I have page handler with 95% traffic, it fetches model from DB using its key and then uses fields in the fetched model to fill a django template.
I want to memcache the fetched model so as to avoid DB reads. Not all fields of the model are used in template so i want to cache it with just the required feilds so as to i... | [
"Neither! Instead, cache the entity Protocol Buffer, as described here.\nYou might want to consider switching to NDB, which has built in support for memcaching model instances.\n",
"You need to measure but for all intended purposes the results should be that its about the same speed.\nIf any method tend to be fas... | [
2,
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007660231_google_app_engine_python.txt |
Q:
Efficiency with "try...except"
The code works fine. I just had an efficiency question. In this code I'm using "try...except" to pass an error that would crash the program. The error is caused by the IP address not being reachable. As I said before, the code does its job. I want to know if this the quickest way to ... | Efficiency with "try...except" | The code works fine. I just had an efficiency question. In this code I'm using "try...except" to pass an error that would crash the program. The error is caused by the IP address not being reachable. As I said before, the code does its job. I want to know if this the quickest way to see if the IP is reachable and pass ... | [
"Your question about efficiency is absolutely unrelated to your use of try ... except. Exception handling in Python is relatively fast, about the same as running any other Python statement (we're talking on the order of microseconds).\nYour 30-45 second performance is undoubtedly due to the behaviour of NetGroupGet... | [
5
] | [] | [] | [
"error_handling",
"ip",
"performance",
"python",
"try_except"
] | stackoverflow_0007669639_error_handling_ip_performance_python_try_except.txt |
Q:
How to hide a row of table (or a list item) and update the datastore without reloading the page?
I have a list of bookmarks displayed on a table. I added a "hide" link to hide a bookmark that I don't want to see on the list but I still want to keep (table and the hide link show only if you are logged in).
Now I do... | How to hide a row of table (or a list item) and update the datastore without reloading the page? | I have a list of bookmarks displayed on a table. I added a "hide" link to hide a bookmark that I don't want to see on the list but I still want to keep (table and the hide link show only if you are logged in).
Now I do it by getting the item from the database and by changing its "display" property to "False" and by ren... | [
"You've tagged this as javascript but I don't see any script in the page. I also don't see a table or a \"hide\" link.\nTo hide an element and all it's child nodes, set its style.display property to \"none\", e.g.\n<div>here is some content\n <button onclick=\"this.parentNode.style.display = 'none';\">Hide</button... | [
2,
1
] | [] | [] | [
"javascript",
"jquery",
"python"
] | stackoverflow_0007669256_javascript_jquery_python.txt |
Q:
Google Apps Engine Datastore Search
I was wondering if there was any way to search the datastore for a entry. I have a bunch of entries for songs(title, artist,rating) but im not sure how to really search through them for both song title and artist. We take in a search term and are looking for all entries that "ma... | Google Apps Engine Datastore Search | I was wondering if there was any way to search the datastore for a entry. I have a bunch of entries for songs(title, artist,rating) but im not sure how to really search through them for both song title and artist. We take in a search term and are looking for all entries that "match." But we are lost :( any help is much... | [
"The song data you work with sounds as a rather static data set (primarily inserts, no or few updates). In that case there is GAE technique called Relation Index Entity (RIE) which is an efficient way to implement keyword-based search. \nBut some preparation work required which is briefly:\n\nbuild special RIE enti... | [
1,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"search"
] | stackoverflow_0007655720_google_app_engine_google_cloud_datastore_python_search.txt |
Q:
Is it possible to get a "high water mark" of memory usage from Python?
Are there any methods in (C)Python to inspect the process' current memory usage? In particular, I'd like to determine the high-water mark of memory usage in a testing script, but if necessary I don't mind periodically checking memory usage and ... | Is it possible to get a "high water mark" of memory usage from Python? | Are there any methods in (C)Python to inspect the process' current memory usage? In particular, I'd like to determine the high-water mark of memory usage in a testing script, but if necessary I don't mind periodically checking memory usage and calculating the high water mark for myself.
EDIT: I'm looking for either a p... | [
"Have a look at my answer to this question. It uses the getrusage() function from the standard library's resource module, and works on Mac OS X.\n",
"On Linux, you can inspect the /proc/self/status file:\nVmPeak: 6784 kB\nVmSize: 6784 kB\nVmLck: 0 kB\nVmHWM: 572 kB\nVmRSS: 572 kB\nVmDa... | [
5,
3,
1,
0
] | [] | [] | [
"macos",
"memory_management",
"python"
] | stackoverflow_0006159053_macos_memory_management_python.txt |
Q:
Importing data from scanned text into Django as YAML fixture or SQL
I'm setting up a simple Django app -- a quiz. The questions and answers come from printed sample tests that have been scanned, OCR'd and parsed. I've parsed them into Python objects like so:
class Quiz(object):
def __init__(self, name):
... | Importing data from scanned text into Django as YAML fixture or SQL | I'm setting up a simple Django app -- a quiz. The questions and answers come from printed sample tests that have been scanned, OCR'd and parsed. I've parsed them into Python objects like so:
class Quiz(object):
def __init__(self, name):
self.name = name
self.questions = {}
class Question(object):
... | [
"The first question to ask yourself is why you are using these intermediate classes at all? This sounds like bad design.\nOnce we move past the bad design. Your code shows that qustion.answers is a dictionary not a list, I assume you just made a typo. \nIf you have a Quiz model instance you can call Quiz.questio... | [
0
] | [] | [] | [
"django",
"fixture",
"python"
] | stackoverflow_0007669550_django_fixture_python.txt |
Q:
python human readable large numbers
is there a python library that would make numbers such as this more human readable
$187,280,840,422,780
edited: for example iw ant the output of this to be 187 Trillion not just comma separated. So I want output to be trillions, millions, billions etc
A:
As I understand it, yo... | python human readable large numbers | is there a python library that would make numbers such as this more human readable
$187,280,840,422,780
edited: for example iw ant the output of this to be 187 Trillion not just comma separated. So I want output to be trillions, millions, billions etc
| [
"As I understand it, you only want the 'most significant' part. To do so, use floor(log10(abs(n))) to get number of digits and then go from there. Something like this, maybe:\nimport math\n\nmillnames = ['',' Thousand',' Million',' Billion',' Trillion']\n\ndef millify(n):\n n = float(n)\n millidx = max(0,min(... | [
97,
62,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003154460_python.txt |
Q:
Parsing iCal feed with multiple events with Python and vobject
I'm trying to parse a feed with multiple events and its only returning me one item
ics = urllib.urlopen("https://www.google.com/calendar/ical/pcolalug%40gmail.com/public/basic.ics").read()
events = []
components = vobject.readComponents(ics)
for event... | Parsing iCal feed with multiple events with Python and vobject | I'm trying to parse a feed with multiple events and its only returning me one item
ics = urllib.urlopen("https://www.google.com/calendar/ical/pcolalug%40gmail.com/public/basic.ics").read()
events = []
components = vobject.readComponents(ics)
for event in components:
to_zone = tz.gettz('America/Chicago')
date ... | [
"Switched to using icalendar instead of vobject, it works a lot better.\nics = urllib.urlopen(\"https://www.google.com/calendar/ical/pcolalug%40gmail.com/public/basic.ics\").read()\nevents = []\n\ncal = Calendar.from_string(ics)\n\nfor event in cal.walk('vevent'):\n to_zone = tz.gettz('America/Chicago')\n\n d... | [
2
] | [] | [] | [
"icalendar",
"python",
"vobject"
] | stackoverflow_0007669761_icalendar_python_vobject.txt |
Q:
python class data descriptor list
I can't seem to figure out how to get a list of a classes data descriptors. Basically, I want to run some validation against the fields and unset fields. For instance:
class Field (object):
def __init__ (self, name, required=False):
self.name = name
self.requir... | python class data descriptor list | I can't seem to figure out how to get a list of a classes data descriptors. Basically, I want to run some validation against the fields and unset fields. For instance:
class Field (object):
def __init__ (self, name, required=False):
self.name = name
self.required = required
def __set__ (self, o... | [
"In order to iterate over the classes' members you need to use inpsect.getmembers. So your last example would look like this:\nimport inspect\n\nfields = []\nfor member_name, member_object in inspect.getmembers(self.__class__):\n if inspect.isdatadescriptor(member_object):\n fields.append(member_name)\n\... | [
3
] | [] | [] | [
"descriptor",
"python"
] | stackoverflow_0007670240_descriptor_python.txt |
Q:
python pgdb hanging database
I'm writing a script to access data in an established database and unfortunately, I'm breaking the DB. I'm able to recreate the issue from the command line:
[user@box tmp]# python
Python 2.7.2 (default, Sep 19 2011, 15:02:41)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on li... | python pgdb hanging database | I'm writing a script to access data in an established database and unfortunately, I'm breaking the DB. I'm able to recreate the issue from the command line:
[user@box tmp]# python
Python 2.7.2 (default, Sep 19 2011, 15:02:41)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright",... | [
"Try calling db.rollback() before you close the cursor (or if you're doing a write operation, db.commit()).\n",
"I suggest using psycopg2 instead of pgdb. pgdb uses the following semantics:\nconnect() -> open database connection, begin transaction\ncommit() -> commit, begin transaction\nrollback() -> rollback, b... | [
2,
2
] | [] | [] | [
"pgdb",
"postgresql",
"python"
] | stackoverflow_0007669434_pgdb_postgresql_python.txt |
Q:
How to share variables between methods in a class?
I'm looking for a way to make a variable set by one method/function in a class accessible by another method/function in that same class without having to do excess (and problematic code) outside.
Here is an example that doesn't work, but may show you what I'm tryi... | How to share variables between methods in a class? | I'm looking for a way to make a variable set by one method/function in a class accessible by another method/function in that same class without having to do excess (and problematic code) outside.
Here is an example that doesn't work, but may show you what I'm trying to do :
#I just coppied this one to have an init meth... | [
"You set it in one method and then look it up in another:\nclass TestClass(object):\n\n def current(self, test):\n \"\"\"Just a method to get a value\"\"\"\n self.test = test\n print(test)\n\n def next_one(self):\n \"\"\"Trying to get a value from the 'current' method\"\"\"\n ... | [
13,
1
] | [] | [] | [
"methods",
"oop",
"python"
] | stackoverflow_0007670415_methods_oop_python.txt |
Q:
how call a python function from Jquery script in django template
am new to django and jquery,I am searching for a 'hello world' sample for jquery using django1.3, Where hello world is returned as a string /json from the server to the client when user press a button or at loading of the page.
Note: I am using djang... | how call a python function from Jquery script in django template | am new to django and jquery,I am searching for a 'hello world' sample for jquery using django1.3, Where hello world is returned as a string /json from the server to the client when user press a button or at loading of the page.
Note: I am using django1.3 and python 2.7.Sorry this is a very basic question.
I successed i... | [
"Finally I got a 'hello' from the server!\nurls.py:\nfrom django.views.generic.simple import direct_to_template\n\n(r'^hello/$',direct_to_template, {'template': 'jqueryserver.html'}),\n(r'^jqueryserver/$',views.jqueryserver),\n\nviews.py:\n#other imports\nfrom django.views.decorators.csrf import csrf_exempt\nfrom d... | [
2,
0
] | [] | [] | [
"django",
"django_1.3",
"django_templates",
"jquery",
"python"
] | stackoverflow_0007609354_django_django_1.3_django_templates_jquery_python.txt |
Q:
Python script using beautifulSoup to scrape webpage
I am trying to scrape the contents of the following page using BeautifulSoup,
<div data-referrer="pagelet_123" id="pagelet_123">
<div id="1" class="p1">
<div class="uiHeader uiHeaderTopAndBottomBorder uiHeaderSection">
<div class="clearfix uiHeaderTop">
<div>
<h4... | Python script using beautifulSoup to scrape webpage | I am trying to scrape the contents of the following page using BeautifulSoup,
<div data-referrer="pagelet_123" id="pagelet_123">
<div id="1" class="p1">
<div class="uiHeader uiHeaderTopAndBottomBorder uiHeaderSection">
<div class="clearfix uiHeaderTop">
<div>
<h4 class="uiHeaderTitle">info - 1</h4>
</div></div></div><d... | [
"Their documentation doesn't serve your purposes?\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html\nIt looks to me like you're going to want something like:\nfrom BeautifulSoup import BeautifulSoup\nimport re\nsoup = BeautifulSoup(theXMLAsAString)\nresults = soup.findAll(re.compile('info - [1-6]'))\... | [
2
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0007670657_beautifulsoup_python.txt |
Q:
how to print two messages in single dialogue box using python?
D= dict[a= 2, b=4, c=1, d=3]
I am using the above dictionary after sorting (ascending order) and displaying the sorted value along with the lowest value.
Desired output in the dialogue box
c=1
a=2
d=3
b=4
c lowest value is 1
I am trying the following... | how to print two messages in single dialogue box using python? | D= dict[a= 2, b=4, c=1, d=3]
I am using the above dictionary after sorting (ascending order) and displaying the sorted value along with the lowest value.
Desired output in the dialogue box
c=1
a=2
d=3
b=4
c lowest value is 1
I am trying the following code:
D dict[a= 2, b=4, c=1, d=3]
f= sorted(D.items(), key=operator... | [
"Insert extra newline characters:\nmsg = '\\n'.join(f) + '\\n\\n' + ' lowest value is '.join(g) + '\\n'\n\nalthough the last line would be more logically built as:\nmsg = '\\n'.join(f) + '\\n\\n%s lowest value is %s\\n' % tuple(g)\n\nAnd how about your dictionary definition?\nD dict[a= 2, b=4, c=1, d=3]\n\nwas mean... | [
0,
0
] | [] | [] | [
"messagebox",
"python"
] | stackoverflow_0007670802_messagebox_python.txt |
Q:
python import cx_Oracle error
I'm trying to install cx_Oracle to use Django inspectdb on an existing Oracle database to create models.py automatically. So far i'ts been very hard. I'm running a VM with Fedora 14 64bit and Python 2.7 and followed a mix of pages found with google to get it installed with sudo -E eas... | python import cx_Oracle error | I'm trying to install cx_Oracle to use Django inspectdb on an existing Oracle database to create models.py automatically. So far i'ts been very hard. I'm running a VM with Fedora 14 64bit and Python 2.7 and followed a mix of pages found with google to get it installed with sudo -E easy_install cx_Oracle
When I fire up ... | [
"It was SELinux, Fedora security system that was blocking it and I didn't notice! Installation was ok and it's working now. Sorry and thanks everyone.\n",
"It has occurred for me long time back\nThere are two set of libraries for 32 bit and 64 bit just copy these \"*.so\" files to the appropriate directories.\nPl... | [
1,
0,
0
] | [] | [] | [
"cx_oracle",
"django",
"inspectdb",
"python"
] | stackoverflow_0005175777_cx_oracle_django_inspectdb_python.txt |
Q:
Ensure Relative Path is Used in cmd.exe when Running Batch Files From Excel
I have an Excel file with a button that calls a Shell command in VB:
Shell(ThisWorkbook.Path & "\python_script.bat", vbNormalFocus)
The Shell command calls the above batch file that runs a Python script:
python python_script.py
All the p... | Ensure Relative Path is Used in cmd.exe when Running Batch Files From Excel | I have an Excel file with a button that calls a Shell command in VB:
Shell(ThisWorkbook.Path & "\python_script.bat", vbNormalFocus)
The Shell command calls the above batch file that runs a Python script:
python python_script.py
All the pertinent files (the Excel file, the batch file, the data files, the Python file) ... | [
"Try this, if path\\to\\sample_program is on the same drive as your home drive\nShell \"cmd.exe /k cd \" & ThisWorkbook.Path & \"&&python_script.bat\"\n\nor this if path\\to\\sample_program is not on the same drive as your home drive, or you dont know in advance \nShell \"cmd.exe /k \" & Left(ThisWorkbook.Path, 2)... | [
2,
1
] | [] | [] | [
"batch_file",
"excel",
"python",
"vba"
] | stackoverflow_0007668942_batch_file_excel_python_vba.txt |
Q:
Openerp module update fails
I am in the process of trying to upgrade my module written for Openerp. Although it works fine on the local machine and the local openerp server. It gives me the below error when I try to update the files via SVN to the staged server. The error states that they are trying to insert a re... | Openerp module update fails | I am in the process of trying to upgrade my module written for Openerp. Although it works fine on the local machine and the local openerp server. It gives me the below error when I try to update the files via SVN to the staged server. The error states that they are trying to insert a record to the DB where is its actua... | [
"\n[2011-09-14 08:12:49,434][oe_test] DEBUG:sql:duplicate key value violates unique constraint \"ir_model_data_module_name_uniq\"\n\nIn ir.model.data, there is an \"_sql_constraint\", defined for unique record name. so error comes from that code and says that You can't have duplicate record name.\nas per my knowled... | [
3,
2,
1
] | [] | [] | [
"openerp",
"python"
] | stackoverflow_0007470503_openerp_python.txt |
Q:
Django QuerySet - Memory usage / Laziness
I have a django model which has a load of relatively small fields and then one kinda huge one. Let's say something like this:
class MyModel(models.Model):
thing = models.ForeignKey('Thing')
egg = models.TextField()
spoon = models.TextField()
race = models.FloatField()
bi... | Django QuerySet - Memory usage / Laziness | I have a django model which has a load of relatively small fields and then one kinda huge one. Let's say something like this:
class MyModel(models.Model):
thing = models.ForeignKey('Thing')
egg = models.TextField()
spoon = models.TextField()
race = models.FloatField()
big_field = models.TextField()
big_field is only... | [
"You can force your queries to fetch only the fields that you want, to save memory.\n"
] | [
3
] | [] | [] | [
"django",
"django_queryset",
"lazy_evaluation",
"memory",
"python"
] | stackoverflow_0007671510_django_django_queryset_lazy_evaluation_memory_python.txt |
Q:
'AFFINE' is not defined PIL python
I am using the transform method of the Image class.
import Image
im = Image.open('Image.jpg')
im1 = im.transform((1000,1000),AFFINE, (1,0,0,1,10,10))
The above code produces an error: NameError: name 'AFFINE' is not defined.
If I use "from Image import *" it works:
from Image i... | 'AFFINE' is not defined PIL python | I am using the transform method of the Image class.
import Image
im = Image.open('Image.jpg')
im1 = im.transform((1000,1000),AFFINE, (1,0,0,1,10,10))
The above code produces an error: NameError: name 'AFFINE' is not defined.
If I use "from Image import *" it works:
from Image import *
im = open('Image.jpg')
im1 = im.... | [
"Use im1 = im.transform((1000,1000),Image.AFFINE, (1,0,0,1,10,10)) prefix the variable with the module name.\n"
] | [
7
] | [] | [] | [
"python",
"python_imaging_library",
"transform"
] | stackoverflow_0007671607_python_python_imaging_library_transform.txt |
Q:
creating an array from a command line option (python::optparse)
There is a python script which reads a benchmark name from command line like this:
-b benchname1
The code for this perpose is:
import optparse
import Mybench
parser = optparse.OptionParser()
# Benchmark options
parser.add_option("-b", "--benchmark", ... | creating an array from a command line option (python::optparse) | There is a python script which reads a benchmark name from command line like this:
-b benchname1
The code for this perpose is:
import optparse
import Mybench
parser = optparse.OptionParser()
# Benchmark options
parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.")
if options.benchmark ... | [
"If you have Python 2.7+, you can use argparse module instead of optparse.\nimport argparse\n\nparser = argparse.ArgumentParser(description='Process benchmarks.')\nparser.add_argument(\"-b\", \"--benchmark\", default=[], type=str, nargs='+',\n help=\"The benchmark to be loaded.\")\n\nargs = parse... | [
8,
4,
1
] | [] | [] | [
"arrays",
"command_line_arguments",
"optparse",
"python"
] | stackoverflow_0007671383_arrays_command_line_arguments_optparse_python.txt |
Q:
Access django dict through shell after aggregate annotate
Simple question
I am trying to get the result of an aggregate to use in my view to make a simple calculation.
I have written the following.
sms_raised = SmsBacker.objects.values('amount').annotate(Sum('amount'))
sms_raised
[{'amount': 150L, 'amount__sum': 6... | Access django dict through shell after aggregate annotate | Simple question
I am trying to get the result of an aggregate to use in my view to make a simple calculation.
I have written the following.
sms_raised = SmsBacker.objects.values('amount').annotate(Sum('amount'))
sms_raised
[{'amount': 150L, 'amount__sum': 600}]
How do I access those values in the shell.
I have tried
... | [
"Dict is the first item in the list, so\nsms_raised[0]['amount']\nsms_raised[0]['amount__sum']\n\n"
] | [
3
] | [] | [] | [
"django",
"django_orm",
"django_shell",
"django_views",
"python"
] | stackoverflow_0007671653_django_django_orm_django_shell_django_views_python.txt |
Q:
partition of a list using dynamic programming
I have posted a bit here related to a project I have been trying to work on and I keep hitting design problems and have to design from scratch. So I'm wondering if I can post what I'm trying to do and someone can help me understand how I can get the result I want.
Bac... | partition of a list using dynamic programming | I have posted a bit here related to a project I have been trying to work on and I keep hitting design problems and have to design from scratch. So I'm wondering if I can post what I'm trying to do and someone can help me understand how I can get the result I want.
BackGround:
I'm new to programming and trying to learn... | [
"You have to be aware, that DP problems are not per se optimal for independent and distributed computations.\nWhen you consider the classical forms of DP algorithms, you have a matrix/table/array and you successively compute new values in a certain order. Each computation of a value requires other values that have ... | [
3
] | [] | [] | [
"algorithm",
"dynamic_programming",
"partitioning",
"python"
] | stackoverflow_0007671396_algorithm_dynamic_programming_partitioning_python.txt |
Q:
Reading real time values with pySerial while plotting
So here is the deal, I have a module which sends out data over the serial port at 9600 baud and I am using the matplotlib to plot that data in real time. I wrote this code
#! python
############ import section ###################
import serial
import struct
i... | Reading real time values with pySerial while plotting | So here is the deal, I have a module which sends out data over the serial port at 9600 baud and I am using the matplotlib to plot that data in real time. I wrote this code
#! python
############ import section ###################
import serial
import struct
import numpy as np
import matplotlib.pyplot as plt
#########... | [
"I know the code below seems long and overly complex for your simple problem, but manual optimization is usually more code and more potential bugs. That's why premature optimization is almost always a mistake. \nIn __init__ it sets up the plot, setting references for the axis, canvas, line (it starts with a line dr... | [
2
] | [] | [] | [
"pyserial",
"python"
] | stackoverflow_0007663263_pyserial_python.txt |
Q:
Python Function To Find String Between Two Markers
I'm looking to build a string function to extract the string contents between two markers. It returns an extraction list
def extract(raw_string, start_marker, end_marker):
... function ...
return extraction_list
I know this can be done using regex but is ... | Python Function To Find String Between Two Markers | I'm looking to build a string function to extract the string contents between two markers. It returns an extraction list
def extract(raw_string, start_marker, end_marker):
... function ...
return extraction_list
I know this can be done using regex but is this fast? This will be called billions of times in my p... | [
"You probably can't go faster than:\ndef extract(raw_string, start_marker, end_marker):\n start = raw_string.index(start_marker) + len(start_marker)\n end = raw_string.index(end_marker, start)\n return raw_string[start:end]\n\nBut if you want to try regex, just try to benchmark it. There's a good timeit mo... | [
11
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0007672432_python_regex_string.txt |
Q:
python string replace unknown number
I am a beginner with PYTHON and useless with regex and are struggling to replace an unknown number in a file with a new number. I have looked through the python how tos and examples for re but still can't make any progress on how to create the expression.
# myfile.txt
Some text... | python string replace unknown number | I am a beginner with PYTHON and useless with regex and are struggling to replace an unknown number in a file with a new number. I have looked through the python how tos and examples for re but still can't make any progress on how to create the expression.
# myfile.txt
Some text
More text
Option "BlankTime" "15"
more t... | [
"import re\nwith open(\"myfile.txt\", \"r\") as myfile:\n mytext = myfile.read()\npattern = re.compile(r'^(Option\\s+\"BlankTime\"\\s+\")(\\d+)\"', re.MULTILINE)\nmystr = pattern.sub(r'\\1REPLACED\"', mytext)\nwith open(\"myfile.txt\", \"w\") as myfile:\n myfile.write(mytext)\n\nThis will replace all occurren... | [
1,
1
] | [
"myfile = open('myfile.txt', 'r')\ntext = myfile.read()\nmyfile.close()\n\nprint re.sub(r'\\d+', '42', text)\n\n\\d matches a number, + matches at least one occurrence of the preceding pattern.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0007672727_python.txt |
Q:
Where should I place a Python package's demo script?
I am coding a new python package to be used by others. To demonstrate how it should be used, I am writing a demo script that executes the main parts of the new package.
What is the convention for doing this, so that other will find the script easily? Should it b... | Where should I place a Python package's demo script? | I am coding a new python package to be used by others. To demonstrate how it should be used, I am writing a demo script that executes the main parts of the new package.
What is the convention for doing this, so that other will find the script easily? Should it be a separate module (by what name)? Should it be located ... | [
"\nShould it be a separate module (by what name)? \n\ndemo/some_useful_name.py\nA demo directory contains demo scripts. Similarly, a test directory contains all your unit tests.\n\nShould it be located in the package's root directory? \n\nNo. It's not part of the package. It's a demo.\n\nOut of the package?\n\nY... | [
4,
3
] | [] | [] | [
"convention",
"demo",
"package",
"program_entry_point",
"python"
] | stackoverflow_0007671348_convention_demo_package_program_entry_point_python.txt |
Q:
how to get the text in the html in python
I wanted to capture some of the text in html using python.
example..
#!/usr/bin/python
import urllib
open = urllib.urlopen('http://localhost/main.php')
read = open.read()
print read
and this source code of the target url
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tran... | how to get the text in the html in python | I wanted to capture some of the text in html using python.
example..
#!/usr/bin/python
import urllib
open = urllib.urlopen('http://localhost/main.php')
read = open.read()
print read
and this source code of the target url
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/... | [
"Try beautiful soup.\nfrom BeautifulSoup import BeautifulSoup\n\n...\n\nsoup = BeautifulSoup(html)\nsoup.findAll(\"body\").string\n\n",
"Use BeautifulSoup:\nfrom BeautifulSoup import BeautifulSoup\n\nhtml = \"\"\"\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/... | [
6,
4
] | [] | [] | [
"python"
] | stackoverflow_0007673007_python.txt |
Q:
Get a whole unicode sentence
I'm trying to parse a sentence like Base: Lote Numero 1, Marcelo T de Alvear 500. Demanda: otras palabras. I want to: first, split the text by periods, then, use whatever is before the colon as a label for the sentence after the colon.
Right now I have the following definition:
from py... | Get a whole unicode sentence | I'm trying to parse a sentence like Base: Lote Numero 1, Marcelo T de Alvear 500. Demanda: otras palabras. I want to: first, split the text by periods, then, use whatever is before the colon as a label for the sentence after the colon.
Right now I have the following definition:
from pyparsing import *
unicode_printabl... | [
"To directly answer your question, wrap your value definition with originalTextFor, and this will give you back the string slice that the matching tokens came from, as a single string. You could also add a parse action, like:\nvalue.setParseAction(lambda t : ' '.join(t))\n\nBut this would explicitly put a single s... | [
2,
1
] | [] | [] | [
"nlp",
"pyparsing",
"python",
"text_segmentation"
] | stackoverflow_0007669462_nlp_pyparsing_python_text_segmentation.txt |
Q:
Is there a Python function like Lua's string.sub?
As per the title, I am looking for a Python function similar to Lua's string.sub, whether it be 3rd party or part of the Python Standard library. I've been searching all over the internet ( including stackoverflow ) for nearly an hour and haven't been able to find ... | Is there a Python function like Lua's string.sub? | As per the title, I am looking for a Python function similar to Lua's string.sub, whether it be 3rd party or part of the Python Standard library. I've been searching all over the internet ( including stackoverflow ) for nearly an hour and haven't been able to find anything whatsoever.
| [
"Lua:\n> = string.sub(\"Hello Lua user\", 7) -- from character 7 until the end\nLua user\n> = string.sub(\"Hello Lua user\", 7, 9) -- from character 7 until and including 9\nLua\n> = string.sub(\"Hello Lua user\", -8) -- 8 from the end until the end\nLua user\n> = string.sub(\"Hello Lua user\", -8, 9) -... | [
13,
10,
4
] | [] | [] | [
"python",
"string",
"substring"
] | stackoverflow_0007673079_python_string_substring.txt |
Q:
UserDict Normal methods explanation
I'm reading 'Dive into Python' and the example below gives an explanation for each line but I'm still having trouble interpreting the meaning. Can someone shed some more light on number 1 and 2. I don't understand #1 when it starts stating about the basic technique of this wrapp... | UserDict Normal methods explanation | I'm reading 'Dive into Python' and the example below gives an explanation for each line but I'm still having trouble interpreting the meaning. Can someone shed some more light on number 1 and 2. I don't understand #1 when it starts stating about the basic technique of this wrapper class...etc... #2 I don't understand ... | [
"As for point 1. It just recalls the basics of a wrapper class... IMHO the documentation-block of the clear-method is not really the best place for recalling these basics....\nAs for point 2. When calling the copy-method of your object you aim to copy your instance, and not the datastore inside the instance ('self.... | [
0
] | [] | [] | [
"copy",
"methods",
"python"
] | stackoverflow_0007672308_copy_methods_python.txt |
Q:
Pyplot/Matplotlib: How to access figures opened by another interpreter?
I am using matplotlib.pyplot (with Eclipse on Windows). Every time I run my code it opens several pyplot figure windows.
The problem is that if I don't close those windows manually they accumulate. I would like to use pyplot to find those win... | Pyplot/Matplotlib: How to access figures opened by another interpreter? | I am using matplotlib.pyplot (with Eclipse on Windows). Every time I run my code it opens several pyplot figure windows.
The problem is that if I don't close those windows manually they accumulate. I would like to use pyplot to find those windows (opened by another process of python.exe) and re-use them. In other word... | [
"There is no simple way to reuse plot windows if you must use eclipse to run it. When I am working interactively with matplotlib, I use either spyder or ipython. Edit class, reload class, and run code again. If you just want to get rid of all the open plot windows, hit the stacked stop icons to kill all your runi... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007655323_matplotlib_python.txt |
Q:
Combining XML data with data type information from XML Schema
I would like to automate creating a flat list/array type structure in a language such as Ruby,Python etc that takes XML data and for each node builds a list/array entry that contains the data plus data type information obtained from its XML Schema.
Any ... | Combining XML data with data type information from XML Schema | I would like to automate creating a flat list/array type structure in a language such as Ruby,Python etc that takes XML data and for each node builds a list/array entry that contains the data plus data type information obtained from its XML Schema.
Any pointers to a solution appreciated.
Cheers.
| [
"In python, there are several xml parsing libraries, but I'd recommend lxml. Then, it's a piece of cake. Just iterate through your xml and this way you have access to data, attributes etc. Filling a list out of them is trivial. Just a little experimentation...\n"
] | [
0
] | [] | [] | [
"python",
"ruby",
"schema",
"xml"
] | stackoverflow_0007672959_python_ruby_schema_xml.txt |
Q:
Converting float.hex() value to binary in Python
I am wondering how to convert the result returned by float.hex() to binary, for example, from 0x1.a000000000000p+2 to 110.1.
Can anyone please help? Thanks.
A:
def float_to_binary(num):
exponent=0
shifted_num=num
while shifted_num != int(shifted_num): ... | Converting float.hex() value to binary in Python | I am wondering how to convert the result returned by float.hex() to binary, for example, from 0x1.a000000000000p+2 to 110.1.
Can anyone please help? Thanks.
| [
"def float_to_binary(num):\n exponent=0\n shifted_num=num\n while shifted_num != int(shifted_num): \n shifted_num*=2\n exponent+=1\n if exponent==0:\n return '{0:0b}'.format(int(shifted_num))\n binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)\n integer_part=binary... | [
10,
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007666713_python.txt |
Q:
Django admin list_display property usage
I have models and their admin code at below. The question is how can I show the first three tag of a book in its list_display property ?
I can show the tags while the book is editing but I would like to its 3 tags while the book are listed in the admin panel.
models.py
cla... | Django admin list_display property usage | I have models and their admin code at below. The question is how can I show the first three tag of a book in its list_display property ?
I can show the tags while the book is editing but I would like to its 3 tags while the book are listed in the admin panel.
models.py
class Book(models.Model):
name = models.CharF... | [
"Use a custom method on the admin class.\nclass BookAdmin(admin.ModelAdmin):\n list_display = ('name', 'three_tags')\n\n def three_tags(self, obj):\n return obj.booktag_set.all()[:3]\n\n"
] | [
15
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0007674072_django_django_admin_python.txt |
Q:
Python import parent file
I have 3 files, file 1 imports file 2, file 2 imports file 3 and file 3 needs to refference something in file 1. A basic example of this is
#---------------------File1.py---------------------
import File2
class core():
def __init__(self):
self.something = "Hello World"
... | Python import parent file | I have 3 files, file 1 imports file 2, file 2 imports file 3 and file 3 needs to refference something in file 1. A basic example of this is
#---------------------File1.py---------------------
import File2
class core():
def __init__(self):
self.something = "Hello World"
self.run = File2.run()
c = c... | [
"\nI don't really want to have to change things around.\n(...)\nWhat's the best way to go about this?\n\nI hate to break this to you, but the best way is to refactor the code; i.e., to shuffle things around. You don't want circular dependencies, they're going to make life hard on you in the long run. A hierarchical... | [
6,
1,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0007674052_import_python.txt |
Q:
how to generate 1 million random integers and write them to a file?
I was trying to do some tests on my external sorting algorithms, and I thought I should generate a huge amount of random numbers and put them into a file.
Here is how I do it:
import tempfile, random
nf = tempfile.NamedTemporaryFile(delete=False)... | how to generate 1 million random integers and write them to a file? | I was trying to do some tests on my external sorting algorithms, and I thought I should generate a huge amount of random numbers and put them into a file.
Here is how I do it:
import tempfile, random
nf = tempfile.NamedTemporaryFile(delete=False)
i = 0
while i < 1000:
j = 0
buf = ''
while j < 1000:
... | [
"Operating systems are already optimized for such I/O operations. So, you can directly write the numbers to file and get a very good speed:\nimport tempfile, random\n\nwith tempfile.NamedTemporaryFile(delete=False) as nf:\n for _ in xrange(1000000): # xrange() is more efficient than range(), in Python 2\n ... | [
7,
3,
2,
1,
1
] | [
"Doing a million of anything is going to be relatively slow. Also, depending on how random you want the numbers, you may want to invest in a more robust random integer generator. This is a personal favorite: http://en.wikipedia.org/wiki/Mersenne_twister\n"
] | [
-2
] | [
"file_io",
"python",
"random"
] | stackoverflow_0007671538_file_io_python_random.txt |
Q:
Code for playing video in wx.Media after the wmv file is loaded
I am a newbie in wxPython and I have to write a code that can immediately start playing a video after I load the file. I have been going through a lot of forums tried to implement 10 - 20 codes, but the wx.media is not playing the video file at all. I... | Code for playing video in wx.Media after the wmv file is loaded | I am a newbie in wxPython and I have to write a code that can immediately start playing a video after I load the file. I have been going through a lot of forums tried to implement 10 - 20 codes, but the wx.media is not playing the video file at all. I am able to load the file but not play it.
I need a simple code in wh... | [
"You can find a tutorial for the wx.media module here.\nYou have to call Load(path) and Play() on your MediaCtrl object.\nIt would be a good idea for future posts to include a small snippet of your code, so that we can know what exactly you have tried.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007674442_python.txt |
Q:
App Engine httplib.HTTPConnection deadline
Since App Engine's httplib is simply wrapped around their own urlfetch, I'm wondering how to set the default urlfetch timeout to the allowed maximum 10 seconds so that it will affect httplib.HTTPConnection.
I can't directly set the timeout on HTTPConnection, as GAE uses ... | App Engine httplib.HTTPConnection deadline | Since App Engine's httplib is simply wrapped around their own urlfetch, I'm wondering how to set the default urlfetch timeout to the allowed maximum 10 seconds so that it will affect httplib.HTTPConnection.
I can't directly set the timeout on HTTPConnection, as GAE uses 2.5. 2.6 added the timeout param.
| [
"Have you tried changing the default urlfetch deadline?\nimport urlfetch\nurlfetch.set_default_fetch_deadline(10)\n\n"
] | [
8
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007673404_google_app_engine_python.txt |
Q:
django excel xlwt
On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using xlwt, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this snippet but it doesn... | django excel xlwt | On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using xlwt, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this snippet but it doesn't do what I need. All ... | [
"neat package! i didn't know about this\nAccording to the doc, the save(filename_or_stream) method takes either a filename to save on, or a file-like stream to write on.\nAnd a Django response object happens to be a file-like stream! so just do xls.save(response). Look the Django docs about generating PDFs with R... | [
56,
6,
2,
2,
1,
0
] | [] | [] | [
"django",
"excel",
"python",
"xlwt"
] | stackoverflow_0000883313_django_excel_python_xlwt.txt |
Q:
I'm looking for a graph-database for a Java/Python centric organization
At work we want our next generation product to be based on a graph database. I'm looking for suggestions as to what database engine might be appropriate for our new project:
Out product is intended to keep track of a large number of prices for... | I'm looking for a graph-database for a Java/Python centric organization | At work we want our next generation product to be based on a graph database. I'm looking for suggestions as to what database engine might be appropriate for our new project:
Out product is intended to keep track of a large number of prices for goods. Here's a simplistic example of what it does - supposing you wanted to... | [
"Neo4J is the most mature graphDB I know of - and is java, with bindings for python too, or REST \n"
] | [
3
] | [] | [] | [
"database",
"graph",
"java",
"python"
] | stackoverflow_0007674895_database_graph_java_python.txt |
Q:
Fab not finding host key
Thank you for taking the time to look at my post.
I have a django site up and running, and I am trying to run a command on the remote (ubuntu) host from my local (windows) computer via fab. I have set the env.key_filename, but every time I run a command I am prompted for the user's passwor... | Fab not finding host key | Thank you for taking the time to look at my post.
I have a django site up and running, and I am trying to run a command on the remote (ubuntu) host from my local (windows) computer via fab. I have set the env.key_filename, but every time I run a command I am prompted for the user's password.
Does anyone have any sugges... | [
"Looks to me like Fabric issue #265. You should use an OpenSSH key, not a .ppk.\n"
] | [
3
] | [] | [] | [
"django",
"fabric",
"key",
"python",
"ssh"
] | stackoverflow_0007674823_django_fabric_key_python_ssh.txt |
Q:
How to compile all resources into one executable file?
I've wrote GTK application with python.
All graphical user interface is in glade file, and there are some images used. I wish to compile my application into EXEcutable file. For that I'm using PyInstaller compiler and UPX packer.
I've done as manual says:
pyth... | How to compile all resources into one executable file? | I've wrote GTK application with python.
All graphical user interface is in glade file, and there are some images used. I wish to compile my application into EXEcutable file. For that I'm using PyInstaller compiler and UPX packer.
I've done as manual says:
python Configure.py
python Makespec.py --onefile --windowed --up... | [
"With a few changes, you can incorporate everything into your source code and thus into your executable file.\nIf you run gdk-pixbuf-csource on your image files, you can convert them into strings, which you can then load using gtk.gdk.pixbuf_new_from_inline().\nYou can also include your Glade file as a string in th... | [
6,
6,
1
] | [] | [] | [
"compiler_construction",
"glade",
"pygtk",
"pyinstaller",
"python"
] | stackoverflow_0006689410_compiler_construction_glade_pygtk_pyinstaller_python.txt |
Q:
vt100 terminal emulation with python / browser
I am trying to build a SSH client for the web browser (similar to ajaxterm). I have built a python backend that uses Paramiko's SSHClient.invoke_shell(term='vt100') and a web server which communicates with a frontend (HTML + AJAX). The system works and displays output... | vt100 terminal emulation with python / browser | I am trying to build a SSH client for the web browser (similar to ajaxterm). I have built a python backend that uses Paramiko's SSHClient.invoke_shell(term='vt100') and a web server which communicates with a frontend (HTML + AJAX). The system works and displays output when I send commands through SSH channel, but the o... | [
"I've tried to do the same thing a few days ago. I didn't finished it, but I found a few python terminal emulator libs.\nI choose pyte, which has a clean API and is easy to use. A list of other libs doing the same job is available at the end of pyte's README.\n"
] | [
4
] | [] | [] | [
"python",
"ssh",
"terminal",
"vt100"
] | stackoverflow_0007674295_python_ssh_terminal_vt100.txt |
Q:
Python non-greedy regex to clean xml
I have an 'xml file' file that has some unwanted characters in it
<data>
<tag>blar </tag><tagTwo> bo </tagTwo>
some extra
characters not enclosed that I want to remove
<anothertag>bbb</anothertag>
</data>
I thought the following non-greedy substitution would remove th... | Python non-greedy regex to clean xml | I have an 'xml file' file that has some unwanted characters in it
<data>
<tag>blar </tag><tagTwo> bo </tagTwo>
some extra
characters not enclosed that I want to remove
<anothertag>bbb</anothertag>
</data>
I thought the following non-greedy substitution would remove the characters that were not properly encase... | [
"The dot does not match newlines unless you specify the re.DOTALL flag.\nre.sub(\"</([a-zA-Z]+)>.*?<\",\"</\\\\1><\",text, flags=re.DOTALL)\n\nshould work fine. (If it does not, my python is at fault, not the regex. Please correct.)\nI think it is good practise to be as precise as possible when defining character c... | [
3,
1
] | [] | [] | [
"non_greedy",
"python",
"regex",
"regex_greedy"
] | stackoverflow_0007671112_non_greedy_python_regex_regex_greedy.txt |
Q:
Read/Write text files in Python
I'm fairly new to Python and don't fully understand all items and I've been given a base for a programme and I need to alter bits, here's what I have so far:
import sys, os
filename = 'C:\main\in.txt'
resultFile = 'C:\main\out.txt'
try:
file = open( filena... | Read/Write text files in Python | I'm fairly new to Python and don't fully understand all items and I've been given a base for a programme and I need to alter bits, here's what I have so far:
import sys, os
filename = 'C:\main\in.txt'
resultFile = 'C:\main\out.txt'
try:
file = open( filename, "w" )
except Exception, e:
... | [
" logger.critical( \"Failed to create file \\\"%s\\\" : %s\" % ( filename, e )\n\nHas 2 left ( and only 1 right ). This appears to be a syntax error. \nSince the statement isn't complete, Python continues parsing. The error message shows up on the following line.\n\nRead this: http://docs.python.org/libra... | [
3
] | [] | [] | [
"exception",
"file",
"python"
] | stackoverflow_0007675433_exception_file_python.txt |
Q:
DB Permissions with Django unit testing
Disclaimer:
I'm very new to Django. I must say that so far I really like it. :)
(now for the "but"...)
But, there seems to be something I'm missing related to unit testing. I'm working on a new project with an Oracle backend. When you run the unit tests, it immediately g... | DB Permissions with Django unit testing | Disclaimer:
I'm very new to Django. I must say that so far I really like it. :)
(now for the "but"...)
But, there seems to be something I'm missing related to unit testing. I'm working on a new project with an Oracle backend. When you run the unit tests, it immediately gives a permissions error when trying to creat... | [
"Don't force Django to do something unnatural.\n\nAllow it to create the test schema. It's a good thing.\nFrom your existing schema, do an unload to create .JSON dump files of the data. These files are your \"fixtures\". These fixtures are used by Django to populate the test database. This is The Greatest Testi... | [
2,
2,
2,
0,
0
] | [] | [] | [
"database",
"django",
"python",
"unit_testing"
] | stackoverflow_0002195791_database_django_python_unit_testing.txt |
Q:
Python's MySqlDB not getting updated row
I have a script that waits until some row in a db is updated:
con = MySQLdb.connect(server, user, pwd, db)
When the script starts the row's value is "running", and it waits for the value to become "finished"
while(True):
sql = '''select value from table where some_cond... | Python's MySqlDB not getting updated row | I have a script that waits until some row in a db is updated:
con = MySQLdb.connect(server, user, pwd, db)
When the script starts the row's value is "running", and it waits for the value to become "finished"
while(True):
sql = '''select value from table where some_condition'''
cur = self.getCursor()
cur.ex... | [
"This is an InnoDB table, right? InnoDB is transactional storage engine. Setting autocommit to true will probably fix this behavior for you.\nconn.autocommit(True)\n\nAlternatively, you could change the transaction isolation level. You can read more about this here:\nhttp://dev.mysql.com/doc/refman/5.0/en/set-trans... | [
17,
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001617637_mysql_python.txt |
Q:
Django - Limit choices to something that depends on the instance
I have some foos which are organized into categories. For each category, I want to be able to select a winner foo.
Hence I have models which look like this:
class Category(models.Model):
name = models.CharField(max_length=30)
# More fields...... | Django - Limit choices to something that depends on the instance | I have some foos which are organized into categories. For each category, I want to be able to select a winner foo.
Hence I have models which look like this:
class Category(models.Model):
name = models.CharField(max_length=30)
# More fields...
winner = models.ManyToManyField(
'Foo',
related_n... | [
"There is no way to put constraint on M2M field on the models level (ie with limit_choices_to). However, you can do this in the form:\nclass MyForm(forms.ModelForm):\n class Meta:\n model = models.Category\n\n def __init__(self, *args, **kwargs):\n super(MyForm, self).__init__(*args, **kwargs)\n... | [
6
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0007672826_django_django_admin_django_models_python.txt |
Q:
Using python, daemonizing a process
Okay I have looked at python-daemon, and also at various other daemon related code recipes. Are there any 'hello world' tutorials out there that can help me get started using a python based daemonized process?
A:
The PEP 3143 contains several examples, the simplest one of whic... | Using python, daemonizing a process | Okay I have looked at python-daemon, and also at various other daemon related code recipes. Are there any 'hello world' tutorials out there that can help me get started using a python based daemonized process?
| [
"The PEP 3143 contains several examples, the simplest one of which is:\nimport daemon\n\nfrom spam import do_main_program\n\nwith daemon.DaemonContext():\n do_main_program()\n\nThis seems as straightforward as it gets. If there's something that's unclear, please pose specific questions.\n"
] | [
5
] | [
"Using subprocess.Popen, you can launch another process that will survive your current process...\nIn a python console run :\nimport subprocess\nsubprocess.Popen([\"/bin/sh\", \"-c\", \"sleep 500\"])\n\nKill your console, look at existing processes, sleep is alive...\n"
] | [
-3
] | [
"daemon",
"process",
"python",
"python_daemon"
] | stackoverflow_0007675573_daemon_process_python_python_daemon.txt |
Q:
Embed python/dsl for scripting in an PHP web application
I'm developing an web based application written in PHP5, which basically is an UI on top of a database. To give users a more flexible tool I want to embed a scripting language, so they can do more complex things like fire SQL queries, do loops and store data... | Embed python/dsl for scripting in an PHP web application | I'm developing an web based application written in PHP5, which basically is an UI on top of a database. To give users a more flexible tool I want to embed a scripting language, so they can do more complex things like fire SQL queries, do loops and store data in variables and so on. In my business domain Python is widel... | [
"How about doing the scripting on the client. That will ensure maximum security and also save server resources.\nIn other words Javascript would be your scripting platform. What you do is expose the functionality of your backend as javascript functions. Depending on how your app is currently written that might requ... | [
3,
2,
1,
1,
0,
0
] | [] | [] | [
"dsl",
"php",
"plpgsql",
"python"
] | stackoverflow_0007528360_dsl_php_plpgsql_python.txt |
Q:
Twisted, MySQLdb and (2006, 'MySQL server has gone away') using Twisted adbapi
In twisted I am a perpetual event loop that is always lookig for a new query to run It polls a SQS queue and are are times where time between queres is long enough to time out and this is the error I get when a new query arrives...
My... | Twisted, MySQLdb and (2006, 'MySQL server has gone away') using Twisted adbapi | In twisted I am a perpetual event loop that is always lookig for a new query to run It polls a SQS queue and are are times where time between queres is long enough to time out and this is the error I get when a new query arrives...
MySQLdb _mysql_exceptions.OperationalError: (2006, 'MySQL server has
gone away')
he... | [
"I have no experience with adbapi, but cp_reconnect parameter, mentioned in docs, looks promising.\nThus your pool initialization will look something like:\nself.pool = adbapi.ConnectionPool(\"MySQLdb\", self.parms['host'], self.parms['username'], self.parms['password'], self.parms['database'], cp_reconnect=True)\... | [
2
] | [] | [] | [
"mysql",
"mysql_python",
"python",
"timeout",
"twisted"
] | stackoverflow_0007656499_mysql_mysql_python_python_timeout_twisted.txt |
Q:
Python, SQLAlchemy and Postgresql: understanding inheritance
Pretty recent (but not newborn) to both Python, SQLAlchemy and Postgresql, and trying to understand inheritance very hard.
As I am taking over another programmer's code, I need to understand what is necessary, and where, for the inheritance concept to wo... | Python, SQLAlchemy and Postgresql: understanding inheritance | Pretty recent (but not newborn) to both Python, SQLAlchemy and Postgresql, and trying to understand inheritance very hard.
As I am taking over another programmer's code, I need to understand what is necessary, and where, for the inheritance concept to work.
My questions are:
Is it possible to rely only on SQLAlchemy f... | [
"Welcome to Stack Overflow: in the future, if you have more than one question; you should provide a separate post for each. Feel free to link them together if it might help provide context.\nTable inheritance in postgres is a very different thing and solves a different set of problems from class inheritance in py... | [
4,
0
] | [] | [] | [
"inheritance",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0007672569_inheritance_postgresql_python_sqlalchemy.txt |
Q:
Passing a valid path to Python from PHP
I have a Python program that parses files, takes a path as and argument and parses all files in the given path and all sub directories - using os.walk(path). I want to call this from my php Web App, so the user can specify a path, which is then passed as an argument to the p... | Passing a valid path to Python from PHP | I have a Python program that parses files, takes a path as and argument and parses all files in the given path and all sub directories - using os.walk(path). I want to call this from my php Web App, so the user can specify a path, which is then passed as an argument to the parser. (Passing a path is ok because its all ... | [
"Check to see what user the PHP server is running as. If I:\\ is a network drive, don't expect those to be mapped under that user. Use a UNC path instead.\nThings to try:\n\na different path (we know C:\\Workspaces\\parsers\\src\\main\\ works, why don't you try that?)\n\n"
] | [
1
] | [] | [] | [
"php",
"python"
] | stackoverflow_0007673563_php_python.txt |
Q:
Matplotlib imshow zoom function?
I have several (27) images represented in 2D arrays that I am viewing with imshow(). I need to zoom in on the exact same spot in every image. I know I can manually zoom, but this is tedious and not precise enough. Is there a way to programmatically specify a specific section of the... | Matplotlib imshow zoom function? | I have several (27) images represented in 2D arrays that I am viewing with imshow(). I need to zoom in on the exact same spot in every image. I know I can manually zoom, but this is tedious and not precise enough. Is there a way to programmatically specify a specific section of the image to show instead of the entire t... | [
"You could use plt.xlim and plt.ylim to set the region to be plotted:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata=np.arange(9).reshape((3,3))\nplt.imshow(data)\nplt.xlim(0.5, 1.5)\nplt.ylim(0.5,1.5)\nplt.show()\n\n",
"If you do not need the rest of your image, you can define a function that crop ... | [
22,
5
] | [] | [] | [
"image",
"matplotlib",
"python"
] | stackoverflow_0007665076_image_matplotlib_python.txt |
Q:
Inner-mosts Lists in Python
Why? Look they are equal, initially. You do the same operation but hey you get different structures. Why do the two methods of constructing nested lists give different results?
>>> lll=[[[[[]]*2 for a in xrange(2)] for b in xrange(2)]]
>>> ll=[[[[[]]*2]*2]*2]
>>> lll
[[[[[], []], [[], [... | Inner-mosts Lists in Python | Why? Look they are equal, initially. You do the same operation but hey you get different structures. Why do the two methods of constructing nested lists give different results?
>>> lll=[[[[[]]*2 for a in xrange(2)] for b in xrange(2)]]
>>> ll=[[[[[]]*2]*2]*2]
>>> lll
[[[[[], []], [[], []]], [[[], []], [[], []]]]]
>>> l... | [
"Well, ll and lll don't compare equal because they contain different values:\nIn [3]: ll[0][0][0][0]=1\n\nIn [4]: lll[0][0][0][0]=1\n\nIn [5]: ll\nOut[5]: [[[[1, []], [1, []]], [[1, []], [1, []]]]]\n\nIn [6]: lll\nOut[6]: [[[[1, []], [[], []]], [[[], []], [[], []]]]]\n\nNow, let's step back and take a simpler examp... | [
4,
3,
1
] | [] | [] | [
"list",
"list_comprehension",
"python",
"reference"
] | stackoverflow_0007676043_list_list_comprehension_python_reference.txt |
Q:
Parsing numbers of integer and real type in string
I have got a list of strings of the following format:
[ "%AB0.1.100", "%TB4.1.15" ]
How i can parse this strings, that a i'd like to take for 1st element of list "0.1" of real type and "100" of integer type and "4.1" of real type and "15" of integer type.
How i c... | Parsing numbers of integer and real type in string | I have got a list of strings of the following format:
[ "%AB0.1.100", "%TB4.1.15" ]
How i can parse this strings, that a i'd like to take for 1st element of list "0.1" of real type and "100" of integer type and "4.1" of real type and "15" of integer type.
How i can do this in loop ?
| [
">>> import re\n>>> l = [ \"%AB0.1.100\", \"%TB4.1.15\" ]\n>>> out = []\n>>> for item in l:\n... m = re.search(r\"(\\d+\\.\\d+)\\.(\\d+)\", item)\n... f = float(m.group(1))\n... i = int(m.group(2))\n... out.append((f, i))\n...\n>>> out\n[(0.1, 100), (4.1, 15)]\n\n",
"l = [ \"%AB0.1.100\", \"%TB4.1.15\... | [
1,
1,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0007672921_parsing_python.txt |
Q:
Is there any Image processing library for Python 2.5 that does not require external dependencies under Windows?
I observed that there are (too) many ImageMagick libraries for Python but I found none that can just be installed and that will include the ImageMagick libraries.
I am looking for something can be be eas... | Is there any Image processing library for Python 2.5 that does not require external dependencies under Windows? | I observed that there are (too) many ImageMagick libraries for Python but I found none that can just be installed and that will include the ImageMagick libraries.
I am looking for something can be be easily installed and that has to work with Python 2.5 (please, don't ask me why 2.5!)
| [
"Did you try the Python Imaging Library (PIL)? They have got an installer for Python 2.5 and I don't think there are further dependencies.\n",
"I won't ask you why 2.5, don't worry - but I am pretty happy with Python Imaging Library. \nI work mostly on Windows, and while PIL has its glitches, it works just fine. ... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0007672493_python.txt |
Q:
How source object can receive feedback information of object at dropping moment (DataSource)?
I have one window - EditWindow ( object of class, which is inherit wx.Frame ), which contain Grid object (self.grid).
In this class i write this method:
def OnSubindexGridCellLeftClick( self, event ):
....
... | How source object can receive feedback information of object at dropping moment (DataSource)? | I have one window - EditWindow ( object of class, which is inherit wx.Frame ), which contain Grid object (self.grid).
In this class i write this method:
def OnSubindexGridCellLeftClick( self, event ):
....
dragSource = MyDropSource( self.grid )
dragSource.SetData( data )
dragSource.DoDra... | [
"You could use pubsub to send the data to the EditorWindow and then display it. Do the sending in the OnDropText method only so it only sends when you actually drop at the end of the drag. Here's a simple tutorial on pubsub to get you going: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-... | [
1,
0
] | [] | [] | [
"drag_and_drop",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0007674311_drag_and_drop_python_wxpython_wxwidgets.txt |
Q:
How do i pass parameters to a class based view in django?
I have the following class based view;
class myClassView():
def get(self):
# lots of code ...
return response
My urlconf for this looks like
(r^'call_myClassView/', myClassView.as_view())
I want to pass parameters to the urlconf the ol... | How do i pass parameters to a class based view in django? | I have the following class based view;
class myClassView():
def get(self):
# lots of code ...
return response
My urlconf for this looks like
(r^'call_myClassView/', myClassView.as_view())
I want to pass parameters to the urlconf the old functional way
(r'call_myClassView/(?P<id>\w+)/$',myClassView... | [
"They are passed in the old way.\nYou access them via self.args and self.kwargs, for positional and keyword arguments respectively. In your case, self.kwargs['id'] would do the trick.\nEdit because you've overridden get() but not preserved the signature. If you're overriding a method, always do def get(self, reques... | [
13
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007676815_django_python.txt |
Q:
Consume WSDL url with XML with escaped chars as argument
I am executing a method of a SOAP web service which receives 3 string arguments with suds library.
The first string argument should be an XML and the other 2 an username and password, this is my semi-working implementation.
from suds.client import Client
url... | Consume WSDL url with XML with escaped chars as argument | I am executing a method of a SOAP web service which receives 3 string arguments with suds library.
The first string argument should be an XML and the other 2 an username and password, this is my semi-working implementation.
from suds.client import Client
url = "http://www.jonima.com.mx:3014/sefacturapac/TimbradoService... | [
"You are easily able to 'escape' any XML values before it goes over to the service. Check out http://wiki.python.org/moin/EscapingXml \n>>> from xml.sax.saxutils import escape\n>>>\n>>> escape(\"< & >\")\n'< & >'\n\nThis has worked for me in the past to do exactly what you're describing, pass XML data ove... | [
2,
2,
1
] | [] | [] | [
"django",
"python",
"soap",
"wsdl",
"xml"
] | stackoverflow_0007619328_django_python_soap_wsdl_xml.txt |
Q:
What is the advantage in using `exec` over `type()` when creating classes at runtime?
I want to dynamically create classes at runtime in python.
For example, I want to replicate the code below:
>>> class RefObj(object):
... def __init__(self, ParentClassName):
... print "Created RefObj with ties to %s"... | What is the advantage in using `exec` over `type()` when creating classes at runtime? | I want to dynamically create classes at runtime in python.
For example, I want to replicate the code below:
>>> class RefObj(object):
... def __init__(self, ParentClassName):
... print "Created RefObj with ties to %s" % ParentClassName
... class Foo1(object):
... ref_obj = RefObj("Foo1")
... class Foo2(... | [
"I would recommend type over exec here.\nIn fact, the class statement is just syntactic sugar for a call to type: The class body is executed within its own namespace, which is then passed on to the metaclass, which defaults to type if no custom metaclass is specified.\nThis approach is less errorprone since there ... | [
7,
4,
2
] | [] | [] | [
"dynamic_class_creation",
"namedtuple",
"python"
] | stackoverflow_0007676947_dynamic_class_creation_namedtuple_python.txt |
Q:
Identifying important words and phrases in text
I have text stored in a python string.
What I Want
To identify key words in that text.
to identify N-grams in that text (ideally more than just bi and tri grams).
Keep in mind...
The text might be small (e.g. tweet sized)
The text might be middle (e.g. news articl... | Identifying important words and phrases in text | I have text stored in a python string.
What I Want
To identify key words in that text.
to identify N-grams in that text (ideally more than just bi and tri grams).
Keep in mind...
The text might be small (e.g. tweet sized)
The text might be middle (e.g. news article sized)
The text might be large (e.g. book or chapte... | [
"As for the best way to identify the most unique individual key words, tfidf is the total measure. So, you have somehow to integrate a search engine ( or make a simple custom inverted index that is dynamic and holds term frequencies, document frequencies ) as to calculate tfidf efficiently and on-the-fly.\nAs for y... | [
1
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0007677201_nlp_nltk_python.txt |
Q:
matrix holes comprehension
This is an offshoot of a previous question which started to snowball. If I have a matrix A and I want to use the mean/average of each row [1:] values to create another matrix B, but keep the row headings intact, this list comprehension works.
from operator import mul,len
# matrix A wit... | matrix holes comprehension | This is an offshoot of a previous question which started to snowball. If I have a matrix A and I want to use the mean/average of each row [1:] values to create another matrix B, but keep the row headings intact, this list comprehension works.
from operator import mul,len
# matrix A with row headings and values
A = [(... | [
"This doesn't work because x is not necessarily a number (you don't tell us what it is either).\nSo you probably have to write your own summing function that checks whether an item is an x or something else (maybe you'll have to use isinstance(element, int) or isinstance(element, float)).\n",
"In average(), use a... | [
0,
0,
0
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0007677316_list_list_comprehension_python.txt |
Q:
List assignment with [:]
What's the difference between
lst = range(100)
and
lst[:] = range(100)
Before that assignment the lst variable was already assigned to a list:
lst = [1, 2, 3]
lst = range(100)
or
lst = [1, 2, 3]
lst[:] = range(100)
A:
When you do
lst = anything
You're pointing the name lst at an obj... | List assignment with [:] | What's the difference between
lst = range(100)
and
lst[:] = range(100)
Before that assignment the lst variable was already assigned to a list:
lst = [1, 2, 3]
lst = range(100)
or
lst = [1, 2, 3]
lst[:] = range(100)
| [
"When you do\nlst = anything\n\nYou're pointing the name lst at an object. It doesn't change the old object lst used to point to in any way, though if nothing else pointed to that object its reference count will drop to zero and it will get deleted.\nWhen you do\nlst[:] = whatever\n\nYou're iterating over whatever,... | [
40,
4,
3,
2,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007677275_list_python.txt |
Q:
Looping Through Nested List - Convert from String to Float
I am new to Python, so apologies if this seems extremely simple:
I have a csv file with 4 columns and a dozen rows. I import the contests as a list (list of lists), and the contents come in as strings. What I want to do is loop through the list (which can ... | Looping Through Nested List - Convert from String to Float | I am new to Python, so apologies if this seems extremely simple:
I have a csv file with 4 columns and a dozen rows. I import the contests as a list (list of lists), and the contents come in as strings. What I want to do is loop through the list (which can be a variable number of rows) and convert the index 2 string to ... | [
"It's not necessary to cast your csv.reader to a list as it is already iterable. You can do something like the following:\nbenchmark=[]\nwith open('test.csv','r') as inp:\n csvin=csv.reader(inp)\n for row in csvin:\n benchmark.append(row[:1] + [float(row[1])] + row[2:])\n\n",
"This would probably wor... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007677500_python.txt |
Q:
python crontab alternative - APScheduler & python-daemon
I'm having trouble using
python-daemon 1.6 getting along with APScheduler to manage a list of tasks.
(The scheduler needs to run them periodically at a specific chosen times - seconds resolution)
Working (until pressing Ctrl+C),
from apscheduler.scheduler ... | python crontab alternative - APScheduler & python-daemon | I'm having trouble using
python-daemon 1.6 getting along with APScheduler to manage a list of tasks.
(The scheduler needs to run them periodically at a specific chosen times - seconds resolution)
Working (until pressing Ctrl+C),
from apscheduler.scheduler import Scheduler
import logging
import signal
def job_functio... | [
"I do not know much about python-daemon, but test_log in job_function() is not defined. The same problem occurs in init_schedule() where you reference Schedule.\n"
] | [
1
] | [] | [] | [
"python",
"python_daemon",
"scheduler"
] | stackoverflow_0007677441_python_python_daemon_scheduler.txt |
Q:
Is there a framework that can be used to test Python modules against several versions of Python?
I there a framework that can be used to run Python unit tests on all installed versions of python?
I have 3 versions of python installed on my system and I want to be able to run the unitests on all of them. The execut... | Is there a framework that can be used to test Python modules against several versions of Python? | I there a framework that can be used to run Python unit tests on all installed versions of python?
I have 3 versions of python installed on my system and I want to be able to run the unitests on all of them. The executables are using the "usual" naming convention: python2.5 python2.7 python3.2
My current environment i... | [
"tox does this and even more, like running the tests on multiple platforms too.\n"
] | [
7
] | [] | [] | [
"python",
"tox",
"unit_testing"
] | stackoverflow_0007677897_python_tox_unit_testing.txt |
Q:
What does the python re.template function do?
While using the re module in ipython I noticed an undocumented template function:
In [420]: re.template?
Type: function
Base Class: <type 'function'>
String Form: <function template at 0xb7eb8e64>
Namespace: Interactive
File: /usr/tidewa... | What does the python re.template function do? | While using the re module in ipython I noticed an undocumented template function:
In [420]: re.template?
Type: function
Base Class: <type 'function'>
String Form: <function template at 0xb7eb8e64>
Namespace: Interactive
File: /usr/tideway/lib/python2.7/re.py
Definition: re.template(p... | [
"In CPython 2.7.1, re.template() is defined as:\ndef template(pattern, flags=0):\n \"Compile a template pattern, returning a pattern object\"\n return _compile(pattern, flags|T)\n\n_compile calls _compile_typed which calls sre_compile.compile. The only place in the code where the T (aka SRE_FLAG_TEMPLATE) fla... | [
15
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007677889_python_regex.txt |
Q:
python - condensing comparisons
I'm a new member here and also new to python. My question is as follows, is it valid to have a line like this?
if x or y is 'whatever':
I tested this in the interpreter and am getting inconsistent results. It would seem that this line yields more consistent and expected results
if ... | python - condensing comparisons | I'm a new member here and also new to python. My question is as follows, is it valid to have a line like this?
if x or y is 'whatever':
I tested this in the interpreter and am getting inconsistent results. It would seem that this line yields more consistent and expected results
if (x or y) is 'whatever':
Or is it alw... | [
"or doesn't work like it does in English.\nx or y returns x if x is a true-ish value, otherwise it returns y. Strings are true-ish if they are not empty.\nWorse, \"is\" has a higher precedence that \"or\", so your expression is the same as x or (y is 'whatever'). So if x is not empty, it returns x (which will be ... | [
8,
3,
1,
1
] | [] | [] | [
"comparison",
"comparison_operators",
"python"
] | stackoverflow_0007678271_comparison_comparison_operators_python.txt |
Q:
Why is mixing 'from x import y' and 'import x' discouraged?
My script contains the following two lines as import-statements:
import os
from os import path
This seems a logical approach for my script: I use os.path very often, so I want to access it as path. On the other side, I need additional methods from os, bu... | Why is mixing 'from x import y' and 'import x' discouraged? | My script contains the following two lines as import-statements:
import os
from os import path
This seems a logical approach for my script: I use os.path very often, so I want to access it as path. On the other side, I need additional methods from os, but very rarely, so it is ok for me to write os.access(...) for exa... | [
"It's usually odd to both import a name from a module, and import the whole module. In this case, you are importing a submodule, so it doesn't seem bad, though most people do just use \"os.path\" in their function calls.\nJust because pychecker doesn't like it doesn't mean you can't do it. Turn off that warning.\... | [
6,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0007678276_import_python.txt |
Q:
How to see the number of finished or remaining map_async jobs?
I use iPython's parallel-processing facility for a big map operation. While waiting for the map operation to finish, I'd like to display to the user how many of the jobs have finished, how many are running, and how many are remaining. How can I find th... | How to see the number of finished or remaining map_async jobs? | I use iPython's parallel-processing facility for a big map operation. While waiting for the map operation to finish, I'd like to display to the user how many of the jobs have finished, how many are running, and how many are remaining. How can I find that information?
Here is what I do. I create a profile that uses a lo... | [
"the AsyncResult has a msg_ids attribute. The outstanding jobs are the intersection of that with rc.outstanding, and the completed jobs are the difference:\nmsgset = set(ar.msg_ids)\ncompleted = msgset.difference(rc.outstanding)\npending = msgset.intersection(rc.outstanding)\n\n"
] | [
3
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0007655825_ipython_python.txt |
Q:
Python suds - method not defined in service
I'm attempting to use suds to connect to a KnowledgeTree web service on my local network. I can create the client and retrieve the service information, but calling the login method listed there produces suds.WebFault: Server raised fault: 'method "login" not defined in ... | Python suds - method not defined in service | I'm attempting to use suds to connect to a KnowledgeTree web service on my local network. I can create the client and retrieve the service information, but calling the login method listed there produces suds.WebFault: Server raised fault: 'method "login" not defined in service'.
(Note: I had to use ImportDoctor to r... | [
"I had lots of issues trying to use suds to connect to KT. Below is the module I ended up using.\nfrom suds.client import Client\nfrom suds.xsd.doctor import ImportDoctor, Import\nfrom suds.plugin import Plugin\n\nimport urllib\n\nclass SessionProxy:\n \"\"\"\n All methods (except login) wants sessionid as fi... | [
3,
1
] | [] | [] | [
"python",
"soap",
"suds",
"wsdl"
] | stackoverflow_0006032174_python_soap_suds_wsdl.txt |
Q:
Using Fabric in Python
I have installed Fabric on Python2.6 using pip, and it has created two directories:
/Library/Python/2.6/site-packages/fabfile
/Library/Python/2.6/site-packages/fabric
When I initially ran the $ fab command it said "command not found". Then I made sure my system path included both folders, a... | Using Fabric in Python | I have installed Fabric on Python2.6 using pip, and it has created two directories:
/Library/Python/2.6/site-packages/fabfile
/Library/Python/2.6/site-packages/fabric
When I initially ran the $ fab command it said "command not found". Then I made sure my system path included both folders, and still I got "command not ... | [
"I did exactly what Torsen saids and it works for me.\nsudo find / | grep \"fab\"\n\nI found fab file at /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/fab on Mac OS X.\n",
"Executives like this are usually not copied to your library folder of python (so not in site-packages). In Ubuntu this one ... | [
3,
1
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0007141823_fabric_python.txt |
Q:
python os.popen fails when given umlauted character
Under winxp (pro x64 version 2003, sp2), running the following at cmd prompt works fine:
dir C:\testüüüdirectory\
Please note the 'ü' character.
But from python 2.7.1.4, the following always returns an error code 1:
>>> res = os.popen("dir C:\\testüüüdirectory\\... | python os.popen fails when given umlauted character | Under winxp (pro x64 version 2003, sp2), running the following at cmd prompt works fine:
dir C:\testüüüdirectory\
Please note the 'ü' character.
But from python 2.7.1.4, the following always returns an error code 1:
>>> res = os.popen("dir C:\\testüüüdirectory\\")
>>> res.close()
1
>>>
How can i get popen to accept t... | [
"This would probably be an encoding issue, where your input doesn't quite match what the file system expects on output. First, you'll need to tell Python what encoding your input uses, then what encoding the popen() call expects.\n>>> filename = \"C:\\\\testüüüdirectory\\\\\".decode(\"utf-8\")\n>>> res = os.popen(... | [
3,
0
] | [] | [] | [
"popen",
"python",
"windows"
] | stackoverflow_0007678677_popen_python_windows.txt |
Q:
How to run my tests from inside setup.py (setuptools)?
I know the setuptools has an option to run your tests but I didn't find any information regarding how to make it run my tests.
By default my tests are included with the module and I use discovery to detect and run them-all.
Any ideas?
A:
Use the test command... | How to run my tests from inside setup.py (setuptools)? | I know the setuptools has an option to run your tests but I didn't find any information regarding how to make it run my tests.
By default my tests are included with the module and I use discovery to detect and run them-all.
Any ideas?
| [
"Use the test command option to setup.py (documented here) as extended by setuptools (or Distribute).\n"
] | [
1
] | [] | [] | [
"python",
"setuptools",
"unit_testing"
] | stackoverflow_0007678206_python_setuptools_unit_testing.txt |
Q:
Py_initialize / Py_Finalize not working twice with numpy
On the second call of the following code, my app segfault, so I guess I am missing something :
Py_Initialize();
pName = PyString_FromString("comp_macbeth");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if(pModule == NULL) {
PyErr_Print();
Py_... | Py_initialize / Py_Finalize not working twice with numpy | On the second call of the following code, my app segfault, so I guess I am missing something :
Py_Initialize();
pName = PyString_FromString("comp_macbeth");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if(pModule == NULL) {
PyErr_Print();
Py_Finalize();
return;
}
pFunc = PyObject_GetAttrString(pMod... | [
"From the Py_Finalize docs:\n\nSome extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.\n\nApparently Numpy is one of those. See also this message from Numpy-discussion.\nCalling Py_Initi... | [
16,
1
] | [] | [] | [
"c",
"numpy",
"python"
] | stackoverflow_0007676314_c_numpy_python.txt |
Q:
How do I turn this date into a python datetime object?
I want a datetime object, but I have strings in this format:
2010-10-06T08:12:41Z
How do I turn that into a datetime object?
A:
from datetime import datetime
print datetime.strptime(timestring, '%Y-%m-%dT%H:%M:%SZ')
it's in the docs
A:
import datetime
da... | How do I turn this date into a python datetime object? | I want a datetime object, but I have strings in this format:
2010-10-06T08:12:41Z
How do I turn that into a datetime object?
| [
"from datetime import datetime\nprint datetime.strptime(timestring, '%Y-%m-%dT%H:%M:%SZ')\n\nit's in the docs\n",
"import datetime\ndatetime.datetime.strptime(\"2010-10-06T08:12:41Z\", \"%Y-%m-%dT%H:%M:%SZ\")\n\n"
] | [
6,
2
] | [] | [] | [
"datetime",
"python",
"string",
"time"
] | stackoverflow_0007679269_datetime_python_string_time.txt |
Q:
Different threads accessing the same dictionaries (for read only)
I have a function (myFunc for e.g.) that takes a start and end date & iterates over it and accesses some dictionaries to process the data for this time period. I am looking to use threads to parallelize this code.
My main() function reads in data fr... | Different threads accessing the same dictionaries (for read only) | I have a function (myFunc for e.g.) that takes a start and end date & iterates over it and accesses some dictionaries to process the data for this time period. I am looking to use threads to parallelize this code.
My main() function reads in data from a bunch of files & stores them in dictionaries. Every time I call my... | [
"Using threading, no, you're not going to have a problem. You're also not going to achieve parallelism. The Global Interpreter Lock (GIL) in Python only allows a single thread to process at any time. If you want true parallel processing you need to look at the multiprocessing module. It has the ability to actua... | [
6
] | [] | [] | [
"conflict",
"dictionary",
"multithreading",
"python",
"thread_safety"
] | stackoverflow_0007679487_conflict_dictionary_multithreading_python_thread_safety.txt |
Q:
Python String Cleaning
I am writing a program in PyQT that needs to take messy strings and clean them up. The possible input values are extremely variable. For example I would like to take the strings:
"Seven_Pounds_(BDrip_1080p_ENG-ITA-GER)_Multisub_x264_bluray_.mkv",
"The_Birds_1963_HDTV_XvidHD_720p-NPW.avi"... | Python String Cleaning | I am writing a program in PyQT that needs to take messy strings and clean them up. The possible input values are extremely variable. For example I would like to take the strings:
"Seven_Pounds_(BDrip_1080p_ENG-ITA-GER)_Multisub_x264_bluray_.mkv",
"The_Birds_1963_HDTV_XvidHD_720p-NPW.avi",
"1892.XVID.AC3.HD.120_mi... | [
"From the looks of diff-match-patch, match being the closest to what you are talking about, it seems to me that its maybe not the best solution, as match apparently wants to find specific patterns (not regex rules)?\nI think you might want to define a series of regex rules, such as underscore being treated like a s... | [
2,
2,
2,
1,
0
] | [] | [] | [
"pyqt",
"python",
"regex"
] | stackoverflow_0007679119_pyqt_python_regex.txt |
Q:
defining sub-domain based on a function in routes.py of Web2Py
I have this page:
http://mysite.org/myapp/pages/blog?name=user9
and I need to have this:
user9.mysite.org
What should i write in my routes.py?
A:
Ok, so i think misinterpreted this a little. You need user9.mysite.org to be served from the web2py app.... | defining sub-domain based on a function in routes.py of Web2Py | I have this page:
http://mysite.org/myapp/pages/blog?name=user9
and I need to have this:
user9.mysite.org
What should i write in my routes.py?
| [
"Ok, so i think misinterpreted this a little. You need user9.mysite.org to be served from the web2py app. One way, if you have your site hosted at mysite.org, is to pass all requests (regardless of subdomain) to the web2py application (you'll need an A record like *.mysite.org with your DNS provider: http://kb.medi... | [
4
] | [] | [] | [
"blogs",
"python",
"urlrewriter",
"web2py"
] | stackoverflow_0007622961_blogs_python_urlrewriter_web2py.txt |
Q:
Create duplicates in a python dictionary (not keys, values)
The picture is the best way to explain my problem, but I'm trying to populate a dictionary object in python, such that each key in the dictionary has a value of a list. Currently, all keys point to the same list. This is not what I want. Instead, I want e... | Create duplicates in a python dictionary (not keys, values) | The picture is the best way to explain my problem, but I'm trying to populate a dictionary object in python, such that each key in the dictionary has a value of a list. Currently, all keys point to the same list. This is not what I want. Instead, I want each key to be associated with an independent copy of that list. I... | [
"You can use the slicing operator to make shallow copies of your list.\n>>> mylist = [1,2,3]\n>>> d = {1:mylist[:], 2:mylist[:], 3:mylist[:]}\n>>> d\n{1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}\n>>> d[1][0] = 23\n>>> d\n{1: [23, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}\n>>>\n\nIf your values are more complex than a list o... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0007679600_python.txt |
Q:
Python and Opswat
I need to trigger my AntiVirus (McAfee) when accessing a test-virus URL (http://eicar.org/download/eicar.com) via python. If I use IE, Firefox or even wget for windows, the AntiVirus detects that a virus URL was accessed, which is the expected behavior. However, when using urllib or urllib2, the ... | Python and Opswat | I need to trigger my AntiVirus (McAfee) when accessing a test-virus URL (http://eicar.org/download/eicar.com) via python. If I use IE, Firefox or even wget for windows, the AntiVirus detects that a virus URL was accessed, which is the expected behavior. However, when using urllib or urllib2, the virus URL is successful... | [
"Write the output to disk- the virus scanner will see it then.\n"
] | [
2
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0007679557_python_windows.txt |
Q:
Why pymongo doesn't work with python3 and it only works with python2
user@ubuntu:~/Documents/MongoDB$ python2
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pymongo import Connection
>>>
user@ubuntu:~/Document... | Why pymongo doesn't work with python3 and it only works with python2 | user@ubuntu:~/Documents/MongoDB$ python2
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pymongo import Connection
>>>
user@ubuntu:~/Documents/MongoDB$ python3
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC ... | [
"Probably because you didn't install it for Python 3. You have to install a module for each version of Python that you have in order to access it from that version.This is all assuming that the module is compatible with each version of Python that you have.\n"
] | [
2
] | [] | [] | [
"mongodb",
"pymongo",
"python",
"ubuntu_10.04"
] | stackoverflow_0007679896_mongodb_pymongo_python_ubuntu_10.04.txt |
Q:
Efficient and clean way of growing a tokenizer function in Python
I have a library that does some "translation" and uses the awesome tokenize.generate_tokens() function to do so.
And it is pretty fast and I have things working correctly. But when translating, I've found that the function keeps growing with new tok... | Efficient and clean way of growing a tokenizer function in Python | I have a library that does some "translation" and uses the awesome tokenize.generate_tokens() function to do so.
And it is pretty fast and I have things working correctly. But when translating, I've found that the function keeps growing with new tokens that I want to translate and the if and elif conditions start to po... | [
"You could use a dict dispatcher. For example, the code you linked to might look like this:\ndef process_number(result,tokval):\n if '.' in tokval:\n result.extend([\n (NAME, 'Decimal'),\n (OP, '('),\n (STRING, repr(tokval)),\n (OP, ')')\n ])\ndef pro... | [
3
] | [] | [] | [
"performance",
"python",
"tokenize"
] | stackoverflow_0007679641_performance_python_tokenize.txt |
Q:
Coding in Python
What is equivalent code in Python for this C++ code:
int T , i , a , b ;
scanf( "%d" , &T ) ;
for( i = 1 ; i <= T ; i++ ) {
scanf( "%d %d" , &a , &b ) ;
printf( "Case %d : %d\n " , i , a + b ) ;
}
Input:
2
1 7
9 8
Output:
Case 1: 8
Case 2: 17
A:
Something like this perhaps...
T = int(... | Coding in Python | What is equivalent code in Python for this C++ code:
int T , i , a , b ;
scanf( "%d" , &T ) ;
for( i = 1 ; i <= T ; i++ ) {
scanf( "%d %d" , &a , &b ) ;
printf( "Case %d : %d\n " , i , a + b ) ;
}
Input:
2
1 7
9 8
Output:
Case 1: 8
Case 2: 17
| [
"Something like this perhaps...\nT = int(raw_input())\nfor i in range(T):\n a, b = map(int, raw_input().split(' '))\n print(\"Case {0} : {1}\".format(i+1, a+b))\n\nSee it working online: ideone\nNotes\n\nUse input instead of raw_input in Python 3.x.\nThis code has no error handling if invalid input is entered... | [
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0007679978_c++_python.txt |
Q:
BeautifulSoup/LXML.html: delete tag and its children if child looks like x
I have a problem getting to the right solution. I want to delete <question> and its children if <answer> is = 99. As a result, I need a string with the filtered questions. I have the following html structure:
<html>
<body>
<quest... | BeautifulSoup/LXML.html: delete tag and its children if child looks like x | I have a problem getting to the right solution. I want to delete <question> and its children if <answer> is = 99. As a result, I need a string with the filtered questions. I have the following html structure:
<html>
<body>
<questionaire>
<question>
<questiontext>
Do I have a question?
</quest... | [
"This will do exactly what you need:\nfrom xml.dom import minidom\n\ndoc = minidom.parseString(text)\nfor question in doc.getElementsByTagName('question'):\n for answer in question.getElementsByTagName('answer'):\n if answer.childNodes[0].nodeValue.strip() == '99':\n question.parentNode.removeC... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"lxml",
"python"
] | stackoverflow_0007679793_beautifulsoup_lxml_python.txt |
Q:
Python: Store Token in Memory
I have a class and in that class I have a function that performs authentication and returns a token.
I would like to store that token in memory for use by other functions in that same class.
How would I do so ?
A:
Presuming a structure like this:
class myClass(object):
def doAu... | Python: Store Token in Memory | I have a class and in that class I have a function that performs authentication and returns a token.
I would like to store that token in memory for use by other functions in that same class.
How would I do so ?
| [
"Presuming a structure like this:\nclass myClass(object):\n def doAuth(self):\n callAuthProcedure()\n\nif callAuthProcedure returns the token, simply adjust it to do this:\nclass myClass(object):\n def doAuth(self):\n self.token = callAuthProcedure()\n\nLater, other methods on the instance of the class can ... | [
5
] | [] | [] | [
"memory",
"python",
"store",
"variables"
] | stackoverflow_0007679993_memory_python_store_variables.txt |
Q:
Print Data in Dictionary in Python
If I have a dictionary that looks like:
{'first': [
{'red': ['six', 'three', 'seven', 'six']},
{'green': ['eight', 'three', 'four']}
],
'second': [
{'blue': ['one', 'five', 'three']}
]
}
How can I get to specific points in the dictionary? For example, how can I pri... | Print Data in Dictionary in Python | If I have a dictionary that looks like:
{'first': [
{'red': ['six', 'three', 'seven', 'six']},
{'green': ['eight', 'three', 'four']}
],
'second': [
{'blue': ['one', 'five', 'three']}
]
}
How can I get to specific points in the dictionary? For example, how can I print out the second 'six' in the 'first' h... | [
"Assuming your dictionary is called d you could do this:\nprint(d['first'][0]['red'][3])\n\n\nThe expression d['first'] gives you the value associated with the key 'first'. The value is a list.\nThe [0] gives you the first element in the list (by the way, why do you have a list containing only one element?). Note t... | [
2,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007680054_dictionary_python.txt |
Q:
What's exactly happening in infinite nested lists?
It's possible to create an infinite nested list in Python. That's clear and, although not popular and definitely not useful is a known fact.
>>> a = [0]
>>> a[0] = a
>>> a
[[...]]
>>> a[0] == a
True
My question is, what is happening here:
>>> a = [0]
>>> b = [0]
... | What's exactly happening in infinite nested lists? | It's possible to create an infinite nested list in Python. That's clear and, although not popular and definitely not useful is a known fact.
>>> a = [0]
>>> a[0] = a
>>> a
[[...]]
>>> a[0] == a
True
My question is, what is happening here:
>>> a = [0]
>>> b = [0]
>>> a[0], b[0] = b, a
>>> a
[[[...]]]
>>> b
[[[...]]]
>>... | [
"Disclaimer: I don't use Python, so some things I say may be wrong. Python experts, feel free to correct me.\nGreat question. I think the central misconception (if I can't even call it that; it's perfectly reasonable how you arrived at the thought process you used) you're having that prompts you to ask the question... | [
32,
12,
10,
7,
4
] | [] | [] | [
"infinite",
"list",
"python"
] | stackoverflow_0007674685_infinite_list_python.txt |
Q:
Http through telnet with python and twisted
This is what I want to do:
web-browser --> connect to remote server through telnet(server1) --> to squid-proxy(which requires authentication) through telnet on port 80(server2)
I have written a small python script that uses Twisted (here :
#! /usr/bin/python
from twisted... | Http through telnet with python and twisted | This is what I want to do:
web-browser --> connect to remote server through telnet(server1) --> to squid-proxy(which requires authentication) through telnet on port 80(server2)
I have written a small python script that uses Twisted (here :
#! /usr/bin/python
from twisted.internet import reactor, protocol
from twisted.w... | [
"I think you want to look at twisted.web.server.Site and twisted.web.resource.Resource. Also, since you are using Twisted, you'll probably want to use twisted.protocols.telnet.Telnet for the telnet connection, otherwise your application will not be asynchronous. \nThis blog post and this answer here may also be use... | [
1
] | [] | [] | [
"proxy",
"python",
"telnet",
"twisted"
] | stackoverflow_0007354864_proxy_python_telnet_twisted.txt |
Q:
Python script runs only with the "python" command
On Linux (Ubuntu 11.04), for some reason, a Python script (specifically the Django's manage.py, but I don't think that matters) recently started acting strangely:
When run as
python manage.py
it runs just fine; however, with
./manage.py
it shows the following err... | Python script runs only with the "python" command | On Linux (Ubuntu 11.04), for some reason, a Python script (specifically the Django's manage.py, but I don't think that matters) recently started acting strangely:
When run as
python manage.py
it runs just fine; however, with
./manage.py
it shows the following error:
: No such file or directory
The file's permissions... | [
"Your file has carriage returns in it. Did you write it in a Windows text editor?\nTry running dos2unix manage.py manage.py\n",
"glenn jackman's answer is correct, but I don't have enough \"reputation\" to upvote him, so I'll post this here. Your script is in Windows format, in which every line ends with a carri... | [
6,
3,
2,
1,
0
] | [] | [] | [
"linux",
"python",
"shell"
] | stackoverflow_0007679366_linux_python_shell.txt |
Q:
Changing default python to another version
Currently when I use "python" command, it points to python2.6. I have installed python3.1 and I want the "python" command point to python3.1. How it is possible?
mahmood@mpc:~$ which python
/usr/bin/python
mahmood@mpc:~$ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 9 201... | Changing default python to another version | Currently when I use "python" command, it points to python2.6. I have installed python3.1 and I want the "python" command point to python3.1. How it is possible?
mahmood@mpc:~$ which python
/usr/bin/python
mahmood@mpc:~$ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 9 2010-11-24 16:14 /usr/bin/python -> python2.6
mahmo... | [
"Since you have Linux, and if you want to simply type \"python\" instead of \"python3\" in order to run Python programs, a solution is simply to define an alias in you shell configuration file (.bashrc, etc.). For Bourne shells, it should be something like\nalias python=python3\n\n(or whatever your Python 3 name i... | [
15,
10,
4,
4,
3,
2
] | [] | [] | [
"default",
"path",
"python"
] | stackoverflow_0007679674_default_path_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.