content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How can I install argparse in Python 3.1?
I am trying to get argparse to install in Python 3.1, but I get a UnicodeDecodeError out of setup.py when I easy_install it:
(ve31) offline@void (projects) $ easy_install argparse
install_dir /Users/offline/tmp/ve31/lib/python3.1/site-packages/
Searching for argparse
Readi... | How can I install argparse in Python 3.1? | I am trying to get argparse to install in Python 3.1, but I get a UnicodeDecodeError out of setup.py when I easy_install it:
(ve31) offline@void (projects) $ easy_install argparse
install_dir /Users/offline/tmp/ve31/lib/python3.1/site-packages/
Searching for argparse
Reading http://pypi.python.org/simple/argparse/
Read... | [
"I downloaded the file from pypi, unzipped it and ran python3 setup.py install. No errors. That's with Python 3.1.2 on Ubuntu 10.04.\n$ wget http://argparse.googlecode.com/files/argparse-1.2.1.tar.gz\n$ tar -zxvf argparse-1.2.1.tar.gz\n$ cd argparse\n$ python3 setup.py install\n\neasy_install worked as well, but I ... | [
1
] | [] | [] | [
"argparse",
"easy_install",
"python",
"python_3.1"
] | stackoverflow_0004635138_argparse_easy_install_python_python_3.1.txt |
Q:
Why are these strings escaping from my regular expression in python?
In my code, I load up an entire folder into a list and then try to get rid of every file in the list except the .mp3 files.
import os
import re
path = '/home/user/mp3/'
dirList = os.listdir(path)
dirList.sort()
i = 0
for names in dirList:
match... | Why are these strings escaping from my regular expression in python? | In my code, I load up an entire folder into a list and then try to get rid of every file in the list except the .mp3 files.
import os
import re
path = '/home/user/mp3/'
dirList = os.listdir(path)
dirList.sort()
i = 0
for names in dirList:
match = re.search(r'\.mp3', names)
if match:
i = i+1
else:
dirList.... | [
"You are modifying your list inside a loop. That can cause issues. You should loop over a copy of the list instead (for name in dirList[:]:), or create a new list. \nmodifiedDirList = []\nfor name in dirList:\n match = re.search(r'\\.mp3', name)\n if match:\n i += 1\n modifiedDirList.append(name... | [
4,
3,
2
] | [] | [] | [
"iteration",
"list",
"python"
] | stackoverflow_0004636300_iteration_list_python.txt |
Q:
Create list of square powers of numbers in range using generator
I'd like to rewrite this part of code using generator :
basic = []
for x in range(0,11):
basic.append(x**2)
How can I do this ? Tried :
basic.append(x**2 for x in range(0,11))
but it raises syntax error in x**2 part.
A:
You'd be better off us... | Create list of square powers of numbers in range using generator | I'd like to rewrite this part of code using generator :
basic = []
for x in range(0,11):
basic.append(x**2)
How can I do this ? Tried :
basic.append(x**2 for x in range(0,11))
but it raises syntax error in x**2 part.
| [
"You'd be better off using list comprehension:\nbasic = [x*x for x in range(11)]\n\n",
"You are mistaken; your code doesn't produce a syntax error, it just does the wrong thing:\n>>> basic = []\n>>> basic.append(x**2 for x in range(0,11))\n>>> basic\n[<generator object <genexpr> at 0x01E9AD78>]\n>>>\n\nIf you mus... | [
20,
9,
1,
0
] | [] | [] | [
"generator",
"python",
"range"
] | stackoverflow_0004636656_generator_python_range.txt |
Q:
Using Python simplejson for transmitting JSON to another server results in unicode encoding problems
I'm encoding a string with Python's simplejson library with special characters:
hello testing
spécißl characters
plusses: +++++
special chars :œ∑´®†¥¨ˆøπ“ß∂ƒ©˙∆˚¬Ω≈ç√∫˜µ≤≥
However, when I encode it and transmit ... | Using Python simplejson for transmitting JSON to another server results in unicode encoding problems | I'm encoding a string with Python's simplejson library with special characters:
hello testing
spécißl characters
plusses: +++++
special chars :œ∑´®†¥¨ˆøπ“ß∂ƒ©˙∆˚¬Ω≈ç√∫˜µ≤≥
However, when I encode it and transmit it to the other machine (using POST), it turns out like this:
{'message': ['{"body": "hello testing sp\\u... | [
">>> import json\n\nsimple example, with plusses, Latin1 \"s sharp\", Cyrillic \"capital zhe\"\nNote: ensure that your strings are unicode or ASCII:\n>>> data = {\"body\" : u\"++\\xdf\\u0416\", \"universe\": 42}\n>>> data\n{'body': u'++\\xdf\\u0416', 'universe': 42}\n\nCreate your JSON string, which turns out to be... | [
2,
0
] | [] | [] | [
"json",
"python",
"simplejson",
"unicode"
] | stackoverflow_0004636657_json_python_simplejson_unicode.txt |
Q:
Python equivalent of Sinatra
I know that many people use Sinatra when programming webapps in Ruby because they don't want their framework to get in the way by forcing them to use MVC.
Is there something similar in Python? I'm looking for a framework which provides the glue between Python and the web, and not much ... | Python equivalent of Sinatra | I know that many people use Sinatra when programming webapps in Ruby because they don't want their framework to get in the way by forcing them to use MVC.
Is there something similar in Python? I'm looking for a framework which provides the glue between Python and the web, and not much more. I've looked at Web.py, but i... | [
"Take a look at the Flask microframework\n",
"There are several micro web frameworks. I personally like Bottle\nA good overview list of options exist here.\n"
] | [
23,
13
] | [] | [] | [
"model_view_controller",
"python",
"sinatra",
"web.py"
] | stackoverflow_0004636942_model_view_controller_python_sinatra_web.py.txt |
Q:
What's the next steps for moving from appengine to full django?
I'm super new to programming and I've been using appengine to help me learn python and general coding. I'm getting better quickly and I'm loving it all the way :)
Appengine was awesome for allowing me to just dive into writing my app and getting somet... | What's the next steps for moving from appengine to full django? | I'm super new to programming and I've been using appengine to help me learn python and general coding. I'm getting better quickly and I'm loving it all the way :)
Appengine was awesome for allowing me to just dive into writing my app and getting something live that works (see http://www.7bks.com/). But I'm realising th... | [
"What makes you think you're being locked into a single platform? Did you know that Google's App Engine SDK is open source? Also, there are universities and other organizations who are working on building platforms that will use the App Engine SDK outside of the context of Google? Amazon EC2 is also capable of r... | [
2,
2,
2,
2,
1
] | [] | [] | [
"django",
"google_app_engine",
"hosting",
"python"
] | stackoverflow_0004633329_django_google_app_engine_hosting_python.txt |
Q:
Python: Importing a file from a parent folder
...Now I know this question has been asked many times & I have looked at these other threads. Nothing so far has worked, from using sys.path.append('.') to just import foo.
I have a python file that wishes to import a file (that is in its parent directory). Can you hel... | Python: Importing a file from a parent folder | ...Now I know this question has been asked many times & I have looked at these other threads. Nothing so far has worked, from using sys.path.append('.') to just import foo.
I have a python file that wishes to import a file (that is in its parent directory). Can you help me figure out how my child file can successfully ... | [
"from .. import a\n\nShould do it. This will only work on recent versions of Python--from 2.6, I believe [Edit: since 2.5].\nEach level (Comp and Subcomp) must also be have an __init__.py file for this to work. You've said that they do.\n",
"\nWhen packages are structured into\n subpackages (as with the sound pa... | [
15,
10,
7
] | [] | [] | [
"python"
] | stackoverflow_0004636976_python.txt |
Q:
change the numbers in the 1st column
I know sed or awk can tackle this kind of problem more elegantly perhaps. But I went the python way, so the problem is that I would like to renumber the first column of my data file from 1 to #of lines in the file. Is that a good idea to read the file by readlines? For small fi... | change the numbers in the 1st column | I know sed or awk can tackle this kind of problem more elegantly perhaps. But I went the python way, so the problem is that I would like to renumber the first column of my data file from 1 to #of lines in the file. Is that a good idea to read the file by readlines? For small files perhaps, but large files not I suppose... | [
"Don't do the readlines() at all, and instead:\nfor line in ifile: \n\nAlso, avoid naming variables with the name list. Since list() is a built-in function, you're shadowing that name which is poor practice.\nThere is no need to del a local variable like you've done with del list; this is automatically taken care o... | [
1,
1,
1,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0004636753_file_python.txt |
Q:
django path problem in windows 7
I am having problems with path, of django-admin.py. It is in my python homes scripts folder, and i have setup a PATH variable too. But it is not working at all. Is it because of windows 7!?
EDIT
I am able to use django-admin from command line when i am inside that scripts folder..... | django path problem in windows 7 | I am having problems with path, of django-admin.py. It is in my python homes scripts folder, and i have setup a PATH variable too. But it is not working at all. Is it because of windows 7!?
EDIT
I am able to use django-admin from command line when i am inside that scripts folder..but not from anywhere else.. that is, ... | [
"I believe that your problem is that the django-admin script can not be located when you try to run it from an arbitrary location. Please let me know if that's incorrect. In the future, you should try to provide any error messages that you receive, to help the community help you.\nCan you show us your PATH environm... | [
1
] | [] | [] | [
"django",
"python",
"windows_7"
] | stackoverflow_0004636736_django_python_windows_7.txt |
Q:
translating play in HTML to python
So, I'd like to represent one of Shakespeare's plays, Hamlet, into the following objects (maybe this isn't the best representation, if so please tell me):
class Play():
acts = []
...
def add_act(self, act): acts.append(act)
class Act():
scenes = []
...
def add_scene(... | translating play in HTML to python | So, I'd like to represent one of Shakespeare's plays, Hamlet, into the following objects (maybe this isn't the best representation, if so please tell me):
class Play():
acts = []
...
def add_act(self, act): acts.append(act)
class Act():
scenes = []
...
def add_scene(self, scene): scenes.append(scene)
clas... | [
"Use lxml or a similar parser. They will read your HTML (XML?) into a document tree, which is basically a more generic version of the data structure which you have written.\nYou can then iterate over the tree generated and prune it or rebuild another tree in memory that looks the way you want to. But the HTML -> da... | [
4,
3
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0004637314_html_parsing_python.txt |
Q:
Iron Python : what are good uses for Iron Python
I have an affinity for python, but I work in a .NET environment, so I was looking into Iron Python, and wondering what it would be used for.
Could you write an app in it? or is it for adding a scripting language to your app?
How do you guys use it?
A:
Either or ... | Iron Python : what are good uses for Iron Python | I have an affinity for python, but I work in a .NET environment, so I was looking into Iron Python, and wondering what it would be used for.
Could you write an app in it? or is it for adding a scripting language to your app?
How do you guys use it?
| [
"Either or both :)\nI wouldn't claim to know a specific \"purpose\" for IronPython but it certainly can be used to write applications, and it can be used for scripting within a larger .NET application.\nAside from anything else, it's a handy way of gently easing Python developers into the world of .NET. (Why not le... | [
32,
11,
8,
6,
4,
4,
2,
2,
2,
1,
1,
1
] | [] | [] | [
".net",
"dynamic_language_runtime",
"ironpython",
"python"
] | stackoverflow_0004336228_.net_dynamic_language_runtime_ironpython_python.txt |
Q:
Catching typos in scripting languages
If your scripting language of choice doesn't have something like Perl's strict mode, how are you catching typos? Are you unit testing everything? Every constructor, every method? Is this the only way to go about it?
A:
Really-thorough unit tests are the most important techni... | Catching typos in scripting languages | If your scripting language of choice doesn't have something like Perl's strict mode, how are you catching typos? Are you unit testing everything? Every constructor, every method? Is this the only way to go about it?
| [
"Really-thorough unit tests are the most important technique (yes, I do always aim for 100% coverage), as they also catch many other typos (e.g. where I write + and meant -), off-by-one issues, etc. Integration and load tests exercising every feature are the second line of defense against all kinds of errors (most... | [
34,
3,
3,
2,
1,
1,
1,
0,
0
] | [
"I write all my Python code in eclipse IDE. As Mladen Jablanović has suggested, eclipse underlines suspicious parts.\nNext step is to run the code. Now there are two kinds of errors that I am likely to face.\n\nErrors that the interpreter catches and gives me a line number for: These are typically quite easy to deb... | [
-1
] | [
"groovy",
"python",
"ruby",
"scripting",
"unit_testing"
] | stackoverflow_0002487089_groovy_python_ruby_scripting_unit_testing.txt |
Q:
Python Fast monochromatic bitmap
i want to implement 1024x1024 monochromatic grid , i need read data from any cell and insert rectangles with various dimensions, i have tried to make list in list ( and use it like 2d array ), what i have found is that list of booleans is slower than list of integers.... i have tri... | Python Fast monochromatic bitmap | i want to implement 1024x1024 monochromatic grid , i need read data from any cell and insert rectangles with various dimensions, i have tried to make list in list ( and use it like 2d array ), what i have found is that list of booleans is slower than list of integers.... i have tried 1d list, and it was slower than 2d ... | [
"Raph's suggestin of using array is good, but it won't help on CPython, in fact I'd expect it to be 10-15% slower, however if you use it on PyPy (http://pypy.org/) I'd expect excellent results.\n",
"One thing I might suggest is using Python's built-in array class (http://docs.python.org/library/array.html), with ... | [
2,
0,
0
] | [] | [] | [
"bitmap",
"performance",
"python"
] | stackoverflow_0004637190_bitmap_performance_python.txt |
Q:
Regex: match sequence of not a certain string
s = 'blah blah blah... _ABC_superman_is_cool_CBA_ ...blah blah blah...'
This is just an example, but I want to match everything between _ABC_ and _CBA_. So 'superman_is_cool'. There may be multiple sections of _ABC_..._CBA_.
re.findall('_ABC_(.*)(?=_CBA_)', s)
I trie... | Regex: match sequence of not a certain string | s = 'blah blah blah... _ABC_superman_is_cool_CBA_ ...blah blah blah...'
This is just an example, but I want to match everything between _ABC_ and _CBA_. So 'superman_is_cool'. There may be multiple sections of _ABC_..._CBA_.
re.findall('_ABC_(.*)(?=_CBA_)', s)
I tried this first, but obviously doesn't correctly work ... | [
"I added an additional _ABC_, _CBA_ pair to make sure it finds all the matches:\n>>> s = 'blah blah blah... _ABC_superman_is_cool_CBA_ ...blah blah _ABC_blah_CBA_...'\n>>> re.findall('_ABC_(.*?)_CBA_', s)\n['superman_is_cool', 'blah']\n\nThe ? makes the * operator non-greedy so it finds as short a match as possible... | [
6,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004638040_python_regex.txt |
Q:
python gui programming
What is the difference between Python Tkinter , wxWidgets (or is it called wxPython) and PyQT. Which one is better ?
A:
This really depends on what you're planning to do with them. Are you writing a GUI "hello world", or planning to do something more serious? Is it for commercial or non... | python gui programming | What is the difference between Python Tkinter , wxWidgets (or is it called wxPython) and PyQT. Which one is better ?
| [
"This really depends on what you're planning to do with them. Are you writing a GUI \"hello world\", or planning to do something more serious? Is it for commercial or non-commercial use?\nHere's a comparison of WxWidgets against other platforms. That can get you started on the major points of difference. If you... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004638125_python.txt |
Q:
Using class variable as non-default argument in python
is there a way to keep a private class variable within the class and still use it as the default value to a non-default variable (without defining that value before, outside of the class)?
example:
class a:
def __init__(self):
self.__variable = 6
... | Using class variable as non-default argument in python | is there a way to keep a private class variable within the class and still use it as the default value to a non-default variable (without defining that value before, outside of the class)?
example:
class a:
def __init__(self):
self.__variable = 6
def b(self, value = self.__variable):
print value... | [
"You're overthinking the problem:\nclass a:\n\n def __init__(self):\n self.__variable = 6\n\n def b(self, value=None):\n if value is None:\n value = self.__variable\n print value\n\n",
"\nself.__variable is an instance variable, not a class variable.\nBecause default argument... | [
14,
4,
4
] | [] | [] | [
"class",
"default_value",
"python",
"variables"
] | stackoverflow_0004638008_class_default_value_python_variables.txt |
Q:
Is this method of importing modules, in Python, causing a loop?
app/__ init__.py
from blah import test
app/x.py
from app import *
test()
Basically, I have an __init__.py file that contains a bunch of imports that will be used throughout the app. I've put them all in here to save me having to import them into ea... | Is this method of importing modules, in Python, causing a loop? | app/__ init__.py
from blah import test
app/x.py
from app import *
test()
Basically, I have an __init__.py file that contains a bunch of imports that will be used throughout the app. I've put them all in here to save me having to import them into each file (every file within this folder will use the same imports)
I'm... | [
"Subpackages and modules within a package are never imported when the package is imported unless they are explicitly imported within __init__.py. Even if they were, the most that would happen is that the module would contain a reference to itself, which is not considered a problem.\n"
] | [
4
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0004638259_import_module_python.txt |
Q:
alternative permissions model with repoze.what
I'm writing a web app, and I'd like to use repoze.what & repoze.who to handle my authorisation & authentication. The problem is that repoze.what seems to be hard-coded to accept a certain permissions model, that is:
Visitors to the site are either a logged in user, o... | alternative permissions model with repoze.what | I'm writing a web app, and I'd like to use repoze.what & repoze.who to handle my authorisation & authentication. The problem is that repoze.what seems to be hard-coded to accept a certain permissions model, that is:
Visitors to the site are either a logged in user, or anonymous.
User accounts belong to 0 or more group... | [
"Well, you could easily just have a \"Group_A_commenter\" group and \"Group_B_editor\" group. They don't have to be manually generated. :) Your model is really just a matter of grouping the groups.\nBut you should also be able to make Predicate checkers that implement your rules.\nhttp://what.repoze.org/docs/1.0/Ma... | [
2,
0
] | [] | [] | [
"authentication",
"authorization",
"python",
"web_frameworks"
] | stackoverflow_0004455197_authentication_authorization_python_web_frameworks.txt |
Q:
How are python pages coded and what can the language be compared to?
I have a few questions about python
I've seen many pages like these on Google
http://mail.google.com/support/bin/answer.py?answer=6583
https://www.google.com/adsense/support/bin/topic.py?topic=13488
...that have .py extensions. 1: Are pages lik... | How are python pages coded and what can the language be compared to? | I have a few questions about python
I've seen many pages like these on Google
http://mail.google.com/support/bin/answer.py?answer=6583
https://www.google.com/adsense/support/bin/topic.py?topic=13488
...that have .py extensions. 1: Are pages like these built on pure python code, but printing out html like print "<div ... | [
"\nIt's likely to be pure python code, yes, but it doesn't have to be. It's just a name. Google does use a lot of Python so it's likely to indeed be a Python script yes. Is it \"pure\" Python? Well, what does that mean? It's definitely using several third-party modules, and I don't think it prints out HTML, that wo... | [
2,
1,
1
] | [] | [] | [
"programming_languages",
"python",
"server_side"
] | stackoverflow_0004638341_programming_languages_python_server_side.txt |
Q:
Parsing Data in XML and Storing to DB in Python
Hi Guys i have problem parsing an xml file and entering the data to sqlite, the format is like i need to enter the chracters before the token like 111,AAA,BBB etc
<DOCUMENT>
<PAGE width="544.252" height="634.961" number="1" id="p1">
<MEDIABOX x1="0" y1="0" x2="544.25... | Parsing Data in XML and Storing to DB in Python | Hi Guys i have problem parsing an xml file and entering the data to sqlite, the format is like i need to enter the chracters before the token like 111,AAA,BBB etc
<DOCUMENT>
<PAGE width="544.252" height="634.961" number="1" id="p1">
<MEDIABOX x1="0" y1="0" x2="544.252" y2="634.961"/>
<BLOCK id="p1_b1">
<TEXT width="3... | [
"you mean this?:\n>>> xml = \"\"\"<DOCUMENT>\n... <PAGE width=\"544.252\" height=\"634.961\" number=\"1\" id=\"p1\">\n... <MEDIABOX x1=\"0\" y1=\"0\" x2=\"544.252\" y2=\"634.961\"/>\n... \n... <BLOCK id=\"p1_b1\">\n... \n... <TEXT width=\"37.7\" height=\"74.124\" id=\"p1_t1\" x=\"51.1\" y=\"20.8652\">\n... <TOKEN s... | [
1
] | [] | [] | [
"database",
"python",
"xml"
] | stackoverflow_0004638697_database_python_xml.txt |
Q:
In pygame blit of subsurface cause error that the subsurface is locked
Here is a minimal script to reproduce that
#!/usr/bin/env python
import pygame
screen = pygame.display.set_mode((640, 480))
screen.fill((255, 255, 255))
screen_half = screen.subsurface((0,0, 640/2.0, 480))
print screen.get_locks()
print scree... | In pygame blit of subsurface cause error that the subsurface is locked | Here is a minimal script to reproduce that
#!/usr/bin/env python
import pygame
screen = pygame.display.set_mode((640, 480))
screen.fill((255, 255, 255))
screen_half = screen.subsurface((0,0, 640/2.0, 480))
print screen.get_locks()
print screen_half.get_locks()
screen_half.blit(screen_half, (0, 0))
the output is
()
(... | [
"I had similar problem and pmoreli is right. I just copied subsurface creating new surface and than blit it on display:\nscreen_half = screen_half.copy()\nscreen_half.blit(screen_half, (0, 0))\n\n",
"Probably the lock occurs during the blit.\nYou're blitting a surface into itself, that's why you get the error.\nI... | [
3,
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0004117407_pygame_python.txt |
Q:
Python nested dict comprehension with sets
Can someone explain how to do nested dict comprehensions?
>> l = [set([1, 2, 3]), set([4, 5, 6])]
>> j = dict((a, i) for a in s for i, s in enumerate(l))
>> NameError: name 's' is not defined
I would have liked:
>> j
>> {1:0, 2:0, 3:0, 4: 1, 5: 1, 6: 1}
I just asked a p... | Python nested dict comprehension with sets | Can someone explain how to do nested dict comprehensions?
>> l = [set([1, 2, 3]), set([4, 5, 6])]
>> j = dict((a, i) for a in s for i, s in enumerate(l))
>> NameError: name 's' is not defined
I would have liked:
>> j
>> {1:0, 2:0, 3:0, 4: 1, 5: 1, 6: 1}
I just asked a previous question about a simpler dict comprehens... | [
"Just reverse the order of the two loops:\nj = dict((a, i) for i, s in enumerate(l) for a in s)\n\n"
] | [
5
] | [] | [] | [
"dictionary",
"list_comprehension",
"python"
] | stackoverflow_0004638949_dictionary_list_comprehension_python.txt |
Q:
pyQt "flush" equivalent
Function that is connected to button opens and regexp replace some text:
def process(self):
# first do this!!
self.label.setText('Processing for 5-10 sec.....')
self.button.setEnabled(0)
# and only then heavy files operations
file = open(self.filename, mode='r', encodin... | pyQt "flush" equivalent | Function that is connected to button opens and regexp replace some text:
def process(self):
# first do this!!
self.label.setText('Processing for 5-10 sec.....')
self.button.setEnabled(0)
# and only then heavy files operations
file = open(self.filename, mode='r', encoding='utf-8')
text = re.sub(... | [
"I can imagine two solutions.\nFirst, try calling QCoreApplication.processEvents() after you set the label's text and disable the button.\nSecond, if the first solution doesn't work, split your method in two. Then, in the first method, set the label's text, disable the button, and use QTimer.singleShot() to call yo... | [
1,
0
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0004638649_pyqt_python_qt.txt |
Q:
"Matrix decomposition" of a matrix with holonic sub structure
Before I start, I must say that for those with a background of linear algebra, this is NOT matrix decomposition as you know it. Please read the following paragraphs to get a clearer understanding of the problem I am trying to solve.
Here are the salient... | "Matrix decomposition" of a matrix with holonic sub structure | Before I start, I must say that for those with a background of linear algebra, this is NOT matrix decomposition as you know it. Please read the following paragraphs to get a clearer understanding of the problem I am trying to solve.
Here are the salient properties/definitions of the matrix and its submatrices:
I have ... | [
"I am not sure if i have a understand correctly the problem.\nSo first ypu want to find all submatrixes that conform with your 2 criterea.\nThats like a graph decomposition problem or a set coverage problem i think, where you can have a recursive function and iterate the matrix to find all available submatrixes.\ne... | [
1
] | [] | [] | [
"c#",
"c++",
"python"
] | stackoverflow_0003704566_c#_c++_python.txt |
Q:
Python Twisted Daemon
I have written a simple twisted server -
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.web import server, resource
from twisted.internet import reactor
class Index(resource.Resource):
isLeaf = True
def render_GET(self, request):
args... | Python Twisted Daemon | I have written a simple twisted server -
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.web import server, resource
from twisted.internet import reactor
class Index(resource.Resource):
isLeaf = True
def render_GET(self, request):
args = request.args
pri... | [
"I'd recommend looking into twistd. That way you don't have to worry about handling any of the start up, pid file management, etc. The documentation on their site is quite good: http://twistedmatrix.com/documents/current/core/howto/basics.html. Also check http://twistedmatrix.com/documents/current/core/howto/tap... | [
9,
3
] | [] | [] | [
"python",
"twisted",
"twisted.client",
"twisted.internet",
"twisted.web"
] | stackoverflow_0004617987_python_twisted_twisted.client_twisted.internet_twisted.web.txt |
Q:
Python PYQT QTreeWidgetItem selected cell
I have QTreeWidget like this
What should i do to get value from selected row and filename column ?
I have current selected item
item = self.ui.files_treewidget.currentItem()
but how to access to specific cell?
A:
You can use QTreeWidgetItem.text(column), where colum... | Python PYQT QTreeWidgetItem selected cell | I have QTreeWidget like this
What should i do to get value from selected row and filename column ?
I have current selected item
item = self.ui.files_treewidget.currentItem()
but how to access to specific cell?
| [
"You can use QTreeWidgetItem.text(column), where column is an integer.\nIn your example you would do:\nitem = self.ui.files_treewidget.currentItem()\nfilename = item.text(0)\nsize = item.text(1)\n\n"
] | [
3
] | [] | [] | [
"pyqt",
"python",
"qtreewidget",
"qtreewidgetitem",
"treewidget"
] | stackoverflow_0004638998_pyqt_python_qtreewidget_qtreewidgetitem_treewidget.txt |
Q:
Python: Handle Missing Files from a Sequence
I have a program that's basically as follows:
for l in range(0,100):
file = open("C:/Twitter/json/user_" + str(l) + ".json", "r")
#do some stuff
file.close()
I am trying to figure out a way to handle the exception that will be thrown if say file 20 is missing, and... | Python: Handle Missing Files from a Sequence | I have a program that's basically as follows:
for l in range(0,100):
file = open("C:/Twitter/json/user_" + str(l) + ".json", "r")
#do some stuff
file.close()
I am trying to figure out a way to handle the exception that will be thrown if say file 20 is missing, and tell it to continue. I attempted to use the conti... | [
"Something like :\nimport json\nfor l in xrange(100):\n try:\n with open('C:/Twitter/json/user_%d.json' % l, 'r') as f:\n data = json.load(f)\n #do stuff with obj\n except IOError:\n pass\n\nedit fixed the code.\n",
"you could check file existence and then open it:\nimpor... | [
8,
4
] | [] | [] | [
"continue",
"exception",
"file",
"python",
"sequence"
] | stackoverflow_0004639126_continue_exception_file_python_sequence.txt |
Q:
how to avoid inheritance when using JAXB schemagen?
I'm using JAXB annotations and schemagen maven plugin to create an xsd. I need to process that xsd with wsdl2py to create a Python's client. But as I have inheritance in my classes, schemagen creates something like this:
<xs:complexType name="b">
<xs:complexCon... | how to avoid inheritance when using JAXB schemagen? | I'm using JAXB annotations and schemagen maven plugin to create an xsd. I need to process that xsd with wsdl2py to create a Python's client. But as I have inheritance in my classes, schemagen creates something like this:
<xs:complexType name="b">
<xs:complexContent>
<xs:extension base="a">
<xs:sequence>
... | [
"This is a shortcoming of wsdl2py rather than JAXB, but it's so easy to fix, using XSLT or XQuery. A quick attempt to fix this in XSLT:\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">... | [
0
] | [] | [] | [
"annotations",
"jaxb2",
"python",
"schemagen"
] | stackoverflow_0004327066_annotations_jaxb2_python_schemagen.txt |
Q:
Python script freezes for no apparent reason (afaik)
i'm not particularly new at python but i just thought there might be a reason for this program not working properly. i have written a similar one from which this is derived, and that still works fine. it is a program to graph the average time of a set of ping re... | Python script freezes for no apparent reason (afaik) | i'm not particularly new at python but i just thought there might be a reason for this program not working properly. i have written a similar one from which this is derived, and that still works fine. it is a program to graph the average time of a set of ping responses, to see if there is any pattern in the time over t... | [
"Change\nself.lt = threading.Thread(target=self.loop())\n\nto\nself.lt = threading.Thread(target=self.loop)\n\ntarget=self.loop() calls the loop method before passing the result to threading.Thread. \nPassing target=self.loop passes the method object to threading.Thread without calling it. This lets threading.Threa... | [
6
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004639336_matplotlib_python.txt |
Q:
using the stats package in scipy error in Python?
I am trying to use the scipy stats package in Python and am getting the following error (on Mac OS X):
$ python
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more... | using the stats package in scipy error in Python? | I am trying to use the scipy stats package in Python and am getting the following error (on Mac OS X):
$ python
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy
>>> from scipy import st... | [
"I would recommend using Fink for installing the latest Python and additional packages. Fink's maintainers take care of creating working versions of the programs.\nIf, for whatever reason, you need to manually install Python packages, make sure to set up environment variables as instructed.\n",
"The message is s... | [
1,
1,
0,
0
] | [] | [] | [
"macos",
"numpy",
"python",
"scipy"
] | stackoverflow_0003172431_macos_numpy_python_scipy.txt |
Q:
Eclipse / PyDev running a pyramid development.ini issue "pkg_resources.DistributionNotFound:"
I'm starting out with the Pyramid framework and trying to run this inside of Eclipse.
My run configuration is:
Main Module: /home/ben/env/bin/paster
Program Arguments: serve /home/ben/dev/python/pyramid/firstPyramid/first... | Eclipse / PyDev running a pyramid development.ini issue "pkg_resources.DistributionNotFound:" | I'm starting out with the Pyramid framework and trying to run this inside of Eclipse.
My run configuration is:
Main Module: /home/ben/env/bin/paster
Program Arguments: serve /home/ben/dev/python/pyramid/firstPyramid/first/development.ini
This virtualenv paster will serve development.ini fine from the command line. Howe... | [
"I fixed this by changing the PYHTONPATH property in pydev to also use env/bin.\n"
] | [
1
] | [] | [] | [
"eclipse",
"pydev",
"pylons",
"pyramid",
"python"
] | stackoverflow_0004635003_eclipse_pydev_pylons_pyramid_python.txt |
Q:
Making a change in a module then reloading it
I am adjusting the wxPython DragImage demo, and I have a main file that i execute which imports the DragImage demo... I want to make changes to the DragImage demo then reload the file, to view the changes. For example, i want to insert something in a list on the DragIm... | Making a change in a module then reloading it | I am adjusting the wxPython DragImage demo, and I have a main file that i execute which imports the DragImage demo... I want to make changes to the DragImage demo then reload the file, to view the changes. For example, i want to insert something in a list on the DragImage, then save the DragImage, then when reloading i... | [
"Use the builtin function reload(modulename)\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004639261_python_wxpython.txt |
Q:
render_to_response gives TemplateDoesNotExist
I am obtaining the path of template using
paymenthtml = os.path.join(os.path.dirname(__file__), 'template\\payment.html')
and calling it in another application where
paymenthtml gets copied to payment_template
return render_to_response(self.payment_template, self.co... | render_to_response gives TemplateDoesNotExist | I am obtaining the path of template using
paymenthtml = os.path.join(os.path.dirname(__file__), 'template\\payment.html')
and calling it in another application where
paymenthtml gets copied to payment_template
return render_to_response(self.payment_template, self.context, RequestContext(self.request))
But I get err... | [
"It seems like Django will only load templates if they're in a directory you define in TEMPLATE_DIRS, even if they exist elsewhere.\nTry this in settings.py:\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n# Other settings...\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_ROOT, \"templates\"),\n)\n\nand t... | [
23,
11,
2,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0001957089_django_django_templates_python.txt |
Q:
os.walk with regex
I'd like to get a list of files that apply to a regex that i have. I guess i should use os.walk, but how can i use it with regex?
Thanks.
A:
I'm not aware of anything in the stdlib implementing this, but it is not hard to code:
import os, os.path
def iter_matching(dirpath, regexp):
"""Gen... | os.walk with regex | I'd like to get a list of files that apply to a regex that i have. I guess i should use os.walk, but how can i use it with regex?
Thanks.
| [
"I'm not aware of anything in the stdlib implementing this, but it is not hard to code:\nimport os, os.path\n\ndef iter_matching(dirpath, regexp):\n \"\"\"Generator yielding all files under `dirpath` whose absolute path\n matches the regular expression `regexp`.\n Usage:\n\n >>> for filenam... | [
8,
5
] | [] | [] | [
"os.walk",
"python",
"regex"
] | stackoverflow_0004639506_os.walk_python_regex.txt |
Q:
Why is a method not identical to itself?
The Python documentation about the is operator says:
The operators is and is not test for
object identity: x is y is true if and
only if x and y are the same object. x
is not y yields the inverse truth
value.
Let's try that:
>>> def m():
... pass
...
>>> m is m... | Why is a method not identical to itself? | The Python documentation about the is operator says:
The operators is and is not test for
object identity: x is y is true if and
only if x and y are the same object. x
is not y yields the inverse truth
value.
Let's try that:
>>> def m():
... pass
...
>>> m is m
True
The Python documentation also says:
Du... | [
"When you ask for an attribute of an instance which is a function, you get a bound method: a callable object which wraps the function defined in the class and passes the instance as the first argument. In Python 2.x, when you ask for an attribute of a class which is a function you get a similar proxy object called ... | [
19,
6,
4
] | [] | [] | [
"comparison",
"identity",
"python"
] | stackoverflow_0004639908_comparison_identity_python.txt |
Q:
What icons are available to use when displaying a notification with libnotify?
I'm using the libnotify library to display a notification in Ubuntu. I would ideally like to display a battery of some sort (since my app is a battery meter).
The types of icons I can use are:
a URI specifying the icon file name (e.g... | What icons are available to use when displaying a notification with libnotify? | I'm using the libnotify library to display a notification in Ubuntu. I would ideally like to display a battery of some sort (since my app is a battery meter).
The types of icons I can use are:
a URI specifying the icon file name (e.g. file://path/to/my-icon.png)
a 'stock' icon name. One that would succeed in a call ... | [
"You can easily find out using pygtk itself:\n>>> import gtk\n>>> print \"\\n\".join(name for name in dir(gtk) if name.startswith(\"STOCK_\"))\n\nOn my machine, this prints:\nSTOCK_ABOUT\nSTOCK_ADD\nSTOCK_APPLY\nSTOCK_BOLD\nSTOCK_CANCEL\nSTOCK_CAPS_LOCK_WARNING\nSTOCK_CDROM\nSTOCK_CLEAR\nSTOCK_CLOSE\nSTOCK_COLOR_PI... | [
7,
5
] | [] | [] | [
"libnotify",
"pygtk",
"python"
] | stackoverflow_0003894763_libnotify_pygtk_python.txt |
Q:
How to write choices(clicks) to file
I have and array of arrays of jpgs and an array with the respective ids(from the sqlite db (urls to jpgs ... [[http://xxxxx.xxx/xxx.jpg]]), each element (array of jpgs) is from one or more themes.
What's the easies way to write to file the choice the user makes (thinking of ji... | How to write choices(clicks) to file | I have and array of arrays of jpgs and an array with the respective ids(from the sqlite db (urls to jpgs ... [[http://xxxxx.xxx/xxx.jpg]]), each element (array of jpgs) is from one or more themes.
What's the easies way to write to file the choice the user makes (thinking of jinja2 template with small images and a few ... | [
"First, understand that when you're dealing with a controller action (the code that returns the Jinja2 template and does the querying of your database), you can carry out any kind of action on the server-side that Python (or whatever your server-side language may be) can do. Of course Python can write to a file; t... | [
1
] | [] | [] | [
"html",
"image",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004640248_html_image_python_tkinter_user_interface.txt |
Q:
How to generate shareable links in django? (similar to pastebin links)
One feature I would like to add to my django app is the ability for users to create some content (without signing up / creating an account), and then generating a content-specific link that the users can share with others. Clicking on the link ... | How to generate shareable links in django? (similar to pastebin links) | One feature I would like to add to my django app is the ability for users to create some content (without signing up / creating an account), and then generating a content-specific link that the users can share with others. Clicking on the link would take the user back to the content they created.
Basically, I'd like th... | [
"Usually all that is made up of is a (possibly random, possibly sequential) token, plus the content, stored in a DB and then served up on demand.\n",
"If you don't mind that your URLs will get a bit longer you can have a look at the uuid module. This should guarantee unique IDs.\n",
"You can create these links ... | [
1,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004637480_django_python.txt |
Q:
Can bytes be safely dropped off a UUID and still expect it to retain its uniqeueness?
I wrote the following module which encodes a UUID to an arbitrary base:
http://pypi.python.org/pypi/shortuuid/
Now, this gets it down to 22 symbols with the default alphabet while preserving uniqueness, but I was wondering how ma... | Can bytes be safely dropped off a UUID and still expect it to retain its uniqeueness? | I wrote the following module which encodes a UUID to an arbitrary base:
http://pypi.python.org/pypi/shortuuid/
Now, this gets it down to 22 symbols with the default alphabet while preserving uniqueness, but I was wondering how many (/which) digits I could cut off while maximising the retained uniqueness.
Are all the di... | [
"Because of the way UUID's are constructed, it very much depends on the version. And yes, some will be more random than others.\nhttp://en.wikipedia.org/wiki/Uuid#Version_1_.28MAC_address.29\nOne way to hack around this is by taking a hash (i.e. sha256 for example) of the UUID. Those hashes should be distributed in... | [
4,
1
] | [] | [] | [
"python",
"random",
"uuid"
] | stackoverflow_0004640691_python_random_uuid.txt |
Q:
ANOVA over time in Python, what am I doing?
I really like statistics, but haven't taken a course in over 6 years. I'm having trouble figuring out what kind of test I need here, and the best numpy/scipy/R function to use for these kinds of issues.
I've got a table of visitors and their corresponding properties (e.g... | ANOVA over time in Python, what am I doing? | I really like statistics, but haven't taken a course in over 6 years. I'm having trouble figuring out what kind of test I need here, and the best numpy/scipy/R function to use for these kinds of issues.
I've got a table of visitors and their corresponding properties (e.g. "Browser = Mozilla, Referrer = Google"), as wel... | [
"AFAIK, the statistical tests available in numpy/scipy are fairly basic. You might want to look into R, a language more or less dedicated to statistics, and with a lot of advanced functions available.\nAlso, I don't think a MANOVA is really what you want to do. MANOVA is for when you have several interacting depend... | [
3
] | [] | [] | [
"anova",
"numpy",
"python",
"significance",
"statistics"
] | stackoverflow_0004640798_anova_numpy_python_significance_statistics.txt |
Q:
Threaded Python port scanner
I am having issues with a port scanner I'm editing to use threads.
This is the basics for the original code:
for i in range(0, 2000):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((TargetIP, i))
if(result == 0) :
c = "Port %d: OPEN\n" % (i,)
... | Threaded Python port scanner | I am having issues with a port scanner I'm editing to use threads.
This is the basics for the original code:
for i in range(0, 2000):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((TargetIP, i))
if(result == 0) :
c = "Port %d: OPEN\n" % (i,)
s.close()
This takes approx 33... | [
"This is where your code is failing.\nthreading.Thread(target = ScanLow).start()\nthreading.Thread(target = ScanHigh).start()\n\ne = a + b\n\nwhile e < 2000:\n f = raw_input()\n\nImmediately after you start your threads, you set the value to e. However, you never update e after that, so the loop never exits.\nIt ... | [
5,
1
] | [] | [] | [
"multithreading",
"port_scanning",
"python",
"windows"
] | stackoverflow_0004640527_multithreading_port_scanning_python_windows.txt |
Q:
Django if with booelan property
How can I create an if statement in Python/Django template that compares a booelan property?
Things I've tried so far:
{% ifequal gallery.draft True %}style="display:none"{% endifequal %} -> never
{% if gallery.draft %}style="display:none"{% endif %} -> always
Thanks in advance!
BT... | Django if with booelan property | How can I create an if statement in Python/Django template that compares a booelan property?
Things I've tried so far:
{% ifequal gallery.draft True %}style="display:none"{% endifequal %} -> never
{% if gallery.draft %}style="display:none"{% endif %} -> always
Thanks in advance!
BTW, I'm doing this in the templates be... | [
"Are you sending in \"True\" as a string to the template? That would not show up in a normal template printout. In that case just adding quotes to the first version would work.\n"
] | [
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004638703_django_django_templates_python.txt |
Q:
Error installing a python module
I am trying to install a python module with the standard python setup.py install but I get the following error. I am fairly new to python but I have been able to install other modules in this way in the past. I am under the impression this module setuptools is not something I am su... | Error installing a python module | I am trying to install a python module with the standard python setup.py install but I get the following error. I am fairly new to python but I have been able to install other modules in this way in the past. I am under the impression this module setuptools is not something I am supposed to have gotten separate from my... | [
"Apparently, that package requires you to have setuptools to install it. Setuptools is a module that provides easy installation of Python packages. You can get it on pypi, here.\n",
"Surprisingly, setuptools does NOT come pre-packaged with Python, despite how often and casually everyone refers to it. I also had t... | [
23,
4
] | [] | [] | [
"installation",
"python",
"setuptools",
"windows_7"
] | stackoverflow_0004641131_installation_python_setuptools_windows_7.txt |
Q:
Tkinter in Python.. Tic Tac Toe Game.. Error With the Button!
Im new at tkinter so im a begginer.. I need help because i was trying to programma Tic Tac Toe .. i wanted to start the game with a heart button as zone the when the player click on that the image has to change in X or O (another gif image)...
So i need... | Tkinter in Python.. Tic Tac Toe Game.. Error With the Button! | Im new at tkinter so im a begginer.. I need help because i was trying to programma Tic Tac Toe .. i wanted to start the game with a heart button as zone the when the player click on that the image has to change in X or O (another gif image)...
So i need a function to help me to switch the image in the button but when i... | [
"Try changing it with:\nbutton.config(image=...)\n\nTo find out what image it already has, you'll need to compare:\nbutton.cget(\"image\") == image.name\n\n(Or keep track of its state separately)\nTk isn't object oriented, so although Tkinter tries to make the interface a bit more \"Pythonic\", it can be a bit awkw... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004640158_python_tkinter.txt |
Q:
PHP or Python for Image Processing?
I am writing an application for image processing. I am just wondering which programming language would be the best fit. Python or PHP. This process is system based not web based so I am just thinking if Python could be of more help.
Let me know your thoughts!
A:
Python has stu... | PHP or Python for Image Processing? | I am writing an application for image processing. I am just wondering which programming language would be the best fit. Python or PHP. This process is system based not web based so I am just thinking if Python could be of more help.
Let me know your thoughts!
| [
"Python has stuff like SciPy and PIL so probably Python.\nHere is how people use it:\nPeak detection in a 2D array\nHow can I improve my paw detection?\n",
"One cannot suggest much without knowing the kind of image processing you have in mind.\n\nIf you just want to do some generic rotate/resize/etc then I guess ... | [
5,
2,
1,
1,
0
] | [] | [] | [
"image",
"image_manipulation",
"image_processing",
"php",
"python"
] | stackoverflow_0004641187_image_image_manipulation_image_processing_php_python.txt |
Q:
FULL JOIN in SQLAlchemy?
I would like to display a list of "last entries" in a budget app. The entries (like expenses, income, account transfers, loans) have different columns defined apart from a user_id.
In SQL I would go for a FULL JOIN, but I am using SQLAlchemy (declarative). What is the correct approach here... | FULL JOIN in SQLAlchemy? | I would like to display a list of "last entries" in a budget app. The entries (like expenses, income, account transfers, loans) have different columns defined apart from a user_id.
In SQL I would go for a FULL JOIN, but I am using SQLAlchemy (declarative). What is the correct approach here? Some meta table?
Thanks a lo... | [
"You'll have to use raw SQL if your database supports it or an union otherewise. from http://groups.google.com/group/sqlalchemy/msg/80ea8e712380bff4\n"
] | [
3
] | [] | [] | [
"flask",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004641156_flask_python_sql_sqlalchemy.txt |
Q:
Dynamic dispatch and inheritance in python
I'm trying to modify Guido's multimethod (dynamic dispatch code):
http://www.artima.com/weblogs/viewpost.jsp?thread=101605
to handle inheritance and possibly out of order arguments.
e.g. (inheritance problem)
class A(object):
pass
class B(A):
pass
@multimethod(A,A)
... | Dynamic dispatch and inheritance in python | I'm trying to modify Guido's multimethod (dynamic dispatch code):
http://www.artima.com/weblogs/viewpost.jsp?thread=101605
to handle inheritance and possibly out of order arguments.
e.g. (inheritance problem)
class A(object):
pass
class B(A):
pass
@multimethod(A,A)
def foo(arg1,arg2):
print 'works'
foo(A(),A(... | [
"Regarding the inheritance issue: This can be done with a slight change to MultiMethod. (Iterating through self.typemap and checking with issubclass):\nregistry = {}\n\nclass MultiMethod(object):\n def __init__(self, name):\n self.name = name\n self.typemap = {}\n def __call__(self, *args):\n ... | [
3,
2
] | [] | [] | [
"dynamic_dispatch",
"python"
] | stackoverflow_0004641289_dynamic_dispatch_python.txt |
Q:
Python: Insert QByteArray to SQLite
I'm trying to store image data (screenshots) in SQLite database.now = int(math.floor(time.time()))
ba = QByteArray()
buff = QBuffer(ba)
image.save(buff, format)
params = (str(ba.data()), "image/%s"%format, now, url)
s_conn = sqlite.connect("cache/screenshots_%s.db"%row['size'])
... | Python: Insert QByteArray to SQLite | I'm trying to store image data (screenshots) in SQLite database.now = int(math.floor(time.time()))
ba = QByteArray()
buff = QBuffer(ba)
image.save(buff, format)
params = (str(ba.data()), "image/%s"%format, now, url)
s_conn = sqlite.connect("cache/screenshots_%s.db"%row['size'])
s_curs = s_conn.cursor()
s_curs.execute("... | [
"The biggest issue is that you are trying to store binary as a string by calling str(ba.data). If you do this then it will not be a valid string and will cause endless grief for you later. Behind the scenes SQLite uses Unicode for all strings. However it does not check that a provided string is valid unicode (UT... | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004637436_python_sqlite.txt |
Q:
python 3 https posting very slow
I have a script which logs in via https using python 3 and FancyURLopener.
So I am doing this:
from urllib.request import FancyURLopener, urlopen
from urllib.parse import urlencode
import re, sys
class SMS:
login_url = "url1"
login_act = "url2"
comp_url = "url3"
c... | python 3 https posting very slow | I have a script which logs in via https using python 3 and FancyURLopener.
So I am doing this:
from urllib.request import FancyURLopener, urlopen
from urllib.parse import urlencode
import re, sys
class SMS:
login_url = "url1"
login_act = "url2"
comp_url = "url3"
comp_act = "url4"
LEN = 100
de... | [
"My guess is that there is something subtly different in the requests, that make your server take a very long time in processing the request.\nIf you are the writer of the server, this should be easy to verify. If not you probably have to use some sort of tracing program so you can see when the request is done from... | [
1
] | [] | [] | [
"http",
"post",
"python",
"python_3.x",
"urllib"
] | stackoverflow_0004640803_http_post_python_python_3.x_urllib.txt |
Q:
Get iframe content in python
I need content of a html pages, but if a html page contains a iframe element, I need iframe content too. (in Python)
Is it possible to load everything with a python function?
A:
Try using BeautifulSoup, which supports iframes out of the box.
Code snippet (full code here):
import re
f... | Get iframe content in python | I need content of a html pages, but if a html page contains a iframe element, I need iframe content too. (in Python)
Is it possible to load everything with a python function?
| [
"Try using BeautifulSoup, which supports iframes out of the box.\nCode snippet (full code here):\nimport re\nfrom BeautifulSoup import BeautifulSoup, Comment\n...\nfor iframe in mosoup(\"iframe\"):\n mosoup.iframe.extract()\n\nUPDATE: Linked to current location of code (now in github).\n"
] | [
3
] | [] | [] | [
"iframe",
"python"
] | stackoverflow_0004641539_iframe_python.txt |
Q:
Django Dynamic Widget/Form field representation
I have a table that contains various types of settings. I want to display and validate each setting differently in a form. For example if the setting is for an integer or for a string.
This is my model
class Setting(models.Model):
SETTING_TYPES = (
(u'1',... | Django Dynamic Widget/Form field representation | I have a table that contains various types of settings. I want to display and validate each setting differently in a form. For example if the setting is for an integer or for a string.
This is my model
class Setting(models.Model):
SETTING_TYPES = (
(u'1', u'Decimal'),
(u'2', u'Integer'),
(u'... | [
"I believe what you're looking for is a custom validator passed into the CharField constructor.\nAnother, possibly more elegant solution depending on the situation, would be to make your own field class that extends CharField and overloads its validation code.\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"dynamic",
"field",
"python"
] | stackoverflow_0004641503_django_django_forms_dynamic_field_python.txt |
Q:
Extending several lists elegantly
Given several lists:
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
...
n = ["n1", "n2", "n3"]
And a list of new values:
new_vals = ["a4", "b4", "n4"]
I would like to get:
["a1", "a2", "a3", "a4"]
["b1", "b2", "b3", "b4"]
...
["n1", "n2", "n3", "n4"]
I can do this with loops and... | Extending several lists elegantly | Given several lists:
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
...
n = ["n1", "n2", "n3"]
And a list of new values:
new_vals = ["a4", "b4", "n4"]
I would like to get:
["a1", "a2", "a3", "a4"]
["b1", "b2", "b3", "b4"]
...
["n1", "n2", "n3", "n4"]
I can do this with loops and temporary variables, of course. It see... | [
"Something like this:\na = [\"a1\", \"a2\", \"a3\"]\nb = [\"b1\", \"b2\", \"b3\"]\n\n# Put the list a, b ... in a big_list. \nbig_list = [a, b]\n\nnew_vals = [\"a4\", \"b4\", \"n4\"]\n\nfor i, new_val in enumerate(new_vals):\n big_list[i].append(new_val)\n\n",
"Suppose you have a list of lists:\nlsts = [ ['a1'... | [
5,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004641209_list_python.txt |
Q:
Which is "better" practice? Passing object references or object method references in Python
I'm writing a small piece of code in Python and am curious what other people think of this.
I have a few classes, each with a few methods, and am trying to determine what is "better": to pass objects through method calls, o... | Which is "better" practice? Passing object references or object method references in Python | I'm writing a small piece of code in Python and am curious what other people think of this.
I have a few classes, each with a few methods, and am trying to determine what is "better": to pass objects through method calls, or to pass methods through method calls when only one method from an object is needed. Basically, ... | [
"The second solution may provide looser coupling because it is more \"functional\", not more \"OOP\". The first solution has the advantage that it works in languages like C++ which don't have closures (though one can get a similar effect using templates and pointer-to-member-functions); but in a language like Pytho... | [
4,
1,
0
] | [] | [] | [
"cohesion",
"functional_programming",
"loose_coupling",
"oop",
"python"
] | stackoverflow_0004641216_cohesion_functional_programming_loose_coupling_oop_python.txt |
Q:
FLOSS/Free solution to generate PDF documents in Python?
What is the easiest way to generate PDF documents with embedded fonts in Python without a commercial/restricted library?
I want to generate documents with tabular data and headers/footers. I've tried reportlab, but while powerful, it seems rather difficult t... | FLOSS/Free solution to generate PDF documents in Python? | What is the easiest way to generate PDF documents with embedded fonts in Python without a commercial/restricted library?
I want to generate documents with tabular data and headers/footers. I've tried reportlab, but while powerful, it seems rather difficult to use.
| [
"You can create the document in html and then use WKHTMLTOPDF to convert to pdf... It is licensed GNU but it is a pretty good tool.\n",
"I've used PISA and been very, very happy. It uses reportlab for you.\nhttp://www.xhtml2pdf.com/doc/pisa-en.html \n",
"Be careful if you want to be able to extract the tabula... | [
3,
1,
0
] | [] | [] | [
"pdf",
"pdf_generation",
"python"
] | stackoverflow_0004641877_pdf_pdf_generation_python.txt |
Q:
python inserting large element in sqlite3 db - memory error
I am doing numerical simulations in python leading to quite large data objects (approx 200 MB). I write them into a sqlite3 db. After increasing resolution (and thus the data size) by about 20% I get a memory error while trying to insert into the db. Work... | python inserting large element in sqlite3 db - memory error | I am doing numerical simulations in python leading to quite large data objects (approx 200 MB). I write them into a sqlite3 db. After increasing resolution (and thus the data size) by about 20% I get a memory error while trying to insert into the db. Worked just fine with the smaller resolution before. Here is a code s... | [
"Note that XP will only increase swap in smaller increments. If your program suddenly tries to use a lot more memory and there is insufficient swap then you will get the memory error.\nSQLite will work quite happily with blobs up to 1GB in size and you can usually use 2GB. However you will run out of address spac... | [
1,
0
] | [] | [] | [
"memory",
"python",
"sqlite"
] | stackoverflow_0004624222_memory_python_sqlite.txt |
Q:
Python data types
Is this statement true?
Python does not enforce a strict type
on containers or variables. With this
concept, developers can design a
container to hold different types of
data
I'm doing an essay on Python and found this statement on a random site, just wondering if anyone could clarify i... | Python data types | Is this statement true?
Python does not enforce a strict type
on containers or variables. With this
concept, developers can design a
container to hold different types of
data
I'm doing an essay on Python and found this statement on a random site, just wondering if anyone could clarify it for me, please.
| [
"Yep its true.\nBesides designing a container, regular lists can hold several types\n>>> myList = [1, 3.14, 'string', {'key1':'value1'}, frozenset([5,2,2,3]), [1,2,3],(5+2j),(4.0,5.0), True, type(5)]\n>>> myList\n[1, 3.1400000000000001, 'string', {'key1': 'value1'}, frozenset([2, 3, 5]), [1, 2, 3], (5+2j), (4.0, 5.... | [
10,
6,
3,
2,
1
] | [] | [] | [
"python",
"types"
] | stackoverflow_0004642032_python_types.txt |
Q:
Testing HSL colours, ideally avoiding Red adjacent to Green (common colour-blindness type)
Inspired by the top answer on this page I wrote a python program to generate N distinct HEX colours. The difference is that the original author would generate saturation and luminance by using math.random(), whereas I use a ... | Testing HSL colours, ideally avoiding Red adjacent to Green (common colour-blindness type) | Inspired by the top answer on this page I wrote a python program to generate N distinct HEX colours. The difference is that the original author would generate saturation and luminance by using math.random(), whereas I use a trigonometric function which I can guarantee will always give a unique hue, saturation & luminan... | [
"\nEh? Test, and if you get red close to green you get another color? I'm not sure what the question is here.\nYou could generate a PNG and open it locally. Thats' probably the easiest. PIL is a good library for that. http://pypi.python.org/pypi/Pillow/\nNope, sorry, I don't know anything about that.\n\n"
] | [
1
] | [] | [] | [
"hsl",
"python"
] | stackoverflow_0004642219_hsl_python.txt |
Q:
Python: PyQt4 Py2exe
Greetings!
So I've made a Python application that uses the ever so great PyQt as it's interface. Now if I was to specify the --bundle 0 option for Py2Exe the resulting compiled executable file works fine! But with all the needed files, the folder gets cluttered up. So I tried passing 1 and 2 f... | Python: PyQt4 Py2exe | Greetings!
So I've made a Python application that uses the ever so great PyQt as it's interface. Now if I was to specify the --bundle 0 option for Py2Exe the resulting compiled executable file works fine! But with all the needed files, the folder gets cluttered up. So I tried passing 1 and 2 for the --bundle option. On... | [
"I know that even using raw win32ui with py2exe can cause problems. Seems like they could be related, but I don't know enough about the architecture of PyQt.\nPy2exeAndWin32ui\nThough I realise this wouldn't give you a neat solution even if it did help.\n"
] | [
0
] | [] | [] | [
"py2exe",
"pyqt",
"python"
] | stackoverflow_0004640140_py2exe_pyqt_python.txt |
Q:
Iterating on a dictionary, adding keys and values
I would like to iterate on a dictionary, amending the dictionary each time rather than what is currently happening which is resetting the old value with the new one.
My current code is:
while True:
grades = { raw_input('Please enter the module ID: '):raw_input(... | Iterating on a dictionary, adding keys and values | I would like to iterate on a dictionary, amending the dictionary each time rather than what is currently happening which is resetting the old value with the new one.
My current code is:
while True:
grades = { raw_input('Please enter the module ID: '):raw_input('Please enter the grade for the module: ') }
but alas,... | [
"In your example, grades (dictionary) is getting refreshed each time with a new key,value pair.\n>>> grades = { 'k':'x'}\n>>> grades\n{'k': 'x'}\n>>> grades = { 'newinput':'newval'}\n>>> grades\n{'newinput': 'newval'}\n>>> \n\nWhat you should have been doing is update the key,value pair for the same dict:\n>>> grad... | [
20,
3,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004642258_dictionary_python.txt |
Q:
python - sys.argv and flag identification
when I accept arguments how do I check if two show up at the same time without having a compound conditional
i.e.
#!/usr/bin/python
import random, string
import mymodule
import sys
z = ' '.join(sys.argv[2:])
q = ''.join(sys.argv[3:])
a = ''.join(sys.argv[2:])
s = ' '.join... | python - sys.argv and flag identification | when I accept arguments how do I check if two show up at the same time without having a compound conditional
i.e.
#!/usr/bin/python
import random, string
import mymodule
import sys
z = ' '.join(sys.argv[2:])
q = ''.join(sys.argv[3:])
a = ''.join(sys.argv[2:])
s = ' '.join(sys.argv[1:])
flags = sys.argv[1:5]
commands ... | [
"Something like\nimport optparse\n\np = optparse.OptionParser()\np.add_option('--foo', '-f', default=\"yadda\")\np.add_option('--bar', '-b')\noptions, arguments = p.parse_args()\n\n# if options.foo and options.bar ...\n\n",
"I'd recommend using argparse for this (or optparse if you're on Python 2.6.x or older).\n... | [
7,
4,
0
] | [] | [] | [
"arguments",
"python",
"sys"
] | stackoverflow_0004642335_arguments_python_sys.txt |
Q:
Multiple calls to /dev/stdin using python subprocess (*nix)
I have a python subprocess call which I would like to link up to three pipes (two standard in and one standard out). I know that there is only one /dev/stdin, but there's all those other devices in /dev I don't know about, and don't know of any python os,... | Multiple calls to /dev/stdin using python subprocess (*nix) | I have a python subprocess call which I would like to link up to three pipes (two standard in and one standard out). I know that there is only one /dev/stdin, but there's all those other devices in /dev I don't know about, and don't know of any python os, sys or subprocess modules that will utilise them in a manner whi... | [
"On Unix systems, a convenient alternative is to use a named pipe. It looks like a file, but takes up no space on disk; you can write to it with one process and read from it with another, just like pipes. You can have your sub-process just do ordinary file I/O; Unix (Mac OS / Linux) will do the heavy lifting for yo... | [
3
] | [] | [] | [
"pipe",
"python",
"subprocess"
] | stackoverflow_0004642322_pipe_python_subprocess.txt |
Q:
Automatically registering "commands" for a command line program in python
I would like to develop a command-line program that can process and give "help" for subcommands. To be concrete, say I have a single script called "cgent" and I would like to have subcommands "abc", "def", and "xyz" execute and accept the r... | Automatically registering "commands" for a command line program in python | I would like to develop a command-line program that can process and give "help" for subcommands. To be concrete, say I have a single script called "cgent" and I would like to have subcommands "abc", "def", and "xyz" execute and accept the rest of the sys.args for processing by optparse.
cgent abc [options]
cgent h... | [
"If you don't have to do complex parsing of arguments I recommend the baker module. It lets you define subcommands and their arguments through decorators. For example:\n#!/usr/bin/env python\nimport baker\n\n@baker.command()\ndef foo(a=1):\n print 'foo:', a\n\n@baker.command()\ndef baz(b=1):\n print 'baz:', b... | [
4,
1
] | [] | [] | [
"command_line_tool",
"python"
] | stackoverflow_0004642373_command_line_tool_python.txt |
Q:
Using lxml, what causes a "lxml.etree.XMLSyntaxError: Document is empty" error?
I'm using mechanize/cookiejar/lxml to read a page and it works for some but not others. The error I'm getting in them is the one in the title. I can't post the pages here because they aren't SFW, but is there a way to fix it? Basically... | Using lxml, what causes a "lxml.etree.XMLSyntaxError: Document is empty" error? | I'm using mechanize/cookiejar/lxml to read a page and it works for some but not others. The error I'm getting in them is the one in the title. I can't post the pages here because they aren't SFW, but is there a way to fix it? Basically, this is what I do:
import mechanize, cookielib
from lxml import etree
br = mec... | [
"use lxml.html.parse for html it can handle even very broken html, you still get an error then?\n",
"What is the nature of response? According to the help, etree.parse is expecting one of:\n - a file name/path\n - a file object\n - a file-like object\n - a URL using the HTTP or FTP protocol\n\n"
] | [
3,
1
] | [] | [] | [
"lxml",
"mechanize",
"python",
"xml"
] | stackoverflow_0004642430_lxml_mechanize_python_xml.txt |
Q:
Short snippet summarizing a webpage?
Is there a clean way of grabbing the first few lines of a given link that summarizes that link? I have seen this being done in some online bookmarking applications but have no clue on how they were implemented. For instance, if I give this link, I should be able to get a summar... | Short snippet summarizing a webpage? | Is there a clean way of grabbing the first few lines of a given link that summarizes that link? I have seen this being done in some online bookmarking applications but have no clue on how they were implemented. For instance, if I give this link, I should be able to get a summary which is roughly like:
I'll admit it, I... | [
"Well first of all i would suggest you use PHP with a DOM Parser Class, this will make it a lot easier to get the tag contents you need. \n// Get HTML from URL or file\n$html = file_get_html('http://www.google.com/');\n\n// Find all paragraphs \n$paragraphs = $html->find('p')\n\n//echo the first paragraph\necho $pa... | [
0,
0
] | [] | [] | [
"javascript",
"jquery",
"php",
"python"
] | stackoverflow_0004642589_javascript_jquery_php_python.txt |
Q:
Handle the HTTP PUT method in Python WSGI
I currently have a bash application that, among other things, uses cURL to upload a file to a web application with the PUT method. I am attempting to duplicate the web application as the client (bash) portion is GPL but the web portion is not. I also cannot alter the clien... | Handle the HTTP PUT method in Python WSGI | I currently have a bash application that, among other things, uses cURL to upload a file to a web application with the PUT method. I am attempting to duplicate the web application as the client (bash) portion is GPL but the web portion is not. I also cannot alter the client application as it auto-updates itself from th... | [
"As I understand it, you will just want to read the stream environ['wsgi.input'], because a PUT request will send the entire contents of the PUT as the body of the request. \nI am not aware of any encoding issues you will have to deal with (other than the fact that it is binary).\nSome time ago, I wrote a simple s... | [
4
] | [] | [] | [
"http",
"put",
"python",
"wsgi"
] | stackoverflow_0004642423_http_put_python_wsgi.txt |
Q:
Python client / server question
I'm working on a bit of a project in python. I have a client and a server. The server listens for connections and once a connection is received it waits for input from the client. The idea is that the client can connect to the server and execute system commands such as ls and cat. T... | Python client / server question | I'm working on a bit of a project in python. I have a client and a server. The server listens for connections and once a connection is received it waits for input from the client. The idea is that the client can connect to the server and execute system commands such as ls and cat. This is my server code:
import sys, os... | [
"Your code calls conn.close() and then loops back around to conn.recv(), but conn is already closed.\n",
"If you want your client to repeat what it's doing, just add a loop in there ;)\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nhost = 'localhost'\nport = input('Port: ')\ns.connect((host, port))\nwhil... | [
6,
3
] | [] | [] | [
"client",
"command",
"python",
"sockets"
] | stackoverflow_0004642345_client_command_python_sockets.txt |
Q:
Rewrite string formatting without format function
I have this piece of code:
parse_string = \
'&category={0}&v=2'.format('%2C+'.join(tag.strip() for tag in tags_list))
how can I rewrite this to be python 2.4 compatible (so the same functionality but without using format function) ?
A:
I think something like... | Rewrite string formatting without format function | I have this piece of code:
parse_string = \
'&category={0}&v=2'.format('%2C+'.join(tag.strip() for tag in tags_list))
how can I rewrite this to be python 2.4 compatible (so the same functionality but without using format function) ?
| [
"I think something like this will do it:\n'&category=%s&v=2' % '%2C+'.join(tag.strip() for tag in tags_list)\n\n"
] | [
5
] | [] | [] | [
"format",
"python",
"python_2.4",
"string_formatting"
] | stackoverflow_0004643037_format_python_python_2.4_string_formatting.txt |
Q:
why do I get unsupported operand type(s) type error?
ok, so I got a little exercise for python and I want to find the values of speed and location at every second from 0 to 30th within a list. also it must notify me when they intersect. while finding the location of the first car I am to use the method of Trapezoi... | why do I get unsupported operand type(s) type error? | ok, so I got a little exercise for python and I want to find the values of speed and location at every second from 0 to 30th within a list. also it must notify me when they intersect. while finding the location of the first car I am to use the method of Trapezoid code only.
the speed equation of the first car is V1=t^3... | [
"I don't know Python, but your function LocationV2() doesn't seem to be returning anything.\n",
"b=LocationV2(t)\n\nThe problem is, this returns None and hence a-b gives the error you are getting.\ndef LocationV2(x):\n x=x*1.0\n def g(x):\n return 5*x**2/2\n\nshould really be:\ndef LocationV2(x):\n ... | [
2,
2,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004641141_python.txt |
Q:
error when using poplib to get email
I am using poplib to get email from the POP3 server.
But this error occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\site-packages\myutils.py", line 251, in dxDown
m=poplib.POP3('pop3.126.com')
File "C:\Python26\li... | error when using poplib to get email | I am using poplib to get email from the POP3 server.
But this error occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\site-packages\myutils.py", line 251, in dxDown
m=poplib.POP3('pop3.126.com')
File "C:\Python26\lib\poplib.py", line 83, in __init__
sel... | [
"Your proxy is for http, it doesn't effect the pop3 traffic.\nA cursory glance suggests that it's probably not able to resolve the hostname to an IP address.\nCan you try one of these:\npop3.126.idns.yeah.net\n220.181.15.128\n\nOr paste the output of:\nnslookup pop3.126.com\n"
] | [
1
] | [] | [] | [
"http",
"networking",
"poplib",
"python",
"sockets"
] | stackoverflow_0004643367_http_networking_poplib_python_sockets.txt |
Q:
tail -f does not seem to work in the shell when file is being populated through file.write()
Greetings everyone,
I am trying to daemonize a python script that currently runs in the foreground. However, I still need to be able to see its output which it currently dumps to stdout.
So I am using the following piece o... | tail -f does not seem to work in the shell when file is being populated through file.write() | Greetings everyone,
I am trying to daemonize a python script that currently runs in the foreground. However, I still need to be able to see its output which it currently dumps to stdout.
So I am using the following piece of code which generates a unique file name in /tmp and then it assigns sys.stdout to this new file.... | [
"Try harder to use unbuffered I/O. The problem is almost certainly that your output is buffered.\nOpening the file like this should work:\noutfile = open(name, 'w', 0)\n\n"
] | [
4
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0004643491_file_io_python.txt |
Q:
I don't understand this Django documentation. How do I use it this module?
I'm using the django_notification module. https://github.com/pinax/django-notification/blob/master/docs/usage.txt
This is what I do in my code to send an email to a user when something happens:
notification.send([to_user], "comment_received... | I don't understand this Django documentation. How do I use it this module? | I'm using the django_notification module. https://github.com/pinax/django-notification/blob/master/docs/usage.txt
This is what I do in my code to send an email to a user when something happens:
notification.send([to_user], "comment_received", noti_dict)
But, this seems to block the request. And it takes a long time to... | [
"It looks like in your settings file you need to set\nNOTIFICATION_QUEUE_ALL=True\n\nAnd then you need to setup a cronjob (maybe every 10-30 seconds or something) to run something like,\ndjango_admin.py emit_notices\n\nThis will periodically run and do the blocking call which sends out all the emails and whatever l... | [
2,
1
] | [] | [] | [
"asynchronous",
"django",
"notifications",
"python",
"queue"
] | stackoverflow_0004643564_asynchronous_django_notifications_python_queue.txt |
Q:
Django: Two fields form a key?
I have a model in Django 1.2.4. It has two fields that I would like to act together as a key. Is this possible?
This documentation only talks about a single field being a primary key.
A:
You may know this already, but one option would be to force the pair is unique and let Django ... | Django: Two fields form a key? | I have a model in Django 1.2.4. It has two fields that I would like to act together as a key. Is this possible?
This documentation only talks about a single field being a primary key.
| [
"You may know this already, but one option would be to force the pair is unique and let Django add its own Primary Key. So suppose you want two fields to be a primary key, well, make them unique together and then make each of those fields a db index.\n",
"Sadly from this link, this ticket is not done yet, you ca... | [
1,
0
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0004643897_database_django_python.txt |
Q:
Is there a Python module for 2.5 that provides something similar to the "string".format() call in 2.6?
Is there a free Python module for 2.5 that provides something similar to the "string".format() call in 2.6/3.x?
I am writing new code for 2.5. I'd rather not use % format expressions for new code.
A:
You might... | Is there a Python module for 2.5 that provides something similar to the "string".format() call in 2.6? | Is there a free Python module for 2.5 that provides something similar to the "string".format() call in 2.6/3.x?
I am writing new code for 2.5. I'd rather not use % format expressions for new code.
| [
"You might find that the code here can be adapted to your need: http://svn.python.org/view/sandbox/trunk/pep3101/\nIn particular, you might be able to get StringFormat.py to run. It optionally imports a couple of things you might not have (like fpformat), but seems to be more or less robust if running as pure Pytho... | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004643981_python_string.txt |
Q:
Python built-in list: remove one item
lst = [(32,(4,5)),(55,(5,6))]
Given a tuple (4,5), so I want to remove the first tuple in lst. How to do that?
Sorry, this wasn't clear, what I mean is remove the list item by the second item in each list item
A:
lst2 = [(x, y) for (x, y) in lst if y != (4, 5)]
Removes ALL... | Python built-in list: remove one item | lst = [(32,(4,5)),(55,(5,6))]
Given a tuple (4,5), so I want to remove the first tuple in lst. How to do that?
Sorry, this wasn't clear, what I mean is remove the list item by the second item in each list item
| [
"lst2 = [(x, y) for (x, y) in lst if y != (4, 5)]\n\nRemoves ALL (4, 5) tuples, not just the first instance.\n",
"You could filter the list:\nlst = filter(lambda x, y: y != (4,5), lst)\n\n",
"This removes the first list entry whose 2nd component matches, but don't use this to remove more than one. To do more t... | [
7,
2,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004644091_list_python.txt |
Q:
Python how to sort this list?
lst = [(1,(1,3,5)), (5,(2,3,4)),(3,(2,3,4))]
I want to sort by the first value, descending order.
A:
just like this:
sorted(lst, reverse=True)
A:
Sort in place? Use:
lst.sort(reverse=True)
A:
import operator
sorted(lst, reverse=True, key=operator.itemgetter(0))
A:
sorted(lis... | Python how to sort this list? | lst = [(1,(1,3,5)), (5,(2,3,4)),(3,(2,3,4))]
I want to sort by the first value, descending order.
| [
"just like this:\nsorted(lst, reverse=True)\n\n",
"Sort in place? Use:\nlst.sort(reverse=True)\n\n",
"import operator\nsorted(lst, reverse=True, key=operator.itemgetter(0))\n\n",
"sorted(list, reverse=True, key=lambda x: x[0])\n\nNote also that \"list\" isn't a great name for your list because it's the built... | [
12,
6,
4,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004644025_list_python.txt |
Q:
Optimization of Function with Dictionary and Zip()
I have the following function:
def filetxt():
word_freq = {}
lvl1 = []
lvl2 = []
total_t = 0
users = 0
text = []
for l in range(0,500):
# Open File
if os.path.exists("C:/Twitter/json/user_" + str(l)... | Optimization of Function with Dictionary and Zip() | I have the following function:
def filetxt():
word_freq = {}
lvl1 = []
lvl2 = []
total_t = 0
users = 0
text = []
for l in range(0,500):
# Open File
if os.path.exists("C:/Twitter/json/user_" + str(l) + ".json") == True:
with open("C:/Twitter/j... | [
"I think you want something like:\nimport string\nfrom collections import defaultdict\nrng = xrange if xrange else range\n\ndef filetxt():\n users = 0\n total_t = 0\n occ = 0\n\n wordcount = defaultdict(int)\n wordpairs = defaultdict(lambda: defaultdict(int))\n for filenum in rng(500):... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"optimization",
"profiling",
"python",
"zip"
] | stackoverflow_0004643536_dictionary_optimization_profiling_python_zip.txt |
Q:
django long running process database connection
i have a django project with a long running (~3hour) management command
in my production environment ( apache mod_wsgi ) this process fails with a broken pipe(32) at the end, when trying to update the database.
thank you
A:
The broken pipe mostly mean that one sock... | django long running process database connection | i have a django project with a long running (~3hour) management command
in my production environment ( apache mod_wsgi ) this process fails with a broken pipe(32) at the end, when trying to update the database.
thank you
| [
"The broken pipe mostly mean that one socket in the canal of transmission has been closed without notifying the other one , in your case i think it mean that the database connection that you have establish was closed from the database part, so when you code try to use it, it raise the exception.\nUsually the databa... | [
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0004644317_apache_django_mod_wsgi_python.txt |
Q:
Django: Where to put global models?
I'm building a fairly large website in Django, and it's my first time doing anything of this scale with the framework. (I have, however, used it in the past, so I know my way around and am not a total newbie.) I have a number of model classes which will be used throughout the a... | Django: Where to put global models? | I'm building a fairly large website in Django, and it's my first time doing anything of this scale with the framework. (I have, however, used it in the past, so I know my way around and am not a total newbie.) I have a number of model classes which will be used throughout the application, so my question is where would... | [
"I think the easiest way is to make a \"main\" application and then import the models from that application into your other peripheral apps when you need the main models.\nmanage.py startapp main\n\n"
] | [
10
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004644559_django_django_models_python.txt |
Q:
Python - Nested dict, versus hashing a tuple?
I'm wondering what are the pros/cons of nested dicts versus hashing a tuple in Python?
The context is a small script to assign "workshops" to attendees at a conference.
Each workshop has several attributes (e.g. week, day, subject etc.). We use four of these attributes... | Python - Nested dict, versus hashing a tuple? | I'm wondering what are the pros/cons of nested dicts versus hashing a tuple in Python?
The context is a small script to assign "workshops" to attendees at a conference.
Each workshop has several attributes (e.g. week, day, subject etc.). We use four of these attributes in order to assign workshops to each attendee - i.... | [
"class Workshop(object):\n def __init__(self, week, stream, strand, day, name):\n self.week = week\n self.stream = stream\n self.day = day\n self.strand = strand\n self.name = name\n\n...\nfor row in workshop_reader:\n workshops['name'] = Workshop(...)\n\nThat is only if the name is the unique attr... | [
7,
4
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004644071_dictionary_python.txt |
Q:
Python value problem: SyntaxError: invalid syntax
I'm learning, so go easy on me.
What am I doing wrong here:
#!/usr/bin/python3.1
import urllib.request
page = urllib.request.urlopen ("http://au.finance.yahoo.com/q?s=AUDUSD=X")
text = page.read().decode("utf8")
where = text.find('Last Trade:</th><td class="yfnc... | Python value problem: SyntaxError: invalid syntax | I'm learning, so go easy on me.
What am I doing wrong here:
#!/usr/bin/python3.1
import urllib.request
page = urllib.request.urlopen ("http://au.finance.yahoo.com/q?s=AUDUSD=X")
text = page.read().decode("utf8")
where = text.find('Last Trade:</th><td class="yfnc_tabledata1"><big><b><span id="yfs_l10_audusd=x">')
st... | [
"The last line should be:\nprint ('The price is $ ', us_price, ' as of ', trade_time)\n\nConsider this to understand it better:\n>>> x = 3\n>>> print('The value of x is:', 3, 'Yes!')\nThe value of x is: 3 Yes!\n\n"
] | [
4
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0004645116_python_urllib.txt |
Q:
How to deploy django project and runtime environment with all in once click
On Windows, its like WAMP, but it including your project code.
Your Project + Django + Python + (other dependence models) + Apache + MySQL all in one installation.
anyone know this?
A:
Take a look at zc.buildout, that does these things. ... | How to deploy django project and runtime environment with all in once click | On Windows, its like WAMP, but it including your project code.
Your Project + Django + Python + (other dependence models) + Apache + MySQL all in one installation.
anyone know this?
| [
"Take a look at zc.buildout, that does these things. I haven't used it with Django, but see no reason why it shouldn't work for Django as well (and bcchuns link, see below, shows that it does, as expected). I use it for Plone (with nginx and varnish, typically).\n"
] | [
1
] | [] | [] | [
"deployment",
"django",
"python"
] | stackoverflow_0004645213_deployment_django_python.txt |
Q:
reading mp3 tags on the www with python
I've found a few modules to read mp3 tags with python -- for example mutagen and id3. When doing this online, I was wondering if the modules were accessing the whole file or just the last 128 bites that contained the tag info.
Thanks
Edit:
When I say accessing, I mean cach... | reading mp3 tags on the www with python | I've found a few modules to read mp3 tags with python -- for example mutagen and id3. When doing this online, I was wondering if the modules were accessing the whole file or just the last 128 bites that contained the tag info.
Thanks
Edit:
When I say accessing, I mean caching to access the file data. At least that's ... | [
"mutagen reads last 128 bytes for id3\nid3 similarly:\nself.title = self.file.read(30)\nself.artist = self.file.read(30)\nself.album = self.file.read(30)\nself.year = self.file.read(4)\nself.comment = self.file.read(30)\n\n"
] | [
0
] | [] | [] | [
"mp3",
"python",
"tags"
] | stackoverflow_0004645033_mp3_python_tags.txt |
Q:
Internationalization of models in Django applications
My application will be available in two languages: english and german. The application will have a couple of XType objects with a description field. How can I translate the description field of XType? Does Django provide support for this or I will have to use a... | Internationalization of models in Django applications | My application will be available in two languages: english and german. The application will have a couple of XType objects with a description field. How can I translate the description field of XType? Does Django provide support for this or I will have to use another Django application?
class XType(models.Model):
d... | [
"Django does not provide direct support of model field translations.\nYou have to find a way to deal with it either within Django or via plugable applications (like posted already django-easymode or check http://blog.muhuk.com/2010/01/06/dynamic-translation-apps-for-django.html).\nIf you want to deal within your ap... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"internationalization",
"localization",
"python"
] | stackoverflow_0004644770_django_django_models_internationalization_localization_python.txt |
Q:
django reverse lookup in model method
Google has lots of examples of doing reverse lookup in the interactive prompt but none of doing them inside a django model as a method.
I have the following models.py file:
class Client(models.Model):
...
def __unicode__(self):
return ???
class ClientDetails(... | django reverse lookup in model method | Google has lots of examples of doing reverse lookup in the interactive prompt but none of doing them inside a django model as a method.
I have the following models.py file:
class Client(models.Model):
...
def __unicode__(self):
return ???
class ClientDetails(models.Model):
client = models.ForeignK... | [
"If a ClientDetails object should only ever be associated with a single Client object, then I would change your FK to a OneToOneField, which will provide you with a neat reverse accessor that can only ever link between a given Client and its associated ClientDetails. Then you can do:\ntry:\n return self.clientdet... | [
3,
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004646352_django_django_models_python.txt |
Q:
Python: How to start a process with Administrator Permissions?
I am starting the following script from a Windows 7 command line with administrator permissions:
import win32com.client
import time
import SendKeys
import os
from ctypes import *
shell = win32com.client.Dispatch("WScript.Shell")
os.startfile("C:\...e... | Python: How to start a process with Administrator Permissions? | I am starting the following script from a Windows 7 command line with administrator permissions:
import win32com.client
import time
import SendKeys
import os
from ctypes import *
shell = win32com.client.Dispatch("WScript.Shell")
os.startfile("C:\...exe")
I have also assigned the feature 'Run this programme as an adm... | [
"I don't have access to Vista or Windows 7, but you should be able to use the runas command. \nimport subprocess\nsubprocess.call(['runas', '/user:Administrator', 'C:/my_program.exe'])\n\n",
"OK ... I figured out what the problem was. It actually had nothing to do with permissions, contrary to my initial suspicio... | [
2,
0
] | [] | [] | [
"process_management",
"python",
"uac",
"windows_7"
] | stackoverflow_0004645909_process_management_python_uac_windows_7.txt |
Q:
Python Tkinter padding issue
I am learning Tkinter and building a simple 8 puzzle game.
(Example: http://www.permadi.com/java/puzzle8/)
Each number is a Canvas object placed into a Frame using a grid layout. One of the objects is adding extra padding between the Canvas objects. I set the border width to the Canvas... | Python Tkinter padding issue | I am learning Tkinter and building a simple 8 puzzle game.
(Example: http://www.permadi.com/java/puzzle8/)
Each number is a Canvas object placed into a Frame using a grid layout. One of the objects is adding extra padding between the Canvas objects. I set the border width to the Canvas objects to -2 which solved some p... | [
"Most likely the cause of your problem is that you're neglecting to set the highlightthickness attribute of each canvas to zero. This value controls a colored ring around the widget used to denote that it has focus. \nHere's a trick when trying to solve these types of layout issues: Give each widget a different bac... | [
10
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004646289_python_tkinter.txt |
Q:
Unable to retrieve search results from server side : Facebook Graph API using Python
I'm doing some simple Python + FB Graph training on my own, and I faced a weird problem:
import time
import sys
import urllib2
import urllib
from json import loads
base_url = "https://graph.facebook.com/search?q="
post_id = None
... | Unable to retrieve search results from server side : Facebook Graph API using Python | I'm doing some simple Python + FB Graph training on my own, and I faced a weird problem:
import time
import sys
import urllib2
import urllib
from json import loads
base_url = "https://graph.facebook.com/search?q="
post_id = None
post_type = None
user_id = None
message = None
created_time = None
def doit(hour):
p... | [
"Trial and error using Chrome (where I got lots of data) and Firefox (where I got the empty response) made me zero on the 'Accept-Language' header. Other modifications are supposedly only cosmetic, but I'm not sure about the CookieJar.\nimport time\nimport sys\nimport urllib2\nimport urllib\nfrom json import loads\... | [
1
] | [] | [] | [
"facebook_graph_api",
"python"
] | stackoverflow_0004644336_facebook_graph_api_python.txt |
Q:
Carrot (Python) [errno 10054] An existing connection was forcibly closed by the remote host
We are using Carrot in our Python project. I wrote a Python script acting as the consumer of the message queue. I invoked this Python script using command line shell in Windows 7 as
python consumer.py
However, after a whi... | Carrot (Python) [errno 10054] An existing connection was forcibly closed by the remote host | We are using Carrot in our Python project. I wrote a Python script acting as the consumer of the message queue. I invoked this Python script using command line shell in Windows 7 as
python consumer.py
However, after a while, the running session was aborted and the error is:
[errno 10054] An existing connection was fo... | [
"I don't know Carrot/AMQP, but I'd first of all check if the AMQP server logged an error at the time your client got disconnected. It could be that you just have to expect these errors to occur from time to time and upon disconnection, catch the exception(?) and reestablish the connection.\n"
] | [
0
] | [] | [] | [
"carrot",
"message_queue",
"python"
] | stackoverflow_0004643533_carrot_message_queue_python.txt |
Q:
Filtering on a left join in SQLalchemy
Using SQLalchemy I want to perform a left outer join and filter out rows that DO have a match in the joined table.
I'm sending push notifications, so I have a Notification table. This means I also have a ExpiredDeviceId table to store device_ids that are no longer valid. (I d... | Filtering on a left join in SQLalchemy | Using SQLalchemy I want to perform a left outer join and filter out rows that DO have a match in the joined table.
I'm sending push notifications, so I have a Notification table. This means I also have a ExpiredDeviceId table to store device_ids that are no longer valid. (I don't want to just delete the affected notifi... | [
"Do you need to be pulling back the ExpiredDeviceId in a tuple? If you don't (i.e. you just care about live device_ids), then can't you just do:\nsess.query(\n Notification\n).outerjoin(\n (ExpiredDeviceId, Notification.device_id == ExpiredDeviceId.device_id)\n).filter(\n ExpiredDeviceId.expiration_time ==... | [
14
] | [] | [] | [
"join",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004629684_join_python_sql_sqlalchemy.txt |
Q:
Collect every pair of elements from a list into tuples in Python
I have a list of small integers, say:
[1, 2, 3, 4, 5, 6]
I wish to collect the sequential pairs and return a new list containing tuples created from those pairs, i.e.:
[(1, 2), (3, 4), (5, 6)]
I know there must be a really simple way to do this, bu... | Collect every pair of elements from a list into tuples in Python | I have a list of small integers, say:
[1, 2, 3, 4, 5, 6]
I wish to collect the sequential pairs and return a new list containing tuples created from those pairs, i.e.:
[(1, 2), (3, 4), (5, 6)]
I know there must be a really simple way to do this, but can't quite work it out.
Thanks
| [
"Well there is one very easy, but somewhat fragile way, zip it with sliced versions of itself.\nzipped = zip(mylist[0::2], mylist[1::2])\n\nIn case you didn't know, the last slice parameter is the \"step\". So we select every second item in the list starting from zero (1, 3, 5). Then we do the same but starting fro... | [
41,
10,
6
] | [] | [] | [
"python"
] | stackoverflow_0004647050_python.txt |
Q:
What would happen if a same file being read and appended at the same time(python programming)?
I'm writing a script using two separate thread one doing file reading operation and the other doing appending, both threads run fairly frequently.
My question is, if one thread happens to read the file while the other i... | What would happen if a same file being read and appended at the same time(python programming)? | I'm writing a script using two separate thread one doing file reading operation and the other doing appending, both threads run fairly frequently.
My question is, if one thread happens to read the file while the other is just in the middle of appending strings such as "This is a test" into this file, what would happen... | [
"If you're worried about this, just have your consumer look for a special character (endline would work) so that it knows that there wasn't an incomplete write. So your producer (the one writing data to the file) can output partial data but the consumer (one reading from the file) will know it only got a partial w... | [
1
] | [] | [] | [
"file_io",
"multithreading",
"operating_system",
"python"
] | stackoverflow_0004646393_file_io_multithreading_operating_system_python.txt |
Q:
TKinter : Image preview - Buttons
What's the easiest way to make a GUI in python (TKinter) that recieves an array of 5 images (urls), shows them side by side with 3 buttos in front.
As you click button1 it append a text1 do a file1 if you do the same on button2 a text2 to a file2.
I want to do this for lots (7000)... | TKinter : Image preview - Buttons | What's the easiest way to make a GUI in python (TKinter) that recieves an array of 5 images (urls), shows them side by side with 3 buttos in front.
As you click button1 it append a text1 do a file1 if you do the same on button2 a text2 to a file2.
I want to do this for lots (7000) groups of 5 pics
Something like this:
... | [
"I'm not sure what you're after when you ask for the \"easiest way\". There are at least a couple solutions, both of which are very straight-forward. You can either choose to organize your \"page\" as a grid, putting each image and button in a column, or you could create an object that represents one row and then c... | [
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004644990_python_tkinter_user_interface.txt |
Q:
Global name 'display' is not defined during "exec()"
I tried executing a simple line drawing program using exec().
It worked fine. But when I tried to execute the same program by sending it through a tcp/ip network(the server reads the program and sends it to the client which receives it to a variable(b) of string... | Global name 'display' is not defined during "exec()" | I tried executing a simple line drawing program using exec().
It worked fine. But when I tried to execute the same program by sending it through a tcp/ip network(the server reads the program and sends it to the client which receives it to a variable(b) of string type) and then i use exec(b) in the client to execute it ... | [
"What exactly is the string you send and then exec? \nYour error sounds like you only send the main() function, which won't work. \n",
"For an example of one approach to networking and graphics, take a look at https://launchpad.net/game\n"
] | [
0,
0
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0004645935_networking_python.txt |
Q:
different behavior when using re.finditer and re.match
I'm working on a regex to to collect some values from a page through some script. I'm using re.match in condition but it returns false but if i use finditer it returns true and body of condition is executed. i tested that regex in my own built tester and it's ... | different behavior when using re.finditer and re.match | I'm working on a regex to to collect some values from a page through some script. I'm using re.match in condition but it returns false but if i use finditer it returns true and body of condition is executed. i tested that regex in my own built tester and it's working there but not in script.
here is sample script.
resu... | [
"re.finditer() returns an iterator object even if there is no match (so an if RE_Add0.finditer(each) would always return True). You have to actually iterate over the object to see if there are actual matches.\nThen, re.match() only matches at the beginning of the string, not anywhere in the string as re.search() or... | [
3,
1,
0
] | [] | [] | [
"python",
"python_2.5",
"regex"
] | stackoverflow_0004646904_python_python_2.5_regex.txt |
Q:
Try all the combinations (cases) Function
I've been struggling with the cutting stock problem for a while, and I need to do a funcion that given an array of values, gives me an array of array for all the possible combinations.
I trying to do this function, but (as everything in python), I think someone must have d... | Try all the combinations (cases) Function | I've been struggling with the cutting stock problem for a while, and I need to do a funcion that given an array of values, gives me an array of array for all the possible combinations.
I trying to do this function, but (as everything in python), I think someone must have done it better :).
I think the name of the funct... | [
">>> from itertools import permutations\n>>> x = range(3)\n>>> list(permutations(x))\n[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]\n>>> \n\n",
"Do you mean itertools.combinations?\n",
">>> from itertools import combinations\n>>> list(combinations('abcd', 2))\n\n"
] | [
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004645822_python.txt |
Q:
SVN Error When Accessed Through Python
I have Python 3.1, Subversion 1.6.12, and PySVN installed on Windows XP.
If I open a Python terminal and do
import subprocess
print subprocess.check_output(['svnlook','youngest','D:/svn-repos/myrepo'])
I get the expected revision number.
However, if I add this to Subversion'... | SVN Error When Accessed Through Python | I have Python 3.1, Subversion 1.6.12, and PySVN installed on Windows XP.
If I open a Python terminal and do
import subprocess
print subprocess.check_output(['svnlook','youngest','D:/svn-repos/myrepo'])
I get the expected revision number.
However, if I add this to Subversion's post-commit.bat, it fails with the error "... | [
"I ended up using a different SVN binding, svn-python, and that worked. I can only guess there was some mismatch between the Windows binaries for the version of subversion and PySVN.\n",
"i think you don't need to use the subprocess (just for this) , you see you can just use :\nimport os\n\nstdout = os.popen('svn... | [
1,
0
] | [] | [] | [
"python",
"svn",
"windows"
] | stackoverflow_0004199501_python_svn_windows.txt |
Q:
How to find all text files with Regex?
Hey there.
I'm using glob.glob function in order to get a list of all .txt files on a path that i provide.
The regex I'm feeding the function as C:\build\*.txt, but it works only for the root directory, and I'd like to find all text files in c:\build\, also c:\build\files\ha.... | How to find all text files with Regex? | Hey there.
I'm using glob.glob function in order to get a list of all .txt files on a path that i provide.
The regex I'm feeding the function as C:\build\*.txt, but it works only for the root directory, and I'd like to find all text files in c:\build\, also c:\build\files\ha.txt for example.
How is it possible?
Thankss... | [
"Notice that glob.glob will accept unix shell wildcards and not regex objects (see the documentation).\nYou might accomplish the feat of getting all .txt files from all sub directories by using os.walk. A method to give you such a list could be something like this:\ndef get_all_txts_on_dir(path):\n import os\n ... | [
5,
0
] | [] | [] | [
"glob",
"python"
] | stackoverflow_0004648115_glob_python.txt |
Q:
How to properly assign serial output to value with ser.readlines for further usage?
I am newbie and wrote a script, which initiates communication ("/?!") to an energy meter through serial USBport and reads out the incoming energy log. It extracts different values from the output and writes those into a local sqlit... | How to properly assign serial output to value with ser.readlines for further usage? | I am newbie and wrote a script, which initiates communication ("/?!") to an energy meter through serial USBport and reads out the incoming energy log. It extracts different values from the output and writes those into a local sqlite-db. It is suppose to run as a cronjob every 15min. A php-website will visualize the sql... | [
"I think instead of \nser.readlines(eol='!') = z\nfor line in z: \n\nyou probably want\nfor line in ser.readlines(eol='!'):\n\n"
] | [
0
] | [] | [] | [
"logging",
"pyserial",
"python",
"regex",
"sqlite"
] | stackoverflow_0004648034_logging_pyserial_python_regex_sqlite.txt |
Q:
Upper diagonal of a 2D numpy array
This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.
Given a 4x4 array, I'd like the index locations at the X's:
[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0... | Upper diagonal of a 2D numpy array | This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.
Given a 4x4 array, I'd like the index locations at the X's:
[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0 0 X ]
Giving:
[ (0,0), (0,1), (0,2), (... | [
"carnieri beat me to the numpy.triu_indices answer, but there is also numpy.triu_indices_from which takes an array as input rather than the dimensions.\n",
"Though the format of index locations is different, it seems like you want the function numpy.triu_indices.\n",
"scipy.linalg.triu and nonzero\n",
"If you... | [
8,
6,
2,
2
] | [] | [] | [
"numpy",
"python",
"slice"
] | stackoverflow_0004445109_numpy_python_slice.txt |
Q:
Errors with Python's mechanize module
I'm using the mechanize module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for ... | Errors with Python's mechanize module | I'm using the mechanize module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.
I just call it with:
se... | [
"$ perl -0777 -ne'print qq($1) if /__all__ = \\[(.*?)\\]/s' __init__.py | grep Error \n\n'BrowserStateError',\n'ContentTooShortError',\n'FormNotFoundError',\n'GopherError',\n'HTTPDefaultErrorHandler',\n'HTTPError',\n'HTTPErrorProcessor',\n'LinkNotFoundError',\n'LoadError',\n'ParseError',\n'RobotExclusionError',\n'U... | [
8,
3,
1
] | [] | [] | [
"exception",
"mechanize",
"python",
"urllib2"
] | stackoverflow_0000151929_exception_mechanize_python_urllib2.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.