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:
Cannot append to a returned list?
def f():
lst = ['a', 'b', 'c']
return lst[1:]
why is f().append('a') is None == True even though f().__class__ is <type 'list'> and f() == ['b', 'c']
A:
Because append() returns None and not the list object. Use
l = f()
l.append('a')
...
A:
Because append() modifies ... | Cannot append to a returned list? | def f():
lst = ['a', 'b', 'c']
return lst[1:]
why is f().append('a') is None == True even though f().__class__ is <type 'list'> and f() == ['b', 'c']
| [
"Because append() returns None and not the list object. Use \nl = f()\nl.append('a')\n...\n\n",
"Because append() modifies the list, but does not return it.\n",
"Try this:\nf()+['a']\n\nHope this helps\n",
"In this context it's always good to be fully aware of the difference between expressions and commands. ... | [
11,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005996439_python.txt |
Q:
Pure python library to read and write jpeg format
guys!
I'm looking for pure python implementation of jpeg writing (reading will be nice, but not necessary) library.
I've founded only TonyJPEG library port at http://mail.python.org/pipermail/image-sig/2004-November/003055.html
But the problem is this library doesn... | Pure python library to read and write jpeg format | guys!
I'm looking for pure python implementation of jpeg writing (reading will be nice, but not necessary) library.
I've founded only TonyJPEG library port at http://mail.python.org/pipermail/image-sig/2004-November/003055.html
But the problem is this library doesn't support writing.
Any ideas?
UPD: I need to modify ... | [
"I don't know of any libraries written in 100% python, however if you just need the library to work in python, then use PIL. It supports reading and writing many different imaging formats, including JPEG. Realistically, it should do everything you need it to do.\n",
"If you want fairly low level access, you can u... | [
6,
1
] | [] | [] | [
"jpeg",
"python"
] | stackoverflow_0005993836_jpeg_python.txt |
Q:
Find Version of Binary File
Does anyone know how I can find the version of a binary file that has been passed to my function?
I got the following code from this page:
def version(fpath):
f = open(fpath, 'rb')
s = f.read(1024)
print s
f.close()
However, this does not give me any useful output sim... | Find Version of Binary File | Does anyone know how I can find the version of a binary file that has been passed to my function?
I got the following code from this page:
def version(fpath):
f = open(fpath, 'rb')
s = f.read(1024)
print s
f.close()
However, this does not give me any useful output similar to what the mentioned websit... | [
"You have a ready-made module for parsing EXE files:\nhttp://code.google.com/p/pefile/\nYou could read it using the following code:\nimport pefile\n\npe = pefile.PE(r'C:\\Windows\\notepad.exe')\nFileVersion = pe.FileInfo[0].StringTable[0].entries['FileVersion']\nProductVersion = pe.FileInfo[0].StringTable[0].ent... | [
9,
4
] | [] | [] | [
"binaryfiles",
"python",
"version"
] | stackoverflow_0005996650_binaryfiles_python_version.txt |
Q:
Efficient way to delete lines from a file in python (and keep the same file name)?
My program is keeping a log for the user. If the log ever gets bigger than a set amount, I want to delete the first 20% of lines.
From similar questions, I've seen suggestions to do read in the old file, and write out all the lines... | Efficient way to delete lines from a file in python (and keep the same file name)? | My program is keeping a log for the user. If the log ever gets bigger than a set amount, I want to delete the first 20% of lines.
From similar questions, I've seen suggestions to do read in the old file, and write out all the lines I want to keep into a new file. However, my files might be too large to be constantly ... | [
"The general method to achieve this for logfiles is 'rotation' - when the logfiles gets older or hits a certain size, you rename it and start writing a new one.\nIf you are using logging module, there is even a preconfigured one - RotatingFileHandler that does this automatically.\nAs for your question: you can only... | [
8,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0005996616_file_python.txt |
Q:
In PyGTK, how do I use a thread?
I have a class that draws a GUI, using gtk.
Clicking a button will call a method that will run some external
programs.
But the GUI may not redraw in the meantime.
One solution may be to use threads. This example creates a thread
outside the GUI class and starts it before calling gt... | In PyGTK, how do I use a thread? | I have a class that draws a GUI, using gtk.
Clicking a button will call a method that will run some external
programs.
But the GUI may not redraw in the meantime.
One solution may be to use threads. This example creates a thread
outside the GUI class and starts it before calling gtk.main().
How do I make a thread outsi... | [
"You don't need another thread to launch an external program, you can use Gtk's idle loop. Here's some pieces of program I wrote to do just that. It had to read the stdout of the program to show parts of it on the GUI as well, so I left that in there. The variable \"job_aborted\" is tied to an \"Abort\" button, ... | [
4
] | [] | [] | [
"gtk",
"multithreading",
"pygtk",
"python"
] | stackoverflow_0005996814_gtk_multithreading_pygtk_python.txt |
Q:
Python rounding error with float numbers
I don't know if this is an obvious bug, but while running a Python script for varying the parameters of a simulation, I realized the results with delta = 0.29 and delta = 0.58 were missing. On investigation, I noticed that the following Python code:
for i_delta in range(0, ... | Python rounding error with float numbers | I don't know if this is an obvious bug, but while running a Python script for varying the parameters of a simulation, I realized the results with delta = 0.29 and delta = 0.58 were missing. On investigation, I noticed that the following Python code:
for i_delta in range(0, 101, 1):
delta = float(i_delta) / 100
(..... | [
"Any number that can't be built from exact powers of two can't be represented exactly as a floating point number; it needs to be approximated. Sometimes the closest approximation will be less than the actual number.\nRead What Every Computer Scientist Should Know About Floating-Point Arithmetic.\n",
"Its very wel... | [
35,
22
] | [] | [] | [
"python"
] | stackoverflow_0005997027_python.txt |
Q:
Sort a list of files using Python
I need to combine a folder full of pdfs into one file. However they must be combined in a certain order. A sample of the file names is:
WR_Mapbook__1.pdf
WR_Mapbook__1a.pdf
WR_Mapbook__2.pdf
WR_Mapbook__2a.pdf
WR_Mapbook__3.pdf
WR_Mapbook__3a.pdf
etc...
The way that... | Sort a list of files using Python | I need to combine a folder full of pdfs into one file. However they must be combined in a certain order. A sample of the file names is:
WR_Mapbook__1.pdf
WR_Mapbook__1a.pdf
WR_Mapbook__2.pdf
WR_Mapbook__2a.pdf
WR_Mapbook__3.pdf
WR_Mapbook__3a.pdf
etc...
The way that they are sorted in windows explorer is... | [
"What you need is to implement \"Natural Order String Comparison\".\nHopefully someone has done this already and shared it.\nEDIT: Here's a brute force example of doing this in Python.\nimport re\n\ndigits = re.compile(r'(\\d+)')\ndef tokenize(filename):\n return tuple(int(token) if match else token\n ... | [
11,
10,
3
] | [] | [] | [
"pdf_generation",
"python",
"sorting"
] | stackoverflow_0005997006_pdf_generation_python_sorting.txt |
Q:
Changing South Migration Directory
How do you change the location where South looks for an app's migrations?
By default, South assumes an app's migrations are in /migrations. However, I've migrated the model of a third-party package which is installed at /usr/local/lib/python-2.6/dist-packages/, so South is lookin... | Changing South Migration Directory | How do you change the location where South looks for an app's migrations?
By default, South assumes an app's migrations are in /migrations. However, I've migrated the model of a third-party package which is installed at /usr/local/lib/python-2.6/dist-packages/, so South is looking for migrations there, instead of the l... | [
"In settings.py:\nSOUTH_MIGRATION_MODULES = {\n 'books': 'myproject.app_name.migrations',\n}\n\n"
] | [
12
] | [] | [] | [
"django",
"django_orm",
"django_south",
"python"
] | stackoverflow_0005994420_django_django_orm_django_south_python.txt |
Q:
Floating point modulus problem
I'm having a problem with modulus on a floating point number in Python. This code:
...
print '(' + repr(olddir) + ' + ' + repr(self.colsize) + ') % (math.pi*2) = ' + repr((olddir+self.colsize)
...
Prints:
(6.281876310240881 + 0.001308996938995747) % (math.pi*2) = 2.9043434324194095e... | Floating point modulus problem | I'm having a problem with modulus on a floating point number in Python. This code:
...
print '(' + repr(olddir) + ' + ' + repr(self.colsize) + ') % (math.pi*2) = ' + repr((olddir+self.colsize)
...
Prints:
(6.281876310240881 + 0.001308996938995747) % (math.pi*2) = 2.9043434324194095e-13
I know floating point numbers a... | [
"Using str() to print a floating point number actually prints a rounded version of the number:\n>>> print repr(math.pi)\n3.1415926535897931\n>>> print str(math.pi)\n3.14159265359\n\nSo we can't really reproduce your results, since we don't know the exact values you are doing the computation with. Obviously, the ex... | [
4,
2
] | [] | [] | [
"floating_point",
"modulus",
"python"
] | stackoverflow_0005997361_floating_point_modulus_python.txt |
Q:
Trouble validating a form in django
I reaaaally don´t know what else to do but come here and ask you guys. Heres the situation:
models.py
class Vote(models.Model):
""" Generic vote model """
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
created = models.DateTimeField(auto... | Trouble validating a form in django | I reaaaally don´t know what else to do but come here and ask you guys. Heres the situation:
models.py
class Vote(models.Model):
""" Generic vote model """
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
created = models.DateTimeField(auto_now_add=True)
objects = models.Mana... | [
"You're overriding the default constuctor so it accepts an queryset, so you should do:\nqs = OptionVote.objects.all()\nform = OptionVoteForm(qs, request.POST)\n\n"
] | [
5
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0005997126_django_django_forms_python.txt |
Q:
Strange python for syntax, how does this work, whats it called?
print max(3 for i in range(4))
#output is 3
Using Python 2.6
The 3 is throwing me off, heres my attempt at explaining whats going on.
for i in range(4) makes a loop that loops 4 times, incrementing i from 0 to 3 at the start of each loop. [no idea wh... | Strange python for syntax, how does this work, whats it called? | print max(3 for i in range(4))
#output is 3
Using Python 2.6
The 3 is throwing me off, heres my attempt at explaining whats going on.
for i in range(4) makes a loop that loops 4 times, incrementing i from 0 to 3 at the start of each loop. [no idea what the 3 means in this context...] max() returns the biggest iterable... | [
"3 for i in range(4) is a generator that yields 3 four times in a row and max takes an iterable and returns the element with the highest value, which is, obviously, three here.\n",
"This evaluates to:\nprint max([3,3,3,3])\n\n... which is an elaborate way to say print 3.\nexpr for x in xs is a generator expressio... | [
14,
11,
7,
3
] | [] | [] | [
"generator_expression",
"python"
] | stackoverflow_0005997540_generator_expression_python.txt |
Q:
Is there a way to pause a Python subprocess, specifically in Ubuntu?
I have a GUI based program where I need the user to be able to pause or resume a subprocess. For example, if I have:
programID = subprocess.Popen("program_name"), shell=True)
Is there a way that I can pause or resume this? I read something abo... | Is there a way to pause a Python subprocess, specifically in Ubuntu? | I have a GUI based program where I need the user to be able to pause or resume a subprocess. For example, if I have:
programID = subprocess.Popen("program_name"), shell=True)
Is there a way that I can pause or resume this? I read something about using SIGTERM but I didn't quite grasp it.
| [
"To pause the process, use\nos.kill(programID.pid, signal.SIGSTOP)\n\nTo resume execution, use\nos.kill(programID.pid, signal.SIGCONT)\n\n"
] | [
8
] | [] | [] | [
"popen",
"python",
"resume",
"subprocess"
] | stackoverflow_0005997829_popen_python_resume_subprocess.txt |
Q:
Could not load library "/usr/lib/pgsql/plpgsql.so" & undefined symbol: PinPortal
I have been running Davical on a CentOS 5 box for a while now with no problems.
Yesterday however, I installed Trac bug-tracker which eventually forced me to run a full update via Yum which updated a whole heap of packages.
I cant see... | Could not load library "/usr/lib/pgsql/plpgsql.so" & undefined symbol: PinPortal | I have been running Davical on a CentOS 5 box for a while now with no problems.
Yesterday however, I installed Trac bug-tracker which eventually forced me to run a full update via Yum which updated a whole heap of packages.
I cant seem to work out exactly what the issue is and time spent googling didn't seem to bring a... | [
"I have had this problem before, although with 8.4 instead of 8.1, but the issue is the same, I believe.\nA recent minor upgrade of all supported maintenance branches of PostgreSQL introduced the function PinPortal in the server, and made PL/pgSQL use it. So if you use a plpgsql.so from the newer version with a se... | [
8
] | [] | [] | [
"centos",
"postgresql",
"python",
"trac"
] | stackoverflow_0005994297_centos_postgresql_python_trac.txt |
Q:
Python - sorted list of lists
Hi all
I am probably missing something obvious
Creating list of lists (in C++ notation "vector\\>"), then trying to sort inner lists ("records") using some of the fields as a sort keys. And it would not work. Tryed two different version: with "lambda" and with "itemgetter". There is n... | Python - sorted list of lists | Hi all
I am probably missing something obvious
Creating list of lists (in C++ notation "vector\\>"), then trying to sort inner lists ("records") using some of the fields as a sort keys. And it would not work. Tryed two different version: with "lambda" and with "itemgetter". There is no error or warning. What am I doing... | [
"sorted returns the new sorted list. You aren't assigning the value to anything. Try:\nself.mx = sorted(self.mx, key=itemgetter(5))\n\n"
] | [
2
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0005998368_list_python_sorting.txt |
Q:
Python Queues appear to be dying
I have a main process that spawns Processes and then those Processes add jobs to a Queue which the main process uses to spawn more processes. And, that works fine for about 20 seconds and then the main process just stops spawning jobs even though it has plenty of jobs in the queue.... | Python Queues appear to be dying | I have a main process that spawns Processes and then those Processes add jobs to a Queue which the main process uses to spawn more processes. And, that works fine for about 20 seconds and then the main process just stops spawning jobs even though it has plenty of jobs in the queue.
here's the code for the job process's... | [
"Not sure if this will be useful, but if your self.page_queue is an instance of Queue (http://docs.python.org/library/queue.html), then get() is blocking by default. Have you verified that the queue isn't empty? It might just be hung waiting for an item. I remember that plagued me when I was using Queues.\nFurther,... | [
1,
1,
0
] | [] | [] | [
"multiprocessing",
"python",
"queue"
] | stackoverflow_0005923200_multiprocessing_python_queue.txt |
Q:
Parsing Data from live website in Python Enumerate problem!
The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like ... | Parsing Data from live website in Python Enumerate problem! | The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like 200 something. Could this be due to the website I'm trying to fet... | [
"Perhaps the number of lines on that web page are fewer than you think? What does this give you?:\nprint max(i for i, _ in enumerate(urllib.urlopen(\"SITE\")))\n\n",
"Aside: Your indentation is stuffed after the while a < 1000: line. Excessive empty lines and one-letter names don't assist the understanding of yo... | [
0,
0
] | [] | [] | [
"enumerate",
"parsing",
"python",
"web"
] | stackoverflow_0005996758_enumerate_parsing_python_web.txt |
Q:
Python - convert comma separated string into reducing string list
Given a Python string like this:
location_in = 'London, Greater London, England, United Kingdom'
I would like to convert it into a list like this:
location_out = ['London, Greater London, England, United Kingdom',
'Greater London, E... | Python - convert comma separated string into reducing string list | Given a Python string like this:
location_in = 'London, Greater London, England, United Kingdom'
I would like to convert it into a list like this:
location_out = ['London, Greater London, England, United Kingdom',
'Greater London, England, United Kingdom',
'England, United Kingdom',
... | [
"location_in = 'London, Greater London, England, United Kingdom'\nlocations = location_in.split(', ')\nlocation_out = [', '.join(locations[n:]) for n in range(len(locations))]\n\n",
"Plenty of ways to do this, but here's one:\ndef splot(data):\n while True:\n yield data\n pre,sep,data=data.partition(',... | [
25,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005998569_python.txt |
Q:
Python - Calling a function from a class
I'm having some trouble calling a function which is within a class in python.
Here is my folder hierarchy.
~/Code/program/main.py
~/Code/program/dc_functions/dcfunc.py
~/Code/program/dc_functions/init.py
Basically, I want to use a function from dcfunc.py inside of main.py... | Python - Calling a function from a class | I'm having some trouble calling a function which is within a class in python.
Here is my folder hierarchy.
~/Code/program/main.py
~/Code/program/dc_functions/dcfunc.py
~/Code/program/dc_functions/init.py
Basically, I want to use a function from dcfunc.py inside of main.py. How would I do this?
Relevant contents of dc... | [
"You need your init.py file to be named __init__.py\nthen use\nfrom dc_functions.dcfunc import function_name\n\nAnd you'll have acccess to the function.\n"
] | [
4
] | [] | [] | [
"class",
"function",
"python"
] | stackoverflow_0005998900_class_function_python.txt |
Q:
Python: Anyway to use map to get first element of a tuple
I have a tuple of tuples and I want to put the first value in each of the tuples into a set. I thought using map() would be a good way of doing this the only thing is I can't find an easy way to access the first element in the tuple. So for example I have t... | Python: Anyway to use map to get first element of a tuple | I have a tuple of tuples and I want to put the first value in each of the tuples into a set. I thought using map() would be a good way of doing this the only thing is I can't find an easy way to access the first element in the tuple. So for example I have the tuple ((1,), (3,)). I'd like to do something like set(map([0... | [
"Use a list comprehension:\ndata = ((1,), (3,))\nprint([x[0] for x in data])\n\n",
"Use operator.itemgetter:\nfrom operator import itemgetter\nmap(itemgetter(0), ((1,), (3,)))\n\nWhile the list comprehensions are generally more readable, itemgetter is closest to what you asked for. It's also a bit faster:\n>>> fr... | [
20,
19,
4,
3,
3,
2,
2,
1
] | [] | [] | [
"map_function",
"python"
] | stackoverflow_0005998835_map_function_python.txt |
Q:
How can a function use variables generated by other (functions) as parameters for itself in python?
I'm learning python and I would like to separate the different processes of my code into different functions. To do that I need to give variables of previous function as a parameter to an other function . I tried so... | How can a function use variables generated by other (functions) as parameters for itself in python? | I'm learning python and I would like to separate the different processes of my code into different functions. To do that I need to give variables of previous function as a parameter to an other function . I tried some thing like this
def F1 (A):
B=A+1
def F2 (B):
C=B+1
print C
F1(1)
F2()
For example in th... | [
"Just return it:\ndef F1 (A):\n return A+1\n\ndef F2 (B):\n C=B+1\n print C\n\n# Then use it as parameter\nF2(F1(1))\n\n",
"EDIT: Since you've edited your post: variables created within functions are local to that function, meaning you can't reference them elsewhere unless you use the global command, e.g. g... | [
3,
2,
1
] | [] | [] | [
"function",
"modular",
"python"
] | stackoverflow_0005998902_function_modular_python.txt |
Q:
SQLAlchemy: can a deferred column be eagerly loaded?
I have a declarative SQLAlchemy object with deferred columns, declared like this:
class Review(Base):
__tablename__ = 'review'
id = Column(Integer, primary_key=True)
name = Column(String(255))
large_field = deferred(Column(Text))
Sometimes I'd ... | SQLAlchemy: can a deferred column be eagerly loaded? | I have a declarative SQLAlchemy object with deferred columns, declared like this:
class Review(Base):
__tablename__ = 'review'
id = Column(Integer, primary_key=True)
name = Column(String(255))
large_field = deferred(Column(Text))
Sometimes I'd like queries to eagerly load these columns, or "undefer" t... | [
"Yep, you can undefer it:\nhttp://www.sqlalchemy.org/docs/orm/mapper_config.html?highlight=deferred#sqlalchemy.orm.undefer\n"
] | [
3
] | [] | [] | [
"eager_loading",
"python",
"sqlalchemy"
] | stackoverflow_0005998256_eager_loading_python_sqlalchemy.txt |
Q:
Better multithreaded use of Python subprocess.Popen & communicate()?
I'm running multiple commands which may take some time, in parallel, on a Linux machine running Python 2.6.
So, I used subprocess.Popen class and process.communicate() method to parallelize execution of mulitple command groups and capture the out... | Better multithreaded use of Python subprocess.Popen & communicate()? | I'm running multiple commands which may take some time, in parallel, on a Linux machine running Python 2.6.
So, I used subprocess.Popen class and process.communicate() method to parallelize execution of mulitple command groups and capture the output at once after execution.
def run_commands(commands, print_lock):
#... | [
"A final result inspired by the comment from J.F.Sebastian.\nhttp://bitbucket.org/daybreaker/kaist-cs443/src/247f9ecf3cee/tools/manage.py\nIt seems to be a Python bug.\n",
"I am not sure it is clear what run_commands needs to be actually doing, but it seems to be simply doing a poll on a subprocess, ignoring the... | [
2,
0,
0
] | [] | [] | [
"multithreading",
"pipe",
"python",
"subprocess"
] | stackoverflow_0004287178_multithreading_pipe_python_subprocess.txt |
Q:
How do I render an Archetypes widget in 'edit' mode in a BrowserView?
I would like to render Plone Archetypes widgets in 'edit' mode in a Products.Five.browser.BrowserView but it seems there is a lot of setup for templates in skins layers that is absent from BrowserView. How do I perform equivalent setup in a Brow... | How do I render an Archetypes widget in 'edit' mode in a BrowserView? | I would like to render Plone Archetypes widgets in 'edit' mode in a Products.Five.browser.BrowserView but it seems there is a lot of setup for templates in skins layers that is absent from BrowserView. How do I perform equivalent setup in a BrowserView?
The resulting form needs to POST to the existing Archetypes logic.... | [
"The best answer to this question as @david-glick and @stevem suggest is: don't do it. If you are going to use AT (Archetypes), use AT best practices; the closest of which are explained here:\n\nhttp://docs.plone.org/old-reference-manuals/plone_3_theming/buildingblocks/skin/templates/how-to-customise-view-or-edit-o... | [
3
] | [] | [] | [
"archetypes",
"plone",
"python"
] | stackoverflow_0005995451_archetypes_plone_python.txt |
Q:
Using mimetools.Message in urllib2.urlopen
I'm using urllib2.urlopen():
req = urllib2.Request('http://www.google.com')
resp = urllib2.urlopen(req)
print resp.info()
print resp.info()['set-cookie']
Date: Sat, 14 May 2011 01:24:12 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charse... | Using mimetools.Message in urllib2.urlopen | I'm using urllib2.urlopen():
req = urllib2.Request('http://www.google.com')
resp = urllib2.urlopen(req)
print resp.info()
print resp.info()['set-cookie']
Date: Sat, 14 May 2011 01:24:12 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=5ec78624283cc0... | [
"Try using getheaders() to get a list of the cookies:\n>>> msg = resp.info()\n>>> msg.getheaders('Set-Cookie')\n['PREF=ID=5975a5ee255f0949:FF=0:TM=1305336283:LM=1305336283:S=1vkES6eF4Yxd-_oM; expires=Mon, 13-May-2013 01:24:43 GMT; path=/; domain=.google.com.au', 'NID=46=lQVFZg6yKUsoWT529Hqp5gA8B_CKYd2epPIbANmw_J0Uz... | [
3
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0005999241_python_urllib2.txt |
Q:
Creating a 2D grid for a board game in python
I'm taking an introductory course to computer science using Python and we were given an exercise to make a board game(dogems). I'm having troubles constructing the board. The program is suppose to take a given argument and, using a function make_board(size), constructs... | Creating a 2D grid for a board game in python | I'm taking an introductory course to computer science using Python and we were given an exercise to make a board game(dogems). I'm having troubles constructing the board. The program is suppose to take a given argument and, using a function make_board(size), constructs a board of equal rows and columns with numbers alo... | [
"Try starting with something really simple, like printing out just the bottom row:\n. 1 2 3 4 5\n\nThat's pretty easy\nprint '.', '1', '2', '3', '4', '5'\n\nNow what if I want to have a variable sized board?\nLet's try a loop\nfor i in range(length+1):\n if i == 0:\n print '.'\n else:\n print i\... | [
8
] | [] | [] | [
"grid",
"python"
] | stackoverflow_0005999751_grid_python.txt |
Q:
Parsing block of text using Python
I am writing a script that will parse a web page, and stick results into MySQL.
Here is an example of HTML content returned that I need to parse:
<TH ALIGN=center COLSPAN=6 BGCOLOR="#C0C0C0"><FONT SIZE="-1">Monthly Totals</FONT></TH> </TR>
<TR><TH ALIGN=center BGCOLOR="#00805c... | Parsing block of text using Python | I am writing a script that will parse a web page, and stick results into MySQL.
Here is an example of HTML content returned that I need to parse:
<TH ALIGN=center COLSPAN=6 BGCOLOR="#C0C0C0"><FONT SIZE="-1">Monthly Totals</FONT></TH> </TR>
<TR><TH ALIGN=center BGCOLOR="#00805c"><FONT SIZE="-1">Hits</FONT></TH>
<TH A... | [
"Use BeautifulSoup, not regular expressions, to parse the HTML (cf. this famous answer)\n",
"Use lxml, not regular expressions, to parse the HTML - as Will said, but with a different preferred tool. lxml is significantly more powerful and robust than BeautifulSoup in my experienced opinion.\n"
] | [
6,
1
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0005997720_html_parsing_python.txt |
Q:
Getting rid of thin border at edge with transparency when antialiasing with Python Image Library
I have a high-resolution image that I want to use as a tiled map overlay using Google Maps API v3.
I used MapTiler to break it into appropriate tiles at the desired zoom levels. That worked well except that there w... | Getting rid of thin border at edge with transparency when antialiasing with Python Image Library | I have a high-resolution image that I want to use as a tiled map overlay using Google Maps API v3.
I used MapTiler to break it into appropriate tiles at the desired zoom levels. That worked well except that there was a thin grey-black border on the tiles that were the edges of the original image.
Following the sugge... | [
"The answer is to change the resampling to BILINEAR (and not BICUBIC, which is what I tried in the Update posted to the question), and then make sure to change any semitransparent pixels to completely transparent pixels.\nAs I said in the Update, the code modifications I made here might not win any awards for elega... | [
2
] | [] | [] | [
"image",
"image_manipulation",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0005986248_image_image_manipulation_image_processing_python_python_imaging_library.txt |
Q:
Pickling a Python Extension type defined as a C struct having PyObject* members
I am running C++ code via Python and would like to pickle an extension type.
So I have a C++ struct (py_db_manager) containing pointers to a database object and a object manager object (both written in C++) that I wrapped with a python... | Pickling a Python Extension type defined as a C struct having PyObject* members | I am running C++ code via Python and would like to pickle an extension type.
So I have a C++ struct (py_db_manager) containing pointers to a database object and a object manager object (both written in C++) that I wrapped with a python type object (t_db_manager). My problem is that this python type needs to know how to... | [
"Because this will be passed to another process, pickling just integer pointers will not work as you would want it to. Different processes use different memory space therefore they don't see the same things.\nSo, to answer your question, you should pickle full objects and reconstruct them from the receiving end.\n"... | [
2
] | [] | [] | [
"c",
"pickle",
"pyobject",
"python",
"struct"
] | stackoverflow_0005996010_c_pickle_pyobject_python_struct.txt |
Q:
How to read a text from input file only after it is updated using python
Actually i will give input from my application1 to input.txt, which intern triggers {used pyinotify} program1 to run this program1 which updates output.txt file, but application1 which is reading from output.txt doesn't wait for program1 to c... | How to read a text from input file only after it is updated using python | Actually i will give input from my application1 to input.txt, which intern triggers {used pyinotify} program1 to run this program1 which updates output.txt file, but application1 which is reading from output.txt doesn't wait for program1 to complete the writing process on the text file(output.txt), It reads the old dat... | [
"There are several ways to watch file changes in Python, most of them are platform-specific. Since you didn't specify your platform, here's a cross-platform package:\nhttp://packages.python.org/watchdog/\nYou should also take a look at the answers for this question:\nHow do I watch a file for changes?\nEdit\nFrom t... | [
3
] | [] | [] | [
"inotify",
"input",
"pyinotify",
"python"
] | stackoverflow_0006000514_inotify_input_pyinotify_python.txt |
Q:
Listen for newly opened windows with a specific title
Is there a way to bind the execution of some Python code to the opening of a window with a specific title?
I know there are some ways to list all the currently open windows, but it would be nice to not have to constantly poll.
A:
You should look into windows ... | Listen for newly opened windows with a specific title | Is there a way to bind the execution of some Python code to the opening of a window with a specific title?
I know there are some ways to list all the currently open windows, but it would be nice to not have to constantly poll.
| [
"You should look into windows hooks. Specifically, the WH_SHELL hook should allow you to monitor window creation. \n",
"PyAA seems like it might be the only module that will let you do this. The tutorial for it is gone but I managed to find an archived copy of it.\nSection of tutorial covering Event Watchers\nThe... | [
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0005996942_python_windows.txt |
Q:
Web Hosting of Django Application
I found a nice project management app written in Django (busylissy.com). Unfortunately, the guys write there at the top that they plan to shut it down and published it as open source for further development. I was thinking of hosting it on ixwebhosting.com with the basic linux pro... | Web Hosting of Django Application | I found a nice project management app written in Django (busylissy.com). Unfortunately, the guys write there at the top that they plan to shut it down and published it as open source for further development. I was thinking of hosting it on ixwebhosting.com with the basic linux program, but I'm not sure whether this is ... | [
"It has dependencies that require compiled code (such as PIL). I'm not really sure what the 'basic linux program' is all about, or what you mean by 'self contained', but it would be trivial to install these dependencies on any normal linux machine. You would have trouble on some shared hosting platforms that do not... | [
0,
0
] | [] | [] | [
"django",
"installation",
"python",
"web_hosting"
] | stackoverflow_0006000353_django_installation_python_web_hosting.txt |
Q:
Tkinter bind problem
I have something like this:
from Tkinter import *
root = Tk()
root.title("Test")
def _quit():
root.destroy()
m = Menu(root)
root.config(menu=m)
fm = Menu(m, tearoff=0)
m.add_cascade(label="File", menu=fm)
fm.add_command(label="Quit", command=_quit, accelerator='Ctrl+Q')
root.bind('<Co... | Tkinter bind problem | I have something like this:
from Tkinter import *
root = Tk()
root.title("Test")
def _quit():
root.destroy()
m = Menu(root)
root.config(menu=m)
fm = Menu(m, tearoff=0)
m.add_cascade(label="File", menu=fm)
fm.add_command(label="Quit", command=_quit, accelerator='Ctrl+Q')
root.bind('<Control-Q>', _quit())
root.b... | [
"When you are binding with Tkinter you typically do not call the function you wish to bind. \nYou're supposed to use the line \nroot.bind('<Control-Q>', _quit) \n\ninstead of \nroot.bind('<Control-Q>', _quit())\n\nTake note of the lack of parentheses behind _quit. \nThis code below should work. \nfrom Tkinter impo... | [
8,
6
] | [] | [] | [
"bind",
"menu",
"python",
"tkinter"
] | stackoverflow_0005994509_bind_menu_python_tkinter.txt |
Q:
How to parse a date and only the date from a `date_string` in python?
I have a variable containing a string from which I want to parse the date. I tryed this:
import datetime
date_string = "July 2010"
parsed_date = datetime.datetime.strptime(date_string, "%B %Y")
print parsed_date
# datetime.datetime(2010, 7, 1, 0... | How to parse a date and only the date from a `date_string` in python? | I have a variable containing a string from which I want to parse the date. I tryed this:
import datetime
date_string = "July 2010"
parsed_date = datetime.datetime.strptime(date_string, "%B %Y")
print parsed_date
# datetime.datetime(2010, 7, 1, 0, 0))
I assume the 1 is added by datetime, because a date must have a day?... | [
"Simply call .date() on the datetime object. This returns a date object.\nIn [5]: dt\nOut[5]: datetime.datetime(2010, 7, 1, 0, 0)\nIn [6]: dt.date()\nOut[6]: datetime.date(2010, 7, 1)\n\nFor your other subquestions:\n\nYes, the 0, 0 is the time.\nA date always has year, month and day (with 1 <= day <= 31).\n\n"
] | [
4
] | [] | [] | [
"date",
"parsing",
"python"
] | stackoverflow_0006000784_date_parsing_python.txt |
Q:
Best style for iterating over a small number of items in Python?
I was just reading a presentation on python and I noted that the author had missed out the round brackets of the tuple for the items to iterate over, and it struck me that I might be inclined to leave them in. A quick re-read of PEP-8 gave no definit... | Best style for iterating over a small number of items in Python? | I was just reading a presentation on python and I noted that the author had missed out the round brackets of the tuple for the items to iterate over, and it struck me that I might be inclined to leave them in. A quick re-read of PEP-8 gave no definitive answer, and I didn't want to 'fall-back' on the old "explicit is b... | [
"I make a point to do neither. I've found that code readability improves if you assign the tuple to a descriptive variable. \nFor instance:\nfor name in relative_names:\n print name\n\nvs\nfor name in \"Tyler\", \"Robert\", \"Marla\", \"Chloe\", \"Lou\":\n print name\n\n",
"I would always prefer:\n>>> # S... | [
3,
1,
0,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0006000291_coding_style_python.txt |
Q:
Need help working with self.MemoryDC in wxPython
I'm trying to make a custom text widget that is double buffered (In order to avoid flicker).
However, I'd like to be able to do a few things. Yet, I'm unsure of the exact methods I should use.
The first two are easy I simply want to change the background and foregro... | Need help working with self.MemoryDC in wxPython | I'm trying to make a custom text widget that is double buffered (In order to avoid flicker).
However, I'd like to be able to do a few things. Yet, I'm unsure of the exact methods I should use.
The first two are easy I simply want to change the background and foreground color.
So more or less I want to be able to chang... | [
"I don't understand what you mean by configuring self.Text after it was created. If you want to change the text after you've drawn it - you can't. Once you've drawn it to the DC it's there, and the only way to change it would be to clear the DC and repaint it. In your case, it seems all you need to do when the text... | [
1
] | [] | [] | [
"doublebuffered",
"python",
"widget",
"wxpython"
] | stackoverflow_0005999437_doublebuffered_python_widget_wxpython.txt |
Q:
Python tkinter widgets not showing
I have created two widgets: a label and a canvas they are inside of a class and in the init method of the class. For some reason, none of the widgets show up and it just gives me a blank tkinter window.
def __init__ (self, master):
self.mousepos = 0,0
self.clickpos = 0,0
... | Python tkinter widgets not showing | I have created two widgets: a label and a canvas they are inside of a class and in the init method of the class. For some reason, none of the widgets show up and it just gives me a blank tkinter window.
def __init__ (self, master):
self.mousepos = 0,0
self.clickpos = 0,0
self.poslabel = Label(master, text =... | [
"If that is all of your code, you're forgetting to run the mainloop method of your root window. Window drawing happens via events that are processed by the event loop; if it doesn't run, the windows don't get the opportunity to draw themselves on the screen.\n",
"For reference here is a working version of your co... | [
2,
2
] | [] | [] | [
"python",
"tkinter",
"widget"
] | stackoverflow_0005933993_python_tkinter_widget.txt |
Q:
Python editor with autocompletion function in imported module
is there a python editor has autocompletion function in imported module ?
i think like Jcreator for java function completion and argument hints.
thanks,
Guns
A:
As a geek I'd recommend Emacs + Rope, but more common options are:
PyDev for Eclipse (fr... | Python editor with autocompletion function in imported module | is there a python editor has autocompletion function in imported module ?
i think like Jcreator for java function completion and argument hints.
thanks,
Guns
| [
"As a geek I'd recommend Emacs + Rope, but more common options are:\n\nPyDev for Eclipse (free) \nPyCharm (very good for its price)\n\nYou can find a big list of available Python editors here.\n",
"PyDev for Eclipse supports autocompletion.\n"
] | [
3,
2
] | [] | [] | [
"editor",
"function",
"module",
"object",
"python"
] | stackoverflow_0006000966_editor_function_module_object_python.txt |
Q:
Usage of for and if in Python
Could you please look at the code below:
def search(self, filter):
return [note for note in self.notes if note.match(filter)]
I thought for and if statements require a colon. Above, there is no colon after for and if. And this kind of if and for usage does not look like what ... | Usage of for and if in Python | Could you please look at the code below:
def search(self, filter):
return [note for note in self.notes if note.match(filter)]
I thought for and if statements require a colon. Above, there is no colon after for and if. And this kind of if and for usage does not look like what I read in text books. What I genera... | [
"That's not a mere loop/if, but a list comprehension\nIn particular this piece of code:\nreturn [note for note in self.notes if note.match(filter)]\n\nfor each note in self.notes returns only those notes matching the filter condition.\nThis is basically a filter, but in general you can use list comprehensions also ... | [
9,
3,
1
] | [] | [] | [
"colon",
"for_loop",
"if_statement",
"python"
] | stackoverflow_0006001209_colon_for_loop_if_statement_python.txt |
Q:
Does the MySQLdb module in python returns utf8 encoding or unicode in this case?
Using MySQLdb I connect to a database where everything is stored in the utf8 encoding.
If I do
cursor.execute("SET NAMES utf8")
and fetch some data from the database by another statement. Does that mean, that the strings in
cursor.ex... | Does the MySQLdb module in python returns utf8 encoding or unicode in this case? | Using MySQLdb I connect to a database where everything is stored in the utf8 encoding.
If I do
cursor.execute("SET NAMES utf8")
and fetch some data from the database by another statement. Does that mean, that the strings in
cursor.execute("SELECT ...")
cursor.fetchall()
will be in unicode? Or do I have to turn them f... | [
"From the docs:\n\nconnect(parameters...)\n ... \n\nuse_unicode \n\nIf True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is best to set the default encoding in the server configuration, or client configuration (read with read_default_file). If you ch... | [
10
] | [] | [] | [
"encoding",
"mysql_python",
"python",
"unicode",
"utf_8"
] | stackoverflow_0006001104_encoding_mysql_python_python_unicode_utf_8.txt |
Q:
Using the update method to control sprite animations in Pyglet
I friends, I will be very gratefull for any answer, a thanks in advance, this is my problem:
In pyglet this is the basic code to update a sprite in the screen:
sprite.x=50
pixels=10
def update(dt):
if move_right == True:
sprite.x += pixels ... | Using the update method to control sprite animations in Pyglet | I friends, I will be very gratefull for any answer, a thanks in advance, this is my problem:
In pyglet this is the basic code to update a sprite in the screen:
sprite.x=50
pixels=10
def update(dt):
if move_right == True:
sprite.x += pixels * dt
pyglet.clock.schedule_interval(update, 1/60.0)
This results in... | [
"Here's one way to do it\nsprite.x=20 \npixels=10 \ndef update(dt):\n if sprite.x != 40: \n if move_right == True: \n sprite.x = min(sprite.x + pixels * dt, 40)\npyglet.clock.schedule_interval(update, 1/60.0)\n\n"
] | [
0
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0006001142_pyglet_python.txt |
Q:
Using a Django JSON response object in Javascript
This might be a silly question but I'm rather new to JavaScript.. I have an JSON encoded response of a python dictionairy which I want to use to inject as data in my javascript
However the django return consists of string with a header AND hashmap
HOW, but more imp... | Using a Django JSON response object in Javascript | This might be a silly question but I'm rather new to JavaScript.. I have an JSON encoded response of a python dictionairy which I want to use to inject as data in my javascript
However the django return consists of string with a header AND hashmap
HOW, but more importantly WHERE should the logic of stripping this down ... | [
"Why is your view separate from the (I presume you mean) app logic? Seems like your json_response function is a view, in that it is returning an HttpResponse. You either need to directly return the value from json_response, or leave out the HttpResponse call in that function.\n"
] | [
1
] | [] | [] | [
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0006001004_django_javascript_jquery_python.txt |
Q:
conditional command-line arguments [ possibly using getopt()?? ]
This is related to my previous post here. Running the actual script, I output the result like this:
[root@test_vm /]# torque_history.py -m 4
Job Id User Real User Start Date S End Date Exec Host Queue
----------- ... | conditional command-line arguments [ possibly using getopt()?? ] | This is related to my previous post here. Running the actual script, I output the result like this:
[root@test_vm /]# torque_history.py -m 4
Job Id User Real User Start Date S End Date Exec Host Queue
----------- -------- -------------- -------------- - -------------- ---------... | [
"optparse is pure Python, so I'd forget about getopt() and pull it into your app if need be.\ntry:\n import optparse\nexcept ImportError:\n import external.optparse as optparse\n\nDon't forget to create external/__init__.py.\n"
] | [
1
] | [] | [] | [
"python",
"python_2.4",
"python_2.6"
] | stackoverflow_0006001309_python_python_2.4_python_2.6.txt |
Q:
how to deal with timezone differences in ical standard records using python?
I'm trying to process a ical recurrence record from the python gdata api.
DTEND: 20110421T190000
params for DTEND:
TZID [u'Europe/London']
DTSTART: 20110421T180000
params for DTSTART:
TZID [u'Europe/London']
RRULE: FREQ=WEEKLY;BY... | how to deal with timezone differences in ical standard records using python? | I'm trying to process a ical recurrence record from the python gdata api.
DTEND: 20110421T190000
params for DTEND:
TZID [u'Europe/London']
DTSTART: 20110421T180000
params for DTSTART:
TZID [u'Europe/London']
RRULE: FREQ=WEEKLY;BYDAY=TH
VTIMEZONE
TZID: Europe/London
DAYLIGHT
DTSTART: 19700329T010000... | [
"I've used Pytz before, with great success: http://pytz.sourceforge.net/\n"
] | [
0
] | [] | [] | [
"datetime",
"gdata_api",
"icalendar",
"python",
"python_dateutil"
] | stackoverflow_0006001290_datetime_gdata_api_icalendar_python_python_dateutil.txt |
Q:
python, signal blocking, databases
i have a question about signals and how they being handled when there is a sql command running. Particularly, i have a python script that runs as a process and inside it another process is being created. After that a data base check is being run and inside that database check a ... | python, signal blocking, databases | i have a question about signals and how they being handled when there is a sql command running. Particularly, i have a python script that runs as a process and inside it another process is being created. After that a data base check is being run and inside that database check a tables column NULLEGE attribute is being... | [
"Your MySQL command is a C-call, which blocks the Python interpreter.\nThe cleanest way is probably to use the \"show processlist\" and \"kill\" commands from mysql or mysql-python before you send TERM.\nSee here:\nhttp://www.techrepublic.com/article/how-to-examine-and-kill-mysql-client-processes/5211762\n"
] | [
0
] | [] | [] | [
"linux",
"mysql",
"python",
"signals",
"sqlalchemy"
] | stackoverflow_0005991345_linux_mysql_python_signals_sqlalchemy.txt |
Q:
How to make mod_python to wait for the updated text file to read?
import cgi
def fill():
s = """\
<html><body>
<form method="get" action="./show">
<p>Type a word: <input type="text" name="word">
<input type="submit" value="Submit"</p>
</form></body></html>
"""
return s
# Receive the Request object
def show... | How to make mod_python to wait for the updated text file to read? | import cgi
def fill():
s = """\
<html><body>
<form method="get" action="./show">
<p>Type a word: <input type="text" name="word">
<input type="submit" value="Submit"</p>
</form></body></html>
"""
return s
# Receive the Request object
def show(req):
# The getfirst() method returns the value of the first field ... | [
"Let's say you have three different requests that come in to your application at the same time. All of them are going to be attempting to write to and read from the same files at the same time.\nFor your above code to work with concurrent requests, you need to use unique filenames for each request/response. Come ... | [
0
] | [] | [] | [
"cgi",
"mod_python",
"pyinotify",
"python",
"textinput"
] | stackoverflow_0006000163_cgi_mod_python_pyinotify_python_textinput.txt |
Q:
Reading query parameters from textfile
I want to store the parameters for a mysql-connect in a textfile but do not know, what could be the most elegant way to store them in "query.txt"
The readline() command seemed to be an option but somehow makes thing very inelegant. Can somebody suggest a smooth solution?
than... | Reading query parameters from textfile | I want to store the parameters for a mysql-connect in a textfile but do not know, what could be the most elegant way to store them in "query.txt"
The readline() command seemed to be an option but somehow makes thing very inelegant. Can somebody suggest a smooth solution?
thanks!
open("query.txt")
??? read parameters ho... | [
"Yet another way: let's say you have a text file, params.txt, that contains Python-style dictionary literal that has your parameters. It might look like this:\n# my cool SQL parameters\n{ \"user\": \"lilu\",\n \"passwd\": \"multipass\",\n \"host\": \"woo.foo.baz\",\n \"db\": \"human-resources\" }\n\nYou ... | [
1,
0,
0,
0,
0
] | [] | [] | [
"mysql",
"python",
"text_files"
] | stackoverflow_0005942959_mysql_python_text_files.txt |
Q:
PHP Simple HTML DOM or Python-BSoup: which one is the easier approach?
i am currently working on a approach to parse a site that contains datas on Foundations in Europe.
http://www.foundationfinder.ch/ which has a dataset of 790 foundations. All the data are free to use - with no limitations copyrights on it.
Wha... | PHP Simple HTML DOM or Python-BSoup: which one is the easier approach? | i am currently working on a approach to parse a site that contains datas on Foundations in Europe.
http://www.foundationfinder.ch/ which has a dataset of 790 foundations. All the data are free to use - with no limitations copyrights on it.
What is the goal: i want to parse the data and save it locally: for the sake of... | [
"My two cents is that you must choose according to language you know the best. If I were I would use Python, which has number of libraries and tools, and would be something like a couple of hours job.\nHowever if you are good with Perl or PHP, you must choose one of these languages. Most scripting languages has lib... | [
1,
1,
1
] | [] | [] | [
"lwp",
"parsing",
"perl",
"php",
"python"
] | stackoverflow_0006001966_lwp_parsing_perl_php_python.txt |
Q:
Writing multiple sound files into a single file in python
I have three sound files for example a.wav, b.wav and c.wav . I want to write them into a single file for example all.xmv (extension could be different too) and when I need I want to extract one of them and I want to play it (for example I want to play a.wa... | Writing multiple sound files into a single file in python | I have three sound files for example a.wav, b.wav and c.wav . I want to write them into a single file for example all.xmv (extension could be different too) and when I need I want to extract one of them and I want to play it (for example I want to play a.wav and extract it form all.xmv).
How can I do it in python. I ha... | [
"Would standard tar/zip files work for you?\nhttp://docs.python.org/library/zipfile.html\nhttp://docs.python.org/library/tarfile.html\n",
"If the archive idea (which is btw, the best answer to your question) doesn't suit you, you can fuse the data from several files in one file, e.g. by writing consecutive blocks... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0005998380_python.txt |
Q:
Speeding up numpy.dot
I've got a numpy script that spends about 50% of its runtime in the following code:
s = numpy.dot(v1, v1)
where
v1 = v[1:]
and v is a 4000-element 1D ndarray of float64 stored in contiguous memory (v.strides is (8,)).
Any suggestions for speeding this up?
edit This is on Intel hardware. Here ... | Speeding up numpy.dot | I've got a numpy script that spends about 50% of its runtime in the following code:
s = numpy.dot(v1, v1)
where
v1 = v[1:]
and v is a 4000-element 1D ndarray of float64 stored in contiguous memory (v.strides is (8,)).
Any suggestions for speeding this up?
edit This is on Intel hardware. Here is the output of my numpy.s... | [
"Perhaps the culprit is copying of the arrays passed to dot.\nAs Sven said, the dot product relies on BLAS operations. These operations require arrays stored in contiguous C order. If both arrays passed to dot are in C_CONTIGUOUS, you ought to see better performance.\nOf course, if your two arrays passed to dot are... | [
5,
5,
4,
2
] | [] | [] | [
"dot_product",
"numpy",
"performance",
"python"
] | stackoverflow_0005990577_dot_product_numpy_performance_python.txt |
Q:
Python - reading Oracle from Linux or Windows with the SAME code
here is a background: We have an Oracle server running on Windows. Years ago I wrote a client (windows) which reads data from Oracle, process, create XML and send it back to the instrument (mass spectrometer) controlling software (running on the same... | Python - reading Oracle from Linux or Windows with the SAME code | here is a background: We have an Oracle server running on Windows. Years ago I wrote a client (windows) which reads data from Oracle, process, create XML and send it back to the instrument (mass spectrometer) controlling software (running on the same machine as Oracle). Utility was written in C++ as dll with two wrappe... | [
"Your question \n\nIs it possible to write Python code\n which reads Oracle data residing on\n either\n\ndoes not make much sense this you can access any database in a portable way\nby using the standard Python DB API which is implemented by all related database bindings.\nSo what is the specific problem here?\nI... | [
0,
0
] | [] | [] | [
"client",
"oracle",
"python"
] | stackoverflow_0006002461_client_oracle_python.txt |
Q:
How to convert an activity diagram to a petrinet, synthesize it and then analyse it?
I am doing a project on Petri nets.
I have generated an activity diagram (in the .xmi format) using the UML tool Umbrello. I need to convert it to a Petri net and then synthesize it using the tool Petrify. But in order to conver... | How to convert an activity diagram to a petrinet, synthesize it and then analyse it? | I am doing a project on Petri nets.
I have generated an activity diagram (in the .xmi format) using the UML tool Umbrello. I need to convert it to a Petri net and then synthesize it using the tool Petrify. But in order to convert it to the Petri net, the activity diagram has to be converted into the XML format.
In o... | [
"Conveniently activity diagrams more or less have the semantics of Petri Nets anyway. Here's the deal: you will need to read and parse the activity digram XML first. There are several good options for this in Python; unless your activity diagrams are just massive, you should probably choose one that keeps the who... | [
1
] | [] | [] | [
"activity_diagram",
"petri_net",
"python",
"tool_uml",
"umbrello"
] | stackoverflow_0006003289_activity_diagram_petri_net_python_tool_uml_umbrello.txt |
Q:
Algorithms for mapping data in data mining
I need to scrape some webpages and extract content from them. I'm planning to select some specific keywords and map the data that has some relationship b/w them. But I have no Idea, how I could do that. Could anyone suggest me some algorithms for doing it?.
For example I ... | Algorithms for mapping data in data mining | I need to scrape some webpages and extract content from them. I'm planning to select some specific keywords and map the data that has some relationship b/w them. But I have no Idea, how I could do that. Could anyone suggest me some algorithms for doing it?.
For example I need to download some webpages about apples and ... | [
"You could try algorithms based on term frequency–inverse document frequency TF-IDF, in Java I would recommend Solr ... well actually you could use Solr and access it with python see here\n",
"Have a look at NLTK, Pattern or Orange modules.\nAs a start \"Programming collective intelligence: building smart web 2. ... | [
1,
1
] | [] | [] | [
"data_mining",
"python",
"text_mining",
"web_scraping"
] | stackoverflow_0006001834_data_mining_python_text_mining_web_scraping.txt |
Q:
nosetests -h fails to run with error
I suspect I failed to install nosetests correctly.
I used easy_install nose - output was
Searching for nose
Best match: nose 1.0.0
Processing nose-1.0.0-py2.7.egg
nose 1.0.0 is already the active version in easy-install.pth
Installing nosetests-script.py script to C:\Python27... | nosetests -h fails to run with error | I suspect I failed to install nosetests correctly.
I used easy_install nose - output was
Searching for nose
Best match: nose 1.0.0
Processing nose-1.0.0-py2.7.egg
nose 1.0.0 is already the active version in easy-install.pth
Installing nosetests-script.py script to C:\Python27\Scripts
Installing nosetests.exe script t... | [
"Weird. In nose/core.py the TestProgram constructor calls the parent constructor like this:\n...\nextra_args = {}\nversion = sys.version_info[0:2]\nif version >= (2,7) and version != (3,0):\n extra_args['exit'] = exit\nunittest.TestProgram.__init__(\n self, module=module, defaultTest=defaultTest,\n argv=ar... | [
2
] | [] | [] | [
"nosetests",
"python"
] | stackoverflow_0006003354_nosetests_python.txt |
Q:
Super basic Amazon SimpleDB authentication tutorial?
I'm a Simple DB newb and am looking for some step-by-step instructions about how to generate the correct signature. Some of the tutorials/sample code I'm seeing say it's a combination of a timestamp, the service you're using, and the method you're requesting be ... | Super basic Amazon SimpleDB authentication tutorial? |
I'm a Simple DB newb and am looking for some step-by-step instructions about how to generate the correct signature. Some of the tutorials/sample code I'm seeing say it's a combination of a timestamp, the service you're using, and the method you're requesting be done on that service. Is this correct? I speak python if ... | [
"You'll want to use boto. It's documentation is really great, and they have a page specifically about SimpleDB.\n",
"You may like to view this: http://www.youtube.com/watch?v=9YEGwmYejt4\n"
] | [
2,
1
] | [] | [] | [
"amazon_simpledb",
"amazon_web_services",
"authentication",
"http",
"python"
] | stackoverflow_0006003654_amazon_simpledb_amazon_web_services_authentication_http_python.txt |
Q:
matplotlib annotate xycoords=('data','axes fraction') => TypeError: 'NoneType' object is not iterable
>>> import matplotlib
>>> matplotlib.__version__
'0.99.1.1'
the following code runs:
import matplotlib.pyplot as plt
plt.figure()
ax=plt.axes([.1, .1, .8, .8])
ax.annotate('++++', xy=(.5,.2), xycoords='data')
ax... | matplotlib annotate xycoords=('data','axes fraction') => TypeError: 'NoneType' object is not iterable | >>> import matplotlib
>>> matplotlib.__version__
'0.99.1.1'
the following code runs:
import matplotlib.pyplot as plt
plt.figure()
ax=plt.axes([.1, .1, .8, .8])
ax.annotate('++++', xy=(.5,.2), xycoords='data')
ax.annotate('aaaa', xy=(.5,.4), xycoords='axes fraction')
#ax.annotate('bbbb', xy=(.5,.6), xycoords=('data', ... | [
"Using a tuple to indicate different x and y transforms for annotate was added in matplotlib 1.0. Here's the relevant commit, if anyone's interested. You'll need to upgrade to the latest version to use it.\nFor the second problem, this is actually the documented behavior. (clip_on is a generic matplotlib text ar... | [
5
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005998523_matplotlib_python.txt |
Q:
Error in mod_python code!
import cgi
def fill():
s = """\
<html><body>
<form method="get" action="./show">
<p>Type a word: <input type="text" name="word">
<input type="submit" value="Submit"</p>
</form></body></html>
"""
return s
# Receive the Request object
def show(req):
# The getfirst() method return... | Error in mod_python code! | import cgi
def fill():
s = """\
<html><body>
<form method="get" action="./show">
<p>Type a word: <input type="text" name="word">
<input type="submit" value="Submit"</p>
</form></body></html>
"""
return s
# Receive the Request object
def show(req):
# The getfirst() method returns the value of the first field ... | [
" while flag!=1:\n x=1\n\nThis loop won't ever finish. When is flag ever going to change so that flag != 1 is False? Remember, flag is a local variable so changing it anywhere else isn't going to have an effect -- especially since no other code is going to have the opportunity to run while that loop is st... | [
2,
0
] | [] | [] | [
"mod_python",
"python"
] | stackoverflow_0006003932_mod_python_python.txt |
Q:
Python recursion not returning value
For some reason x in this code is not updating within the recursion. Shouldn't x update as I'm calling b(c) within a(y)? When x updates in b(c) but doesn't return to
global nested
def extract(nested,depth):
y = depth[0]
depth = depth[1:]
extract = nested[y]
new... | Python recursion not returning value | For some reason x in this code is not updating within the recursion. Shouldn't x update as I'm calling b(c) within a(y)? When x updates in b(c) but doesn't return to
global nested
def extract(nested,depth):
y = depth[0]
depth = depth[1:]
extract = nested[y]
newlist(extract)
return depth
def newlist... | [
"Is this what you are trying to do?\ndef recursiveRef(nested,depth):\n \"\"\"Return element from nested list\n list ->int\n \"\"\"\n if len(depth) == 0:\n return nested\n else:\n return recursiveRef(nested[depth[0]],depth[1:])\n\nprint recursiveRef([[1,2,3],[4,[5,6],7]],[1])\nprint recu... | [
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"recursion",
"return_value"
] | stackoverflow_0006001180_python_recursion_return_value.txt |
Q:
Source large MySQL dump with Python script
I have a huge (1GB+) database dump that I want to load into new databases on other servers. I tried parsing it line by line and executing each into mysql, but it unfortunately doesn't split lines evenly into commands and just fails on the incomplete ones.
filename='/var/t... | Source large MySQL dump with Python script | I have a huge (1GB+) database dump that I want to load into new databases on other servers. I tried parsing it line by line and executing each into mysql, but it unfortunately doesn't split lines evenly into commands and just fails on the incomplete ones.
filename='/var/test.sql'
fp = open(filename)
while True:
... | [
"Assuming queries do end on line boundaries, you could just add lines together until they make a complete query.\nSomething like:\nfilename='/var/test.sql'\nfp = open(filename)\nlines = ''\nwhile True:\n a = fp.readline()\n if not a:\n break\n try:\n cursor.execute(lines + a... | [
1,
1,
0
] | [] | [] | [
"database_backups",
"mysql_python",
"python"
] | stackoverflow_0005991521_database_backups_mysql_python_python.txt |
Q:
Scala: Implementing Java's AspectJ around advice or Python decorators
I have been using Java + AspectJ extensively for my startup. I would love to switch to Scala but I have a common design pattern that I am not sure entirely the best way to implement in Scala.
A tremendous amount of our application uses AspectJ p... | Scala: Implementing Java's AspectJ around advice or Python decorators | I have been using Java + AspectJ extensively for my startup. I would love to switch to Scala but I have a common design pattern that I am not sure entirely the best way to implement in Scala.
A tremendous amount of our application uses AspectJ pointcuts using annotations as the marker.
This is very similar to Python's ... | [
"Incidentally, I am giving a talk at Scala Days 2011 on the same topic. The core idea is the same as Kim's and Dean's example. However, when it comes to the full spectrum of crosscutting concerns, similarity and differences become more nuanced.\nOn one end of the spectrum, there are not-really-crosscutting concerns... | [
12,
9,
5
] | [] | [] | [
"aop",
"aspectj",
"java",
"python",
"scala"
] | stackoverflow_0006002418_aop_aspectj_java_python_scala.txt |
Q:
new sys.path in python
I am having difficulties importing a script from a directory that is not stored in sys.path. I have a script saved as test.py in a directory called "Development" and am trying to add the development directory to sys.path so I can import a function from my current script called index.py.
Her... | new sys.path in python | I am having difficulties importing a script from a directory that is not stored in sys.path. I have a script saved as test.py in a directory called "Development" and am trying to add the development directory to sys.path so I can import a function from my current script called index.py.
Here is my code for index.py:
i... | [
"\nIf you do import test, the function you defined is imported into its own namespace, so you must refer to it as test.printline().\ntest may be the name of another module in your Python path, and since the directory you insert is appended to the path, it will be considered only if test is nowhere else to be found.... | [
3,
1,
1
] | [] | [] | [
"import",
"python",
"sys.path"
] | stackoverflow_0006004240_import_python_sys.path.txt |
Q:
python datetime query
I have a string "Fri, 31 Dec 1999 23:59:59 GMT" which comes from retry-after.
I want to compare this with today's datetime.
I don't understand how to work with GMT.
Can anyone help me out?
A:
Using dateutil and pytz:
import datetime as dt
import dateutil.parser as parser
import pytz
date_s... | python datetime query | I have a string "Fri, 31 Dec 1999 23:59:59 GMT" which comes from retry-after.
I want to compare this with today's datetime.
I don't understand how to work with GMT.
Can anyone help me out?
| [
"Using dateutil and pytz:\nimport datetime as dt\nimport dateutil.parser as parser\nimport pytz\n\ndate_string=\"Fri, 31 Dec 1999 23:59:59 GMT\" \nthen=parser.parse(date_string)\n\neastern=pytz.timezone('US/Eastern')\nnow=eastern.localize(dt.datetime.now())\n\nprint(repr(then))\n# datetime.datetime(1999, 12, 31,... | [
3
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0006004063_datetime_python.txt |
Q:
How to compare columns from two CSV in python?
Hi
I have two CSV files as input, for example:
file1 :
AK163828 chr5 s1 + e1 cttt 4
AK163828 chr5 s2 + e2 gtca 4
AK168688 chr6 s3 + e3 ggcg 4
AK168688 chr6 s4 + e4 tctg 4
file2 :
chr6s3+e3 ggcg
chr5s1+e1 cttt
chr6s4+e4 tata
chr5s2+e2 ggcg
#as you can see the file2 i... | How to compare columns from two CSV in python? | Hi
I have two CSV files as input, for example:
file1 :
AK163828 chr5 s1 + e1 cttt 4
AK163828 chr5 s2 + e2 gtca 4
AK168688 chr6 s3 + e3 ggcg 4
AK168688 chr6 s4 + e4 tctg 4
file2 :
chr6s3+e3 ggcg
chr5s1+e1 cttt
chr6s4+e4 tata
chr5s2+e2 ggcg
#as you can see the file2 is randomly sorted
I want to compare column 1 of fil... | [
"Quick and dirty:\nimport csv\n\nfile1 = 'C:/Users/Me/Desktop/file1'\nfile2 = 'C:/Users/Me/Desktop/file2'\n\nreader1 = csv.reader(open(file1))\nreader2 = csv.reader(open(file2))\n\nF1 = set(''.join(row1[0].strip().split()[1:6]) for row1 in reader1)\nF2 = set(''.join(row2[0].strip().split()) for row2 in reader2)\n\n... | [
3,
1
] | [] | [] | [
"bioinformatics",
"compare",
"csv",
"python"
] | stackoverflow_0006004242_bioinformatics_compare_csv_python.txt |
Q:
Regex + Python - Converting multiple commands into one or fewer commands
Does anyone have an idea on how to convert the following commands into one or fewer commands?
variable = re.search("[a-zA-Z0-9]+[a-zA-Z0-9\-' ]+[a-zA-Z0-9]+", variable).group(0)
variable = re.sub(" {2,}", " ", variable)
variable = re.sub("'{2... | Regex + Python - Converting multiple commands into one or fewer commands | Does anyone have an idea on how to convert the following commands into one or fewer commands?
variable = re.search("[a-zA-Z0-9]+[a-zA-Z0-9\-' ]+[a-zA-Z0-9]+", variable).group(0)
variable = re.sub(" {2,}", " ", variable)
variable = re.sub("'{2,}", "'", variable)
variable = re.sub("\-{2,}", "-", variable)
Kind Regards,
... | [
"This is a start:\nvariable = re.search(\"[a-zA-Z0-9]+[a-zA-Z0-9\\-' ]+[a-zA-Z0-9]+\", variable).group(0)\nvariable = re.sub(\"([ '\\-])\\\\1+\", \"\\\\1\", variable)\n\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006004429_python_regex.txt |
Q:
matplotlib 'auto dimensioning of axes' not showing all datapoints
I recently moved from matplotlib version '0.99.1.1' to '1.0.1'.
A new glitch i'm encountering has to do with "automatic axis dimensioning' ... not all datapoints end up being shown. Here is some code that reproduces my problem, some more discussion... | matplotlib 'auto dimensioning of axes' not showing all datapoints | I recently moved from matplotlib version '0.99.1.1' to '1.0.1'.
A new glitch i'm encountering has to do with "automatic axis dimensioning' ... not all datapoints end up being shown. Here is some code that reproduces my problem, some more discussion is below.
import datetime
from pylab import *
print matplotlib.__versi... | [
"What's happening is that the axis isn't set to \"automatically dimension\" after you call ax.axis(). Calling axis turns off autoscaling (it assumes that if you're manually getting the axis limits, you probably don't want them to change). \nJust add an ax.axis('auto') or an ax.set_autoscale_on() after you plot eve... | [
2
] | [] | [] | [
"matplotlib",
"points",
"python"
] | stackoverflow_0006004669_matplotlib_points_python.txt |
Q:
How to alter the URI in django?
http://packages.python.org/django_simple_feedback/ref/request-response.html tells that the absolute URI is built using the server variables available in this request. So, How can I alter the URI using HttpRequest.build_absolute_uri.
My situation is:
/foo/bar/2/ is the url having... | How to alter the URI in django? | http://packages.python.org/django_simple_feedback/ref/request-response.html tells that the absolute URI is built using the server variables available in this request. So, How can I alter the URI using HttpRequest.build_absolute_uri.
My situation is:
/foo/bar/2/ is the url having corresponding view load_view(request... | [
"You can use django.shortcuts.redirect to redirect to a different location:\ndef load_view(request):\n return redirect('/foo/')\n\nYou will still need a corresponding view setup for that url, of course, as this will cause the user's browser to redirect to /foo/. If you want to change the url without refreshing t... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006004590_django_python.txt |
Q:
What is the reason for an unhandled win32 exception in an installer program?
I got the following message:
An unhandled win32 exception occurred in numpy-1.5.0-sse3.exe [3324].
The exception occurred in the Numpy installer for Python 2.7---I have the latter on the machine.
When I clicked "Yes" for using the selecte... | What is the reason for an unhandled win32 exception in an installer program? | I got the following message:
An unhandled win32 exception occurred in numpy-1.5.0-sse3.exe [3324].
The exception occurred in the Numpy installer for Python 2.7---I have the latter on the machine.
When I clicked "Yes" for using the selected debugger, I got the following message:
The Application Data folder for Visual St... | [
"This is not the reason for the exception. Instead, when you tried to debug the original problem, you encountered a problem with Visual Studio. The Visual Studio error is resolved in the following manner:\nCheck your registry under the following path:\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersi... | [
0
] | [] | [] | [
"numpy",
"python",
"visual_studio_2008",
"winapi",
"windows"
] | stackoverflow_0003718791_numpy_python_visual_studio_2008_winapi_windows.txt |
Q:
How can I play more than one song at a time in PyGame?
I've got it working now but with the time delay is there a better way because I want two different scripts to be working I want to have these playing in this order and have my images come up in order and the images are a long script and have time delays on the... | How can I play more than one song at a time in PyGame? | I've got it working now but with the time delay is there a better way because I want two different scripts to be working I want to have these playing in this order and have my images come up in order and the images are a long script and have time delays on them too.
#!/usr/bin/env python
import pygame
pygame.mixer.init... | [
"Did you check the pygame.Mixer module ? On default, you can play 8 songs simultaneously\nIf you use the pygame.mixer.music, you'll be able to play only one song at the time.\nIf you use the pygame.mixer.sound, you'll be able to play up to 8 songs at the time.\nThe music module is here to stream music (it doesn't l... | [
6,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0006004887_pygame_python.txt |
Q:
I'd like to create an array from a list, but preserve the NaNs and infs
I am parsing a datafile which contains white-space delimited text which was generated from c++. Some of the driving computations will overflow, underflow or generate NaN's. It appears that the the strings "1.#INF00" and "1.#IND00" are not dig... | I'd like to create an array from a list, but preserve the NaNs and infs | I am parsing a datafile which contains white-space delimited text which was generated from c++. Some of the driving computations will overflow, underflow or generate NaN's. It appears that the the strings "1.#INF00" and "1.#IND00" are not digested by numpy.array(), returning an "invalid literal for float()" error. I ... | [
"float('nan') should return NaN and float('inf') should return infinity. At least that's how they work on my interpreter (CPython 2.7). It seems like things were different on some platforms (especially on Windows) back in CPython 2.5, but I doubt you're using such an old version of Python.\nMaybe the problem is wit... | [
4,
1
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0005998706_matplotlib_numpy_python.txt |
Q:
How to retrict access to myapplication.appspot.com - google app engine?
For a google app engine application, I would like to retrict access to myself to my website http://myapplication.appspot.com but at the same time let my android phone app users access it.
My android phone app use GetValue and StoreValue comman... | How to retrict access to myapplication.appspot.com - google app engine? | For a google app engine application, I would like to retrict access to myself to my website http://myapplication.appspot.com but at the same time let my android phone app users access it.
My android phone app use GetValue and StoreValue command from a custom TinyWebdB component from google app inventor to my appspot da... | [
"In your mobile app you should put something unique into the headers sent, or the user-agent string. Then in your python code could you could check for the presence of that value to decide if the visitor is allowed or forbidden (return status code 403).\nTo allow yourself to view the app you should check to see if... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006002180_google_app_engine_python.txt |
Q:
How to define the models with Multiple to Multiple relationship in Google App Engine?
I am writing a Google App Engine application which has a data model with multiple to multiple relationship. I think I am doing it wrong. My data model class definition is:
class Project(db.Model):
name = db.StringProperty()
... | How to define the models with Multiple to Multiple relationship in Google App Engine? | I am writing a Google App Engine application which has a data model with multiple to multiple relationship. I think I am doing it wrong. My data model class definition is:
class Project(db.Model):
name = db.StringProperty()
description = db.TextProperty()
admin = db.ReferenceProperty(Appuser)
website = ... | [
"A quick fix to the circular reference issue is to drop the referance_class when defining admin in Project (it is not required just a validation really). \nclass Project(db.Model):\n admin = db.ReferenceProperty()\n\nIt's not ideal, but should solve the issue.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0006003756_google_app_engine_python_web_applications.txt |
Q:
Django: How to save a formset based on two models
I am having difficult times saving a formset to the database. I have 2 models, one having a ForeignKey to the other(I made some entries for Balanta model in Django admin page):
models.py
class Balanta(models.Model):
data=models.DateField()
class Meta:
... | Django: How to save a formset based on two models | I am having difficult times saving a formset to the database. I have 2 models, one having a ForeignKey to the other(I made some entries for Balanta model in Django admin page):
models.py
class Balanta(models.Model):
data=models.DateField()
class Meta:
ordering=['data']
verbose_name_plural="... | [
"Check this out:\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets\nThis really simplifies the related by foreign-keys use case which should perfectly fit you.\nYou shouldn't iterate over the cleaned_data like you do, a simple form.save() should do it. Also, it strikes me as odd that yo... | [
4
] | [] | [] | [
"django",
"formset",
"python"
] | stackoverflow_0006003984_django_formset_python.txt |
Q:
Running Selenium RC tests in firefox in offline mode
Is there a way to run Selenium test in offline mode? If I set the offline mode in the firefox profile, selenium is stuck at selenium.start(). I'm using the python client driver. The code is as below
sel = selenium('localhost', 4444, '*firefox', 'file:///home/... | Running Selenium RC tests in firefox in offline mode | Is there a way to run Selenium test in offline mode? If I set the offline mode in the firefox profile, selenium is stuck at selenium.start(). I'm using the python client driver. The code is as below
sel = selenium('localhost', 4444, '*firefox', 'file:///home/user/selenium/selenium-python/client-driver-1.0.1/inputs/i... | [
"The following description in a blog helped me to fix the same problem, but using selenium with java junit tests.\nWithout knowing to much about running selenium from python, I do not see where you are starting the selenium RC server with the firefox profile.\ni.e\n\njava -jar selenium-server.jar -firefoxProfileTem... | [
1
] | [] | [] | [
"firefox",
"offline_mode",
"python",
"selenium"
] | stackoverflow_0003155140_firefox_offline_mode_python_selenium.txt |
Q:
Python, trace undefined variables
in my program I have undefined variable somewhere:
global name 'cmd' is not defined
How can I pull out the line number where the variable is being used?
I know where the error is (cmd versus self.cmd). The question is how to get the line number (or why it isnt shown).
Since I wa... | Python, trace undefined variables | in my program I have undefined variable somewhere:
global name 'cmd' is not defined
How can I pull out the line number where the variable is being used?
I know where the error is (cmd versus self.cmd). The question is how to get the line number (or why it isnt shown).
Since I was catching error, I had to traceback.pr... | [
"Where are you running your program? a Python stacktrace usually looks like this:\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'cmd' is not defined\n\nAs you can see it indicates the line where the error is happening.\n",
"The traceback that results from this NameE... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0006005243_python.txt |
Q:
I have problem in sending a data via serial port using python
I am trying to ON my application by sending a command called ON via serial port using PYTHON..I already wrote a program in my controller that when ever i receive a command via serial port it has to perform some operations.
this is my code:
import serial... | I have problem in sending a data via serial port using python | I am trying to ON my application by sending a command called ON via serial port using PYTHON..I already wrote a program in my controller that when ever i receive a command via serial port it has to perform some operations.
this is my code:
import serial
s=serial.Serial(0)
s.write('^ON') #this is my string to ON
s.clo... | [
"Your microcontroller might be expecting \"hardware flow control\", using the RTS/CTS or DSR/DTR pins on the connector. That is, to receive, it may expect the transmitter to \"raise\" a certain pin, to alert the controller to prepare for a transmission. This hardware flow control seems to be getting less common, an... | [
0
] | [] | [] | [
"python",
"serial_port"
] | stackoverflow_0006001087_python_serial_port.txt |
Q:
Trouble with Python Inheritance
The code that I'm acttualy having the problem with is very long, so I made an example that displays my problem.
I have two classes that inherit from a base-class (BaseClass). Both of these classes add some elements to self.Dict. However, they seem to cross contaminate elements. I w... | Trouble with Python Inheritance | The code that I'm acttualy having the problem with is very long, so I made an example that displays my problem.
I have two classes that inherit from a base-class (BaseClass). Both of these classes add some elements to self.Dict. However, they seem to cross contaminate elements. I was expecting c0.Dict to return {'clas... | [
"You hit a python gotcha : mutable default arguments.\nhttp://blog.objectmentor.com/articles/2008/05/22/pythons-mutable-default-problem\nclass BaseClass :\n def __init__ (self, _dict=None) :\n self.Dict = _dict or {}\n\n"
] | [
9
] | [] | [] | [
"class",
"inheritance",
"object",
"python"
] | stackoverflow_0006005316_class_inheritance_object_python.txt |
Q:
Getting global scroll events with PyObjC
How can I get global scroll events with PyObjC? Can it be done with an NSEvent call?
Sample code would be great...
A:
You were on the right track with NSEvent! As long as you don't want to modify the event, but just observe it, it's as easy as calling addGlobalMonitorForE... | Getting global scroll events with PyObjC | How can I get global scroll events with PyObjC? Can it be done with an NSEvent call?
Sample code would be great...
| [
"You were on the right track with NSEvent! As long as you don't want to modify the event, but just observe it, it's as easy as calling addGlobalMonitorForEventsMatchingMask:handler:. Your app will get notified via a callback whenever an event of the type you specify with the mask is posted to another app.* The hand... | [
1
] | [] | [] | [
"macos",
"pyobjc",
"python"
] | stackoverflow_0005999869_macos_pyobjc_python.txt |
Q:
re-calling a function (recursion) vs using the while statement in Python
Okay, I know you can have a program keep running while a certain condition is true using the while statement. However, is it incorrect or bad practice to just recall the function in the else condition like below?
def ask():
me = input("W... | re-calling a function (recursion) vs using the while statement in Python | Okay, I know you can have a program keep running while a certain condition is true using the while statement. However, is it incorrect or bad practice to just recall the function in the else condition like below?
def ask():
me = input("What is your name? ")
if me == "Tom":
print("Hi, Tom!")
else:
... | [
"To be totally honest they both \"work\" it just depends on your user case. Granted you are more likely to hit recursion depth compared to something going wrong with while they both achieve similar results. Really its more simple and in my opinion slightly more pythonic (in this specific case) to use a while loop. ... | [
3,
1,
0,
0
] | [] | [] | [
"python",
"recursion",
"while_loop"
] | stackoverflow_0006005504_python_recursion_while_loop.txt |
Q:
Drawing PyQt Painter
I'm trying to draw a map with pyqt and it does not work. So far either I have no output or I get errors like Seg fault.
Here is the code I'm using now:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Example(QWidget):
def __i... | Drawing PyQt Painter | I'm trying to draw a map with pyqt and it does not work. So far either I have no output or I get errors like Seg fault.
Here is the code I'm using now:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Example(QWidget):
def __init__(self):
supe... | [
"I'm using Python 2.6.6 on old Debian stable.\nYou'll need to offset negative numbers to make them positive, or they'll render \"offscreen\" and won't be visible in your app.\n"
] | [
2
] | [] | [] | [
"graphic",
"pyqt",
"python",
"qt"
] | stackoverflow_0006005593_graphic_pyqt_python_qt.txt |
Q:
Python 2.6 problem: Capturing output from tcpdump subprocess
I am trying to capture the output of a tcpdump/grep pipeline from Python. I am using Python 2.6 on Mac OS 10.6.7.
When I try it with dmesg/grep, the caller receives output from the subprocesses, as expected.
When I try it with tcpdump/grep, select never ... | Python 2.6 problem: Capturing output from tcpdump subprocess | I am trying to capture the output of a tcpdump/grep pipeline from Python. I am using Python 2.6 on Mac OS 10.6.7.
When I try it with dmesg/grep, the caller receives output from the subprocesses, as expected.
When I try it with tcpdump/grep, select never returns anything.
What am I doing wrong?
#! /usr/bin/python
def t... | [
"Try\ncmd2 = ['grep', '--line-buffered', '-a', '-o', '-E', 'Host\\: .*|GET \\/.*']\n\n"
] | [
2
] | [] | [] | [
"macos",
"nonblocking",
"python",
"subprocess",
"tcpdump"
] | stackoverflow_0006005082_macos_nonblocking_python_subprocess_tcpdump.txt |
Q:
Pyparsing - parse jascii text from mixed jascii/ascii text file?
I have a text file with mixed jascii/shift-jis and ascii text. I'm using pyparsing and am unable to tokenize such strings.
Here is an example code:
from pyparsing import *
subrange = r"[\0x%x40-\0x%x7e\0x%x80-\0x%xFC]"
shiftJisChars = u''.join(srang... | Pyparsing - parse jascii text from mixed jascii/ascii text file? | I have a text file with mixed jascii/shift-jis and ascii text. I'm using pyparsing and am unable to tokenize such strings.
Here is an example code:
from pyparsing import *
subrange = r"[\0x%x40-\0x%x7e\0x%x80-\0x%xFC]"
shiftJisChars = u''.join(srange(subrange % (i,i,i,i)) for i in range(0x81,0x9f+1) + range(0xe0,0xfc+... | [
"When you have a problem with non-ASCII characters/bytes, it is rather unhelpful to print them to your console and them copy/past that into your question. What you see is quite often NOT what you have got. You should use the built-in repr() function [Python 3.x: ascii()] to show your data as unambigously as possibl... | [
1,
0,
0
] | [] | [] | [
"ascii",
"parsing",
"pyparsing",
"python",
"shift_jis"
] | stackoverflow_0005886011_ascii_parsing_pyparsing_python_shift_jis.txt |
Q:
Resizing a wxPython Window
Is it possible to make a wxPython window only re-sizable to a certain ratio? I know you can disable resizing; however, I'd like it so when the window was resized it stuck to a certain width to height ratio.
A:
One obvious way to do this would be to bind wx.EVT_SIZE to a function that c... | Resizing a wxPython Window | Is it possible to make a wxPython window only re-sizable to a certain ratio? I know you can disable resizing; however, I'd like it so when the window was resized it stuck to a certain width to height ratio.
| [
"One obvious way to do this would be to bind wx.EVT_SIZE to a function that constrains the aspect ratio. I'm not certain this is The Right Way to do this, but it works:\nimport wx\n\nclass SizeEvent(wx.Frame):\n def __init__(self, parent, id, title):\n wx.Frame.__init__(self, parent, id, title)\n\n ... | [
6
] | [
"I'm not too familiar with wxPython, but can't you just reset the window size to your max/min size that you want once the user pass that? Preferably in the event that detects resizing?\n"
] | [
-1
] | [
"python",
"resize",
"wxpython"
] | stackoverflow_0006005960_python_resize_wxpython.txt |
Q:
How to install PyObjC with Python 3 and Xcode 3 on Mac OS X 10.6
I want to start using PyObjC. I've got Xcode 3 on OS X 10.6
I have both Python 3.2 and 2.6 installed, but I want to use 3.2
I've heard that PyObjC is included and that I just select it in the Xcode New Project dialog, but I don't see the option. This... | How to install PyObjC with Python 3 and Xcode 3 on Mac OS X 10.6 | I want to start using PyObjC. I've got Xcode 3 on OS X 10.6
I have both Python 3.2 and 2.6 installed, but I want to use 3.2
I've heard that PyObjC is included and that I just select it in the Xcode New Project dialog, but I don't see the option. This makes me assume I've missed some install step.
Can someone tell me ho... | [
"PyObjC is installed: /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/\nThe parts you're missing are the Project and File Templates. Apple stopped including those around the time of Leopard, because the Xcode and PyObjC development cycles are not at all synced up.\nYou can download... | [
2
] | [] | [] | [
"macos",
"pyobjc",
"python",
"python_3.x"
] | stackoverflow_0006005676_macos_pyobjc_python_python_3.x.txt |
Q:
How to get access to Gmail in Django
I'm trying to have a page in my webapp with a button 'Connect to Gmail', which sends the user to an authentication page, and when they get back their access token gets saved in my database for later use. I've been literally trying this for weeks, but I can't figure it out. I've... | How to get access to Gmail in Django | I'm trying to have a page in my webapp with a button 'Connect to Gmail', which sends the user to an authentication page, and when they get back their access token gets saved in my database for later use. I've been literally trying this for weeks, but I can't figure it out. I've tried xoauth, but it seems to only work a... | [
"What you are looking for is OpenID. Check if some fits your need here:\nhttp://djangopackages.com/grids/g/facebook-authentication/ (I know they write facebook authentication, though this page includes openid solutions and full featured solutions with Facebook/Twitter login as well)\nI made good experience with dja... | [
0
] | [] | [] | [
"django",
"oauth",
"python"
] | stackoverflow_0006005026_django_oauth_python.txt |
Q:
including a bound string object in regular expression in python
i want to match "stackover" stored in a variable x in "stackoverflow",
using perl i can do this as follows;
$x = "stackover";
$y = "stackoverflow";
if ($y =~ /^$x/){
print "success";
}
how do i do this in python,
i cannot have x variable in the ... | including a bound string object in regular expression in python | i want to match "stackover" stored in a variable x in "stackoverflow",
using perl i can do this as follows;
$x = "stackover";
$y = "stackoverflow";
if ($y =~ /^$x/){
print "success";
}
how do i do this in python,
i cannot have x variable in the regex
reg = re.compile("x") # this will match x instead of matching... | [
"import re\n\nx = 'stackover'\ny = 'stackoverflow'\n\nif re.match(x, y):\n print 'success'\n\nYou can compile and match as follows:\nreg = re.compile(x)\nif reg.match(y):\n print 'success'\n\n",
">>> y = 'stackoverflow'\n>>> x = 'stackover'\n>>> if re.match('^%s' % x, y):\n... print \"success\"\n... \nsucce... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006006268_python_regex.txt |
Q:
Python code as arguments
How to pass a piece of code as arguments to python?
I tried like this, but it didn't work.
$ python3 'print("hello world")'
can't open file 'print(hello': [Errno 2] No such file or directory
A:
python -c 'print("hello world")'
A:
Try
python3 -c 'print("hello world")'
| Python code as arguments | How to pass a piece of code as arguments to python?
I tried like this, but it didn't work.
$ python3 'print("hello world")'
can't open file 'print(hello': [Errno 2] No such file or directory
| [
"python -c 'print(\"hello world\")'\n",
"Try\npython3 -c 'print(\"hello world\")'\n\n"
] | [
8,
3
] | [] | [] | [
"arguments",
"python"
] | stackoverflow_0006006322_arguments_python.txt |
Q:
Python ImportError (Cannot import name Variables)
I have done some research on this question and nothing seems to fix it, I suspect I may be accidentally circularly importing somewhere, but this one has stumped me.
This package is a Python IRC Service framework. The issue occurs when dynamically loading a module (... | Python ImportError (Cannot import name Variables) | I have done some research on this question and nothing seems to fix it, I suspect I may be accidentally circularly importing somewhere, but this one has stumped me.
This package is a Python IRC Service framework. The issue occurs when dynamically loading a module (via imp.load_source()), and the new module tries to imp... | [
"Show the full traceback. Look through it for evidence of (attempted) circular import.\nRun Python with the -v option ... what does that tell you?\nLook at the contents of sys.path and sys.modules just before the error happens.\n\"**ERROR: ModLoad(): Unable to ...\" doesn't look line a Python-raised error. Is that ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006006085_python.txt |
Q:
Making a Ctrl-F Feature for wx.TextCtrl
I'm attempting to make a Ctrl+F (Find) feature for a wx.TextCtrl widget. However I'm unsure of how to highlight certain indexes/phrases. How would I go about this?
A:
How about wx.TextCtrl.SetSelection(from, to)
| Making a Ctrl-F Feature for wx.TextCtrl | I'm attempting to make a Ctrl+F (Find) feature for a wx.TextCtrl widget. However I'm unsure of how to highlight certain indexes/phrases. How would I go about this?
| [
"How about wx.TextCtrl.SetSelection(from, to)\n"
] | [
3
] | [] | [] | [
"find",
"python",
"wxpython",
"wxtextctrl"
] | stackoverflow_0006006359_find_python_wxpython_wxtextctrl.txt |
Q:
DjangoAppEngine TestApp
Need some help starting up the djangoappengine testapp.I followed the instructions at http://www.allbuttonspressed.com/projects/djangoappengine, but when I run ./manage.py runserver . while in the project directory I get the following error:
WARNING 2011-03-24 12:23:21,994 datastore_file... | DjangoAppEngine TestApp | Need some help starting up the djangoappengine testapp.I followed the instructions at http://www.allbuttonspressed.com/projects/djangoappengine, but when I run ./manage.py runserver . while in the project directory I get the following error:
WARNING 2011-03-24 12:23:21,994 datastore_file_stub.py:657] Could not read ... | [
"You probably already solved this, but for future users:\nThe warning can have multiple causes:\n\ndata store is empty, in that case ignore\nwrong permissions on the datastore files\ndata corruption issue\n\nThe error can be solved by updating djangoappengine\n",
"Update to the latest version of google app engine... | [
0,
0
] | [] | [] | [
"django",
"django_nonrel",
"google_app_engine",
"python"
] | stackoverflow_0005423172_django_django_nonrel_google_app_engine_python.txt |
Q:
Vague Image Recognition in Python
So my goal here is to take an image input and get out a list of the shapes contained in it as an output. Of course, the shapes will not be anything like 'triangle' or 'square', but just lists of contiguous pixels of like values.
My first attempt used a recursive algorithm which '... | Vague Image Recognition in Python | So my goal here is to take an image input and get out a list of the shapes contained in it as an output. Of course, the shapes will not be anything like 'triangle' or 'square', but just lists of contiguous pixels of like values.
My first attempt used a recursive algorithm which 'roamed' the image through paths of like... | [
"what you're looking for sounds like \"image segmentation\" (cf http://en.wikipedia.org/wiki/Segmentation_(image_processing) ). Usually a difficult math problem but implemented in OpenCV.\nYou may consider using level sets and the \"Chan-Vese Algorithim\" (cf http://www.univ-pau.fr/~cgout/viscosite/old/20032004/ves... | [
3
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0006006507_image_processing_python.txt |
Q:
In Python, how could I get a user input while simultaneously running the script?
In my program I am trying to take the chat from a website and printing it on my console. While that's going on I'm using raw_input to get chat from whoever is using it. My problem is that raw_input pauses the rest of the script until ... | In Python, how could I get a user input while simultaneously running the script? | In my program I am trying to take the chat from a website and printing it on my console. While that's going on I'm using raw_input to get chat from whoever is using it. My problem is that raw_input pauses the rest of the script until i say something or press enter. Is there a simple way to fix this?
| [
"You have to multithread. One thread for user input and another for the background tasks.\nThe documentation is a bit complex (I'm pretty confused by it), but it's a start: http://docs.python.org/library/threading.html\n",
"You may also want to look into the curses module: http://docs.python.org/library/curses.ht... | [
5,
4
] | [] | [] | [
"chat",
"python",
"raw_input",
"user_input"
] | stackoverflow_0006006669_chat_python_raw_input_user_input.txt |
Q:
How to make a proper error object?
I'm working on making a small Python module. I want this module to return errors, if any occur. What is the proper or standard way to create error objects in Python?
Edit: I'm not really sure how to create my own errors, surely because i am not sure how errors work (i just know ... | How to make a proper error object? | I'm working on making a small Python module. I want this module to return errors, if any occur. What is the proper or standard way to create error objects in Python?
Edit: I'm not really sure how to create my own errors, surely because i am not sure how errors work (i just know how to catch them in try: ... except: ..... | [
"You can create your own exception class by inheriting Exception:\nclass YourError( Exception ): pass\n\nnext just raise it whenever you need to:\nraise YourError(\"error message\")\n\n",
"The question is always:\n\nreturning some error object or\nraising an exception\n\nIt all depends on the individual usecase a... | [
5,
2
] | [] | [] | [
"error_handling",
"python",
"python_module"
] | stackoverflow_0006007047_error_handling_python_python_module.txt |
Q:
Jquery works only on first forloop element?
Here is my Django template:
{% for feed in feeds %}
<div id="feed"><b>At {{feed.location}}:<b> {{feed.msg}}</b></div></br>
<button id="bb{{feed.id}}">Add Comment</button>
<div id="commentbox" style="display:none;">
<form method="post" action="/comment/{... | Jquery works only on first forloop element? | Here is my Django template:
{% for feed in feeds %}
<div id="feed"><b>At {{feed.location}}:<b> {{feed.msg}}</b></div></br>
<button id="bb{{feed.id}}">Add Comment</button>
<div id="commentbox" style="display:none;">
<form method="post" action="/comment/{{feed.id}}/">
{{cform.as_p}}
<inp... | [
"make this change:\n<button class=\"bb\" id=\"bb{{feed.id}}\">Add Comment</button>\n<div class=\"commentbox\" style=\"display:none;\">\n\nand this one:\n$(document).ready(function() {\n $(\".bb\").each(function(){\n $(this).click(function () {\n $(this).next().toggle(\"slow\");\n });\n });\n});\n\nUpda... | [
5,
3
] | [] | [] | [
"django",
"django_templates",
"jquery",
"jquery_selectors",
"python"
] | stackoverflow_0006007056_django_django_templates_jquery_jquery_selectors_python.txt |
Q:
How to prioritize internationalization parameters
given that these all have different values:
HTTP browser accept language header
parameter
HTTP GET human language parameter eg. hl=en or hl=fr
Cookie value for language choice
How should we decide which language to display pages in if deciding based on these va... | How to prioritize internationalization parameters | given that these all have different values:
HTTP browser accept language header
parameter
HTTP GET human language parameter eg. hl=en or hl=fr
Cookie value for language choice
How should we decide which language to display pages in if deciding based on these values? It's also thinkable saving user's preferred langu... | [
"If you have a saved preference somewhere, then that would be the first choice.\nThe cookie value is, presumably, what they chose last time they were around so that would be the first thing to check.\nThe hl parameter is something that Google has figured out and they probably know what they're doing so that seems l... | [
5
] | [] | [] | [
"django",
"google_app_engine",
"internationalization",
"nlp",
"python"
] | stackoverflow_0006006839_django_google_app_engine_internationalization_nlp_python.txt |
Q:
How do I delay a task using Celery?
Not talking about the delay method.
I want to be able to get a task, given it's task_id and change it's ETA on the fly, before it is executed.
For now I have to cancel it, and re-schedule one. Troublesome if the scheduled process involve a lot of stuff.
A:
You should store som... | How do I delay a task using Celery? | Not talking about the delay method.
I want to be able to get a task, given it's task_id and change it's ETA on the fly, before it is executed.
For now I have to cancel it, and re-schedule one. Troublesome if the scheduled process involve a lot of stuff.
| [
"You should store some 'pause' value outside of celery/task queue. I do this with a mailer using celery. I can pause parts of the system by setting values in either memcache or mysql. The tasks then make sure to query the outside resource before executing the task. If it's meant to be paused it sets it does a task.... | [
1,
1
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0003357472_celery_django_python.txt |
Q:
Calling Java Method with variable length argument (varags) from jython
I'm trying to test some Java code with Jython, but I'm stuck with a constructor that uses the ... varags syntax.
I tried these:
MyConstructor(normal_arg, foo1, foo2)
MyConstructor(normal_arg, [foo1, foo2])
MyConstructor(normal_arg, array([foo1,... | Calling Java Method with variable length argument (varags) from jython | I'm trying to test some Java code with Jython, but I'm stuck with a constructor that uses the ... varags syntax.
I tried these:
MyConstructor(normal_arg, foo1, foo2)
MyConstructor(normal_arg, [foo1, foo2])
MyConstructor(normal_arg, array([foo1, foo2], footype))
But none of those worked (edit: sorry, nr. 2 and 3 do wor... | [
"Oooops, never mind. MyConstructor(normal_arg, [foo1, foo2]) actually worked and I misread an error in another line.\n"
] | [
0
] | [] | [] | [
"java",
"jython",
"python",
"testing"
] | stackoverflow_0006007231_java_jython_python_testing.txt |
Q:
Hot deployment using mod_wsgi,python and django on Apache
I have setup an Apache server with mod_wsgi, python_sql, mysql and django.
Everything works fine, except the fact that if I make some code changes, they do not reflect immidiately, though I thing that everything is compiled on the fly when it comes to pytho... | Hot deployment using mod_wsgi,python and django on Apache | I have setup an Apache server with mod_wsgi, python_sql, mysql and django.
Everything works fine, except the fact that if I make some code changes, they do not reflect immidiately, though I thing that everything is compiled on the fly when it comes to python/mod_wsgi.
I have to shut down the server and come back again ... | [
"This is covered by mod_wsgi documentation. See:\nhttp://code.google.com/p/modwsgi/wiki/ReloadingSourceCode\n",
"Just touching the wsgi file allways worked for me.\n"
] | [
7,
3
] | [] | [] | [
"apache2",
"django",
"hotdeploy",
"mod_wsgi",
"python"
] | stackoverflow_0006006666_apache2_django_hotdeploy_mod_wsgi_python.txt |
Q:
python unittesting problem
I have gone through docs but did not understand unittesting in real sense in python.
i have a test code can anyone will tell me how to do unittestng on it?
a = 1
b = 2
def test():
c = a + 2
if c > 5:
z = 7
else:
z = 8
answer = b + z
return answer
... | python unittesting problem |
I have gone through docs but did not understand unittesting in real sense in python.
i have a test code can anyone will tell me how to do unittestng on it?
a = 1
b = 2
def test():
c = a + 2
if c > 5:
z = 7
else:
z = 8
answer = b + z
return answer
| [
"To test your test() method you should create a test file like this \nimport unittest\nfrom your_file import test\n\nclass TestMethodTestCase(unittest.TestCase):\n def test_01a(self):\n \"\"\" test the test method\"\"\"\n self.failUnlessEqual(9, test(a=4, b=2)) # here you write all the use case you... | [
1,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0006005005_python_unit_testing.txt |
Q:
What makes a python tuple?
The following code does not print what I would expect:
#!/usr/bin/env python
print type(1,)
a = 1,
print type(a)
Here is the output:
<type 'int'>
<type 'tuple'>
I understand that the comma makes a into a tuple. But if that is the case how come the original print is not printing a tup... | What makes a python tuple? | The following code does not print what I would expect:
#!/usr/bin/env python
print type(1,)
a = 1,
print type(a)
Here is the output:
<type 'int'>
<type 'tuple'>
I understand that the comma makes a into a tuple. But if that is the case how come the original print is not printing a tuple type but an int?
| [
"Because the tuple syntax inside a function call is also the way parameters are passed:\n>>> print type(1,2)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: type() takes 1 or 3 arguments\n\n>>> print type((1,))\n<type 'tuple'>\n\n>>> a = 1,\n>>> type(a)\n<type 'tuple'>\n\nIt... | [
9,
1,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0006007728_python_tuples.txt |
Q:
How to intersect two horizontal lists using python?
At the code I'm writing I need to intersect two horizontal list like:
listA:
chr1 aatt
chr8 tagg
chr11 aaaa
chr7 gtag
listB
chr8 tagt
chr1 tttt
chr7 gtag
chr11 aaaa
chr9 atat
#This lists are compounded by one str per line, wich it has a... | How to intersect two horizontal lists using python? | At the code I'm writing I need to intersect two horizontal list like:
listA:
chr1 aatt
chr8 tagg
chr11 aaaa
chr7 gtag
listB
chr8 tagt
chr1 tttt
chr7 gtag
chr11 aaaa
chr9 atat
#This lists are compounded by one str per line, wich it has a "/t" in the middle.
#Also note that are in different or... | [
"Convert to sets and intersect: set(a) & set(b)\n",
"Use Python sets\nlistA = (\n ('chr1', 'aatt'),\n ('chr8', 'tagg'),\n ('chr11', 'aaaa'),\n ('chr7', 'gtag'),\n)\n\nlistB = (\n ('chr8', 'tagt'),\n ('chr1', 'tttt'),\n ('chr7', 'gtag'),\n ('chr11','aaaa'),\n ('chr9', 'atat'),\n)\n\ncomb... | [
5,
4,
2,
1,
0
] | [] | [] | [
"intersection",
"list",
"python"
] | stackoverflow_0006005359_intersection_list_python.txt |
Q:
Sum() in python
I have been trying to be comfortable with the sum() in python, I did understand the basic function of sum but as a mathematica backgroud,I was just inquistive to know can we use sum in python in the same way like we do in mathematica for example consider this mathematica module:
Sq[a_, b_] := Modul... | Sum() in python | I have been trying to be comfortable with the sum() in python, I did understand the basic function of sum but as a mathematica backgroud,I was just inquistive to know can we use sum in python in the same way like we do in mathematica for example consider this mathematica module:
Sq[a_, b_] := Module[{m, n}, m = Max[a, ... | [
"sum((m - r + 1) * (n - r + 1) for r in xrange(1,n+1))\n\n\nThere's no implicit multiplication between integers, so you need the *.\nf(x) for x in xes is the general format of a list comprehension, where you want x to iterate through every element of xes, and give back the value f(x).\n\n"
] | [
13
] | [] | [] | [
"python",
"sum"
] | stackoverflow_0006007808_python_sum.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.