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: tokenize a string keeping delimiters in Python Is there any equivalent to str.split in Python that also returns the delimiters? I need to preserve the whitespace layout for my output after processing some of the tokens. Example: >>> s="\tthis is an example" >>> print s.split() ['this', 'is', 'an', 'example'] >>>...
tokenize a string keeping delimiters in Python
Is there any equivalent to str.split in Python that also returns the delimiters? I need to preserve the whitespace layout for my output after processing some of the tokens. Example: >>> s="\tthis is an example" >>> print s.split() ['this', 'is', 'an', 'example'] >>> print what_I_want(s) ['\t', 'this', ' ', 'is', ' ',...
[ "How about\nimport re\nsplitter = re.compile(r'(\\s+|\\S+)')\nsplitter.findall(s)\n\n", ">>> re.compile(r'(\\s+)').split(\"\\tthis is an example\")\n['', '\\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']\n\n", "the re module provides this functionality:\n>>> import re\n>>> re.split('(\\W+)', 'Words, words,...
[ 19, 6, 4, 3 ]
[ "Thanks guys for pointing for the re module, I'm still trying to decide between that and using my own function that returns a sequence...\ndef split_keep_delimiters(s, delims=\"\\t\\n\\r \"):\n delim_group = s[0] in delims\n start = 0\n for index, char in enumerate(s):\n if delim_group != (char in d...
[ -1 ]
[ "python", "split", "string", "tokenize" ]
stackoverflow_0001820336_python_split_string_tokenize.txt
Q: Appending lists from files to a single list in Python I'm trying to write a function that reads files from a "deferred" directory which contains files that contain lists. Here's what the files in the deferred folder contain: '173378981', '45000', '343434', '3453453', '34534545', '3452342', '234234', '42063008', 'E...
Appending lists from files to a single list in Python
I'm trying to write a function that reads files from a "deferred" directory which contains files that contain lists. Here's what the files in the deferred folder contain: '173378981', '45000', '343434', '3453453', '34534545', '3452342', '234234', '42063008', 'Exempted', '10000' '1000014833', '0', '0', '0', '0', '0', '0...
[ "First, the last line in the store function needs to be like this f.close()\nYour store function saves the values in a newline-separated manner. To read all the files, should be enough:\ndef getDeferredRecords():\n \"\"\"docstring for getDeferredRecords\"\"\"\n return dict((infile, list(iter(file(infile)))) \...
[ 2, 1, 1, 0 ]
[]
[]
[ "io", "list", "python" ]
stackoverflow_0001820357_io_list_python.txt
Q: Must Standard libraries for python beginner Though there can be many but as i am very new to python so which modules or classes within standard libraries i should know when programming in python, especially when i am practicing programming challenges from a C++ book? Libraries which can make my life easier? Since ...
Must Standard libraries for python beginner
Though there can be many but as i am very new to python so which modules or classes within standard libraries i should know when programming in python, especially when i am practicing programming challenges from a C++ book? Libraries which can make my life easier? Since there can be no single correct answer, i am makin...
[ "The standard libraries, i.e. the ones considered more or less part of Python. Start with those, there is plenty to learn before starting on 3rd party stuff.\nThings like:\n\nos\nre\nsubprocess\nstruct\n\n", "Check out the excellent Python Module of the Week blog series.\n", "The re module is a must. itertools ...
[ 9, 9, 5, 4, 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001820657_python.txt
Q: Django redirect not working I can see the problem, I attached my code and error page. In my template, I have: {% if user.get_profile.is_store %} <!--DO SOME LOGIC--> {%endif%} In my view, I have: def downloads(request): """ Downloads page, a user facing page for the trade members to downloads POS etc """ if n...
Django redirect not working
I can see the problem, I attached my code and error page. In my template, I have: {% if user.get_profile.is_store %} <!--DO SOME LOGIC--> {%endif%} In my view, I have: def downloads(request): """ Downloads page, a user facing page for the trade members to downloads POS etc """ if not authenticated_user(request): ...
[ "self.account is pointing at a non-existent Account object when it's trying to process is_store(). I would guess you are using a database that doesn't enforce foreign keys *cough*MySQL*cough*, and your data got messed up.\n", "It looks like the user.get_profile() return value is empty, and therefore it fails on ...
[ 3, 0, 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0001820852_django_django_templates_django_views_python.txt
Q: Unique UUIDs from multiple processes on same machine To tag the data we create, I'm considering using uuids. Security is not an issue, so I was going to use version 1 (date-and-mac-address-based). The only concern is that each user may be creating multiple data files at once from different processes with multipl...
Unique UUIDs from multiple processes on same machine
To tag the data we create, I'm considering using uuids. Security is not an issue, so I was going to use version 1 (date-and-mac-address-based). The only concern is that each user may be creating multiple data files at once from different processes with multiple threads. Assuming Python's uuid library is thread-safe ...
[ "Just use uuid4 for completely random UUIDs. There is no need to worry about collisions.\nedit in response to comment: In my experience, redundant data leads to inconsistencies sooner or later. There is a reason that avoiding redundancy is a dogma of relational database design. \nSo don't use the UUID as a \"redund...
[ 4 ]
[]
[]
[ "python", "uuid" ]
stackoverflow_0001821399_python_uuid.txt
Q: sqlalchemy does not create my foreign key SqlAlchemy newbie question: Base = declarative_base() class A(Base): __tablename__ = 'as' id = Column(Integer, primary_key=True) class B(Base): __tablename__ = 'bs' id = Column(Integer, primary_key=True) a = relation(A) When I create my database sche...
sqlalchemy does not create my foreign key
SqlAlchemy newbie question: Base = declarative_base() class A(Base): __tablename__ = 'as' id = Column(Integer, primary_key=True) class B(Base): __tablename__ = 'bs' id = Column(Integer, primary_key=True) a = relation(A) When I create my database schema, I have two tables, as and bs, which have on...
[ "relation() only tells the mapper how are the two tables related. You still need to add a column with the foreign key information. For example:\nclass B(Base):\n __tablename__ = 'bs'\n id = Column(Integer, primary_key=True)\n a_id = Column(Integer, ForeignKey('as.id'), name=\"a\")\n a = relation(A)\n\n"...
[ 5 ]
[]
[]
[ "mysql", "orm", "python", "sqlalchemy" ]
stackoverflow_0001821527_mysql_orm_python_sqlalchemy.txt
Q: Beautifulsoup get value in table I am trying to scrape http://www.co.jefferson.co.us/ats/displaygeneral.do?sch=000104 and get the "owner Name(s)" What I have works but is really ugly and not the best I am sure, so I am looking for a better way. Here is what I have: soup = BeautifulSoup(url_opener.open(url)) ...
Beautifulsoup get value in table
I am trying to scrape http://www.co.jefferson.co.us/ats/displaygeneral.do?sch=000104 and get the "owner Name(s)" What I have works but is really ugly and not the best I am sure, so I am looking for a better way. Here is what I have: soup = BeautifulSoup(url_opener.open(url)) x = soup('table', text = re.comp...
[ "(Edit: apparently the HTML the OP posted lies -- there is in fact no tbody tag to look for, even though he made it a point of including in that HTML. So, changing to use table instead of tbody).\nAs there may be several table-rows you want (e.g., see the sibling URL to the one you give, with the last digit, 4, cha...
[ 5, 3, 1 ]
[]
[]
[ "beautifulsoup", "html_content_extraction", "python", "screen_scraping" ]
stackoverflow_0001817184_beautifulsoup_html_content_extraction_python_screen_scraping.txt
Q: How to get unicode month name in Python? I am trying to get a unicode version of calendar.month_abbr[6]. If I don't specify an encoding for the locale, I don't know how to convert the string to unicode. The example code below shows my problem: >>> import locale >>> import calendar >>> locale.setlocale(locale.LC_AL...
How to get unicode month name in Python?
I am trying to get a unicode version of calendar.month_abbr[6]. If I don't specify an encoding for the locale, I don't know how to convert the string to unicode. The example code below shows my problem: >>> import locale >>> import calendar >>> locale.setlocale(locale.LC_ALL, ("ru_RU")) 'ru_RU' >>> print repr(calendar....
[ "Change the last line in your code:\n>>> print calendar.month_abbr[6].decode(\"utf8\")\nИюн\n\nImproperly used repr() hides from you that you already get what you needed.\nAlso getlocale() can be used to get encoding for current locale:\n>>> locale.setlocale(locale.LC_ALL, 'en_US')\n'en_US'\n>>> locale.getlocale()\...
[ 12, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0001821204_python_unicode.txt
Q: Simple question about numpy matrix in python Let's suppose I have a numpy matrix variable called MATRIX with 3 coordinates: (x, y, z). Is acessing the matrix's value through the following code myVar = MATRIX[0,0,0] equal to myVar = MATRIX[0,0][0] or myVar = MATRIX[0][0,0] ? What about if I have the following co...
Simple question about numpy matrix in python
Let's suppose I have a numpy matrix variable called MATRIX with 3 coordinates: (x, y, z). Is acessing the matrix's value through the following code myVar = MATRIX[0,0,0] equal to myVar = MATRIX[0,0][0] or myVar = MATRIX[0][0,0] ? What about if I have the following code? myTuple = (0,0) myScalar = 0 myVar = MATRIX[my...
[ "I assume you have a array instance rather than a matrix, since the latter only can have two dimensions.\nm[0, 0, 0] gets the element at position (0, 0, 0).\nm[0, 0] gets a whole subarray (a slice), which is itself a array. You can get the first element of this subarray like this: m[0, 0][0], which is why both synt...
[ 6, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001822417_numpy_python.txt
Q: Python: Nested Loop Consider this: >>> a = [("one","two"), ("bad","good")] >>> for i in a: ... for x in i: ... print x ... one two bad good How can I write this code, but using a syntax like: for i in a: print [x for x in i] Obviously, This does not work, it prints: ['one', 'two'] ['bad', 'good...
Python: Nested Loop
Consider this: >>> a = [("one","two"), ("bad","good")] >>> for i in a: ... for x in i: ... print x ... one two bad good How can I write this code, but using a syntax like: for i in a: print [x for x in i] Obviously, This does not work, it prints: ['one', 'two'] ['bad', 'good'] I want the same outpu...
[ "List comprehensions and generators are only designed to be used as expressions, while printing is a statement. While you can effect what you're trying to do by doing\nfrom __future__ import print_function\nfor x in a:\n [print(each) for each in x]\n\ndoing so is amazingly unpythonic, and results in the generat...
[ 7, 7, 4, 3, 3, 1, 1, 0 ]
[]
[]
[ "loops", "nested", "python" ]
stackoverflow_0001821471_loops_nested_python.txt
Q: Need a Python package suitable for visualizing queue simulations I am working on a simulation in Queueing Theory, within a wxPython GUI. (Project link.) What would be a good tool for visualizing the simulations? The visualization should consist of simple objects, such as clients, servers, a facility and a populati...
Need a Python package suitable for visualizing queue simulations
I am working on a simulation in Queueing Theory, within a wxPython GUI. (Project link.) What would be a good tool for visualizing the simulations? The visualization should consist of simple objects, such as clients, servers, a facility and a population. They should all be represented by simple boxes or something like t...
[ "Have you considered using NS3? It may be a little more than what you're looking for, but it is the standard for open source queue simulations. Here's the documentation on Python bindings for NS3.\n", "Here's a list of some 2D Graphics packages you might consider:\nhttp://www.vrplumber.com/py3d.py?category=grap...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "scientific_computing", "simulation", "visualization", "wxpython" ]
stackoverflow_0001820939_python_scientific_computing_simulation_visualization_wxpython.txt
Q: Find and replace multiple strings in file then output to new filename python I am looking to create a python script that will read one source file then produce another file with a string for the name. for example macaddress.cnf.xml contains the source file I need to change '6000' to '6001' in multiple places of...
Find and replace multiple strings in file then output to new filename python
I am looking to create a python script that will read one source file then produce another file with a string for the name. for example macaddress.cnf.xml contains the source file I need to change '6000' to '6001' in multiple places of macaddress.cnf.xml, then I want to output to newmacaddress.cnf.xl. This is what I...
[ "It is unclear from your question what all of your goals are, but I will try to address some of them. If you want to take input from one file, modify it, and then write to another file you could do following: \nbuffer = \"\";\nwith open(\"input_file\") as in:\n buffer = in.read();\n\n# do modifications ...\n\nw...
[ 1, 0 ]
[]
[]
[ "full_text_search", "python", "replace" ]
stackoverflow_0001822307_full_text_search_python_replace.txt
Q: Python integer to read-only buffer I am using cdb for a constant database in python. I would like to associate integer id's with some strings, and I would like to avoid storing each of these integer id's as strings, and instead store them as an integer. cdb though is looking for either a string or a read only bu...
Python integer to read-only buffer
I am using cdb for a constant database in python. I would like to associate integer id's with some strings, and I would like to avoid storing each of these integer id's as strings, and instead store them as an integer. cdb though is looking for either a string or a read only buffer. Is there a way that I can store t...
[ "According to the cdb website the database only takes strings as keys\n\nA cdb is an associative array: it maps strings (keys) to strings (data).\n\nSo you will have to convert the integers to strings first. I suggest you wrap the str in a utility function and forget about the overhead.\n" ]
[ 4 ]
[]
[]
[ "binary", "cdb", "python" ]
stackoverflow_0001822709_binary_cdb_python.txt
Q: How do I send and receive real-time signals `sigqueue()` in Python? Python provides a signals module and os.kill; does it have a facility for sigqueue() (real-time signals with attached data)? What are the alternatives? A: You could do it with ctypes >>> from ctypes import * >>> c = cdll.LoadLibrary("libc.so.6")...
How do I send and receive real-time signals `sigqueue()` in Python?
Python provides a signals module and os.kill; does it have a facility for sigqueue() (real-time signals with attached data)? What are the alternatives?
[ "You could do it with ctypes\n>>> from ctypes import *\n>>> c = cdll.LoadLibrary(\"libc.so.6\")\n>>> c.sigqueue\n<_FuncPtr object at 0xb7dbd77c>\n>>> c.sigqueue(100, 10, 0)\n-1\n>>>\n\nYou'll have to look up how to make a union in ctypes which I've never done before but I think is possible.\n", "One alternative, ...
[ 3, 2 ]
[]
[]
[ "ipc", "python", "signals", "sigqueue", "unix" ]
stackoverflow_0001822449_ipc_python_signals_sigqueue_unix.txt
Q: Parsing dates from free-text input in Python I'm about to start working on a simple calendar app for a website I'm working on (using Django, but that fact's probably not relevant). I'd like users to be able to enter when an event is in a text box like this: Every Sunday evening at 7pm Next Friday Tuesday 1st Dec ...
Parsing dates from free-text input in Python
I'm about to start working on a simple calendar app for a website I'm working on (using Django, but that fact's probably not relevant). I'd like users to be able to enter when an event is in a text box like this: Every Sunday evening at 7pm Next Friday Tuesday 1st Dec 2009 and have my application begin to make some g...
[ "There is http://code.google.com/p/parsedatetime/ \n", "I proposed a pyparsing solution to this question, which seems similar to yours.\n" ]
[ 4, 2 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001822787_datetime_python.txt
Q: Set and use flags against a users profile model in Django I have a simple webapp in Django for an iPhone app. I want to prompt the user to review our product, but just once. I then don't want to show that prompt again. So would the best practise way of implementing this to be to add a new entry to the user profile...
Set and use flags against a users profile model in Django
I have a simple webapp in Django for an iPhone app. I want to prompt the user to review our product, but just once. I then don't want to show that prompt again. So would the best practise way of implementing this to be to add a new entry to the user profile model with a bolean field: "reviewed" - and then set that flag...
[ "If you are using MySQL or PostgreSQL, you can do some ALTER TABLE without loosing any data.\nIn Django, it is quite easy to add a profile for the user.\nMake sure, to create the profile if it doesn't exist :\ntry:\n profile = request.user.get_profile()\nexcept UserProfile.DoesNotExist:\n # If DoesNotExists, ...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001823372_django_django_models_python.txt
Q: incorrect function being called on multiple fast calls to python's threading.Thread() I'm having some problems with launching threads from a list of functions. They are in a list because they are configuration-specific functions. I'm wrappering the functions so that I can store the results of the functions in 'sel...
incorrect function being called on multiple fast calls to python's threading.Thread()
I'm having some problems with launching threads from a list of functions. They are in a list because they are configuration-specific functions. I'm wrappering the functions so that I can store the results of the functions in 'self', but something is going wrong in a non-threadsafe way that I get the right number of thr...
[ "The problem is that functionList[functionListIndex] is evaluated only when the lambda it is in is run (within the thread). By then the value of functionListIndex can change.\nTo fix this, you can pass a parameter to the lambda that will be evaluated at definition time:\nnewThread = threading.Thread(target=lambda f...
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001823493_multithreading_python.txt
Q: Debugging Pyparsing Grammar I'm building a parser for an imaginary programming language called C-- (not the actual C-- language). I've gotten to the stage where I need to translate the language's grammar into something Pyparsing can accept. Unfortunatly when I come to parse my input string (which is correct and sh...
Debugging Pyparsing Grammar
I'm building a parser for an imaginary programming language called C-- (not the actual C-- language). I've gotten to the stage where I need to translate the language's grammar into something Pyparsing can accept. Unfortunatly when I come to parse my input string (which is correct and should not cause Pyparsing to error...
[ "1) Change Literal(\"if\") to Keyword(\"if\") (and so on, down to Literal(\"void\")), to prevent matching the leading \"if\" of a variable named \"ifactor\".\n2) nums, alphas, and alphanums are not expressions, they are strings, that can be used with the Word class to define some typical sets of characters when def...
[ 33 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0001823427_pyparsing_python.txt
Q: which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)? I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much faster to develop and less time is spent in programming details which ...
which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)?
I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much faster to develop and less time is spent in programming details which does not actually earn anything solution wise. EDIT 2: I plan to use python-graph lib from Google-cod...
[ "I think you're looking for Python, because you can:\n\nFocus on the algorithms themselves and not have to worry about other detail like memory management. \nDo more with less code\nThe syntax is almost like working with pseudo code.\nThere is great built in language support for lists, tuples, list comprehensions,...
[ 23, 9, 8, 6, 6, 5, 4, 4, 3, 2, 2, 1, 0 ]
[]
[]
[ "algorithm", "c++", "graph", "python" ]
stackoverflow_0001823431_algorithm_c++_graph_python.txt
Q: in protocol with regard to sequence How is this implemented at a python level? I've got an object that pretends to be a dict for the most part (in retrospect I should have just subclassed dict, but I'd rather not refactor the codebase, and I'd also like to know this for future reference), which looks something a b...
in protocol with regard to sequence
How is this implemented at a python level? I've got an object that pretends to be a dict for the most part (in retrospect I should have just subclassed dict, but I'd rather not refactor the codebase, and I'd also like to know this for future reference), which looks something a bit like class configThinger(object): ...
[ "It sounds like you want to overload the in operator?\nYou can do that by defining the method __contains__: http://docs.python.org/reference/datamodel.html#object.contains\n", "For the best support for the in operator (containment aka membership checking), implement the __contains__ special method on your configT...
[ 3, 1 ]
[]
[]
[ "protocols", "python" ]
stackoverflow_0001823752_protocols_python.txt
Q: Django best practice for displaying mostly read-only form, one field writeable I have a requirement where one user creates an 'instance' of an object via a ModelForm. Another user of a different group has access to read all of the fields of the form, but has to update only one field. Think of a student who creates...
Django best practice for displaying mostly read-only form, one field writeable
I have a requirement where one user creates an 'instance' of an object via a ModelForm. Another user of a different group has access to read all of the fields of the form, but has to update only one field. Think of a student who creates an exam object. Then a teach pulls up the exam and just needs to put in a grade, th...
[ "\nShould I just query for the object, and display each field individually, then create a form (not a ModelForm?) for just the one field?\n\nThis is probably the best way to go about it. Note you can use a ModelForm for the teacher form, see the Django documentation on using a subset of fields on a model form. You ...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001823852_django_python.txt
Q: How do I query XHTML using python? I have created a simple test harness in python for my ASP .net web site. I would like to look up some HTML tags in the resulting page to find certain values.\ What would be the best way of doing this in python? eg (returned page): <div id="ErrorPanel">An error occurred......</di...
How do I query XHTML using python?
I have created a simple test harness in python for my ASP .net web site. I would like to look up some HTML tags in the resulting page to find certain values.\ What would be the best way of doing this in python? eg (returned page): <div id="ErrorPanel">An error occurred......</div> would display (in std out from pytho...
[ "Do you want to parse XML, as you state in your question's title, or HTML, as you show in the text of the question? For the latter, I recommend BeautifulSoup -- download it and install it, then, once having made a soup object out of the HTML, you can easily locate the tag with a certain id (or other attribute), e....
[ 4, 4 ]
[]
[]
[ "html", "python" ]
stackoverflow_0001824057_html_python.txt
Q: Microprocessor to RS-232 realtime plot using PySerial/Matplotlib? I'm new to the world of Python and my programming skills are fairly poor but I'm trying to figure a way to use Python to display the output from an EEG circuit (using the OpenEEG circuit http://openeeg.sourceforge.net) The analogue output is amplifi...
Microprocessor to RS-232 realtime plot using PySerial/Matplotlib?
I'm new to the world of Python and my programming skills are fairly poor but I'm trying to figure a way to use Python to display the output from an EEG circuit (using the OpenEEG circuit http://openeeg.sourceforge.net) The analogue output is amplified and processed via an ADC (in an ATmega8 microcontroller) and is conv...
[ "To handle the complicated binary data format you could maybe use structured arrays in numpy (see also here for a nice introduction). After defining the structure of the data it should be very easy to read it in. Then you could use numpy's functionality to cook down the data to what you need.\n", "There's a good ...
[ 2, 2 ]
[]
[]
[ "matplotlib", "microprocessors", "pyserial", "python", "serial_port" ]
stackoverflow_0001797249_matplotlib_microprocessors_pyserial_python_serial_port.txt
Q: merge background audio file I have 2 audio files for primary and background music that I want to merge (not concatenate). The final audio file should be as long as the primary file, and if the background music is shorter then it should repeat. If there a Linux command or a Python library that can be used to do thi...
merge background audio file
I have 2 audio files for primary and background music that I want to merge (not concatenate). The final audio file should be as long as the primary file, and if the background music is shorter then it should repeat. If there a Linux command or a Python library that can be used to do this? Sox supports merging, but does...
[ "As a possible solution, why not detect if the length of the background file < length of the foreground file and then construct a background file which is a loop, if necessary? Then you can pass that into sox.\nYou should be able to get the length from sndhdr (look at the frames count).\nAs far as a python way of m...
[ 1 ]
[]
[]
[ "audio", "linux", "merge", "python" ]
stackoverflow_0001823480_audio_linux_merge_python.txt
Q: Get mach_absolute_time/UpTime() in nanoseconds in Python I need to access the elapsed time since startup in nanoseconds from a Python program running on Mac OS X 10.6. I use the following Carbon calls to get this in C code: AbsoluteTime uptimeAbs = AbsoluteToNanoseconds(UpTime()); uint64_t elapsedTime = ((uint64_t...
Get mach_absolute_time/UpTime() in nanoseconds in Python
I need to access the elapsed time since startup in nanoseconds from a Python program running on Mac OS X 10.6. I use the following Carbon calls to get this in C code: AbsoluteTime uptimeAbs = AbsoluteToNanoseconds(UpTime()); uint64_t elapsedTime = ((uint64_t)uptimeAbs.hi << 32) + uptimeAbs.lo; Is it possible to get to...
[ "Within the code in one of the answers at CGEventTimestamp to NSDate, I found -[NSProcessInfo systemUptime], available starting in 10.6. This gives me the time in decimal seconds, which I can multiply:\nfrom Foundation import *\nNSProcessInfo.processInfo().systemUptime() * 1e9\n\nThe result does have nanosecond pre...
[ 2 ]
[]
[]
[ "macos", "macos_carbon", "pyobjc", "python" ]
stackoverflow_0001824399_macos_macos_carbon_pyobjc_python.txt
Q: In Pinax, how to invite when ACCOUNT_OPEN_SIGNUP = False? In Pinax, when ACCOUNT_OPEN_SIGNUP = False how does the admin invite more users to the system? How does one generate invitation codes? How do they work? A: The only way currently is to hit /admin/invite_user/ as a site admin. Currently, you can only sen...
In Pinax, how to invite when ACCOUNT_OPEN_SIGNUP = False?
In Pinax, when ACCOUNT_OPEN_SIGNUP = False how does the admin invite more users to the system? How does one generate invitation codes? How do they work?
[ "The only way currently is to hit /admin/invite_user/ as a site admin. Currently, you can only send out one invitation at a time. We are definitely going to improve this in 0.9. Suggestions welcome.\n" ]
[ 2 ]
[]
[]
[ "django", "invitation", "invite", "pinax", "python" ]
stackoverflow_0001817270_django_invitation_invite_pinax_python.txt
Q: major changes in python since version 2.2.3 I've written a small python script to create a file and calculate times. I've tested it on Fedora 10, and Ubuntu 8.x and it worked well. the python versions were 2.5.x. I tried to run it on my production server (an old red hat based linux server), the version of python i...
major changes in python since version 2.2.3
I've written a small python script to create a file and calculate times. I've tested it on Fedora 10, and Ubuntu 8.x and it worked well. the python versions were 2.5.x. I tried to run it on my production server (an old red hat based linux server), the version of python is 2.2.3. the script does not work and raises a sy...
[ "I wrote a script a while ago to help answer this exact question: pyqver. \n\nThis script attempts to identify the minimum version of Python that is required\n to execute a particular source file.\nWhen developing Python scripts for distribution, it is desirable to identify\n which minimum version of the Python i...
[ 8, 1, 1, 1, 0 ]
[]
[]
[ "changelog", "python" ]
stackoverflow_0001824417_changelog_python.txt
Q: Infinity generated in python code I'm looking over some complex Python 2.6 code which is occasionally resulting in an infinity being generated (at least an Infinity being serialized by the json library -- which checks w/ math.isinf). What is especially baffling is that Python (as far as I can tell) shouldn't be ab...
Infinity generated in python code
I'm looking over some complex Python 2.6 code which is occasionally resulting in an infinity being generated (at least an Infinity being serialized by the json library -- which checks w/ math.isinf). What is especially baffling is that Python (as far as I can tell) shouldn't be able to ever produce computation results ...
[ "Somewhere between 1e308 and 1e309 the floats run out of precision, so if you are computing results above that range you will see inf\n>>> 1e308\n1e+308\n>>> 1e309\ninf\n\n>>> json.dumps(1e308,allow_nan=False)\n'1e+308'\n>>> json.dumps(1e309,allow_nan=False)\nTraceback (most recent call last):\n File \"<stdin>\", ...
[ 13 ]
[]
[]
[ "infinity", "python" ]
stackoverflow_0001824751_infinity_python.txt
Q: How to send status to the VIM status line after calling custom VIM (Python) function I've just created my first VIM script, I wrote it in Python. It's a simple script to switch color schemes from a directory (/vim/etc/colors). I would like to know how to send a notification after the color scheme changed with the ...
How to send status to the VIM status line after calling custom VIM (Python) function
I've just created my first VIM script, I wrote it in Python. It's a simple script to switch color schemes from a directory (/vim/etc/colors). I would like to know how to send a notification after the color scheme changed with the name of the selected color scheme to the vim 'statusline'. rson gave an answer to my quest...
[ "vim.command('redraw | echo \"%s\"' % colorschemes[position])\nFrom :help echo:\n\nA later redraw may make the message disappear again.\n And since Vim mostly postpones redrawing until it's\n finished with a sequence of commands this happens\n quite often. To avoid that a command from before the\n \":echo\" ca...
[ 5, 1 ]
[]
[]
[ "color_scheme", "python", "scripting", "vim" ]
stackoverflow_0001822619_color_scheme_python_scripting_vim.txt
Q: Can I find all of a certain base model in App Engine? Given a class-like relationship: class A(db.Model): pass class B(A): pass Can I get all of the base class? The query: models.A.all().fetch(1) returns an empty list. A: The datastore doesn't natively support this sort of polymorphism - but you can u...
Can I find all of a certain base model in App Engine?
Given a class-like relationship: class A(db.Model): pass class B(A): pass Can I get all of the base class? The query: models.A.all().fetch(1) returns an empty list.
[ "The datastore doesn't natively support this sort of polymorphism - but you can use the polymodel class to do this. Just inherit from PolyModel instead of Model and things will behave more or less as you expect them to.\n", "The datastore does not record inheritance, per se: it stores the B entities as being of k...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001823151_google_app_engine_python.txt
Q: Python QtreeWidget: return tree hierarchy I got stuck in trying to obtain the hierarchical view of a widget tree. The code works fine and generates a nice tree like that: ROOT(Animal): | | |___Not extinct: . | (red) . |_____BIRD--------------(blue) . | ...
Python QtreeWidget: return tree hierarchy
I got stuck in trying to obtain the hierarchical view of a widget tree. The code works fine and generates a nice tree like that: ROOT(Animal): | | |___Not extinct: . | (red) . |_____BIRD--------------(blue) . | (green) | | ...
[ "What about a method in each QtreeWidgetItem in which you could print the path to this item.\nIn this method, you could use recursion to get the complete path of the item's parents (you have a \"QTreeWidgetItem * parent () const\" method to do this) and you add the current item's text to its parent's path ! You sto...
[ 2 ]
[]
[]
[ "hierarchy", "pyqt", "python", "qt", "treeview" ]
stackoverflow_0001824735_hierarchy_pyqt_python_qt_treeview.txt
Q: Self import of subpackages or not? Suppose you have the following b b/__init__.py b/c b/c/__init__.py b/c/d b/c/d/__init__.py In some python packages, if you import b, you only get the symbols defined in b. To access b.c, you have to explicitly import b.c or from b import c. In other words, you have to import b ...
Self import of subpackages or not?
Suppose you have the following b b/__init__.py b/c b/c/__init__.py b/c/d b/c/d/__init__.py In some python packages, if you import b, you only get the symbols defined in b. To access b.c, you have to explicitly import b.c or from b import c. In other words, you have to import b import b.c import b.c.d print b.c.d In ...
[ "I like namespaces -- so I think that import b should only get what's in b itself (presumably in b/__init__.py). If there's a reason to segregate other functionality in b.c, b.c.d, or whatever, then just import b should not drag it all in -- if the \"drag it all in\" does happen, I think that suggests that the nam...
[ 5 ]
[ "__all__ = [your vars, functions, classes]\nUse syntax above in package b's __init__.py to auto load things listed in dict. :)\n" ]
[ -1 ]
[ "package", "python" ]
stackoverflow_0001824001_package_python.txt
Q: Is it possible for my linux machine (with no GUI) to hit Twitter sign up page, and then spit out a captcha in a webpage format So that I can just type in the letters and register (through my linux box's IP)? (twitter uses recaptcha) Is there some way to grab that javascript, output it into a webpage. Then submit...
Is it possible for my linux machine (with no GUI) to hit Twitter sign up page, and then spit out a captcha in a webpage format
So that I can just type in the letters and register (through my linux box's IP)? (twitter uses recaptcha) Is there some way to grab that javascript, output it into a webpage. Then submit it through?
[ "Twitter offers a special API for services. Use that to automatically login from one of your programs to post tweets.\n" ]
[ 3 ]
[]
[]
[ "captcha", "forms", "http", "python", "twitter" ]
stackoverflow_0001825186_captcha_forms_http_python_twitter.txt
Q: What's the best way to divide large files in Python for multiprocessing? I run across a lot of "embarrassingly parallel" projects I'd like to parallelize with the multiprocessing module. However, they often involve reading in huge files (greater than 2gb), processing them line by line, running basic calculations, ...
What's the best way to divide large files in Python for multiprocessing?
I run across a lot of "embarrassingly parallel" projects I'd like to parallelize with the multiprocessing module. However, they often involve reading in huge files (greater than 2gb), processing them line by line, running basic calculations, and then writing results. What's the best way to split a file and process it u...
[ "One of the best architectures is already part of Linux OS's. No special libraries required.\nYou want a \"fan-out\" design.\n\nA \"main\" program creates a number of subprocesses connected by pipes.\nThe main program reads the file, writing lines to the pipes doing the minimum filtering required to deal the lines...
[ 9, 6, 4, 1, 1, 1, 0 ]
[]
[]
[ "bioinformatics", "concurrency", "multiprocessing", "python" ]
stackoverflow_0001823300_bioinformatics_concurrency_multiprocessing_python.txt
Q: Inheriting methods from a metaclass In the example enumeration code given in this question, reproduced below, why does TOKEN contain the implementations of __contains__ and __repr__ from the metaclass EnumerationType? from ctypes import * class EnumerationType(type(c_uint)): def __new__(metacls, name, bases...
Inheriting methods from a metaclass
In the example enumeration code given in this question, reproduced below, why does TOKEN contain the implementations of __contains__ and __repr__ from the metaclass EnumerationType? from ctypes import * class EnumerationType(type(c_uint)): def __new__(metacls, name, bases, dict): if not "_members_" in ...
[ "Both Enumeration and TOKEN are instances of EnumerationType:\n>>> isinstance(Enumeration, EnumerationType)\nTrue\n>>> isinstance(TOKEN, EnumerationType)\nTrue\n\nAnd special methods for instances of new style classes are looked up in class, e.g. repr(TOKEN) is equivalent to type(TOKEN).__repr__(TOKEN), which is En...
[ 2 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0001825544_metaclass_python.txt
Q: Is SOAPpy the same thing as SOAPy? I would normally read the documentation to figure that out, but the links from both websites are on sourceforge and both are 404ing. A: They appear to be 2 separate projects. SOAPy was written by Adam Elman (from here.) SOAPpy was originally written by Cayce Ullman and Brian ...
Is SOAPpy the same thing as SOAPy?
I would normally read the documentation to figure that out, but the links from both websites are on sourceforge and both are 404ing.
[ "They appear to be 2 separate projects. \nSOAPy was written by Adam Elman (from here.) \nSOAPpy was originally written by Cayce Ullman and Brian Matthews (from here.)\n" ]
[ 2 ]
[]
[]
[ "python", "soap", "soappy" ]
stackoverflow_0001825873_python_soap_soappy.txt
Q: Decoding a WBXML SyncML message from an S60 device I'm trying to decode a WBXML encoded SyncML message from a Nokia N95. My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> t...
Decoding a WBXML SyncML message from an S60 device
I'm trying to decode a WBXML encoded SyncML message from a Nokia N95. My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> thr...
[ "Funnily enough I've been working on the same problem. I'm about halfway through writing my own pure-Python WBXML parser, but it's not yet complete enough to be useful, and I have very little time to work on it right now.\nThose <Unknown> tags might be because pywbxml / libwbxml doesn't have the right tag vocabula...
[ 1, 1, 0 ]
[]
[]
[ "python", "s60", "syncml", "wbxml" ]
stackoverflow_0000226279_python_s60_syncml_wbxml.txt
Q: Django, updating a user profile with a ModelForm I'm trying to display a simple ModelForm for a user's profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful form.save() call, the old values show on the page. It isn't until a refresh that the appropriat...
Django, updating a user profile with a ModelForm
I'm trying to display a simple ModelForm for a user's profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful form.save() call, the old values show on the page. It isn't until a refresh that the appropriate value is shown. What is wrong here? @login_required ...
[ "Try this:\n@login_required\ndef user_profile(request):\n success = False\n user = User.objects.get(pk=request.user.id)\n if request.method == 'POST':\n upform = UserProfileForm(request.POST, instance=user.get_profile())\n if upform.is_valid():\n up = upform.save(commit=False)\n ...
[ 8, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001823588_django_python.txt
Q: Suppress linebreak on file.write When writing to a text file, some of the file.write instances are followed by a linebreak in the output file and others aren't. I don't want linebreaks except where I tell them to occur. Code: for doc,wc in wordcounts.items(): out.write(doc) #this works fi...
Suppress linebreak on file.write
When writing to a text file, some of the file.write instances are followed by a linebreak in the output file and others aren't. I don't want linebreaks except where I tell them to occur. Code: for doc,wc in wordcounts.items(): out.write(doc) #this works fine, no linebreak for word in w...
[ "file.write() does not add any newlines if the string you write does not contain any \\ns.\nBut you force a newline for each word in your word list using out.write(\"\\n\"), is that what you want?\n for doc,wc in wordcounts.items(): \n out.write(doc) #this works fine, no linebreak\n for...
[ 13, 1, 1, 0 ]
[]
[]
[ "file", "line_breaks", "python" ]
stackoverflow_0001826400_file_line_breaks_python.txt
Q: Passing a list to eval() Is there a way to pass a list as a function argument to eval() Or do I have to convert it to a string and then parse it as a list in the function? My simple example looks like: eval("func1(\'" + fArgs + "\')") I'm just not sure if there is a better way of taking fArgs as a list instead o...
Passing a list to eval()
Is there a way to pass a list as a function argument to eval() Or do I have to convert it to a string and then parse it as a list in the function? My simple example looks like: eval("func1(\'" + fArgs + "\')") I'm just not sure if there is a better way of taking fArgs as a list instead of a string Note: The list is p...
[ "If you're using Python 2.6.x, then you should be able to use the json module (see py doc 19.2). If not, then there is python-json available through the python package index. Both of these packages will provide a reader for parsing JSON data into an appropriate Python data type.\nFor your second problem of calling ...
[ 7, 2, 2, 0 ]
[]
[]
[ "eval", "json", "list", "python" ]
stackoverflow_0001826467_eval_json_list_python.txt
Q: Outgoing load balancer I have a big threaded feed retrieval script in python. My question is, how can I load balance outgoing requests so that I don't hit any one host too often? This is a big problem for feedburner, since a large percentage of sites proxy their RSS through feedburner and to further complicate mat...
Outgoing load balancer
I have a big threaded feed retrieval script in python. My question is, how can I load balance outgoing requests so that I don't hit any one host too often? This is a big problem for feedburner, since a large percentage of sites proxy their RSS through feedburner and to further complicate matters many sites will alias a...
[ "You should probably do a one-time request (per week/month, whatever fits). for each feed and follow redirects to get the \"true\" address. Regardless of your throttling situation at the time, you should be able to resolve all feeds, save that data and then just do it once for every new feed you add to the list. Yo...
[ 3, 2, 1 ]
[]
[]
[ "feedburner", "load_balancing", "networking", "python", "web_crawler" ]
stackoverflow_0001827018_feedburner_load_balancing_networking_python_web_crawler.txt
Q: The best way to join two dissimilar mySQL tables -- planning for django from python table a (t_a): id name last first email state country 0 sklass klass steve sklass@foo.com in uk 1 jabid abid john abid@foo.com ny us 2 jcolle colle john jcolle@foo.com wi...
The best way to join two dissimilar mySQL tables -- planning for django from python
table a (t_a): id name last first email state country 0 sklass klass steve sklass@foo.com in uk 1 jabid abid john abid@foo.com ny us 2 jcolle colle john jcolle@foo.com wi us table b (t_b): id sn given nick email l c 0 steven...
[ "You can do this in MySQL directly via a cursor executed through a stored procedure.\nDELIMITER $$\nCREATE PROCEDURE `proc_name`()\nBEGIN\n DECLARE done INT DEFAULT 0;\n DECLARE a_id BIGINT UNSIGNED;\n DECLARE b_id BIGINT UNSIGNED;\n DECLARE x_count INT;\n\n -- something like the following\n DECLARE cur1 CURS...
[ 1 ]
[]
[]
[ "django", "django_models", "mysql", "python" ]
stackoverflow_0001826686_django_django_models_mysql_python.txt
Q: import from {in,out}side of a packages I have a project I build on a library I'm building in parallel. The structure is the following : project/ main.py MyLibrary/ __init__.py --> empty Module1.py --> contain the class Class1 Module2.py --> contain the class Class2 Module3.py --> contain ...
import from {in,out}side of a packages
I have a project I build on a library I'm building in parallel. The structure is the following : project/ main.py MyLibrary/ __init__.py --> empty Module1.py --> contain the class Class1 Module2.py --> contain the class Class2 Module3.py --> contain the class Class3 ... I need to import...
[ "The behavior you're experiencing (where imports work normally on one machine and not another) often happens because you've got multiple packages named MyLibrary on one system and your PYTHONPATH doesn't list '.' first.\nTo test if this is the problem, in the project directory, run Python and do\n>>> import MyLibra...
[ 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0001783996_import_python.txt
Q: In python how can I check to see if an object has a value? Base Account class BaseAccount(models.Model): user = models.ForeignKey(User, unique=True) def __unicode__(self): """ Return the unicode representation of this customer, which is the user's full name, if set, otherwise, the user's username ...
In python how can I check to see if an object has a value?
Base Account class BaseAccount(models.Model): user = models.ForeignKey(User, unique=True) def __unicode__(self): """ Return the unicode representation of this customer, which is the user's full name, if set, otherwise, the user's username """ fn = self.user.get_full_name() if fn: return...
[ "If the Account class is your user profile, as its docstring suggests, then you should be able to do something like this:\nis_trade_user = user.get_profile().default_address.trade_user\n\nif the definition of a trade user is \"Has a default address for which trade_user is true\"\nOn the other hand, if the definitio...
[ 5 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0001827683_django_django_models_django_views_python.txt
Q: Django using a generic view for create_update update_object, form not displaying Trying to use a generic view so I can update an object via a user facing form. My code looks like this in views: from django.views.generic.create_update import update_object @permission_required('myapp.change_foo', login_url="/accoun...
Django using a generic view for create_update update_object, form not displaying
Trying to use a generic view so I can update an object via a user facing form. My code looks like this in views: from django.views.generic.create_update import update_object @permission_required('myapp.change_foo', login_url="/accounts/login/") def foo_update(request, foo_id): return update_object( request...
[ "It's right there in the documentation:\n\nIn addition to extra_context, the template's context will be:\n\nform: A django.forms.ModelForm instance representing the form for editing the object. This lets you refer to form fields easily in the template system.\n\n\nThe template_object_name argument influences the na...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001827817_django_python.txt
Q: Using super() in nested classes Imagine this: class A(object): class B(object): def __init__(self): super(B, self).__init__() This creates an error: NameError: global name B is not defined. I've tried A.B, but then it says that A is not defined. Update: I've found the problem. I've had a...
Using super() in nested classes
Imagine this: class A(object): class B(object): def __init__(self): super(B, self).__init__() This creates an error: NameError: global name B is not defined. I've tried A.B, but then it says that A is not defined. Update: I've found the problem. I've had a class like this: class A(object): ...
[ "I'm not sure why A.B is not working correctly for you, as it should.. Here's some shell output that works:\n>>> class A(object):\n... class B(object):\n... def __init__(self):\n... super(A.B, self).__init__()\n... def getB(self):\n... return A.B()\n... \n>>> A().getB()\n<__main__.B object at 0x10...
[ 20, 5, 2 ]
[]
[]
[ "python", "super" ]
stackoverflow_0001825384_python_super.txt
Q: os.kill not raising an OSError, however I do not see the given pid running On my ubuntu server I run the following command: python -c 'import os; os.kill(5555, 0)' This is done so that I can see if pid 5555 is running. From my understanding this should raise an OSError if the pid is not running. This is not rai...
os.kill not raising an OSError, however I do not see the given pid running
On my ubuntu server I run the following command: python -c 'import os; os.kill(5555, 0)' This is done so that I can see if pid 5555 is running. From my understanding this should raise an OSError if the pid is not running. This is not raising an OSError for me which means it should be a running process. However when...
[ "Under linux, each process and each thread have a different pid. os.kill doesn't care whether you have a thread pid, or a task pid, however ps doesn't normally show the thread pids.\nFor instance on my machine the process with PID 8502 is running threads which you can see like this\n$ ls /proc/8502/task/\n8502 85...
[ 7, 1, 1, 0 ]
[]
[]
[ "pid", "python", "ubuntu" ]
stackoverflow_0001826824_pid_python_ubuntu.txt
Q: Writing a Template Tag in Django I'm trying to customise a CMS written in Django. The content editors aren't flexible enough so I'm trying to come up with a better solution. Without over-explaining it, I'd like it to be a bit like django-better-chunks or django-flatblocks. You set up an editable region entirely fr...
Writing a Template Tag in Django
I'm trying to customise a CMS written in Django. The content editors aren't flexible enough so I'm trying to come up with a better solution. Without over-explaining it, I'd like it to be a bit like django-better-chunks or django-flatblocks. You set up an editable region entirely from within the template. I want to bind...
[ "for this you can create an inclusion tag and use it like:\n{% load my_tags %}\n{% product bicycle <extra vars ...> %}\n\nTo define the tag, add to your app/templatetags/mytags.py:\n@register.inclusion_tag('results.html')\ndef product(item, *extra):\n #maybe repackage extra variables\n #and add them to the re...
[ 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001200548_django_django_templates_python.txt
Q: Overload a method with a function at runtime OK, I'll admit upfront this is a mega kludge and that I could definately implement this better. It's only morbid curiosity that's driving me to find out how I could do this. class SomeClass(object): def __init__(self): def __(self, arg): self.doS...
Overload a method with a function at runtime
OK, I'll admit upfront this is a mega kludge and that I could definately implement this better. It's only morbid curiosity that's driving me to find out how I could do this. class SomeClass(object): def __init__(self): def __(self, arg): self.doStuff(arg) self.overLoaded = __ def doS...
[ "Don't worry about the self parameter, the function already has that from local scope.\nclass SomeClass(object):\n def __init__(self):\n def __(arg):\n self.bar(arg)\n self.foo = __\n def foo(self, arg):\n print \"foo\", arg\n def bar(self, arg):\n print \"bar\", arg\...
[ 8, 3, 0 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0001823898_metaprogramming_python.txt
Q: PyQt subclassing The usual way to use Qt widgets from Python seems to be to subclass them. Qt widget classes have a great many methods, so inevitably I'm going to end up adding a method to the subclass, with the same name as one inherited from the Qt widget. In Python, all methods are virtual, so what I'm concerne...
PyQt subclassing
The usual way to use Qt widgets from Python seems to be to subclass them. Qt widget classes have a great many methods, so inevitably I'm going to end up adding a method to the subclass, with the same name as one inherited from the Qt widget. In Python, all methods are virtual, so what I'm concerned about is that some Q...
[ "If the underlaying C++ methods are virtual, your Python methods that override them will be called any time C++ code calls them. If they are just regular methods, any C++ code will call the original C++ methods by default (Python code will call the Python methods though, because it sees the Python object and all me...
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0001828567_pyqt_pyqt4_python_qt_qt4.txt
Q: reading mails using python how do i read mails from my mail box using python?? import getpass, imaplib M = imaplib.IMAP4('IMAP4.gmail.com:993') M.login(getpass.getuser(), getpass.getpass()) M.select() typ, data = M.search(None, 'ALL') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') print '...
reading mails using python
how do i read mails from my mail box using python?? import getpass, imaplib M = imaplib.IMAP4('IMAP4.gmail.com:993') M.login(getpass.getuser(), getpass.getpass()) M.select() typ, data = M.search(None, 'ALL') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data[0...
[ "Three issues:\n\nThe hostname is imap.gmail.com, not imap4.gmail.com\nThe IMAP4 constructor takes two parameters: the host and port (not colon-separated)\nGmail expects you to be talking SSL\n\nSo:\nimport imaplib\nM = imaplib.IMAP4_SSL(\"imap.gmail.com\", 993)\n\n", "The error means that the host is unreachable...
[ 13, 1 ]
[]
[]
[ "email", "gmail", "imap", "python" ]
stackoverflow_0001827848_email_gmail_imap_python.txt
Q: 2 Axes Reportlab Graph I have managed to create a 2 axes graph in ReportLab, by overlapping a barchart and linepot. Here is the code for anyone interested in something similar: from reportlab.graphics.shapes import Drawing,colors from reportlab.graphics.widgets.markers import makeMarker from reportlab.graphics.cha...
2 Axes Reportlab Graph
I have managed to create a 2 axes graph in ReportLab, by overlapping a barchart and linepot. Here is the code for anyone interested in something similar: from reportlab.graphics.shapes import Drawing,colors from reportlab.graphics.widgets.markers import makeMarker from reportlab.graphics.charts.barcharts import Vertica...
[ "I did this recently. Something like\ny2Axis.labels.dx = 10\n\nshould do the trick for you.\n" ]
[ 3 ]
[]
[]
[ "graph", "python", "reportlab" ]
stackoverflow_0001826761_graph_python_reportlab.txt
Q: Setting object owner with generic create_object view in django Is it possible to use create_object view to create a new object and automatically assign request.user as foreign key? P.E: class Post(models.Model): text = models.TextField() author = models.ForeignKey(User) What I want is to use create_object...
Setting object owner with generic create_object view in django
Is it possible to use create_object view to create a new object and automatically assign request.user as foreign key? P.E: class Post(models.Model): text = models.TextField() author = models.ForeignKey(User) What I want is to use create_object and fill author with request.user.
[ "In many ways, all the solutions to this will be more trouble than they are worth. This one qualifies as a hack. It is possible for a django update to leave you high and dry if they change the way create_update is implemented. For simplicity sake, I'll assume that you are trying to set a default user, not silent...
[ 3, 3, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000639792_django_python.txt
Q: return a FaultObject on purpose from pyamf I am currently migrating from RubyAMF to PyAMF. In RubyAMF you can return a FaultObject deliberately like so: render :amf => FaultObject.new("Thats not your pie!") Is there comparable functionality in PyAMF? I've searched the docs and can't find any mention of it. A: ...
return a FaultObject on purpose from pyamf
I am currently migrating from RubyAMF to PyAMF. In RubyAMF you can return a FaultObject deliberately like so: render :amf => FaultObject.new("Thats not your pie!") Is there comparable functionality in PyAMF? I've searched the docs and can't find any mention of it.
[ "coulix is right (but due to reputation restrictions I cannot upvote! :)\nFrom within your service method, raise an exception as you would normally and PyAMF will trap that and convert it to an appropriate fault object for consumption by the requestor (e.g. using Flex Messaging this will be an ErrorMessage instance...
[ 1, 0 ]
[]
[]
[ "actionscript_3", "apache_flex", "django", "pyamf", "python" ]
stackoverflow_0001772226_actionscript_3_apache_flex_django_pyamf_python.txt
Q: Delaunay tessellation in Python? I need to find the Delaunay tessellation of a polygon in Python, and the only libraries I could find (Delny, scikits) triangulate point clouds, not polygons. Any suggestions? A: Apparently Triangle has a Python binding. I'll try to get it working A: According to Wikipedia's art...
Delaunay tessellation in Python?
I need to find the Delaunay tessellation of a polygon in Python, and the only libraries I could find (Delny, scikits) triangulate point clouds, not polygons. Any suggestions?
[ "Apparently Triangle has a Python binding. I'll try to get it working\n", "According to Wikipedia's article, the Delaunay triangulation is defined for a set of points, not for a polygon. Could you just pass the set of the polygon's points into one of those libraries?\n", "Have you tried matplotlib.delaunay.inte...
[ 2, 1, 0 ]
[]
[]
[ "delaunay", "graphics", "python" ]
stackoverflow_0001829365_delaunay_graphics_python.txt
Q: python modify __metaclass__ for whole program EDIT: Note that this is a REALLY BAD idea to do in production code. This was just an interesting thing for me. Don't do this at home! Is it possible to modify __metaclass__ variable for whole program (interpreter) in Python? This simple example is working: class Chatt...
python modify __metaclass__ for whole program
EDIT: Note that this is a REALLY BAD idea to do in production code. This was just an interesting thing for me. Don't do this at home! Is it possible to modify __metaclass__ variable for whole program (interpreter) in Python? This simple example is working: class ChattyType(type): def __init__(cls, name, bases, dct...
[ "The \"global __metaclass__\" feature of Python 2 is designed to work per-module, only (just think what havoc it would wreak, otherwise, by forcing your own metaclass on all library and third-party modules that you imported from that point onwards -- shudder!). If it's very important to you to \"secretly\" alter t...
[ 7, 4, 1 ]
[]
[]
[ "metaclass", "metaprogramming", "python", "python_2.x" ]
stackoverflow_0001829205_metaclass_metaprogramming_python_python_2.x.txt
Q: Good way to pass variables for common elements to Mako templates? I'm using Mako's inheritance features to factor out common page elements, like a header and footer, into a "base.mako" template. Page-specific controllers use their own templates, which inherit base.mako. base.mako needs a set of variables -- for ...
Good way to pass variables for common elements to Mako templates?
I'm using Mako's inheritance features to factor out common page elements, like a header and footer, into a "base.mako" template. Page-specific controllers use their own templates, which inherit base.mako. base.mako needs a set of variables -- for example, the name of the logged-on user goes in the header for all page...
[ "You have two OO design choices for your page controllers.\nCommon features can be handled two ways.\n\nInheritance. All page controllers are subclasses of a common class that provides the common attributes.\nDelegation. All page controllers are part of a pipeline where some common process (either before or after...
[ 0 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0001830042_mako_python.txt
Q: TypeError: ListControl, must set a sequence (python error) I am using Python Mechanize to open a website, fill out a form, and submit that form. It's actually pretty simple. It works until I come across radio buttons and "select" input boxes. br.open(url) br.select_form(name="postmsg") br.form['subject'] = "Is thi...
TypeError: ListControl, must set a sequence (python error)
I am using Python Mechanize to open a website, fill out a form, and submit that form. It's actually pretty simple. It works until I come across radio buttons and "select" input boxes. br.open(url) br.select_form(name="postmsg") br.form['subject'] = "Is this good for the holidays? " br.form['message'] = "I'm new to tech...
[ "Radio buttons and Check-boxes can have different behavior then other elements. It depends on their name and id.\nIf the items have the same name, try doing this:\nbr.find_control(name=\"E\").value = [\"0\"]\n\nAnother option is:\nform.find_control(name=\"E\", kind=\"list\").value = [\"0\"]\n\nand finally, this mig...
[ 8 ]
[]
[]
[ "http", "mechanize", "python", "url" ]
stackoverflow_0001830262_http_mechanize_python_url.txt
Q: How to cleanly loop over two files in parallel in Python I frequently write code like: lines = open('wordprob.txt','r').readlines() words = open('StdWord.txt','r').readlines() i = 0 for line in lines: v = [eval(s) for s in line.split()] if v[0] > v[1]: print words[i].strip(), i += 1 Is it poss...
How to cleanly loop over two files in parallel in Python
I frequently write code like: lines = open('wordprob.txt','r').readlines() words = open('StdWord.txt','r').readlines() i = 0 for line in lines: v = [eval(s) for s in line.split()] if v[0] > v[1]: print words[i].strip(), i += 1 Is it possible to avoid use variable i and make the program shorter? Tha...
[ "It looks like you don't care what the value of i is. You just are using it as a way to pair up the lines and the words. Therefore, I recommend you read one line at a time, and at the same time read one word. Then they will match.\nAlso, when you use .readlines() you read all the input at once into memory. For ...
[ 22, 16, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001830552_python.txt
Q: Uncompress Zlib string in using ByteArrays I have a web application developed in Adobe Flex 3 and Python 2.5 (deployed on Google App Engine). A RESTful web service has been created in Python and its results are currently in an XML format which is being read by Flex using the HttpService object. Now the main object...
Uncompress Zlib string in using ByteArrays
I have a web application developed in Adobe Flex 3 and Python 2.5 (deployed on Google App Engine). A RESTful web service has been created in Python and its results are currently in an XML format which is being read by Flex using the HttpService object. Now the main objective is to compress the XML so that there is as l...
[ "What is byteArray.writeUTF( event.result.toString() ); supposed to do? The result of zlib.compress() is neither unicode nor \"UTF\" (meaningless without a number after it!?); it is binary aka raw bytes; you should neither decode it nor encode it nor apply any other transformation to it. The receiver should decompr...
[ 2 ]
[]
[]
[ "actionscript_3", "apache_flex", "compression", "python", "zlib" ]
stackoverflow_0001830665_actionscript_3_apache_flex_compression_python_zlib.txt
Q: Python - Exists a function that is called when an object does not implement a function? In Smalltalk there is a message DoesNotUnderstand that is called when an object does not understand a message (this is, when the object does not have the message sent implemented). So, I like to know if in python there is a fu...
Python - Exists a function that is called when an object does not implement a function?
In Smalltalk there is a message DoesNotUnderstand that is called when an object does not understand a message (this is, when the object does not have the message sent implemented). So, I like to know if in python there is a function that does the same thing. In this example: class MyObject: def __init__(self): ...
[ "Here is a proposition for what you want to do:\nclass callee:\n def __init__(self, name):\n self.name = name\n\n def __call__(self):\n print self.name, \"has been called\"\n\n\nclass A:\n def __getattr__(self, attr):\n return callee(attr)\n\na = A()\n\na.DoSomething()\n>>> DoSomething...
[ 7, 3, 3, 2 ]
[]
[]
[ "function", "oop", "python" ]
stackoverflow_0001820160_function_oop_python.txt
Q: How to load compiled python modules from memory? I need to read all modules (pre-compiled) from a zipfile (built by py2exe compressed) into memory and then load them all. I know this can be done by loading direct from the zipfile but I need to load them from memory. Any ideas? (I'm using python 2.5.2 on windows) T...
How to load compiled python modules from memory?
I need to read all modules (pre-compiled) from a zipfile (built by py2exe compressed) into memory and then load them all. I know this can be done by loading direct from the zipfile but I need to load them from memory. Any ideas? (I'm using python 2.5.2 on windows) TIA Steve
[ "It depends on what exactly you have as \"the module (pre-compiled)\". Let's assume it's exactly the contents of a .pyc file, e.g., ciao.pyc as built by:\n$ cat>'ciao.py'\ndef ciao(): return 'Ciao!' \n$ python -c'import ciao; print ciao.ciao()'\nCiao!\n\nIOW, having thus built ciao.pyc, say that you now do:\n$ pyt...
[ 33, 10 ]
[]
[]
[ "module", "python" ]
stackoverflow_0001830727_module_python.txt
Q: Boost.Python: __init__ accepting None argument I have a C++ value type wrapped with Boost.Python which has a concept of a NULL value. The relevant parts of the wrapper code appear as follows: class_<TCurrency> currency( "TCurrency" ) .def( init<long>() ) .def( init<const std::string&>() ) <...>; Curr...
Boost.Python: __init__ accepting None argument
I have a C++ value type wrapped with Boost.Python which has a concept of a NULL value. The relevant parts of the wrapper code appear as follows: class_<TCurrency> currency( "TCurrency" ) .def( init<long>() ) .def( init<const std::string&>() ) <...>; Currently, trying to create a NULL instance in Python by...
[ "Adding an init<void*> overload will pass NULL if None is used, but I'm not sure how this could affect other ctors in corner cases. I also don't get the same None to string const& conversion that you mention, if I leave init<void*> out. Using Boost.Python 1.37 and Python 2.6.2.\nExample:\n#include <iostream>\n#in...
[ 2 ]
[]
[]
[ "boost_python", "crash", "python" ]
stackoverflow_0001830902_boost_python_crash_python.txt
Q: Pythonic List Comprehension This seems like a common task, alter some elements of an array, but my solution didn't feel very pythonic. Is there a better way to build urls with list comprehension? links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text) if len(links) == 0: return text urls = [] for ...
Pythonic List Comprehension
This seems like a common task, alter some elements of an array, but my solution didn't feel very pythonic. Is there a better way to build urls with list comprehension? links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text) if len(links) == 0: return text urls = [] for link in links: if link[0:4] =...
[ "If you want to go with list comprehensions, use:\nurls = ['http://' + link if link.startswith('www.') else link for link in links]\n\nBut I actually think that the more verbose way of looping through the links that you used is easier to read. \"Shorter\" does not always equal \"better\" or \"more readable\".\n", ...
[ 4, 1, 1, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0001831129_list_comprehension_python.txt
Q: Performing operations on a NumPy arrray but masking values along the diagonal from these operations as I can perform operations on arrays so that does nothing on the diagonal is calculated such that all but the diagonal array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.] [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1....
Performing operations on a NumPy arrray but masking values along the diagonal from these operations
as I can perform operations on arrays so that does nothing on the diagonal is calculated such that all but the diagonal array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.] [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37] [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ] [1.37, 1.73, 1.37, 0. , 1.37, 1.73, 2.37] ...
[ "I wonder if masked arrays might do what you want, e.g.,\nimport numpy as NP\nA = NP.random.random_integers(0, 9, 16).reshape(4, 4)\ndg = NP.r_[ [NP.nan] * 4 ] # proper syntax is 'nan' not 'NaN'\ndg = NP.diag(dg)\nA += dg # a 4x4 array w/ NaNs down the main diagonal\nNP.sum(A, axis=1) ...
[ 2, 1, 1, 0 ]
[]
[]
[ "arrays", "numpy", "python", "scipy" ]
stackoverflow_0001803860_arrays_numpy_python_scipy.txt
Q: Review my Django Model - Need lots of suggestions I am pulling a variety of information sources to build up a profile of a person. Once I do this I want to the flexibility to look at a person in a different ways. I don't have a lot of expierience in django so I would like a critique (be gentle) of my model. Adm...
Review my Django Model - Need lots of suggestions
I am pulling a variety of information sources to build up a profile of a person. Once I do this I want to the flexibility to look at a person in a different ways. I don't have a lot of expierience in django so I would like a critique (be gentle) of my model. Admittedly even as I coded this I'm thinking redundancy (a...
[ "__unicode__ should return unicode\ndef __unicode__(self):\n return u'%s' %self.name\n\nDjango provides a emailfield for complete adresses:\nmail = models.EmailField()\n\nI think, a address model might be sense-full. A person could have several addresses (work, home,...)\nedit\nI just saw, you are using email...
[ 5, 4, 2, 2, 1 ]
[]
[]
[ "coding_style", "django", "django_models", "python" ]
stackoverflow_0001829489_coding_style_django_django_models_python.txt
Q: python Encoding Problem? I read from source.sql ( sql script ) file INSERT INTO `Tbl_abc` VALUES (1111, 2222, 'CLEMENT', 'taya', 'MME', 'Gérant', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 4688, 0, NULL, NULL, 'MAILLOT 01/02/09', 'MAILLOT 01/04/09', NULL, NULL); And write to dest.sql With my list formated I met th...
python Encoding Problem?
I read from source.sql ( sql script ) file INSERT INTO `Tbl_abc` VALUES (1111, 2222, 'CLEMENT', 'taya', 'MME', 'Gérant', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 4688, 0, NULL, NULL, 'MAILLOT 01/02/09', 'MAILLOT 01/04/09', NULL, NULL); And write to dest.sql With my list formated I met the problem with encoding for ex...
[ "Please use .encode(\"utf-8\"), when you write to .sql file too.\nopen the file\nfileObj = codecs.open( \"someFile\", \"r\", \"utf-8\" )\n\nlets say you read it \ndata=fileOjb.read()\n\n... do something on data\nopen(\"newfile\",\"w\").write(data.encode(\"utf-8\"))\n\n", "Hi check encoding of your file .sql maybe...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001831378_python.txt
Q: Getting data from the database with python(on Django framework) ordinarily if I were writing a sql statement to this I would do something like this, SELECT * FROM (django_baseaccount LEFT JOIN django_account ON django_baseaccount.user_id = django_account.baseaccount_ptr_id) LEFT JOIN django_address ON django_a...
Getting data from the database with python(on Django framework)
ordinarily if I were writing a sql statement to this I would do something like this, SELECT * FROM (django_baseaccount LEFT JOIN django_account ON django_baseaccount.user_id = django_account.baseaccount_ptr_id) LEFT JOIN django_address ON django_account.baseaccount_ptr_id = django_address.user_id;name how do I pu...
[ "\"ordinarily if I were writing a sql statement\"\nWelcome to ORM. You're not writing SQL so remove this from the question. Do not ever post SQL and ask how to translate SQL into ORM. Translating SQL limits your ability to learn. Stop doing it.\nWrite down what the result is supposed to be.\nIt appears that you...
[ 8, 2, 2 ]
[]
[]
[ "django", "mysql", "python", "sql" ]
stackoverflow_0001831980_django_mysql_python_sql.txt
Q: Python 3: Best string compression method to minimize the size of a sqlite3 db I recently created a script that parses several web proxy logs into a tidy sqlite3 db file that is working great for me... with one snag. the file size. I have been pressed to use this format (a sqlite3 db) and python handles it native...
Python 3: Best string compression method to minimize the size of a sqlite3 db
I recently created a script that parses several web proxy logs into a tidy sqlite3 db file that is working great for me... with one snag. the file size. I have been pressed to use this format (a sqlite3 db) and python handles it natively like a champ, so my question is this... what is the best form of string compres...
[ "Here is a page with an SQLite extension to provide compression.\nThis extension provides a function that can be called on individual fields.\nHere is some of the example text from the page \n\ncreate a test table \nsqlite> create table test(name varchar(20),surname varchar(20)); \ninsert into test table some text ...
[ 1, 0, 0 ]
[]
[]
[ "compression", "python", "sqlite" ]
stackoverflow_0001829256_compression_python_sqlite.txt
Q: Python SOAP client library using a HTTPS connection with keys I want to query a SOAP service that requires the use of keys. I could write a SOAP client myself making use of httplib's HTTPSConnection, I'm pretty sure that would work, but it means I have to write a load of XML. Is there a nicer way to do this? Perha...
Python SOAP client library using a HTTPS connection with keys
I want to query a SOAP service that requires the use of keys. I could write a SOAP client myself making use of httplib's HTTPSConnection, I'm pretty sure that would work, but it means I have to write a load of XML. Is there a nicer way to do this? Perhaps getting an existing SOAP library to use a HTTPSConnection object...
[ "See twisted.web.xmlrpc.Proxy. The url argument knows about HTTPS:\n\nurl - The URL to which to post method calls. Calls will be made over SSL if the scheme is HTTPS.\n\nThis twisted doc page claims \n\nFrom the point of view of a Twisted developer, there is little difference between XML-RPC support and SOAP suppor...
[ 1 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0001832433_python_soap.txt
Q: What does Python's builtin __build_class__ do? In Python 3.1, there is a new builtin function I don't know in the builtins module: __build_class__(...) __build_class__(func, name, *bases, metaclass=None, **kwds) -> class Internal helper function used by the class statement. What does this function do? Wh...
What does Python's builtin __build_class__ do?
In Python 3.1, there is a new builtin function I don't know in the builtins module: __build_class__(...) __build_class__(func, name, *bases, metaclass=None, **kwds) -> class Internal helper function used by the class statement. What does this function do? Why must it be in builtins if it's internal? What is t...
[ "Compiling the PEP 3115 metaclass\nGuido van Rossum said:\n\nThe PEP proposes that the class\n statement accepts keyword arguments,\n *args, and **kwds syntax as well as positional bases. This is a bit messy\n to compile and execute, but we already\n have this, of course, in the code for\n calling regular func...
[ 32 ]
[]
[]
[ "metaclass", "python", "python_3.x" ]
stackoverflow_0001832997_metaclass_python_python_3.x.txt
Q: How to refer to the local module in Python? Let's say we have a module m: var = None def get_var(): return var def set_var(v): var = v This will not work as expected, because set_var() will not store v in the module-wide var. It will create a local variable var instead. So I need a way of referring the ...
How to refer to the local module in Python?
Let's say we have a module m: var = None def get_var(): return var def set_var(v): var = v This will not work as expected, because set_var() will not store v in the module-wide var. It will create a local variable var instead. So I need a way of referring the module m from within set_var(), which itself is a...
[ "def set_var(v):\n global var\n var = v\n\nThe global keyword will allow you to change global variables from within in a function.\n", "As Jeffrey Aylesworth's answer shows, you don't actually need a reference to the local module to achieve the OP's aim. The global keyword can achieve this aim.\nHowever for...
[ 10, 9, 3 ]
[]
[]
[ "import", "module", "package", "python" ]
stackoverflow_0001832626_import_module_package_python.txt
Q: Why _mysql.co that compiled on one Mac doesn't work on another? I want to use Python-MySQLDB library on Mac so I have compiled the source code to get the _mysql.so under Mac10.5 with my Intel iMac (i386) This _mysql.co works in 2 of my iMacs and another Macbook. But that's it, it doesn't work in any other Macs. Do...
Why _mysql.co that compiled on one Mac doesn't work on another?
I want to use Python-MySQLDB library on Mac so I have compiled the source code to get the _mysql.so under Mac10.5 with my Intel iMac (i386) This _mysql.co works in 2 of my iMacs and another Macbook. But that's it, it doesn't work in any other Macs. Does this mean some machine specific info got compiled into the file?
[ "If you've only built one architecture (i386 / PPC) then it won't work on Macs with the opposite architecture. Are the machines that don't work PPC machines, by any chance?\nSometimes build configurations are set up to build only the current architecture by default - I haven't build Python-MySQLDB so I'm not sure i...
[ 2, 1 ]
[]
[]
[ "compilation", "mysql", "python" ]
stackoverflow_0001831979_compilation_mysql_python.txt
Q: how can I save a form with ModelMultipleChoiceField? I have a model Calendar and in a form I want to be able to create multiple instances of it. Here are my models: class Event(models.Model): user = models.ForeignKey(User) class Group(models.Model): name = models.CharField(_('Name'), max_length=80) ev...
how can I save a form with ModelMultipleChoiceField?
I have a model Calendar and in a form I want to be able to create multiple instances of it. Here are my models: class Event(models.Model): user = models.ForeignKey(User) class Group(models.Model): name = models.CharField(_('Name'), max_length=80) events = models.ManyToManyField(Event, through='Calendar') ...
[ "That's not how to deal with many-to-many relationships in forms. You can't iterate through fields in a form and save them, it really doesn't work that way.\nIn this form, there's only one field, which happens to have multiple values. The thing to do here is to iterate through the values of this field, which you'll...
[ 2 ]
[]
[]
[ "django", "django_forms", "multiple_instances", "python", "save" ]
stackoverflow_0001833275_django_django_forms_multiple_instances_python_save.txt
Q: Javascript + python url-en/decoding problem Hi there im kinda stucked with the url encoding between python and javascript, i hope you can help me out :S Javascript: encodeURIComponent('lôl'); -> "l%C3%B4l" Python: import urllib test = container.REQUEST.form.get('test') print test print urllib.unquote(test) -> "lÃ...
Javascript + python url-en/decoding problem
Hi there im kinda stucked with the url encoding between python and javascript, i hope you can help me out :S Javascript: encodeURIComponent('lôl'); -> "l%C3%B4l" Python: import urllib test = container.REQUEST.form.get('test') print test print urllib.unquote(test) -> "lÃŽl" -> "lÃŽl" Javascript encodes "lôl" twice how...
[ "zope already url-decodes it - issue is that you're getting a utf-8 bytestring and printing it on a non-utf-8 terminal. Try decoding the string.\nx = 'l\\xc3\\xb4l'\nunicode_x = x.decode('utf-8')\nprint unicode_x\n\n" ]
[ 1 ]
[]
[]
[ "javascript", "python", "urlencode", "zope" ]
stackoverflow_0001833776_javascript_python_urlencode_zope.txt
Q: Installing TortoiseHG on Gnome in Ubuntu 9.10? I followed the following steps to install TortoiseHG on Ubuntu 9.10 using the following document: http://bitbucket.org/tortoisehg/stable/wiki/nautilus I get the following error in my ~/.xsession-errors evolution-alarm-notify-Message: Tue Dec 1 23:28:26 2009 sys:1:...
Installing TortoiseHG on Gnome in Ubuntu 9.10?
I followed the following steps to install TortoiseHG on Ubuntu 9.10 using the following document: http://bitbucket.org/tortoisehg/stable/wiki/nautilus I get the following error in my ~/.xsession-errors evolution-alarm-notify-Message: Tue Dec 1 23:28:26 2009 sys:1: GtkWarning: Refusing to add non-unique action 'HgNa...
[ "It appears you are using Mercurial 1.2.1, which does not have the refactoring done in revision 6b5522cb2ad2. That means that you cannot use the latest version of TortoiseHg with such an old version of Mercurial.\nI suggest updating Mercurial to a newer version or use an older version of TortoiseHg.\n" ]
[ 2 ]
[]
[]
[ "gnome", "mercurial", "python", "tortoisehg", "ubuntu" ]
stackoverflow_0001830705_gnome_mercurial_python_tortoisehg_ubuntu.txt
Q: Confirmation of Successful HTTP Download in Python Is there a easy and reliable way to confirm that a web download completed successfully to download using Python or WGET [for large files]? I want to make sure the file downloaded in its entirety before performing another action. A: Given many (most in practice,...
Confirmation of Successful HTTP Download in Python
Is there a easy and reliable way to confirm that a web download completed successfully to download using Python or WGET [for large files]? I want to make sure the file downloaded in its entirety before performing another action.
[ "Given many (most in practice, I believe) HTTP/1.1 header sections, you can get an expectation about how long the entity body is. If you have that expectation, you can decide if you got all the entity data. See RFC 2616 section 4.4 for full details, but essentially:\n\nsometimes the content-length accurately refle...
[ 3, 2 ]
[]
[]
[ "python", "wget" ]
stackoverflow_0001834004_python_wget.txt
Q: Python check windows server version I need to log the current windows version in my python application for reporting purposes, but the built in functions I've found so far cant tell the difference between Windows client and server versions: os.sys.getwindowsversion() (6, 0, 6002, 2, 'Service Pack 2') platform.rele...
Python check windows server version
I need to log the current windows version in my python application for reporting purposes, but the built in functions I've found so far cant tell the difference between Windows client and server versions: os.sys.getwindowsversion() (6, 0, 6002, 2, 'Service Pack 2') platform.release() 'Vista' platform.win32_ver() ('Vist...
[ "You could use the GetVersionEx Win32 API and check the value of wProductType to differentiate.\nCheck out the Python for Windows extension package.\n\nVER_NT_DOMAIN_CONTROLLER 0x0000002\nThe system is a domain controller and\n the operating system is Windows Server\n 2008, Windows Server 2003, or Windows\n 2000...
[ 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0001834446_python_windows.txt
Q: Does a File Object Automatically Close when its Reference Count Hits Zero? I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line: foo = open('foo').read() would get you the file's contents and immediately close the file. However, after reading the an...
Does a File Object Automatically Close when its Reference Count Hits Zero?
I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line: foo = open('foo').read() would get you the file's contents and immediately close the file. However, after reading the answer to Is close() necessary when using iterator on a Python file object I get t...
[ "The answer is in the link you provided.\nGarbage collector will close file when it destroys file object, but:\n\nyou don't really have control over when it happens.\nWhile CPython uses reference counting to deterministically release resources\n(so you can predict when object will be destroyed) other versions don't...
[ 33, 27, 12, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001834556_python.txt
Q: split a comma separated list with links in with beautifulsoup I've got a comma separated list in a table cell in an HTML document, but some of items in the list are linked: <table> <tr> <td>Names</td> <td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td> </tr> </table> I've be...
split a comma separated list with links in with beautifulsoup
I've got a comma separated list in a table cell in an HTML document, but some of items in the list are linked: <table> <tr> <td>Names</td> <td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td> </tr> </table> I've been using beautiful soup to parse the html, and I can get to the tab...
[ "This is one way you could do it:\nimport BeautifulSoup\n\nsoup = BeautifulSoup.BeautifulSoup('''<table>\n <tr>\n <td>Names</td>\n <td>Fred, John, Barry, <a href=\"http://www.example.com/\">Roger</a>, James</td>\n </tr>\n</table>''')\n\nresult = []\nfor tag in soup.table.findAll('td')[1]:\n if isinstance(t...
[ 10 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0001834779_beautifulsoup_html_parsing_python.txt
Q: Serving simple image with App Engine django patch? How the heck do i serve a simple img without all that MediaGenerator nonsense, in Django on App Engine? I am using app engine patch. I got layout like this: django_app_engine_project_folder my_app Where should my folder for my media be? In my_app? Or do I put e...
Serving simple image with App Engine django patch?
How the heck do i serve a simple img without all that MediaGenerator nonsense, in Django on App Engine? I am using app engine patch. I got layout like this: django_app_engine_project_folder my_app Where should my folder for my media be? In my_app? Or do I put everything in the top media folder? I want to do someth...
[ "Well it seems that using app.yaml works out:\n- url: /my_app/media/\n static_dir: my_app/media\n\nWhich allows me to refer to image a.jpg in folder my_app/media with a url like:\n<img src=\"/my_app/media/a.jpg\" />\n\n" ]
[ 2 ]
[]
[]
[ "app_engine_patch", "django", "python" ]
stackoverflow_0001834610_app_engine_patch_django_python.txt
Q: Qt QFileDialog QSizePolicy of sidebar With a QFileDialog I'm trying to change the size of the side bar in a QFileDialog. I want it to have a larger width. I was looking at dir(QtGui.QFileDialog) which shows a plethora of functions/methods and dir(QtGui.QSizePolicy) which seemed like the right choice. I've not been...
Qt QFileDialog QSizePolicy of sidebar
With a QFileDialog I'm trying to change the size of the side bar in a QFileDialog. I want it to have a larger width. I was looking at dir(QtGui.QFileDialog) which shows a plethora of functions/methods and dir(QtGui.QSizePolicy) which seemed like the right choice. I've not been able to manipulate the size of the side ba...
[ "I would suggest using find_children and then maybe qobject_cast to get the sidebar object and the manipulate it directly. \n" ]
[ 0 ]
[]
[]
[ "pyqt", "python", "qt", "resize" ]
stackoverflow_0001241893_pyqt_python_qt_resize.txt
Q: python regex escape characters We have: >>> str 'exit\r\ndrwxr-xr-x 2 root root 0 Jan 1 2000 \x1b[1;34mbin\x1b[0m\r\ndrwxr-xr-x 3 root root 0 Jan 1 2000 \x1b[1;34mlib\x1b[0m\r\ndrwxr-xr-x 10 root root 0 Jan 1 1970 \x1b[1;34mlocal\x1b[0m\r\ndrwxr-xr-x ...
python regex escape characters
We have: >>> str 'exit\r\ndrwxr-xr-x 2 root root 0 Jan 1 2000 \x1b[1;34mbin\x1b[0m\r\ndrwxr-xr-x 3 root root 0 Jan 1 2000 \x1b[1;34mlib\x1b[0m\r\ndrwxr-xr-x 10 root root 0 Jan 1 1970 \x1b[1;34mlocal\x1b[0m\r\ndrwxr-xr-x 2 root root 0 Jan 1...
[ "You have a few issues:\n\nYou're passing arguments to re.sub in the wrong order wrong. It should be:\nre.sub(regexp_pattern, replacement, source_string)\nThe string doesn't contain \"\\x\". That \"\\x1b\" is the escape character, and it's a single character.\nAs interjay pointed out, you want \".*?\" rather than...
[ 12, 3, 3, 2, 1 ]
[]
[]
[ "ansi_escape", "python", "regex" ]
stackoverflow_0001833873_ansi_escape_python_regex.txt
Q: Compile IP2Location Python extension for Windows 7 I want to compile / install the IP2Location Python extension found here: www.ip2location.com/python.aspx I tried following the instructions at these sites: eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/ boodebr.org/main...
Compile IP2Location Python extension for Windows 7
I want to compile / install the IP2Location Python extension found here: www.ip2location.com/python.aspx I tried following the instructions at these sites: eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/ boodebr.org/main/python/build-windows-extensions But I am getting no wh...
[ "OK, so the full solution is:\n\ndownload stdint.h and put it in the IP2Location C Library folder: http://msinttypes.googlecode.com/svn/trunk/stdint.h\nopen a dos prompt and execute \"C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\"\nfrom the same dos prompt execute \"nmake /f Makefile.win\"\ncd ...
[ 2, 1 ]
[]
[]
[ "c", "python", "windows" ]
stackoverflow_0001815689_c_python_windows.txt
Q: In Python, is the idiom "from Module import ClassName" typical? Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py. Within a package, if another modu...
In Python, is the idiom "from Module import ClassName" typical?
Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py. Within a package, if another module needs to instanciate an object of class ToolSet, I use: from ToolS...
[ "To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide\n\nit's okay to say this though:\nfrom subprocess import Popen, PIPE\n\nI like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather...
[ 5, 0, 0, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0001835014_import_python.txt
Q: How to do scheduled sending of email with django-mailer I'm making a django app that needs to be able to make emails and then send these out at a given time. I was thinking i could use django-mailer to put things in que and then send it of. But even though theire sample case list, lists that this is a feature, I c...
How to do scheduled sending of email with django-mailer
I'm making a django app that needs to be able to make emails and then send these out at a given time. I was thinking i could use django-mailer to put things in que and then send it of. But even though theire sample case list, lists that this is a feature, I cant seem to find out how. What I need is to be able to set a ...
[ "You need to implement the cron job for django-mailer:\n* * * * * (cd $PINAX; /usr/local/bin/python2.5 manage.py send_mail >> $PINAX/cron_mail.log 2>&1)\n\nAnd then in engine.py line 96:\n # Get rid of \"while True:\"\n while not Message.objects.all():\n # Get rid of logging.debug(\"sleeping for %s secon...
[ 4, 0 ]
[]
[]
[ "django", "django_mailer", "email", "python", "schedule" ]
stackoverflow_0001177088_django_django_mailer_email_python_schedule.txt
Q: Problem with variable scoping in Python This problem is partly due to my lack of completely understanding scoping in python, so I'll need to review that. Either way, here is a seriously trivial piece of code that keeps crashing on my Django test app. Here's a snippet: @login_required def someview(request): try: ...
Problem with variable scoping in Python
This problem is partly due to my lack of completely understanding scoping in python, so I'll need to review that. Either way, here is a seriously trivial piece of code that keeps crashing on my Django test app. Here's a snippet: @login_required def someview(request): try: usergroup = request.user.groups.all()[0].nam...
[ "HttpResponseRedirect('/accounts/login')\n\nYou're creating it but not returning it. Flow continues to the next line, which references usergroup despite it never having been assigned due to the exception.\nThe except is also troublesome. In general you should never catch ‘everything’ (except: or except Exception:) ...
[ 10, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001835809_django_python.txt
Q: Python universal database interface? Does there exist, or is there an intention to create, a universal database frontend for Python like Perl's DBI? I am aware of Python's DB-API, but all the separate packages are leaving me somewhat aggravated. A: AFAIK there is no one Python module that implements the DB-API t...
Python universal database interface?
Does there exist, or is there an intention to create, a universal database frontend for Python like Perl's DBI? I am aware of Python's DB-API, but all the separate packages are leaving me somewhat aggravated.
[ "AFAIK there is no one Python module that implements the DB-API to multiple databases and that's pretty much by design: why bring in unneeded functionality and possibly require the underlying database libraries to be installed if you are not going to use them? You can argue with that design decision but that's the...
[ 3, 2 ]
[]
[]
[ "database", "python" ]
stackoverflow_0001836061_database_python.txt
Q: Is close() necessary when using iterator on a Python file object Is it bad practice to do the following and not explicitly handle a file object and call its close() method? for line in open('hello.txt'): print line NB - this is for versions of Python that do not yet have the with statement. I ask as the Pytho...
Is close() necessary when using iterator on a Python file object
Is it bad practice to do the following and not explicitly handle a file object and call its close() method? for line in open('hello.txt'): print line NB - this is for versions of Python that do not yet have the with statement. I ask as the Python documentation seems to recommend this :- f = open("hello.txt") try: ...
[ "Close is always necessary when dealing with files, it is not a good idea to leave open file handles all over the place. They will eventually be closed when the file object is garbage collected but you do not know when that will be and in the mean time you will be wasting system resources by holding to file handles...
[ 82, 21, 13, 7, 6, 5, 3, 2 ]
[]
[]
[ "file", "iterator", "python" ]
stackoverflow_0001832528_file_iterator_python.txt
Q: Python, PowerShell, or Other? What are the advantages of Python, PowerShell, and other scripting environments? We would like to standardize our scripting and are currently using bat and cmd files as the standard. I think Python would be a better option than these, but am also researching PowerShell and other scr...
Python, PowerShell, or Other?
What are the advantages of Python, PowerShell, and other scripting environments? We would like to standardize our scripting and are currently using bat and cmd files as the standard. I think Python would be a better option than these, but am also researching PowerShell and other scripting tools. The scripts would be ...
[ "Python works as a great, all-purpose tool if you're looking to replace CMD and BAT scripts on your Windows boxes, and can also be written to run scripts on your (L)inux boxes, too. It's a great, flexible language and can handle many tasks you throw at it.\nThat being said, PowerShell is an amazingly versatile tool...
[ 46, 20, 15, 3, 2, 2, 2, 1 ]
[]
[]
[ "powershell", "python", "scripting" ]
stackoverflow_0001834850_powershell_python_scripting.txt
Q: Subprocess Popen and PIPE in Python The following code prints an empty line as an output which is false. The problem is not in the permissions, since I tested the command with 777 permissions for the pdf -file. How can you fix the command to give a right output? import subprocess from subprocess import PIPE, Popen...
Subprocess Popen and PIPE in Python
The following code prints an empty line as an output which is false. The problem is not in the permissions, since I tested the command with 777 permissions for the pdf -file. How can you fix the command to give a right output? import subprocess from subprocess import PIPE, Popen output = Popen(['pdftotext', '/home/aal/...
[ "pdftotext creates a file by default. To send the result to standard output, use:\npdftotext file.pdf -\n\nor in Python:\noutput = Popen(['pdftotext', '/home/aal/Desktop/lkn_pdf/appa.pdf', '-'], stdout=PIPE).communicate()[0]\n\n" ]
[ 6 ]
[]
[]
[ "pipe", "popen", "python", "subprocess" ]
stackoverflow_0001836588_pipe_popen_python_subprocess.txt
Q: Can I remove leading zeros in a url in django? Am redirecting urls from a legacy site, which gets me to a url like this: http://example.com/blog/01/detail I would like to automatically remove the leading zeros from these urls (seems it doesn't matter how many zeros are in there 001 0001 000001 work) so that the pa...
Can I remove leading zeros in a url in django?
Am redirecting urls from a legacy site, which gets me to a url like this: http://example.com/blog/01/detail I would like to automatically remove the leading zeros from these urls (seems it doesn't matter how many zeros are in there 001 0001 000001 work) so that the page redirects to: http://example.com/blog/1/detail Is...
[ "You can fix it by eiditing either the urls.py regex or the .htaccess regex:\nIn Django\n'^blog/0*(?P<object_id>\\d+)/detail$'\n\nIn .htaccess\nRewriteRule ^blog-0*([0-9]+) http://example.com/blog/$1 [R=301]\n\n", "Perhaps\nurl(u'^blog/0*(?P<object_id>\\d+)/detail$', \n list_detail.object_detail,\n { 'query...
[ 3, 1 ]
[]
[]
[ ".htaccess", "django", "python" ]
stackoverflow_0001836721_.htaccess_django_python.txt
Q: Need a zip of Python 2.6 for windows Not the source codes, thats the only thing i seem to find. I can't install py2.6 because it would overtake 2.5 and cause mayor mess in my pc. A: How would it overtake 2.5? You can install both in parallel, just make sure that you unselect the option to "Register Extensions" d...
Need a zip of Python 2.6 for windows
Not the source codes, thats the only thing i seem to find. I can't install py2.6 because it would overtake 2.5 and cause mayor mess in my pc.
[ "How would it overtake 2.5? You can install both in parallel, just make sure that you unselect the option to \"Register Extensions\" during the install of 2.6.\nI have several Python installations on my PC in parallel, one of them my \"standard\" one that I expect to run when I doubleclick on a .py file, and the ot...
[ 8, 2 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0001835930_python_zip.txt
Q: How do ldexp and frexp work in python? The python frexp and ldexp functions splits floats into mantissa and exponent. Do anybody know if this process exposes the actual float structure, or if it requires python to do expensive logarithmic calls? A: Python 2.6's math.frexp just calls the underlying C library frex...
How do ldexp and frexp work in python?
The python frexp and ldexp functions splits floats into mantissa and exponent. Do anybody know if this process exposes the actual float structure, or if it requires python to do expensive logarithmic calls?
[ "Python 2.6's math.frexp just calls the underlying C library frexp directly. We must assume that the C library simply uses the float representation's parts directly instead of calculating if avaliable (IEEE 754).\nstatic PyObject *\nmath_frexp(PyObject *self, PyObject *arg)\n{\n int i;\n double x = Py...
[ 5, 1, 1 ]
[]
[]
[ "exponent", "floating_point", "ieee_754", "mantissa", "python" ]
stackoverflow_0001834825_exponent_floating_point_ieee_754_mantissa_python.txt
Q: Similarity Between Users Based On Votes lets say i have a set of users, a set of songs, and a set of votes on each song: =========== =========== ======= User Song Vote =========== =========== ======= user1 song1 [score] user1 song2 [score] user1 song3 [score] user2...
Similarity Between Users Based On Votes
lets say i have a set of users, a set of songs, and a set of votes on each song: =========== =========== ======= User Song Vote =========== =========== ======= user1 song1 [score] user1 song2 [score] user1 song3 [score] user2 song1 [score] user2 song2 ...
[ "There are two common metrics that can be used to find similarities between users:\n\nEuclidean Distance, that is exactly what you are thinking: imagine a n-dimensional graph that has for each axis a song that is reviewed by two involved users (u1 and *u2) and the value on its axis is the score. You can easily calc...
[ 11, 5, 3, 1, 1, 1, 0 ]
[]
[]
[ "database", "information_retrieval", "mysql", "python", "similarity" ]
stackoverflow_0001836352_database_information_retrieval_mysql_python_similarity.txt
Q: Passing numpy.arange() an argument I'm trying to pass the values that I want numpy.arange to use. The code is: for x in numpy.arange(argument) where argument is: argument = (.1,6.3,.1) (tuple) TypeError: arange: scaler arguements expected instead of a tuple arguement = [.1,6.3,.1] (list) TypeError: unsupported o...
Passing numpy.arange() an argument
I'm trying to pass the values that I want numpy.arange to use. The code is: for x in numpy.arange(argument) where argument is: argument = (.1,6.3,.1) (tuple) TypeError: arange: scaler arguements expected instead of a tuple arguement = [.1,6.3,.1] (list) TypeError: unsupported operand type(s) for -: 'str' and 'int' ar...
[ "arange is like python's range function.\nPerhaps you were looking for numpy.array?\nOr maybe you really did want the range to be from 0.1 to 6.3 in steps of 0.1. In that case, use Python's argument unpacking syntax:\narguments = (.1, 6.3, .1)\nnumpy.arange(*arguments)\n\n" ]
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001836966_numpy_python.txt
Q: What Python-only HTTP/1.1 web servers are available? There is CherryPy. Are there any others? A: magnum-py or... Make your own! A: Twisted includes a web server. A: also: web.py (webpy.org) paste (pythonpaste.org)
What Python-only HTTP/1.1 web servers are available?
There is CherryPy. Are there any others?
[ "magnum-py\nor...\nMake your own!\n", "Twisted includes a web server.\n", "also:\nweb.py (webpy.org)\npaste (pythonpaste.org)\n" ]
[ 2, 2, 1 ]
[]
[]
[ "http", "python" ]
stackoverflow_0001835668_http_python.txt
Q: Does pytables support NULL? I have table looks like this ------------------ GeneId | ProteinId 1 | 157 2 | - 3 | 587 4 | 897 5 | - 6 | 120 In realational database, I can treat ProteinId column as INT and use NULL for "-" data. However, I can't find the s...
Does pytables support NULL?
I have table looks like this ------------------ GeneId | ProteinId 1 | 157 2 | - 3 | 587 4 | 897 5 | - 6 | 120 In realational database, I can treat ProteinId column as INT and use NULL for "-" data. However, I can't find the same option in pytables. Does pyta...
[ "As the docs say,\n\nCells in a PyTables' table always have\n a value of the cell type, so there is\n no NULL. Instead, cells take a default\n value (zero or empty) which can be\n changed in the type declaration, like\n this: col_name = StringCol(10,\n dflt='nothing') (col_name takes the\n value 'nothing' if...
[ 5 ]
[]
[]
[ "database", "python" ]
stackoverflow_0001837181_database_python.txt
Q: How do I uninstall Python 2.5? I recently upgraded to Mac OS 10.6 and didn't realise that it shipped with Python 2.6. I installed Python 2.5.4 and now it is the default Python installation. Can I uninstall Python 2.5.4 and keep 2.6? A: While there is no uninstaller for the python.org OS X python installers (bec...
How do I uninstall Python 2.5?
I recently upgraded to Mac OS 10.6 and didn't realise that it shipped with Python 2.6. I installed Python 2.5.4 and now it is the default Python installation. Can I uninstall Python 2.5.4 and keep 2.6?
[ "While there is no uninstaller for the python.org OS X python installers (because they use the standard Apple installer mechanism which does not provide an uninstaller by default), it is not difficult to remove. I've documented the full process here but keep in mind that it doesn't hurt to have multiple python ins...
[ 6, 2, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0001835003_macos_python.txt
Q: python help display regular expression result I am doing simple regular expressions in python I am trying the re.split but things like ['\r\n', '\r\n'] are coming instead of the answer. Can someone please tell me how to display the actual text please? I tried this statement: t_html = re.split("<[a-zA-Z0-9\s\w\W]*>...
python help display regular expression result
I am doing simple regular expressions in python I am trying the re.split but things like ['\r\n', '\r\n'] are coming instead of the answer. Can someone please tell me how to display the actual text please? I tried this statement: t_html = re.split("<[a-zA-Z0-9\s\w\W]*>[a-zA-Z0-9\s\w\W]*</[a-zA-Z0-9\s\w\W]*>" ,s) THank...
[ "re.split by its very nature splits on the pattern but does not preserve it. If you want to return the string matched by the pattern you can put parentheses around the pattern: re.split((R),string) where R is your expression. If you want to say find all non overlapping matches use re.findall which will return a lis...
[ 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001836637_python_regex.txt