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:
Python threading: What am I missing? (task_done() called too many times)
My apologies for the long-ish post up front. Hopefully it'll give enough context for a solution. I've tried to create a utility function that will take any number of old classmethods and stick them into a multi-threaded queue:
class QueuedCal... | Python threading: What am I missing? (task_done() called too many times) | My apologies for the long-ish post up front. Hopefully it'll give enough context for a solution. I've tried to create a utility function that will take any number of old classmethods and stick them into a multi-threaded queue:
class QueuedCall(threading.Thread):
def __init__(self, name, queue, fn, args, cb):
... | [
"Your approach to this problem is \"unconventional\". But ignoring that for now ... the issue is simply that in the code you have given \nq.put(QueuedCall('twitter', q, Twitter.get_status, [5,], __op_complete))\n\nit is clearly possible for the following workflow to occur\n\nA thread is constructed and started by ... | [
7,
3
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0007439401_multithreading_python_queue.txt |
Q:
How do I pass multiple class attributes through django to the template?
Getting this error:
Exception Value:
Could not parse the remainder: ' + contact.last_name' from 'contact.first_name + contact.last_name'
I am having trouble displaying a list of names, with each name as a link.
My models.py code:
class Contact... | How do I pass multiple class attributes through django to the template? | Getting this error:
Exception Value:
Could not parse the remainder: ' + contact.last_name' from 'contact.first_name + contact.last_name'
I am having trouble displaying a list of names, with each name as a link.
My models.py code:
class Contact(models.Model):
first_name = models.CharField("First Name", max_length=30... | [
"You can just do:\n{{ contact.first_name }} {{ contact.last_name }}\n\nDjango doesn't know what to do with the +, and you don't need it.\n",
"for a not so long contact list , \neg:\ndef index(request):\ncontact_list = Contact.objects.all()\nfor i in contact_list:\n contactlist.append(i.first_name + i.last_n... | [
4,
0
] | [] | [] | [
"django",
"html",
"python",
"templates"
] | stackoverflow_0007440031_django_html_python_templates.txt |
Q:
How to recover text that was encoded with base64?
How can I recover a text that was corrupted by base64 encoding? E.g.
f('Dan=E7a')=Dança
I tried with python but couldn't get it right.
A:
That looks like Quoted-printable encoding, not base-64.
There's a module in the Python standard library called quopri that... | How to recover text that was encoded with base64? | How can I recover a text that was corrupted by base64 encoding? E.g.
f('Dan=E7a')=Dança
I tried with python but couldn't get it right.
| [
"That looks like Quoted-printable encoding, not base-64.\nThere's a module in the Python standard library called quopri that should be able to convert the text.\n"
] | [
2
] | [] | [] | [
"base64",
"corruption",
"python",
"restore"
] | stackoverflow_0007440092_base64_corruption_python_restore.txt |
Q:
Python: What am I doing wrong?
I want to get this function to work:
def getEvenNumbers (numbers):
bo = []
for num in numbers:
bo.append(num)
if num % 2 == 0:
return bo
getEvenNumbers([1, 4, 8, 9]) returns [4] though.
I expect more result like [4,8] but it not working, I only ... | Python: What am I doing wrong? | I want to get this function to work:
def getEvenNumbers (numbers):
bo = []
for num in numbers:
bo.append(num)
if num % 2 == 0:
return bo
getEvenNumbers([1, 4, 8, 9]) returns [4] though.
I expect more result like [4,8] but it not working, I only get [4]? what am I doing wrong?
| [
"You are returning as soon as one of the numbers is found to be even.\ndef get_even_numbers(numbers):\n bo = []\n for num in numbers:\n if num % 2 == 0:\n bo.append(num)\n return bo\n\nOr:\ndef get_even_numbers(l):\n return [n for n in l if n % 2 == 0]\n\n",
"Actually your code as gi... | [
8,
2,
1
] | [] | [] | [
"function",
"list",
"python"
] | stackoverflow_0007440144_function_list_python.txt |
Q:
I can't get the entities with my query
I was using the same procedure that I was using in my previous projects, that I learned from the tutorials provided by Google, but this time I'm getting no results..
My code is to get 3 random jokes from my datastore, which keeps only 100 jokes & to show them in a HTML table.... | I can't get the entities with my query | I was using the same procedure that I was using in my previous projects, that I learned from the tutorials provided by Google, but this time I'm getting no results..
My code is to get 3 random jokes from my datastore, which keeps only 100 jokes & to show them in a HTML table.
Here is my model:
class joke(db.Model):
jok... | [
"I've checked your example, and this code works for me:\ndef get(self):\n deck = range(1, 101)\n shuffle(deck)\n items = db.GqlQuery(\"SELECT * FROM joke WHERE jokeID IN :1\", deck[:3])\n template_values = {'items' : items}\n path = os.path.join(os.path.dirname(__file__), 'index.html')\n self.resp... | [
2
] | [
"\nMy code is to get 3 random\n\ndef get_random_joke(self, category):\n jokeinfo = JokeData.all().filter(\"category =\", category)\n return jokeinfo[random.randint(0, jokeinfo.count()-1)] \n\nI think the above code would work to get one random joke from a category in the datastore if you have categories. \n"
... | [
-1
] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007425243_google_app_engine_google_cloud_datastore_python.txt |
Q:
python smtplib using gmail: messages with a body longer than about 35 characters are never received
I have the strangest bug. I am using smtplib to send email from a gmail account. Every time that I run the script I see the message show up in the "sent" tab of the gmail account that I am using to send. However som... | python smtplib using gmail: messages with a body longer than about 35 characters are never received | I have the strangest bug. I am using smtplib to send email from a gmail account. Every time that I run the script I see the message show up in the "sent" tab of the gmail account that I am using to send. However sometimes don't get the message on the receiving end.
I have noticed a correlation between the length of th... | [
"The most likely explanation for only receiving a subset of the messages that you're sending is that the destination is discarding them (have you checked a spam folder?). FWIW, if I use your script, all 100 messages arrive.\nWhen you send the message, you might get rejected by Google, or they might accept it for d... | [
2
] | [] | [] | [
"gmail",
"python",
"smtplib"
] | stackoverflow_0007437455_gmail_python_smtplib.txt |
Q:
Filtering Django admin changelist to show specific rows based on the logged-in user
I have a django model like this:
class Tour(models.Model):
Name=models.CharField(max_length=100)
Count=models.SmallIntegerField()
PriceUnitCode=models.ForeignKey(PriceUnit)
Price=models.CharField(max_length=12)
Desc... | Filtering Django admin changelist to show specific rows based on the logged-in user | I have a django model like this:
class Tour(models.Model):
Name=models.CharField(max_length=100)
Count=models.SmallIntegerField()
PriceUnitCode=models.ForeignKey(PriceUnit)
Price=models.CharField(max_length=12)
Description=models.TextField()
ActionDate=models.CharField(max_length=16)
ActionUser=mo... | [
"Thanks buddy\nI tryed your code but it had error!!so I changed it and now it work well:\nclass TourAdmin(admin.ModelAdmin):\n def queryset(self, request):\n qs = super(TourAdmin, self).queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(ActionUserCode=reques... | [
4,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007435623_django_python.txt |
Q:
how to modularize django settings.py?
When you install a new django application, you have to add/modify your settings.py module.
For a project I'm trying to make that module a python subpackage and create a module for each application:
settings\
__init__.py
base.py
admin.py
feincms.py
...
The ... | how to modularize django settings.py? | When you install a new django application, you have to add/modify your settings.py module.
For a project I'm trying to make that module a python subpackage and create a module for each application:
settings\
__init__.py
base.py
admin.py
feincms.py
...
The problem I'm confronted with is how to merge... | [
"\"When you install a new django application, you have to add/modify your settings.py module.\"\nI think this is fine as is. \nI don't see any reason to change or modify this at all.\nWhat we do, however, is to \"subclass\" the core settings module.\nOur developer-specific and installation-specific files have names... | [
8,
7,
6,
3,
2,
1,
0
] | [
"just put\nfrom base import *\nfrom admin import *\n...\n\nin ur init.py\nthat should work\ni used it for different sites\nbase/settings.py # common settings: db, apps, ...\nbase/sites/website1/settings.py # site_id, custom middleware \nbase/sites/website2/settings.py # site_id, custom middleware\n\nthe website set... | [
-1
] | [
"django",
"python"
] | stackoverflow_0002035733_django_python.txt |
Q:
Spawning a separate thread of execution (i.e. sending log email to dev) in Flask Python?
I am running a Flask webapp running behind uwsgi (2 processes). A part of my code involves pinging a remote resource, seeing if it has been modified (If-Modified-Since), and updating a local copy of that resource on the webser... | Spawning a separate thread of execution (i.e. sending log email to dev) in Flask Python? | I am running a Flask webapp running behind uwsgi (2 processes). A part of my code involves pinging a remote resource, seeing if it has been modified (If-Modified-Since), and updating a local copy of that resource on the webserver if modified.
That update also sends myself an email of the diff. I'm concerned that this t... | [
"The best solution for this kind of tasks is using the uWSGI spooler. If you want to run the tasks at specific interval you can use the @timer decorator and let the spooler to the hard work:\nfrom uwsgidecorators import *\n\n#this will execute the_task() every 30 seconds in the spooler\n@timer(30, target='spooler')... | [
6,
2
] | [] | [] | [
"flask",
"multithreading",
"python",
"uwsgi"
] | stackoverflow_0007437899_flask_multithreading_python_uwsgi.txt |
Q:
Running Pylint on Windows -> ImportError: cannot import from builtins
Maybe someone has a clue about this one. Google, the Logilab.org archives and every other source I tried to determine a solution have turned up empty.
I was trying to get Pylint 2.4 running with PyDev in Eclipse (with Python 2.6) on Windows, but... | Running Pylint on Windows -> ImportError: cannot import from builtins | Maybe someone has a clue about this one. Google, the Logilab.org archives and every other source I tried to determine a solution have turned up empty.
I was trying to get Pylint 2.4 running with PyDev in Eclipse (with Python 2.6) on Windows, but right now I'd be happy simply running pylin at all. I used easy_install to... | [
"For me, there is a logilab.common.compat module buried inside the egg \"logilab.pylintinstaller-0.15.2-py2.6.egg\" in my site-packages folder. Having the logilab_common egg installed, removing the pylintinstaller egg got pylint working in eclipse. I found this out via IPython like so:\nIn [37]: import logilab.comm... | [
1,
0
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0007363492_pylint_python.txt |
Q:
MP3 audio file splitting with Python
I have mp3 files and i want to slice these into samples, by giving a start and end time to a library function.
Does anyone know which python library suits me to do this??
A:
Mp3splt, This works fabulously :)
Example:
import os
os.system("mp3splt inputfile.mp3")
| MP3 audio file splitting with Python | I have mp3 files and i want to slice these into samples, by giving a start and end time to a library function.
Does anyone know which python library suits me to do this??
| [
"Mp3splt, This works fabulously :)\nExample:\nimport os\nos.system(\"mp3splt inputfile.mp3\")\n\n"
] | [
8
] | [] | [] | [
"mp3",
"python",
"slice"
] | stackoverflow_0006846413_mp3_python_slice.txt |
Q:
How to establish a ssh connection through python or jython and run a script remotly?
Hi I want to know how i can establish a ssh connection through python or jython and run a script file remotly on another machine. I am not sure about the platform of the machine where i want to run the script? Please provide some ... | How to establish a ssh connection through python or jython and run a script remotly? | Hi I want to know how i can establish a ssh connection through python or jython and run a script file remotly on another machine. I am not sure about the platform of the machine where i want to run the script? Please provide some sample code as well. I wont mind going for some other scripting language as well.
| [
"The simplest/quickest way would be to use Python's os.system() to call the ssh command of the system:\nhttp://docs.python.org/library/os.html?highlight=system#os.system\nE.g. this works on Ubuntu\nimport os\nos.system('/usr/bin/ssh localhost ls -la /')\n\nruns 'ls -la /' through ssh on localhost.\nYou will need to... | [
2,
1,
1
] | [] | [] | [
"jython",
"python",
"scripting"
] | stackoverflow_0007441215_jython_python_scripting.txt |
Q:
Open and read sequential XML files with unknown files names in Python
I wish to read incoming XML files that have no specific name (e.g. date/time naming) to extract values and perform particular tasks.
I can step through the files but am having trouble opening them and reading them.
What I have that works is:-
i... | Open and read sequential XML files with unknown files names in Python | I wish to read incoming XML files that have no specific name (e.g. date/time naming) to extract values and perform particular tasks.
I can step through the files but am having trouble opening them and reading them.
What I have that works is:-
import os
path = 'directory/'
listing = os.listdir(path)
for infile in li... | [
"os.listdir provides the base names, not absolute paths. You'll need to do os.path.join(path, infile) instead of just infile (that may still be a relative path, which should be fine; if you needed an absolute path, you'd feed it through os.path.abspath).\n",
"You need to provide the path to file too:\nfile = open... | [
3,
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0007438950_python.txt |
Q:
python image to number avoiding ocr
I have the following problem. A range of images should be assigned to numbers as soon as they appear. I made several attempts to ocr the images but failed. Is there a simpler solution? If I take a certain position from the screen (coordinates are always the same) process the pix... | python image to number avoiding ocr | I have the following problem. A range of images should be assigned to numbers as soon as they appear. I made several attempts to ocr the images but failed. Is there a simpler solution? If I take a certain position from the screen (coordinates are always the same) process the pixels with some function and map a number m... | [
"Although this would be classified as OCR, there are many out of the box Python machine learning libraries that may be useful to do the ocr for you, especially if you labelled examples of the digits. Take a look at http://scikit-learn.sourceforge.net/stable/auto_examples/plot_digits_classification.html, which may b... | [
2
] | [] | [] | [
"image",
"ocr",
"preprocessor",
"python"
] | stackoverflow_0007441462_image_ocr_preprocessor_python.txt |
Q:
Execute a python script from firefox, on a very specific app, just to let firefox provide the graphical IDE
So, I've been searching the topic for quite a while, but I am unable to find out whether it is possible or not. I suspect not, but I need to be sure.
What I'm doing:
I am building a fancy web app that uses x... | Execute a python script from firefox, on a very specific app, just to let firefox provide the graphical IDE | So, I've been searching the topic for quite a while, but I am unable to find out whether it is possible or not. I suspect not, but I need to be sure.
What I'm doing:
I am building a fancy web app that uses xml, xsl and javascript. However, I need to do some transformation to a text file to convert it into a proper xml ... | [
"Yes, It is possible to execute an external python script. You can use a simpleServer (example) that receives a (Ajax) request from your page and calls a subprocess or os.startfile to launch the script. In fact, you can call the function itself from within the server and return the result (e.g. as json) to the page... | [
1,
1
] | [] | [] | [
"external_script",
"firefox",
"plugins",
"python"
] | stackoverflow_0007438295_external_script_firefox_plugins_python.txt |
Q:
Sharing method implementations in Cython without inheritance
I have a few classes in my ray tracer's Python binding that implement a .transform() method (Objects, Textures, Cameras, etc.), which takes a transformation matrix. I'd like to have all these classes also implement .scale(), .rotate(), etc., and share c... | Sharing method implementations in Cython without inheritance | I have a few classes in my ray tracer's Python binding that implement a .transform() method (Objects, Textures, Cameras, etc.), which takes a transformation matrix. I'd like to have all these classes also implement .scale(), .rotate(), etc., and share common implementations that call self.transform(...). One way to d... | [
"Your transformable is likely to become a do_everything.\nComposition is IMHO both the answer in term of cython code and architecture.\nsee : this article for a good explanation.\nIIRC, Blender use this architecture so it looks quite compatible with what you want to do.\n(BTW, could you post a bit of code so I coul... | [
0
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0007437091_cython_python.txt |
Q:
_shutdown AttributeError (ignored) when linting code that uses M2Crypto
I'm running lint as follows:
$ python -m pylint.lint m2test.py
with this code:
import M2Crypto
def f():
M2Crypto.RSA.new_pub_key("").as_pem(cipher=None).split("\n")
The lint output ends with:
Exception AttributeError: '_shutdown' in <mod... | _shutdown AttributeError (ignored) when linting code that uses M2Crypto | I'm running lint as follows:
$ python -m pylint.lint m2test.py
with this code:
import M2Crypto
def f():
M2Crypto.RSA.new_pub_key("").as_pem(cipher=None).split("\n")
The lint output ends with:
Exception AttributeError: '_shutdown' in <module 'threading' from '/usr/lib/python2.7/site-packages/M2Crypto-0.21.1-py2.7-... | [
"The exception that you are seeing is caused by a bug in the astng package (presumably “Abstract Syntax Tree, Next Generation”?) which is a toolkit on which pylint depends, written by the same people. I should note in passing that I always encourage people to use pyflakes instead of pylint when possible, because it... | [
16,
3,
1,
0
] | [] | [] | [
"m2crypto",
"pylint",
"python"
] | stackoverflow_0007302769_m2crypto_pylint_python.txt |
Q:
How can I get a list of attributes of a Python object which doen't have __dict__?
How would you do this for an instance of xml.etree.cElementTree.Element?
$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> from xml.etree.cEl... | How can I get a list of attributes of a Python object which doen't have __dict__? | How would you do this for an instance of xml.etree.cElementTree.Element?
$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> from xml.etree.cElementTree import Element
>>> obj = Element('aaa')
>>> obj
<Element 'aaa' at 0x101bde27... | [
"If attributes are returned via custom __getattr__ or __getattribute__, you cannot know whether an attribute will be returned without trying and you cannot get a full list without trying all possible names. You can get the list of static attributes via dir().\n",
"The xml.etree.ElementTree.Element object does hav... | [
3,
1
] | [] | [] | [
"attributes",
"inspect",
"python"
] | stackoverflow_0007427801_attributes_inspect_python.txt |
Q:
How can I configure Pylint to check all things PEP8 checks?
Searching for an answer on Pylint's mailing list brings no interesting results.
Pylint is known to be very customizable, so I guess this should be possible...
The reason I would like Pylint to check compliance with PEP8 is because
PyDev has much better s... | How can I configure Pylint to check all things PEP8 checks? | Searching for an answer on Pylint's mailing list brings no interesting results.
Pylint is known to be very customizable, so I guess this should be possible...
The reason I would like Pylint to check compliance with PEP8 is because
PyDev has much better support for Pylint than it has for PEP8.
It's easier to have one t... | [
"\nE203 is not yet supported in Pylint AFAIK\nE225 is C0322 / C0323\nE251 should be C0322/C0323, but I'm not sure that Pylint does not special case parameters and allows lack of space there\nE301, E303 are not supported AFAIK\nE501 is C0301 and you can configure the length in your pylintrc\nW291, W292 and W203 are ... | [
12
] | [] | [] | [
"coding_style",
"lint",
"pep8",
"pylint",
"python"
] | stackoverflow_0006879640_coding_style_lint_pep8_pylint_python.txt |
Q:
What is the best way to break up this string in Python?
I am parsing a text file that looks something like this:
a1 a2 a3 b1 b2 b3
a1 b1 b2
a1 a2 b1
Basically what I want to end up with is each column in its own string. I'm pretty sure there is an obvious answer ... | What is the best way to break up this string in Python? | I am parsing a text file that looks something like this:
a1 a2 a3 b1 b2 b3
a1 b1 b2
a1 a2 b1
Basically what I want to end up with is each column in its own string. I'm pretty sure there is an obvious answer to this but I think I've been staring at the screen too long.... | [
"You could read each line and split on more then one space or a tab, wichever is between column 1 and 2\n",
"This is the second time this has happened to me in the last couple of days. I've managed to solve my own problem...\nThe text layout is effectively fixed - the \"second half\" of the line always starts at ... | [
1,
0
] | [] | [] | [
"python",
"regex",
"split",
"string"
] | stackoverflow_0007441850_python_regex_split_string.txt |
Q:
try this in python shell: list.extend/append
This is what I just did in python shell:
>>>[1, 2]
...[1, 2]
>>>[1, 2].extend([2,3]) #when I pressed Enter
>>>
#nothing came out
then I tried something else:
>>>l = [1, 2]
>>>l
...[1, 2]
>>>m = [1, 2].extend([2, 3])
>>>m #pressed... | try this in python shell: list.extend/append | This is what I just did in python shell:
>>>[1, 2]
...[1, 2]
>>>[1, 2].extend([2,3]) #when I pressed Enter
>>>
#nothing came out
then I tried something else:
>>>l = [1, 2]
>>>l
...[1, 2]
>>>m = [1, 2].extend([2, 3])
>>>m #pressed Enter, nothing came out
>>>m is None
...True
why... | [
"No you can't, extend (as append, pop...) modify the object inplace without returning anything.\nThe list objects are mutable objects, they can be modified without need to recreate one.\nIn your case, you have to do \n>>>l = [1,2]\n>>>l.extend([2,3])\n>>>l\n[1,2,2,3]\n\nIf you change the type of l, assume this is a... | [
5,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007442124_list_python.txt |
Q:
how do you statically find dynamically loaded modules
How does one get (finds the location of) the dynamically imported modules from a python script ?
so, python from my understanding can dynamically (at run time) load modules.
Be it using _import_(module_name), or using the exec "from x import y", either using im... | how do you statically find dynamically loaded modules | How does one get (finds the location of) the dynamically imported modules from a python script ?
so, python from my understanding can dynamically (at run time) load modules.
Be it using _import_(module_name), or using the exec "from x import y", either using imp.find_module("module_name") and then imp.load_module(param... | [
"You can't; the very nature of programming (in any language) means that you cannot predict what code will be executed without actually executing it. So you have no way of telling which modules could be included.\nThis is further confused by user-input, consider: __import__(sys.argv[1]).\nThere's a lot of theoretica... | [
3,
2,
1,
1,
0
] | [] | [] | [
"loadmodule",
"module",
"python"
] | stackoverflow_0007441726_loadmodule_module_python.txt |
Q:
importing app engine app parent directory for unittest
I am sure this is simple to solve, but I have been staring at it for so long that I am staring straight past the solution. Any tips/hints/suggestions/solutions appreciated!
I am trying to add some unittests to my app engine app. I am using the testrunner.py ex... | importing app engine app parent directory for unittest | I am sure this is simple to solve, but I have been staring at it for so long that I am staring straight past the solution. Any tips/hints/suggestions/solutions appreciated!
I am trying to add some unittests to my app engine app. I am using the testrunner.py example from http://code.google.com/appengine/docs/python/tool... | [
"Have you tried to use an absolute path?\nsys.path.append(os.path.abspath(os.path.dirname(test_path)))\n\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"unit_testing"
] | stackoverflow_0007441814_google_app_engine_python_unit_testing.txt |
Q:
Fasta file description parsing using biopython
I have a fasta file (first sequence is mentioned below) with long description. I need to pick specific description fields. when i used following code; whole description get into string.
from Bio import SeqIO
for record in SeqIO.parse("geneTemp.fasta", "fasta") :
... | Fasta file description parsing using biopython | I have a fasta file (first sequence is mentioned below) with long description. I need to pick specific description fields. when i used following code; whole description get into string.
from Bio import SeqIO
for record in SeqIO.parse("geneTemp.fasta", "fasta") :
id=record.id
desc=record.description
print desc... | [
"The description part of FASTA is not standard. You can use regex to parse it.\n>>> import re\n>>> desc = 'FBgn0207418 type=gene; loc=scaffold_12875:complement(14361770..14363857); ...'\n>>> fields = dict(re.findall(r'(\\w+)=(.*?);', desc))\n>>> fields['type']\n'gene'\n>>> fields['length']\n'2088'\n\n"
] | [
5
] | [] | [] | [
"biopython",
"fasta",
"parsing",
"python"
] | stackoverflow_0007441376_biopython_fasta_parsing_python.txt |
Q:
Buildbot properties from changes to all build
I am using buildbot (system for CI) and have one problem. How can I send parameters of Change to all builders? I want to use the properties comments and who of Changes object.
Thx
A:
I'm find answer: inheritance from BuildStep and use
self.build.allChanges() and for... | Buildbot properties from changes to all build | I am using buildbot (system for CI) and have one problem. How can I send parameters of Change to all builders? I want to use the properties comments and who of Changes object.
Thx
| [
"I'm find answer: inheritance from BuildStep and use \nself.build.allChanges() and for set property: self.setProperty()\n"
] | [
0
] | [] | [] | [
"buildbot",
"continuous_integration",
"python"
] | stackoverflow_0007417518_buildbot_continuous_integration_python.txt |
Q:
Python post build to change an msi name wiht Branding and Version?
Hi I run a Build system for the company i work for...
Currently I am using a dictionary function to take the name of the msi that is produced by the builds and renaming to the naming convention decided up for that release.
def Rename_MSI(dict):
... | Python post build to change an msi name wiht Branding and Version? | Hi I run a Build system for the company i work for...
Currently I am using a dictionary function to take the name of the msi that is produced by the builds and renaming to the naming convention decided up for that release.
def Rename_MSI(dict):
global Src_Dir
for msi in dict.keys():
if os.path.exists(Sr... | [
"import os\n\nmsi = \"ProductSolution_x64.msi\"\n\nname,arch = os.path.splitext(msi)[0].split('_') \n\nnewname = \"%s_%s_%s_%s.msi\" %(brand, name, version, arch)\n\nShould work...\n"
] | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007436396_python_string.txt |
Q:
Space padded binary string in Python
I need to convert this PHP function into Python but I don't even know, what is space padded binary string.
pack('A*', $string);
Python has struct.pack what should be probably used but I end here. Can somebody help and explain me the behaviour?
Thanks!
UPDATE:
This is the whol... | Space padded binary string in Python | I need to convert this PHP function into Python but I don't even know, what is space padded binary string.
pack('A*', $string);
Python has struct.pack what should be probably used but I end here. Can somebody help and explain me the behaviour?
Thanks!
UPDATE:
This is the whole code I need to implement in Python. Unti... | [
"I think that is a noop.\n$string = 'asdf';\nprint pack('A10', $string) . \"|<-\\n\";\n\nwould give you\nasdf |<-\n\nSince the * means \"take as many as possible,\" there is never any reason to pad.\nIMHO you can just throw away the whole line.\n\nRe. your Update:\nThe pack function still serves no purpose, ex... | [
1
] | [] | [] | [
"php",
"python",
"string"
] | stackoverflow_0007442390_php_python_string.txt |
Q:
Trick code completion with PyDev like with PDT?
Is there a way to help PyDev code completion by telling it the type of a variable?
With PDT, you can use PHPDoc-like syntax for such purpose:
/* @var $my_var MyClass */
$my_var = myFunction();
// PDT is able to figure out that $my_var is a MyClass object.
But till n... | Trick code completion with PyDev like with PDT? | Is there a way to help PyDev code completion by telling it the type of a variable?
With PDT, you can use PHPDoc-like syntax for such purpose:
/* @var $my_var MyClass */
$my_var = myFunction();
// PDT is able to figure out that $my_var is a MyClass object.
But till now, I cannot figure out how to do the same in python.... | [
"Actually, you can if you do an assert isinstance()\nE.g.:\na = function()\nassert isinstance(a, MyClass)\na. <- would get the proper completions\n\nNote that Pydev does analyze the return of the functions, so, it's possible that it knows that on a number of cases.\nAlso, that shouldn't have runtime penalties if yo... | [
3,
3,
1
] | [] | [] | [
"code_completion",
"pydev",
"python"
] | stackoverflow_0002016269_code_completion_pydev_python.txt |
Q:
Auto-populating created_by and actionDate field with Django admin site
I have a model like this:
class Tour(models.Model):
Name=models.CharField(max_length=100)
Count=models.SmallIntegerField()
ActionDate=models.DateTimeField(editable=False)
ActionUser=models.ForeignKey(User,editable=False)
StatusT... | Auto-populating created_by and actionDate field with Django admin site | I have a model like this:
class Tour(models.Model):
Name=models.CharField(max_length=100)
Count=models.SmallIntegerField()
ActionDate=models.DateTimeField(editable=False)
ActionUser=models.ForeignKey(User,editable=False)
StatusType=models.ForeignKey(StatusType)
now I wanna auto populate current user in... | [
"Why don't you use auto_now in the field definition?\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007442510_django_python.txt |
Q:
List of products of values for all keys that match in two dictionaries
I have two hash tables in the form of dictionaries. The keys map features to a list of occurrences of said features.
a_dict = {'a': [1,2], 'b': [2,], 'c': [1,3]}
b_dict = {'a': [6], 'c': [4]}
What I need is list or ideally a numpy array that c... | List of products of values for all keys that match in two dictionaries | I have two hash tables in the form of dictionaries. The keys map features to a list of occurrences of said features.
a_dict = {'a': [1,2], 'b': [2,], 'c': [1,3]}
b_dict = {'a': [6], 'c': [4]}
What I need is list or ideally a numpy array that contains all combinations of occurrences for two matching features. So in thi... | [
"import numpy as np\nimport itertools\n\na_dict = {'a': [1,2], 'b': [2,], 'c': [1,3]}\nb_dict = {'a': [6], 'c': [4]}\n\nprint(list(itertools.chain.from_iterable(\n itertools.product(value, b_dict[key]) for key,value in a_dict.iteritems()\n if key in b_dict)))\n# [(1, 6), (2, 6), (1, 4), (3, 4)]\n\n"
] | [
3
] | [] | [] | [
"cython",
"dictionary",
"list",
"python"
] | stackoverflow_0007442902_cython_dictionary_list_python.txt |
Q:
Threading on Python
I am working on a program which logs memory usage on a server. The server has multiple instances running, and the program is logging all.
I am trying to figure out what would be more optimal.
Options:
(Assuming two instances)
1. Single Thread Program, which handles each instance, one by one. T... | Threading on Python | I am working on a program which logs memory usage on a server. The server has multiple instances running, and the program is logging all.
I am trying to figure out what would be more optimal.
Options:
(Assuming two instances)
1. Single Thread Program, which handles each instance, one by one. Time delay 0.5 seconds.
2.... | [
"Both options are perfectly fine. Note that writing a single-threaded program is way easier, so unless you have tight performance requirements or timing constraints, you should forgo threads in favor of faster development and less bugs.\n"
] | [
2
] | [] | [] | [
"logging",
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0007442956_logging_multithreading_python_python_multithreading.txt |
Q:
Python3 parallelize jobs with multiprocessing
I have a script that parses a file containing directories to other file, that have to be opened and read searching for a keyword.
Since the number of file is growing I'd like to enable multiprocessing to reduce the amount of time requested to complete the job.
I was th... | Python3 parallelize jobs with multiprocessing | I have a script that parses a file containing directories to other file, that have to be opened and read searching for a keyword.
Since the number of file is growing I'd like to enable multiprocessing to reduce the amount of time requested to complete the job.
I was thinking to leave the parent process parsing the file... | [
"\nI was thinking to leave the parent process parsing the file containing directories and use child processes to fetch the other files. \n\nA directory is a name. The parent parses a list and provides the directory name to each child. Right? The child then reads the files inside the directory.\n\nSince the paren... | [
3
] | [] | [] | [
"multiprocessing",
"python",
"python_3.x"
] | stackoverflow_0007442826_multiprocessing_python_python_3.x.txt |
Q:
Django shell encoding error (Debian only, Ubuntu fine)
Good day
Can somebody explain what is going on behind the Django manage.py shell console?
The problem is following. I'm developing a Django app, which is using an urllib to parse some html pages to get some info from them. And that info is in russian language,... | Django shell encoding error (Debian only, Ubuntu fine) | Good day
Can somebody explain what is going on behind the Django manage.py shell console?
The problem is following. I'm developing a Django app, which is using an urllib to parse some html pages to get some info from them. And that info is in russian language, so it should be unicode (this is address string in this cas... | [
"If you run the following python script, you'll see what's happening:\n# -*- coding: utf-8 -*-\na = r\"Челябинск\"\nprint \"Encode from UTF-8 to UTF-8:\",unicode(a,'utf-8').encode('utf-8')\nprint \"Encode from ISO8859-1 to UTF-8:\",unicode(a,'iso8859-1').encode('utf-8')\n\nThe output is:\n\nEncode from ISO8859-1 to... | [
3
] | [] | [] | [
"python",
"terminal",
"unicode"
] | stackoverflow_0007432533_python_terminal_unicode.txt |
Q:
How can I format the items of file to comply with the items in another file in python?
I have two files containing records of this form 'Date',"points','Name', but there are differences between the two files regarding the name,for example Bob in one file and Bobb in another.I am trying to have Bob in all the files... | How can I format the items of file to comply with the items in another file in python? | I have two files containing records of this form 'Date',"points','Name', but there are differences between the two files regarding the name,for example Bob in one file and Bobb in another.I am trying to have Bob in all the files.Any tips ?Thanks.
| [
"You could read in each file using the \"csv\" module, then write a conversion dictionary {'Bobb':'Bob',...} and run through the rows checking to see if the name is in the dict.\n"
] | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007443286_list_python.txt |
Q:
How do I first login then continue to check gmail via imaplib and python
I have been working on a small Arduino project to activate a servo with a flag on it every time I get a new e-mail in GMail. I would like to log into Gmail, check to see if I have any new e-mail and then check again every x seconds.
What I ... | How do I first login then continue to check gmail via imaplib and python | I have been working on a small Arduino project to activate a servo with a flag on it every time I get a new e-mail in GMail. I would like to log into Gmail, check to see if I have any new e-mail and then check again every x seconds.
What I have discovered is that the first connection goes fine, but after that, I get ... | [
"You need to take the \"conn.login(user,pwd)\" line out of the while loop. Putting it as the line before the while loop should work fine.\n"
] | [
0
] | [] | [] | [
"gmail",
"imaplib",
"python"
] | stackoverflow_0007426649_gmail_imaplib_python.txt |
Q:
Writing to a remote MySql DB with Python
I'm new to coding so I do apologise for any blatant faux pas I may made in my design concept.
I am looking to design a very basic app using Python which will scan for Access Points and log their details in a remote MySql database. My code works fine at present and writes th... | Writing to a remote MySql DB with Python | I'm new to coding so I do apologise for any blatant faux pas I may made in my design concept.
I am looking to design a very basic app using Python which will scan for Access Points and log their details in a remote MySql database. My code works fine at present and writes the information to a locally held database no pr... | [
"You could launch a separate thread (using the threading module) to handle writes to the database. Then just pass the information to be written to that thread (using the Queue module, perhaps) and carry on.\nThe database thread can try the remote write and if it fails then write the data to a temporary file on the ... | [
0
] | [] | [] | [
"3g_network",
"mysql",
"python"
] | stackoverflow_0007425299_3g_network_mysql_python.txt |
Q:
How to apply a scrollbar to a frame in a canvas
I'm having a really hard time trying to achieve a decdent GUI layout in tkinter. I'm aiming for the layout on the left, but didn't get any further than the layout on the right:
I feel completely lost in all that different layout managers. This is my code so far:
fro... | How to apply a scrollbar to a frame in a canvas | I'm having a really hard time trying to achieve a decdent GUI layout in tkinter. I'm aiming for the layout on the left, but didn't get any further than the layout on the right:
I feel completely lost in all that different layout managers. This is my code so far:
from Tkinter import *
class ScrolledCanvas:
def __... | [
"You cannot pack (or grid, or place) widgets into the canvas and expect them to scroll. Instead, you must use the create_window method. \n"
] | [
4
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0007441544_python_tkinter_user_interface.txt |
Q:
Python Twitter streaming API - followed users only
I'm attempting to get the statuses of followed users only using the Python Twitter library. It works fine for the 'everyone' stream:
from twitter.stream import TwitterStream
from twitter.oauth import OAuth
from twitter.util import printNicely
stream = TwitterS... | Python Twitter streaming API - followed users only | I'm attempting to get the statuses of followed users only using the Python Twitter library. It works fine for the 'everyone' stream:
from twitter.stream import TwitterStream
from twitter.oauth import OAuth
from twitter.util import printNicely
stream = TwitterStream(
auth=OAuth(
acc_key, acc_secr... | [
"I recommend twython for a Python Twitter library. It is regularly maintained, a useful property considering how often Twitter changes its API.\nEDIT: See tweetstream for a simple streaming API implementation which as filtering capabilities.\n",
"Actually, twython doesn't support support the userstream live strea... | [
0,
0
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0007404461_python_twitter.txt |
Q:
passing a single character/multiple character user input from a python function to a C++ function
I have a C++ .dll function that I am accessing through python 3.2 with the syntax:
int Create(char argID)
and I am trying to access this function using python. I can access it, but I am confused on why it is telling ... | passing a single character/multiple character user input from a python function to a C++ function | I have a C++ .dll function that I am accessing through python 3.2 with the syntax:
int Create(char argID)
and I am trying to access this function using python. I can access it, but I am confused on why it is telling for 'wrong type' whenever I try to pass the function an argument.
Python Script:
Create.argtypes = [c_c... | [
"A c_char is a one-byte value, not a Unicode string. Set ID = bytes(ID, 'utf8')[0] (or use a different 8-bit character mapping than 'utf8', such as 'latin-1'). Then you can call Create(ID). \nBy the way, assigning ID to c_char only gives you another reference to c_char, and then you immediately reassign ID to the r... | [
2,
0
] | [] | [] | [
"dll",
"function",
"input",
"python"
] | stackoverflow_0007442116_dll_function_input_python.txt |
Q:
Python themed tkinter: Entry variable will not set
The following Python 3 code has a label and an Entry field that are correctly initialized with a string ("junk" in the example). But when the second "import" line is uncommented to replace the old Entry widget with the new themed widget, the label and Entry field... | Python themed tkinter: Entry variable will not set | The following Python 3 code has a label and an Entry field that are correctly initialized with a string ("junk" in the example). But when the second "import" line is uncommented to replace the old Entry widget with the new themed widget, the label and Entry fields are not initialized.
Any clue why the themed widget in... | [
"The problem is that v is a local variable. When it goes out of scope (ie: when __init__ finishes executing), v is getting garbage-collected. Change v to self.v and the problem goes away. \nWhy you see the problem with the ttk Entry widget and not the standard one, I don't know. I guess one is just more sensitive t... | [
5
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007439432_python_tkinter.txt |
Q:
Can't catch exception!
I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!
The class PyMonitor.cc describes the swig interface... | Can't catch exception! | I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!
The class PyMonitor.cc describes the swig interface to the desired class, Monit... | [
"You have to forward the exceptions to Python if you want to parse them there.\nSee the SWIG Documentation.\nIn order to forward exceptions, you only have to add some code in the SWIG interface (.i) file. Basically, this can be anywhere in the .i file.\nAll types of exceptions should be specified here, and SWIG onl... | [
4,
1,
1
] | [] | [] | [
"c++",
"exception",
"python",
"swig"
] | stackoverflow_0000913396_c++_exception_python_swig.txt |
Q:
PyQT - How to get coordinates of an image selection
I have to get the coordinates of a section of an image in PyQT.
At first I need a widget that can show an image (png or jpeg) but I don't know which can do this. And then I must select a portion of this image with a rectangle and get the top-left and bottom-right... | PyQT - How to get coordinates of an image selection | I have to get the coordinates of a section of an image in PyQT.
At first I need a widget that can show an image (png or jpeg) but I don't know which can do this. And then I must select a portion of this image with a rectangle and get the top-left and bottom-right coordinates of the rectangle.
Thank you
| [
"You can display images:\n\nwith a QLabel and its method QLabel.setPixmap, OR\nwith a QGraphicsScene/QGraphicsView, OR\nin a QWidget by redefining the paintEvent method and using e.g. QPainter.drawPixmap.\n\nOnce the image is displayed you can use a QRubberBand (example) to allow and display the selection. \n"
] | [
2
] | [] | [] | [
"coordinates",
"image",
"pyqt",
"python",
"selection"
] | stackoverflow_0007443055_coordinates_image_pyqt_python_selection.txt |
Q:
how to specify the name of my daemon process using pydaemon
I'm using pydaemon ( http://www.python.org/dev/peps/pep-3143/ ) to make a friendly daemon. How do I give it a name? by default it's called 'python' but I want something more meaningful.
A:
Changing the process name cannot be done from plain Python, and ... | how to specify the name of my daemon process using pydaemon | I'm using pydaemon ( http://www.python.org/dev/peps/pep-3143/ ) to make a friendly daemon. How do I give it a name? by default it's called 'python' but I want something more meaningful.
| [
"Changing the process name cannot be done from plain Python, and pydaemon is 100% Python. You need a C-level library like py-setproctitle to do that. Then, simply add the following to your main method:\ntry:\n import setproctitle\n setproctitle.setproctitle('my-awesome-program')\nexcept:\n pass # Ignore errors, ... | [
3
] | [] | [] | [
"daemon",
"python"
] | stackoverflow_0007443872_daemon_python.txt |
Q:
having trouble with redirects
I'm using Django nonrel with App Engine and having an issue with redirects.
Very simple redirects in my view handlers:
@login_required
def dashboard(request):
if check_if_user_needs_to_import(request.user):
return redirect("user_welcome")
Are not redirecting properly in... | having trouble with redirects | I'm using Django nonrel with App Engine and having an issue with redirects.
Very simple redirects in my view handlers:
@login_required
def dashboard(request):
if check_if_user_needs_to_import(request.user):
return redirect("user_welcome")
Are not redirecting properly in App Engine but rather returning th... | [
"It looks like you're outputting text to the response before Django sends its own response. Check your code for print statements - more likely than not you're calling print, which you should never do in a WSGI app. The output from print gets sent before any output from your Django app, and thus gets treated as the ... | [
3,
0,
0
] | [] | [] | [
"django",
"django_nonrel",
"djangoappengine",
"google_app_engine",
"python"
] | stackoverflow_0006889642_django_django_nonrel_djangoappengine_google_app_engine_python.txt |
Q:
Why does my Swing window keep closing itself after a few seconds?
Edit: In case the multiple tags are confusing, I'm working in Jython.
Here's my SSCCE:
from javax.swing import JFrame
window = JFrame('Test',
defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
size = (800, 600))
window.v... | Why does my Swing window keep closing itself after a few seconds? | Edit: In case the multiple tags are confusing, I'm working in Jython.
Here's my SSCCE:
from javax.swing import JFrame
window = JFrame('Test',
defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
size = (800, 600))
window.visible = True
The window opens, sits there for a few seconds, and then... | [
"I suggest the following strategy to learn more about the problem:\nsun.awt.AWTAutoShutdown is the class that prevents shutdown of the JVM if a native window peer is registered with the toolkit. Any component is registered when addNotify() is called on it. For a frame, this is done when you call setVisible(true).\n... | [
0
] | [] | [] | [
"java",
"jython",
"python",
"swing",
"user_interface"
] | stackoverflow_0007438848_java_jython_python_swing_user_interface.txt |
Q:
Django localization: my django.po file became empty after compiling
After doing:
django-admin.py compilemessages
My django.po file became empty. All my translations are gone.
The compiled django.mo file is still there. I have a copy of my django.po on github but it's 1 day old.
Is there any way to decompile the dj... | Django localization: my django.po file became empty after compiling | After doing:
django-admin.py compilemessages
My django.po file became empty. All my translations are gone.
The compiled django.mo file is still there. I have a copy of my django.po on github but it's 1 day old.
Is there any way to decompile the django.mo to get the last added translations?
| [
"The binary *.mo files from gettext could be \"decompiled\" by using msgunfmt: http://www.gnu.org/software/gettext/manual/gettext.html#msgunfmt-Invocation\n"
] | [
1
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0007444493_django_internationalization_python.txt |
Q:
bad interpreter error while executing cron job using cpanel
the cpanel was using 2.3 python verion, but my script need the 2.6 at least so i installed python 2.6.2 and added this #!/usr/bin/python.2.6.2 line at top of my script to point to newly installed python. but i am getting following error when cron job runs... | bad interpreter error while executing cron job using cpanel | the cpanel was using 2.3 python verion, but my script need the 2.6 at least so i installed python 2.6.2 and added this #!/usr/bin/python.2.6.2 line at top of my script to point to newly installed python. but i am getting following error when cron job runs.
/bin/sh: /home/somme_user/public_html/xml_feed/cron_job_wod.py:... | [
"Your installed python (not the .py file) is not marked executable.\nsudo chmod a+x /usr/bin/python.2.6.2\n\nshould fix that.\n"
] | [
2
] | [] | [] | [
"cpanel",
"python"
] | stackoverflow_0007443118_cpanel_python.txt |
Q:
Calling External Command On Python Without Quotes
Following the advice given in;
Calling an external command in Python
I have been experimenting using the call() function to call an external command, however the command I need to call is being called correctly but it does not like the parameters being passed to it... | Calling External Command On Python Without Quotes | Following the advice given in;
Calling an external command in Python
I have been experimenting using the call() function to call an external command, however the command I need to call is being called correctly but it does not like the parameters being passed to it.
This is because the Call function is passing the para... | [
"This should work - if not then please update the question with specific error text:\ntest = call(['/opt/program/something/lookup', 'search', '\"bob\"'])\n\n"
] | [
6
] | [] | [] | [
"call",
"linux",
"python",
"shell",
"subprocess"
] | stackoverflow_0007444783_call_linux_python_shell_subprocess.txt |
Q:
Calculating cumulative returns in Numpy, problem with array indices
I am new to using the numpy class and I am having problems with manipulating the contents of the array. Here is the code:
# finance equation to apply to each element of array
for row in cum_ret:
for col in row:
if sum(row)!=0:
... | Calculating cumulative returns in Numpy, problem with array indices | I am new to using the numpy class and I am having problems with manipulating the contents of the array. Here is the code:
# finance equation to apply to each element of array
for row in cum_ret:
for col in row:
if sum(row)!=0:
row[col] = prev_row[col]*(1+row[col])
else:
row[col] =... | [
"If cum_ret is the array, you can use numpy.sum(cum_ret, axis=1) to get the row-sum and numpy.sum(cum_ret, axis=1) != 0 to generate your test on the whole array at once. Then you can use numpy.select() to apply your conditions.\nIf you put a print row statement at the beginning of your loop you will notice that it ... | [
6
] | [] | [] | [
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0007445157_multidimensional_array_numpy_python.txt |
Q:
Geodjango with Mysql coordinates/polygons precision
I've created a geodjango database working with MySQL.
My problem is that when I add a new record with a PolygonField and then check
for a point if it is inside this polygon I get a wrong results (more points then I should have). I use [Location.objects.filter(sh... | Geodjango with Mysql coordinates/polygons precision | I've created a geodjango database working with MySQL.
My problem is that when I add a new record with a PolygonField and then check
for a point if it is inside this polygon I get a wrong results (more points then I should have). I use [Location.objects.filter(shape__contains='POINT(-0.058188 51.504289)')] to check fo... | [
"Quote Justin Bronn: \n\n\"MySQL is a crippled spatial database...\"\n\nInstead of contains it actually executes bbcontains, and is well known for unreliable results. https://code.djangoproject.com/ticket/13430\nI'd suggest moving to PostgreSQL.\nI don't have answer if it's not an option.\n",
"Thank you for your ... | [
2,
0
] | [] | [] | [
"django",
"geodjango",
"mysql",
"polygon",
"python"
] | stackoverflow_0006871457_django_geodjango_mysql_polygon_python.txt |
Q:
numpy histogram with 3x3D arrays as indices
I've got 3x3D arrays which are the red, green and blue channels of a 3D rgb image. What is an elegant way in numpy to to create a histogram volume of the input channels?
The operation would be equivalent to
""" assume R, G and B are 3D arrays and output is a 3D array fil... | numpy histogram with 3x3D arrays as indices | I've got 3x3D arrays which are the red, green and blue channels of a 3D rgb image. What is an elegant way in numpy to to create a histogram volume of the input channels?
The operation would be equivalent to
""" assume R, G and B are 3D arrays and output is a 3D array filled with zeros """
for x in x_dim:
for y in ... | [
"You can do it using numpy.histogramdd but, as you say, the method proposed by @jozzas won't work. What you have to do is flatten each of your three 3D arrays and then combine them into a 2-d array of dimensions (x_dim*y_dim*z_dim, 3), which you pass to histogramdd. The fact that your original data are 3D is a red ... | [
7,
3,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007422713_numpy_python.txt |
Q:
Python splitext
In python, why is os.path.splitext using '.' as extension separator instead of os.extsep?
A:
os.extsep is defined by importing os.path.extsep. But you're right, os.path.splitext() always uses ., regardless of os.path.extsep:
From os.py (3.2.2):
from os.path import (curdir, pardir, sep, pathsep, d... | Python splitext | In python, why is os.path.splitext using '.' as extension separator instead of os.extsep?
| [
"os.extsep is defined by importing os.path.extsep. But you're right, os.path.splitext() always uses ., regardless of os.path.extsep:\nFrom os.py (3.2.2):\nfrom os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,\n devnull)\n\nFrom ntpath.py (which becomes os.path)\nextsep = '.'\n[...]\ndef _ge... | [
5
] | [] | [] | [
"operating_system",
"path",
"python",
"separator"
] | stackoverflow_0007445804_operating_system_path_python_separator.txt |
Q:
Can I change windowFlags outside of widget constructor?
I am attempting to add a "Full Screen" option to my Qt (using PyQt) application. If the user hits F11, the goal is to maximize the window.
I am having problems removing the window title bar though. Normally, I'd do something like self.setWindowFlags(QtCore.Qt... | Can I change windowFlags outside of widget constructor? | I am attempting to add a "Full Screen" option to my Qt (using PyQt) application. If the user hits F11, the goal is to maximize the window.
I am having problems removing the window title bar though. Normally, I'd do something like self.setWindowFlags(QtCore.Qt.CustomizeWindowHint) in __init__ and the title bar would not... | [
"From the Qt documentation on QWidget::windowFlags:\n\nNote: This function calls setParent() when changing the flags for a window, causing the widget to be hidden. You must call show() to make the widget visible again.\n\nSo just add self.show() after self.setWindowFlags(...) and you'll be fine.\n"
] | [
2
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0007445821_pyqt_python_qt.txt |
Q:
Going crazy with python set
Please take a look at the following snippet from ipython:
In [122]: len(netean)
Out[122]: 150
In [123]: len(nwrongpea)
Out[123]: 100
In [124]: len(set.intersection(set(nwrongpea), set(netean)))
Out[124]: 8
In [125]: len(set(nwrongpea) - set(netean))
Out[125]: 90
In [126]: len(set(ne... | Going crazy with python set | Please take a look at the following snippet from ipython:
In [122]: len(netean)
Out[122]: 150
In [123]: len(nwrongpea)
Out[123]: 100
In [124]: len(set.intersection(set(nwrongpea), set(netean)))
Out[124]: 8
In [125]: len(set(nwrongpea) - set(netean))
Out[125]: 90
In [126]: len(set(netean) - set(nwrongpea))
Out[126]:... | [
"It looks like one(or two) of this collections have some duplicate elements. So creating sets from them gives you sets with less number of elements..\nTry len(set(natean)) + len(set(nwrongpea)) and you'll see.\n"
] | [
10
] | [] | [] | [
"python",
"set"
] | stackoverflow_0007446198_python_set.txt |
Q:
Django question on forms
Hello I have a django app that has a form that you can add sales and purchase. There is a change I want to make with it. If a user chooses a purchase instead of a sale, I do not want them to have a country type (location). In fact I do not want them to have any value for a purchase.
So to ... | Django question on forms | Hello I have a django app that has a form that you can add sales and purchase. There is a change I want to make with it. If a user chooses a purchase instead of a sale, I do not want them to have a country type (location). In fact I do not want them to have any value for a purchase.
So to summerise, All sales should ha... | [
"This question is not really django related. You should do that via javascript: hide or show some field base on <select> value.\nThe only thing is form validation. You should perform it like that in your case:\n from django.core.exceptions import ValidationError\n\n class Transaction(models.Model):\n # yo... | [
0,
0
] | [] | [] | [
"django",
"forms",
"models",
"python"
] | stackoverflow_0007445125_django_forms_models_python.txt |
Q:
Read MIME Message stored in text file with Python
I have a MIME Message stored in a 'text/plain' file that looks like this:
http://pastebin.com/sPWWC9LL
The MIME Message is supposed to be a multipart message.
How do I parse this in Python? I have tried email.message_from_string(), but it's still encoded as 'text/p... | Read MIME Message stored in text file with Python | I have a MIME Message stored in a 'text/plain' file that looks like this:
http://pastebin.com/sPWWC9LL
The MIME Message is supposed to be a multipart message.
How do I parse this in Python? I have tried email.message_from_string(), but it's still encoded as 'text/plain', and thus I can't use the email library to parse ... | [
"You should be able to parse the message and walk through the parts using code from this SO answer, however, first you'll need to add\nContent-type: multipart/alternative; \n boundary=\"cbsms-main-boundary\"\n\nto the beginning of the message, or preserve the full original message.\n\nI believe your code works.... | [
5
] | [] | [] | [
"mime",
"python"
] | stackoverflow_0007446284_mime_python.txt |
Q:
Unique Value validation using djangoforms on App Engine
I am trying to validate the uniqueness of an email address in datastore. The problem is that this does not allow me to edit/update the entry (e.g. if I only want to change the display_name - see models.py below).
I am submitting a form build using djangoforms... | Unique Value validation using djangoforms on App Engine | I am trying to validate the uniqueness of an email address in datastore. The problem is that this does not allow me to edit/update the entry (e.g. if I only want to change the display_name - see models.py below).
I am submitting a form build using djangoforms (with an datastore entry prefilled as I already know the key... | [
"You can check to see if your email field has changed before checking whether or not to validate it against all previous email addresses. Your clean method would be changed to:\ndef clean_email(self):\n \"\"\"Prevent duplicate email addresses.\"\"\"\n if 'email' in self.changed_data:\n if self.Meta.model.all... | [
1
] | [] | [] | [
"django",
"django_forms",
"google_app_engine",
"python",
"validation"
] | stackoverflow_0007446684_django_django_forms_google_app_engine_python_validation.txt |
Q:
Cython numpy array indexing
I am trying to speed up some python code with cython, and I'm making use of cython's -a option to see where I can improve things. My understanding is that in the generated html file, the highlighted lines are ones where python functions are called - is that correct?
In the following tr... | Cython numpy array indexing | I am trying to speed up some python code with cython, and I'm making use of cython's -a option to see where I can improve things. My understanding is that in the generated html file, the highlighted lines are ones where python functions are called - is that correct?
In the following trivial function, I have declared t... | [
"The answer is that the highlighter fools the reader.\nI compiled your code and the instructions generated under the highlight are those needed\nto handle the error cases and the return value, they are not related to the array assignment.\nIndeed if you change the code to read :\ndef foo(numpy.ndarray[double, ndim=... | [
5
] | [] | [] | [
"arrays",
"cython",
"indexing",
"numpy",
"python"
] | stackoverflow_0007445769_arrays_cython_indexing_numpy_python.txt |
Q:
Giving access to shared memory after child processes have already started
How do I give child processes access to data in shared memory if the data is only available after the child processes have been spawned (using multiprocessing.Process)?
I am aware of multiprocessing.sharedctypes.RawArray, but I can't figure ... | Giving access to shared memory after child processes have already started | How do I give child processes access to data in shared memory if the data is only available after the child processes have been spawned (using multiprocessing.Process)?
I am aware of multiprocessing.sharedctypes.RawArray, but I can't figure out how to give my child processes access to a RawArray that is created after t... | [
"Disclaimer: I am the author of the question.\nI eventually used the posix_ipc module to create my own version of RawArray. I used mainly posix_ipc.SharedMemory which calls shm_open() under the hood.\nMy implementation (ShmemRawArray) exposes the same functionality as RawArray but required two additional parameters... | [
7,
6,
0
] | [] | [] | [
"ipc",
"multiprocessing",
"python",
"shared_memory"
] | stackoverflow_0007419159_ipc_multiprocessing_python_shared_memory.txt |
Q:
Python's threads stuck in Popen.communicate
I have a Python application that uses threads as follows:
Create tasks queue (Queue module)
Create 10 threads and pass to each a queue object
Put tasks into queue (around 8500 tasks in total)
Each thread:
takes a task and runs some Linux commands using Popen.communi... | Python's threads stuck in Popen.communicate | I have a Python application that uses threads as follows:
Create tasks queue (Queue module)
Create 10 threads and pass to each a queue object
Put tasks into queue (around 8500 tasks in total)
Each thread:
takes a task and runs some Linux commands using Popen.communicate()
Mutexes, critical sections, queue manage... | [
"In subprocess.py at line 1131/1132, a file descriptor is duplicated via os.dup.\nFor this reason I suspect your operating system is limiting the number of subprocesses and/or the number of file descriptors available to your application. However, I do not understand why os.dup doesn't raise/throw an exception in th... | [
1
] | [] | [] | [
"multithreading",
"process",
"python"
] | stackoverflow_0007446578_multithreading_process_python.txt |
Q:
Is there a "Back Button" in Python PyS60
What it is I am creating an application on a Nokia mobile phone 5800 series and I was wondering if there was a back button function.
It would be better to give an example of what I mean,
If I typing in some onformation in this application and clicked next, but I forgot to ... | Is there a "Back Button" in Python PyS60 | What it is I am creating an application on a Nokia mobile phone 5800 series and I was wondering if there was a back button function.
It would be better to give an example of what I mean,
If I typing in some onformation in this application and clicked next, but I forgot to add a small piece of information on the previo... | [
"appuifw.app.menu = [(u\"forward\", forward), (u\"back\", back)]\n\n"
] | [
0
] | [] | [] | [
"pys60",
"python"
] | stackoverflow_0005606214_pys60_python.txt |
Q:
Numpy product or tensor product question
How can I calculate this product without a loop? I think I need to use numpy.tensordot but I can't seem to set it up correctly. Here's the loop version:
import numpy as np
a = np.random.rand(5,5,3,3)
b = np.random.rand(5,5,3,3)
c = np.zeros(a.shape[:2])
for i in range(c.sh... | Numpy product or tensor product question | How can I calculate this product without a loop? I think I need to use numpy.tensordot but I can't seem to set it up correctly. Here's the loop version:
import numpy as np
a = np.random.rand(5,5,3,3)
b = np.random.rand(5,5,3,3)
c = np.zeros(a.shape[:2])
for i in range(c.shape[0]):
for j in range(c.shape[1]):
... | [
"I've lost the plot. The answer is simply\nc = a * b\nc = np.sum(c,axis=3)\nc = np.sum(c,axis=2)\n\nor on one line\nc = np.sum(np.sum(a*b,axis=2),axis=2)\n\n",
"May this help you with the syntax ?\n>>> from numpy import *\n>>> a = arange(60.).reshape(3,4,5)\n>>> b = arange(24.).reshape(4,3,2)\n>>> c = tensordot(a... | [
3,
0
] | [] | [] | [
"linear_algebra",
"matrix",
"numpy",
"python"
] | stackoverflow_0007447184_linear_algebra_matrix_numpy_python.txt |
Q:
using Python logger class to generate multiple logs for different log levels
I looked through the tutorials for the python logging class here and didnt see anything that would let me make multiple logs of different levels for the same output. In the end I would like to have three logs:
<timestamp>_DEBUG.log (debu... | using Python logger class to generate multiple logs for different log levels | I looked through the tutorials for the python logging class here and didnt see anything that would let me make multiple logs of different levels for the same output. In the end I would like to have three logs:
<timestamp>_DEBUG.log (debug level)
<timestamp>_INFO.log (info Level)
<timestamp>_ERROR.log (error level)
I... | [
"Create multiple Handlers, each for one output file (INFO.log, DEBUG.log etc.).\nAdd a filter to each handler that only allows the specific level.\nFor example:\nimport logging\n\n# Set up loggers and handlers.\n# ...\n\nclass LevelFilter(logging.Filter):\n def __init__(self, level):\n self.level = level\... | [
15
] | [] | [] | [
"file_io",
"logging",
"python",
"sikuli"
] | stackoverflow_0007447382_file_io_logging_python_sikuli.txt |
Q:
how to use numpy.vectorize or numpy.frompyfunc
[EDIT:I sort of brush this example up so I didn't clean up my code very well. My question is more on, how do I pass a subarray into a numpy.vectorize-d function, not specifically about this example.]
I can't figure out how to use numpy.vectorize or numpy.frompyfunc to... | how to use numpy.vectorize or numpy.frompyfunc | [EDIT:I sort of brush this example up so I didn't clean up my code very well. My question is more on, how do I pass a subarray into a numpy.vectorize-d function, not specifically about this example.]
I can't figure out how to use numpy.vectorize or numpy.frompyfunc to vectorize commands that takes an array as an argume... | [
"One of your problems is that aa and bb are lists, not numpy.array(). You should be doing:\naa = np.array([[1,2,3,4], [2,3,4,5], [5,6,7,8], [9,10,11,12]])\nbb = np.array([[100,200,300,400], [100,200,300,400], [100,200,300,400], [100,200,300,400]])\n\nThe second thing I notice is that to get the second element of ea... | [
5
] | [] | [] | [
"numpy",
"python",
"vectorization"
] | stackoverflow_0007445618_numpy_python_vectorization.txt |
Q:
How to email an attachment from a form with GAE?
My attempt at emailing from a form gets an error message. How should I process the file with the POST request? I don't need to write it to the blobstore, just email it.
Template:
<form method="POST" action="{{form_url}}" name="upload" enctype="multipart/form-data... | How to email an attachment from a form with GAE? | My attempt at emailing from a form gets an error message. How should I process the file with the POST request? I don't need to write it to the blobstore, just email it.
Template:
<form method="POST" action="{{form_url}}" name="upload" enctype="multipart/form-data">
<table border="0"><tr><td colspan="2">
<div... | [
"In GAE uploading a file as you have is synonymous with writing it to the blobstore so you need to work with it as such.\nfrom google.appengine.ext import blobstore\n\nupload_files = self.get_uploads('file')\nblob_info = upload_files[0]\nblob_reader = blobstore.BlobReader(blob_info.key())\n\nmessage.attachments = [... | [
1
] | [] | [] | [
"forms",
"google_app_engine",
"http",
"post",
"python"
] | stackoverflow_0007445309_forms_google_app_engine_http_post_python.txt |
Q:
Importing Large iGraph Memory Exhausted
I'm trying to import a large LGL file (~2GB) and I am attempting to import this in igraph using
graph = Graph.Read_Lgl("Biggraph.lgl")
The error it is throwing is
Traceback (most recent call last):
File "graph.py", line8, in <module>
graph = Graph.Read_Lgl("Biggraph.l... | Importing Large iGraph Memory Exhausted | I'm trying to import a large LGL file (~2GB) and I am attempting to import this in igraph using
graph = Graph.Read_Lgl("Biggraph.lgl")
The error it is throwing is
Traceback (most recent call last):
File "graph.py", line8, in <module>
graph = Graph.Read_Lgl("Biggraph.lgl")
igraph.core.InternalError: Error at fore... | [
"For the record, the poster has found a bug in the igraph library and we are working on a fix right now. The problem is caused by a right-recursive rule in the bison parser specification for the LGL format. Once we have an official patch for it in the trunk of the project, I will post the URL of the patch here shou... | [
3
] | [] | [] | [
"igraph",
"python"
] | stackoverflow_0007435828_igraph_python.txt |
Q:
Django-cms translatable objects
I am implementing payment plans on an multilingual eshop based on django-cms. I need internationalized support for payment plans.
User can enter abritrary number of payment plans (implies standard django models)
Every payment plan must have a description in every language site supp... | Django-cms translatable objects | I am implementing payment plans on an multilingual eshop based on django-cms. I need internationalized support for payment plans.
User can enter abritrary number of payment plans (implies standard django models)
Every payment plan must have a description in every language site supports (3 at the moment). Implies basic... | [
"Found the solution. Django-nani.\n"
] | [
0
] | [] | [] | [
"django",
"django_cms",
"internationalization",
"python"
] | stackoverflow_0007017059_django_django_cms_internationalization_python.txt |
Q:
Creating a Python wrapper for my algorithm which uses Opencv 2.3
I am looking to wrap a c++ class which implements an algorithm I wrote using Opencv 2.3. I am aware that there is python wrappers for opencv as a whole but what I need is to wrap my own code which uses opencv. This seems logical because the lower lev... | Creating a Python wrapper for my algorithm which uses Opencv 2.3 | I am looking to wrap a c++ class which implements an algorithm I wrote using Opencv 2.3. I am aware that there is python wrappers for opencv as a whole but what I need is to wrap my own code which uses opencv. This seems logical because the lower level of my algorithm will be fast compiled c++ code and I will be free t... | [
"I found some code on google that converts numpy array to cv::mat in c++ using boost::python:\nlink\n"
] | [
1
] | [] | [] | [
"boost",
"opencv",
"python",
"swig",
"wrapper"
] | stackoverflow_0007448924_boost_opencv_python_swig_wrapper.txt |
Q:
Return values from one script to another script
I have the following script that will run each script (sequentially) in a directory:
import os
directory = []
for dirpath, dirnames, filenames in os.walk("path\to\scripts"):
for filename in [f for f in filenames if f.endswith(".py")]:
directory.append(o... | Return values from one script to another script | I have the following script that will run each script (sequentially) in a directory:
import os
directory = []
for dirpath, dirnames, filenames in os.walk("path\to\scripts"):
for filename in [f for f in filenames if f.endswith(".py")]:
directory.append(os.path.join(dirpath, filename))
for entry in director... | [
"\nI'm just curious if there is a way to return values so that the parent script can access the data.\n\nThis is why you define functions and return values.\nScript 1 should include a function.\ndef main():\n all the various bits of script 1 except the import \n return x\n\nif __name__ == \"__main__\":\n x... | [
8,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0007448694_python.txt |
Q:
Segmentation fault error for face detection python code in OpenCV 2.2
I recently installed OpenCV v2.2 on my Ubuntu 11 machine using instructions given at http://www.samontab.com/web/2011/06/installing-opencv-2-2-in-ubuntu-11-04/. Im able to run the sample C programs and some of the sample python programs too. But... | Segmentation fault error for face detection python code in OpenCV 2.2 | I recently installed OpenCV v2.2 on my Ubuntu 11 machine using instructions given at http://www.samontab.com/web/2011/06/installing-opencv-2-2-in-ubuntu-11-04/. Im able to run the sample C programs and some of the sample python programs too. But running python facedetect.py ~/img.jpg is giving me "Segmentation Fault".... | [
"Same problem. I've tracked it down to cv.Load on the cascade. I'm on OS X 10.6, OpenCV 2.3.1, and Python 2.6. Here's the dump:\nException Type: EXC_BAD_ACCESS (SIGSEGV)\nException Codes: KERN_INVALID_ADDRESS at 0x0000000000000000\nCrashed Thread: 0 Dispatch queue: com.apple.main-thread\n\nThread 0 Crashed: Dis... | [
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0007296827_opencv_python.txt |
Q:
Call python script within java code (runtime.exec)
I'm trying to run a python script in java but I'm having some troubles.
I'm using the command bellow to execute the python script which is inside a folder called python in my java project:
Runtime r = Runtime.getRuntime();
Process p = r.exec("cmd /c python python\... | Call python script within java code (runtime.exec) | I'm trying to run a python script in java but I'm having some troubles.
I'm using the command bellow to execute the python script which is inside a folder called python in my java project:
Runtime r = Runtime.getRuntime();
Process p = r.exec("cmd /c python python\\test.py");
The script should write something in a text... | [
"Most likely the python executable is not in the path that's given to the child process. Try changing the command line to include the full path to the python executable, as in\nProcess p = r.exec(\"cmd /c c:\\\\path\\\\to\\\\python python\\\\test.py\");\n\n"
] | [
8
] | [] | [] | [
"java",
"python",
"runtime.exec",
"windows"
] | stackoverflow_0007449395_java_python_runtime.exec_windows.txt |
Q:
get element and change element text with python and lxml
First thing first, I know there are many questions regarding python and lxml on StackOverflow already, and I did read most of them, if not all. Right now I am looking for a more comprehensive answer in this question.
I am doing some HTML conversion and I nee... | get element and change element text with python and lxml | First thing first, I know there are many questions regarding python and lxml on StackOverflow already, and I did read most of them, if not all. Right now I am looking for a more comprehensive answer in this question.
I am doing some HTML conversion and I need to grammatically parse the HTML and then do some content cha... | [
"lxml and ElementTree are quite similar. The ElementTree portion of the lxml documentation site, in fact, just points to ElementTree's documentation.\nYou might try working through the ElementTree tutorials and examples at the bottom of the overview page. Since ElementTree is part of the Python distribution, it ten... | [
1
] | [] | [] | [
"html",
"lxml",
"python"
] | stackoverflow_0007449623_html_lxml_python.txt |
Q:
Creating a Django Registration Form by Extending Django-Registation Application
Am trying to create a registration form by extending django-registration app and using Django Profile. I have created the model and form for the profile and when I checked through the django shell it is generating the fields. For the p... | Creating a Django Registration Form by Extending Django-Registation Application | Am trying to create a registration form by extending django-registration app and using Django Profile. I have created the model and form for the profile and when I checked through the django shell it is generating the fields. For the profile fields i am using ModelForm. Now I am struck on how to bring both the django-r... | [
"You are aware that the User model already has first_name and last_name fields, right? Also, you misstyped last_name to last_field.\nI would advise to extend the form provided by django-registration and making a new form that adds your new fields. You can also save the first name and last name directly to the User ... | [
1
] | [] | [] | [
"django",
"django_registration",
"python"
] | stackoverflow_0007447522_django_django_registration_python.txt |
Q:
sqlite3.OperationalError: near "?": syntax error in python -- using 'IN' operator
Code:
print 'SELECT %s FROM %s WHERE %s %s %s' % (q_select, q_table, q_where, q_where_operator, q_value)
rows = cursor.execute('SELECT %s FROM %s WHERE %s %s ?' % (q_select, q_table, q_where, q_where_operator), (q_value,)).fetchall()... | sqlite3.OperationalError: near "?": syntax error in python -- using 'IN' operator | Code:
print 'SELECT %s FROM %s WHERE %s %s %s' % (q_select, q_table, q_where, q_where_operator, q_value)
rows = cursor.execute('SELECT %s FROM %s WHERE %s %s ?' % (q_select, q_table, q_where, q_where_operator), (q_value,)).fetchall()
Result:
SELECT ticket FROM my_table WHERE issue_key IN ('APSEC-2261')
Traceback (most... | [
"The problem is when one uses the IN operator, they must have the ? in parentheses, (?).\n>>> t = ('APSEC-2261',)\n>>> cursor.execute('SELECT remediation_ticket FROM remediation WHERE issue_key IN (?)', t)\n<sqlite3.Cursor object at 0x1723570>\n>>> cursor.execute('SELECT remediation_ticket FROM remediation WHERE is... | [
3,
3
] | [] | [] | [
"python",
"sqlite",
"syntax_error"
] | stackoverflow_0007447938_python_sqlite_syntax_error.txt |
Q:
rename files in zip folder using zipmodule
I was wondering if anyone knows how I can rename a file called "logo.png" in my zip folder under ("fw/resources/logo.png") to ("fw/resources/logo.png.bak"), using python's zip module.
A:
As mentioned by rocksportrocker, you cannot rename/remove a file from a zipfile ar... | rename files in zip folder using zipmodule | I was wondering if anyone knows how I can rename a file called "logo.png" in my zip folder under ("fw/resources/logo.png") to ("fw/resources/logo.png.bak"), using python's zip module.
| [
"As mentioned by rocksportrocker, you cannot rename/remove a file from a zipfile archive. You would have iterate over the files in the zipfile and selectively add the files you want. So to remove a certain directory from the zipfile, you would not copy them to the new zipfile. That would be something like this:\nso... | [
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0007428318_python.txt |
Q:
pl/python TypeError: sequence item 21: expected string, int found
Friends: in PostgreSQL plpython, am trying to do an iterative search/replace in a text block 'data'.
Using re-sub to define a match pattern, then call a function 'replace' to do the work.
Objective is to have the 'replace' function called repeatedl... | pl/python TypeError: sequence item 21: expected string, int found | Friends: in PostgreSQL plpython, am trying to do an iterative search/replace in a text block 'data'.
Using re-sub to define a match pattern, then call a function 'replace' to do the work.
Objective is to have the 'replace' function called repeatedly, as some replacements generate further 'rule' matches, which require ... | [
"The answer to this turned out to be quite simple, of course, once you know Python! (I don't!)\nTo initiate the repeat loop, I had been doing this test:\nwhile re.search('(rule:[A-Za-z#]+)', data) != '':\n\nHad also tried this one, which will also not work:\nwhile re.search('(rule:[A-Za-z#]+)', data) != 'None':\n\n... | [
0
] | [] | [] | [
"plpython",
"postgresql",
"python"
] | stackoverflow_0007356333_plpython_postgresql_python.txt |
Q:
Python functions in Mako templates (not in module-level blocks)
I'm using Pyramid and Mako for templating.
It is possible to define a (semi-anonymous) function within a Mako block <% and %>.
I know it can be done with a module-level block <%! and %>, but this means my function doesn't have any access to the local ... | Python functions in Mako templates (not in module-level blocks) | I'm using Pyramid and Mako for templating.
It is possible to define a (semi-anonymous) function within a Mako block <% and %>.
I know it can be done with a module-level block <%! and %>, but this means my function doesn't have any access to the local scope when templating, meaning I have to pass every bit of variable i... | [
"Add a dictionary in your context using:\ntemplate.render(local_vars={})\n\nand then use it in your functions.\nNote: Mako is too fast, because the engine will create a python module for each *.mak(template file) before render it, you may try this:\nfrom mako.template import Template\nmytemplate = Template(filename... | [
3,
0
] | [] | [] | [
"function",
"mako",
"python",
"templating"
] | stackoverflow_0007448722_function_mako_python_templating.txt |
Q:
Python - Extracting text by Column Header from Given Row
I created a text file from multiple email messages.
Each of the three tuples below was written to the text file from a different email message and sender.
Cusip NAME Original Current Cashflow Collat Offering
362341D71 GSAA 2005-15 2A2 1... | Python - Extracting text by Column Header from Given Row | I created a text file from multiple email messages.
Each of the three tuples below was written to the text file from a different email message and sender.
Cusip NAME Original Current Cashflow Collat Offering
362341D71 GSAA 2005-15 2A2 10,000 8,783 FCF 5/25 65.000
026932AC7 AHM 2007-1 GA1... | [
"The formatting for this makes it a little tricky since your names can have spaces, which can make csv difficult to use. One way to get around this is to use the first column to get the location and width of the columns you are interested by using regex. You can try something like this:\nimport re\n\nfor email in... | [
3,
0
] | [] | [] | [
"python",
"text"
] | stackoverflow_0007449677_python_text.txt |
Q:
How to Send Sequence to Web Gene Prediction Server in Python?
I am currently doing some projects about 'ab initio gene prediction' programs.
I found some interesting web gene prediction servers such as 'FGENESH' and 'GenScan'.
Url Below:
http://linux1.softberry.com/berry.phtml?topic=fgenesh&group=programs&subgroup... | How to Send Sequence to Web Gene Prediction Server in Python? | I am currently doing some projects about 'ab initio gene prediction' programs.
I found some interesting web gene prediction servers such as 'FGENESH' and 'GenScan'.
Url Below:
http://linux1.softberry.com/berry.phtml?topic=fgenesh&group=programs&subgroup=gfind
What I want to ask you is how I can send DNA sequence file i... | [
"The raw way for your problem is to use mechanize (kind of simulates the browser). And then for parsing XML/HTML-results, you probably want to use BeautifulSoup, which allows you to get the XML-structure in a composited object-oriented format, from where you can access text and attributes. There are dozens of examp... | [
0
] | [] | [] | [
"bioinformatics",
"parsing",
"python",
"web"
] | stackoverflow_0007410953_bioinformatics_parsing_python_web.txt |
Q:
How do I get user input from the keyboard in Python 2?
I wrote a function in Python which prompts the user to give two numbers and adds them.
It also prompts the user to enter a city and prints it. For some reason, when I run it in a shell, I get "name is not defined" after I enter the city.
def func_add(num1, nu... | How do I get user input from the keyboard in Python 2? | I wrote a function in Python which prompts the user to give two numbers and adds them.
It also prompts the user to enter a city and prints it. For some reason, when I run it in a shell, I get "name is not defined" after I enter the city.
def func_add(num1, num2):
a = input("your city")
print a
return num1 + n... | [
"If you're on Python 2, you need to use raw_input:\ndef func_add(num1, num2):\n\n a = raw_input(\"your city\")\n print a\n return num1 + num2 \n\ninput causes whatever you type to be evaluated as a Python expression, so you end up with\na = whatever_you_typed\n\nSo if there isn't a variable named whatever_you... | [
9,
1,
0,
0,
0,
0
] | [] | [] | [
"input",
"python",
"python_2.x"
] | stackoverflow_0007450223_input_python_python_2.x.txt |
Q:
Calling 'mv' from Python Popen with wildcard
I can't seem to get the 'mv' command to work from Python subprocess.Popen with a wildcard.
The code:
def moveFilesByType(source, destination, extension):
params = []
params.append("mv")
params.append(source + "/*." + extension)
params.append(dest... | Calling 'mv' from Python Popen with wildcard | I can't seem to get the 'mv' command to work from Python subprocess.Popen with a wildcard.
The code:
def moveFilesByType(source, destination, extension):
params = []
params.append("mv")
params.append(source + "/*." + extension)
params.append(destination + "/")
print params
pipe = subp... | [
"Use a string instead of an array:\nparams = \"mv /full_path_to_folder_source/*.nib /full_path_to_folder_target/\"\n\nWhen you specify arguments via the array form, the argument '/full_path_to_folder_source/*.nib' is passed to mv. You want to force bash to expand the argument, but Popen won't pass each argument th... | [
9,
3,
1
] | [] | [] | [
"python",
"scripting",
"shell",
"unix"
] | stackoverflow_0007450456_python_scripting_shell_unix.txt |
Q:
Replicating the indices result of Matlab's ISMEMBER function in NumPy?
I have been racking my brain for a solution that is along the lines of this older question. I have been trying to find a Python code pattern that replicates the indices result. For example:
A = [3;4;4;3;6]
B = [2;5;2;6;3;2;2;5]
[tf ix] = isme... | Replicating the indices result of Matlab's ISMEMBER function in NumPy? | I have been racking my brain for a solution that is along the lines of this older question. I have been trying to find a Python code pattern that replicates the indices result. For example:
A = [3;4;4;3;6]
B = [2;5;2;6;3;2;2;5]
[tf ix] = ismember(A,B)
>> A(tf)
ans =
3
3
6
>> B(ix(tf))
ans =
3
... | [
"import numpy as np\n\nA = np.array([3,4,4,3,6])\nB = np.array([2,5,2,6,3,6,2,2,5])\n\ndef ismember(a, b):\n # tf = np.in1d(a,b) # for newer versions of numpy\n tf = np.array([i in b for i in a])\n u = np.unique(a[tf])\n index = np.array([(np.where(b == i))[0][-1] if t else 0 for i,t in zip(a,tf)])\n ... | [
5
] | [] | [] | [
"matlab",
"numpy",
"python"
] | stackoverflow_0007448554_matlab_numpy_python.txt |
Q:
Does this sorting algorithm have a name? (Cross between select and merge)
I just thought of an interesting way to do a sort. I'm sure someone has thought of it before, but I've never seen it. It goes in two steps:
1- Iterate through the input list, pulling out sequences of items that are in order (not necessarily ... | Does this sorting algorithm have a name? (Cross between select and merge) | I just thought of an interesting way to do a sort. I'm sure someone has thought of it before, but I've never seen it. It goes in two steps:
1- Iterate through the input list, pulling out sequences of items that are in order (not necessarily contiguous) into bins. Create one bin for each pass, until the list is empty.
2... | [
"I believe that you're looking at strand sort, a modified merge sort that works by locating and removing \"strands\" of increasing values out of the original array, then merging all the strands back together. It has best-case runtime O(n) if the input sequence is already sorted, and both average- and worst-case ru... | [
4,
2,
2,
1
] | [] | [] | [
"algorithm",
"python",
"sorting"
] | stackoverflow_0007447904_algorithm_python_sorting.txt |
Q:
How do I get the XML having No Root Node in Python
Given the following data:
<rdf:RDF
xmlns="http://purl.org/rss/1.0/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
xmlns:dc="http://purl.org/dc/elements/1.
<channel rdf:about="http://www... | How do I get the XML having No Root Node in Python | Given the following data:
<rdf:RDF
xmlns="http://purl.org/rss/1.0/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
xmlns:dc="http://purl.org/dc/elements/1.
<channel rdf:about="http://www.gmanews.tv/">
<title>GMANews.TV</title>
... | [
"lxml provides a nice way to handle all things XML. An example for the XML you posted:\nfrom lxml import etree\n\ndocument = etree.parse('your-example-xml.rdf')\nroot = document.getroot()\n\n# Namespace shortcuts\nns = root.nsmap.get(None)\nrdf = root.nsmap.get('rdf')\n\nfor item in root.xpath('purl:item', namespac... | [
2,
1
] | [] | [] | [
"python",
"xml",
"xml_parsing"
] | stackoverflow_0007413873_python_xml_xml_parsing.txt |
Q:
circular array class in python
I have a project to create a circular array class, and the language I will be using is python. I am new to classes in python, but after reading through some webpages and chapters in books I think I have an understanding of how they work. However I need help, so I figured I would come... | circular array class in python | I have a project to create a circular array class, and the language I will be using is python. I am new to classes in python, but after reading through some webpages and chapters in books I think I have an understanding of how they work. However I need help, so I figured I would come to the wonderful teachers here at S... | [
"In __init__ you set\nself.store = []\n\nIn addToBack you do \nself.store[self.endIndex] = value\n\nIf this is the first operation on the circular array, and you pass 2 as the value, then that turns into\n[][0] = 2\n\nThe problem should be obvious -- an empty list has no index of 0, it has no indexes at all.\nYou n... | [
1
] | [] | [] | [
"circular_buffer",
"class",
"python"
] | stackoverflow_0007450804_circular_buffer_class_python.txt |
Q:
decoding, little endian, uncompressed and float array
I have Base64 encoded data from an experiment. So what I am trying to do in stepwise is:
Retrieve bytes from base64 encoding (Decode it)
Convert bytes to little-endian
Decompress bytes from (zlib)
Convert byte array to float array
Example:
Dn3LQ3np4kOyxQJE20... | decoding, little endian, uncompressed and float array | I have Base64 encoded data from an experiment. So what I am trying to do in stepwise is:
Retrieve bytes from base64 encoding (Decode it)
Convert bytes to little-endian
Decompress bytes from (zlib)
Convert byte array to float array
Example:
Dn3LQ3np4kOyxQJE20kDRBRuFkScZB5ENxEzRFa+O0THMz9EOQRCRFC1QkRYeUNEwXJJROfbSUScv... | [
"It appears your data isn't actually compressed. Read the data as floats either in a loop using struct.unpack_from() or as one big structure using struct.unpack().\nimport base64\nimport struct\n\nencoded = 'Dn3LQ3np ... 9BnKRA=='\n\n# decode the string\ndata = base64.standard_b64decode(encoded)\n\n# ensure that t... | [
6,
1,
0
] | [] | [] | [
"base64",
"python"
] | stackoverflow_0007450454_base64_python.txt |
Q:
issue while committing data using SQLAlchemy Session object in a Loop
I am having a database committing problem with SQLalchemy. Here is my scenario I have a list of records to be added into a table. Once a records is added into a table I need to get the inserted records Id and do another insert into a second tabl... | issue while committing data using SQLAlchemy Session object in a Loop | I am having a database committing problem with SQLalchemy. Here is my scenario I have a list of records to be added into a table. Once a records is added into a table I need to get the inserted records Id and do another insert into a second table. I am doing these operation under single session. The code structure is g... | [
"There's a very good chance that you don't need to issue two commits; One of the main reasons for using sqlalchemy sessions is that it understands how objects can interrelate, and will order its inserts in such a way that data gets properly inserted and correctly represents the desired structure. This works princ... | [
8,
4
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007447309_python_sqlalchemy.txt |
Q:
python urllib returns two 0xfffd characters instead of expected unicode characters
I'm scraping some website, encoding is unicode:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
To do that I use urllib:
html = unicode(urllib.openurl(url).read(), 'utf-8')
Sometimes some of the unicode chara... | python urllib returns two 0xfffd characters instead of expected unicode characters | I'm scraping some website, encoding is unicode:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
To do that I use urllib:
html = unicode(urllib.openurl(url).read(), 'utf-8')
Sometimes some of the unicode characters will be replaced with two 0xFFFD characters at random. I guess that a single chara... | [
"Browsers do a lot of magic to correct invalid characters. Try looking at the raw bytes returned by .read() and check to see if the source page has invalid characters. For example, sometimes pages will encode accented letters with latin-1 or similar, and other characters with utf-8.\n",
"I see two possibilities.\... | [
0,
0,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0007438445_python_unicode.txt |
Q:
python module for html
I've seen few people ask this question. But what i'm looking for is more specific. I need a module that works with python 2.4 and it's only for html (not too new like html5) and potentially css.
what i'm going to do is to extract info from a text file or from a database and write it to an h... | python module for html | I've seen few people ask this question. But what i'm looking for is more specific. I need a module that works with python 2.4 and it's only for html (not too new like html5) and potentially css.
what i'm going to do is to extract info from a text file or from a database and write it to an html file.
What do you think... | [
"Have you tried lxml?\n>>> from lxml.html import builder as E\n>>> from lxml.html import usedoctest\n>>> html = E.HTML(\n... E.HEAD(\n... E.LINK(rel=\"stylesheet\", href=\"great.css\", type=\"text/css\"),\n... E.TITLE(\"Best Page Ever\")\n... ),\n... E.BODY(\n... E.H1(E.CLASS(\"heading\"), \"Top N... | [
1,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0007451069_html_python.txt |
Q:
SQLAlchemy Event interface
I'm using SQLAlchemy 0.7. I would like some 'post-processing' to occur after a session.flush(), namely, I need to access the instances involved in the flush() and iterate through them. The flush() call will update the database, but the instances involved also store some data in an LDAP d... | SQLAlchemy Event interface | I'm using SQLAlchemy 0.7. I would like some 'post-processing' to occur after a session.flush(), namely, I need to access the instances involved in the flush() and iterate through them. The flush() call will update the database, but the instances involved also store some data in an LDAP database, I would like SQLAlchemy... | [
"According to the link you provided:\n\nNote that the session’s state is still in pre-flush, i.e. ‘new’, ‘dirty’, and ‘deleted’ lists still show pre-flush state as well as the history settings on instance attributes.\n\nThis means that you should be able to get an access of all the dirty objects in the session.dirt... | [
4
] | [] | [] | [
"events",
"python",
"sqlalchemy"
] | stackoverflow_0007275888_events_python_sqlalchemy.txt |
Q:
MatPlotLib coulored triangulars
I have no idea how to plot the following. My data file contains the corner points of many triangulars in the following structure:
1 0
0 1
1 1
0.1 1
0.2 2
0.3 3
I want to draw them in one image and color the surface of each triangles differently. How do I do that?
Thanks for the he... | MatPlotLib coulored triangulars | I have no idea how to plot the following. My data file contains the corner points of many triangulars in the following structure:
1 0
0 1
1 1
0.1 1
0.2 2
0.3 3
I want to draw them in one image and color the surface of each triangles differently. How do I do that?
Thanks for the help : )
| [
"a quick look at artist demo\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfig = plt.figure(figsize=(5,5))\nax = plt.axes([0,0,1,1])\ntriangle1 = mpatches.Polygon(np.array([[0,1],[1,0],[1,1]]), fc=\"blue\")\ntriangle2 = mpatches.Polygon(np.array([[-0.1,-1],[-2,-2],[-2,... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007451320_matplotlib_python.txt |
Q:
Pymongo, connection pooling and asynchronous tasks via Celery
I'm using pymongo to access mongodb in an application that also uses Celery to perform many asynchronous tasks. I know pymongo's connection pooling does not support asynchronous workers (based on the docs).
To access collections I've got a Collection c... | Pymongo, connection pooling and asynchronous tasks via Celery | I'm using pymongo to access mongodb in an application that also uses Celery to perform many asynchronous tasks. I know pymongo's connection pooling does not support asynchronous workers (based on the docs).
To access collections I've got a Collection class wrapping certain logic that fits my application. I'm trying to... | [
"From pymongo's docs : \"PyMongo is thread-safe and even provides built-in connection pooling for threaded applications.\"\nThe word \"asynchronous\" in your situation can be translated into how \"inconsistent\" requirements your application has.\nStatements like \"x += 1\" will never be consistent in your app. If ... | [
0
] | [] | [] | [
"celery",
"connection_pooling",
"django",
"pymongo",
"python"
] | stackoverflow_0006987804_celery_connection_pooling_django_pymongo_python.txt |
Q:
Accessing DateCreated and DateUpdated in Django/Python for Twilio
Here's my first post! I'm working with a python web app that is recording phone calls. I am able to access client.recordings.uri, but I'm not able to access recordings.datecreated or dateupdated in my code.
{% for recording in recordings %}
<li... | Accessing DateCreated and DateUpdated in Django/Python for Twilio | Here's my first post! I'm working with a python web app that is recording phone calls. I am able to access client.recordings.uri, but I'm not able to access recordings.datecreated or dateupdated in my code.
{% for recording in recordings %}
<li><a href="{{ recording.uri }}.mp3">{{ recording.datecreated }} {{ recor... | [
"{% for recording in recordings %}\n<li>\n <a href=\"{{ recording.uri }}.mp3\">\n {{ recording.date_created }} {{ recording.duration }} sec.\n </a>\n</li>\n{% endfor %}\n\nYou'll need to add an underscore between datecreated. You can find a list of all attributes on the recording object here.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"twilio"
] | stackoverflow_0007451246_django_python_twilio.txt |
Q:
Is it possible to synchronize lists in Python?
For instance, if I have a list of words:
Words = ['A', 'list', 'of', 'words']
and want a second list to reference the lengths of those words, how could I achieve this? I'm aware that I could do something like:
Lengths = map(lambda w: len(w), Words)
[1, 4, 2, 5]
but ... | Is it possible to synchronize lists in Python? | For instance, if I have a list of words:
Words = ['A', 'list', 'of', 'words']
and want a second list to reference the lengths of those words, how could I achieve this? I'm aware that I could do something like:
Lengths = map(lambda w: len(w), Words)
[1, 4, 2, 5]
but I would have to continually call that function every... | [
"You could use a class:\nclass mywords:\n def __init__(self, a):\n self.words = a\n self.length = map(lambda w: len(w), a)\n def append(self, string):\n self.words.append(string)\n self.length.append(len(string))\n\n\na = mywords(['A', 'list', 'of', 'words'])\n\na.append(\"this\")\... | [
4,
3
] | [] | [] | [
"list",
"python",
"synchronization"
] | stackoverflow_0007451492_list_python_synchronization.txt |
Q:
Retaining variable with method in python
I'm trying to have python recall the 'enstring' variable I set using the 'crypto' method I created so I can use it in the 'decrypto' method.
class encryptString():
def crypto(self, string):
enstring = base64.b64encode(string)
print enstring
def decr... | Retaining variable with method in python | I'm trying to have python recall the 'enstring' variable I set using the 'crypto' method I created so I can use it in the 'decrypto' method.
class encryptString():
def crypto(self, string):
enstring = base64.b64encode(string)
print enstring
def decrypto(self, enstring):
destring = base6... | [
"If you want the class to save enstring as a member, then you must assign it to self.enstring:\nclass encryptString():\n\n def __init__(self):\n self.enstring = ''\n self.destring = ''\n\n def crypto(self, string):\n self.enstring = base64.b64encode(string)\n print self.enstring\n\... | [
3,
1
] | [] | [] | [
"methods",
"python",
"save",
"variables"
] | stackoverflow_0007451486_methods_python_save_variables.txt |
Q:
Which is a better cross platform language?
If you wanted to distribute a program to as many OS as much as possible what's the best language to use?
I'm considering user's convenience here. For example, they don't need to download java run time, flash or .net framework if they don't have it. Also once they download... | Which is a better cross platform language? | If you wanted to distribute a program to as many OS as much as possible what's the best language to use?
I'm considering user's convenience here. For example, they don't need to download java run time, flash or .net framework if they don't have it. Also once they download it, they don't need to compile it themselves.
I... | [
"Make it a web application with all the computation done server side. That should be very broad.\n",
"Both Java and Python would do the job. IMHO, Python would do it in a nicer way and would make you happier, especially if you are coming from a C-like language. Java would probably be faster, unless you do some h... | [
2,
0,
0,
0,
0
] | [] | [] | [
"apache_flex",
"cross_platform",
"java",
"python"
] | stackoverflow_0007451538_apache_flex_cross_platform_java_python.txt |
Q:
Extract specific lines from file and create sections of data in python
Trying to write a python script to extract lines from a file. The file is a text file which is a dump of python suds output.
I want to:
strip all characters except words and numbers. I don't want any "\n", "[", "]", "{", "=", etc character... | Extract specific lines from file and create sections of data in python | Trying to write a python script to extract lines from a file. The file is a text file which is a dump of python suds output.
I want to:
strip all characters except words and numbers. I don't want any "\n", "[", "]", "{", "=", etc characters.
find a section where it starts with "ArrayOf_xsd_string"
remove the next ... | [
"Several suggestions on your code:\nStripping all non-alphanumeric characters is totally unnecessary and timewasting; there is no need whatsoever to build linelist. Are you aware you can simply use plain old string.find(\"ArrayOf_xsd_string\") or re.search(...)?\n\nstrip all characters except words and numbers. I d... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007451239_python.txt |
Q:
Django's Double Underscore
In Django, you can make database queries like the following:
Model.objects.filter(name__icontains = 'bob')
The question is: how is this working 'under the cover'? Is the double underscore a Django thing or a Python thing? Is this just a single variable named name__icontains, or is it... | Django's Double Underscore | In Django, you can make database queries like the following:
Model.objects.filter(name__icontains = 'bob')
The question is: how is this working 'under the cover'? Is the double underscore a Django thing or a Python thing? Is this just a single variable named name__icontains, or is it some sort of attribute-access s... | [
"It's a Django thing, implemented with some Python things.\nIn Python, you can get a dictionary of the keyword arguments passed to a function or method:\n>>> def func(*args, **kwargs):\n... print(kwargs)\n>>> func(a=1, b=2)\n{'a': 1, 'b': 2}\n\nFrom there, it can simply iterate over the dictionary keys and spli... | [
20
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007451933_django_python.txt |
Q:
How do I ask a function for the names of its parameters in Python?
Possible Duplicate:
Getting list of parameters inside python function
E.g. supposes I have
def foo(a, b='B'): return
How can I ask foo to tell me that it has required parameter 'a', and parameter 'b', which has 'B' as it's default value?
A:
Us... | How do I ask a function for the names of its parameters in Python? |
Possible Duplicate:
Getting list of parameters inside python function
E.g. supposes I have
def foo(a, b='B'): return
How can I ask foo to tell me that it has required parameter 'a', and parameter 'b', which has 'B' as it's default value?
| [
"Use inspect.getargspec.\ndef foo(a, b='B'): pass\n\nimport inspect\nprint inspect.getargspec(foo)\n\nIt may appear to be unclear which argument the default is for, but since non-default arguments can't follow default arguments, the default has to be for the 2nd argument.\nEdit: The linked duplicate is good, an ans... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007452036_python.txt |
Q:
Errors Writing CSVs with Python
I'm encountering errors in the .csv files that I'm writing with python (the necessary format because I'm on a team which depends on .csvs). In a non-patterned way, there are errors creeping up across hundreds of 1g files. For example, an extra 10 columns for only 1 row, an extra r... | Errors Writing CSVs with Python | I'm encountering errors in the .csv files that I'm writing with python (the necessary format because I'm on a team which depends on .csvs). In a non-patterned way, there are errors creeping up across hundreds of 1g files. For example, an extra 10 columns for only 1 row, an extra row with eroneous inputs, certain rows... | [
"As an aside, using xrange instead of range is usually faster.\nAre you absolutely certain that the memory and and disk on the machine that runs the job are good? Since your data ranges into the hundreds of gigabytes, it's not out of the question that you're seeing hardware-based corruption. Even if the machine see... | [
3
] | [] | [] | [
"csv",
"file_io",
"numpy",
"python"
] | stackoverflow_0007452195_csv_file_io_numpy_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.