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:
How to retrieve the xml which has been created using the minidom?
from xml.dom.minidom import Document
def generateXML():
# Create the minidom document
doc = Document()
# Create the <discover> base element
discover = doc.createElement("discover")
doc.appendChild(discover)
# Create the... | How to retrieve the xml which has been created using the minidom? | from xml.dom.minidom import Document
def generateXML():
# Create the minidom document
doc = Document()
# Create the <discover> base element
discover = doc.createElement("discover")
doc.appendChild(discover)
# Create the main <host> element
host = doc.createElement("host")
host.app... | [
"You are appending the elements the wrong way. It's parentnode.appendChild(childnode), you've written it as childnode.appendChild(parentnode)\n"
] | [
1
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0006546541_minidom_python_xml.txt |
Q:
Page switching using AJAX in Django
I am trying to create site navigation using AJAX. I have navigation menu with links to different views (using {% url name %} in template). The thing I am trying to do is to load the page content using AJAX. The page content I am trying to load is enclosed in content block ({% bl... | Page switching using AJAX in Django | I am trying to create site navigation using AJAX. I have navigation menu with links to different views (using {% url name %} in template). The thing I am trying to do is to load the page content using AJAX. The page content I am trying to load is enclosed in content block ({% block content %}).
I also found this snippe... | [
"You should use django-pjax which is built exactly for that kind of thing.\nAll you will have to do is to, in the base template, include the whole page or just the block content based on whether the request is ajax or not.\ndjango-pjax does the AJAX calls using the jQuery and manipulates history using HTML5 push st... | [
7,
3
] | [] | [] | [
"django",
"pjax",
"python"
] | stackoverflow_0006546562_django_pjax_python.txt |
Q:
Help with validation in Models and Forms
I have a few questions about validation in Models and Forms. Could you help me out with these:
Where should validation be done? Should it be in the Model or the Form? Is the right way to go about this is to have validators in the form and constraints in the mode?
What is ... | Help with validation in Models and Forms | I have a few questions about validation in Models and Forms. Could you help me out with these:
Where should validation be done? Should it be in the Model or the Form? Is the right way to go about this is to have validators in the form and constraints in the mode?
What is the difference between writing a 'clean_' meth... | [
"The validation should be done on the form, not the model. However, if you are using ModelForms, which is usually makes a lot of sense, it will inherit some of the validation rules from the models themselves (those specific to the database, like maximum_field length, database field type, but also if they can be lef... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_validation",
"python"
] | stackoverflow_0006546706_django_django_forms_django_models_django_validation_python.txt |
Q:
class definition dependence on runtime
in my webapp I made two different sessionhandler classes inheriting from a class called SessionHandler
Now I'd like to initiate the appropriate handler (dependent on a cookie value.)
Background: My SessionHandler should be the base class of the Controller as it needs to call ... | class definition dependence on runtime | in my webapp I made two different sessionhandler classes inheriting from a class called SessionHandler
Now I'd like to initiate the appropriate handler (dependent on a cookie value.)
Background: My SessionHandler should be the base class of the Controller as it needs to call a Controller backend method otherwise i woul... | [
"I am not sure I entirely understood your question, but are you sure you need to use inheritance? Couldn't the class you need just be a member instead?\nChanging the superclass at runtime does not sound like a very good design, if at all possible.\nJust to be sure I got you, what you want to do is have Controller i... | [
0
] | [] | [] | [
"inheritance",
"python",
"superclass"
] | stackoverflow_0006546786_inheritance_python_superclass.txt |
Q:
how to create uncollectable garbage in python?
I have a large long-running server, and, over weeks the memory usage steadily climbs.
Generally, as pointed out below, its unlikely that leaks are my problem; however, I have not got a lot to go on so I want to see if there are any leaks.
Getting at console output is ... | how to create uncollectable garbage in python? | I have a large long-running server, and, over weeks the memory usage steadily climbs.
Generally, as pointed out below, its unlikely that leaks are my problem; however, I have not got a lot to go on so I want to see if there are any leaks.
Getting at console output is tricky so I'm not running with gc.set_debug(). This... | [
"Any cycle of finalizable objects (that is, objects with a __del__ method) is uncollectable (because the garbage collector does not know which order to run the finalizers in):\n>>> class Finalizable:\n... def __del__(self): pass\n...\n>>> a = Finalizable()\n>>> b = Finalizable()\n>>> a.x = b\n>>> b.x = a\n>>> d... | [
12
] | [] | [] | [
"garbage_collection",
"python"
] | stackoverflow_0006546823_garbage_collection_python.txt |
Q:
Do all iterators cache? How about csv.Reader?
We know the following code is loading the data line-by-line only rather than loading them all in memory. i.e. the line alread read will be somehow marked 'deletable' for the OS
def fileGen( file ):
for line in file:
yield line
with open("somefile") as file... | Do all iterators cache? How about csv.Reader? | We know the following code is loading the data line-by-line only rather than loading them all in memory. i.e. the line alread read will be somehow marked 'deletable' for the OS
def fileGen( file ):
for line in file:
yield line
with open("somefile") as file:
for line in fileGen( file ):
print li... | [
"The most reliable way to find out what csv.reader is doing is to read the source. See _csv.c, lines 773 onwards. You'll see that the reader object has a pointer to the underlying iterator (typically a file iterator), and it calls PyIter_Next each time it needs another line. So it does not read ahead or otherwise c... | [
4
] | [] | [] | [
"caching",
"csv",
"iterator",
"memory",
"python"
] | stackoverflow_0006546540_caching_csv_iterator_memory_python.txt |
Q:
Measuring process time of a multi-thread code in Python
I am running the following code try to measure how long my PG process finish, however, the "toc-tic" displays as soon as the whole loop finish, is there any way that I can measure the total time and time for individual thread? Thanks
tic = time.clock()
for i ... | Measuring process time of a multi-thread code in Python | I am running the following code try to measure how long my PG process finish, however, the "toc-tic" displays as soon as the whole loop finish, is there any way that I can measure the total time and time for individual thread? Thanks
tic = time.clock()
for i in range(0,2):
start = i * step
end = start +... | [
"Join the threads, before toc!\nYou can put the objects to a list, then call join on them!\nbefore the for :\npglist = [] \n... start the threads...\n\nfor pg in pglist:\n pg.join()\n\ntoc = time.clock()\n\nprint toc - tic\n\n"
] | [
2
] | [] | [] | [
"multithreading",
"profiling",
"python"
] | stackoverflow_0006546498_multithreading_profiling_python.txt |
Q:
Decoding response while opening a URL
I am using the following code to open a url and retrieve it's response :
def get_issue_report(query):
request = urllib2.Request(query)
response = urllib2.urlopen(request)
response_headers = response.info()
print response.read()
The response I get is as follows... | Decoding response while opening a URL | I am using the following code to open a url and retrieve it's response :
def get_issue_report(query):
request = urllib2.Request(query)
response = urllib2.urlopen(request)
response_headers = response.info()
print response.read()
The response I get is as follows :
<?xml version='1.0' encoding='UTF-8'?><e... | [
"Sentinel has explained how you can decode entity references like < but there's a bit more to the problem than that.\nThe example you give suggests that you are reading an Atom feed. If you want to do this reliably in Python, then I recommend using Mark Pilgrim's Universal Feed Parser.\nHere's how one would read... | [
3,
1,
1
] | [] | [] | [
"character_encoding",
"python",
"urllib2",
"utf_8"
] | stackoverflow_0006547237_character_encoding_python_urllib2_utf_8.txt |
Q:
Indentation error : unexpected error
I am new to Python and have written a code in notepad++. I have used spaces instead of tab and I guess I have used the correct indentation format. But I still get thie error. I dont understand what am I doing wrong. Here is the code,
#!/usr/bin/python
import sys
import shutil
... | Indentation error : unexpected error | I am new to Python and have written a code in notepad++. I have used spaces instead of tab and I guess I have used the correct indentation format. But I still get thie error. I dont understand what am I doing wrong. Here is the code,
#!/usr/bin/python
import sys
import shutil
import sys
def Usage() :
print "LabelFi... | [
"There is an indentation too much in front of\nfor line in iter(InFile) :\n\nReduce the indentation for that line and the following eight lines, and you should be all set.\n",
"line 21:\nfor line in iter(InFile) :\n\nstart aligning it with the line above\nTracebacks also tell you error line number so it's quite e... | [
3,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006547161_python.txt |
Q:
multithreading performance issue
Possible Duplicate:
Multithreading performance overhead
I have a piece of code that run slower on multithread and faster while using one thread.
Output from one thread:
Batch 0 finished in 0.0970576110595
Batch 1 finished in 0.712632355587
Batch 2 finished in 2.16707853982
Batch 3... | multithreading performance issue |
Possible Duplicate:
Multithreading performance overhead
I have a piece of code that run slower on multithread and faster while using one thread.
Output from one thread:
Batch 0 finished in 0.0970576110595
Batch 1 finished in 0.712632355587
Batch 2 finished in 2.16707853982
Batch 3 finished in 5.13259954359
Batch 4 fi... | [
"@mac's answer probably covers the why, but we'll need some of your code to give any more help. Something you may want to try, it to use multiprocessing instead of threading, but then you have data access issues...\nThreading in python is only any good on non-blocking IO as you only have one active thread per pytho... | [
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0006547552_multithreading_python.txt |
Q:
Initializing object variables - a Java approach, a Python approach?
I have an object that needs to have some 4-5 values passed to it. To illustrate:
class Swoosh():
spam = ''
eggs = ''
swallow = ''
coconut = ''
[... methods ...]
Right now, the way to use Swoosh is:
swoosh = Swoosh()
swoosh.se... | Initializing object variables - a Java approach, a Python approach? | I have an object that needs to have some 4-5 values passed to it. To illustrate:
class Swoosh():
spam = ''
eggs = ''
swallow = ''
coconut = ''
[... methods ...]
Right now, the way to use Swoosh is:
swoosh = Swoosh()
swoosh.set_spam('Spam!')
swoosh.set_eggs('Eggs!')
swoosh.set_swallow('Swallow!')
s... | [
"Firstly you're using old style classes. You really, really should be using new style classes that inherit from object:\nclass Swoosh(object):\n\nDefining an __init__ method that takes arguments is definitely the Pythonic way of doing things:\ndef __init__(self,spam,eggs,swallow,coconut):\n self.spam = spam\n ... | [
16,
11,
5,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0006547649_python.txt |
Q:
Getting value from radiobox in Tkinter - Python
I'm trying to create a GUI in Python using the Tkinter module, and part of that involves giving the user the option of two radioboxes, and to select which one they want. Depending on which box they tick, it then runs different functions which return different results... | Getting value from radiobox in Tkinter - Python | I'm trying to create a GUI in Python using the Tkinter module, and part of that involves giving the user the option of two radioboxes, and to select which one they want. Depending on which box they tick, it then runs different functions which return different results - results that I then want to use outside of the win... | [
"Generally speaking you should never have any code after the call to mainloop, that's just not how GUI programs work. \nWhen the user presses the button, all the work should happen (or be started from) the command for the button. If you then want the program to exit you destroy the root window (which causes the mai... | [
1,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006547355_python_tkinter.txt |
Q:
django/python - db hits while accessing variables
class AppUser(models.Model):
user = models.ForeignKey(User, unique=True)
slug = models.SlugField(editable=False, blank=True)
For above model suppose we have a object "appuser" which we have rendered in template
Does django hits User db each time when we us... | django/python - db hits while accessing variables | class AppUser(models.Model):
user = models.ForeignKey(User, unique=True)
slug = models.SlugField(editable=False, blank=True)
For above model suppose we have a object "appuser" which we have rendered in template
Does django hits User db each time when we use it like appuser.user.username in our code??
Any help ... | [
"You should carefully read through this for all details to database access optimization: https://docs.djangoproject.com/en/1.3/topics/db/optimization/\nAnd select_related():\nhttps://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related\nAs for a quick answer to your question: It depends on how you've ... | [
2,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006547743_django_python.txt |
Q:
Scapy show2() packet problem
I'm trying to create some scapy layers and want them to adapt their size on the fly. I use the following code:
class Foo(Packet):
name = "Testpacket"
fields_desc = [
ByteField("length", None),
ByteField("byte2", None),
ByteField("byte3", None),
ByteF... | Scapy show2() packet problem | I'm trying to create some scapy layers and want them to adapt their size on the fly. I use the following code:
class Foo(Packet):
name = "Testpacket"
fields_desc = [
ByteField("length", None),
ByteField("byte2", None),
ByteField("byte3", None),
ByteField("byte4", None),
Byte... | [
"Martin, your understanding is mistaken... .show2() computes the packet after assembly. .show() is not supposed to calculate the length... for example, with IP...\n>>> from scapy.all import IP\n>>> bar = IP(dst='4.2.2.2')/\"Yo mama is ugly. So ugly. Aaahhhhhh my eyes\"\n\nresults of .show2()...\n>>> bar.show2()\... | [
2
] | [] | [] | [
"python",
"scapy"
] | stackoverflow_0006545620_python_scapy.txt |
Q:
How do I find the numbers that are not listed or missing?
I'll have a list of numbers, each on its own line (say 0 -100). How do I find the numbers that are not listed or missing?
A:
Add them all to a set. Then subtract from a set filled with 1-100. Here's an example for 0-9:
>>> set(range(10)) - set([1, 4, 5, ... | How do I find the numbers that are not listed or missing? | I'll have a list of numbers, each on its own line (say 0 -100). How do I find the numbers that are not listed or missing?
| [
"Add them all to a set. Then subtract from a set filled with 1-100. Here's an example for 0-9:\n>>> set(range(10)) - set([1, 4, 5, 6, 8, 2])\nset([0, 9, 3, 7])\n>>> \n\nI had [1, 4, 5, 6, 8, 2] listed. To find out which numbers in range 0-9 are missing, I created a set with all of 0-9 and then subtracted the set wi... | [
12,
1,
0,
0
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0006544403_bash_python.txt |
Q:
Python 3 C API. Initialising MIMEText object fails
I am looking to embed Python into a C program. Among other things Python will look after sending email. I have no trouble using the base types from C, but I have trouble using other objects within the library.
I am looking to instantiate a MIMEText instance by:
Py... | Python 3 C API. Initialising MIMEText object fails | I am looking to embed Python into a C program. Among other things Python will look after sending email. I have no trouble using the base types from C, but I have trouble using other objects within the library.
I am looking to instantiate a MIMEText instance by:
PyObject *mimeTextModule = PyImport_ImportModule("email.mi... | [
"Returning NULL means that an exception occurred and you need to check what it is.\nIf you want to instantiate a class then you do it the same way in C as you do in Python: call it.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006547693_python.txt |
Q:
evernote api : notes in listLinkedNotebooks
with evernote python api,
I can see the shared notebooks
notebooks = noteStore.listLinkedNotebooks(authToken)
print "Found ", len(notebooks), " notebooks:"
for notebook in notebooks:
print " * ", notebook,notebook.guid
but, if I try read the note in the notebooks... | evernote api : notes in listLinkedNotebooks | with evernote python api,
I can see the shared notebooks
notebooks = noteStore.listLinkedNotebooks(authToken)
print "Found ", len(notebooks), " notebooks:"
for notebook in notebooks:
print " * ", notebook,notebook.guid
but, if I try read the note in the notebooks
notebooks = noteStore.listLinkedNotebooks(authT... | [
"Please have a look at this thread and see if it helps: http://forum.evernote.com/phpbb/viewtopic.php?f=43&t=17957\n"
] | [
1
] | [] | [] | [
"api",
"evernote",
"python"
] | stackoverflow_0006464086_api_evernote_python.txt |
Q:
why cant i change directories in python?
I'm trying to change directories in python. I first tried:
>>> os.getcwd()
and got:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
I then tried
>>> os.chir('/directory/i/want/to/change/to')
but I still got
N... | why cant i change directories in python? | I'm trying to change directories in python. I first tried:
>>> os.getcwd()
and got:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
I then tried
>>> os.chir('/directory/i/want/to/change/to')
but I still got
NameError: name 'os' is not defined
How do I d... | [
"You need to import the os module first:\nimport os\nos.getcwd()\n\n",
"import os. Perhaps you should read the tutorial?\n",
"Have you imported the os module?\nimport os\nprint(os.getcwd())\n\n",
"You need to import the package \nimport os\n\n"
] | [
22,
6,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0006549173_python.txt |
Q:
Iron python, beautiful soup, win32 app
Does beautiful soup work with iron python?
If so with which version of iron python?
How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
A:
I was asking myself this same question and after s... | Iron python, beautiful soup, win32 app | Does beautiful soup work with iron python?
If so with which version of iron python?
How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
| [
"I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there ... | [
34,
8,
5,
2,
1,
1,
1,
0
] | [
"If you have the complete standard library and the real re module (google for IronPython community edition) it might work. But IronPython is an incredible bad python implementation, I wouldn't count on that.\nBesides, give html5lib a try. That parser parses with the same rules firefox parses documents.\n"
] | [
-2
] | [
".net",
"ironpython",
"python"
] | stackoverflow_0000118654_.net_ironpython_python.txt |
Q:
Abstract class with Python 2.5
I currently refactor a class defining a client or a server. The class had a lot of
if client:
XXXXXXXXXXXX
elif server:
YYYYYYYYYYYY
So I decided to create a class A with the similar code and one class C for the client and an other one S for the server which inherit A. (they... | Abstract class with Python 2.5 | I currently refactor a class defining a client or a server. The class had a lot of
if client:
XXXXXXXXXXXX
elif server:
YYYYYYYYYYYY
So I decided to create a class A with the similar code and one class C for the client and an other one S for the server which inherit A. (they don't have theses names of course ^... | [
"This approach has the advantage that you do not need to do anything to the subclass to make it non-abstract.\nclass ABC(object):\n abstract = True\n def __new__(cls, *args, **kwargs):\n if \"abstract\" in cls.__dict__ and cls.__dict__[\"abstract\"] == True:\n raise RuntimeError(cls.__name__... | [
2,
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"refactoring"
] | stackoverflow_0006548228_python_refactoring.txt |
Q:
Python: Checking if field exists in table
How can I check if a field exists in a table. I need an if statement I believe to do this.
I don't want to insert data into the row if a field within the row contains the same data.
So for example I have a table with 6 rows. Prefix, code_id, answer, station_id, timestamp... | Python: Checking if field exists in table | How can I check if a field exists in a table. I need an if statement I believe to do this.
I don't want to insert data into the row if a field within the row contains the same data.
So for example I have a table with 6 rows. Prefix, code_id, answer, station_id, timestamp, comport.
The user will enter in the station_... | [
"If you want to see if there is data in the table already that meets the conditions, then you simply query for it:\nIn pseudo-code\nif \"select count(*) from scan where prefix = ? and code_id = ? and ...\" == 0:\n execute(\"insert into scan....\")\n\n"
] | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0006549287_mysql_python.txt |
Q:
Navigate manually with a cursor through nested lists by only providing "left()" and "right()" as commands?
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and... | Navigate manually with a cursor through nested lists by only providing "left()" and "right()" as commands? | Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class w... | [
"One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a... | [
3,
3,
1,
1
] | [] | [] | [
"navigation",
"nested_lists",
"python",
"user_interaction"
] | stackoverflow_0006548996_navigation_nested_lists_python_user_interaction.txt |
Q:
Python does not properly process text input from an HTML textarea
I have a standard form on an HTML page with the usual input types: text, select, submit. Using Python (the Pyramid framework) to process these forms has been straightforward and without issue.
In this particular form, though, I have needed to use a ... | Python does not properly process text input from an HTML textarea | I have a standard form on an HTML page with the usual input types: text, select, submit. Using Python (the Pyramid framework) to process these forms has been straightforward and without issue.
In this particular form, though, I have needed to use a textarea to accept longer, multi-line input. When processing the user ... | [
"There is no difference between a input[type=text] and a textarea when the data is submitted. The problem you describe should happen in both.\nCorrect me if I'm wrong, but WebOb, which is used in Pyramid, does the decoding for you. You get Unicode already, so there is no need to decode or encode anything. Also, you... | [
2
] | [] | [] | [
"forms",
"html",
"pyramid",
"python",
"textarea"
] | stackoverflow_0006545473_forms_html_pyramid_python_textarea.txt |
Q:
matplotlib scatter_hist with stepfilled histtype in histogram
I modified scatter_hist.py example found here to have two data sets to be plotted.
I'd like to have histograms with "stepfilled" type, but somehow if I set the type "stepfilled" the Y-axis histogram (orientation = "horizontal") is not working.
Is there... | matplotlib scatter_hist with stepfilled histtype in histogram | I modified scatter_hist.py example found here to have two data sets to be plotted.
I'd like to have histograms with "stepfilled" type, but somehow if I set the type "stepfilled" the Y-axis histogram (orientation = "horizontal") is not working.
Is there any other way to do the histogram to look like "stepfilled"-style ... | [
"The documentation only mentions special cases for multiple data when using 'bar' and 'barstacked', which I would assume means that this isn't properly implemented for the other two types. Changing your code to add multiple histograms instead of just one worked for me:\nhisttype = \"stepfilled\"\nfor i in xrange(le... | [
2
] | [] | [] | [
"histogram",
"matplotlib",
"python"
] | stackoverflow_0006508769_histogram_matplotlib_python.txt |
Q:
Create numpy array from C-ptr aquired via ctypes
I have allocated a chunk of double in a C library and I would like to create a numpy 1D array based on that data; ideally I would like two versions one which only wraps the c_ptr readonly - letting the C layer retain ownership of the data, and one which copies the d... | Create numpy array from C-ptr aquired via ctypes | I have allocated a chunk of double in a C library and I would like to create a numpy 1D array based on that data; ideally I would like two versions one which only wraps the c_ptr readonly - letting the C layer retain ownership of the data, and one which copies the data. So simplified code would be like this:
C-code
d... | [
"Yes, numpy.ctypeslib.as_array\nTo get a given dtype, as_array(ptr, shape).view(dtype).\nThis should work, at least in theory (don't have time to test it now).\n"
] | [
2
] | [] | [] | [
"ctypes",
"numpy",
"python"
] | stackoverflow_0006545824_ctypes_numpy_python.txt |
Q:
Need a python script to search specific keywords in a collection of sql files returning the index of where each keyword was found
I'm extremely new to python and I was just wondering how could I take a collection of files (sql), and using some specific keywords, find which line of code they are matched throughout ... | Need a python script to search specific keywords in a collection of sql files returning the index of where each keyword was found | I'm extremely new to python and I was just wondering how could I take a collection of files (sql), and using some specific keywords, find which line of code they are matched throughout all the files. Any notions, ideas or suggestions would be life savingly helpful.
Kind Regards
Tiago M
| [
"Solution\ns = 'somestring'\nnames = ['file1.sql', 'file2.sql']\nfor n in names: \n f = open(n)\n lines = f.readlines()\n for i, l in enumerate(lines):\n if s in l:\n print 'line %d' % (i)\n\n",
"You want to look at the os.walk function then open each file and use in, string.find, or r... | [
2,
1
] | [] | [] | [
"python",
"search",
"sql"
] | stackoverflow_0006550105_python_search_sql.txt |
Q:
Python command to get last part file
I have .dat file look like:
STEP1
a1 b1
a2 b2
a3 b3
STEP2
a4 b4
a5 b5
.
.
.
STEPn
an bn
am bm
Each step has two column (a and b). I need a scrip, which looks last step and gives me "an" and "am"
Thank you for the help!
A:
Something efficient, that even works wi... | Python command to get last part file | I have .dat file look like:
STEP1
a1 b1
a2 b2
a3 b3
STEP2
a4 b4
a5 b5
.
.
.
STEPn
an bn
am bm
Each step has two column (a and b). I need a scrip, which looks last step and gives me "an" and "am"
Thank you for the help!
| [
"Something efficient, that even works with very long files (uses almost no memory):\nwith open(\"data.dat\") as f: # File automatically closed\n for line in f: # Goes through all the line (no need to store them)\n pass\nstep, an, bn, am, bm = line.split() # Splits the last line read (on spaces)\n\nIf y... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006550274_python.txt |
Q:
Erratic problem with App Engine when writing files directly to the blobstore
I'm using App Engine with Python. In order to store the images of my users, I write them directly to the blobstore as indicated in Google documentation.
My code is below:
# Image insertion in the blobstore
file_name = files.blobstore.crea... | Erratic problem with App Engine when writing files directly to the blobstore | I'm using App Engine with Python. In order to store the images of my users, I write them directly to the blobstore as indicated in Google documentation.
My code is below:
# Image insertion in the blobstore
file_name = files.blobstore.create(mime_type='image/jpeg')
with files.open(file_name, 'a') as f:
f.write(self.... | [
"I finally managed to solve this problem by making the thread sleep during intervals of 50ms\nThis is the code I added:\n# Sometimes blobKey is None\nself.blobKey = files.blobstore.get_blob_key(file_name)\n\n# We have to make it wait til it works!\nfor i in range(1,3):\n if(self.blobKey):\n break\n el... | [
3
] | [] | [] | [
"blobstore",
"google_app_engine",
"image",
"python"
] | stackoverflow_0006545247_blobstore_google_app_engine_image_python.txt |
Q:
Python: Regex and String Length in byte
I am writing a program in python and have some question (I am 100% new to python):
import re
rawData = '7I+8I-7I-9I-8I-'
print len(rawData)
rawData = re.sub("[0-9]I\+","",rawData)
rawData = re.sub("[0-9]I\-","",rawData)
print rawData
How to merge the 2 regex into one us... | Python: Regex and String Length in byte | I am writing a program in python and have some question (I am 100% new to python):
import re
rawData = '7I+8I-7I-9I-8I-'
print len(rawData)
rawData = re.sub("[0-9]I\+","",rawData)
rawData = re.sub("[0-9]I\-","",rawData)
print rawData
How to merge the 2 regex into one using |? It means it will get rid of both 9I- ... | [
"See the difference:\n$ python3\nPython 3.1.3 (r313:86834, May 20 2011, 06:10:42) \n[GCC 4.4.5] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> len('día') # Unicode text\n3\n>>> \n\n$ python\nPython 2.7.1 (r271:86832, May 20 2011, 17:19:04) \n[GCC 4.4.5] on linux2\nT... | [
5,
0,
0
] | [] | [] | [
"python",
"regex",
"string_length"
] | stackoverflow_0006550230_python_regex_string_length.txt |
Q:
Amazon Elastic MapReduce - Format or Examples for python map and reduce code
Maybe it is the same has Hadoop but I just couldn't find what is the format or example of writing the map and reduce python code beside map example here: http://docs.amazonwebservices.com/ElasticMapReduce/latest/GettingStartedGuide/
but I... | Amazon Elastic MapReduce - Format or Examples for python map and reduce code | Maybe it is the same has Hadoop but I just couldn't find what is the format or example of writing the map and reduce python code beside map example here: http://docs.amazonwebservices.com/ElasticMapReduce/latest/GettingStartedGuide/
but I couldn't find reduce code example,
is it the same as Hadoop?
and what is the form... | [
"EMR streaming is no different to general Hadoop streaming.\nHere's an example of a python reducer\nhttp://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/#reduce-reducer-py\n"
] | [
5
] | [] | [] | [
"amazon_emr",
"elastic_map_reduce",
"hadoop",
"mapreduce",
"python"
] | stackoverflow_0006526529_amazon_emr_elastic_map_reduce_hadoop_mapreduce_python.txt |
Q:
Unicode HTML Conversion to ASCII in Python
Possible Duplicate:
Unescaping Characters in a String with Python
I have a string of unicode HTML in Python which begins with: \u003ctable>\u003ctr
I need to convert this to ascii so I can then parse it with BeautifulSoup. However, Python's encode and decode functions s... | Unicode HTML Conversion to ASCII in Python |
Possible Duplicate:
Unescaping Characters in a String with Python
I have a string of unicode HTML in Python which begins with: \u003ctable>\u003ctr
I need to convert this to ascii so I can then parse it with BeautifulSoup. However, Python's encode and decode functions seem to have no effect; I get the original strin... | [
"Use \ns.decode(\"unicode-escape\")\n\nto decode the html data first (no idea how you get this character crap from).\n"
] | [
3
] | [
"I have no clue what you're talking about. I suspect that I'm not the only one.\n>>> s = BeautifulSoup.BeautifulSoup(u'<html><body>\\u003ctable>\\u003ctr</body></html>')\n>>> s\n<html><body><table><tr></tr></table></body></html>\n\n"
] | [
-1
] | [
"ascii",
"python",
"unicode"
] | stackoverflow_0006550953_ascii_python_unicode.txt |
Q:
Python : run multiple queries in parallel and get the first finished
I try to create a Python script that performs queries to multiple sites. The script works well (I use urllib2) but just for one link. For multiples sites, I make multiple requests one after the other but it is not very powerful.
What is the ideal... | Python : run multiple queries in parallel and get the first finished | I try to create a Python script that performs queries to multiple sites. The script works well (I use urllib2) but just for one link. For multiples sites, I make multiple requests one after the other but it is not very powerful.
What is the ideal solution (the threads I guess) to run multiple queries in parallel and st... | [
"You can use Twisted to deal with multiple requests concurrently. Internally it will use epoll (or iocp or kqueue depending on the platform) to get notified of tcp availability efficently, which is cheaper than using threads. Once one request matches, you cancel the others.\nHere is the Twisted http agent tutorial.... | [
2,
0,
0
] | [] | [] | [
"multithreading",
"python",
"urllib2"
] | stackoverflow_0006549601_multithreading_python_urllib2.txt |
Q:
Polar contour plot in Matplotlib
I have a set of data that I want to use to produce a contour plot in polar co-ordinates using Matplotlib.
My data is the following:
theta - 1D array of angle values
radius - 1D array of radius values
value - 1D array of values that I want to use for the contours
These are all 1D ... | Polar contour plot in Matplotlib | I have a set of data that I want to use to produce a contour plot in polar co-ordinates using Matplotlib.
My data is the following:
theta - 1D array of angle values
radius - 1D array of radius values
value - 1D array of values that I want to use for the contours
These are all 1D arrays that align properly - eg:
theta... | [
"Matplotlib's contour() function expects data to be arranged as a 2D grid of points and corresponding grid of values for each of those grid points. If your data is naturally arranged in a grid you can convert r, theta to x, y and use contour(r*np.cos(theta), r*np.sin(theta), values) to make your plot.\nIf your dat... | [
8,
3
] | [] | [] | [
"graphing",
"matplotlib",
"python"
] | stackoverflow_0006548556_graphing_matplotlib_python.txt |
Q:
Inserting two enties in a transaction & getting 'Cannot operate on different entity groups in a transaction' Error
My end goal is simple. I need to have an entity that has two, unique, indexed fields that can operate like keys. If this was a SQL database, the equivelant would be having two fields that are define... | Inserting two enties in a transaction & getting 'Cannot operate on different entity groups in a transaction' Error | My end goal is simple. I need to have an entity that has two, unique, indexed fields that can operate like keys. If this was a SQL database, the equivelant would be having two fields that are defined as both unique and are independant of one another. I know this functionality isn't directly possible for one data sto... | [
"I've fixed this problem but it the solution is unrelated to the setup mentioned above. As I had previously stated, my actual class contains some validation code within the InsertData method. Portions of the Validation logic were taking place in the txn() method. I assumed that this wouldn't be a problem because... | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"transactions"
] | stackoverflow_0006550029_google_app_engine_google_cloud_datastore_python_transactions.txt |
Q:
Detect argument passing convention of a C library function
With pure Python functions you can pass arguments either by order (e.g. foo(1, 2, 3)) or by name (e.g. foo(a=1, c=3, b=2)).
Functions defined in C modules can use either convention. You cannot say range(stop=10, step=2), and so it is with most but not all ... | Detect argument passing convention of a C library function | With pure Python functions you can pass arguments either by order (e.g. foo(1, 2, 3)) or by name (e.g. foo(a=1, c=3, b=2)).
Functions defined in C modules can use either convention. You cannot say range(stop=10, step=2), and so it is with most but not all functions implemented using C interface.
Is there a way to deter... | [
"It appears to be an open bug: there is simply no way to tell this. Also, the issue is implementation-dependent: your code might work in (for example) PyPy, though I can't confirm this.\nThe devs on the bug page aren't sure whether to change the documentation style or the implementation, but I get the impression i... | [
4
] | [] | [] | [
"cpython",
"python"
] | stackoverflow_0006551468_cpython_python.txt |
Q:
Appending strings to a list
Novice question here.
I'm working on finding every single combination of various string elements, and then want to place them into a list.
import itertools
mydata = [ ]
main = [["car insurance", "auto insurance"], ["insurance"], ["cheap", "budget"],
["low cost"], ["quote", "quo... | Appending strings to a list | Novice question here.
I'm working on finding every single combination of various string elements, and then want to place them into a list.
import itertools
mydata = [ ]
main = [["car insurance", "auto insurance"], ["insurance"], ["cheap", "budget"],
["low cost"], ["quote", "quotes"], ["rate", "rates"], ["compa... | [
"To get the return values of twofunc and threefunc into a list, you can change the return statements so that lists are returned. Then append the result to mydata. An example follows for twofunc:\ndef twofunc(one, two):\n for a, b in itertools.product(main[one], main[two]):\n return [a, b]\n\nmydata.appe... | [
2,
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006550728_python_string.txt |
Q:
parsing xpath expressions
I want to parse XPath expressions
I an looking for a lexer/parser implementation in C++ or Python
Here is all the information about XPath parsers I manage to gather :
ANTLR grammar for XPath 1 & 2 ( from Parse XPath Expressions )
the Python parser & lexer from PDIS
several python impleme... | parsing xpath expressions | I want to parse XPath expressions
I an looking for a lexer/parser implementation in C++ or Python
Here is all the information about XPath parsers I manage to gather :
ANTLR grammar for XPath 1 & 2 ( from Parse XPath Expressions )
the Python parser & lexer from PDIS
several python implementations from Towards a Standar... | [
"Based on a comment by OP, \n\nI am working on XPath queries rewriting and equivalence\n\nwhat he needs is a parser that builds abstract syntax trees, and ways to analyze those trees and transform them. Analyzers and \"rewriting\" can then be done procedurally by walking/modifying the AST; this is the traditional... | [
2,
0,
0
] | [] | [] | [
"c++",
"lexer",
"parsing",
"python",
"xpath"
] | stackoverflow_0006513044_c++_lexer_parsing_python_xpath.txt |
Q:
lxml - parse an xml with no line breaks in it
I am using lxml iterparse in python to loop through the elements in my xml file. It works fine with most of the xmls, but fails for some. One of them has no line breaks in it. The error and a sample of such xml are as below. Any clues?
Thanks!!
<root><person><name>"xyz... | lxml - parse an xml with no line breaks in it | I am using lxml iterparse in python to loop through the elements in my xml file. It works fine with most of the xmls, but fails for some. One of them has no line breaks in it. The error and a sample of such xml are as below. Any clues?
Thanks!!
<root><person><name>"xyz"</name><age>"10"</age></person><person><name>"abc"... | [
"etree.iterparse expects buffer for source argument. And name of variable you passing, \"fullFilePath\", tells me that it's not file (So parser is trying to parse file_path insted of file content ).\nTry passing opened file instead.\ncontext=etree.iterparse(open(fullFilePath), events=(\"start\",\"end\")) \n\nor s... | [
2
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0006551498_lxml_python.txt |
Q:
biopython import in Enthought Python Distribution?
I am using the Enthought Python Distribution v7.0-2 (32-bit) and I am having trouble importing biopython. Does anyone know how to import biopython in EPD? I can import other libraries like numpy, matplotlib, etc. with no problem, but import biopython is not recogn... | biopython import in Enthought Python Distribution? | I am using the Enthought Python Distribution v7.0-2 (32-bit) and I am having trouble importing biopython. Does anyone know how to import biopython in EPD? I can import other libraries like numpy, matplotlib, etc. with no problem, but import biopython is not recognized. What's going on?
Thanks in advance for the help.
| [
"You want:\nimport Bio\n\nThe tutorial documentation is a good place to get started learning about Biopython:\nhttp://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc6\n"
] | [
3
] | [] | [] | [
"biopython",
"enthought",
"python"
] | stackoverflow_0006551862_biopython_enthought_python.txt |
Q:
How to decrease hatch density in matplotlib
I need to decrease the density of the hatch in a bar made with matplotlib.
The way I add the hatches:
kwargs = {'hatch':'|'}
rects2 = ax.bar(theta, day7, width,fill=False, align='edge', alpha=1, **kwargs)
kwargs = {'hatch':'-'}
rects1 = ax.bar(theta, day1, width,fill=Fa... | How to decrease hatch density in matplotlib | I need to decrease the density of the hatch in a bar made with matplotlib.
The way I add the hatches:
kwargs = {'hatch':'|'}
rects2 = ax.bar(theta, day7, width,fill=False, align='edge', alpha=1, **kwargs)
kwargs = {'hatch':'-'}
rects1 = ax.bar(theta, day1, width,fill=False, align='edge', alpha=1, **kwargs)
I know tha... | [
"This is a complete hack, but it should work for your scenario.\nBasically, you can define a new hatch pattern that becomes less dense the longer the input string. I've gone ahead and adapted the HorizontalHatch pattern for you (note the use of the underscore character):\nclass CustomHorizontalHatch(matplotlib.hatc... | [
9
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004745937_matplotlib_python.txt |
Q:
How to login to webpage with cookies and user-agent?
I am trying to log to certain server and download pictures from there programatically. I know login and I was able to get which variables are username and password. I was also able to download pictures which needed no password with this code.
Web page keeps tell... | How to login to webpage with cookies and user-agent? | I am trying to log to certain server and download pictures from there programatically. I know login and I was able to get which variables are username and password. I was also able to download pictures which needed no password with this code.
Web page keeps telling me my user agent is unsupported, so I assume I am sett... | [
"The python docs page has this format for building openers using square brackets. You are passing it as {(...)}\nimport urllib2\nopener = urllib2.build_opener()\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\nopener.open('http://www.example.com/')\n\n"
] | [
1
] | [] | [] | [
"authentication",
"cookies",
"download",
"python",
"user_agent"
] | stackoverflow_0006552063_authentication_cookies_download_python_user_agent.txt |
Q:
How to download files over HTTP via python-urllib2 correctly?
I've written parser on python to download images from Internet:
import urllib2
for i in xrange(1,10):
r = urllib2.urlopen('http://example.com/'+str(i)+'.gif'))
f = open('C:\\' + str(i) + '.gif', 'w+')
f.write(r.read())
f.close()
Images can't b... | How to download files over HTTP via python-urllib2 correctly? | I've written parser on python to download images from Internet:
import urllib2
for i in xrange(1,10):
r = urllib2.urlopen('http://example.com/'+str(i)+'.gif'))
f = open('C:\\' + str(i) + '.gif', 'w+')
f.write(r.read())
f.close()
Images can't be opened. Windows says 'Error while building image'. But I've found... | [
"When working with windows you may need to put the \"binary\" flag b in open...\nf = open(r'C:\\\\'+str(i)+'.gif','wb')\n\n",
"On Windows you need to specify 'wb', not 'w+'\n",
"You can try urllib.urlretrieve - it handles most of details by itself.\nSo your code will look like this:\nfor i in xrange(1,10):\n ... | [
13,
5,
5
] | [] | [] | [
"file",
"image",
"python"
] | stackoverflow_0006552121_file_image_python.txt |
Q:
Problem with Python CSV putting each letter in new field
I'm trying to put a list of URLs into a csv file that I'm scraping from a webpage using urllib2 and BeautifulSoup. I have tried writing the links to a csv file as unicode and also converted to utf-8. In both cases, each letter is inserted into a new field.... | Problem with Python CSV putting each letter in new field | I'm trying to put a list of URLs into a csv file that I'm scraping from a webpage using urllib2 and BeautifulSoup. I have tried writing the links to a csv file as unicode and also converted to utf-8. In both cases, each letter is inserted into a new field.
Here's my code (I've tried it at least these two ways):
f = o... | [
"From the docs: \"A row must be a sequence of strings or numbers ...\" You are passing a single string, not a sequence of strings, so it treats each letter as an item. Put your string in a list.\nSo change w.writerow(link['href']) to w.writerow([link['href']]).\nNote: A csv file with a single column looks exactly... | [
6,
2,
2
] | [] | [] | [
"beautifulsoup",
"csv",
"python"
] | stackoverflow_0006552352_beautifulsoup_csv_python.txt |
Q:
PyCharm right-click on folder -> context menu: how to change from "hold down" to "toggle"?
The latest oddity with this IDE is the default behaviour of right-clicking on a folder: it requires one to hold down the mouse button to navigate the menu, with selection occurring upon release.
Does anyone know how to chang... | PyCharm right-click on folder -> context menu: how to change from "hold down" to "toggle"? | The latest oddity with this IDE is the default behaviour of right-clicking on a folder: it requires one to hold down the mouse button to navigate the menu, with selection occurring upon release.
Does anyone know how to change this setting?
| [
"If you are on Linux and using Eclipse keymap, check this issue for a workaround.\n"
] | [
3
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0006552375_pycharm_python.txt |
Q:
Tkinter text field with limited number of availabale character
I'm working on an application to edit DNA sequences and I'd like to have a tkinter text widget in which only letters atgcATGC can be entered.
Is there any easy way to do that?
Thanks,
David
A:
You can use the validatecommand feature of the Entry widg... | Tkinter text field with limited number of availabale character | I'm working on an application to edit DNA sequences and I'd like to have a tkinter text widget in which only letters atgcATGC can be entered.
Is there any easy way to do that?
Thanks,
David
| [
"You can use the validatecommand feature of the Entry widget. The best documentation I can find is this answer to a similar question. Following that example,\nimport Tkinter as tk\n\nclass MyApp():\n def __init__(self):\n self.root = tk.Tk()\n vcmd = (self.root.register(self.validate), '%S')\n ... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006510950_python_tkinter.txt |
Q:
Is it possible to include a library like lxml without installing it?
I need to perform some xml parsing using a machine that I may not have permission to install libraries in. So is it possible to include a python library like lxml with my source?
A:
Have you tried using virtualenv? That should let you use lxm... | Is it possible to include a library like lxml without installing it? | I need to perform some xml parsing using a machine that I may not have permission to install libraries in. So is it possible to include a python library like lxml with my source?
| [
"Have you tried using virtualenv? That should let you use lxml without \"installing\" it.\n",
"Sometimes yes... you can put some libraries source code folder in your project and use it as a module, don't know if it works for lxml but for pure python libraries it works.\nAnother option is to install it \"locally... | [
4,
1,
1,
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0006550005_lxml_python.txt |
Q:
How do I run a twisted trial in Windows?
I'm new to Python, Twisted, and Trial... and for Windows users the setup process isn't very clear. Right now, I have Python 2.7 installed, along with Twisted. From the Python GUI, I can run the reactor, so I'm convinced things are set up OK. But I can't figure out how to ... | How do I run a twisted trial in Windows? | I'm new to Python, Twisted, and Trial... and for Windows users the setup process isn't very clear. Right now, I have Python 2.7 installed, along with Twisted. From the Python GUI, I can run the reactor, so I'm convinced things are set up OK. But I can't figure out how to run trial from the command line to run my unit... | [
"There's nothing terribly special about running trial on Windows. Run it like any Python script:\nC:\\Python27\\python.exe C:\\Python27\\Scripts\\trial.py [additional arguments]\n\nOr if you have .py associated with a Python interpreter already:\nC:\\Python27\\Scripts\\trial.py [additional arguments]\n\nOr if you ... | [
3
] | [] | [] | [
"installation",
"python",
"trial",
"twisted"
] | stackoverflow_0006551891_installation_python_trial_twisted.txt |
Q:
Python Parsing user defined values
I was trying to change:-
import urllib2 as urllib
... ...
file2 = urllib.urlopen(url2)
... ...
for line in file2:
indexfrom2 = line.find('Mean Temperature')
if indexfrom2 > -1:
nxtLn = file2.next()
nextLine = file2.next()
indexfrom21 = nextLine.fin... | Python Parsing user defined values | I was trying to change:-
import urllib2 as urllib
... ...
file2 = urllib.urlopen(url2)
... ...
for line in file2:
indexfrom2 = line.find('Mean Temperature')
if indexfrom2 > -1:
nxtLn = file2.next()
nextLine = file2.next()
indexfrom21 = nextLine.find('"nobr"')
if indexfrom21 > -1:... | [
"You probably want to be using BeautifulSoup for this. It's the canonical way to parse HTML (and it works pretty well even in some horrible edge cases). If you continue with your current approach, you're relying on things like line numbers and so your code is pretty brittle in the face of minor document structure c... | [
1
] | [] | [] | [
"html",
"parsing",
"python",
"url"
] | stackoverflow_0006552421_html_parsing_python_url.txt |
Q:
remove one comma using a python script
I have csv file with a line that looks something like this:
,,,,,,,,,,
That's 10 commas. I wish to remove only the last (i.e. the 10th) comma, so that the line changes to:
,,,,,,,,,
Has anyone had any experience dealing with a case like this? I use the vim text editor also.... | remove one comma using a python script | I have csv file with a line that looks something like this:
,,,,,,,,,,
That's 10 commas. I wish to remove only the last (i.e. the 10th) comma, so that the line changes to:
,,,,,,,,,
Has anyone had any experience dealing with a case like this? I use the vim text editor also. So, any help using python script or text ed... | [
"Removing last comma in current line in vim:\n:s/,$//\nThe same for lines n through m:\n:n,ms/,$//\nThe same for whole file:\n:%s/,$//\n",
"This will do it in the simplest case, once you've updated your question with what you're looking for, I'll update the code.\ncommas = \",,,,,,,,,,,\"\nprint commas.replace(\"... | [
10,
3,
2,
1
] | [] | [] | [
"csv",
"python",
"vim"
] | stackoverflow_0006508254_csv_python_vim.txt |
Q:
Numpy Index values for each element in 3D array
I have a 3D array created using the numpy mgrid command so that each element has a certain value and the indexes retain the spatial information. For example, if one summed over the z-axis (3rd dimension) then the the resultant 2D array could be used in matplotlib wit... | Numpy Index values for each element in 3D array | I have a 3D array created using the numpy mgrid command so that each element has a certain value and the indexes retain the spatial information. For example, if one summed over the z-axis (3rd dimension) then the the resultant 2D array could be used in matplotlib with the function imshow() to obtain an image with diffe... | [
"I'm not exactly clear on your meaning, but if you are looking for 3d arrays that contain the indices x, y, and z, then the following may suit your needs; assume your data is held in a 3D array called \"abc\":\nimport numpy as nm\nx,y,z = nm.mgrid[[slice(dm) for dm in abc.shape]]\n\n"
] | [
1
] | [] | [] | [
"arrays",
"element",
"indexing",
"numpy",
"python"
] | stackoverflow_0006551666_arrays_element_indexing_numpy_python.txt |
Q:
How do I remove an extra square bracket from JSON in Python?
I have JSON of the following form:
{"blah":
[
[
{"first":
{"something":"that","something":"else","another":"thing","key":"value"}...[etc.]
}
]
]
}
that I'm trying to parse in Python. I've imported json (or simplejson, depending on... | How do I remove an extra square bracket from JSON in Python? | I have JSON of the following form:
{"blah":
[
[
{"first":
{"something":"that","something":"else","another":"thing","key":"value"}...[etc.]
}
]
]
}
that I'm trying to parse in Python. I've imported json (or simplejson, depending on what version of Python you're using) and everything goes pretty w... | [
"If there's always exactly one \"extra\" set of array brackets:\nfor result in page['blah']:\n that = result[0]['this']\n list.append(that)\n\n",
"There is not need to remove the brackets from the JSON string. I think making sure to remove only the rights is not worth the effort. Just figure out the right w... | [
1,
0,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0006551524_json_python.txt |
Q:
On keystroke insert line of code in (mac)vim, for pdb
I'm looking for the way to insert a line of code with a keystroke like leaderp in Macvim
I want to insert the following line of code:
import pdb; pdb.set_trace()
Probably not an unheard of line of code in python land
A:
I'd use a simple mapping (without func... | On keystroke insert line of code in (mac)vim, for pdb | I'm looking for the way to insert a line of code with a keystroke like leaderp in Macvim
I want to insert the following line of code:
import pdb; pdb.set_trace()
Probably not an unheard of line of code in python land
| [
"I'd use a simple mapping (without functions) to leader p:\nnnoremap <leader>p oimport pdb; pdb.set_trace()<Esc>\n\nWhen pressing o, this enters insert mode inserts a blank line after the current one (with o) and then types import pdb; pdb.set_trace(), finally it goes back to normal mode (with Esq).\n\nIf you want ... | [
12,
6,
5,
2
] | [] | [] | [
"macvim",
"pdb",
"python",
"vim"
] | stackoverflow_0006547680_macvim_pdb_python_vim.txt |
Q:
Comparing keywords in a page or CSV file: PHP ? Bash?
I have a series of keywords in an HTML web page - they are comma separated so I could get them to CSV, and would like to know which ones are NOTin another CSV file displayed as an html web page.
How would you do that comparison ? I have ideas for mysql and tabl... | Comparing keywords in a page or CSV file: PHP ? Bash? | I have a series of keywords in an HTML web page - they are comma separated so I could get them to CSV, and would like to know which ones are NOTin another CSV file displayed as an html web page.
How would you do that comparison ? I have ideas for mysql and tables but this is CSV or html sources.
Thanks !
| [
"If it is just a list of keywords, you want to do a search and replace (you can use sed) to replace all the commas with carriage returns. So you will end up with a file containing one keyword on each line. Do that to both versions of the list. Then use the \"join\" command:\njoin -v 1 leftfile rightfile\n\nThis ... | [
1,
1,
1
] | [] | [] | [
"bash",
"logic",
"php",
"python"
] | stackoverflow_0006552076_bash_logic_php_python.txt |
Q:
CherryPy Custom Tool for user authentication
I'm trying to set up a simple way of decorating methods in my CherryPy controller classes so that a user is redirected to the login page if they haven't authenticated yet. I was going to do a basic Python decorator, but an answer here suggested I use a CherryPy Custom ... | CherryPy Custom Tool for user authentication | I'm trying to set up a simple way of decorating methods in my CherryPy controller classes so that a user is redirected to the login page if they haven't authenticated yet. I was going to do a basic Python decorator, but an answer here suggested I use a CherryPy Custom Tool instead. So I'm trying to do that, but I can... | [
"I was using the wrong hook. Changing:\ncherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)\n\nTo:\ncherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)\n\nFixed the problem. Apparently my authenticate method was getting called before sessions had been turned on, ... | [
5,
0
] | [] | [] | [
"authentication",
"cherrypy",
"custom_tools",
"python",
"session"
] | stackoverflow_0006552025_authentication_cherrypy_custom_tools_python_session.txt |
Q:
Saving temporary files with CGI (Ubuntu)
I am a postdoc and I just finished a cool little scientific application in Python and want to share it with the world. It's a really useful tool for genetecists.
I'd really like to let people run this program through a CGI form interface. Since I'm not a student anymore, I... | Saving temporary files with CGI (Ubuntu) | I am a postdoc and I just finished a cool little scientific application in Python and want to share it with the world. It's a really useful tool for genetecists.
I'd really like to let people run this program through a CGI form interface. Since I'm not a student anymore, I no longer have webspace with a tidy little cg... | [
"Well, the \"right\" way is probably to re-work things using an existing web framework like Django. It's probably overkill in this case. Don't underestimate the security aspects here. They're probably more relevant than you think.\nAll that said, you probably want to use Python's temp file module from the standard ... | [
3,
1
] | [] | [] | [
"cgi",
"python",
"ubuntu"
] | stackoverflow_0006552777_cgi_python_ubuntu.txt |
Q:
Python: Are `hash` values for built-in numeric types, strings standardised?
I came to this question while pondering about the ordering of set, frozenset and dict. Python doesn't guarantee any ordering, and any ordering is coupled to the hash value at some level. But is the hash value for a value of a numeric or st... | Python: Are `hash` values for built-in numeric types, strings standardised? | I came to this question while pondering about the ordering of set, frozenset and dict. Python doesn't guarantee any ordering, and any ordering is coupled to the hash value at some level. But is the hash value for a value of a numeric or string built-in type standardized? In other words, would
hash((a,b,c,d,e,f,g))
ha... | [
"The hash values for strings and integers are absolutely not standardized. They could change with any new implementation of Python, including between 2.6.1 and 2.6.2, or between a Mac and a PC implementation of the same version, etc.\nMore importantly, though, stable hash values doesn't imply repeatable iteration ... | [
10,
4,
2
] | [
"AFAIK, the result of __hash__() should always the unique for that object. In the case of integers, the hash is the value itself.\nAccording to the documentation:\n\nobject.hash(self)\nCalled by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. hash() s... | [
-1,
-2
] | [
"python"
] | stackoverflow_0006550660_python.txt |
Q:
How to delete an object and all related objects with all imageFields insite them (photo gallery)
I have a photo gallery with an album model (just title and date and stuff) and a photo model with a foriegn key to the album and three imageFields in it (regular, mid and thumb).
When a user delete an album i need to d... | How to delete an object and all related objects with all imageFields insite them (photo gallery) | I have a photo gallery with an album model (just title and date and stuff) and a photo model with a foriegn key to the album and three imageFields in it (regular, mid and thumb).
When a user delete an album i need to delete all the photos reletaed to the album (from server) then all the DB records that point to the alb... | [
"Here is a possible answer for the question i figured out:\n\nGetting the list of albums in a string, in my case separated by commas \nYou need to import shutil, then:\n@login_required\ndef remove_albums(request):\n if request.is_ajax():\n if request.method == 'POST':\n #if the ajax call for de... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0006550003_django_django_models_django_views_python.txt |
Q:
Import a module into a module, can't explain what i'm trying to do
So, the following is an example. Here's a module (called feedy.py) in let's say, the core directory:
import feedparser
feed = feedparser.parse("http://site.com/feed")
[...]
A bad example, but anyway: my problem is in the main script (parent dir),... | Import a module into a module, can't explain what i'm trying to do | So, the following is an example. Here's a module (called feedy.py) in let's say, the core directory:
import feedparser
feed = feedparser.parse("http://site.com/feed")
[...]
A bad example, but anyway: my problem is in the main script (parent dir), I have to do
import feedparser
as well as
from core import feedy
Howe... | [
"In principle, yes. However, it's not usually a good idea.\nWhen you import a module, you effectively declare a local variable which is a reference to that module. So in feedy you have an object called feedparser, which happens to be the module feedparser, although you could at any time reassign it to be any other... | [
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0006553370_import_module_python.txt |
Q:
Multiple subprocesses with timeouts
I'm using a recipe that relies on SIGALRM to set alarm interrupt --
Using module 'subprocess' with timeout
The problem is that I have more than one Python script using signal.ALARM process to set time-outs, and only the latest alarm gets called. What is a good way to improve thi... | Multiple subprocesses with timeouts | I'm using a recipe that relies on SIGALRM to set alarm interrupt --
Using module 'subprocess' with timeout
The problem is that I have more than one Python script using signal.ALARM process to set time-outs, and only the latest alarm gets called. What is a good way to improve this multiple Python functions setting time-... | [
"Except for simple, quick hacks, avoid SIGALRM. It's a very old, limited mechanism, not suited to anything more complex: you can only set a single alarm, and it interrupts any system call at the time rather than just the one you intend to interrupt.\nIt's much cleaner to use a timeout thread to kill the process, f... | [
11
] | [] | [] | [
"python",
"signals"
] | stackoverflow_0006553423_python_signals.txt |
Q:
Re-install Python 2.6 on Mac OS X 10.6
Quite a while back I deleted the 2.6 directory that contained the built in Mac OS X Python install, and now I am in need of having it back. How might one go about re-compiling and installing Python to the original location?
Solutions like Fink, brew, and MacPorts are all thin... | Re-install Python 2.6 on Mac OS X 10.6 | Quite a while back I deleted the 2.6 directory that contained the built in Mac OS X Python install, and now I am in need of having it back. How might one go about re-compiling and installing Python to the original location?
Solutions like Fink, brew, and MacPorts are all things I'm aware of, but if they are capable of ... | [
"The simplest solution is to reinstall OS X 10.6 over your existing installation. As noted in the comments, it's not practical to build an exact duplicate of the Apple-supplied system Python because of the numerous Apple tweeks although many of them are published by Apple here (you can drill down to a particular O... | [
4
] | [] | [] | [
"build",
"compilation",
"macos",
"python"
] | stackoverflow_0006501941_build_compilation_macos_python.txt |
Q:
How can I convert every pixel that is not black to a certain color?
I want every pixel that is not black to be set to white (or any arbitrary color).
I need this in Python (preferably using PIL, but other libraries can also be considered)
Thanks
A:
Try this:
import sys
from PIL import Image
imin = Image.open(... | How can I convert every pixel that is not black to a certain color? | I want every pixel that is not black to be set to white (or any arbitrary color).
I need this in Python (preferably using PIL, but other libraries can also be considered)
Thanks
| [
"Try this:\nimport sys\n\nfrom PIL import Image\n\nimin = Image.open(sys.argv[1])\nimout = Image.new(\"RGB\", imin.size)\n\nimout.putdata(map(\n lambda pixel: (0,0,0) if pixel == (0,0,0) else (255,255,255),\n imin.getdata()\n )\n ) \n\nimout.save(sys.arg... | [
3,
3,
1
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0006553399_image_processing_python_python_imaging_library.txt |
Q:
Quick debugging question [Python, pygame]
It's still an incomplete program, but for some reason the value of the textbox doesn't increase when it should... Why is this??
When the Pizza sprite overlaps with the Pan sprite, the score in the textbox is supposed to increase in value by 10. Why does this not occur?
Tha... | Quick debugging question [Python, pygame] | It's still an incomplete program, but for some reason the value of the textbox doesn't increase when it should... Why is this??
When the Pizza sprite overlaps with the Pan sprite, the score in the textbox is supposed to increase in value by 10. Why does this not occur?
Thanks!
'''
Created on Jul 1, 2011
@author: *... | [
"The textbox takes a value that is a string. When you create the textbox, you create a string from the current value of score, and set the text to that string. No lasting connection between score and textbox is made.\nThe textbox probably has a method available to update its text; call that method with the value st... | [
5
] | [] | [] | [
"debugging",
"livewires",
"pygame",
"python"
] | stackoverflow_0006553728_debugging_livewires_pygame_python.txt |
Q:
Python module for ganglia - precision number being rounded by gmond
I've written a python module for ganglia that is returning response times. The raw times look like this:
0.0120489597321
I parse this with my python module and return the time as such:
return int(response_time)
If I run the script with python, i... | Python module for ganglia - precision number being rounded by gmond | I've written a python module for ganglia that is returning response times. The raw times look like this:
0.0120489597321
I parse this with my python module and return the time as such:
return int(response_time)
If I run the script with python, it works fine:
[ DEBUG ]: returning: 0.0120489597321
However, gmond (gang... | [
"I'm not sure what you're trying to do here. int(response_time) will return an integer, int(0.0120489597321) is 0.\n",
"You can try to multiply that number by 10^6 before reporting to ganglia and then set the ganglia RRA to divide it by 10^6 before graphing.\n"
] | [
1,
0
] | [] | [] | [
"ganglia",
"int",
"precision",
"python"
] | stackoverflow_0006553358_ganglia_int_precision_python.txt |
Q:
python md5, d.update(strParam).hexdigest() returns NoneType.=, why?
>>> d = md5.new()
>>> d.update('a').hexdigest()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'hexdigest'
this would work -
>>> d = md5.new()
>>> d.update(... | python md5, d.update(strParam).hexdigest() returns NoneType.=, why? | >>> d = md5.new()
>>> d.update('a').hexdigest()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'hexdigest'
this would work -
>>> d = md5.new()
>>> d.update('a')
>>> d.hexdigest()
'0cc175b9c0f1b6a831c399e269772661'
is there an ex... | [
"You can just do:\nmd5.new('a').hexdigest()\n\nParaphrased from the documentation: \n\nnew(arg) returns a new md5 object. If arg\n is present, the method call\n update(arg) is made.\n\n\nBut md5 is deprecated.\nUse hashlib instead.\nEdit:\nThere are also issues with md5 so depending on your purposes you might wan... | [
6,
4,
2
] | [] | [] | [
"md5",
"python"
] | stackoverflow_0006553809_md5_python.txt |
Q:
Alice vs Python for someone with zero experience
My brother would like to learn some programming to find out if he'd enjoy doing it. He's 16 and doesn't know much about computers in general and knows nothing about programming in particular.
I'm thinking about picking either Alice or Python. I see Think Python is t... | Alice vs Python for someone with zero experience | My brother would like to learn some programming to find out if he'd enjoy doing it. He's 16 and doesn't know much about computers in general and knows nothing about programming in particular.
I'm thinking about picking either Alice or Python. I see Think Python is the often recommended read, but isn't it a bit too much... | [
"The advantage of Python is that - should he be bitten by the bug - there's massive a community and lots of resources to drawn on and explore.\nIf he's not bitten by Python, then programming might be a hard sell anyway, so I don't see the advantage of starting on logo-likes, even 3D ones like Alice. Alice can of c... | [
5,
4,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"alice",
"python"
] | stackoverflow_0001182650_alice_python.txt |
Q:
Understanding resource and context in Pyramid
Please bear with me, since I am just getting started with Pyramid. I am having trouble understanding context and resource in Pyramid, with regards to URL Dispatch. I'm not quite sure what it means from the description in the documentation, context and resource is somew... | Understanding resource and context in Pyramid | Please bear with me, since I am just getting started with Pyramid. I am having trouble understanding context and resource in Pyramid, with regards to URL Dispatch. I'm not quite sure what it means from the description in the documentation, context and resource is somewhat circular (to me).
What is a resource in pyrami... | [
"First of all, the main reason that you would want to even care about this stuff when using URL Dispatch is for the purposes of using pyramid's auth system. If you don't care about that, then you can completely ignore contexts and resource trees and go on with dispatch.\nResource Trees\nPyramid has a unique concept... | [
14,
0
] | [] | [] | [
"pyramid",
"python",
"resources",
"url_routing"
] | stackoverflow_0006363273_pyramid_python_resources_url_routing.txt |
Q:
Embedding Python in C++ libraries
I'm working on embedding Python in some C++ code, but I'm getting stuck compiling it.
For a header file, I have
#include <Python.h>
I would initial try,
$g++ EmbeddedPython.cpp
but would end up getting
EmbeddedPython.cpp:1:20: error: Python.h: No such file or directory
EmbeddedP... | Embedding Python in C++ libraries | I'm working on embedding Python in some C++ code, but I'm getting stuck compiling it.
For a header file, I have
#include <Python.h>
I would initial try,
$g++ EmbeddedPython.cpp
but would end up getting
EmbeddedPython.cpp:1:20: error: Python.h: No such file or directory
EmbeddedPython.cpp: In function ‘int main(int, c... | [
"You need to link against libpython. UNIX programmers do this with \"-lpython\" in the link command (ie at the end of that \"g++\" command). On a Mac, I think it would be \"-framework Python\".\n"
] | [
5
] | [] | [] | [
"c++",
"embedding",
"linker",
"python"
] | stackoverflow_0006553975_c++_embedding_linker_python.txt |
Q:
Data structure that is partially filesystem-backed?
Is there an existing (Python) implementation of a hash-like data structure that exists partially on disk? Or, can persist specific keys to some secondary storage, based on some criteria (like last-accessed-time)?
ex: "data at key K has not been accessed in M m... | Data structure that is partially filesystem-backed? | Is there an existing (Python) implementation of a hash-like data structure that exists partially on disk? Or, can persist specific keys to some secondary storage, based on some criteria (like last-accessed-time)?
ex: "data at key K has not been accessed in M milliseconds; serialize it to persistent storage (disk?), ... | [
"Go for SQLITE. A big problem that you will face down the road is concurrency/file corruption, etc and SQLite makes these very easy to avoid as it provides transactional integrity. Just define a single table with schema (primary key string key, string value). SQLite is insanely fast, especially if you wrap bunches ... | [
2,
1
] | [] | [] | [
"data_structures",
"persistence",
"python"
] | stackoverflow_0006553972_data_structures_persistence_python.txt |
Q:
Is it possible to make python print a specified string if it get an error?
What I mean is, if for example I get an error like
Traceback (most recent call last):
File "score_keeper-test.py", line 106, in <module>
app = program()
File "score_keeper-test.py", line 37, in __init__
self.label1.set_text(tea... | Is it possible to make python print a specified string if it get an error? | What I mean is, if for example I get an error like
Traceback (most recent call last):
File "score_keeper-test.py", line 106, in <module>
app = program()
File "score_keeper-test.py", line 37, in __init__
self.label1.set_text(team1_name)
TypeError: Gtk.Label.set_text() argument 1 must be string, not None
Is... | [
"The Pythonic idiom is EAFP: easier to ask for forgiveness than permission. In this case:\ntry:\n self.label1.set_text(team1_name)\nexcept TypeError:\n print \"You MUST enter a name in the TWO boxes\"\n\nNote how I explicitly catch TypeError. This is recommended by PEP 8 -- Style Guide for Python Code (essent... | [
9,
2
] | [] | [] | [
"python"
] | stackoverflow_0006554244_python.txt |
Q:
What does << do in Python?
I solved a problem on Project Euler but it took about 4 minutes to run, which is above the recommended time, so I was looking through the different solutions in the forum. One of them included the symbol << in a list comprehension. This is what it looked like
blist.extend([(i << 1) + 3... | What does << do in Python? | I solved a problem on Project Euler but it took about 4 minutes to run, which is above the recommended time, so I was looking through the different solutions in the forum. One of them included the symbol << in a list comprehension. This is what it looked like
blist.extend([(i << 1) + 3 for i in range(num) if alist.ge... | [
"It's a bit shift operator (Python docs), and is common among many programming languages, such as C, Java, PHP, etc. According to the Python docs:\n\nThey shift the first argument to the\n left or right by the number of bits\n given by the second argument.\nA right shift by n bits is defined as\n division by po... | [
10,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006554415_python.txt |
Q:
Getting HTML with Pycurl
I've been trying to retrieve a page of HTML using pycurl, so I can then parse it for relevant information using str.split and some for loops. I know Pycurl retrieves the HTML, since it prints it to the terminal, however, if I try to do something like
html = str(c.perform())
The variable... | Getting HTML with Pycurl | I've been trying to retrieve a page of HTML using pycurl, so I can then parse it for relevant information using str.split and some for loops. I know Pycurl retrieves the HTML, since it prints it to the terminal, however, if I try to do something like
html = str(c.perform())
The variable will just hold a string which... | [
"this will send a request and store/print the response body:\nfrom StringIO import StringIO \nimport pycurl\n\nurl = 'http://www.google.com/'\n\nstorage = StringIO()\nc = pycurl.Curl()\nc.setopt(c.URL, url)\nc.setopt(c.WRITEFUNCTION, storage.write)\nc.perform()\nc.close()\ncontent = storage.getvalue()\nprint con... | [
21,
6
] | [] | [] | [
"pycurl",
"python"
] | stackoverflow_0006554386_pycurl_python.txt |
Q:
Loading SQLite3 values into Python variables
I have a project built in Python 2.7, using SQLite3 as the database. I need to know how to load an item from a particular row and column into an existing Python variable.
TY!
A:
Here are the basic steps:
import sqlite3
conn = sqlite3.connect(':memory:')
curs = conn.cu... | Loading SQLite3 values into Python variables | I have a project built in Python 2.7, using SQLite3 as the database. I need to know how to load an item from a particular row and column into an existing Python variable.
TY!
| [
"Here are the basic steps:\nimport sqlite3\nconn = sqlite3.connect(':memory:')\ncurs = conn.cursor()\nresults = curs.execute( \"\"\"SELECT mycol \n FROM mytable \n WHERE somecol = ?;\"\"\", (some_var,) ).fetchall()\ncurs.close()\nconn.close()\n\nFor further res... | [
3
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006554455_python_sqlite.txt |
Q:
My program runs well, but why is it giving me an Attribute Error after it exits?
The game is simple where the Pan object catches the Pizza objects that are dispensed by the Chef object. When the Pan object (the user) misses a Pizza object, and it hits the floor of the screen, "Game Over" is printed (def game_over(... | My program runs well, but why is it giving me an Attribute Error after it exits? | The game is simple where the Pan object catches the Pizza objects that are dispensed by the Chef object. When the Pan object (the user) misses a Pizza object, and it hits the floor of the screen, "Game Over" is printed (def game_over(self)) and the game terminates. But after the game terminates, my IDE gives me these e... | [
"One of your self.overlapping_sprites is a Pan, not a Pizza.\nAlso, you have two main()s.\n"
] | [
1
] | [] | [] | [
"attributeerror",
"debugging",
"python"
] | stackoverflow_0006554629_attributeerror_debugging_python.txt |
Q:
benchmarking python script reveals mysterious time delays
i have two modules: moduleParent and moduleChild
i'm doing something like this in moduleParent:
import moduleChild
#a bunch of code
start = time.time()
moduleChild.childFunction()
finish = time.time()
print "calling child function takes:", finish-start, "... | benchmarking python script reveals mysterious time delays | i have two modules: moduleParent and moduleChild
i'm doing something like this in moduleParent:
import moduleChild
#a bunch of code
start = time.time()
moduleChild.childFunction()
finish = time.time()
print "calling child function takes:", finish-start, "total seconds"
#a bunch of code
i'm doing something like this... | [
"Edit 2: I just noticed a typo in child function, you have t2 - t2 in the print statement\nignore below:\nCalling the function itself has overhead (setting up stack space, saving local variables, returning, etc). The result suggests that your function is so trivial that setting up for a function call took longer t... | [
0,
0
] | [] | [] | [
"benchmarking",
"python",
"time"
] | stackoverflow_0006554614_benchmarking_python_time.txt |
Q:
python : FTP with TarFile
i have the following code, and i want to know how can supress the error, i tried some google search but with no sucess.
def backup_system(dirs):
""" Funcao para fazer backup das confs do systema """
os.walk("/")
try:
tar = tarfile.open("/home/backup/system/system_back... | python : FTP with TarFile | i have the following code, and i want to know how can supress the error, i tried some google search but with no sucess.
def backup_system(dirs):
""" Funcao para fazer backup das confs do systema """
os.walk("/")
try:
tar = tarfile.open("/home/backup/system/system_backup_%s.tgz" % today, "w:gz")
... | [
"tar is a tarfile.TarFile, but open() expects a string to use as a filename.\n",
"To augment Ignacio's answer I updated your backup_system a bit, hopefully this should do the trick.\ndef backup_system(dirs):\n \"\"\" Funcao para fazer backup das confs do systema \"\"\" \n os.walk(\"/\")\n tar_name = \"/h... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0006554602_python.txt |
Q:
unbind socket connection C#/python
What I have:
I have two socket client programs written in C#.
I have one socket server program (not written by me but it works) in Python.
The problem:
The first c# socket client I wrote works fine and can communicate with the python server client. I can send data over with no ... | unbind socket connection C#/python | What I have:
I have two socket client programs written in C#.
I have one socket server program (not written by me but it works) in Python.
The problem:
The first c# socket client I wrote works fine and can communicate with the python server client. I can send data over with no issue. However I wanted to rewrite the ... | [
"I know you said you already calling close or disconnect.\nBut are you reinitializing the socket variable.\neg: connection = new System.Net.Sockets.Socket(...\nIf you are using an older version of .Net you may also have to call Dispose() after call Close().\neg: \nconnection.Close();\nconnection.Dispose();\nconnect... | [
0
] | [] | [] | [
"c#",
"python",
"sockets"
] | stackoverflow_0006543220_c#_python_sockets.txt |
Q:
Django inlines working on Dev server, yet not on Apache Test server?
I'm having an issue where the Inline Admin functionality is behaving differently in different environments.
In Dev, when editing a technology I get a link at the bottom to add more Roll Modifiers as needed that works flawlessly.
In Test, I get a ... | Django inlines working on Dev server, yet not on Apache Test server? | I'm having an issue where the Inline Admin functionality is behaving differently in different environments.
In Dev, when editing a technology I get a link at the bottom to add more Roll Modifiers as needed that works flawlessly.
In Test, I get a single roll modifier with no link to add more and it silently fails to sav... | [
"Figured it out. Some time ago I'd copied the Django admin files to /var/www/media/admin and aliases /media/ to /var/www/media/\nWhich means it was serving up the old media files - giving me working CSS / images but silently failing to find the JavaScript - which the StackedInline admin interface relies upon to do ... | [
0
] | [] | [] | [
"django",
"django_admin",
"inlines",
"python"
] | stackoverflow_0006554780_django_django_admin_inlines_python.txt |
Q:
Finding if a number is prime using Python
Possible Duplicates:
Fastest way to list all primes below N in python
Checking if a number is a prime number in Python
I am working on Project Euler Problem 10, which states as follows:
Find the sum of all the primes below two million.
Here's my program:
numbers = []
su... | Finding if a number is prime using Python |
Possible Duplicates:
Fastest way to list all primes below N in python
Checking if a number is a prime number in Python
I am working on Project Euler Problem 10, which states as follows:
Find the sum of all the primes below two million.
Here's my program:
numbers = []
sum = 0
range_number = 2000000
#Appends all num... | [
"Your problem is that you never eliminate the last number in numbers. If range_number is 21, then len(numbers) is 20 and len(numbers)-1 is 19. So this line here:\nfor n in range(i + numbers[i], len(numbers)-1, numbers[i]):\n\nNever actually removes the number 20 from the list. You could have seen this if you'd p... | [
1
] | [] | [] | [
"algorithm",
"math",
"primes",
"python"
] | stackoverflow_0006555060_algorithm_math_primes_python.txt |
Q:
control-b: is it reserved?
I was surprised when a function that I wrote in python/tkinter and binded to Ctrl-b behaved strangely (specific: it was losing the value of the selected text, so that text.index(SEL_FIRST) was undefined).
I was surprised when, after changing the more improbable things I binded it instead... | control-b: is it reserved? | I was surprised when a function that I wrote in python/tkinter and binded to Ctrl-b behaved strangely (specific: it was losing the value of the selected text, so that text.index(SEL_FIRST) was undefined).
I was surprised when, after changing the more improbable things I binded it instead to something else - and it work... | [
"If you are talking about the text widget, from the official tk text widget documentation:\n\n\"The Left and Right keys move the\n insertion cursor one character to the\n left or right; they also clear any\n selection in the text...Control-b and\n Control-f behave the same as Left and\n Right, respectively.\"\... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006536533_python_tkinter.txt |
Q:
What is the theory behind mutable and immutable types?
One of the things that I admire about Python is its distinction between mutable and immutable types. Having spent a while programming in c before coming to Python, I was astonished at how easily Python does away with all the complexities of pointer dereferenci... | What is the theory behind mutable and immutable types? | One of the things that I admire about Python is its distinction between mutable and immutable types. Having spent a while programming in c before coming to Python, I was astonished at how easily Python does away with all the complexities of pointer dereferencing that drive me mad in c. In Python everything just works t... | [
"If you like the idea of immutability, you should check out a pure functional language. In Haskell all (pure) variables are immutable (yet still referred to as \"variables\", but there you go). It is a great idea - you and the compiler both know that passing something into a function cannot change it in any way. ... | [
7,
5,
4
] | [
"I'd recommend reading the following entries from Wikipedia:\n\nImmutable object\nFunctional Programming\n\n"
] | [
-2
] | [
"immutability",
"language_theory",
"mutable",
"python"
] | stackoverflow_0006554653_immutability_language_theory_mutable_python.txt |
Q:
How to print certain lines and certain parts of line in a text file
I'm trying to extract information from an HTML file(Google Chrome Bookmarks exported)
It contains text of the following format
and I would like to extract just the website adresses after <DT><A HREF= and before ADD_DATE=
I'm considering using SED ... | How to print certain lines and certain parts of line in a text file | I'm trying to extract information from an HTML file(Google Chrome Bookmarks exported)
It contains text of the following format
and I would like to extract just the website adresses after <DT><A HREF= and before ADD_DATE=
I'm considering using SED and AWK or Python
So any answers from the three languages are welcome
So ... | [
"A very quick solution would be to use regular expressions in Python.\nAssuming that the variable s contains your HTML string:\nimport re\n\ns = ''' <DT><A HREF=\"http://gmazars.info/conf/index.html\" \n <DT><A HREF=\"http://research.google.com/\" \n <DT><A HREF=\"http://research.microsoft.c... | [
4,
1,
0
] | [] | [] | [
"awk",
"python",
"sed"
] | stackoverflow_0006551025_awk_python_sed.txt |
Q:
Python making cmd invisible when using the os.system
I found out that i could ping a system on python by typing
os.system('ping ip')
but when i execute it, it shows cmd.
My question is, how do i ping someone on python without showing the cmd?
A:
Look at the
http://docs.python.org/library/subprocess.html
modu... | Python making cmd invisible when using the os.system | I found out that i could ping a system on python by typing
os.system('ping ip')
but when i execute it, it shows cmd.
My question is, how do i ping someone on python without showing the cmd?
| [
"Look at the \nhttp://docs.python.org/library/subprocess.html\nmodule.\nIt gives you enough options for controlling the output.\nOr use standard bash redirection in order to send the output to /dev/null\n",
"If you need only a ping, then it would be better to use something like ping.py.\nIn other cases use subpro... | [
0,
0,
0
] | [] | [] | [
"cmd",
"execute",
"ping",
"python"
] | stackoverflow_0006555573_cmd_execute_ping_python.txt |
Q:
Web dev in python
i am still a novice in these areas so here is my question:
I want to see the dns request sent out by my browser (say chrome).so i set up a udp server in python with host='' and port=21567(can be anything other than the previlaged and reserved ones).i set my server to listen for connections using ... | Web dev in python | i am still a novice in these areas so here is my question:
I want to see the dns request sent out by my browser (say chrome).so i set up a udp server in python with host='' and port=21567(can be anything other than the previlaged and reserved ones).i set my server to listen for connections using the udp.recvfrom(1024)
... | [
"Setting up a proxy in your browser tells it where to make TCP connections; it doesn't have anything to do with how it queries DNS, which is determined by your operating system's resolver.\nFor Linux you'd just shut down bind, e.g. Debian /etc/init.d/bind9 stop; then your Python script would catch the traffic on po... | [
1
] | [] | [] | [
"dns",
"python"
] | stackoverflow_0006556035_dns_python.txt |
Q:
how to make multiline wx.ListBox
I need a ListBox to show a phone book.Then i need to show name in top and number in bottom in each list item like phone.how to bind the datas into listbox.
now i made a listbox with singleline as shown below
cur.execute("select fname from tblsample1 order by fname")
names =... | how to make multiline wx.ListBox | I need a ListBox to show a phone book.Then i need to show name in top and number in bottom in each list item like phone.how to bind the datas into listbox.
now i made a listbox with singleline as shown below
cur.execute("select fname from tblsample1 order by fname")
names = [str(item[0]) for item in cur.fetchal... | [
"Use the HtmlListBox, here is a little example to get you started.\nimport wx\n\n\nclass PhoneNumbers(wx.HtmlListBox):\n def __init__(self, parent):\n wx.HtmlListBox.__init__(self, parent)\n self.data = [\n (\"Foo\", \"3452-453\"),\n (\"Bar\", \"5672-346\"),\n ]\n ... | [
3,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006546092_python_wxpython.txt |
Q:
Get the remote python version with fabric
I am new to Fabric, and so far I am able to use all the basic functionality, connect and execute bash commands. But I am trying to execute python commands too to verify the running version and other things.
but as far as the version goes, how can I get the remote python v... | Get the remote python version with fabric | I am new to Fabric, and so far I am able to use all the basic functionality, connect and execute bash commands. But I am trying to execute python commands too to verify the running version and other things.
but as far as the version goes, how can I get the remote python version with fab.
UPDATE (Error details):
Here i... | [
"This is probably the easiest solution:\nversion = run(\"python --version\").split()[2]\n\nNote: on my system, the first line of output is \"BASHRC\", which is why you need to do [2].\n"
] | [
3
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0006556347_fabric_python.txt |
Q:
Python resource module not work
(forgive my poor English, I am not native)
I tried Python resource module to limit child process.
It seems that setting RLIMIT_CPU can successfully limit the amount of cputime, but others like RLIMIT_RSS didn't work at all.
For example, I use following script to call child.py, and s... | Python resource module not work | (forgive my poor English, I am not native)
I tried Python resource module to limit child process.
It seems that setting RLIMIT_CPU can successfully limit the amount of cputime, but others like RLIMIT_RSS didn't work at all.
For example, I use following script to call child.py, and set RSS limit to (1024, 1024):
import ... | [
"According to the documentation for setrlimit(), RLIMIT_RSS has no effect in Linux 2.4.30 and later. Also, it only counts memory marked with madvise():\n\nRLIMIT_RSS\n Specifies the limit (in pages) of the process's resident set (the number\n of virtual pages resident in RAM).\n This limit only has effect in Lin... | [
2
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0006556442_linux_python.txt |
Q:
Display line starting with word in a file Python regex
I have a file "abc.txt" with the following contents..
EMBOSS_001 601 FEDSESRRDSLFVPHRPGERRNSNGTTTETEVRKRRLSSYQISMEMLEDS 650
:...::.||...||....|..|.|.... |..:.|.|.|..:
EMBOSS_002 1 -----NPSLTVTVPIAVGESDFENLNTEEFSSE-... | Display line starting with word in a file Python regex | I have a file "abc.txt" with the following contents..
EMBOSS_001 601 FEDSESRRDSLFVPHRPGERRNSNGTTTETEVRKRRLSSYQISMEMLEDS 650
:...::.||...||....|..|.|.... |..:.|.|.|..:
EMBOSS_002 1 -----NPSLTVTVPIAVGESDFENLNTEEFSSE----SELEESKEKLNAT 41
EMBOSS_001 651 SGRQRS-MSIASIL... | [
"No one is going to write your code for you. However, I will tell you that you'll probably want to use regular expressions/regex (the \"re\" module in Python). Read http://docs.python.org/library/re.html and http://docs.python.org/howto/regex.html\n"
] | [
2
] | [] | [] | [
"biopython",
"emboss",
"python",
"regex"
] | stackoverflow_0006556514_biopython_emboss_python_regex.txt |
Q:
How to read a CSV file from a stream and process each line as it is written?
I would like to read a CSV file from the standard input and process each row as it comes. My CSV outputting code writes rows one by one, but my reader waits the stream to be terminated before iterating the rows. Is this a limitation of cs... | How to read a CSV file from a stream and process each line as it is written? | I would like to read a CSV file from the standard input and process each row as it comes. My CSV outputting code writes rows one by one, but my reader waits the stream to be terminated before iterating the rows. Is this a limitation of csv module? Am I doing something wrong?
My reader code:
import csv
import sys
import... | [
"As it says in the documentation,\n\nIn order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer.\n\nAnd you can see by looking at the implementation of the csv module (line 784) that csv.reader calls the next() ... | [
50,
1,
0
] | [] | [] | [
"csv",
"line_by_line",
"python",
"stream"
] | stackoverflow_0006556078_csv_line_by_line_python_stream.txt |
Q:
Convert date to months and year
From the following dates how to get months and year using python
dates are
"2011-07-01 09:26:11" //This showud display as "This month"
"2011-06-07 09:26:11" //This should display as June
"2011-03-12 09:26:11" //This should display... | Convert date to months and year | From the following dates how to get months and year using python
dates are
"2011-07-01 09:26:11" //This showud display as "This month"
"2011-06-07 09:26:11" //This should display as June
"2011-03-12 09:26:11" //This should display as March
"201... | [
"import time\nimport calendar\n\ncurrent = time.localtime()\n\ndates = [\"2011-07-01 09:26:11\", \"2011-06-07 09:26:11\", \"2011-03-12 09:26:11\", \"2010-07-25 09:26:11\"]\n\nfor date in dates:\n print \"%s\" % date\n date = time.strptime(date, \"%Y-%m-%d %H:%M:%S\")\n\n if date.tm_year == current.tm_year ... | [
5,
3,
0
] | [
"You could use datetime.strptime to paste the date. \nBut for simple case like yours, i would just use regex.\n>>>> import re\n>>>> re.match('^(\\d+)-(\\d+)', \"2011-07-01 09:26:11\").groups()\n('2011', '07')\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0006556581_python.txt |
Q:
How to install BeautifulSoup 3.2 in Python 3.2 in Windows?
I downloaded the beautifulsoup installation files and `python setup.py install' command fails since it appears to be written in earlier version of python and print method doesn't have braces around the text.
How do I install it in this scenario besides goi... | How to install BeautifulSoup 3.2 in Python 3.2 in Windows? | I downloaded the beautifulsoup installation files and `python setup.py install' command fails since it appears to be written in earlier version of python and print method doesn't have braces around the text.
How do I install it in this scenario besides going and fixing all such errors manually?
| [
"BeautifulSoup 3.2 is not supported on Python 3. You can use BeautifulSoup 3.1 instead. From the BeautifulSoup homepage:\n\nIf you're using Python 3.0, you must use the 3.1 series. Beautiful Soup version 3.1.0.1 was released January 6, 2009. It won't work very well—I consider it a failed experiment—but nothing else... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0006557048_beautifulsoup_python.txt |
Q:
Storing data on the fly with Python
I have a program where I want to record the function name, parameters passed to the function and the result. I am currently recording this using a decorator. However I am unsure how to store this. Currently I am just appending to a file each time.
I want to just be able to add m... | Storing data on the fly with Python | I have a program where I want to record the function name, parameters passed to the function and the result. I am currently recording this using a decorator. However I am unsure how to store this. Currently I am just appending to a file each time.
I want to just be able to add my decorators to any function in any pytho... | [
"wrap all those inside a class and then use pickle module\nI have a project that do something very close to what you want: coopy\n",
"Use the logging module from the standard library. It is designed to provide a flexible framework for logging information from a running application (across modules and source files... | [
3,
2
] | [] | [] | [
"persistence",
"python",
"save"
] | stackoverflow_0006557112_persistence_python_save.txt |
Q:
How to retrieve the first X objects with unique attribute value
In one of my Django application, I am looking for an elegant and performant solution for a problem that could be described with the following example :
Given these objects:
class Author(models.Model):
name = models.CharField()
class Book(models.M... | How to retrieve the first X objects with unique attribute value | In one of my Django application, I am looking for an elegant and performant solution for a problem that could be described with the following example :
Given these objects:
class Author(models.Model):
name = models.CharField()
class Book(models.Model):
collection = models.ForeignKey(Collection)
publication... | [
"Probably this post answers your question\nDjango: Distinct foreign keys\n",
"You could use annotate, extra or raw. Here's how you'd use annotatate:\nbooks = [a.book_set.latest('pub_date') for a in Author.objects\n .annotate(latest=Max('book__pub_date'))\n .order_by('-latest')[... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006557141_django_python.txt |
Q:
Python "self" convention __init__ vs method
class MyClass(object):
def __init__(self):
self.var = "hi"
def some_method(self):
print self.var
#for the example below
myClass= MyClass()
So I understand that the following statements are equivelent.
myClass.some_method()
MyClass.some_method(myCla... | Python "self" convention __init__ vs method | class MyClass(object):
def __init__(self):
self.var = "hi"
def some_method(self):
print self.var
#for the example below
myClass= MyClass()
So I understand that the following statements are equivelent.
myClass.some_method()
MyClass.some_method(myClass)
It takes object and passes it as the first a... | [
"myClass= MyClass() calls MyClass.__new__ method to create an instance of MyClass. After that MyClass.__init__ is called with this instance as first argument.\nSee the doc object.__new__:\n\nobject.__new__(cls[, ...])\nCalled to create a new instance of class cls.\nobject.__init__(self[, ...])\nCalled when the inst... | [
13,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0006557420_python.txt |
Q:
In Pyramid, how can I use a different renderer based on contents of context?
I have 3 different product page layouts that I would like to display dependent on the information available about the products. Using traversal I have a class called ProductFinder that grabs all the information. For example the user goes ... | In Pyramid, how can I use a different renderer based on contents of context? | I have 3 different product page layouts that I would like to display dependent on the information available about the products. Using traversal I have a class called ProductFinder that grabs all the information. For example the user goes to domain/green/small and ProductFinder will list all products from my DB that are... | [
"I will start off by saying this sort of seems like something you want to take care of in your template.\nHowever, you can influence which renderer is used as part of the view lookup in just about any way you want to. As you might already know you can use the same view handler for multiple views, you simply need to... | [
11,
6
] | [] | [] | [
"mako",
"pyramid",
"python",
"traversal"
] | stackoverflow_0006553569_mako_pyramid_python_traversal.txt |
Q:
In Python, how do I check if an instance of my class exists?
I'm making a program that asks the user to login, and I'm wondering how I can make it so it checks if an instance of my Username class exists. Oh and please excuse my sloppy and disorganized coding, I'm not very good at it.
quit_login = 1
class Usernames... | In Python, how do I check if an instance of my class exists? | I'm making a program that asks the user to login, and I'm wondering how I can make it so it checks if an instance of my Username class exists. Oh and please excuse my sloppy and disorganized coding, I'm not very good at it.
quit_login = 1
class Usernames:
def __init__(self, password):
self.password = passwo... | [
"The missing piece is a collection to hold your Usernames instances. For this particular scenario, you probably want a dictionary.\n>>> myDict = {}\n>>> myDict['foo'] = 5\n>>> 'foo' in myDict\nTrue\n>>> myDict['foo']\n5\n>>> myDict.get('bar', 'nope')\n'nope'\n>>> \n\n"
] | [
2
] | [] | [] | [
"authentication",
"class",
"instance",
"python"
] | stackoverflow_0006557349_authentication_class_instance_python.txt |
Q:
webapp in python
I have got a very simple idea in mind that i want to try out. Say i have a browser, chrome for instance, and i want to search for the ip of the domain name, say www.google.com. I use windows 7 and i have set the dns lookup properties to manual and have given the address 127.0.0.1 where my server (... | webapp in python | I have got a very simple idea in mind that i want to try out. Say i have a browser, chrome for instance, and i want to search for the ip of the domain name, say www.google.com. I use windows 7 and i have set the dns lookup properties to manual and have given the address 127.0.0.1 where my server (written in Python is r... | [
"DNS uses a compression algorithm and uses [length]string to represent parts of the domain name (as far as I remember). e.g. [3]www[6]google[3]com.\nHave a look at the DNS RFCs, e.g. http://www.zoneedit.com/doc/rfc/rfc1035.txt\n"
] | [
0
] | [] | [] | [
"dns",
"python"
] | stackoverflow_0006556856_dns_python.txt |
Q:
what does 'objects being subclassable' mean?
Dive into Python -
Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have nei... | what does 'objects being subclassable' mean? | Dive into Python -
Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapt... | [
"To be subclassable means that you can inherit from them. e.g.\nclass Foo(object):\n pass\n\nobject here is subclassable because Foo can inherit from it.\n"
] | [
3
] | [
"In this context I think it is talking about Inheritance or Interfaces. As in, you can subclass a Human into Male and Female.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0006557959_python.txt |
Q:
Is there a way to give parts of the local namespace to an importee?
a.py:
import b
import c
...
import z
class Foo(object):
...
Each of thoses module B-Z needs to use class foo.
Is some way, like importing, which allows indirect access (e.g. via an object) to all values of all modules A-Z, while still allowi... | Is there a way to give parts of the local namespace to an importee? | a.py:
import b
import c
...
import z
class Foo(object):
...
Each of thoses module B-Z needs to use class foo.
Is some way, like importing, which allows indirect access (e.g. via an object) to all values of all modules A-Z, while still allowing each module B-Z access to A's namespace (e.g. foo).
| [
"No. They must each in turn import A themselves.\n",
"I still cannot tell what you are trying to do or even asking, but this is my best guess:\nNormally, just use classic imports.\nIF a module is growing too large, or if you have an extremely good reason to split things up but desire to share the same namespace, ... | [
2,
2
] | [] | [] | [
"import",
"namespaces",
"python"
] | stackoverflow_0006557860_import_namespaces_python.txt |
Q:
Python: reverse a string
Possible Duplicate:
Reverse a string in Python
I understand that data in Python (strings) are stored like lists
Example:
string1 = "foo"
"foo"[1] = "o"
How would I use the list.reverse function to reverse the characters in a string? Such that I input "foo" and get returned back "oof"
A... | Python: reverse a string |
Possible Duplicate:
Reverse a string in Python
I understand that data in Python (strings) are stored like lists
Example:
string1 = "foo"
"foo"[1] = "o"
How would I use the list.reverse function to reverse the characters in a string? Such that I input "foo" and get returned back "oof"
| [
"You normally wouldn't.\n>>> \"foo\"[::-1]\n'oof'\n\n",
"Like this:\n''.join(reversed(myString))\n\n",
"If you want to use list.reverse, then you have to do this:\nc = list(string1)\nc.reverse()\nprint ''.join(c)\n\nBut you are better using ''.join(reversed('foo')) or just 'foo'[::-1]\n"
] | [
14,
3,
2
] | [] | [] | [
"list",
"python",
"reverse"
] | stackoverflow_0006557950_list_python_reverse.txt |
Q:
How to split string at a specific char(set of chars, actually), but with specified length
I'm pretty sure that there's such question..
Here's the issue - I want to split a string, using some specified chars as delimiters, but I also want the substrings to have length, close to the specified.
Real world example -... | How to split string at a specific char(set of chars, actually), but with specified length | I'm pretty sure that there's such question..
Here's the issue - I want to split a string, using some specified chars as delimiters, but I also want the substrings to have length, close to the specified.
Real world example - split long subtitles lines.
Example:
1234,asd dsa qwerty 567,
I want to split the line to a n... | [
"In [1]: import textwrap\n\nIn [2]: textwrap.wrap('1234,asd dsa qwerty 567,', 10)\nOut[2]: ['1234,asd', 'dsa qwerty', '567,']\n\n",
"The following code splits your string as desired at spaces with a width of 10:\nimport re\nr = \"1234,asd dsa qwerty 567,\"\np = re.compile(\"(.{,10})($|\\s)\")\nr = p.sub(\"\\\\1\\... | [
3,
1
] | [] | [] | [
"delimiter",
"python",
"split",
"string"
] | stackoverflow_0006558072_delimiter_python_split_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.