text stringlengths 226 34.5k |
|---|
Create an encrypted ZIP file in Python
Question: I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far:
import zipfile, os
locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()
... |
Are there static analysis tools for Python?
Question: I am starting to use Python (specifically because of Django) and I would like
to remove the burden for exhaustive testing by performing some static
analysis. What tools/parameters/etc. exist to detect issues at compile time
that would otherwise show up during runtim... |
Get Last Day of the Month in Python
Question: Is there a way using Python's standard library to easily determine (i.e. one
function call) the last day of a given month?
If the standard library doesn't support that, does the dateutil package
support this?
Answer: I didn't notice this earlier when I was looking at the... |
How to find the mime type of a file in python?
Question: Let's say you want to save a bunch of files somewhere, for instance in BLOBs.
Let's say you want to dish these files out via a web page and have the client
automatically open the correct application/viewer.
Assumption: The browser figures out which application/v... |
How to know whether a window with a given title is already open in Tk?
Question: I’ve writen a little python script that just pops up a message box containing
the text passed on the command line. I want to pop it up only when the window
—resulting from a previous call— is not open.
from Tkinter import *
... |
What is the simplest way to find the difference between 2 times in python?
Question: I have 2 time values which have the type `datetime.time`. I want to find their
difference. The obvious thing to do is t1 - t2, but this doesn't work. It
works for objects of type `datetime.datetime` but not for `datetime.time`. So
what... |
How to get an absolute file path in Python
Question: Given a path such as `"mydir/myfile.txt"`, how do I find the absolute filepath
relative to the current working directory in Python? E.g. on Windows, I might
end up with:
"C:/example/cwd/mydir/myfile.txt"
Answer:
>>> import os
>>> os.pat... |
How do I write a python HTTP server to listen on multiple ports?
Question: I'm writing a small web server in Python, using BaseHTTPServer and a custom
subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this
listen on more than one port?
What I'm doing now:
class MyRequestHandler(B... |
Random in python 2.5 not working?
Question: I am trying to use the `import random` statement in python, but it doesn't
appear to have any methods in it to use.
Am I missing something?
Answer: You probably have a file named random.py or random.pyc in your working
directory. That's shadowing the built-in random module... |
Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language?
Question: I wonder why would a C++, C#, Java developer want to learn a dynamic language?
Assuming the company won't switch its main development language from
C++/C#/Java to a dynamic one what use is there for a dynamic la... |
Is there a pretty printer for python data?
Question: Working with python interactively, it's sometimes necessary to display a
result which is some arbitrarily complex data structure (like lists with
embedded lists, etc.) The default way to display them is just one massive
linear dump which just wraps over and over and ... |
Python sockets suddenly timing out?
Question: I came back today to an old script I had for logging into Gmail via SSL. The
script worked fine last time I ran it (several months ago) but now it dies
immediately with:
<urlopen error The read operation timed out>
If I set the timeout (no matter how lo... |
What's the easiest non-memory intensive way to output XML from Python?
Question: Basically, something similar to System.Xml.XmlWriter - A streaming XML Writer
that doesn't incur much of a memory overhead. So that rules out xml.dom and
xml.dom.minidom. Suggestions?
Answer: I think you'll find XMLGenerator from xml.sax... |
How do I read selected files from a remote Zip archive over HTTP using Python?
Question: I need to read selected files, matching on the file name, from a remote zip
archive using Python. I don't want to save the full zip to a temporary file
(it's not that large, so I can handle everything in memory).
I've already writ... |
Python reading Oracle path
Question: On my desktop I have written a small Pylons app that connects to Oracle. I'm
now trying to deploy it to my server which is running Win2k3 x64. (My desktop
is 32-bit XP) The Oracle installation on the server is also 64-bit.
I was getting errors about loading the OCI dll, so I instal... |
What is the standard way to add N seconds to datetime.time in Python?
Question: Given a `datetime.time` value in Python, is there a standard way to add an
integer number of seconds to it, so that `11:34:59` \+ 3 = `11:35:02`, for
example?
These obvious ideas don't work:
>>> datetime.time(11, 34, 59) + 3... |
How to generate all permutations of a list in Python
Question: How do you generate all the permutations of a list in Python, independently of
the type of elements in that list?
For example:
permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
... |
How do I get a decimal value when using the division operator in Python?
Question: For example, the standard division symbol '/' rounds to zero:
>>> 4 / 100
0
However, I want it to return 0.04. What do I use?
Answer: There are three options:
>>> 4 / float(100)
0.04
>>> ... |
How do you use the ellipsis slicing syntax in Python?
Question: This came up in [Hidden features of
Python](http://stackoverflow.com/questions/101268/hidden-features-of-python),
but I can't see good documentation or examples that explain how the feature
works.
Answer: The ellipsis is used to slice higher-dimensional ... |
Short Integers in Python
Question: Python allocates integers automatically based on the underlying system
architecture. Unfortunately I have a huge dataset which needs to be fully
loaded into memory.
So, is there a way to force Python to use only 2 bytes for some integers
(equivalent of C++ 'short')?
Answer: Nope. B... |
How can I read the RGB value of a given pixel in Python?
Question: If I open an image with `open("image.jpg")`, how can I get the RGB values of a
pixel, if I have the coordinates of the pixel?
Then how can I do the reverse of this? Starting with a blank graphic, 'write'
a pixel with a certain RGB value?
It would be s... |
listing all functions in a python module
Question: I have a python module installed on my system and I'd like to be able to see
what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like
ClassName.methods to get a list of all the methods available o... |
Calling C/C++ from python?
Question: What would be the quickest way to construct a python binding to a C or C++
library?
(using windows if this matters)
Answer: I like [ctypes](http://docs.python.org/2/library/ctypes.html) a lot,
[swig](http://www.swig.org/) always tended to give me
[problems](http://groups.google.c... |
Python - How do I write a decorator that restores the cwd?
Question: How do I write a decorator that restores the current working directory to what
it was before the decorated function was called? In other words, if I use the
decorator on a function that does an os.chdir(), the cwd will not be changed
after the functio... |
Python - Py2exe can't build .exe using the 'email' module
Question: py2exe does not work with the standard email module
Hello. I am trying to use py2exe for converting a script into an exe. The
build process shows this:
* * *
The following modules appear to be missing
## ['email.Encoders', 'email.Generator', 'email... |
How do I convert a file's format from Unicode to ASCII using Python?
Question: I use a 3rd party tool that outputs a file in Unicode format. However, I
prefer it to be in ASCII. The tool does not have settings to change the file
format.
What is the best way to convert the entire file format using Python?
Answer: You... |
Accessing python egg's own metadata
Question: I've produced a python egg using setuptools and would like to access it's
metadata at runtime. I currently got working this:
import pkg_resources
dist = pkg_resources.get_distribution("my_project")
print(dist.version)
but this would probably wor... |
How to check if OS is Vista in Python?
Question: How, in the simplest possible way, distinguish between Windows XP and Windows
Vista, using Python and
[pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or
[wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff... |
Can you list the keyword arguments a Python function receives?
Question: I have a dict, which I need to pass key/values as keyword arguments.. For
example..
d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)
This works fine, _but_ if there are values in the d_args dict that are not
a... |
Design question: How can I access an IPC mechanism transparently?
Question: I want to do this (no particular language):
print(foo.objects.bookdb.books[12].title);
or this:
book = foo.objects.bookdb.book.new();
book.title = 'RPC for Dummies';
book.save();
Where foo actua... |
Is there any way to get python omnicomplete to work with non-system modules in vim?
Question: The only thing I can get python omnicomplete to work with are system modules.
I get nothing for help with modules in my site-packages or modules that I'm
currently working on.
Answer: Once I generated ctags for one of my sit... |
extracting a parenthesized Python expression from a string
Question: I've been wondering about how hard it would be to write some Python code to
search a string for the index of a substring of the form `${`_expr_`}`, for
example, where _expr_ is meant to be a Python expression or something
resembling one. Given such a ... |
Python's __import__ doesn't work as expected
Question: When using `__import__` with a dotted name, something like:
`somepackage.somemodule`, the module returned isn't `somemodule`, whatever is
returned seems to be mostly empty! what's going on here?
Answer: From the python docs on `__import__`:
>
> __import__( n... |
Python Inverse of a Matrix
Question: How do I get the inverse of a matrix in python? I've implemented it myself,
but it's pure python, and I suspect there are faster modules out there to do
it.
Answer: You should have a look at
[numpy](http://www.scipy.org/Tentative_NumPy_Tutorial) if you do matrix
manipulation. This... |
how to generate unit test code for methods
Question: i want to write code for unit test to test my application code. I have
different methods and now want to test these methods one by one in python
script. but i do not how to i write. can any one give me example of small code
for unit testing in python. i am thankful
... |
How Python web frameworks, WSGI and CGI fit together
Question: I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can
run Python scripts as CGI. I guess it's the simplest CGI, because to run I
have to define the following in `.htaccess`:
Options +ExecCGI
AddType text/html py
... |
How to script Visual Studio 2008 from Python?
Question: I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++
2008. All the examples I've found so far use `win32com.client.Dispatch`. This
works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:
import win32com.cli... |
Incoming poplib refactoring using windows python 2.3
Question: Hi Guys could you please help me refactor this so that it is sensibly
pythonic.
import sys
import poplib
import string
import StringIO, rfc822
import datetime
import logging
def _dump_pop_emails(self):
sel... |
How do I iterate through a string in Python?
Question: As an example, lets say I wanted to list the frequency of each letter of the
alphabet in a string. What would be the easiest way to do it?
This is an example of what I'm thinking of... the question is how to make
allTheLetters equal to said letters without somethi... |
Cannot import SQLite with Python 2.6
Question: I'm running Python 2.6 on Unix and when I run the interactive prompt
([SQLite](http://en.wikipedia.org/wiki/SQLite) is supposed to be preinstalled)
I get:
[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (R... |
How can I call a DLL from a scripting language?
Question: I have a third-party product, a terminal emulator, which provides a DLL that
can be linked to a C program to basically automate the driving of this product
(send keystrokes, detect what's on the screen and so forth).
I want to drive it from a scripting language... |
Retrieving python module path
Question: I want to detect whether module has changed. Now, using inotify is simple, you
just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python?
Answer:
import a_module
print a_module.__file__
Will actually give you... |
Is it possible to communicate with a sub subprocess with subprocess.Popen?
Question: I'm trying to write a python script that packages our software. This script
needs to build our product, and package it. Currently we have other scripts
that do each piece individually which include csh, and perl scripts. One such
scrip... |
In Python, is there a concise way of comparing whether the contents of two text files are the same?
Question: I don't care what the differences are. I just want to know whether the
contents are different.
Answer: The low level way:
from __future__ import with_statement
with open(filename1) as f1:
... |
Python vs Groovy vs Ruby? (based on criteria listed in question)
Question: Considering the criteria listed below, which of Python, Groovy or Ruby would
you use?
* _Criteria (Importance out of 10, 10 being most important)_
* Richness of API/libraries available (eg. maths, plotting, networking) (9)
* Ability to em... |
How to build Python C extension modules with autotools
Question: Most of the documentation available for building Python extension modules uses
distutils, but I would like to achieve this by using the appropriate python
autoconf & automake macros instead.
I'd like to know if there is an open source project out there t... |
using jython and open office 2.4 to convert docs to pdf
Question: I completed a python script using pyuno which successfully converted a
document/ xls / rtf etc to a pdf. Then I needed to update a mssql database,
due to open office currently supporting python 2.3, it's ancientness, lacks
support for decent database lib... |
HTTP Request Timeout
Question: In Python 2.6, a new "timeout" parameter was added to the
httplib.HTTPConnection class:
<http://docs.python.org/library/httplib.html#httplib.HTTPConnection>
However, this is only a timeout for the connection to a server. I am looking
to set a timeout value for the **request** , not the c... |
Best way to strip punctuation from a string in Python
Question: It seems like there should be a simpler way than:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
Is there?
Answer: From an efficiency perspective... |
import mechanize module to python script
Question: I tried to import mechanize module to my python script like this,
from mechanize import Browser
But, Google appengine throws HTTP 500 when accessing my script.
To make things more clear, Let me give you the snapshot of my package
structure,
root
... |
Parse HTML via XPath
Question: In .Net, I found this great library,
[HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack) that allows you to
easily parse non-well-formed HTML using XPath. I've used this for a couple
years in my .Net sites, but I've had to settle for more painful libraries for
my Python, Ruby and o... |
How to split a web address
Question: So I'm using python to do some parsing of web pages and I want to split the
full web address into two parts. Say I have the address
<http://www.stackoverflow.com/questions/ask>. I would need the protocol and
domain (e.g. <http://www.stackoverflow.com>) and the path (e.g.
/questions/... |
How do I find userid by login (Python under *NIX)
Question: I need to set my process to run under 'nobody', I've found os.setuid(), but
how do I find `uid` if I have `login`?
I've found out that uids are in /etc/passwd, but maybe there is a more
pythonic way than scanning /etc/passwd. Anybody?
Answer: You might want... |
Pycurl WRITEDATA WRITEFUNCTION collision/crash
Question: How do I turnoff WRITEFUNCTION and WRITEDATA?
Using pycurl I have a class call curlUtil. In it I have pageAsString (self,
URL) which returns a string.
To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn,
overwrite=0) I do an open and self.c.Se... |
Which is more efficient in Python: standard imports or contextual imports?
Question: I apologize in advance if this question seems remedial.
Which would be considered more efficient in Python:
**Standard import**
import logging
try:
...some code...
exception Exception, e:
loggi... |
How do I remove/delete a folder that is not empty with Python?
Question: I am getting an 'access is denied' error when I attempt to delete a folder
that is not empty. I used the following command in my attempt:
`os.remove("/folder_name")`.
What is the most effective way of removing/deleting a folder/directory that is
... |
Is there a better StringCollection editor for use in PropertyGrids?
Question: I'm making heavy use of PropertySheets in my application framework's
configuration editor. I like them a lot because it's pretty easy to work with
them (once you learn how) and make the editing bulletproof.
One of the things that I'm storing... |
Python decorator makes function forget that it belongs to a class
Question: I am trying to write a decorator to do logging:
def logger(myFunc):
def new(*args, **keyargs):
print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
return myFunc(*args, **keyargs)
... |
How do I randomly select an item from a list using Python?
Question: Assume I have the following list:
foo = ['a', 'b', 'c', 'd', 'e']
What is the simplest way to retrieve an item at random from this list?
Answer: Use
[`random.choice`](https://docs.python.org/2/library/random.html#random.choice):... |
How can I dynamically get the set of classes from the current python module?
Question: I have a python module that defines a number of classes:
class A(object):
def __call__(self):
print "ran a"
class B(object):
def __call__(self):
print "ran b"
c... |
Need skeleton code to call Excel VBA from PythonWin
Question: I need to invoke a VBA macro within an Excel workbook from a python script.
Someone else has provided the Excel workbook with the macro. The macro grabs
updated values from an external database, and performs some fairly complex
massaging of the data. I need ... |
Why are .Net programmers so afraid of exceptions?
Question: First of all, I'm not trying to be critical of anyone here or saying that all
.Net programmers are this way. But I'm definitely noticing a trend: .Net
programmers seem to avoid exceptions like they're the plague.
Of course, there's always the [Raymond
Chen](h... |
A small question about python's variable scope
Question: I am a beginner of python and have a question, very confusing for me. If I
define a function first but within the function I have to use a variable which
is defined in another function below, can I do it like this? Or how can I
import the return things of another... |
How to organize python test in a way that I can run all tests in a single command?
Question: Currently my code is organized in the following tree structure:
src/
module1.py
module2.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
... |
Finding the Current Active Window in Mac OS X using Python
Question: Is there a way to find the application name of the current active window at a
given time on Mac OS X using Python?
Answer: This should work:
#!/usr/bin/python
from AppKit import NSWorkspace
activeAppName = NSWorkspace.sha... |
How do I create a wx.Image object from in-memory data?
Question: I'm writing a GUI application in Python using wxPython and I want to display
an image in a static control (`wx.StaticBitmap`).
I can use [`wx.ImageFromStream`](http://www.wxpython.org/docs/api/wx-
module.html#ImageFromStream) to load an image from a file... |
Python: single instance of program
Question: Is there a Pythonic way to have only one instance of a program running?
The only reasonable solution I've come up with is trying to run it as a server
on some port, then second program trying to bind to same port - fails. But
it's not really a great idea, maybe there's some... |
Elegant ways to support equivalence ("equality") in Python classes
Question: When writing custom classes it is often important to allow equivalence by
means of the `==` and `!=` operators. In Python, this is made possible by
implementing the `__eq__` and `__ne__` special methods, respectively. The
easiest way I've foun... |
wxPython and sharing objects between windows
Question: I've been working with python for a while now and am just starting to learn
wxPython. After creating a few little programs, I'm having difficulty
understanding how to create objects that can be shared between dialogs.
Here's some code as an example (apologies for ... |
python introspection not showing functions for Lock
Question: When I try to use introspection to look at what methods are available on
threading.Lock I don't see what I would expect.
Specifically I don't see acquire, release or locked. Why is this?
Here's what I do see:
>>> dir (threading.Lock)
['_... |
Reading and running a mathematical expression in Python
Question: Using Python, how would I go about reading in (be from a string, file or url)
a mathematical expression (1 + 1 is a good start) and executing it?
Aside from grabbing a string, file or url I have no idea of where to start
with this.
Answer: Because pyt... |
Sorting and Grouping Nested Lists in Python
Question: I have the following data structure (a list of lists)
[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somen... |
Unit testing and mocking email sender in Python with Google AppEngine
Question: I'm a newbie to python and the app engine.
I have this code that sends an email based on request params after some auth
logic. in my Unit tests (i'm using
[GAEUnit](http://code.google.com/p/gaeunit/)), how do I confirm an email with
specif... |
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)
Question: Is there any reason to prefer `unicode(somestring, 'utf8')` as opposed to
`somestring.decode('utf8')`?
My only thought is that `.decode()` is a bound method so python may be able to
resolve it more efficiently, but correct me if I'm wrong... |
Using "with" statement for CSV files in Python
Question: Is it possible to use the `with` statement directly with CSV files? It seems
natural to be able to do something like this:
import csv
with csv.reader(open("myfile.csv")) as reader:
# do things with reader
But csv.reader doesn't pr... |
decrypting pdf protected by aes-256bit using the right password
Question: Is there any way to decrypting a pdf protected by an aes-256 bit key?
I have the correct password and I need a command-line tool (or library -
perhaps in python :P ) for decrypting the file and then doing some operation
over it.
The best thing ... |
How do I determine the size of an object in Python?
Question: In C, we can find the size of an `int`, `char`, etc. I want to know how to get
size of objects like a string, integer, etc. in Python.
Related question: [How many bytes per element are there in a Python list
(tuple)?](http://stackoverflow.com/questions/1356... |
Python Path
Question: I am installing active python, django. I really dont know how to set the
python path in vista environment system. first of all will it work in vista.
Answer: # Temporary Change
To change the python path temporarily (i.e., for one interactive session),
just append to `sys.path` like this:
... |
PHP Get Source and Search for Word
Question: I need help i want to code a program that search for a word inside the source
code.
Here a Example in Python:
import urllib2, re
site = "http://stackoverflow.com/"
tosearch = "Questions"
source = urllib2.urlopen(site).read()
if re.search(... |
Python object.__repr__(self) should be an expression?
Question: I was looking at the builtin object methods in the [Python
documentation](http://docs.python.org/reference/datamodel.html#objects-values-
and-types), and I was interested in the documentation for
`object.__repr__(self)`. Here's what it says:
> Called by t... |
How can I test that I have a Python module successfully installed?
Question: I tried to install beautifulsoup. I get such an error:
<\-- snip -->
raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pyd... |
Standard way to embed version into python package?
Question: Is there a standard way to associate version string with a python package in
such way that I could do the following?
import foo
print foo.version
I would imagine there's some way to retrieve that data without any extra
hardcoding, sin... |
Can I get the matrix determinant using Numpy?
Question: I read in the manual of Numpy that there is function `det(M)` that can
calculate the determinant. However, I can't find the `det()` method in Numpy.
By the way, I use Python 2.5. There should be no compatibility problems with
Numpy.
Answer: You can use
[`numpy.... |
How are POST and GET variables handled in Python?
Question: In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string)
variables. What's the equivalent in Python?
Answer: suppose you're posting a html form with this:
<input type="text" name="username">
If using [raw cgi](http://... |
Any Python OLAP/MDX ORM engines?
Question: I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like
Django ORM for Python that would support OLAP.
I'm a Python/Django developer and if there would be something that would have
some level of integration with Django I would be much interested in learning... |
problem using an instance in a with_statement
Question: I've recently started to learn python , and I reached the **with** statement .
I've tried to use it with a class instance , but I think I'm doing something
wrong . Here is the code :
from __future__ import with_statement
import pdb
clas... |
How do I remove VSS hooks from a VS Web Site?
Question: I have a Visual Studio 2008 solution with 7 various projects included with it.
3 of these 'projects' are Web Sites (the kind of project without a project
file).
I have stripped all the various Visual Sourcesafe files from all the
directories, removed the Scc refe... |
Incorrect answer in dll import in Python
Question: In my Python script I'm importing a dll written in VB.NET. I'm calling a
function of initialisation in my script. It takes 2 arguments: a path to XML
file and a string. It returns an integer - 0 for success, else error. The
second argument is passed by reference. So if... |
What's the idiomatic Python equivalent to Django's 'regroup' template tag?
Question: <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup>
I can think of a few ways of doing it with loops but I'd particularly like to
know if there is a neat one-liner.
Answer: Combine
[`itertools.groupby`](http://doc... |
How would you determine where each property and method of a Python class is defined?
Question: Given an instance of some class in Python, it would be useful to be able to
determine which line of source code _defined_ each method and property (e.g.
to implement [1]). For example, given a module ab.py
clas... |
calculate exponential moving average in python
Question: I have a range of dates and a measurement on each of those dates. I'd like to
calculate an exponential moving average for each of the dates. Does anybody
know how to do this?
I'm new to python. It doesn't appear that averages are built into the standard
python l... |
AJAX command-line interface in browser
Question: I'm building a Web app to allow users to view and manipulate data,
particularly numeric and geographic data. It's important that the output be
clear and professional (data grids, Google Map overlays, etc.). But in terms
of the user interface, I'd rather start with the fl... |
How to clear python interpreter console?
Question: Like most Python developers, I typically keep a console window open with the
Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and
prints gets to be cluttered, and sometime... |
Is there a way to loop through a sub section of a list in Python
Question: So for a list that has 1000 elements, I want to loop from 400 to 500. How do
you do it?
I don't see a way by using the for each and for range techniques.
Answer:
for x in thousand[400:500]:
pass
If you are working with an i... |
The right language for OpenGL UI prototyping. Ditching Python
Question: So, I got this idea that I'd try to prototype an experimental user interface
using OpenGL and some physics. I know little about either of the topics, but
am pretty experienced with programming languages such as C++, Java and C#.
After some initial ... |
NumPy, PIL adding an image
Question: I'm trying to add two images together using NumPy and PIL. The way I would do
this in [MATLAB](http://en.wikipedia.org/wiki/MATLAB) would be something like:
>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');... |
Do Python regexes support something like Perl's \G?
Question: I have a Perl regular expression (shown
[here](http://stackoverflow.com/questions/529657/how-do-i-write-a-regex-that-
performs-multiple-substitutions-on-each-line-except/529735#529735), though
understanding the whole thing isn't hopefully necessary to answer... |
Python 2.x gotcha's and landmines
Question: The purpose of my question is to strengthen my knowledge base with Python and
get a better picture of it, which includes knowing its faults and surprises.
To keep things specific, I'm only interested in the CPython interpreter.
I'm looking for something similar to what learn... |
Connecting to MS SQL Server using python on linux with 'Windows Credentials'
Question: Is there any way to connect to an MS SQL Server database with python on linux
using Windows Domain Credentials?
I can connect perfectly fine from my windows machine using Windows
Credentials, but attempting to do the same from a lin... |
Extracting extension from filename in Python
Question: Is there a function to extract the extension from a filename?
Answer: Yes. Use
[`os.path.splitext`](https://docs.python.org/2/library/os.path.html#os.path.splitext):
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefi... |
End of preview. Expand in Data Studio
Stackoverflow Q&A about Python
This dataset is a subset of StackSample. Each row is a text containing a question and the highest rated answer - if it relates to Python.
The relatively contained size of this set might be helpful to deploy as a local RAG application.
- Downloads last month
- 38