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 - TypeError: (function) takes exactly 2 arguments (3 given) - but I only gave 2!
I'm parsing a list of patient visits (csv file). To deal with this, I have a custom set of classes:
class Patient:
def __init__(self,Rx,ID):
....
class PtController:
def __init__(self,openCSVFile):
self.dic... | Python - TypeError: (function) takes exactly 2 arguments (3 given) - but I only gave 2! | I'm parsing a list of patient visits (csv file). To deal with this, I have a custom set of classes:
class Patient:
def __init__(self,Rx,ID):
....
class PtController:
def __init__(self,openCSVFile):
self.dict=DictReader(openCSVFile)
self.currentPt = ''
....
def initNewPt(self,ro... | [
"You do not need to pass self directly as in self.initNewPt(self,firstRow), since it is automatically passed implicitly by Python.\n",
"When you call self.initNewPt() you should not pass self as a parameter. This is an implied parameter that's automatically present.\n",
"You need to call the initNewPt without ... | [
11,
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0006751656_python.txt |
Q:
Python Syntax Errors after print
Everything was working fine in this program I've been writing, and then out of nowhere I started getting all sorts of weird errors. For example:
print Bounds[atomCounter][i][2]
elif Bounds[atomCounter][i][2] == 'S':
Gives the error:
elif Bounds[atomCounter][i][2] == 'S':
... | Python Syntax Errors after print | Everything was working fine in this program I've been writing, and then out of nowhere I started getting all sorts of weird errors. For example:
print Bounds[atomCounter][i][2]
elif Bounds[atomCounter][i][2] == 'S':
Gives the error:
elif Bounds[atomCounter][i][2] == 'S':
^
SyntaxError: invalid syntax
It di... | [
"I don't know why you're using elif, but you can only do that after an if or another elif block. So of course that wouldn't work.\nSince it looks like you might have an if block before what you've written, try indenting the print line and see if that works.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006751751_python.txt |
Q:
Custom HTTP Methods for Ajax in Google App Engine (Python)
So I was reading the documentation for the RequestHandler class in python, and I noticed that it supports several more methods other than the two that I'm used to, namely GET and POST.
Is it possible to add custom methods to the RequestHandler class or my ... | Custom HTTP Methods for Ajax in Google App Engine (Python) | So I was reading the documentation for the RequestHandler class in python, and I noticed that it supports several more methods other than the two that I'm used to, namely GET and POST.
Is it possible to add custom methods to the RequestHandler class or my class that implements RequestHandler to extend those methods eve... | [
"You might want to take a look at ProtoRPC ... it's not exactly what you're asking, but achieves the same kind of end-result.\n"
] | [
0
] | [] | [] | [
"django",
"google_app_engine",
"jquery",
"python",
"web_applications"
] | stackoverflow_0006751607_django_google_app_engine_jquery_python_web_applications.txt |
Q:
How to be able to avoid a browser refreshing a page, after a HTTP POST request has been sent in Python/CGI
I am writing a CGI script in python 2.5 and I have run into an issue I cant solve.
My cgi script allows a user to into data into a html form and press refresh and the data gets successfully added. But it has... | How to be able to avoid a browser refreshing a page, after a HTTP POST request has been sent in Python/CGI | I am writing a CGI script in python 2.5 and I have run into an issue I cant solve.
My cgi script allows a user to into data into a html form and press refresh and the data gets successfully added. But it has turned out that if a user presses the refresh button on their browser the data that they inputted before gets a... | [
"I assume you actually have two scenarios:\n\nThe user entered the data correctly; reloading the page would cause the added data to be added again (which is wrong); the user may be redirected to the start page.\nThe user did not enter the data correctly (there are error messages); reloading would cause the same mes... | [
1,
0,
0
] | [] | [] | [
"cgi",
"html",
"python",
"redirect"
] | stackoverflow_0006697273_cgi_html_python_redirect.txt |
Q:
Changing axis values on a plot
How can I change the data on one axis?
I'm making some spectrum analysis on some data and my x-axis is the index of some matrix. I'd like to change it so that the x-axis becomes the data itself.
I'm using the imshow() to plot the data (I have a matrix whose elements are some intensit... | Changing axis values on a plot | How can I change the data on one axis?
I'm making some spectrum analysis on some data and my x-axis is the index of some matrix. I'd like to change it so that the x-axis becomes the data itself.
I'm using the imshow() to plot the data (I have a matrix whose elements are some intensity, the y axes are their detector-sou... | [
"Yes, you can use the xticks method exemplified in this example.\nThere are also more sophisticated ways of doing it. See ticker.\n"
] | [
2
] | [] | [] | [
"data_analysis",
"matplotlib",
"python"
] | stackoverflow_0006751955_data_analysis_matplotlib_python.txt |
Q:
Query Django models
I am trying to create a query using django models. I have 4 models. The functionality is to display all a person's facebook friends that are not already friends and do not have a friend request waiting.
CustomUserFriends
id,
from_customuser_id,
to_customuser_id,
FacebookProfile
id,
facebook_... | Query Django models | I am trying to create a query using django models. I have 4 models. The functionality is to display all a person's facebook friends that are not already friends and do not have a friend request waiting.
CustomUserFriends
id,
from_customuser_id,
to_customuser_id,
FacebookProfile
id,
facebook_id,
custom_user_id
Custom... | [
"So, I wasn't entirely sure what you were trying to accomplish here. It was a toss up between getting all non-friends for a particular user or having a particular user and trying to find all of his friends who weren't friends with each other. I decided I'd do both and let you decide which one you wanted.\nFirst, th... | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006750343_django_django_models_python.txt |
Q:
ctypes cast c_uint64 to c_char_p
from ctypes import * and
In [27]: sizeof(c_char_p)
Out[27]: 8
In [28]: sizeof(c_uint64)
Out[28]: 8
In [29]: cast(c_uint64(0), c_char_p)
---------------------------------------------------------------------------
ArgumentError Traceback (most recent cal... | ctypes cast c_uint64 to c_char_p | from ctypes import * and
In [27]: sizeof(c_char_p)
Out[27]: 8
In [28]: sizeof(c_uint64)
Out[28]: 8
In [29]: cast(c_uint64(0), c_char_p)
---------------------------------------------------------------------------
ArgumentError Traceback (most recent call last)
/Users/az/Programmierung/PyCP... | [
"Is the c_uint64 a memory address? If so, then you can do this:\n>>> n = c_uint64(1234567890) #assume this is a valid memory address...beware of segfaults\n>>> p = c_char_p(n.value)\n>>> #or..\n>>> p.value = n.value #special semantics for c_char_p - accepts both addresses and strings\n\n(see http://docs.python.org... | [
3,
1,
1
] | [] | [] | [
"casting",
"ctypes",
"python",
"sizeof"
] | stackoverflow_0006685801_casting_ctypes_python_sizeof.txt |
Q:
Gunzipping Contents of a URL - Python
I'm back. :) Again trying to get the gzipped contents of a URL and gunzip them. This time in Python. The #SERVER section of code is the script I'm using to generate the gzipped data. The data is known good, as it works with Java. The #CLIENT section of code is the bit of code ... | Gunzipping Contents of a URL - Python | I'm back. :) Again trying to get the gzipped contents of a URL and gunzip them. This time in Python. The #SERVER section of code is the script I'm using to generate the gzipped data. The data is known good, as it works with Java. The #CLIENT section of code is the bit of code I'm using client-side to try and read that ... | [
"This StackOverflow question seemed to help me out.\nApparently, it was just wise to by-pass the gzip module entirely, opting for zlib instead. Also, changing \"*\" to \"gzip\" in the \"Accept-Encoding\" header may've helped.\n#CLIENT\nurlReq = urllib2.Request(url)\nurlReq.add_header('Accept-Encoding', 'gzip')\nurl... | [
0
] | [] | [] | [
"content_encoding",
"gzip",
"http",
"ioerror",
"python"
] | stackoverflow_0006752243_content_encoding_gzip_http_ioerror_python.txt |
Q:
why does this blit from a numpy array to a pygame surface leak memory?
def blit_convert(dst_sfc, board):
dst_ary = pg.surfarray.pixels2d(dst_sfc)
src_ary = np.asarray(board, dtype=np.uint8)
dst_ary[...] = src_ary
del src_ary
del dst_ary
is called with:
dst_sfc = pg.Surface((width, height), 0, ... | why does this blit from a numpy array to a pygame surface leak memory? | def blit_convert(dst_sfc, board):
dst_ary = pg.surfarray.pixels2d(dst_sfc)
src_ary = np.asarray(board, dtype=np.uint8)
dst_ary[...] = src_ary
del src_ary
del dst_ary
is called with:
dst_sfc = pg.Surface((width, height), 0, 8)
board = np.zeros((width, height), dtype=np.uint16)
python 2.5.2, pygame ... | [
"pygame 1.7.1 usesNumeric and doing dst_ary[...] = src_ary where dst_ary is a Numeric.array and src_ary is a numpy.ndarray leaks memory for some unknown reason.\nUpgrading pygame to 1.9.1 which can use numpy for surface access fixes this.\n"
] | [
2
] | [] | [] | [
"numpy",
"pygame",
"python"
] | stackoverflow_0006746673_numpy_pygame_python.txt |
Q:
How to display an image with Pylab from a script in a non blocking way
I am writing some iterative image processing algorithm in a script (I don't want to be using iPython), and I would like to visualize the image I generate after each iteration. That's very easy to do in Matlab, without blocking the main thread, ... | How to display an image with Pylab from a script in a non blocking way | I am writing some iterative image processing algorithm in a script (I don't want to be using iPython), and I would like to visualize the image I generate after each iteration. That's very easy to do in Matlab, without blocking the main thread, but I am struggling to do it in Python.
In pylab the show() function is bloc... | [
"Try using pylab.draw() instead of pylab.show().\npylab.show() will start a Tk mainloop, hence it is blocking. Whereas pylab.draw() will force a draw of figure at that point. Since you are using pylab.ion(), figures are created already. But at the end of the script you have to put a pylab.show() otherwise figures w... | [
3,
2
] | [] | [] | [
"image",
"matplotlib",
"python"
] | stackoverflow_0005896737_image_matplotlib_python.txt |
Q:
Using Win32api to print to printer
I'm trying to get a python script of mine to print a CSV file to the printer via Win32api.ShellExectute, I.E.
win32api.ShellExecute(0,"print","C:\Test.csv",None,".",0)
Here's my problem: when I associate the file with Open Office, it just completely refuses to print. Prints fine... | Using Win32api to print to printer | I'm trying to get a python script of mine to print a CSV file to the printer via Win32api.ShellExectute, I.E.
win32api.ShellExecute(0,"print","C:\Test.csv",None,".",0)
Here's my problem: when I associate the file with Open Office, it just completely refuses to print. Prints fine in notepad. Prints fine in Microsoft Ex... | [
"You're relying on the shell defining a \"print\" verb for a particular file type. This works as follows:\n\nThe shell strips off the file extension, in this case \".csv\".\nThe shell looks up the extension in the registry under HKEY_CLASSES_ROOT to find the associated file type. On my system for example this is \"... | [
1
] | [] | [] | [
"csv",
"openoffice.org",
"python",
"winapi"
] | stackoverflow_0006752833_csv_openoffice.org_python_winapi.txt |
Q:
graphing milliseconds in python matplotlib.dates
I have time tagged data formatted using datetime.datetime.strptime that includes milliseconds. The data can span from a few minutes to a few hours. When I plot using pyplot and zoom in, it seems the minimum tick mark is 1 second. It appears that matplotlib's Tick... | graphing milliseconds in python matplotlib.dates | I have time tagged data formatted using datetime.datetime.strptime that includes milliseconds. The data can span from a few minutes to a few hours. When I plot using pyplot and zoom in, it seems the minimum tick mark is 1 second. It appears that matplotlib's TickHelper RRuleLocator only has a SecondLocator. Is ther... | [
"Matplotlib uses Matlab like numbers (seconds since 1970) for dates. If you have milliseconds, you must convert the dates to 'number':\nimport matplotlib.dates as mdates\nntimes = mdates.num2epoch(times / 1000.0)\n\nand plot ntimes instead of times.\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005587079_matplotlib_python.txt |
Q:
write xml with beautiful soup
this may be a truly stupid question but I haven't readily found the answer.
once i modify the xml tree as necessary, how do I write it back out to file?
code:
workbook = open("C:\\Users\\rabdel.WINCMPT\\Documents\\Retail Footwear.twb")
soup = BeautifulSoup(workbook)
for dashboard in ... | write xml with beautiful soup | this may be a truly stupid question but I haven't readily found the answer.
once i modify the xml tree as necessary, how do I write it back out to file?
code:
workbook = open("C:\\Users\\rabdel.WINCMPT\\Documents\\Retail Footwear.twb")
soup = BeautifulSoup(workbook)
for dashboard in soup.findAll("dashboard"):
prin... | [
"Simplest way, get the output as a string and write to file:\nf = open(workbook.name, \"w\")\nf.write(soup.prettify())\nf.close()\n\n",
"From the docs: you can turn a Beautiful Soup document (or any subset of it) into a string with the str function, or the prettify or renderContents methods. You can also use the ... | [
18,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0006753276_beautifulsoup_python.txt |
Q:
Twisted Authentication with Perspective Broker
Has been studying Tvisted week, read the book and most of the docks, but I can not understand a single moment. From Twisted docs
http://twistedmatrix.com/documents/10.1.0/core/howto/pb-cred.html
server
#!/usr/bin/env python
# Copyright (c) 2009 Twisted Matrix Laborat... | Twisted Authentication with Perspective Broker | Has been studying Tvisted week, read the book and most of the docks, but I can not understand a single moment. From Twisted docs
http://twistedmatrix.com/documents/10.1.0/core/howto/pb-cred.html
server
#!/usr/bin/env python
# Copyright (c) 2009 Twisted Matrix Laboratories.
# See LICENSE for details.
from zope.interfa... | [
"If you want to implement retry, do it entirely in the client. You should not change the server to report messages like \"Bad password\" or \"No such user\", as these leak information to an attacker.\nTo have the client retry, add an errback to the login Deferred that prompts for a new password (and maybe a new us... | [
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0006751801_python_twisted.txt |
Q:
how to create a bar chart with matplotlib using table data
The idea is quite simple: I want to create a bar chart with matplotlib using data of a table that is being generated before.
I expect a chart like this one:
http://matplotlib.sourceforge.net/examples/pylab_examples/table_demo.html
But Im wondering how to... | how to create a bar chart with matplotlib using table data | The idea is quite simple: I want to create a bar chart with matplotlib using data of a table that is being generated before.
I expect a chart like this one:
http://matplotlib.sourceforge.net/examples/pylab_examples/table_demo.html
But Im wondering how to do this just by using data out of a dbf table instead.
It seem... | [
"There is dbfpy which allows you reading from a DBF file. But I suggest using a CSV file and numpy.loadtxt if possible, because it should be much faster.\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006752095_matplotlib_python.txt |
Q:
Re-size one axis of a plot
This a quite easy questions I didn't manage to find some old topic about it.
I'm doing plots and I change the data lim, especifically the xlim, (I take out like 60-70% of the graph away with that).
But when I do this, it makes my graph look really small, and than I can't extract anythin... | Re-size one axis of a plot | This a quite easy questions I didn't manage to find some old topic about it.
I'm doing plots and I change the data lim, especifically the xlim, (I take out like 60-70% of the graph away with that).
But when I do this, it makes my graph look really small, and than I can't extract anything from it. How can I resize the ... | [
"By default, matplotlib does what you want for line plots, etc.\nSomewhere in your code, you're probably setting a fixed aspect ratio and setting the adjustable part of the axis boundary to \"box\" rather than \"datalim\". \nMore likely, something you're calling is doing this without you being aware of it. For exa... | [
4
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006752559_matplotlib_python.txt |
Q:
Slice string in python
I just want to slice string from the beginning.As like I have a sentences:
"All the best wishes"
I want to get
"the best wishes" , "best wishes", "wishes".
Any solution please,Thanks!
A:
>>> words
['All', 'the', 'best', 'wishes']
>>> [" ".join(words[i:]) for i in range(len(words))]
['Al... | Slice string in python | I just want to slice string from the beginning.As like I have a sentences:
"All the best wishes"
I want to get
"the best wishes" , "best wishes", "wishes".
Any solution please,Thanks!
| [
">>> words\n['All', 'the', 'best', 'wishes']\n>>> [\" \".join(words[i:]) for i in range(len(words))]\n['All the best wishes', 'the best wishes', 'best wishes', 'wishes']\n>>> [\" \".join(words[i:]) for i in range(len(words))][1:]\n['the best wishes', 'best wishes', 'wishes']\n\n",
"use:\nsearchWords.extend([' '.j... | [
5,
4,
1,
1,
1
] | [] | [] | [
"python",
"slice",
"string"
] | stackoverflow_0006748122_python_slice_string.txt |
Q:
Using python to process a chunk of a file every x lines
What I'm trying to do here is to read in z lines every line interval y from a file DATA.txt then execute the function find on that chuck of lines. I.e. I want to skip the first y lines; read in the next z lines; execute the function find on those lines just r... | Using python to process a chunk of a file every x lines | What I'm trying to do here is to read in z lines every line interval y from a file DATA.txt then execute the function find on that chuck of lines. I.e. I want to skip the first y lines; read in the next z lines; execute the function find on those lines just read in; skip the next y lines; and repeat for the length of t... | [
"edit: Try the following, I think I have a better idea of what you are trying to do now.\ng = open('tmp','a+')\nwhile x<int(sys.argv[1]):\n x+=1 \n if mod(x, y)==0:\n curr = g.tell()\n for i in range(x,x+z):\n block=linecache.getline('DATA.txt', i)\n g.write(block)\n li... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"text_extraction"
] | stackoverflow_0006751403_python_text_extraction.txt |
Q:
How to have separate folders for each app's static files in Django
When I run python manage.py collectstatic, it puts all static files from different apps together in one location (STATIC_ROOT). I would like to have a separate folder within STATIC_ROOT for each app. For example static files from app1/static should... | How to have separate folders for each app's static files in Django | When I run python manage.py collectstatic, it puts all static files from different apps together in one location (STATIC_ROOT). I would like to have a separate folder within STATIC_ROOT for each app. For example static files from app1/static should go to STATIC_ROOT/app1 and static files from app2/static should go to S... | [
"I usually put them all in one directory like the following just like how I work with templates:\nMyProject/staticfiles/app1\nMyProject/staticfiles/app2\nMyProject/staticfiles/app3\n\n"
] | [
2
] | [] | [] | [
"django",
"project_structure",
"python",
"static_files"
] | stackoverflow_0006745118_django_project_structure_python_static_files.txt |
Q:
Python "if modified since" detection?
I wrote some code to tackle a work-related problem. The idea is that the program is in an infinite loop and every 10 minutes it checks a certain folder for new files and if there are any, it copies them to another folder. My code reads all the files in the folder and drops the... | Python "if modified since" detection? | I wrote some code to tackle a work-related problem. The idea is that the program is in an infinite loop and every 10 minutes it checks a certain folder for new files and if there are any, it copies them to another folder. My code reads all the files in the folder and drops the list into a txt file. After 10 minutes it ... | [
"The cleanest solution is file alteration monitoring. See this question for information for both *ix and Windows. To summarize, on Linux, you could use libfam, and Windows has FindFirstChangeNotification and related functions.\nThere are some clear problems with your script, such as NOP lines like i==i. You also... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006752763_python.txt |
Q:
Issue getting VTK to work with Qt
I'm trying to embed a VTK5 visualization inside a Qt4 window, but am not having much luck. The following code doesn't work on my Mac (10.6, Python 2.7):
from PyQt4 import QtGui
from vtk.qt4 import QVTKRenderWindowInteractor
import sys
class Window(QVTKRenderWindowInteractor.QVTKR... | Issue getting VTK to work with Qt | I'm trying to embed a VTK5 visualization inside a Qt4 window, but am not having much luck. The following code doesn't work on my Mac (10.6, Python 2.7):
from PyQt4 import QtGui
from vtk.qt4 import QVTKRenderWindowInteractor
import sys
class Window(QVTKRenderWindowInteractor.QVTKRenderWindowInteractor):
def __init_... | [
"I figured it out eventually so am putting the solution here in case it's useful to other people. I had installed VTK5 with:\nsudo port install vtk5 +python27\n\nbut I needed to include the qt4_mac variant. The following worked:\nsudo port install vtk5 +python27 +qt4_mac\n\n"
] | [
2
] | [] | [] | [
"python",
"qt4",
"vtk"
] | stackoverflow_0006700615_python_qt4_vtk.txt |
Q:
How do I removes \n founds between double quotes from a string?
Good day,
I am totally new to Python and I am trying to do something with string.
I would like to remove any \n characters found between double quotes ( " ) only, from a given string :
str = "foo,bar,\n\"hihi\",\"hi\nhi\""
The desired output must be:
... | How do I removes \n founds between double quotes from a string? | Good day,
I am totally new to Python and I am trying to do something with string.
I would like to remove any \n characters found between double quotes ( " ) only, from a given string :
str = "foo,bar,\n\"hihi\",\"hi\nhi\""
The desired output must be:
foo,bar
"hihi", "hihi"
Edit:
The desired output must be similar to t... | [
"This should do:\ndef removenewlines(s):\n inquotes = False\n result = []\n\n for chunk in s.split(\"\\\"\"):\n if inquotes: chunk.replace(\"\\n\", \"\")\n result.append(chunk)\n inquotes = not inquotes\n\n return \"\\\"\".join(result)\n\n",
"A simple stateful filter will do the t... | [
3,
3,
2,
2,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006753849_python_string.txt |
Q:
Talking between Flash and a TCP Server (Python)
What is the best recommended way to talk between a Flash client and gevent? Should I use XMLSocket or is there something better... also, should I create my own syntax "such as MOVE 1, 500, 3000" or should I use something similar to JSON? This is for production, thank... | Talking between Flash and a TCP Server (Python) | What is the best recommended way to talk between a Flash client and gevent? Should I use XMLSocket or is there something better... also, should I create my own syntax "such as MOVE 1, 500, 3000" or should I use something similar to JSON? This is for production, thanks guys.
| [
"Flash has a serialisation format called AMF (ActionScript Message Format). I’ve found it to be faster than XML or JSON, and it’s also terser (i.e.: produces smaller payloads than XML or JSON). I’ve only used it for a couple of projects, but check out amfast and PyAMF for the server-side. Both projects come with co... | [
0
] | [] | [] | [
"flash",
"gevent",
"python"
] | stackoverflow_0006748157_flash_gevent_python.txt |
Q:
Most efficient method to get key for a value in a dict
I have a dictionary of objects:
dic = {'k1':obj1, 'k2':obj2, 'k3':obj3, ...}
class MyObject:
def __init__(self,x,y):
self.x=x
self.y=y
I wonder how I can have the best implementation for finding the key that corresponds to a value. Someth... | Most efficient method to get key for a value in a dict | I have a dictionary of objects:
dic = {'k1':obj1, 'k2':obj2, 'k3':obj3, ...}
class MyObject:
def __init__(self,x,y):
self.x=x
self.y=y
I wonder how I can have the best implementation for finding the key that corresponds to a value. Something equivalent to:
def find_key(dic, val):
for k,v in di... | [
"Ignoring the possibility that samb8s raises, that multiple keys exist for a single value, you can easily reverse the dictionary like this:\nreverse_dic = dict((v, k) for k, v in dic.items())\n\n",
"You can use list comprehension. This code gives you the keys in a list:\n>>> a\n{1: 2, 3: 4, 9: 4, 5: 6, 7: 8}\n>>>... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006748226_python.txt |
Q:
Search start of the word using regular expression
How to write regular expression where we can find all words which are started by specified string. For ex-
a = "asasasa sasDRasas dr.klklkl DR.klklklkl Dr klklklkklkl"
Here I want to fetch all words which are starting by dr using ignorecase. I tried but all funct... | Search start of the word using regular expression | How to write regular expression where we can find all words which are started by specified string. For ex-
a = "asasasa sasDRasas dr.klklkl DR.klklklkl Dr klklklkklkl"
Here I want to fetch all words which are starting by dr using ignorecase. I tried but all functions results where dr is found in word not start of the... | [
"You can use \\b to find word boundaries, and the re.IGNORECASE flag to search case-insensitively.\nimport re\n\na = \"asasasa sasDRasas dr.klklkl DR.klklklkl Dr klklklkklkl\"\nfor match in re.finditer(r'\\bdr', a, re.IGNORECASE):\n print 'Found match: \"{0}\" at position {1}'.format(match.group(0), match.start(... | [
8,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006746157_python_regex.txt |
Q:
The methods I'm using are unbound?
I'm working on a calendar via Python's HTMLCalendar and Django. The functions I'm using to input data into the calendar are showing up as unbound, and therefore not working.
Here's the calendar code:
from www.wednesday.models import Event
import calendar
e = Event()
class EventCa... | The methods I'm using are unbound? | I'm working on a calendar via Python's HTMLCalendar and Django. The functions I'm using to input data into the calendar are showing up as unbound, and therefore not working.
Here's the calendar code:
from www.wednesday.models import Event
import calendar
e = Event()
class EventCal(calendar.HTMLCalendar):
def forma... | [
"dd() is a method of an instance of the class.\nYou call it like this:\ne = Event()\nx = e.dd()\n\nYou can't apply dd to Event itself.\nI am not sure what exactly you are trying to do, so I am not sure how you need to modify your code.\n",
"In formatday you have:\nif day == 0:\n\nbut also:\nif day == Event.dd():\... | [
5,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006754192_django_python.txt |
Q:
Dictionary-like efficient storing of scipy/numpy arrays
BACKGROUND
The issue I'm working with is as follows:
Within the context of an experiment I am designing for my research, I produce a large number of large (length 4M) arrays which are somewhat sparse, and thereby could be stored as scipy.sparse.lil_matrix in... | Dictionary-like efficient storing of scipy/numpy arrays | BACKGROUND
The issue I'm working with is as follows:
Within the context of an experiment I am designing for my research, I produce a large number of large (length 4M) arrays which are somewhat sparse, and thereby could be stored as scipy.sparse.lil_matrix instances, or simply as scipy.array instances (the space gain/l... | [
"as JoshAdel already suggested, I would go for HDF5, the simplest way is to use h5py:\nhttp://h5py.alfven.org/\nyou can attach several attributes to an array with a dictionary like sintax:\ndset.attrs[\"Name\"] = \"My Dataset\"\n\nwhere dset is your dataset which can be sliced exactly as a numpy array, but in the b... | [
5,
2,
2,
2
] | [] | [] | [
"numpy",
"python",
"scipy",
"serialization"
] | stackoverflow_0005330010_numpy_python_scipy_serialization.txt |
Q:
Python example to access a php site(HTTPS) protected by PKI
I am looking for a example code for how to implement a Python application to communicate with a php site over HTTPS and use PKI protection.
I probably will use pyOpenSSL and httplib.HTTPSConnection. My question is where can I find a site that uses PKI for... | Python example to access a php site(HTTPS) protected by PKI | I am looking for a example code for how to implement a Python application to communicate with a php site over HTTPS and use PKI protection.
I probably will use pyOpenSSL and httplib.HTTPSConnection. My question is where can I find a site that uses PKI for authentication? (would Github do this?). Also, is there any samp... | [
"I believe all you need to do is use httplib.HTTPSConnection like you said. I tried the following and it worked for me.\nExample:\n\n\n import httplib\n HOSTNAME = 'login.yahoo.com'\n conn = httplib.HTTPSConnection(HOSTNAME)\n conn.putrequest('GET', '/')\n conn.endheaders()\n response = conn.getre... | [
2,
1
] | [] | [] | [
"https",
"openssl",
"pki",
"python"
] | stackoverflow_0006743276_https_openssl_pki_python.txt |
Q:
using strings as python dictionaries (memory management)
I need to find identical sequences of characters in a collection of texts. Think of it as finding identical/plagiarized sentences.
The naive way is something like this:
ht = defaultdict(int)
for s in sentences:
ht[s]+=1
I usually use python but I'm beg... | using strings as python dictionaries (memory management) | I need to find identical sequences of characters in a collection of texts. Think of it as finding identical/plagiarized sentences.
The naive way is something like this:
ht = defaultdict(int)
for s in sentences:
ht[s]+=1
I usually use python but I'm beginning to think that python is not the best choice for this ta... | [
"\nYes, dict store the key in memory. If you data fit in memory this is the easiest approach.\nHash should work. Try MD5. It is 16 byte int so collision is unlikely. \nTry BerkeleyDB for a disk based approach.\n\n",
"Python dicts are indeed monsters in memory. You hardly can operate in millions of keys when stori... | [
2,
1,
0,
0
] | [] | [] | [
"dictionary",
"hash",
"memory",
"python"
] | stackoverflow_0006753812_dictionary_hash_memory_python.txt |
Q:
Implementing a Multiple (Checkbox) Select + "Other" widget in Django
I need to populate a CharField with the result of a set of checkboxes plus an "other" [please specify] option (the value would be 'option-a,other' for the form state below). The form can basically look like:
[x] option a
[ ] option b
[x] other
I... | Implementing a Multiple (Checkbox) Select + "Other" widget in Django | I need to populate a CharField with the result of a set of checkboxes plus an "other" [please specify] option (the value would be 'option-a,other' for the form state below). The form can basically look like:
[x] option a
[ ] option b
[x] other
If you selected "other", please specify. [__________]
I've managed to get ... | [
"As the error only occurs once you save a model instance out of the form, check if the “Value u'education,other' is not a valid choice” error is coming from model validation instead of form validation. That can happen if you also have a choices set on the model field when you really want to store a free-form string... | [
1,
0
] | [] | [] | [
"django",
"forms",
"modelform",
"python",
"validation"
] | stackoverflow_0006743022_django_forms_modelform_python_validation.txt |
Q:
Pyramid equivalent to Django's syncdb command?
I noticed in the Pyramid + SQLAlchemy + URL Dispatch Wiki Tutorial that the database is initialized in the main function when the application is run.
def main(global_config, **settings):
""" This function returns a WSGI application.
"""
engine = engine_fro... | Pyramid equivalent to Django's syncdb command? | I noticed in the Pyramid + SQLAlchemy + URL Dispatch Wiki Tutorial that the database is initialized in the main function when the application is run.
def main(global_config, **settings):
""" This function returns a WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
initialize_sql... | [
"Since Pyramid does not make any assumptions about data models, it does not attempt to manage them for you. This is entirely up to you and what specific data layer you are using.\nWith respect to using SQLAlchemy, it is possible to manage migrations using the SQLAlchemy-migrate package. When you set this up, it pro... | [
10
] | [] | [] | [
"django",
"pyramid",
"python",
"sqlalchemy",
"web_frameworks"
] | stackoverflow_0006754465_django_pyramid_python_sqlalchemy_web_frameworks.txt |
Q:
Scipy sparse... arrays?
So, I'm doing some Kmeans classification using numpy arrays that are quite sparse-- lots and lots of zeroes. I figured that I'd use scipy's 'sparse' package to reduce the storage overhead, but I'm a little confused about how to create arrays, not matrices.
I've gone through this tutorial o... | Scipy sparse... arrays? | So, I'm doing some Kmeans classification using numpy arrays that are quite sparse-- lots and lots of zeroes. I figured that I'd use scipy's 'sparse' package to reduce the storage overhead, but I'm a little confused about how to create arrays, not matrices.
I've gone through this tutorial on how to create sparse matric... | [
"Use a scipy.sparse format that is row or column based: csc_matrix and csr_matrix. \nThese use efficient, C implementations under the hood (including multiplication), and transposition is a no-op (esp. if you call transpose(copy=False)), just like with numpy arrays.\nEDIT: some timings via ipython:\nimport numpy, s... | [
35,
1,
1
] | [] | [] | [
"matrix",
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0002540059_matrix_numpy_python_scipy_sparse_matrix.txt |
Q:
Efficient item binning algorithm (itertools/numpy)
I think this is a common combinatorics problem, but I can't seem to find a name for it or any material about it. I am doing this in Python and numpy, but if there is a fast matrix method for this, I can probably translate.
Basically, given n items, I need to gener... | Efficient item binning algorithm (itertools/numpy) | I think this is a common combinatorics problem, but I can't seem to find a name for it or any material about it. I am doing this in Python and numpy, but if there is a fast matrix method for this, I can probably translate.
Basically, given n items, I need to generate all ways to put them in m bins. As an example, binni... | [
"Based on the recursion C(n, k) = C(n - 1, k) + C(n - 1, k - 1), memoized, using numpy operations.\nimport numpy as np\n\ndef binnings(n, k, cache={}):\n if n == 0:\n return np.zeros((1, k))\n if k == 0:\n return np.empty((0, 0))\n args = (n, k)\n if args in cache:\n return cache[ar... | [
7,
3
] | [] | [] | [
"algorithm",
"cartesian_product",
"combinatorics",
"numpy",
"python"
] | stackoverflow_0006750298_algorithm_cartesian_product_combinatorics_numpy_python.txt |
Q:
Sample python code for android: Login dialog with username and pasword
sl4a does come with a sample getPassword, but I want to see if I can get a simply popup login box that has both Login username and Password. I have been trying to search a lot for this but cannot find how to do this in python. Any help would be... | Sample python code for android: Login dialog with username and pasword | sl4a does come with a sample getPassword, but I want to see if I can get a simply popup login box that has both Login username and Password. I have been trying to search a lot for this but cannot find how to do this in python. Any help would be appreciated.
| [
"Have a look at the UiFacade on the ApiReference. There are for example dialogCreateInput and \ndialogCreatePassword.\n"
] | [
0
] | [] | [] | [
"android",
"python",
"sl4a"
] | stackoverflow_0006529740_android_python_sl4a.txt |
Q:
paramiko-python exec_command() cannot work on channel type tuple :(
Test Function
def GetTestFile():
sshConn = paramiko.SSHClient()
sshConn.load_system_host_keys()
sshConn.connect(host, port, usrnm, pwrd)
(connin, out, err) = sshObj.exec_command("cat test.txt")
print out.readlines()
lines =... | paramiko-python exec_command() cannot work on channel type tuple :( | Test Function
def GetTestFile():
sshConn = paramiko.SSHClient()
sshConn.load_system_host_keys()
sshConn.connect(host, port, usrnm, pwrd)
(connin, out, err) = sshObj.exec_command("cat test.txt")
print out.readlines()
lines = []
for i in out.readlines():
lines = lines.append(i)
... | [
"the list.append method does not return the list, it is an in-place append. You want\nfor i in out.readlines():\n lines.append(i)\n print lines\n\n"
] | [
1
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0006754828_paramiko_python.txt |
Q:
Django - change select items display
I use ModelForm. One of the fields is:
repertoire = models.ForeignKey(Repertoire)
I need to change its display type. Instead of using __str__ (or __unicode__ in Python 2) in display I want to show name and date of repertoire.
How can I do this with ModelForm?
A:
Subclass Mod... | Django - change select items display | I use ModelForm. One of the fields is:
repertoire = models.ForeignKey(Repertoire)
I need to change its display type. Instead of using __str__ (or __unicode__ in Python 2) in display I want to show name and date of repertoire.
How can I do this with ModelForm?
| [
"Subclass ModelChoiceField and override label_from_instance to return the repertoire name and date. Then use the new field in your ModelForm.\nfrom django import forms\n\nclass RepertoireModelChoiceField(forms.ModelChoiceField):\n def label_from_instance(self, obj):\n return \"%s - %s\" % (obj.name, obj.d... | [
5
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006754776_django_django_forms_python.txt |
Q:
How to declare Raw Binary/Hex data in ObjC and how to pass it in an argument?
This is what I have in Python:
ourAddr = Binary('\x4c\x6f\x8c')
I need to declare it in ObjC then pass it to a python script running on another server.
This is how I've been trying:
char *addr = "\x4c\x6f\x8c";
NSArray *hex = [NSArray ... | How to declare Raw Binary/Hex data in ObjC and how to pass it in an argument? | This is what I have in Python:
ourAddr = Binary('\x4c\x6f\x8c')
I need to declare it in ObjC then pass it to a python script running on another server.
This is how I've been trying:
char *addr = "\x4c\x6f\x8c";
NSArray *hex = [NSArray arrayWithObjects: [NSNumber numberWithChar: addr], nil];
[waitOnEvent setMethod:@"w... | [
"Are you trying to send your data as ASCII/UTF-8 encoded hex strings or raw binary data?\nIf it's the latter, you can do the following (I have used your code accordingly):\nconst char addr[] = {0x4c, 0x6f, 0x8c};\nNSData *data = [NSData dataWithBytes:addr length:sizeof(addr)];\nNSArray *array = [NSArray arrayWithOb... | [
2,
0
] | [] | [] | [
"ios",
"objective_c",
"python"
] | stackoverflow_0006752139_ios_objective_c_python.txt |
Q:
How to detect ftp server timeouts in Python
Uploading large amounts of files to an FTP server. In the middle of my upload the server times out preventing me from uploading any further. Does anyone know of a way to detect if the server has timed out, reconnect and continue transmission of the data? I am using the P... | How to detect ftp server timeouts in Python | Uploading large amounts of files to an FTP server. In the middle of my upload the server times out preventing me from uploading any further. Does anyone know of a way to detect if the server has timed out, reconnect and continue transmission of the data? I am using the Python ftp library for the transmission.
Thanks ... | [
"You can simply specify a timeout for the connect, but for timeouts during file transfer or other operations it's not so simple.\nBecause the storbinary and retrbinary methods allow you to provide a callback, you can implement a watchdog timer. Each time you get data you reset the timer. If you don't get data at ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006753269_python.txt |
Q:
Exceptions and Python
I'm very new to Python and I have a problem which I thought I had solved but it keeps occurring. I have something similar to the following.
def funct1()
dosomestuff
funct2()
def funct2()
dosomestuff
funct3()
def funct3()
dosomestuff
funct1()
def exceptionRecovery()
... | Exceptions and Python | I'm very new to Python and I have a problem which I thought I had solved but it keeps occurring. I have something similar to the following.
def funct1()
dosomestuff
funct2()
def funct2()
dosomestuff
funct3()
def funct3()
dosomestuff
funct1()
def exceptionRecovery()
checksomethings
fun... | [
"Do you get a stackoverflow exception per chance :) ? Since python does not have tail-call recursion optimization, you can not infinitely nest function calls. For this reason you should consider putting your logic into an infinite while loop.\nwhile True:\n //logic to call func1, 2, 3 or whatever\n\n",
"Your p... | [
9,
7,
3,
3,
3,
2,
1,
1,
0
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0006755017_exception_python.txt |
Q:
program for comparisons in python
I'm really new to programming (really, really new) and need help with the basics. I'm trying to write a program with python that will compare the contents of two .txt files, one a reference and the other the source. The contents are a simple random listing of names, and I want it ... | program for comparisons in python | I'm really new to programming (really, really new) and need help with the basics. I'm trying to write a program with python that will compare the contents of two .txt files, one a reference and the other the source. The contents are a simple random listing of names, and I want it to print out if there are any names in ... | [
"If you are totally, completely new to programming then it will take you some time to be able to implement what you describe. Take a step back, pour yourself a beverage, and start here. Start at the beginning, and repeat each illustration until you understand.\nhttp://docs.python.org/tutorial/\n",
"As previousl... | [
3,
1,
0,
0,
0
] | [] | [] | [
"compare",
"new_operator",
"python"
] | stackoverflow_0006755146_compare_new_operator_python.txt |
Q:
wtforms ReferencePropertyField set selected
Using the GAE-helper ReferencePropertyField to show possible groups that a user can be in.
How do I make it show the what group the user currently is in when editing the user?
The selectfield works fine, I can change the group of the user and the changes are written to t... | wtforms ReferencePropertyField set selected | Using the GAE-helper ReferencePropertyField to show possible groups that a user can be in.
How do I make it show the what group the user currently is in when editing the user?
The selectfield works fine, I can change the group of the user and the changes are written to the datastore, but I can't figure out how to set t... | [
"Is current_data a string? If not try using str(current_data) to convert, I had a similar issue using either entity keys or ids as values on a SelectField.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python",
"wtforms"
] | stackoverflow_0006753973_google_app_engine_python_wtforms.txt |
Q:
Can i install jython and normal django on same server
I have normal sites running with php and jango on my VPS.
Now i also want to try Jython. I want to know that can i install that on my same VPS server or i need to get new server for jython. WOn't the normal , python Django modules mix up with each other
A:
Wa... | Can i install jython and normal django on same server | I have normal sites running with php and jango on my VPS.
Now i also want to try Jython. I want to know that can i install that on my same VPS server or i need to get new server for jython. WOn't the normal , python Django modules mix up with each other
| [
"Was there something wrong with Jython Django?\ndjango project with jython &\ndjango jython project\nEdit apologies links updated use link 2.\n"
] | [
0
] | [] | [] | [
"java",
"jython",
"linux",
"python"
] | stackoverflow_0006745523_java_jython_linux_python.txt |
Q:
Python Error(Beginner)
I been learning python the last day or so using online tutorials I found, everything has been coming along well till I got an error that I can not seem to fix.
The site I been using today is http://wiki.wxpython.org/Getting%20Started
I have got all the way to sizers with little trouble. Whe... | Python Error(Beginner) | I been learning python the last day or so using online tutorials I found, everything has been coming along well till I got an error that I can not seem to fix.
The site I been using today is http://wiki.wxpython.org/Getting%20Started
I have got all the way to sizers with little trouble. When I try to run a program fro... | [
"Everything from wx.Frame.__init__(...) up to but not including the next def must be indented one additional level.\n",
"You have an indentation error: everything from the 8th line down should be indented to match the previous lines.\n"
] | [
3,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006755487_python_wxpython.txt |
Q:
Sentence segmentation using Regex
I have few text(SMS) messages and I want to segment them using period('.') as a delimiter. I am unable to handle following types of messages. How can I segment these messages using Regex in Python.
Before segmentation:
'hyper count 16.8mmol/l.plz review b4 5pm.just to inform u.th... | Sentence segmentation using Regex | I have few text(SMS) messages and I want to segment them using period('.') as a delimiter. I am unable to handle following types of messages. How can I segment these messages using Regex in Python.
Before segmentation:
'hyper count 16.8mmol/l.plz review b4 5pm.just to inform u.thank u'
'no of beds 8.please inform pers... | [
"Some weeks ago, I searched for a regex that would catch every string representing a number in a string, whatever the form in which the number is written, even the ones in scientific notation, even the indian numbers having commas: see this thread\nI use this regex in the following code to give a solution to your p... | [
5,
2,
1,
0
] | [
"\"...\".split(\".\")\n\nsplit is a Python builtin that separates a string at a specific character.\n"
] | [
-1
] | [
"python",
"regex",
"text_segmentation"
] | stackoverflow_0006745592_python_regex_text_segmentation.txt |
Q:
Handle undeclared dict key in Python
In my Ruby application I have a hash table:
c = {:sample => 1,:another => 2}
I can handle the table like this:
[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]
I'm trying to do the same thing in Python. I created a new dictionary:
c = {"sample":1, "another":2}
I co... | Handle undeclared dict key in Python | In my Ruby application I have a hash table:
c = {:sample => 1,:another => 2}
I can handle the table like this:
[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]
I'm trying to do the same thing in Python. I created a new dictionary:
c = {"sample":1, "another":2}
I couldn't handle the nil value exception for:... | [
"In your particular case, you should probably do this instead of comparing with None:\n\"not_in_dictionary\" in c\n\nIf you were literally using this code, it will not work:\nc[:not_in_dictionary] is not None\n\nPython doesn't have special :keywords for dictionary keys; ordinary strings are used instead.\n\nThe ord... | [
40
] | [] | [] | [
"exception",
"exception_handling",
"python"
] | stackoverflow_0006755655_exception_exception_handling_python.txt |
Q:
Mysterious errors importing numpy and scipy with "knee.py"
There's a file included with the Python source called knee.py. It overrides the regular import statement with it's own hook. The code is supposed to be correct, and for builtin modules and single file modules, it is. However, I get a bizarre error (both di... | Mysterious errors importing numpy and scipy with "knee.py" | There's a file included with the Python source called knee.py. It overrides the regular import statement with it's own hook. The code is supposed to be correct, and for builtin modules and single file modules, it is. However, I get a bizarre error (both different) when I try to import numpy with it.
(...long stack trac... | [
"SOLVED. (only guaranteeing solution for packaged modules numpy and scipy)\nI implemented my own solution. Be wary that while the code I post here works, it contains a bunch of silly debug statements and commented out code that can be removed, as well as doing a couple of other things that are related to what I wan... | [
1
] | [] | [] | [
"import",
"module",
"numpy",
"python",
"scipy"
] | stackoverflow_0006714411_import_module_numpy_python_scipy.txt |
Q:
Running Thread even after the main thread terminates using Django
I am working on a django project where the user hits a submits a bunch of images that needs to be processed in the backend.
The images are already uploaded on the server but once the user hits submit, it takes a lot of time to process the request an... | Running Thread even after the main thread terminates using Django | I am working on a django project where the user hits a submits a bunch of images that needs to be processed in the backend.
The images are already uploaded on the server but once the user hits submit, it takes a lot of time to process the request and about 15 seconds until a 'thank you for using us' message is displaye... | [
"PROCESSORS = [] # empty list of background processors\n\nInherit from Trheading.thread\nclass ImgProcessor(threading.Thread):\n def __init__(self, img, username, jobID):\n self.img = img\n self.username = username\n self.jobID = jobID\n threading.Thread.__init__(self)\n self.s... | [
0,
0
] | [] | [] | [
"django",
"multithreading",
"python"
] | stackoverflow_0006755585_django_multithreading_python.txt |
Q:
Django customize AdminModel view
In my Django application I have Guest user accounts that are created for all unregistered users (they all have email='guest@mysite.com'). At the same time I create some demo objects related to the Guest account.
These objects live in the same table (have the same model) as objects... | Django customize AdminModel view | In my Django application I have Guest user accounts that are created for all unregistered users (they all have email='guest@mysite.com'). At the same time I create some demo objects related to the Guest account.
These objects live in the same table (have the same model) as objects for registered users. And I have more... | [
"Guess you are doing a lot more work than necessary. You could also create your own ModelAdmin class and overwrite its queryset method, no need to construct your own ChangeList class:\nclass MyFilteredAdmin(admin.ModelAdmin):\n def queryset(self, request):\n qs = super(MyFilteredAdmin, self).queryset(requ... | [
5,
2,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0006752388_django_django_admin_python.txt |
Q:
In App Engine for Python, is it possible to persist a class with another object nested inside it?
In App Engine for Python, is there anything like Objectify (Java Library) where I can easily embed a class within another and save it to the datastore?
This class would be modeled like the following example where a Ve... | In App Engine for Python, is it possible to persist a class with another object nested inside it? | In App Engine for Python, is there anything like Objectify (Java Library) where I can easily embed a class within another and save it to the datastore?
This class would be modeled like the following example where a Venue contain a Location object. I want to persist this as one nested object, as well as be able to quer... | [
"Consider using Reference properties. I.e. store a Location object as its own entity and incorporate that location into the Venue object by reference.\nclass Location():\n city = db.StringProperty()\n state = db.StringProperty()\n\nclass Venue(db.Model):\n name = db.StringProperty()\n location = db.ReferencePro... | [
3,
2
] | [] | [] | [
"datastore",
"google_app_engine",
"nested",
"python"
] | stackoverflow_0006753545_datastore_google_app_engine_nested_python.txt |
Q:
Django select_related() and GenericForeignKey
I have models like these:
class Comment(models.Model):
text = models.TextField(max_length = 250, blank = False)
author = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object =... | Django select_related() and GenericForeignKey | I have models like these:
class Comment(models.Model):
text = models.TextField(max_length = 250, blank = False)
author = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_... | [] | [] | [
"You could try to refactor your database to look somewhat like this:\nclass Comment(models.Model):\n ...\n content_object = models.ForeignKey(Content)\n\nclass Content(models.Model):\n text = models.CharField(max_length=123)\n\nclass SomeSpecificContent(models.Model):\n ...\n content = models.Foreign... | [
-1
] | [
"django",
"python"
] | stackoverflow_0006755626_django_python.txt |
Q:
one liner for removing blank lines from a file in python?
I'm looking for one liner which will remove all the blank lines from a file in python.
python equivalent for --> grep -v '^$' file_name > file_name
A:
lines = [i for i in open(file_path) if i[:-1]]
If writing to another file is a requirement, you can use... | one liner for removing blank lines from a file in python? | I'm looking for one liner which will remove all the blank lines from a file in python.
python equivalent for --> grep -v '^$' file_name > file_name
| [
"lines = [i for i in open(file_path) if i[:-1]]\n\nIf writing to another file is a requirement, you can use file_object.writelines(lines) with opening file for writing.\n",
"The following isn't a one-liner, but does the job and is easy to read:\nfor line in open(filename):\n line = line.rstrip()\n if line != ''... | [
10,
6,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006745854_python.txt |
Q:
Python/Tkinter: How can I get the .bind() method to work with keyboard keys?
I'm trying to learn Tkinter but I'm running into a problem. I'd like it so once the user hits their Enter key it will copy what is in an Entry field. I was planning on using the .bind() method but it doesn't seem to register my key presse... | Python/Tkinter: How can I get the .bind() method to work with keyboard keys? | I'm trying to learn Tkinter but I'm running into a problem. I'd like it so once the user hits their Enter key it will copy what is in an Entry field. I was planning on using the .bind() method but it doesn't seem to register my key presses. I tried multiple ways and it seems if they are keyboard related, they do not wo... | [
"It seems you have to call self.frame.focus_set() first.\n"
] | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006755747_python_tkinter.txt |
Q:
Hashing an IP address to a number in [0, H)
I'm using Python-2.6. I have very little knowledge of hash functions.
I want to use a CRC hash function to hash an IP address like '128.0.0.5' into the range [0, H). Currently I'm thinking of doing
zlib.crc32('128.0.0.5')%H.
Is this okay? There's a few ques. you could ... | Hashing an IP address to a number in [0, H) | I'm using Python-2.6. I have very little knowledge of hash functions.
I want to use a CRC hash function to hash an IP address like '128.0.0.5' into the range [0, H). Currently I'm thinking of doing
zlib.crc32('128.0.0.5')%H.
Is this okay? There's a few ques. you could try and answer...
does it make any diff. if I ha... | [
"Why do you want to hash an IP address into a number? They already have a native integer representation. For example, using netaddr:\n>>> import netaddr\n>>> ip = netaddr.IPAddress('192.168.1.1')\n>>> ip.value\n3232235777\n>>> netaddr.IPAddress(3232235777)\nIPAddress('192.168.1.1')\n\n",
"ad 1) It will yield dif... | [
5,
2,
2
] | [] | [] | [
"crc32",
"hash",
"ip_address",
"python",
"zlib"
] | stackoverflow_0006756063_crc32_hash_ip_address_python_zlib.txt |
Q:
Python regex for unenclosed quotation marks
Possible Duplicate:
Split a string by spaces — preserving quoted substrings — in Python
Given the following string:
term1 term2 "the second term has spaces" term3 bad term 4
What regex will give me this list:
["term1", "term2", "the second term has spaces", "term3", "... | Python regex for unenclosed quotation marks |
Possible Duplicate:
Split a string by spaces — preserving quoted substrings — in Python
Given the following string:
term1 term2 "the second term has spaces" term3 bad term 4
What regex will give me this list:
["term1", "term2", "the second term has spaces", "term3", "bad", "term", "4"]
| [
"For your simple example, this works fine:\nimport re\nquotestring = 'term1 term2 \"the second term has spaces\" term3 bad term 4'\n# uses a lookahead and lookbehind to check for quoted strings\nstringlist = re.findall(r'((?<=\\\").+(?=\\\")|\\w+)', quotestring)\nprint(stringlist) # works on Python 2 or 3\n\nOr, fr... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006755749_python_regex.txt |
Q:
Python import issue
So apparently I just don't know how to import things correctly in a Python program. I'm just starting with the language, and it's much different from the Java that I'm used to.
Anyway, the main problem is that there's something wrong with how I'm importing packages/modules/classes and I can't s... | Python import issue | So apparently I just don't know how to import things correctly in a Python program. I'm just starting with the language, and it's much different from the Java that I'm used to.
Anyway, the main problem is that there's something wrong with how I'm importing packages/modules/classes and I can't seem to figure out what it... | [
"main.py:\nfrom Person import Person\nfrom Person import Student\n\nif __name__ == '__main__':\n\n p = Person.Person(\"Jim\", 20)\n print(p)\n s = Student.Student(\"Jim\", 20, \"math\")\n print(s)\n\nstudent.py\nfrom Person import Person\n\nclass Student(Person):\n\n def __init__(self, name, age, sub... | [
2,
0
] | [] | [] | [
"import",
"inheritance",
"python"
] | stackoverflow_0006756569_import_inheritance_python.txt |
Q:
Python: OpenMPI Vs. RabbitMQ
Suppose that one is interested to write a python app where there should be communication between different processes. The communications will be done by sending strings and/or numpy arrays.
What are the considerations to prefer OpenMPI vs. a tool like RabbitMQ?
A:
There is no single ... | Python: OpenMPI Vs. RabbitMQ | Suppose that one is interested to write a python app where there should be communication between different processes. The communications will be done by sending strings and/or numpy arrays.
What are the considerations to prefer OpenMPI vs. a tool like RabbitMQ?
| [
"There is no single correct answer to such question. It all depends on a big number of different factors. For example:\n\nWhat kind of communications do you have? Are you sending large packets or small packets, do you need good bandwidth or low latency?\nWhat kind of delivery guarantees do you need?\nOpenMPI can in... | [
13,
4
] | [] | [] | [
"amqp",
"messaging",
"mpi",
"python",
"rabbitmq"
] | stackoverflow_0006756630_amqp_messaging_mpi_python_rabbitmq.txt |
Q:
Numpy: is it possible to use numpy and ndarray to replace for a loop in this code snippet?
I am looking for a smarter and better solution.
I want to apply different scaling factors to a number field based on the label content. Hopefully the following code can illustrate what I am trying to achieve:
PS = [('A', 'LA... | Numpy: is it possible to use numpy and ndarray to replace for a loop in this code snippet? | I am looking for a smarter and better solution.
I want to apply different scaling factors to a number field based on the label content. Hopefully the following code can illustrate what I am trying to achieve:
PS = [('A', 'LABEL1', 20),
('B', 'LABEL2', 15),
('C', 'LABEL3', 120),
('D', 'LABEL1', 3),]
FACTOR = [('LABEL1'... | [
"If you want to mix data types you are going to want structured arrays.\nIf you are going to want the index of matching values in a lookup array you want searchsorted\nYour example goes like this:\n>>> import numpy as np\n>>> PS = np.array([\n ('A', 'LABEL1', 20),\n ('B', 'LABEL2', 15),\n ('C', 'LABEL3', 1... | [
4,
1,
0
] | [] | [] | [
"numpy",
"performance",
"python"
] | stackoverflow_0006756616_numpy_performance_python.txt |
Q:
Comparing two lists and "looking back"
How would you approach comparing two lists and "looking back"?
I'm comparing the elements of two lists like this:
score = 0
for (x,y) in zip(seqA,seqB):
if x == y:
score = score +1
if x !=y :
score = score - 1
Now I would like score + 3 if the previ... | Comparing two lists and "looking back" | How would you approach comparing two lists and "looking back"?
I'm comparing the elements of two lists like this:
score = 0
for (x,y) in zip(seqA,seqB):
if x == y:
score = score +1
if x !=y :
score = score - 1
Now I would like score + 3 if the previous pair was a match, so basically I would h... | [
"Just save the result of the last match.\nscore = 0\nprev = 0\n\nfor (x,y) in zip(seqA,seqB):\n\n if x == y:\n if prev == 1:\n score = score +3\n else:\n score = score +1\n prev = 1\n\n if x !=y :\n score = score - 1\n prev = 0\n\n",
"There may be a ... | [
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006757169_python.txt |
Q:
Python httplib2 Handling Exceptions
I have this very simple code to check if a site is up or down.
import httplib2
h = httplib2.Http()
response, content = h.request("http://www.folksdhhkjd.com")
if response.status == 200:
print "Site is Up"
else:
print "Site is down"
When I enter a valid URL then it prop... | Python httplib2 Handling Exceptions | I have this very simple code to check if a site is up or down.
import httplib2
h = httplib2.Http()
response, content = h.request("http://www.folksdhhkjd.com")
if response.status == 200:
print "Site is Up"
else:
print "Site is down"
When I enter a valid URL then it properly prints Site is Up because the status... | [
"try:\n response, content = h.request(\"http://www.folksdhhkjd.com\")\n if response.status==200:\n print \"Site is Up\"\nexcept httplib2.ServerNotFoundError:\n print \"Site is Down\"\n\nThe issue with your code is that if the host doesn't respond, the request doesn't return ANY status code, and so t... | [
7,
4
] | [] | [] | [
"httplib2",
"python"
] | stackoverflow_0006757252_httplib2_python.txt |
Q:
How to find whether a value is not contains in a List or Dist in Python
I can use dist.__ contains__ (value) to know whether a value is included or not in a List or Dist.But I need to return True if a value is not included in dist or list.
I tried If !dist._contains _(value) .Obviously, not worked.Please give me... | How to find whether a value is not contains in a List or Dist in Python | I can use dist.__ contains__ (value) to know whether a value is included or not in a List or Dist.But I need to return True if a value is not included in dist or list.
I tried If !dist._contains _(value) .Obviously, not worked.Please give me a solution.
| [
"It's simple:\nif value not in dist:\n\n",
"Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) \n>>> 3 in [1, 2, 3] # To know if a value is in a list\nTrue\n>>> 3 in {1: 'one', 2: 'two', 3: 'three'} # To know if a value is in keys of a dict\nTrue\n>>> 'three' in {1: 'one', 2: 'two', 3: 'three'}.values() # To know ... | [
4,
2,
1
] | [] | [] | [
"conditional",
"python"
] | stackoverflow_0006756132_conditional_python.txt |
Q:
How to convert two strings to give you a function name in Python
If you had two strings, like so ->
string1 = "get"
string2 = "Feed"
So how would you use these 2 strings to call a function named -> getFeed() ?
A:
Depending on where the function is, you can use one of these:
globals()[string1 + string2]()
loca... | How to convert two strings to give you a function name in Python | If you had two strings, like so ->
string1 = "get"
string2 = "Feed"
So how would you use these 2 strings to call a function named -> getFeed() ?
| [
"Depending on where the function is, you can use one of these:\nglobals()[string1 + string2]()\nlocals()[string1 + string2]()\n\n",
"If ImportedLib had your function getFeed(), you'd call it as such:\nimport ImportedLib\ngetattr(ImportedLib, string1+string2)()\n\n",
"Assume the function is located inside foo. T... | [
7,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0006757630_python.txt |
Q:
Python Sorting of HTML Tags on Page / CSS Columnization
This code / markup...
<ul id="tag-directory" class="clearfix">
<li py:for="tag in tags"><a href="${h.url_for(controller='/media', action='index', tag=tag.slug)}">${tag.name}</a> (${tag.media_count_published})</li>
</ul>
With this styling...
#tag-dire... | Python Sorting of HTML Tags on Page / CSS Columnization | This code / markup...
<ul id="tag-directory" class="clearfix">
<li py:for="tag in tags"><a href="${h.url_for(controller='/media', action='index', tag=tag.slug)}">${tag.name}</a> (${tag.media_count_published})</li>
</ul>
With this styling...
#tag-directory {
clear: both;
}
#tag-directory li {
width: 50... | [
"If Internet Explorer's lack of support is not an issue for you, you could use CSS3 columns.\nUpdate in response to comment:\nAs your items are all in one list (and I assume you want to keep it that way), it's tricky. You might like to take a look at this (pages 2 and 3 deal with fake columns), but to be honest I'd... | [
1
] | [] | [] | [
"css",
"html",
"python"
] | stackoverflow_0006757612_css_html_python.txt |
Q:
Running Python in php function possible?
I have to execute a Python script; problem is I have never used it before
import urlib
import urlib2
data={'username':'xyz', 'secret':'12312'}
encoded_data = urllib.urlencode(data)
open_url= urllib2.url
open('www.abc.com/api/',encoded_data)
print open_url.read()
Now... | Running Python in php function possible? | I have to execute a Python script; problem is I have never used it before
import urlib
import urlib2
data={'username':'xyz', 'secret':'12312'}
encoded_data = urllib.urlencode(data)
open_url= urllib2.url
open('www.abc.com/api/',encoded_data)
print open_url.read()
Now I want to use this script in my PHP function,... | [
"I personally think, if that's the contents of your Python script, that you should just replace your call out to the Python script with a native PHP call to curl.\nHere is a basic example: http://www.php.net/manual/en/curl.examples-basic.php\n<?php\n\n $ch = curl_init(\"http://www.example.com/\");\n $fp = fop... | [
2,
1
] | [] | [] | [
"codeigniter",
"php",
"python"
] | stackoverflow_0006757748_codeigniter_php_python.txt |
Q:
Generator function with pymongo
I am trying to make a generator function that yields an item on each call, however I keep getting the same item. Here is my code:
1 from pymongo import Connection
2
3 connection = Connection()
4 db = connection.store
5 collection = db.products
6
7 def test():
8 ... | Generator function with pymongo | I am trying to make a generator function that yields an item on each call, however I keep getting the same item. Here is my code:
1 from pymongo import Connection
2
3 connection = Connection()
4 db = connection.store
5 collection = db.products
6
7 def test():
8 global collection #using a globa... | [
"First of all, remove return, it's not necessary.\nYour problem isn't with test() but how you're calling it. Don't just call test().\nDo something like:\nfor item in test():\n print item\n\nAnd you'll get one item at a time. What this is doing is basically:\nfrom exceptions import StopIteration\nit = iter(test()... | [
1
] | [] | [] | [
"generator",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0006757900_generator_mongodb_pymongo_python.txt |
Q:
String.Contains in Python
I have a code like this...
if active == 1: // A flag which is set if a Site is Active
for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')):
if link.has_key('href'):
if 'MY_TEXT' in link['href'].upper(): //Check if the link has the string MY_TEXT in ... | String.Contains in Python | I have a code like this...
if active == 1: // A flag which is set if a Site is Active
for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')):
if link.has_key('href'):
if 'MY_TEXT' in link['href'].upper(): //Check if the link has the string MY_TEXT in it. If it has print it and brea... | [
"You don't tell us the input on which it does not work.\nOne obvious difference between the first version and the second is the lack of .upper() in the second. Is this what's causing the problem?\nIt is also unclear why you'd replace in with __contains__, but that should not matter either way.\n",
"A cleaner way ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006758399_python.txt |
Q:
Python exit codes
Where can I find information about meaning of exit codes of "python" process on Unix? For instance, if I do "python thisfiledoesntexist.py", I get exit code 2
Summary:
from errno import errorcode
print errorcode[2]
A:
As stated, mostly the error codes come from the executed script and sys.exit(... | Python exit codes | Where can I find information about meaning of exit codes of "python" process on Unix? For instance, if I do "python thisfiledoesntexist.py", I get exit code 2
Summary:
from errno import errorcode
print errorcode[2]
| [
"As stated, mostly the error codes come from the executed script and sys.exit().\nThe example with a non-existing file as an argument to the interpreter fall in a different category. Though it's stated nowhere I would guess, that these exit codes are the \"standard\" Linux error codes. There is a module called errn... | [
9,
8,
3,
0
] | [] | [] | [
"python",
"unix"
] | stackoverflow_0006758514_python_unix.txt |
Q:
Convert Intel HEX file to binary file
I have a Intel HEX file and I want to have a binary file.
How, in python ?
I think use the binascii module but I don't know what function is the most appropriate.
Thanks
A:
You may be interested in the IntelHex python lib.
A:
If you have a string of hex, you can decode it ... | Convert Intel HEX file to binary file | I have a Intel HEX file and I want to have a binary file.
How, in python ?
I think use the binascii module but I don't know what function is the most appropriate.
Thanks
| [
"You may be interested in the IntelHex python lib.\n",
"If you have a string of hex, you can decode it using the decode method. For instance,\n>>> s = '0001020304'\n>>> s.decode('hex')\n'\\x00\\x01\\x02\\x03'\n\n"
] | [
8,
0
] | [] | [] | [
"binary",
"hex",
"python"
] | stackoverflow_0006754487_binary_hex_python.txt |
Q:
Django - huge memory usage on "for" with QuerySet
I have such QuerySet in Django.
j = piosenki.objects.select_related('projekt__postac').distinct().exclude(typ__in=["live", "remix"]).filter(piosenki__plyta__status=1, piosenki__plyta__typ='s')
.extra(select={ 'ocena' : 'dobroc', 'plyta' : 'SELECT plyta_id FROM plyt... | Django - huge memory usage on "for" with QuerySet | I have such QuerySet in Django.
j = piosenki.objects.select_related('projekt__postac').distinct().exclude(typ__in=["live", "remix"]).filter(piosenki__plyta__status=1, piosenki__plyta__typ='s')
.extra(select={ 'ocena' : 'dobroc', 'plyta' : 'SELECT plyta_id FROM plyty_piosenki INNER JOIN plyty_plyty ON plyty_plyty.id = p... | [
"First, ensure you use db_index on the fields you do sorting and joining on. Secondly, try queryset iterators:\n\nFor a QuerySet which returns a large number of objects, this often\n results in better performance and a significant reduction in memory\n\n",
"If you don't need model instances or only certain field... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006758609_django_python.txt |
Q:
Serving static files with WSGI and Python 3
What is the simplest way to serve static files with WSGI and Python 3.2? There are some WSGI apps for PEP 333 and Python 2 for this purpose - but was is about PEP 3333 and Python 3? I want to use wsgiref for development.
A:
Typically, you don't want to serve static fil... | Serving static files with WSGI and Python 3 | What is the simplest way to serve static files with WSGI and Python 3.2? There are some WSGI apps for PEP 333 and Python 2 for this purpose - but was is about PEP 3333 and Python 3? I want to use wsgiref for development.
| [
"Typically, you don't want to serve static files using WSGI. WSGI is used so that dynamic content can be generated by using Python. Static files, by definition, are not dynamic content, so you don't need the additional layer of WSGI and any web app you've built on it. Instead, you would be best to set up your web s... | [
7,
2,
1
] | [] | [] | [
"file",
"python",
"python_3.x",
"wsgi"
] | stackoverflow_0006757898_file_python_python_3.x_wsgi.txt |
Q:
Beautiful Soup to Find and Regex Replace text 'not within '
I am using Beautiful Soup to parse a html to find all text that is
1.Not contained inside any anchor elements
I came up with this code which finds all links within href but not the other way around.
How can I modify this code to get only plain text usin... | Beautiful Soup to Find and Regex Replace text 'not within ' | I am using Beautiful Soup to parse a html to find all text that is
1.Not contained inside any anchor elements
I came up with this code which finds all links within href but not the other way around.
How can I modify this code to get only plain text using Beautiful Soup, so that I can do some find and replace and modif... | [
"If I understand you correct, you want to get the text that is inside an a element that contains an href attribute. If you want to get the text of the element, you can use the .text attribute. \n>>> soup = BeautifulSoup.BeautifulSoup()\n>>> soup.feed('<a href=\"http://something.com\">this is some text</a>')\n>>> ... | [
3
] | [] | [] | [
"beautifulsoup",
"find",
"html",
"python"
] | stackoverflow_0006758100_beautifulsoup_find_html_python.txt |
Q:
Run shell commands from python and string concatenation
I am trying to adjust the "post to dropbox" services for Snow loepard (http://dl.dropbox.com/u/1144075/Post%20to%20Dropbox.zip).
I dont want the public URL, but a shortened one from goo.gl
Therefor I am using these shell commands:
curl -s --data-urlencode "ur... | Run shell commands from python and string concatenation | I am trying to adjust the "post to dropbox" services for Snow loepard (http://dl.dropbox.com/u/1144075/Post%20to%20Dropbox.zip).
I dont want the public URL, but a shortened one from goo.gl
Therefor I am using these shell commands:
curl -s --data-urlencode "url=http://link.com" http://googl/action/shorten | grep "googl"... | [
"I think your os.system call should look something like this:\nos.system(\"curl -s --data-urlencode \\\"url=%s\\\" http://goo.gl/action/shorten | grep \\\"goo.gl\\\" | awk -F\\\\\\\" '{print $(NF-1)}' | awk 'BEGIN { FS = \\\"=\\\" } ; { print $2}' | pbcopy \" % thisURL)\n\n",
"UPDATE I wrote the script for you an... | [
1,
0,
0
] | [] | [] | [
"dropbox",
"python"
] | stackoverflow_0006750133_dropbox_python.txt |
Q:
Django loose coupling and extending a pre-existing model
Lets say that I create an application blog [which is irrelevant it's just there so I can do app.blog.posts - so it's really just a folder] and then in blog I create the app posts inside of blog and posts defines the model post. After I do this I would then ... | Django loose coupling and extending a pre-existing model | Lets say that I create an application blog [which is irrelevant it's just there so I can do app.blog.posts - so it's really just a folder] and then in blog I create the app posts inside of blog and posts defines the model post. After I do this I would then create an application categories in blog which should extend t... | [
"If \"extend\" means to somehow add functionality, in general, signals are are great idea. Using signals, you can hook into some of a model's methods without even modifying the model files.\nIf you simply need your blog posts to have categories, what's the problem using a foreign key in blog posts?\nIt's always a g... | [
2
] | [] | [] | [
"django",
"django_models",
"loose_coupling",
"python"
] | stackoverflow_0006756947_django_django_models_loose_coupling_python.txt |
Q:
Getting a list from a config file with ConfigParser
I have something like this in my config file (a config option that contains a list of strings):
[filters]
filtersToCheck = ['foo', '192.168.1.2', 'barbaz']
Is there a more elegant (built-in) way to get a list from filtersToCheck instead of removing the brackets,... | Getting a list from a config file with ConfigParser | I have something like this in my config file (a config option that contains a list of strings):
[filters]
filtersToCheck = ['foo', '192.168.1.2', 'barbaz']
Is there a more elegant (built-in) way to get a list from filtersToCheck instead of removing the brackets, single-quotes, spaces and then using split() to do that?... | [
"You cannot use the python object like a list in the value for the config file. But you can ofcourse have them as comma separated values and once you get it do a split\n[filters]\nfiltersToCheck = foo,192.168.1.2,barbaz\n\nand do\nfiltersToCheck = value.split(',')\n\nThe other approach is ofcourse, subclassing Safe... | [
27,
1
] | [] | [] | [
"configparser",
"configuration_files",
"list",
"python",
"python_3.x"
] | stackoverflow_0006759016_configparser_configuration_files_list_python_python_3.x.txt |
Q:
Joining Elements in a List according to length - Python
I am trying to design a parser for FASTA files (without using biopython) and am having problems in the following area:
I have a list of DNA sequences such as ['AAACCCGAU', 'AUUCCCCCCGGA', 'AACCCGGUU', 'AAACCCCUU'] etc.. named sequence_lines2.
My target progra... | Joining Elements in a List according to length - Python | I am trying to design a parser for FASTA files (without using biopython) and am having problems in the following area:
I have a list of DNA sequences such as ['AAACCCGAU', 'AUUCCCCCCGGA', 'AACCCGGUU', 'AAACCCCUU'] etc.. named sequence_lines2.
My target program is:
If the element in the list has any multiple of 60 chara... | [
"Try with this one liner : \nresult = \"\".join([el for el in sequence_lines2 if not len(el) % 60])\n\nThe len(el) % 60 computes the modulo of length with 60 and if the result is 0, this is a multiple of 60.\n"
] | [
2
] | [] | [] | [
"bioinformatics",
"python"
] | stackoverflow_0006759231_bioinformatics_python.txt |
Q:
Decorator with parameters injection
I would like to injecte a decorator on a method class from another class.
I have the following interface :
class Interface(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def run(self):
"""Run the process."""
return
I am have my class that... | Decorator with parameters injection | I would like to injecte a decorator on a method class from another class.
I have the following interface :
class Interface(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def run(self):
"""Run the process."""
return
I am have my class that uses the interface
class Launch(Interfa... | [
"Using your help I create the follwing function that detects if implementation is done :\n modpath = \"C:/mypath\"\n\n for modname in listdir(modpath):\n if modname.endswith(\".py\"):\n # look only in the modpath directory when importing\n oldpath, pa... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006651961_python.txt |
Q:
Sorting files by date
I found this directory checking code on the web and modified it a little, so it would print out added files. There's a buoy that sends me readings every now-and-then, but sometimes the connection is lost and instead of one file it sends multiple files. I need the program to sort them for me b... | Sorting files by date | I found this directory checking code on the web and modified it a little, so it would print out added files. There's a buoy that sends me readings every now-and-then, but sometimes the connection is lost and instead of one file it sends multiple files. I need the program to sort them for me by date created. Is there a ... | [
"added.sort(key=lambda x: os.stat(os.path.join(path_to_watch, x)).st_mtime)\n\nWill sort the added list by the last modified time of the files \nUse st_ctime instaed of st_mtime for creation time on Windows (it doesn't mean that on other platforms).\n"
] | [
27
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0006759415_list_python_sorting.txt |
Q:
Max element/size of a numpy matrix?
what is the max element/case of a numpy matrix or what is the maximal size of a numpy matrix?
the code above returns memory error at variable matrix size...so from what environmental thing does it depend (number of sequential amount of memory available?)?
for ret in xrange(5000,... | Max element/size of a numpy matrix? | what is the max element/case of a numpy matrix or what is the maximal size of a numpy matrix?
the code above returns memory error at variable matrix size...so from what environmental thing does it depend (number of sequential amount of memory available?)?
for ret in xrange(5000,7000,50):
res = []
for x in xrange... | [
"See Upper memory limit?.\nAs for when it returned a memory error, the answer is when allocating memory for one of the large objects. It could be any one, because you'll be at a higher amount of memory than ever before by the time you allocate the later rows of res, since the numpy matrixes don't get garbage collec... | [
1
] | [] | [] | [
"matrix",
"memory_management",
"numpy",
"python",
"windows"
] | stackoverflow_0006758986_matrix_memory_management_numpy_python_windows.txt |
Q:
Why can't I get my static dir to work with django 1.3?
This problem is very simple, but I just can't figure it out
added to my urlpatterns
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/user/www/site/static'})
where my main.css is : /home/user/www/site/static/css/main.css
when... | Why can't I get my static dir to work with django 1.3? | This problem is very simple, but I just can't figure it out
added to my urlpatterns
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/user/www/site/static'})
where my main.css is : /home/user/www/site/static/css/main.css
when I access http://localhost:8000/static/
I get: 404: Director... | [
"If you are using the built-in development webserver (i.e. run it with manage.py runserver), Django will take care of static files while in development.\nPlease note that STATIC_ROOT is the path where Django collects static files in, rather than the path that it serves files from. You should not maintain STATIC_RO... | [
9,
1,
0
] | [] | [] | [
"django",
"python",
"static",
"url_pattern",
"web"
] | stackoverflow_0006363728_django_python_static_url_pattern_web.txt |
Q:
format string in python 2.5 unpacking a list
Is there a way to do something like this in Python 2.5:
b = ('{!s}'*3)
b.format(*[i for i in xrange (3)])
because this is not working:
b = ('%s'*3)
b % (*[i for i in xrange (3)])
A:
b = '%s' * 3
b % tuple(range(3))
A:
b = '%s'*3
b % tuple(i for i in xrange (3))
| format string in python 2.5 unpacking a list | Is there a way to do something like this in Python 2.5:
b = ('{!s}'*3)
b.format(*[i for i in xrange (3)])
because this is not working:
b = ('%s'*3)
b % (*[i for i in xrange (3)])
| [
"b = '%s' * 3\nb % tuple(range(3))\n\n",
"b = '%s'*3\nb % tuple(i for i in xrange (3))\n\n"
] | [
6,
1
] | [] | [] | [
"iterable_unpacking",
"python",
"string_formatting",
"tuples"
] | stackoverflow_0006759700_iterable_unpacking_python_string_formatting_tuples.txt |
Q:
Most efficient method to get key for similar values in a dict
I have a dictionary of objects:
# I have thousands of objects in my real world scenario
dic = {'k1':obj1, 'k2':obj2, 'k3':obj3, ...}
# keys are string
# objs are MyObject
Edit: Sorry for letting doubt in the question. Here is the exact class and the li... | Most efficient method to get key for similar values in a dict | I have a dictionary of objects:
# I have thousands of objects in my real world scenario
dic = {'k1':obj1, 'k2':obj2, 'k3':obj3, ...}
# keys are string
# objs are MyObject
Edit: Sorry for letting doubt in the question. Here is the exact class and the like() function:
class MyObject(object):
def __init__(self, perio... | [
"Since I don't know the structure of your data or the nature of the similarity you are seeking, I can only guess at what might work. But perhaps you could build some kind of prefix tree using dictionaries. As in:\ntrie = {'a':{'b':{'e':{}, 's':{}}, 'c':{'t':{}, 'k':{}}}}\n\nThese are most commonly used for looking ... | [
3,
2,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006749106_python.txt |
Q:
N-Dimensional Matrix Array in Python (with different sizes)
In Matlab, there is something called struct, which allow the user to have a dynamic set of matrices.
I'm basically looking for a function that allows me to index over dynamic matrices that have different sizes.
Example: (with 3 matrices)
Matrix 1: 3x2
M... | N-Dimensional Matrix Array in Python (with different sizes) | In Matlab, there is something called struct, which allow the user to have a dynamic set of matrices.
I'm basically looking for a function that allows me to index over dynamic matrices that have different sizes.
Example: (with 3 matrices)
Matrix 1: 3x2
Matrix 2: 2x2
Matrix 3: 2x1
Basically I want to store the 3 matr... | [
"Just use a tuple or list. \nA tuple matrices = tuple(matrix1, matrix2, matrix3) will be slightly more efficient;\nA list matrices = [matrix1, matrix2, matrix3] is more flexible as you can matrix.append(matrix4).\nEither way you can access them as matrices[0] or for matrix in matricies: pass # do stuff.\n",
"Put ... | [
7,
0
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0006760380_matrix_python.txt |
Q:
Unable to connect to mongodb running on a remote machine
I have mongodb running on a remote server. I can ssh to the remote server and connect to mongodb from the shell on the remote machine. However i have to connect to that mongodb instance from my python script.
However, im unable to connect to mongodb directly... | Unable to connect to mongodb running on a remote machine | I have mongodb running on a remote server. I can ssh to the remote server and connect to mongodb from the shell on the remote machine. However i have to connect to that mongodb instance from my python script.
However, im unable to connect to mongodb directly from the shell on my local machine running linux using the co... | [
"You can use netstat -a -p on the machine running mongodb to see what port it's attached to. (netstat -a lists all connections and -p provides the name of the program owning the connection.) Also make sure the remote computer is allowing external connections on that port (the connections aren't being blocked by a... | [
4
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0006760375_mongodb_pymongo_python.txt |
Q:
Replace \\ with / Python
This doesn't work:
import re
re.sub('\\', '/', "C:\\Users\\Judge")
Error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
re.sub('\\', '/', "C:\\Users")
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, ... | Replace \\ with / Python | This doesn't work:
import re
re.sub('\\', '/', "C:\\Users\\Judge")
Error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
re.sub('\\', '/', "C:\\Users")
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Python27\lib... | [
"Try escaping two backslashes instead of one: \\\\\\\\\nre.sub('\\\\\\\\', '/', \"C:\\\\Users\\\\Judge\")\nYou are just passing the RE engine one backslash, which confuses it. So, not only do you have to escape the backslashes for Python to be happy, you need to escape it again for RE. Since you are escaping two ba... | [
7,
4,
2,
1,
1,
1
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0006760443_python_replace.txt |
Q:
Dynamic printing in web.py
I'm shifting an application from cgi to web.py. I get results and print them dynamically with a simple print statement in cgi. So the results have been printed before the page has completed loading. In web.py, I have a return statement and can't figure out how I can achieve the same.
Sa... | Dynamic printing in web.py | I'm shifting an application from cgi to web.py. I get results and print them dynamically with a simple print statement in cgi. So the results have been printed before the page has completed loading. In web.py, I have a return statement and can't figure out how I can achieve the same.
Sample cgi code:
print "<p><b>Disp... | [
"Either use a string which you append to and finally return:\ns = \"My page with...\"\ns += \"More data\"\nfor y in x:\n s += \"And this!\"\nreturn s\n\nOr the ability to yield data, described in http://webpy.org/cookbook/streaming_large_files\nThere are some gotchas, you have to set some headers and you can't m... | [
2,
1
] | [] | [] | [
"cgi",
"python",
"web.py"
] | stackoverflow_0006732227_cgi_python_web.py.txt |
Q:
Python CrawlSpider
I've been learning how to use scrapy though I had minimal experience in python to begin with. I started learning how to scrape using the BaseSpider. Now I'm trying to crawl websites but I've encountered a problem that has really confuzzled me. Here is the example code from the official site at h... | Python CrawlSpider | I've been learning how to use scrapy though I had minimal experience in python to begin with. I started learning how to scrape using the BaseSpider. Now I'm trying to crawl websites but I've encountered a problem that has really confuzzled me. Here is the example code from the official site at http://doc.scrapy.org/top... | [
"start_urls = ['http://www.example.com']\n\nexample.com doesn't have any links for categories or items. This is just an example of what a scraped site URL might be.\nThis is a non-working example in the documentation.\n",
"You might try making a spider that you know works, and see if print statements do anything ... | [
1,
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler",
"web_scraping"
] | stackoverflow_0006653535_python_scrapy_web_crawler_web_scraping.txt |
Q:
Problem in creating a separate function to read file in Hadoop Streaming
I have problem in creating a separate function to read file in Hadoop Streaming.
mapper.py: Works well (very inefficient)
#!/usr/bin/env python
import sys
def main():
for line in sys.stdin:
line = line.strip() # each line cont... | Problem in creating a separate function to read file in Hadoop Streaming | I have problem in creating a separate function to read file in Hadoop Streaming.
mapper.py: Works well (very inefficient)
#!/usr/bin/env python
import sys
def main():
for line in sys.stdin:
line = line.strip() # each line contains only one word, 5+ million lines
filename = "my_dict.txt" # contains... | [
"Try this simplified script:\n#!/usr/bin/env python\n\nimport sys\n\ndef main():\n filename = \"my_dict.txt\"\n listfile = open(filename)\n # doesn't create an itermediate list\n listDM = set(line.strip() for line in listfile)\n # less Pythonic but significantly faster\n # still doesn't create an ... | [
1
] | [] | [] | [
"hadoop",
"python"
] | stackoverflow_0006760684_hadoop_python.txt |
Q:
Python: sub list of items depending on a certain value of the items, e.g. boolean
I have a list of similar objects, some of them have a certain value set, here more specifically a boolean flag:
myList = [WhatEver(..., True, ...), WhatEver(..., True, ...), WhatEver(..., False, ...), WhatEver(..., True, ...), WhatEv... | Python: sub list of items depending on a certain value of the items, e.g. boolean | I have a list of similar objects, some of them have a certain value set, here more specifically a boolean flag:
myList = [WhatEver(..., True, ...), WhatEver(..., True, ...), WhatEver(..., False, ...), WhatEver(..., True, ...), WhatEver(..., False, ...), ...]
Is there a painless way in Python to get a sub list of items... | [
"Yes, there is. List comprehensions are a very good fit for this:\n[item for item in myList if item.flag]\n[item for item in myList if not item.flag]\n\nwhere flag is the name of WhatEver's field that you want to check.\n",
"Use filter:\nfiltered_list = filter(lambda item: item.flag, myList)\n\n"
] | [
7,
1
] | [] | [] | [
"boolean",
"list",
"python",
"sublist"
] | stackoverflow_0006760857_boolean_list_python_sublist.txt |
Q:
escape character for sqlalchemy using execute()
I am dealing with a mySQL/sqlAlchemy execute statement that looks like this:
stmt = 'SELECT * from myTable where id=:idVar AND pct LIKE :pctVar'
args = {idVar:5, pctVar:'5%\\%'}
result = session.execute(stmt, args).fetchall()
How do I escape the '%'? The above does... | escape character for sqlalchemy using execute() | I am dealing with a mySQL/sqlAlchemy execute statement that looks like this:
stmt = 'SELECT * from myTable where id=:idVar AND pct LIKE :pctVar'
args = {idVar:5, pctVar:'5%\\%'}
result = session.execute(stmt, args).fetchall()
How do I escape the '%'? The above does not match "55%"
| [
"Try the following query with explicit ESCAPE specification:\nstmt = \"SELECT * from myTable where id=:idVar AND pct LIKE :pctVar ESCAPE '\\\\'\"\n\nIf it works, then check out NO_BACKSLASH_ESCAPES option.\n"
] | [
3
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0006755404_mysql_python_sqlalchemy.txt |
Q:
in eclipse, how can I read python build-in func source code? eg filter, map, reduce
how can I read python build-in function's source code? eg, filter, map, reduce
A:
These functions are written in C. You can view the source code here (be sure to select the correct version by tag) or download the source tarball f... | in eclipse, how can I read python build-in func source code? eg filter, map, reduce | how can I read python build-in function's source code? eg, filter, map, reduce
| [
"These functions are written in C. You can view the source code here (be sure to select the correct version by tag) or download the source tarball from here. \nAnyway, you can find the code for all function in __builtin__ in the file Python/bltinmodule.c. I.e. the implementation of filter is a function called built... | [
6
] | [] | [] | [
"eclipse",
"macos",
"python"
] | stackoverflow_0006760899_eclipse_macos_python.txt |
Q:
Is the += operator thread-safe in Python?
I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.
c = 0
def increment():
c += 1
def decrement():
c -= 1
Is this code thread safe?
If not, may I understand why it is not thread safe, an... | Is the += operator thread-safe in Python? | I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.
c = 0
def increment():
c += 1
def decrement():
c -= 1
Is this code thread safe?
If not, may I understand why it is not thread safe, and what kind of statements usually lead to non-t... | [
"No, this code is absolutely, demonstrably not threadsafe.\nimport threading\n\ni = 0\n\ndef test():\n global i\n for x in range(100000):\n i += 1\n\nthreads = [threading.Thread(target=test) for t in range(10)]\nfor t in threads:\n t.start()\n\nfor t in threads:\n t.join()\n\nassert i == 1000000,... | [
121,
31,
17,
12,
5,
2,
2,
0
] | [] | [] | [
"increment",
"python",
"thread_safety"
] | stackoverflow_0001717393_increment_python_thread_safety.txt |
Q:
How to slice list into contiguous groups of non-zero integers in Python
Can't seem to find a clue to this online and can't figure it out myself so:
How would I go about slicing a list so that I return a list of slices of contiguous non-zero integers. ie:
data = [3, 7, 4, 0, 1, 3, 7]
and I want to produce:
slices ... | How to slice list into contiguous groups of non-zero integers in Python | Can't seem to find a clue to this online and can't figure it out myself so:
How would I go about slicing a list so that I return a list of slices of contiguous non-zero integers. ie:
data = [3, 7, 4, 0, 1, 3, 7]
and I want to produce:
slices = [[3, 7, 4], [1, 3, 7]]
I have tried various methods of iterating through t... | [
"import itertools\n[ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]\n\n",
"Look at itertools.groupby:\n>>> data = [3, 7, 4, 0, 1, 3, 7, 4, 0, 5]\n>>> a=[list(i[1]) for i in itertools.groupby(data, key=lambda i:i==0)]\n>>> a\n[[3, 7, 4], [0], [1, 3, 7, 4], [0], [5]]\n>>> [i for i in a ... | [
15,
6,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006760871_python.txt |
Q:
inspect.getmembers() vs __dict__.items() vs dir()
Can anybody explain to me with adequate examples whats the difference b/w
>>> import inspect
>>> inspect.getmembers(1)
and
>>> type(1).__dict__.items()
and
>>> dir(1)
except that they show an decreasing no.s of attributes & methods in that order.
1 is intege... | inspect.getmembers() vs __dict__.items() vs dir() | Can anybody explain to me with adequate examples whats the difference b/w
>>> import inspect
>>> inspect.getmembers(1)
and
>>> type(1).__dict__.items()
and
>>> dir(1)
except that they show an decreasing no.s of attributes & methods in that order.
1 is integer (but it can be of any type.)
EDIT
>>>obj.__class__._... | [
"dir() allows you to customize what attributes your object reports, by defining __dir__().\nFrom the manual, if __dir__() is not defined:\n\nIf the object is a module object, the list contains the names of the module’s attributes.\nIf the object is a type or class object, the list contains the names of its attribut... | [
23
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0006761106_namespaces_python.txt |
Q:
inspect.getfile () vs inspect.getsourcefile()
I was just going through the inspect module docs.
What exactly is the difference between:
inspect.getfile()
and
inspect.getsourcefile()
I get exactly the same file path (of the module) for both.
A:
getfile():
Return the name of the (text or binary) file in which a... | inspect.getfile () vs inspect.getsourcefile() | I was just going through the inspect module docs.
What exactly is the difference between:
inspect.getfile()
and
inspect.getsourcefile()
I get exactly the same file path (of the module) for both.
| [
"getfile():\n\nReturn the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.\n\ngetfile() also returns pyc (compiled) files, where as getsourcefile() will only return source files.\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0006761337_python.txt |
Q:
Ported python3 csv module to C# what license should I use for my module?
I have ported python3 csv module to C# what license could I use for my module?
Should I distribute my module?
Should I put PSF copyright in every header of my module?
thanks
A:
You need to pay a copyright lawyer to tell you that. But my g... | Ported python3 csv module to C# what license should I use for my module? | I have ported python3 csv module to C# what license could I use for my module?
Should I distribute my module?
Should I put PSF copyright in every header of my module?
thanks
| [
"You need to pay a copyright lawyer to tell you that. But my guess is that you need to use the PSF license. Note that PSF does not have the copyright to Python source code. They coders do how that copyright translates into you making a C# port is something only a copyright expert can say. Also note that it is likel... | [
0
] | [] | [] | [
"licensing",
"module",
"python"
] | stackoverflow_0006761201_licensing_module_python.txt |
Q:
creating a dictionary named as variable
I am using pyodbc to query database and retrieve some data (obviously).
What I would like is to create new dictionaries namd according to values returned from query.
For example I have a table with 1000 items, and one of collumns in that table is a INT number which is in ran... | creating a dictionary named as variable | I am using pyodbc to query database and retrieve some data (obviously).
What I would like is to create new dictionaries namd according to values returned from query.
For example I have a table with 1000 items, and one of collumns in that table is a INT number which is in range 1-51.
I want to do a rundown through my ta... | [
"Don't.\nCreate a dictionary bought, and give it keys based on your number:\nbought = {}\nfor number in column_x:\n bought[number] = \"whatever object you need here\"\n\nSame for sold, created etc.\nOr just one big dict:\nmydict = {\"bought\": {}, \"sold\": {}, \"created\": {}}\nfor number in column_x:\n for ... | [
9
] | [] | [] | [
"dictionary",
"python",
"variables"
] | stackoverflow_0006761480_dictionary_python_variables.txt |
Q:
Python/Django import error os.path
I'm currently working on a Django-Project that amongst others has to read different file-formats. Each format got its own reading-script. The formats to be used depend on a choice, that is why the corresponding scripts are imported at run-time by my admin_view.py. That's done via... | Python/Django import error os.path | I'm currently working on a Django-Project that amongst others has to read different file-formats. Each format got its own reading-script. The formats to be used depend on a choice, that is why the corresponding scripts are imported at run-time by my admin_view.py. That's done via imp:
module = imp.load_source('lidardat... | [
"Rather than using imp, have a look at the magic method __import__, which can import modules without using filenames. Your code will end up something like:\nmodule_name = 'polly'\nmodule = getattr(__import__('lidardaten.datatypes', globals(), locals(), [module_name]), module_name)\n\n"
] | [
1
] | [] | [] | [
"django",
"import",
"importerror",
"python"
] | stackoverflow_0006761594_django_import_importerror_python.txt |
Q:
How to disable reverse dns lookup in python webserver?
i have a simple python cgi server:
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
h... | How to disable reverse dns lookup in python webserver? | i have a simple python cgi server:
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
httpd = server(server_address, handler)
httpd.serve_forever()... | [
"You can subclass your own handler class, which won't do the DNS lookups. This follows from http://docs.python.org/library/cgihttpserver.html#module-CGIHTTPServer which says CGIHTTPRequestHandler is interface compatible with BaseHTTPRequestHandler and BaseHTTPRequestHandler has a method address_string().\nclass MyH... | [
12
] | [] | [] | [
"dns",
"networking",
"python"
] | stackoverflow_0006761559_dns_networking_python.txt |
Q:
Pip install python modules easy
I am looking for an easy way to install/uninstall Python modules and found pip.
Where does pip install to?
I installed as an example "linkify" and it supposed to work but I didnt find it in the sitepackages.
With videodownloader I had a permission denied issue at usr/local/bin.
So ... | Pip install python modules easy | I am looking for an easy way to install/uninstall Python modules and found pip.
Where does pip install to?
I installed as an example "linkify" and it supposed to work but I didnt find it in the sitepackages.
With videodownloader I had a permission denied issue at usr/local/bin.
So I lost my hopes again to find somethi... | [
"Setuptools, http://pypi.python.org/pypi/setuptools includes the EasyInstall tool.\nCheck out http://packages.python.org/distribute/easy_install.html#downloading-and-installing-a-package to see how to use it.\nOnce you get that installed it should be ... easy.\n"
] | [
1
] | [] | [] | [
"installation",
"module",
"pip",
"python"
] | stackoverflow_0006761752_installation_module_pip_python.txt |
Q:
importing multiple functions from a Python module
I am importing lots of functions from a module
Is it better to use
from my_module import function1, function2, function3, function4, function5, function6, function7
which is a little messy, but avoids flooding the current namespace with everything from that module... | importing multiple functions from a Python module | I am importing lots of functions from a module
Is it better to use
from my_module import function1, function2, function3, function4, function5, function6, function7
which is a little messy, but avoids flooding the current namespace with everything from that module or
from my_module import *
Which looks tidy but will ... | [
"If you really need that many functions, you are already polluting your namespace.\nI would suggest:\nimport my_module\n\nOr, if my_module has a long name use an alias:\nimport my_long_module as m\n\n",
"If it's between one or the other, use\nfrom my_module import function1, function2, function3, function4, funct... | [
65,
43,
16
] | [] | [] | [
"coding_style",
"import",
"python"
] | stackoverflow_0006761825_coding_style_import_python.txt |
Q:
string searching with returning matched line in python
I am quite new in python.I want to match string in some lines of a file.Let's say,
I have string:
british 7
German 8
France 90
And I have some lines in a file as like:
<s id="69-7">...Meanwhile is the studio 7 album by British pop band 10cc.</s>
<s... | string searching with returning matched line in python | I am quite new in python.I want to match string in some lines of a file.Let's say,
I have string:
british 7
German 8
France 90
And I have some lines in a file as like:
<s id="69-7">...Meanwhile is the studio 7 album by British pop band 10cc.</s>
<s id="15-8">...And Then There Were Three... is the ninth stud... | [
"I have something rather complicated, but I wrote it in hurry and for the moment it does the job.\nNote that:\n\nI added 'in France' after Meanwhile is the studio 7 album by British pop band 10cc\nand that only British is modified\n'1978' in by the german band Genesis 8 and was released in 1978 isn't modified while... | [
4,
3,
1
] | [] | [] | [
"python",
"string_matching"
] | stackoverflow_0006761103_python_string_matching.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.