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:
Using set in Python inside a loop
I have the following list in Python:
[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
I want to group them into [[1,2,7],[3,4,6,9]]
My code to do this looks like this:
l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in l:
for lfi in lf:
if lfi.intersection(set(li)):
... | Using set in Python inside a loop | I have the following list in Python:
[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
I want to group them into [[1,2,7],[3,4,6,9]]
My code to do this looks like this:
l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in l:
for lfi in lf:
if lfi.intersection(set(li)):
lfi=lfi.union(set(li))
... | [
"The problem is here:\nlfi=lfi.union(set(li))\n\nYou are not modifying the set. You are creating a new set which is then discarded. The original set is still in the lf array. Use update instead:\nlfi.update(li)\n\nThis modifies the original set instead of creating a new one. The result after making this change:\n[s... | [
5,
2,
0
] | [] | [] | [
"dataset",
"python"
] | stackoverflow_0002519682_dataset_python.txt |
Q:
Importing a function/class from a Python module of the same name
I have a Python package mymodule with a sub-package utils (i.e. a subdirectory which contains modules each with a function). The functions have the same name as the file/module in which they live.
I would like to be able to access the functions as fo... | Importing a function/class from a Python module of the same name | I have a Python package mymodule with a sub-package utils (i.e. a subdirectory which contains modules each with a function). The functions have the same name as the file/module in which they live.
I would like to be able to access the functions as follows,
from mymodule.utils import a_function
Strangely however, someti... | [
"Do your utils functions need to import other utils functions? (or import other modules that import other utils functions). Suppose for example that a_function.py contains contains \"from mymodule.utils import b_function\". Here's your utils.py with a bunch of extra comments:\n# interpreter is executing utils.py\... | [
7
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0002519511_import_module_python.txt |
Q:
Python OSError not reporting errors
Ive got this snippet that Im using to convert image files to tiff. I want to be informed when a file fails to convert. Imagemagick exits 0 when successfully run, so I figured the following snippet would report the issue. However no errors are being reported at all.
def i... | Python OSError not reporting errors | Ive got this snippet that Im using to convert image files to tiff. I want to be informed when a file fails to convert. Imagemagick exits 0 when successfully run, so I figured the following snippet would report the issue. However no errors are being reported at all.
def image(filePath,dirPath,fileUUID,shortFile)... | [
"os.system() does not throw an exception if the return value is non-zero. What you should do is capture the return value and check that:\nret = os.system(...)\nif ret == ...:\n\nOf course, what you should also do is replace os.system() with subprocess.\n",
"A better think will be to use check_call from the subpro... | [
5,
3,
1,
0
] | [] | [] | [
"imagemagick",
"python"
] | stackoverflow_0002520325_imagemagick_python.txt |
Q:
Django templates crashes with no sense
Hello I'm trying to use google visualization API along with django templates system. I got an error that don't know how to fix. The error is the following:
invalid_block_tag
raise self.error(token, "Invalid block tag: '%s'" % command)
django.template.TemplateSyntaxError:... | Django templates crashes with no sense | Hello I'm trying to use google visualization API along with django templates system. I got an error that don't know how to fix. The error is the following:
invalid_block_tag
raise self.error(token, "Invalid block tag: '%s'" % command)
django.template.TemplateSyntaxError: Invalid block tag: 'endfor'
The code is:
f... | [
"You goofed your for tag:\n{% for d in datos %}\n\n"
] | [
2
] | [] | [] | [
"django_templates",
"python"
] | stackoverflow_0002520618_django_templates_python.txt |
Q:
mongokit and django
I'm looking for good tutorial or really simple code to integrate mongokit and django
A:
http://www.peterbe.com/plog/how-and-why-to-use-django-mongokit would seem to cover this. BTW this was the first result on google for search term "mongokit django".
| mongokit and django | I'm looking for good tutorial or really simple code to integrate mongokit and django
| [
"http://www.peterbe.com/plog/how-and-why-to-use-django-mongokit would seem to cover this. BTW this was the first result on google for search term \"mongokit django\".\n"
] | [
5
] | [] | [] | [
"django",
"mongodb",
"python"
] | stackoverflow_0002520440_django_mongodb_python.txt |
Q:
What algorithms are suitable for this simple machine learning problem?
I have a what I think is a simple machine learning question.
Here is the basic problem: I am repeatedly given a new object and a list of descriptions about the object. For example: new_object: 'bob' new_object_descriptions: ['tall','old','funny... | What algorithms are suitable for this simple machine learning problem? | I have a what I think is a simple machine learning question.
Here is the basic problem: I am repeatedly given a new object and a list of descriptions about the object. For example: new_object: 'bob' new_object_descriptions: ['tall','old','funny']. I then have to use some kind of machine learning to find previously hand... | [
"An algorithm that seems to meet your requirements (and is perhaps similar to what John the Statistician is suggesting) is Semantic Hashing. The basic idea is that it trains a deep belief network (a type of neural network that some have called 'neural networks 2.0' and is a very active area of research right now) t... | [
9,
3,
3,
2,
1,
1
] | [] | [] | [
"artificial_intelligence",
"classification",
"machine_learning",
"neural_network",
"python"
] | stackoverflow_0002520018_artificial_intelligence_classification_machine_learning_neural_network_python.txt |
Q:
Django OpenID django-openid-auth Login Error
I get the following error when attempting to use django-openid-auth OpenID discovery error: No usable OpenID services found for *******@gmail.com
I have followed the instructions that come with it, though it seems there is something I am missing. the installation is on... | Django OpenID django-openid-auth Login Error | I get the following error when attempting to use django-openid-auth OpenID discovery error: No usable OpenID services found for *******@gmail.com
I have followed the instructions that come with it, though it seems there is something I am missing. the installation is on my localhost.
| [
"Are you supplying an email address or URL? OpenID needs a URL and *******@gmail.com is an email address.\n"
] | [
1
] | [] | [] | [
"django",
"openid",
"python"
] | stackoverflow_0002520144_django_openid_python.txt |
Q:
Avoid IF statement after condition has been met
I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible.
I have an if condition ... | Avoid IF statement after condition has been met | I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible.
I have an if condition to test the divisor value in order to avoid the div b... | [
"Don't worry. An if (a != 0) is cheap.\nThe alternative (if you really want one) could be to split the loop into two, and exit the first one once the divisor gets its value. But that sounds like it would make the code unnecessarily complex (difficult to read).\n",
"I would wrap your call in try/except blocks. The... | [
9,
6,
1
] | [] | [] | [
"if_statement",
"performance",
"python"
] | stackoverflow_0002521558_if_statement_performance_python.txt |
Q:
scoping error in recursive closure
why does this work:
def function1():
a = 10
... | scoping error in recursive closure | why does this work:
def function1():
a = 10
def function2():
print a
... | [
"The error doesn't seem to be very descriptive of the root problem. Mike explains the messages but that does not explain the root cause.\nThe actual problem is that in python you cannot assign to closed over variables. So in function2 'a' is read only. When you assign to it you create a new variable which, as Mike ... | [
14,
5,
3
] | [] | [] | [
"closures",
"python",
"recursion",
"scope"
] | stackoverflow_0002516652_closures_python_recursion_scope.txt |
Q:
Possible to use Python with Intel's Atom Developer SDK (C/C++)?
So I've made a game in Python and PyGame. Now I'm interested in submitting the game to Intel's March Developer Challenge. However, the developer challenge requires use of Intel's Atom Developer SDK (http://appdeveloper.intel.com/en-us/sdk), which only... | Possible to use Python with Intel's Atom Developer SDK (C/C++)? | So I've made a game in Python and PyGame. Now I'm interested in submitting the game to Intel's March Developer Challenge. However, the developer challenge requires use of Intel's Atom Developer SDK (http://appdeveloper.intel.com/en-us/sdk), which only has API's for C and C++.
I'm new to Python and PyGame, and have no ... | [
"Don't drop down to bare C if you can help it. Write bindings using Cython.\n"
] | [
1
] | [] | [] | [
"c",
"intel_atom",
"pygame",
"python",
"visual_studio"
] | stackoverflow_0002521774_c_intel_atom_pygame_python_visual_studio.txt |
Q:
Problem simulating a key press on Python for Symbian platform on a Nokia 5th ed phone
I am developing an app for Nokia 5800 Music Express (S60 5th edition) using PyS60 (Python for S60) ,I want to simulate a KeyPress say if a message comes,I detect a message and Press a Key.
There does exist a Keypress module for ... | Problem simulating a key press on Python for Symbian platform on a Nokia 5th ed phone | I am developing an app for Nokia 5800 Music Express (S60 5th edition) using PyS60 (Python for S60) ,I want to simulate a KeyPress say if a message comes,I detect a message and Press a Key.
There does exist a Keypress module for PyS60 for 2nd edition phones which allows this. However I have not been able to install it ... | [
"There are compatibility breaks between 2nd and 3rd editions so binaries developed on one won't work on the other.\nThere's also a keypress module for 3rd edition. It should also work on 5th edition but I haven't tested it myself.\n"
] | [
0
] | [] | [] | [
"nokia",
"pys60",
"python",
"symbian"
] | stackoverflow_0002522033_nokia_pys60_python_symbian.txt |
Q:
Query for model by key
What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner... | Query for model by key | What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't hav... | [
"There's a really easy way around this: Retrieve two records, and filter out the user's own one, if it's present.\ndef text_message(self, msg):\n user = User.get_or_insert(msg.sender)\n\n if not user.partner:\n # user doesn't have a partner, find them one\n other = db.Query(User).filter('partner... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002521012_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to reduce latency of data sent through a REST api
I have an application which obtains data in JSON format from one of our other servers. The problem I am facing is, there is is significant delay when when requesting for this information. Since a lot of data is passed (approx 1000 records per request where each... | How to reduce latency of data sent through a REST api | I have an application which obtains data in JSON format from one of our other servers. The problem I am facing is, there is is significant delay when when requesting for this information. Since a lot of data is passed (approx 1000 records per request where each record is pretty huge) is there a way that compression wou... | [
"I would first look at how much of this 8s delay is related to:\n\nServer side processing (how much took for the data to be generated)\nThere are a lot of techniques to improve this time, including:\n\nDB indexes\ncaching\na faster to_json library\n\n\nSome excellent resources are the NewRelic podcasts on Rails sca... | [
6,
3
] | [] | [] | [
"compression",
"latency",
"networking",
"python",
"ruby_on_rails"
] | stackoverflow_0002522204_compression_latency_networking_python_ruby_on_rails.txt |
Q:
does cProfile profile calls inside threads?
I ran cprofile on a bit of code, which among other things spawns several threads that do most of the work.
When I looked at the output of the profiling, I see no logging of all the functions that were called inside the threads. I am sure they were called, as they do stuf... | does cProfile profile calls inside threads? | I ran cprofile on a bit of code, which among other things spawns several threads that do most of the work.
When I looked at the output of the profiling, I see no logging of all the functions that were called inside the threads. I am sure they were called, as they do stuff that is easy to see such as writing to a DB etc... | [
"Found the answer here: link\n\nIt's worth pointing out that using the profiler only works (by default) on the main thread, and you won't get any information from other threads if you use them. This can be a bit of a gotcha as it is completely unmentioned in the profiler documentation.\n If you also want to profil... | [
8
] | [] | [] | [
"cprofile",
"multithreading",
"python"
] | stackoverflow_0002522452_cprofile_multithreading_python.txt |
Q:
Is it possible to autoload a file based on the namespace in PHP?
Would what mentioned in the title be possible? Python module style that is. See this example for what I exactly mean.
index.php
<?php
use Hello\World;
World::greet();
Hello/World.php
<?php
namespace Hello\World;
function greet() { echo 'Hello, World... | Is it possible to autoload a file based on the namespace in PHP? | Would what mentioned in the title be possible? Python module style that is. See this example for what I exactly mean.
index.php
<?php
use Hello\World;
World::greet();
Hello/World.php
<?php
namespace Hello\World;
function greet() { echo 'Hello, World!'; }
Would this be possible?
| [
"Yes, have a look at the example of spl_autoload_register\nnamespace Foobar;\n\nclass Foo {\n static public function test($name) {\n print '[['. $name .']]';\n }\n}\n\nspl_autoload_register(__NAMESPACE__ .'\\Foo::test'); // As of PHP 5.3.0\n\nnew InexistentClass;\n\n\nThe above example will output some... | [
5
] | [] | [] | [
"autoload",
"module",
"namespaces",
"php",
"python"
] | stackoverflow_0002522801_autoload_module_namespaces_php_python.txt |
Q:
Iterating over consecutive sublists in Python
Does Python offer a way to iterate over all "consecutive sublists" of a given list L - i.e. sublists of L where any two consecutive elements are also consecutive in L - or should I write my own?
(Example: if L = [1, 2, 3], then the set over which I want to iterate is {... | Iterating over consecutive sublists in Python | Does Python offer a way to iterate over all "consecutive sublists" of a given list L - i.e. sublists of L where any two consecutive elements are also consecutive in L - or should I write my own?
(Example: if L = [1, 2, 3], then the set over which I want to iterate is {[1], [2], [3], [1, 2], [2,3], [1, 2, 3]}. [1, 3] is... | [
"I don't think there's a built-in for exactly that; but it probably wouldn't be too difficult to code up by hand - you're basically just looping through all of the possible lengths from 1 to L.length, and then taking all substrings of each length.\nYou could probably use itertools.chain() to combine the sequences f... | [
2,
1,
1
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0002523236_iterator_python.txt |
Q:
requiring set of files to be made before running function in Ruffus pipeline
I'm using ruffus to write a pipeline. I have a function that gets called in parallel many times and it creates several files. I'd like to make a function "combineFiles()" that gets called after all those files have been made. Since the... | requiring set of files to be made before running function in Ruffus pipeline | I'm using ruffus to write a pipeline. I have a function that gets called in parallel many times and it creates several files. I'd like to make a function "combineFiles()" that gets called after all those files have been made. Since they run in parallel on a cluster, they will not all finish together. I wrote a func... | [
"I am the developer of Ruffus. I am not sure I entirely understand what you are trying to do but here goes:\nWaiting for jobs which take a different amount of time to finish in order to run the next stage of your pipeline is exactly what Ruffus is about so this hopefully is straightforward.\nThe first question is d... | [
2
] | [] | [] | [
"cluster_computing",
"distributed_computing",
"pipeline",
"python",
"ruffus"
] | stackoverflow_0002465953_cluster_computing_distributed_computing_pipeline_python_ruffus.txt |
Q:
Proper way to set object instance variables
I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean:
class User(object):
def setName(self,name):
#Do sanity checks on name
self._name = name
def setPassword(sel... | Proper way to set object instance variables | I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean:
class User(object):
def setName(self,name):
#Do sanity checks on name
self._name = name
def setPassword(self,password):
#Check password length > 6 ... | [
"It's generally correct, AFAIK, but you could clean it up with properties.\nclass User(object):\n\n def _setName(self, name=None):\n self._name = name\n\n def _getName(self):\n return self._name\n\n def _setPassword(self, password):\n self._password = password\n\n def _getPassword(s... | [
23,
9,
3,
2
] | [] | [] | [
"oop",
"pylons",
"python"
] | stackoverflow_0002521753_oop_pylons_python.txt |
Q:
Easiest ways to generate graphs from Python?
I'm using Python to process CSV files filled with data that I want to run calculations on, and then graph. I'm looking for a library to use that I can send processed CSV information to, or a dict of some sort, and then choose different graphing styles with.
Does anyo... | Easiest ways to generate graphs from Python? | I'm using Python to process CSV files filled with data that I want to run calculations on, and then graph. I'm looking for a library to use that I can send processed CSV information to, or a dict of some sort, and then choose different graphing styles with.
Does anyone have any recommendations?
| [
"I'm personally using matplotlib and am very happy with it.\n",
"Matplotlib and Gnuplot.py are popular choices. I've used both.\n",
"For client-side charts Open Flash Chart or Google Charts Tools.\n",
"I've been using matplotlib for about 3 years now to plot experimental data. Before I was using Excel and th... | [
10,
7,
4,
3,
1,
1
] | [] | [] | [
"google_visualization",
"graph",
"python",
"visualization"
] | stackoverflow_0002523689_google_visualization_graph_python_visualization.txt |
Q:
LXML E builder for java?
There is one thing I really love about LXML, and that the E builder. I love that I can throw XML together like this:
message = E.Person(
E.Name(
E.First("jack")
E.Last("Ripper")
)
E.PhoneNumber("555-555-5555")
)
To make:
<Person>
<Name>
<First>Jack</First>
<Last>Ri... | LXML E builder for java? | There is one thing I really love about LXML, and that the E builder. I love that I can throw XML together like this:
message = E.Person(
E.Name(
E.First("jack")
E.Last("Ripper")
)
E.PhoneNumber("555-555-5555")
)
To make:
<Person>
<Name>
<First>Jack</First>
<Last>Ripper</Last>
</Name>
<Phone... | [
"will be hard with pure Java, but if you can use Groovy in your projects then you could use the MarkupBuilder which comes very close to what you're asking for\ndef xml = new MarkupBuilder(writer)\nxml.records() {\n car(name:'HSV Maloo', make:'Holden', year:2006) {\n country('Australia')\n record(type:'speed'... | [
2
] | [] | [] | [
"java",
"lxml",
"python"
] | stackoverflow_0002523715_java_lxml_python.txt |
Q:
Python PyQt Timer Firmata
I am pretty new to python and working with firmata I am trying to play around with an arduino .
Here is what I want to happen:
Set arduino up with an LED as a
digital out
Set potentiometer to analog 0
Set PyQt timer up to update
potentiometer position in
application
Set a thr... | Python PyQt Timer Firmata | I am pretty new to python and working with firmata I am trying to play around with an arduino .
Here is what I want to happen:
Set arduino up with an LED as a
digital out
Set potentiometer to analog 0
Set PyQt timer up to update
potentiometer position in
application
Set a threshold in PyQt to turn
LED o... | [
"Self didn't need to be passed. I have no clue why it failed the first time, or why self is included already.\n",
"In your code 'a' is the class instance, so all methods, bound to it, already have self pointers passed as first params. \nWelcome to python, someday you'd like it :)\nIn contra, you can call any met... | [
0,
0
] | [] | [] | [
"arduino",
"firmata",
"pyqt",
"python"
] | stackoverflow_0002519699_arduino_firmata_pyqt_python.txt |
Q:
How to connect a variable to Entry widget?
I'm trying to associate a variable with a Tkinter entry widget, in a way that:
Whenever I change the value (the "content") of the entry, mainly by typing something into it, the variable automatically gets assigned the value of what I've typed. Without me having to push a... | How to connect a variable to Entry widget? | I'm trying to associate a variable with a Tkinter entry widget, in a way that:
Whenever I change the value (the "content") of the entry, mainly by typing something into it, the variable automatically gets assigned the value of what I've typed. Without me having to push a button "Update value " or something like that f... | [
"I think you want something like this. In the example below, I created a variable myvar and assigned it to be textvariable of both a Label and Entry widgets. This way both are coupled and changes in the Entry widget will reflect automatically in Label.\nYou can also set trace on variables, e.g. to write to stdout.\... | [
15
] | [] | [] | [
"python",
"tkinter",
"tkinter_entry",
"validation",
"variables"
] | stackoverflow_0002524031_python_tkinter_tkinter_entry_validation_variables.txt |
Q:
How can I add a code that is always executed by Waf before exit?
I want to make Waf generate a beep when it finishes the execution of any command that took more than 10 seconds.
I don't know how do add this and assure that the code executes when Waf exits.
This should run for any Waf command not only build.
I ch... | How can I add a code that is always executed by Waf before exit? | I want to make Waf generate a beep when it finishes the execution of any command that took more than 10 seconds.
I don't know how do add this and assure that the code executes when Waf exits.
This should run for any Waf command not only build.
I checked the Waf book but I wasn't able to find any indication about how ... | [
"In your wscript module, you can use the Python standard library's atexit to register callables that you want to be called when the process exit. For example:\nimport atexit\nimport time\n\nclass MayBeep(object):\n def __init__(self, deadline=10.0):\n self.deadline = time.time() + deadline\n def __call__(self... | [
4
] | [] | [] | [
"python",
"waf"
] | stackoverflow_0002522773_python_waf.txt |
Q:
Entity references and lxml
Here's the code I have:
from cStringIO import StringIO
from lxml import etree
xml = StringIO('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY test "This is a test">
]>
<root>
<sub>&test;</sub>
</root>''')
d1 = etree.parse(xml)
print '%r' % d1.find('/sub').text
par... | Entity references and lxml | Here's the code I have:
from cStringIO import StringIO
from lxml import etree
xml = StringIO('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY test "This is a test">
]>
<root>
<sub>&test;</sub>
</root>''')
d1 = etree.parse(xml)
print '%r' % d1.find('/sub').text
parser = etree.XMLParser(resolve_en... | [
"The \"unresolved\" Entity is left as child node of the element node sub\n>>> print d2.find('/sub')[0]\n&test;\n>>> d2.find('/sub').getchildren()\n[&test;]\n\n"
] | [
19
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0002524299_lxml_python_xml.txt |
Q:
Japanese in python function
I wrote a function in Python which is used to tell me whether the two words are similar or not.
Now I want to pass Japanese text in my same function. It is giving error "not a ascii character." I tried using utf-8 encoding, but then it giving the same error
Non-ASCII character '\xe3' in... | Japanese in python function | I wrote a function in Python which is used to tell me whether the two words are similar or not.
Now I want to pass Japanese text in my same function. It is giving error "not a ascii character." I tried using utf-8 encoding, but then it giving the same error
Non-ASCII character '\xe3' in file
Is there any way to do tha... | [
"This worked for me:\n# -*- coding: utf-8 -*-\n\ndef filterKeyword(keyword, adText, filterType):\n # same as yours\n\nfilterKeyword(u'ポケモン', u'黄色のポケモン', 'contains')\n\n",
"Please do not do this:\nadtext = str.lower(adText)\nkeyword = str.lower(keyword)\n\nPlease do this:\nadtext= adText.lower()\nkeyword = keyw... | [
3,
1,
0,
0,
0
] | [] | [] | [
"internationalization",
"python"
] | stackoverflow_0002522408_internationalization_python.txt |
Q:
command CHOICE in DOS batch replacement/reproduction in python
I want to reproduce the behavior of the command CHOICE in DOS batch but with python.
raw_input requires the user to type whatever then press the ENTER/RETURN key. What I really want is for the user to press a single key and the script to continue from ... | command CHOICE in DOS batch replacement/reproduction in python | I want to reproduce the behavior of the command CHOICE in DOS batch but with python.
raw_input requires the user to type whatever then press the ENTER/RETURN key. What I really want is for the user to press a single key and the script to continue from there.
| [
"For Unix, it uses sys, tty, termios modules.\nimport sys, tty, termios\nfd = sys.stdin.fileno()\nold_settings = termios.tcgetattr(fd)\ntty.setraw(sys.stdin.fileno())\nch = sys.stdin.read(1)\n\nFor Windows, it uses msvcrt module.\nimport msvcrt\nch = msvcrt.getch()\n\nSource\n",
"A small utility class to read sin... | [
3,
2
] | [] | [] | [
"batch_file",
"python"
] | stackoverflow_0002524693_batch_file_python.txt |
Q:
Django: testing get query
Okay, so I am sick of writing this...
res = Something.objects.filter(asdf=something)
if res:
single = res[0]
else:
single = None
if single:
# do some stuff
I would much rather be able to do something like this:
single = Something.objects.filter(asdf=something)
if single:
#do so... | Django: testing get query | Okay, so I am sick of writing this...
res = Something.objects.filter(asdf=something)
if res:
single = res[0]
else:
single = None
if single:
# do some stuff
I would much rather be able to do something like this:
single = Something.objects.filter(asdf=something)
if single:
#do some stuff
I want to be able to ... | [
"The django-annoying project includes a get_object_or_None shortcut which does this, although it's trivial to write it yourself.\n",
"Create a custom Manager which encapsulates the bit you're sick of repeating as a method (with a better name than the one below) or just write a utility function which does the same... | [
3,
2
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0002525026_django_django_models_django_queryset_python.txt |
Q:
Map only certain parts of the class to a database using SQLAlchemy?
When mapping an object using SQLAlchemy, is there a way to only map certain elements of a class to a database, or does it have to be a 1:1 mapping?
Example:
class User(object):
def __init__(self, name, username, password, year_of_birth):
... | Map only certain parts of the class to a database using SQLAlchemy? | When mapping an object using SQLAlchemy, is there a way to only map certain elements of a class to a database, or does it have to be a 1:1 mapping?
Example:
class User(object):
def __init__(self, name, username, password, year_of_birth):
self.name = name
self.username = username
self.passw... | [
"Your mapper can specify what columns to map, you could even map a single table to multiple objects and multiple tables to a single object.\nHere's the documentation for mapping a single object multiple times: http://www.sqlalchemy.org/docs/05/mappers.html#multiple-mappers-for-one-class\nWhat you want is to configu... | [
2
] | [] | [] | [
"database",
"python",
"sqlalchemy"
] | stackoverflow_0002519287_database_python_sqlalchemy.txt |
Q:
How can I catch non valid ASCII characters in Panic Coda?
Sometimes I get errors while coding, because of typing some combination of keys (eg. ALT + SHIFT + SQUARE BRACKET) in a wrong way. So I get Syntax Error in Python, but I can't see where the illegal character is, 'cause Coda do not show it to me. Any solutio... | How can I catch non valid ASCII characters in Panic Coda? | Sometimes I get errors while coding, because of typing some combination of keys (eg. ALT + SHIFT + SQUARE BRACKET) in a wrong way. So I get Syntax Error in Python, but I can't see where the illegal character is, 'cause Coda do not show it to me. Any solution?
| [
"Python uses the 7-bit ASCII character set for program text. So all you need to do is convert your program to ASCII by going to text > convert to ASCII. Any bad characters will automatically be removed. If you want to specifically know which characters were the bad ones, you can use diff to compare changed and unch... | [
1
] | [] | [] | [
"ascii",
"coda",
"python"
] | stackoverflow_0002525002_ascii_coda_python.txt |
Q:
Capture subprocess output
I learned that when executing commands in Python, I should use subprocess.
What I'm trying to achieve is to encode a file via ffmpeg and observe the program output until the file is done. Ffmpeg logs the progress to stderr.
If I try something like this:
child = subprocess.Popen(command, s... | Capture subprocess output | I learned that when executing commands in Python, I should use subprocess.
What I'm trying to achieve is to encode a file via ffmpeg and observe the program output until the file is done. Ffmpeg logs the progress to stderr.
If I try something like this:
child = subprocess.Popen(command, shell=True, stderr=subprocess.PI... | [
"communicate() blocks until the child process returns, so the rest of the lines in your loop will only get executed after the child process has finished running. Reading from stderr will block too, unless you read character by character like so:\nimport subprocess\nimport sys\nchild = subprocess.Popen(command, shel... | [
27,
1
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0002525263_python_subprocess.txt |
Q:
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
Update:
This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):
Solution:
r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-... | Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end | Update:
This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):
Solution:
r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$'
Original Question (albeit, after 3 edits)
I'm using Python and I'm not tryin... | [
"Try this regular expression:\n^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$\n\nThis regular expression does only allow hyphens to separate sequences of one or more characters of [a-zA-Z0-9].\n\nEdit Following up your comment: The expression (…)* allows the part inside the group to be repeated zero or more times. That means\na... | [
17,
4,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002525327_python_regex.txt |
Q:
Matching first set of elements with xpath
I have an xml document that looks like this.
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tos... | Matching first set of elements with xpath | I have an xml document that looks like this.
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
<bar type="artist"/> Bob Marley </bar>
<bar type="artist"/> Peter Tosh </bar>
<bar type="artist"/> Marlon Wayans... | [
"In order to get only sub elements of some \"indexed\" node:\n//foo[1]/bar[@type='artist']\n\nExmaple in C#:\nstring xml =\n @\"<root>\n <foo>\n <bar type='artist'> Artist 1 </bar>\n <bar type='artist'> Artist 2 </bar>\n <bar type='artist'> Artist 3 </bar>\n </foo>\... | [
2
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0002525627_lxml_python_xpath.txt |
Q:
QTreeWidget insertTopLevelItem - index given not accurately displayed in Tree?
I am unable to properly insert a QTreeWidgetItem at a specific index, in this case I am removing all QTreeWidgetItems from the tree, doing a custom sort on their Date Objects and then inserting them back into the QTreeWidget.
However, ... | QTreeWidget insertTopLevelItem - index given not accurately displayed in Tree? | I am unable to properly insert a QTreeWidgetItem at a specific index, in this case I am removing all QTreeWidgetItems from the tree, doing a custom sort on their Date Objects and then inserting them back into the QTreeWidget.
However, upon inserting (even one at a time) the QTreeWidgetItem is not inserted into the cor... | [
"You can do your custom sort without a need to refill tree. You just need to overload item's 'less' operator.\nNote, that QT figures out, what to draw in the cell, what size it should be, what text should it contain, by looking in item's\nvirtual QVariant data ( int column, int role ) const\n\nwhen you create an it... | [
2,
2
] | [] | [] | [
"pyqt",
"python",
"qt",
"qtreewidget",
"qtreewidgetitem"
] | stackoverflow_0002520282_pyqt_python_qt_qtreewidget_qtreewidgetitem.txt |
Q:
Access is denied error with pregenerated .pyc or .pyo files
I am getting an Access is denied error while I am trying to run the .pyo file by double click or from the command prompt.
Lets say I have abc.py (keeping main method entry point) which imports files xyz.py and imports wx etc.
I generate the .pyo file. But... | Access is denied error with pregenerated .pyc or .pyo files | I am getting an Access is denied error while I am trying to run the .pyo file by double click or from the command prompt.
Lets say I have abc.py (keeping main method entry point) which imports files xyz.py and imports wx etc.
I generate the .pyo file. But once I try to run abc.pyo I get the access is denied error.
I am... | [
"You can tell the system that your hw.pyo file is \"executable\", for example (in Linux, MacOSX, or any other Unix-y system) by executing the command chmod +w hw.pyo at the terminal shell prompt. Consider, for example, the following short and simple shell session:\n$ cat >hw.py\nprint('hello world')\n$ python2.5 -... | [
2,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002523961_python_wxpython.txt |
Q:
Writing code translator from Python to C?
I was asked to write a code translator that would take a Python program and produce a C program. Do you have any ideas how could I approach this problem or is it even possible?
A:
Shedskin: http://code.google.com/p/shedskin/
Boost Python: http://www.boost.org/doc/libs/1_... | Writing code translator from Python to C? | I was asked to write a code translator that would take a Python program and produce a C program. Do you have any ideas how could I approach this problem or is it even possible?
| [
"Shedskin: http://code.google.com/p/shedskin/\nBoost Python: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/index.html\nPyCXX: http://cxx.sourceforge.net/\nCython: http://www.cython.org/\nfrom http://wiki.python.org/moin/compile%20Python%20to%20C, there's a list of related projects.\nPyrex: http://www.cosc.ca... | [
25,
7,
4,
3
] | [] | [] | [
"c",
"code_translation",
"python"
] | stackoverflow_0002525518_c_code_translation_python.txt |
Q:
Inconsistency in modified/created/accessed time on mac
I'm having trouble using os.utime to correctly set the modification time on the mac (Mac OS X 10.6.2, running Python 2.6.1 from /usr/bin/python). It's not consistent with the touch utility, and it's not consistent with the properties displayed in the Finder's ... | Inconsistency in modified/created/accessed time on mac | I'm having trouble using os.utime to correctly set the modification time on the mac (Mac OS X 10.6.2, running Python 2.6.1 from /usr/bin/python). It's not consistent with the touch utility, and it's not consistent with the properties displayed in the Finder's "get info" window.
Consider the following command sequence. ... | [
"POSIX atime, mtime, ctime\nIt might help if you included a full script and its actual and expected outputs instead of the REPL fragments.\nimport sys, os, stat, time\n\ndef get_times(p):\n s = os.stat(p)\n return ( \n os.path.getatime(p),\n os.path.getmtime(p),\n os.path.getctime(p),\n ... | [
5
] | [] | [] | [
"macos",
"python",
"stat",
"touch"
] | stackoverflow_0002479690_macos_python_stat_touch.txt |
Q:
WebService client libraries for Python and Perl
I want to access web service in Python or/and Perl scripts. What are the most popular and reliable libraries today?
I read this question, and I know about SOAPpy and ZSI. Can anybody say something about this libraries? Are they reliable enough for use in production?
... | WebService client libraries for Python and Perl | I want to access web service in Python or/and Perl scripts. What are the most popular and reliable libraries today?
I read this question, and I know about SOAPpy and ZSI. Can anybody say something about this libraries? Are they reliable enough for use in production?
| [
"If you're talking about SOAP then for Python I would definitely recommend suds :\nhttps://fedorahosted.org/suds/\n",
"Checking couple of libraries for SOAP (including suds) only ZSI worked reliably for me. It is not complicated to use and it just works(tm). I recommend that.\n",
"Perl has fantastic CPAN librar... | [
2,
0,
0
] | [] | [] | [
"perl",
"python",
"web_services"
] | stackoverflow_0002524195_perl_python_web_services.txt |
Q:
Automatically Update Field when a Different Field is Changed
I have a model with a bunch of different fields like first_name, last_name, etc. I also have fields first_name_ud, last_name_ud, etc. that correspond to the last updated date for the related fields (i.e. when first_name is modified, then first_name_ud i... | Automatically Update Field when a Different Field is Changed | I have a model with a bunch of different fields like first_name, last_name, etc. I also have fields first_name_ud, last_name_ud, etc. that correspond to the last updated date for the related fields (i.e. when first_name is modified, then first_name_ud is set to the current date).
Is there a way to make this happen aut... | [
"Either write Field children that update both fields or use server-side triggers.\n",
"Thanks for your help. I ended up modifying the model's save method, which I think will work:\ndef save(self):\n current_date = date.today()\n if self.id:\n try:\n old = UserProfile.objects.get(pk = self... | [
3,
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0002521793_django_django_forms_django_models_python.txt |
Q:
Proper way in Python to raise errors while setting variables
What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it?
Is it bad to print errors from a class?
Do I have to return False if I'm raisi... | Proper way in Python to raise errors while setting variables | What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it?
Is it bad to print errors from a class?
Do I have to return False if I'm raising an exception?
Just want to make sure that I'm doing things righ... | [
"Your code is out of a context so is not obvious the right choice. Following some tips:\n\nDon't use NameError exception, it is only used when a name, as the exception itself said, is not found in the local or global scope, use ValueError or TypeError if the exception concerns the value or the type of the parameter... | [
67,
10,
4
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0002525845_error_handling_python.txt |
Q:
How do I get the path of the Python script I am running in?
Duplicate:
In Python, how do I get the path and name of the file that is currently executing?
How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]), however on Mac I only get the filename - not the full path as I ... | How do I get the path of the Python script I am running in? |
Duplicate:
In Python, how do I get the path and name of the file that is currently executing?
How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]), however on Mac I only get the filename - not the full path as I do on Windows.
No matter where my application is launched from, ... | [
"Use this to get the path of the current file. It will resolve any symlinks in the path.\nimport os\n\nfile_path = os.path.realpath(__file__)\n\nThis works fine on my mac. It won't work from the Python interpreter (you need to be executing a Python file).\n",
"import os\nprint os.path.abspath(__file__)\n\n",
"7... | [
607,
155,
142,
50
] | [
"If you have even the relative pathname (in this case it appears to be ./) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop off the last element (the script), then push (or for you, append) on whatever I... | [
-7
] | [
"path",
"python"
] | stackoverflow_0000595305_path_python.txt |
Q:
Settings module not found deploying django on a shared server
I'm trying to deploy my django project on a shared hosting as describe here
I have my project on /home/user/www/testa
I'm using this script
#!/usr/bin/python
import sys, os
sys.path.append("/home/user/bin/python")
sys.path.append('/home/user/www/test... | Settings module not found deploying django on a shared server | I'm trying to deploy my django project on a shared hosting as describe here
I have my project on /home/user/www/testa
I'm using this script
#!/usr/bin/python
import sys, os
sys.path.append("/home/user/bin/python")
sys.path.append('/home/user/www/testa')
os.chdir("/home/user/www/testa")
os.environ['DJANGO_SETTINGS... | [
"The line\nos.environ['DJANGO_SETTINGS_MODULE'] = \"settings.py\"\n\nshould be more like\nos.environ['DJANGO_SETTINGS_MODULE'] = \"settings\"\n\nbased on how you're setting up sys.path. That environment variable is supposed to contain the path to the module as it should be imported by Python, not the actual filena... | [
3
] | [] | [] | [
"django",
"fastcgi",
"python"
] | stackoverflow_0002526172_django_fastcgi_python.txt |
Q:
GQL how to select by UserProperty
Hey I have this code but it doesn't work because it is expecting a string. How can I make it work?
class Atable(BaseModel):
owner = db.UserProperty()
(...)
--------- // --------------
query = "SELECT * FROM Atable WHERE owner=", users.get_current_user()
results = db.G... | GQL how to select by UserProperty | Hey I have this code but it doesn't work because it is expecting a string. How can I make it work?
class Atable(BaseModel):
owner = db.UserProperty()
(...)
--------- // --------------
query = "SELECT * FROM Atable WHERE owner=", users.get_current_user()
results = db.GqlQuery(query)
How can I fix that sear... | [
"You could try the GQL way:\nresults = db.GqlQuery(\"SELECT * FROM Atable WHERE owner = :1\", users.get_current_user().key())\n\nor the Python Query way:\nquery = db.Query(Atable)\nresults = query.filter('owner =', users.get_current_user())\n\n",
"query = GqlQuery(\"SELECT * FROM Atable WHERE owner = :1\", users.... | [
3,
2,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002525180_django_google_app_engine_python.txt |
Q:
Creating a "less"-like console pager interface for pysqlite3 database
I would like to add some interactive capability to a python CLI application I've writen that stores data in a SQLite3 database. Currently, my app reads-in a certain type of file, parses and analyzes, puts the analysis data into the db, and spit... | Creating a "less"-like console pager interface for pysqlite3 database | I would like to add some interactive capability to a python CLI application I've writen that stores data in a SQLite3 database. Currently, my app reads-in a certain type of file, parses and analyzes, puts the analysis data into the db, and spits the formatted records to stdout (which I generally pipe to a file). Ther... | [
"You might want to take a look at urwid. It is a console user interface library for Python. The examples should be more than enough to convince you that this is what you want, if you really want to go text-console UI.\nI'd use something like pygtk instead though.\n",
"After looking around a bit, I found that less... | [
2,
2
] | [] | [] | [
"linux",
"python",
"sqlite"
] | stackoverflow_0002526212_linux_python_sqlite.txt |
Q:
Game login authentication and security
First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd... | Game login authentication and security | First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd party applications (bots) to WPE packet man... | [
"This is a tough problem, because the code runs on the client. The replay problem can be solved by using a challenge by letting the server sending a random token which the client adds to the string to be encrypted. This way, the password string will be different each time, and replaying the encrypted string doesn't... | [
1,
1,
1,
0
] | [] | [] | [
"authentication",
"python",
"security"
] | stackoverflow_0002526110_authentication_python_security.txt |
Q:
Can I avoid a threaded UDP socket in Python dropping data?
First off, I'm new to Python and learning on the job, so be gentle!
I'm trying to write a threaded Python app for Windows that reads data from a UDP socket (thread-1), writes it to file (thread-2), and displays the live data (thread-3) to a widget (gtk.Ima... | Can I avoid a threaded UDP socket in Python dropping data? | First off, I'm new to Python and learning on the job, so be gentle!
I'm trying to write a threaded Python app for Windows that reads data from a UDP socket (thread-1), writes it to file (thread-2), and displays the live data (thread-3) to a widget (gtk.Image using a gtk.gdk.pixbuf). I'm using queues for communicating d... | [
"UDP doesn't verify the target received it (like TCP does) - you must implement retransmission and such in your applications if you want to ensure all of the data arrives. Do you control the sending UDP source?\n",
"UDP is, by definition, unreliable. You must not write programs that expect UDP datagrams to alway... | [
4,
2
] | [
"Edit - Struck out listen/accept sentence, thanks Daniel, I was just coming to remove it when I saw your comment :)\nI'd suggest that this is a network programming issue, rather than python per-se.\nYou've set a packet-per-second rate and a duration to define the number of recv calls you make to your UDP socket. I ... | [
-1,
-1,
-1
] | [
"gtk",
"multithreading",
"pygtk",
"python",
"sockets"
] | stackoverflow_0002456727_gtk_multithreading_pygtk_python_sockets.txt |
Q:
pyInotify performance
I have a very large directory tree I am wanting pyInotify to watch.
Is it better to have pyInotify watch the entire tree or is it better to have a number of watches reporting changes to specific files ?
Thanks
A:
If you're going to watch only a few files in a huge tree, it makes sense to w... | pyInotify performance | I have a very large directory tree I am wanting pyInotify to watch.
Is it better to have pyInotify watch the entire tree or is it better to have a number of watches reporting changes to specific files ?
Thanks
| [
"If you're going to watch only a few files in a huge tree, it makes sense to watch individual files. On the other hand, if you're going to watch almost all files in the tree, watching the entire tree instead makes sense. To know the point of turn exactly, you must benchmark both to see which one performs better.\n"... | [
0
] | [] | [] | [
"pyinotify",
"python"
] | stackoverflow_0002526273_pyinotify_python.txt |
Q:
Python Permutation Program Flow help
i found this code at activestate, it takes a string and prints permutations of the string.
I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch!
import sys
def prin... | Python Permutation Program Flow help | i found this code at activestate, it takes a string and prints permutations of the string.
I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch!
import sys
def printList(alist, blist=[]):
if not len(ali... | [
"You can figure out how printList behaves by drawing a recursion tree. Each node consists of two elements: an alist and a blist. The root has the alist with the initial sequence of items you want to permute, and an empty blist.\nEach node of the tree has one branch for each element of that node's alist; you move fr... | [
6,
3,
0
] | [] | [] | [
"python",
"recursion",
"workflow"
] | stackoverflow_0002526540_python_recursion_workflow.txt |
Q:
How do I join three tables with SQLalchemy and keeping all of the columns in one of the tables?
So, I have three tables:
The class defenitions:
engine = create_engine('sqlite://test.db', echo=False)
SQLSession = sessionmaker(bind=engine)
Base = declarative_base()
class Channel(Base):
__tablename__ = 'channel'... | How do I join three tables with SQLalchemy and keeping all of the columns in one of the tables? | So, I have three tables:
The class defenitions:
engine = create_engine('sqlite://test.db', echo=False)
SQLSession = sessionmaker(bind=engine)
Base = declarative_base()
class Channel(Base):
__tablename__ = 'channel'
id = Column(Integer, primary_key = True)
title = Column(String)
description = Column(St... | [
"Option-1:\nSubscription is just a many-to-many relation object, and I would suggest that you model it as such rather then as a separate class. See Configuring Many-to-Many Relationships documentation of SQLAlchemy/declarative. \nYou model with the test code becomes:\nfrom sqlalchemy import create_engine, Column, I... | [
14,
1,
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy",
"sqlite"
] | stackoverflow_0002524600_python_sql_sqlalchemy_sqlite.txt |
Q:
How do I make a dialog box that waits for user response?
When you tkSimpleDialog.askinteger, the program stalls and waits for user input. What are the basics of writing my own method that would have the same effect? I want to make the same kind of dialog box, I just want to be able to request more information.
Th... | How do I make a dialog box that waits for user response? | When you tkSimpleDialog.askinteger, the program stalls and waits for user input. What are the basics of writing my own method that would have the same effect? I want to make the same kind of dialog box, I just want to be able to request more information.
The problem that I'm having is that when I open the new window u... | [
"First off, if you can use some other widget system like PyGtk or PyQt, you should seriously consider it. Tkinter is ancient, and the newer libraries have a lot more functionality (read: more things you don't have to reinvent). I've used PyGtk and like it a lot more than Tkinter, which I used in the old Python 1.... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0002527247_python_tkinter.txt |
Q:
How do I install a python package
I want to install this python package:
http://pypi.python.org/pypi/netifaces/0.5
But I don't know how and I know nothing about python. Still, I guess there is a standardized way to install it. Am I right?
Thanks in advance
A:
From http://pypi.python.org/pypi:
to use a package f... | How do I install a python package | I want to install this python package:
http://pypi.python.org/pypi/netifaces/0.5
But I don't know how and I know nothing about python. Still, I guess there is a standardized way to install it. Am I right?
Thanks in advance
| [
"From http://pypi.python.org/pypi:\n\nto use a package from this index\n either \"pip install package\" or\n download, unpack and \"python setup.py\n install\" it.\n\nThat said, often distributions of Linux package a lot in their repositories, so try those too.\n",
"Check easy_install : http://peak.telecommuni... | [
2,
0,
0
] | [] | [] | [
"installation",
"linux",
"package",
"python"
] | stackoverflow_0002527461_installation_linux_package_python.txt |
Q:
Error handling with Python + Pylons
What is the proper way to handle errors with Python + Pylons?
Say a user sets a password via a form that, when passed to a model class via the controller, throws an error because it's too short. How should that error be handled so that an error message gets displayed on the web... | Error handling with Python + Pylons | What is the proper way to handle errors with Python + Pylons?
Say a user sets a password via a form that, when passed to a model class via the controller, throws an error because it's too short. How should that error be handled so that an error message gets displayed on the web page rather than the entire script termi... | [
"What are you using to validate your forms? I'm using formalchemy. It validates the input data using built-in and custom validators, and feeds a list with the errors it finds. You can then display that list in any way you want in your template.\nDocumentation here.\n",
"I use formencode @validate decorator. It is... | [
2,
1,
1
] | [] | [] | [
"error_handling",
"pylons",
"python"
] | stackoverflow_0002526458_error_handling_pylons_python.txt |
Q:
compare two files in python
in a.txt i have the text(line one after the other)
login;user;name
login;user;name1
login;user
in b.txt i have the text
login;user
login;user
login;user;name2
after comparing it should display in a text file as
login;user;name
login;user;name1
login;user;name2....
How can it be don... | compare two files in python | in a.txt i have the text(line one after the other)
login;user;name
login;user;name1
login;user
in b.txt i have the text
login;user
login;user
login;user;name2
after comparing it should display in a text file as
login;user;name
login;user;name1
login;user;name2....
How can it be done using python?
| [
"for a, b in zip(open('a'), open('b')):\n print(a if len(a.split(';')) == 3 else b)\n\n",
"Perhaps the standard-lib difflib module can be of help - check out its documentation. Your question is not clear enough for a more complete answer.\n",
"Based on the vague information given, I would try something like ... | [
4,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002523329_python_string.txt |
Q:
(interactive) graph as in graph theory on a web page?
Possible Duplicate:
Graph visualization code in javascript?
I have to integrate a graph with nodes and edges on a web page. Ideally, i would like to be able to interact with it (like moving the nodes around).
Actually, i'm beginning by representing trees, so ... | (interactive) graph as in graph theory on a web page? |
Possible Duplicate:
Graph visualization code in javascript?
I have to integrate a graph with nodes and edges on a web page. Ideally, i would like to be able to interact with it (like moving the nodes around).
Actually, i'm beginning by representing trees, so i would appreciate to be able to collapse subtrees.
How ca... | [
"Two other options are:\n\nPrefuse Flare which is in flash\nJavaScript InfoVis Toolkit (JIT)\n\n",
"RaphaelJS may be of interest to you. Particularly this example.\n",
"http://processingjs.org/ might have what you're looking for.\n",
"I'd go for SVG (all 'newer' browsers implement it more or less; older via p... | [
5,
3,
1,
0
] | [] | [] | [
"ajax",
"graph",
"javascript",
"python"
] | stackoverflow_0002525781_ajax_graph_javascript_python.txt |
Q:
Speex in Python
How can I use Speex to encode/decode from within python? Are there any wrappers?
I found an old project pySpeex but it is obsolete now (requires Python 2.2).
A:
I think starting from pySpeex (and tweaking any issue that may arise if you're using Python 2.6, say, in lieu of 2.2) is by far the pa... | Speex in Python | How can I use Speex to encode/decode from within python? Are there any wrappers?
I found an old project pySpeex but it is obsolete now (requires Python 2.2).
| [
"I think starting from pySpeex (and tweaking any issue that may arise if you're using Python 2.6, say, in lieu of 2.2) is by far the path of least resistance -- there aren't that many backward incompatibilities between 2.2 and 2.6, after all, so the amount of work should be pretty limited (and then you can contribu... | [
1
] | [] | [] | [
"python",
"speex",
"wrapper"
] | stackoverflow_0002525494_python_speex_wrapper.txt |
Q:
Merging contents of two lists based on a if-loop
I have a minor problem while checking for elements in a list:
I have two files with contents something like this
file 1: file2:
47 358 47
48 450 49
49 56 50
I parsed both files into two lists and used the following code to... | Merging contents of two lists based on a if-loop | I have a minor problem while checking for elements in a list:
I have two files with contents something like this
file 1: file2:
47 358 47
48 450 49
49 56 50
I parsed both files into two lists and used the following code to check
for i in file_1:
for j in file_2:
j =... | [
"r1=open('file1').read().split()\nr2=open('file2').read().split()\n\nd=dict(zip(r2[1::2],r2[::2]))\n\noutput='\\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)\n\nopen('output_file','wb').write(output)\n\nTest\n>>> file1='47\\n48\\n49\\n50'\n>>> file2='358 47\\n450 49\\n56 50'\n>>>\n>>> r1=file1.split()\n>>> r... | [
2,
1,
1,
0,
0
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0002507090_list_loops_python.txt |
Q:
maintaining a large list in python
I need to maintain a large list of python pickleable objects. The list is too large to be all stored in the RAM, so some database\paging mechanism is required. I need that the mechanism will support fast access for close (nearby) areas in the list.
The list should implement all t... | maintaining a large list in python | I need to maintain a large list of python pickleable objects. The list is too large to be all stored in the RAM, so some database\paging mechanism is required. I need that the mechanism will support fast access for close (nearby) areas in the list.
The list should implement all the python-list features, but most of the... | [
"Using zc.blist can bring good results after all, and setting the \"cache_size\" option when creating the DB controls the size of the data that will remain in the RAM. The size of used RAM can grow bigger if you don't do \"transaction.commit\" often enough. By defining a large cache_size and doing transaction.commi... | [
2,
0,
0
] | [] | [] | [
"database",
"python",
"zodb"
] | stackoverflow_0002510218_database_python_zodb.txt |
Q:
What's the Python2.5 equivalent of Python2.6 translate with None as first param?
In Python 2.6, I can run the following fine to strip out chars like -()
'(123) 456-7890'.translate(None, '-(), ')
Python2.5 translate does not accept None, how can I do the above in 2.5?
A:
That should be possible with maketrans:
i... | What's the Python2.5 equivalent of Python2.6 translate with None as first param? | In Python 2.6, I can run the following fine to strip out chars like -()
'(123) 456-7890'.translate(None, '-(), ')
Python2.5 translate does not accept None, how can I do the above in 2.5?
| [
"That should be possible with maketrans:\nimport string\n'(123) 456-7890'.translate(string.maketrans('', ''), '-(), ')\n\nBut you can also use regular expressions which is more readable.\n",
"Use string.maketrans with empty arguments to create the identity translation table:\n\nstring.maketrans(from, to)\nReturn ... | [
3,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002365876_python.txt |
Q:
Is there a way to create a python object that will be not sortable?
Is there a possibility to create any python object that will be not sortable? So that will be an exception when trying to sort a list of that objects?
I created a very simple class, didn't define any comparison methods, but still instances of this... | Is there a way to create a python object that will be not sortable? | Is there a possibility to create any python object that will be not sortable? So that will be an exception when trying to sort a list of that objects?
I created a very simple class, didn't define any comparison methods, but still instances of this class are comparable and thus sortable. Maybe, my class inherits compari... | [
"You could define a __cmp__ method on the class and always raise an exception when it is called. That might do the trick.\nOut of curiosity, why?\n",
"As Will McCutchen has mentioned, you can define a __cmp__ method that raises an exception to prevent garden variety sorting. Something like this:\nclass Foo(objec... | [
7,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002367119_python.txt |
Q:
use proxy in python to fetch a webpage
I am trying to write a function in Python to use a public anonymous proxy and fetch a webpage, but I got a rather strange error.
The code (I have Python 2.4):
import urllib2
def get_source_html_proxy(url, pip, timeout):
# timeout in seconds (maximum number of seconds will... | use proxy in python to fetch a webpage | I am trying to write a function in Python to use a public anonymous proxy and fetch a webpage, but I got a rather strange error.
The code (I have Python 2.4):
import urllib2
def get_source_html_proxy(url, pip, timeout):
# timeout in seconds (maximum number of seconds willing for the code to wait in
# case there is ... | [
"urllib2.build_opener takes a list of handlers\nopener = urllib2.build_opener([proxy_handler])\n\n",
"The @ itself is a red herring, the traceback comes from the fact that it's trying to execute a x in host operation and, in that context, that means host has to be iterable (such as a string). You'll want to insp... | [
3,
0
] | [] | [] | [
"proxy",
"python"
] | stackoverflow_0002527668_proxy_python.txt |
Q:
Python MySQLdb placeholders syntax
I'd like to use placeholders as seen in this example:
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
Except I'd like to have the query be its own variable as I need to insert a query into multiple databases, as in:
query = "... | Python MySQLdb placeholders syntax | I'd like to use placeholders as seen in this example:
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
Except I'd like to have the query be its own variable as I need to insert a query into multiple databases, as in:
query = """UPDATE animal SET name = %s
... | [
"query = \"\"\"UPDATE animal SET name = %s\n WHERE name = %s\n \"\"\"\nvalues = (\"snake\", \"turtle\")\n\ncursor.execute(query, values)\ncursor2.execute(query, values)\n\nor if you want group them together...\narglist = [query, values]\ncursor.execute(*arglist)\ncursor2.execute(*arglist)\n\nbut... | [
5
] | [] | [] | [
"mysql",
"pylons",
"python"
] | stackoverflow_0002527941_mysql_pylons_python.txt |
Q:
Replace a whole line in a txt file
I'am new to Python 3 and could really use a little help. I have a txt file containing:
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\somewhere
FriendlyName=something
I have a python script that in the end, should change just two lines to:
TargetName=D:\new
Fri... | Replace a whole line in a txt file | I'am new to Python 3 and could really use a little help. I have a txt file containing:
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\somewhere
FriendlyName=something
I have a python script that in the end, should change just two lines to:
TargetName=D:\new
FriendlyName=Big
Could anyone help me, ple... | [
"import fileinput\nfor line in fileinput.FileInput(\"file\",inplace=1):\n sline=line.strip().split(\"=\")\n if sline[0].startswith(\"TargetName\"):\n sline[1]=\"new.txt\"\n elif sline[0].startswith(\"FriendlyName\"):\n sline[1]=\"big\"\n line='='.join(sline) \n print(line)\n\n",
"A... | [
5,
2,
2,
2,
0
] | [] | [] | [
"python",
"python_3.x",
"replace",
"text"
] | stackoverflow_0002527435_python_python_3.x_replace_text.txt |
Q:
Simplest way to handle and display errors in a Python Pylons controller without a helper class
I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times... | Simplest way to handle and display errors in a Python Pylons controller without a helper class | I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times for each variable.
Is this a correct way of doing it? Is there a better (but still simple) way? ... | [
"You could remove repetition from the code as a semi-measure:\nclass RegisterController(BaseController):\n\n def index(self):\n if request.POST:\n c.errors = {}\n u = User()\n for key in \"name email password\".split():\n try:\n value = re... | [
0
] | [] | [] | [
"forms",
"pylons",
"python"
] | stackoverflow_0002527992_forms_pylons_python.txt |
Q:
How to customize a modelform widget in Django 1.1?
I'm trying to modify a Django form to use a textarea instead of a normal input for the "address" field in my house form. The docs seem to imply this changed from Django 1.1 (which I'm using) to 1.2. But neither approach is working for me. Here's what I've tried:... | How to customize a modelform widget in Django 1.1? | I'm trying to modify a Django form to use a textarea instead of a normal input for the "address" field in my house form. The docs seem to imply this changed from Django 1.1 (which I'm using) to 1.2. But neither approach is working for me. Here's what I've tried:
class HouseForm(forms.ModelForm):
address = forms.T... | [
"I think Textarea needs to be assigned as a widget.\nTry\nclass HouseForm(forms.ModelForm):\n address = forms.CharField(widget=forms.Textarea)\n\n class Meta:\n model = House\n\n"
] | [
4
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002528195_django_django_forms_python.txt |
Q:
Need help parsing HTML with a regex in python
My string is
mystring = "<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)
100.00</span></td></tr>"
My problem here is I have to search and get the total amount
test = re.search("(Indian Rupees)(\d{2})(?:\D|$)", mystring)
but my test give me None... | Need help parsing HTML with a regex in python | My string is
mystring = "<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)
100.00</span></td></tr>"
My problem here is I have to search and get the total amount
test = re.search("(Indian Rupees)(\d{2})(?:\D|$)", mystring)
but my test give me None.
How can I get the values and values can be 10.00,... | [
"I strongly recommend using a real HTML parser for this, instead of a custom regular-expression.\nHere's an example with the BeautifulSoup library:\nfrom BeautifulSoup import BeautifulSoup\n\nstr = r'''\n<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees) 100.00</span></td></tr>\n'''\n\nsoup = Beau... | [
7,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002528198_python.txt |
Q:
Modify python USB device driver to only use vendor_id and product_id, excluding BCD
I'm trying to modify the Android device driver for calibre (an e-book management program) so that it identifies devices by only vendor id and product id, and excludes BCD.
The driver is a fairly simply python plugin, and is curre... | Modify python USB device driver to only use vendor_id and product_id, excluding BCD | I'm trying to modify the Android device driver for calibre (an e-book management program) so that it identifies devices by only vendor id and product id, and excludes BCD.
The driver is a fairly simply python plugin, and is currently set up to use all three numbers, but apparently, when Android devices use custom And... | [
"That is a data structure, it doesn't \"match\" anything per se. The change would have to happen in the code that uses that data structure to do the matching. Nothing you could do on the data structure itself would mean \"match all\" unless there's some kind of flag the matching code recognizes.\n"
] | [
0
] | [] | [] | [
"android",
"calibre",
"python",
"usb"
] | stackoverflow_0002528359_android_calibre_python_usb.txt |
Q:
Is Using Python to MapReduce for Cassandra Dumb?
Since Cassandra doesn't have MapReduce built in yet (I think it's coming in 0.7), is it dumb to try and MapReduce with my Python client or should I just use CouchDB or Mongo or something?
The application is stats collection, so I need to be able to sum values with g... | Is Using Python to MapReduce for Cassandra Dumb? | Since Cassandra doesn't have MapReduce built in yet (I think it's coming in 0.7), is it dumb to try and MapReduce with my Python client or should I just use CouchDB or Mongo or something?
The application is stats collection, so I need to be able to sum values with grouping to increment counters. I'm not, but pretend I'... | [
"Cassandra supports map reduce since version 0.6. (Current stable release is 0.5.1, but go ahead and try the new map reduce functionality in 0.6.0-beta3) To get started I recommend to take a look at the word count map reduce example in 'contrib/word_count'.\n",
"MongoDB has update-in-place, so MongoDB should be v... | [
6,
3
] | [] | [] | [
"cassandra",
"couchdb",
"mongodb",
"nosql",
"python"
] | stackoverflow_0002527173_cassandra_couchdb_mongodb_nosql_python.txt |
Q:
Django foreign key question
All,
i have the following model defined,
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharFi... | Django foreign key question | All,
i have the following model defined,
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
header... | [
"Given your:\np= header(title=name,created_by=id)\np.save()\n\nYou can now:\nc=criteria(details='some details', headerid=p)\nc.save()\no=options(opt_details='more details', headerid=p)\no.save()\n\nHope this helps.\n",
"Take advantage of <related>_set query managers, it's clearer and shorter than constructing and... | [
3,
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0002528867_django_django_models_django_templates_django_views_python.txt |
Q:
why python find not working
i am using python 2.5.2. The following code not working.
def findValue(self, text, findText):
index = text.find(findText)
print index
Although the findText is present in text, but it still returns None.
I have printed the values of text and findText and they are present.
Edi... | why python find not working | i am using python 2.5.2. The following code not working.
def findValue(self, text, findText):
index = text.find(findText)
print index
Although the findText is present in text, but it still returns None.
I have printed the values of text and findText and they are present.
Edit: I have fixed the issue.
The pr... | [
"You aren't returning a value from your function, you are only printing it. This means that the return value for the function will be None.\nTry adding return indexat the end of your code.\ndef myfind(self, text, findText):\n index = text.find(findText)\n return index\n\n",
"Python doesn't automatically r... | [
5,
1,
0
] | [] | [] | [
"find",
"python"
] | stackoverflow_0002513606_find_python.txt |
Q:
want to add url links to .csv datafeed using python
ive looked through the current related questions but have not managed to find anything similar to my needs.
Im in the process of creating a affiliate store using zencart - now one of the issues is that zencart is not designed for redirects and affiliate stores bu... | want to add url links to .csv datafeed using python | ive looked through the current related questions but have not managed to find anything similar to my needs.
Im in the process of creating a affiliate store using zencart - now one of the issues is that zencart is not designed for redirects and affiliate stores but it can be done. I will be changing the store so it acts... | [
"You could craft a python script using csv module like this:\n>>> import csv\n>>> cartWriter = csv.writer(open('yourcart.csv', 'wb'))\n>>> cartWriter.writerow(['Product', 'yourinfo', 'yourlink'])\n\nYou need to know how link should be formatted hoping that it could be composed using the other parameters present on ... | [
2,
0
] | [] | [] | [
"add",
"csv",
"datafeed",
"python",
"url"
] | stackoverflow_0002529238_add_csv_datafeed_python_url.txt |
Q:
How do I get minidom to ignore namespaces?
I am using minidom in Python and I'd like getElementsByTagName() to match elements purely by tag-name and ignore any namespaces. The documents are being parsed by minidom.parseString(). Is it possible?
A:
getElementsByTagName does match elements purely by tagName.
Do yo... | How do I get minidom to ignore namespaces? | I am using minidom in Python and I'd like getElementsByTagName() to match elements purely by tag-name and ignore any namespaces. The documents are being parsed by minidom.parseString(). Is it possible?
| [
"getElementsByTagName does match elements purely by tagName.\nDo you mean you want to match purely on localName? ie. the part of the tag name after the : (if any)? If so use the DOM Level 2 Core method getElementsByTagNameNS:\nels= document.getElementsByTagNameNS('*', 'tag')\n\n"
] | [
15
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002528852_python_xml.txt |
Q:
What is the difference between .get() and .fetch(1)
I have written an app and part of it is uses a URL parser to get certain data in a ReST type manner. So if you put /foo/bar as the path it will find all the bar items and if you put /foo it will return all items below foo
So my app has a query like
data = Paths.a... | What is the difference between .get() and .fetch(1) | I have written an app and part of it is uses a URL parser to get certain data in a ReST type manner. So if you put /foo/bar as the path it will find all the bar items and if you put /foo it will return all items below foo
So my app has a query like
data = Paths.all().filter('path =', self.request.path).get()
Which wor... | [
"You're looking at the docs for the wrong get() - you want the get() method on the Query object. In a nutshell, .fetch() always returns a list, while .get() returns the first result, or None if there are no results.\n",
"get() requires (I think) that there be exactly one element, and returns it, while fetch() ret... | [
11,
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002529198_google_app_engine_google_cloud_datastore_python.txt |
Q:
importing files in python
I have that file structure-
Blog\DataObjects\User.py
Blog\index.py
I want to import the function(say_hello) at User.py from index.py.
I am trying this code -
from Blog.DataObjects.User import say_hello
say_hello()
And I have that error -
Traceback (most recent call last):
File "in... | importing files in python | I have that file structure-
Blog\DataObjects\User.py
Blog\index.py
I want to import the function(say_hello) at User.py from index.py.
I am trying this code -
from Blog.DataObjects.User import say_hello
say_hello()
And I have that error -
Traceback (most recent call last):
File "index.py", line 1, in <module>
... | [
"Python expects in every directory that should be importable, a file __init__.py, which may be empty. So, if you correct your file structure to this:\nBlog/__init__.py\nBlog/index.py\nBlog/DataObjects/User.py\nBlog/DataObjects/__init__.py\n\nit should work, if the path to the directory is in your Python path (you c... | [
12,
1
] | [] | [] | [
"package",
"python",
"python_2.6"
] | stackoverflow_0002529466_package_python_python_2.6.txt |
Q:
Can Django be used for non web apps?
I noticed in the main Django introductin they show a feature that maps python objects to the database. This doesn't strike me as being mutually exclusive with with development, is there any reason why this can't be used for non web apps? Is it easy to separate out?
A:
The par... | Can Django be used for non web apps? | I noticed in the main Django introductin they show a feature that maps python objects to the database. This doesn't strike me as being mutually exclusive with with development, is there any reason why this can't be used for non web apps? Is it easy to separate out?
| [
"The part you're mentioning is the ORM and yes, ORMs are useful besides web development. In theory you could use the Django ORM for non-web stuff. However this can be a bit complicated because it is not released separately so you'd have to extract the code yourself (or you have to include the whole django package).... | [
8
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002529497_django_django_models_python.txt |
Q:
Duplicate django query set?
I have a simple django's query set like:
qs = AModel.objects.exclude(state="F").order_by("order")
I'd like to use it as follows:
qs[0:3].update(state='F')
expected = qs[3] # throws error here
But last statement throws:
"Cannot update a query once a slice has been taken."
How can I dup... | Duplicate django query set? | I have a simple django's query set like:
qs = AModel.objects.exclude(state="F").order_by("order")
I'd like to use it as follows:
qs[0:3].update(state='F')
expected = qs[3] # throws error here
But last statement throws:
"Cannot update a query once a slice has been taken."
How can I duplicate the query set?
| [
"It's the first line throwing the error: you can't do qs[0:3].update(). qs[0:3] is taking a slice; update() is updating the query.\nupdate() is meant for bulk updates, resulting in SQL queries like\nUPDATE app_model SET state = 'F' WHERE state <> 'F';\n\nYou're trying to update the first three items according to \... | [
2,
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001170235_django_django_models_python.txt |
Q:
google app engine - auto increment
I am new to Google App Engine,
I have this entites User class -
user_id - integer
user_name - string
password - string
I want to do auto increment for the user_id,How I can do this?
A:
You don't need to declare user_id, GAE will create a unique key id every time you insert a... | google app engine - auto increment | I am new to Google App Engine,
I have this entites User class -
user_id - integer
user_name - string
password - string
I want to do auto increment for the user_id,How I can do this?
| [
"You don't need to declare user_id, GAE will create a unique key id every time you insert a new row.\nclass User(db.Model):\nuser_name = db.StringProperty()\npassword = db.StringProperty()\n\nand to store a new user you will do:\nuser = User()\nuser.user_name = \"Username\"\nuser.password = \"Password\"\nuser.put()... | [
19,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002529620_google_app_engine_google_cloud_datastore_python.txt |
Q:
Sorting and aligning the contents of a text file in Python
In my program I have a text file that I read from and write to. However, I would like to display the contents of the text file in an aligned and sorted manner. The contents currently read:
Emily, 6
Sarah, 4
Jess, 7
This is my code where the text file in r... | Sorting and aligning the contents of a text file in Python | In my program I have a text file that I read from and write to. However, I would like to display the contents of the text file in an aligned and sorted manner. The contents currently read:
Emily, 6
Sarah, 4
Jess, 7
This is my code where the text file in read and printed:
elif userCommand == 'V':
print "High Scores... | [
"You could use csv module, and then could use sorted to sort.\nLet's says, scores1.txt have following\nRichard,100\nMichael,200\nRicky,150\nChaung,100\n\nTest\nimport csv\n\nreader=csv.reader(open(\"scores1.txt\"),dialect='excel')\nitems=sorted(reader)\nfor x in items:\n print x[0],x[1]\n\n...\nEmily 6\nJess 7... | [
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002528839_python.txt |
Q:
Faster or more memory-efficient solution in Python for this Codejam problem
I tried my hand at this Google Codejam Africa problem (the contest is already finished, I just did it to improve my programming skills).
The Problem:
You are hosting a party with G guests
and notice that there is an odd number
of guests! ... | Faster or more memory-efficient solution in Python for this Codejam problem | I tried my hand at this Google Codejam Africa problem (the contest is already finished, I just did it to improve my programming skills).
The Problem:
You are hosting a party with G guests
and notice that there is an odd number
of guests! When planning the party you
deliberately invited only couples and
gave each coupl... | [
"I don't know about python, but the problem itself is a classic. Given 2K - 1 numbers, each except one appearing an even number of times, find the one appearing an odd number of times.\nNeeded formulas:\n\nx xor x == 0 for all x\nx xor y == y xor x for all x and y\nx xor (y xor z) == (x xor y) xor z (associativity)... | [
5,
4,
2,
1,
1
] | [] | [] | [
"puzzle",
"python"
] | stackoverflow_0002529727_puzzle_python.txt |
Q:
Refresh decorator
I'm trying to write a decorator that 'refreshes' after being called, but where the refreshing only occurs once after the last function exits. Here is an example:
@auto_refresh
def a():
print "In a"
@auto_refresh
def b():
print "In b"
a()
If a() is called, I want the refresh function... | Refresh decorator | I'm trying to write a decorator that 'refreshes' after being called, but where the refreshing only occurs once after the last function exits. Here is an example:
@auto_refresh
def a():
print "In a"
@auto_refresh
def b():
print "In b"
a()
If a() is called, I want the refresh function to be run after exitin... | [
"To count the number of \"nestings\", in a thread-safe way, is a good example of using thread-local storage:\nimport threading\nmydata = threading.local()\nmydata.nesting = 0\n\nclass auto_refresh(object):\n\n def __init__(self, f):\n self.f = f\n\n def __call__(self, *args, **kwargs):\n mydata.nesting += 1... | [
5,
1,
0
] | [] | [] | [
"algorithm",
"decorator",
"python"
] | stackoverflow_0002529592_algorithm_decorator_python.txt |
Q:
Python c_types .dll functions (pari library)
Alright, so a couple days ago I decided to try and write a primitive wrapper for the PARI library. Ever since then I've been playing with ctypes library in loading the dll and accessing the functions contained using code similar to the following:
from ctypes import *
li... | Python c_types .dll functions (pari library) | Alright, so a couple days ago I decided to try and write a primitive wrapper for the PARI library. Ever since then I've been playing with ctypes library in loading the dll and accessing the functions contained using code similar to the following:
from ctypes import *
libcyg=CDLL("<path/cygwin1.dll") #It needs cygwin to... | [
"You have two problems here, one give fibo the correct return type and two convert the GEN return type to the value you are looking for.\nPoking around the source code a bit, you'll find that GEN is defined as a pointer to a long. Also, at looks like the library provides some converting/printing GENs. I focused i... | [
3
] | [] | [] | [
"ctypes",
"pari",
"python"
] | stackoverflow_0002527705_ctypes_pari_python.txt |
Q:
Get parent function
Is there a way to find what function called the current function? So for example:
def first():
second()
def second():
# print out here what function called this one
Any ideas?
A:
import inspect
def first():
return second()
def second():
return inspect.getouterframes( inspe... | Get parent function | Is there a way to find what function called the current function? So for example:
def first():
second()
def second():
# print out here what function called this one
Any ideas?
| [
"import inspect\n\ndef first():\n return second()\n\ndef second():\n return inspect.getouterframes( inspect.currentframe() )[1]\n\nfirst()[3] # 'first'\n\n",
"These work well for quickly adding minimal where-am-I debugging aids when you don't want to import yet another module. (CPython only, for debugging o... | [
11,
5,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0002529859_python.txt |
Q:
Python beautifulsoup trying to remove html tags 'span'
I am trying to remove
[<span class="street-address">
510 E Airline Way
</span>]
and I have used this clean function to remove the one that is in between < >
def clean(val):
if type(val) is not StringType: val = str(val)
val = re.sub(r... | Python beautifulsoup trying to remove html tags 'span' | I am trying to remove
[<span class="street-address">
510 E Airline Way
</span>]
and I have used this clean function to remove the one that is in between < >
def clean(val):
if type(val) is not StringType: val = str(val)
val = re.sub(r'<.*?>', '',val)
val = re.sub("\s+" , " ", val)
return va... | [
"Using re:\n>>> import re\n>>> s='[<span class=\"street-address\">\\n 510 E Airline Way\\n </span>]'\n>>> re.sub(r'\\[|\\]|\\s*<[^>]*>\\s*', '', s)\n'510 E Airline Way'\n\nUsing BeautifulSoup:\n>>> from BeautifulSoup import BeautifulSoup\n>>> s='[<span class=\"street-address\">\\n 51... | [
9
] | [] | [] | [
"beautifulsoup",
"python",
"regex"
] | stackoverflow_0002529978_beautifulsoup_python_regex.txt |
Q:
How To Collapse Just One Field in Django Admin?
The django admin allows you to specify fieldsets. You properly structure a tuple that groups different fields together. You can also specify classes for certain groups of fields. One of those classes is collapse, which will hide the field under a collapsable area. Th... | How To Collapse Just One Field in Django Admin? | The django admin allows you to specify fieldsets. You properly structure a tuple that groups different fields together. You can also specify classes for certain groups of fields. One of those classes is collapse, which will hide the field under a collapsable area. This is good for hiding rarely used or advanced fields ... | [
"Django doesn't have a built in way of doing this that I'm aware of but I can think of a couple of ways you could do something once, rather than having to manually modify lots of fieldsets.\nOne approach would be to use javascript to rewrite the page markup. Maybe the javascript could have a list of fieldnames and ... | [
5,
0
] | [
"If you want you can use fieldset in your admin.py and the field which you want to collapse use the class as collapse and remaining as foobar.\nRefer to django docs\n"
] | [
-3
] | [
"django",
"django_admin",
"python"
] | stackoverflow_0002420516_django_django_admin_python.txt |
Q:
Django Foreign key queries
In the following model:
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
... | Django Foreign key queries | In the following model:
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(h... | [
"Ironfroggy is right, but there is another more obvious way to get the relevant options and criteria objects. Django automatically creates a 'reverse relation' for every foreign key pointing at a model, and that is usually the name of the related model plus _set. So:\nmycriteria.options_set.all()\nmycriteria.header... | [
21,
9,
5,
4
] | [] | [] | [
"django",
"django_queryset",
"django_views",
"python"
] | stackoverflow_0002530158_django_django_queryset_django_views_python.txt |
Q:
Python idiom for '... if ... else ...' expression
How to write the expression shorter:
return '%.0f' % float_var if float_var else float_var
or
if float_var:
return formatted_string
else:
return None
Thanks!
A:
The expression <value> if <condition> else <other_value> is pretty idiomatic already -- cert... | Python idiom for '... if ... else ...' expression | How to write the expression shorter:
return '%.0f' % float_var if float_var else float_var
or
if float_var:
return formatted_string
else:
return None
Thanks!
| [
"The expression <value> if <condition> else <other_value> is pretty idiomatic already -- certainly more so than the other example, and is probably preferred whenever <value> is simple. This is Python's ternary operator, so if you were looking for something like <condition> ? <value> : <other_value>, that doesn't ex... | [
32,
6,
2,
1,
0
] | [] | [] | [
"idioms",
"python"
] | stackoverflow_0002529536_idioms_python.txt |
Q:
Installing Sphinx on App Engine - possible?
Following up on my last year's question on documentation, I now want to get started and try out Python-based Sphinx for putting together the developer documentation for a PHP CMS I've been working on.
Instead of setting up Python locally on my workstation, I would like t... | Installing Sphinx on App Engine - possible? | Following up on my last year's question on documentation, I now want to get started and try out Python-based Sphinx for putting together the developer documentation for a PHP CMS I've been working on.
Instead of setting up Python locally on my workstation, I would like to run it on a publicly accessible web server from... | [
"You do not need to install Sphinx on GAE at all.\nYou use Sphinx to create a directory of static HTML, CSS and JS. When this step is finished, you simply upload the output from Sphinx -- in it's entirety.\nThe output from Sphinx (HTML, CSS and JS) is simply served from one place. You upload the documentation fro... | [
6,
3,
1,
1
] | [] | [] | [
"google_app_engine",
"python",
"python_sphinx"
] | stackoverflow_0002522255_google_app_engine_python_python_sphinx.txt |
Q:
Why eclipse + pydev print() output look strange with two strings?
hay all, I just did the following:
a = input("give a word: ")
b = input("give another word: ")
c = a + " " + b
print("result is", c)
and get the output as follows:
give a word: name
give another word: word
result is name
word
my question is why ... | Why eclipse + pydev print() output look strange with two strings? | hay all, I just did the following:
a = input("give a word: ")
b = input("give another word: ")
c = a + " " + b
print("result is", c)
and get the output as follows:
give a word: name
give another word: word
result is name
word
my question is why the output on pydev or eclipse console in two lines? i expected to outp... | [
"It seems to me that Eclipse + PyDev is storing the newline character in the string as well. There are a few variants of the newline character depending on the operating system: \\n, \\r, \\r\\n.\nIn any case, I think the following should fix your problem:\na = raw_input(\"give a word: \").strip()\nb = raw_input(\"... | [
1,
0
] | [] | [] | [
"eclipse_3.5",
"pydev",
"python",
"python_3.x"
] | stackoverflow_0002530387_eclipse_3.5_pydev_python_python_3.x.txt |
Q:
Python regex group clarification
I have 0 experience with python, very little with regex and I'm trying to figure out what this small snippet of
python regex would give back from a http response header Set-Cookie entry:
REGEX_COOKIE = '([A-Z]+=[^;]+;)'
resp = urllib2.urlopen(req)
re.search(REGEX_COOKIE, resp.info(... | Python regex group clarification | I have 0 experience with python, very little with regex and I'm trying to figure out what this small snippet of
python regex would give back from a http response header Set-Cookie entry:
REGEX_COOKIE = '([A-Z]+=[^;]+;)'
resp = urllib2.urlopen(req)
re.search(REGEX_COOKIE, resp.info()['Set-Cookie']).group(1)
Can one giv... | [
"A Set-Cookie is a list of name value pairs, separated with semi-colons:\n\nHTTP/1.1 200 OK\nContent-type: text/html\nSet-Cookie: RMID=732423sdfs73242; expires=Fri, 31-Dec-2010 23:59:59 GMT\n\n(content of page)\n\nThe regular expression matches the name, the equals sign, and the value up to the first semi-colon - i... | [
4
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002530794_python_regex.txt |
Q:
How to get frame rate (fps) up in Python + Pygame?
I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Cor... | How to get frame rate (fps) up in Python + Pygame? | I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Core 2 Duo. This is a problem since I'm creating the game f... | [
"Let events come to you with event.wait\nDo you really need to do processing every tick? If not, use pygame.event.wait for your event loop to only process when an event comes in, and pygame.time.set_timer if you need periodic events like your SecondEvent.\nThis means you won't be drawing many frames during seconds... | [
8,
3
] | [] | [] | [
"frame_rate",
"performance",
"pygame",
"python"
] | stackoverflow_0002530478_frame_rate_performance_pygame_python.txt |
Q:
Python unit-testing with nose: Making sequential tests
I am just learning how to do unit-testing. I'm on Python / nose / Wing IDE.
(The project that I'm writing tests for is a simulations framework, and among other things it lets you run simulations both synchronously and asynchronously, and the results of the sim... | Python unit-testing with nose: Making sequential tests | I am just learning how to do unit-testing. I'm on Python / nose / Wing IDE.
(The project that I'm writing tests for is a simulations framework, and among other things it lets you run simulations both synchronously and asynchronously, and the results of the simulation should be the same in both.)
The thing is, I want so... | [
"In general, I'd recommend not making one test depend upon another. Do the synchronous_test, do the asynchronous_test, compare them each to the expected correct output, not to each other.\nSo something like:\nclass TestSimulate(TestCase):\n def setup(self):\n self.simpack = SimpackToTest()\n self.... | [
6,
6
] | [] | [] | [
"nose",
"python",
"unit_testing"
] | stackoverflow_0002530747_nose_python_unit_testing.txt |
Q:
Python: How to transfer varrying length arrays over a network connection
I need to transfer an array of varying length in which each element is a tuple of two integers. As an example:
path = [(1,1),(1,2)]
path = [(1,1),(1,2),(2,2)]
I am trying to use pack and unpack, however, since the array is of varying length... | Python: How to transfer varrying length arrays over a network connection | I need to transfer an array of varying length in which each element is a tuple of two integers. As an example:
path = [(1,1),(1,2)]
path = [(1,1),(1,2),(2,2)]
I am trying to use pack and unpack, however, since the array is of varying length I don't know how to create a format such that both know the format. I was tr... | [
"While you can use pack and unpack, I'd recommend using something like YAML or JSON to transfer your data.\n\nPack and unpack can lead to difficult to debug errors and incompatibilities if you change your interface and have different versions trying to communicate with each other.\nPickle can give security problems... | [
7,
1,
0,
0,
0
] | [] | [] | [
"arrays",
"networking",
"pack",
"python",
"unpack"
] | stackoverflow_0002530865_arrays_networking_pack_python_unpack.txt |
Q:
How do I translate Ruby's IO.popen calls into Python's subprocess.Popen calls?
I've read the documentation and I've tried lots of things in the REPL, and Googled, but I can't for the life of me understand how subprocess.Popen works in Python.
Here is some Ruby code I am using:
IO.popen("some-process") do |io|
wh... | How do I translate Ruby's IO.popen calls into Python's subprocess.Popen calls? | I've read the documentation and I've tried lots of things in the REPL, and Googled, but I can't for the life of me understand how subprocess.Popen works in Python.
Here is some Ruby code I am using:
IO.popen("some-process") do |io|
while(line = io.gets)
# do whatever with line
end
end
How do I translate this i... | [
"Probably the simplest \"close relative\" of your Ruby code in Python:\n>>> import subprocess\n>>> io = subprocess.Popen('ls', stdout=subprocess.PIPE).stdout\n>>> for line in io: print(line.strip())\n\n",
"import subprocess\n\nprocess = subprocess.Popen(['ls',], stdout=subprocess.PIPE)\nprint process.communicate(... | [
2,
0
] | [] | [] | [
"io",
"popen",
"python",
"ruby",
"subprocess"
] | stackoverflow_0002530906_io_popen_python_ruby_subprocess.txt |
Q:
Matplotlib canvas drawing
Let's say I define a few functions to do certain matplotlib actions, such as
def dostuff(ax):
ax.scatter([0.],[0.])
Now if I launch ipython, I can load these functions and start a new figure:
In [1]: import matplotlib.pyplot as mpl
In [2]: fig = mpl.figure()
In [3]: ax = fig.add_su... | Matplotlib canvas drawing | Let's say I define a few functions to do certain matplotlib actions, such as
def dostuff(ax):
ax.scatter([0.],[0.])
Now if I launch ipython, I can load these functions and start a new figure:
In [1]: import matplotlib.pyplot as mpl
In [2]: fig = mpl.figure()
In [3]: ax = fig.add_subplot(1,1,1)
In [4]: run funct... | [
"Why doesn't my answer to this SO question of yours about \"refresh decorator\" make it simple? I showed exactly what to do what you're again requesting here (by keeping a count of nestings -- incidentally, one that's also thread-safe) and you completely ignored my answer... peculiar behavior!-)\n"
] | [
2
] | [] | [] | [
"algorithm",
"matplotlib",
"python"
] | stackoverflow_0002531333_algorithm_matplotlib_python.txt |
Q:
Pointer argument to boost python
What's the best way to make a function that has pointer as argument work with boost python?
I see there are many possibilities for return values in the docs, but I don't know how to do it with arguments.
void Tesuto::testp(std::string* s)
{
if (!s)
cout << " NULL s" << ... | Pointer argument to boost python | What's the best way to make a function that has pointer as argument work with boost python?
I see there are many possibilities for return values in the docs, but I don't know how to do it with arguments.
void Tesuto::testp(std::string* s)
{
if (!s)
cout << " NULL s" << endl;
else
cout << s << en... | [
"As far as I can tell, after doing a bit of googling on the subject, is that you can't. Python doesn't support pointer argument types by default. If you wanted to, you could probably edit the python interpreter by hand, but this seems to me to be production code of some sort, so that probably isn't an option.\nEDIT... | [
4
] | [] | [] | [
"argument_passing",
"arguments",
"boost",
"pointers",
"python"
] | stackoverflow_0002385561_argument_passing_arguments_boost_pointers_python.txt |
Q:
Apply relative URL to an absolute URL
I have an absolute URL, and the URL that a link on that page points to. Is there a builtin function to apply a relative URL to an absolute URL?
Ie. "http://example.com/some/url", "/some/url/I/want/to/go/to" => "http://example.com/some/url/I/want/to/go/to"
A:
urlparse.urljoin... | Apply relative URL to an absolute URL | I have an absolute URL, and the URL that a link on that page points to. Is there a builtin function to apply a relative URL to an absolute URL?
Ie. "http://example.com/some/url", "/some/url/I/want/to/go/to" => "http://example.com/some/url/I/want/to/go/to"
| [
"urlparse.urljoin() does just this.\n"
] | [
9
] | [] | [] | [
"python",
"url"
] | stackoverflow_0002531538_python_url.txt |
Q:
In Python, what are some examples of when decorators greatly simplify a task?
Trying to find examples of when decorators might be really beneficial, and when not so much.
Sample code is appreciated.
A:
Decorators are simple syntax for a specific way to call higher-order functions, so if you're focusing just on t... | In Python, what are some examples of when decorators greatly simplify a task? | Trying to find examples of when decorators might be really beneficial, and when not so much.
Sample code is appreciated.
| [
"Decorators are simple syntax for a specific way to call higher-order functions, so if you're focusing just on the syntax it's unlikely to make a great difference. IOW, wherever you can say\n@mydecorator\ndef f(...):\n # body of f\n\nyou could identically say\ndef f(...):\n # body of f\nf = mydecorator(f)\n\nThe... | [
8,
4,
4,
1,
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002531696_decorator_python.txt |
Q:
Multiple Unpacking Assignment in Python when you don't know the sequence length
The textbook examples of multiple unpacking assignment are something like:
import numpy as NP
M = NP.arange(5)
a, b, c, d, e = M
# so of course, a = 0, b = 1, etc.
M = NP.arange(20).reshape(5, 4) # numpy 5x4 array
a, b, c, d, e = ... | Multiple Unpacking Assignment in Python when you don't know the sequence length | The textbook examples of multiple unpacking assignment are something like:
import numpy as NP
M = NP.arange(5)
a, b, c, d, e = M
# so of course, a = 0, b = 1, etc.
M = NP.arange(20).reshape(5, 4) # numpy 5x4 array
a, b, c, d, e = M
# here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each to a t... | [
"Python 3.x can do this easily:\na, b, *c = someseq\n\nPython 2.x needs a bit more work:\n(a, b), c = someseq[:2], someseq[2:]\n\n",
"Syntax for this is added to Python 3\n>>> # Python 3.x only\n>>> a, b, *c = range(10)\n>>> a\n0\n>>> b\n1\n>>> c\n[2, 3, 4, 5, 6, 7, 8, 9]\n\nbut no similar solution exists in Pyth... | [
35,
11
] | [] | [] | [
"python",
"variable_assignment"
] | stackoverflow_0002531776_python_variable_assignment.txt |
Q:
Convert binary information to regular data type without outside modules in python
I'm tasked with reading a poorly formatted binary file and taking in the variables. Although I need to do it in C++ (ROOT, specifically), I've decided to do it in python because python makes sense to me, but my plan is to get it work... | Convert binary information to regular data type without outside modules in python | I'm tasked with reading a poorly formatted binary file and taking in the variables. Although I need to do it in C++ (ROOT, specifically), I've decided to do it in python because python makes sense to me, but my plan is to get it working in python and then tackle re-writing in in C++, so using easy to use python modules... | [
"You're basically computing a \"number-in-base-256\", which is a polynomial, so, by Horner's method:\n>>> v = 0\n>>> for c in someval: v = v * 256 + ord(c)\n\nMore typical would be to use equivalent bit-operations rather than arithmetic -- the following's equivalent:\n>>> v = 0\n>>> for c in someval: v = v << 8 | o... | [
2,
2,
2,
1,
0
] | [] | [] | [
"binary",
"python"
] | stackoverflow_0002531439_binary_python.txt |
Q:
Key word extraction in Python
I'm building a website in django that needs to extract key words from short (twitter-like) messages.
I've looked at packages like topia.textextract and nltk - but both seem to be overkill for what I need to do. All I need to do is filter words like "and", "or", "not" while keeping nou... | Key word extraction in Python | I'm building a website in django that needs to extract key words from short (twitter-like) messages.
I've looked at packages like topia.textextract and nltk - but both seem to be overkill for what I need to do. All I need to do is filter words like "and", "or", "not" while keeping nouns and verbs that aren't conjunctiv... | [
"You can make a set sw of the \"stop words\" you want to eliminate (maybe copy it once and for all from the stop words corpus of NLTK, depending how familiar you are with the various natural languages you need to support), then apply it very simply.\nE.g., if you have a list of words sent that make up the sentence ... | [
3,
1
] | [] | [] | [
"django",
"keyword",
"python"
] | stackoverflow_0002531717_django_keyword_python.txt |
Q:
I am having issues with django test
I have this test case
def setUp(self):
self.user = User.objects.create(username="tauri", password='gaul')
def test_loginin_student_control_panel(self):
c = Client()
c.login(username="tauri", password="gaul")
response = c.get('/student/')
self.assertEqual(respons... | I am having issues with django test | I have this test case
def setUp(self):
self.user = User.objects.create(username="tauri", password='gaul')
def test_loginin_student_control_panel(self):
c = Client()
c.login(username="tauri", password="gaul")
response = c.get('/student/')
self.assertEqual(response.status_code, 200)
the view associated ... | [
"The problem is the way you create your User object.\nDjango does not store your password in plain text in the database, it stores its hash value. But in your code password is set in plain text.\nSo when you use c.login(...) internally Django will make a call to check_password method which will generate a hash valu... | [
4,
1
] | [] | [] | [
"django",
"python",
"unit_testing"
] | stackoverflow_0002531658_django_python_unit_testing.txt |
Q:
Why won't numpy matrix let me print its rows?
Okay this is probably a really dumb question, however it's really starting to hurt. I have a numpy matrix, and basically I print it out row by row. However I want to make each row be formatted and separated properly.
>>> arr = numpy.matrix([[x for x in range(5)] for ... | Why won't numpy matrix let me print its rows? | Okay this is probably a really dumb question, however it's really starting to hurt. I have a numpy matrix, and basically I print it out row by row. However I want to make each row be formatted and separated properly.
>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> arr
matrix([[0, 1, 2, 3, 4],
... | [
"arr is returned as a matrix type, which may not be an iterable object that plays nicely with join.\nYou could convert arr to a list with tolist() and then perform your join.\n>>> a = arr.tolist() # now you can manipulate the list.\n>>> for i in a:\n '|'.join(map(str,i)) \n\n'0|1|2|3|4'\n'0|1|2|3|4'\n'0|1|2|3|4'... | [
3,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002532012_numpy_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.