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:
Split string into different variables instead of array in Python
Possible Duplicate:
Python Split String
Is possible to directly split string into variables in one line, instead of using two lines. I'm sure that split would have two elements.
Two lines example:
myString = "Anonym Anonymous"
a = myString.split()
... | Split string into different variables instead of array in Python |
Possible Duplicate:
Python Split String
Is possible to directly split string into variables in one line, instead of using two lines. I'm sure that split would have two elements.
Two lines example:
myString = "Anonym Anonymous"
a = myString.split()
firstName,lastName = a[0],a[1]
| [
"firstName, lastName = myString.split() should do it if you're sure it will return 2.\nBetter is firstName, lastName = myString.split(' ', 1)\n",
"firstname, lastname = \"Anonym Anonymous\".split()\n\n"
] | [
78,
7
] | [] | [] | [
"python"
] | stackoverflow_0006670290_python.txt |
Q:
Boost python wrapping a virtual method
I'm using boost python to create a binding to a c++ library. A number of classes in this library have virtual methods which accept iterator/const_iterator types as arguments. I don't particularly want to expose these types but would prefer to create some wrappers around these... | Boost python wrapping a virtual method | I'm using boost python to create a binding to a c++ library. A number of classes in this library have virtual methods which accept iterator/const_iterator types as arguments. I don't particularly want to expose these types but would prefer to create some wrappers around these virtual methods that accept the appropriate... | [
"\nDocumentation on virtual functions you reference is related to wrapping virtual functions which can be further overridden in python -- i.e. in python classes deriving from the c++ class. The logic is such that c++ only handles virtual resolution in c++; if it lands on the wrapper class (from which your python cl... | [
0
] | [] | [] | [
"boost_python",
"c++",
"python",
"virtual_functions"
] | stackoverflow_0006668670_boost_python_c++_python_virtual_functions.txt |
Q:
Python selenium webdriver click functionality
Does anyone know how you can click on a link based on the href using the python webdriver bindings. In waitr-webdriver you can do something like this:
browser.link(:href => "http://www.testsite.com/pageOne.html").click
But I haven't be able to find a similar function ... | Python selenium webdriver click functionality | Does anyone know how you can click on a link based on the href using the python webdriver bindings. In waitr-webdriver you can do something like this:
browser.link(:href => "http://www.testsite.com/pageOne.html").click
But I haven't be able to find a similar function in the python webdriver. All there is are
find_ele... | [
"Under the covers, watir-webdriver is converting the call to find the link where the href attribute is a given value into a WebDriver find-by-XPath expression. Mimicing this in your own code, the appropriate way to handle this in Python would be:\n# assume driver is an instance of WebDriver\n# NOTE: this code is un... | [
6
] | [] | [] | [
"click",
"python",
"selenium",
"webdriver"
] | stackoverflow_0006669352_click_python_selenium_webdriver.txt |
Q:
Issues installing scrapy on OS X 10.6
When trying to install Scrapy 0.12 I'm running in to a reoccurring issue with the GCC 4.2 compiler.
From reading MANY posts on this i'm worried I've started to do more damage than good.
any suggestions on what I'm missing?
I've:
Installed xcode4 (from the appstore, not CD)
... | Issues installing scrapy on OS X 10.6 | When trying to install Scrapy 0.12 I'm running in to a reoccurring issue with the GCC 4.2 compiler.
From reading MANY posts on this i'm worried I've started to do more damage than good.
any suggestions on what I'm missing?
I've:
Installed xcode4 (from the appstore, not CD)
reinstalled python with dependencies from m... | [
"See this answer. Because you have installed Xcode 4, you need to remove PPC from the standard architectures that the Apple-supplied Python in 10.6 attempts to build for.\n"
] | [
2
] | [] | [] | [
"gcc",
"macos",
"python",
"scrapy"
] | stackoverflow_0006665016_gcc_macos_python_scrapy.txt |
Q:
Python - GTK - applet similar to gnome dictionary error
I'm new to programing, this is my first python-gtk applet and I'm trying to make an applet similar to gnome-dictionary that retrieves the word meaning from the site http://www.priberam.pt/dlpo/. I'm doing it little-by-little but now I'm stuck, can someone hel... | Python - GTK - applet similar to gnome dictionary error | I'm new to programing, this is my first python-gtk applet and I'm trying to make an applet similar to gnome-dictionary that retrieves the word meaning from the site http://www.priberam.pt/dlpo/. I'm doing it little-by-little but now I'm stuck, can someone help me to see what am I doing wrong?
I get this error:
"TypeErr... | [
"Why is the function enter_callback a method of the class x? It doesn't seem like there is any good structural reason for it to be in x in the first place. Take it out of x and the error message will go away (the error message is complaining that self isn't being passed to enter_callback). Well, at least this one w... | [
0
] | [] | [] | [
"gtk",
"html_parsing",
"python"
] | stackoverflow_0006638714_gtk_html_parsing_python.txt |
Q:
wxpython's SetTransparent doesn't capture user input if set to an opacity of zero
I'm trying to make a wxpython window (only a window in the sense that it's a window object).. that fills the entire screen and is completely invisible. I then want to allow the user to click and drag within the "window" (ie. anywhere... | wxpython's SetTransparent doesn't capture user input if set to an opacity of zero | I'm trying to make a wxpython window (only a window in the sense that it's a window object).. that fills the entire screen and is completely invisible. I then want to allow the user to click and drag within the "window" (ie. anywhere on the screen).
When I try doing self.SetTransparent(0) user input doesn't get capture... | [
"You can override EVT_ERASE_BACKGROUND to accomplish the same effect.\nI also cleaned up other aspects of the code.\nBehaves slightly differently on XP versus 7, but probably not an issue for the type of app you're describing.\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n super(Frame, self)... | [
1
] | [] | [] | [
"invisible",
"opacity",
"python",
"transparent",
"wxpython"
] | stackoverflow_0006670483_invisible_opacity_python_transparent_wxpython.txt |
Q:
Django cache causes duplicate key error in database?
Possible Duplicate:
Django cache.set() causing duplicate key error
I ran into this problem using django core's database cache:
ERROR: duplicate key value violates unique constraint "cache_pkey"
STATEMENT: INSERT INTO "cache" (cache_key, value, expires) VALUE... | Django cache causes duplicate key error in database? |
Possible Duplicate:
Django cache.set() causing duplicate key error
I ran into this problem using django core's database cache:
ERROR: duplicate key value violates unique constraint "cache_pkey"
STATEMENT: INSERT INTO "cache" (cache_key, value, expires) VALUES (E':1:cms-menu_nodes_en-us_1', E'gAJdcQEoY21lbnVzLmJhc2... | [
"\nSounds like a bug in django core, since if a key exist, it should update the record.\n\nIndeed, but I'd suggest that said bug is related to a concurrency issue, in which case it could be fixed at the app level. As in two neighboring calls to the same asset/page/whatever run an exist() statement, find no row, and... | [
1
] | [] | [] | [
"caching",
"database",
"django",
"postgresql",
"python"
] | stackoverflow_0006666728_caching_database_django_postgresql_python.txt |
Q:
A minimum configuration or turnkey web-server to run Django or any other python based web-framework?
Is there anything similar solution like XAMPP (which is php ready) for python frameworks. More or less like a turnkey solution deploy and run python based web-services on linux and windows desktops.
I am confused w... | A minimum configuration or turnkey web-server to run Django or any other python based web-framework? | Is there anything similar solution like XAMPP (which is php ready) for python frameworks. More or less like a turnkey solution deploy and run python based web-services on linux and windows desktops.
I am confused what is the purpose of Tornado Web Server. The site says it is Web Server, then it also say something about... | [
"I'm currently using nginx + CherryPy http://www.cherrypy.org/ quite happily. CherryPy seems about as simple as it can get when hosting a Django powered website.\n",
"You will always deploy some kind of web server as a front-end to your Python code.\nApache, nginx or lighttpd.\nFor most Python frameworks, you'll... | [
1,
0
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"xampp"
] | stackoverflow_0006669446_apache_django_mod_wsgi_python_xampp.txt |
Q:
How to draw a transparent section within an opaque area
How would you go about cutting a transparent hole into the background of a wxpython window?
Would I have to draw the non transparent area manually, leaving a hole, instead of being able to use a background colour?
A:
Adapting my answer to your previous ques... | How to draw a transparent section within an opaque area | How would you go about cutting a transparent hole into the background of a wxpython window?
Would I have to draw the non transparent area manually, leaving a hole, instead of being able to use a background colour?
| [
"Adapting my answer to your previous question, though I'm not sure if this meets your needs 100%. Let me know?\nBasically we're leaving the previous screen contents intact by not erasing the background. Then we handle the paint events and only draw on certain portions of the screen.\nYou could switch back to using ... | [
2
] | [] | [] | [
"python",
"transparent",
"wxpython"
] | stackoverflow_0006670948_python_transparent_wxpython.txt |
Q:
HDI: write large string xml into file (python xml.dom.minidom)
I'm currently building large xml files with xml.dom.minidom and then writing them out to file via the toprettyxml. is there a way to stream the xml to a document because I'm hitting memory errors.
def run(self):
while True:
domain = self.q... | HDI: write large string xml into file (python xml.dom.minidom) | I'm currently building large xml files with xml.dom.minidom and then writing them out to file via the toprettyxml. is there a way to stream the xml to a document because I'm hitting memory errors.
def run(self):
while True:
domain = self.queue.get()
try:
conn = boto.connect_sdb(awsa, aw... | [
"\nbuilding large xml files with xml.dom.minidom and then writing them out to file via the toprettyxml.\n\nIf you run out of memory you should probably stop doing that.\nYou can build XML with simple string manipulation.\nwith open(domain + \".xml\", \"w\") as f:\n f.write( \"<?xml...\" )\n f.write( \"<items... | [
1
] | [] | [] | [
"minidom",
"python",
"stream",
"xml"
] | stackoverflow_0006670934_minidom_python_stream_xml.txt |
Q:
What is the best way to implement a pool of worker processes compatible with gevent?
Scenario
I have a server process implemented in Python and gevent, which is connecting to a backend service over TCP/IP and serving many Web clients (~1000 per process) with fast changing dynamic content based on the changes deliv... | What is the best way to implement a pool of worker processes compatible with gevent? | Scenario
I have a server process implemented in Python and gevent, which is connecting to a backend service over TCP/IP and serving many Web clients (~1000 per process) with fast changing dynamic content based on the changes delivered by the backend service. The service is running on Ubuntu 10.04 and won't run on Windo... | [
"I'd consider custom socket IPC or using ZeroMQ.\n",
"I recommend taking a look at Celery - distributed task processing system written in Python.\nThe basic idea with celery is that you have a queue (either RabbitMQ or Redis), with workers written as Python processes, and exposed via the celeryd daemon. According... | [
2,
1
] | [] | [] | [
"asynchronous",
"gevent",
"linux",
"multiprocessing",
"python"
] | stackoverflow_0005360050_asynchronous_gevent_linux_multiprocessing_python.txt |
Q:
Trying to get Scrapy into a project to run Crawl command
I'm new to Python and Scrapy and I'm walking through the Scrapy tutorial. I've been able to create my project by using DOS interface and typing:
scrapy startproject dmoz
The tutorial later refers to the Crawl command:
scrapy crawl dmoz.org
But each time I ... | Trying to get Scrapy into a project to run Crawl command | I'm new to Python and Scrapy and I'm walking through the Scrapy tutorial. I've been able to create my project by using DOS interface and typing:
scrapy startproject dmoz
The tutorial later refers to the Crawl command:
scrapy crawl dmoz.org
But each time I try to run that I get a message that this is not a legit comma... | [
"You have to execute it in your 'startproject' folder. You will have another commands if it finds your scrapy.cfg file. You can see the diference here: \n$ scrapy startproject bar\n$ cd bar/\n$ ls\nbar scrapy.cfg\n$ scrapy\nScrapy 0.12.0.2536 - project: bar\n\nUsage:\n scrapy <command> [options] [args]\n\nAvailab... | [
9,
2
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0004988297_python_scrapy_web_crawler.txt |
Q:
pyQt equivalent of asyncore/asynchat
Is there an equivalent of asyncore/asynchat in pyQt ?
If not, then i trust there wouldn't be a problem by just using asyncore/asynchat in a client-server GUI application, right?
A:
Yes, QTcpSocket/QTcpServer in QNetwork module can work asynchronously, like most of QNetwork's ... | pyQt equivalent of asyncore/asynchat | Is there an equivalent of asyncore/asynchat in pyQt ?
If not, then i trust there wouldn't be a problem by just using asyncore/asynchat in a client-server GUI application, right?
| [
"Yes, QTcpSocket/QTcpServer in QNetwork module can work asynchronously, like most of QNetwork's classes.\nFrom documentation at http://doc.qt.io/qt-4.8/network-programming.html:\n\nQTcpSocket works asynchronously and emits signals to report status\n changes and errors, just like QNetworkAccessManager and QFtp.\n\n... | [
1
] | [] | [] | [
"pyqt",
"python",
"python_3.x",
"qt"
] | stackoverflow_0006671038_pyqt_python_python_3.x_qt.txt |
Q:
optparse(): Input validation
My apology in advance if it's already answered somewhere; I've been in the python site since last hr. but didn't quite figure out how I can I do this. My script should take the options like this:
myScript.py -f <file-name> -e [/ -d]
myScript.py -s <string> -e [/ -d]
myScript.py -f <fi... | optparse(): Input validation | My apology in advance if it's already answered somewhere; I've been in the python site since last hr. but didn't quite figure out how I can I do this. My script should take the options like this:
myScript.py -f <file-name> -e [/ -d]
myScript.py -s <string> -e [/ -d]
myScript.py -f <file-name> [/ -s <string>] -e -w [<f... | [
"You should try with argparse if you are using 2.7+.\nThis section should be what you want.\nTl;dr: \nparser = argparse.ArgumentParser()\ngroup = parser.add_mutually_exclusive_group()\ngroup.add_argument('--foo', action='store_true')\ngroup.add_argument('--bar', action='store_false')\n\nmakes --foo and --bar mutual... | [
2,
2
] | [] | [] | [
"optparse",
"python",
"validation"
] | stackoverflow_0006669828_optparse_python_validation.txt |
Q:
n-largest elements in a sequence (need to retain duplicates)
I need to find the n largest elements in a list of tuples. Here is an example for top 3 elements.
# I have a list of tuples of the form (category-1, category-2, value)
# For each category-1, ***values are already sorted descending by default***
# The lis... | n-largest elements in a sequence (need to retain duplicates) | I need to find the n largest elements in a list of tuples. Here is an example for top 3 elements.
# I have a list of tuples of the form (category-1, category-2, value)
# For each category-1, ***values are already sorted descending by default***
# The list can potentially be approximately a million elements long.
lot = ... | [
"I take it from your code snippet that lot is grouped w.r.t. category-1. Following should work then:\nfrom itertools import groupby, islice\nfrom operator import itemgetter\n\nans = []\nfor x, g1 in groupby(lot, itemgetter(0)):\n for y, g2 in islice(groupby(g1, itemgetter(2)), 0, 3):\n ans.extend(list(g2)... | [
7,
2,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"heap",
"python",
"sequence",
"sorting"
] | stackoverflow_0006669632_algorithm_heap_python_sequence_sorting.txt |
Q:
Using template.render() without a file reference
Is it possible to use template.render() without a file path?
I'd like to do dynamic string replacemnt for text properties in my datastore. Templating immediately came to mind. Perhaps there is another way? My thought was the following...
my_string = template.render... | Using template.render() without a file reference | Is it possible to use template.render() without a file path?
I'd like to do dynamic string replacemnt for text properties in my datastore. Templating immediately came to mind. Perhaps there is another way? My thought was the following...
my_string = template.render(my_model.description,template_dict)
| [
"Judging from the \"google-app-engine\" tag, I assume you are talking about the templating engine provided with google.appengine.ext.webapp? According to the documentation: \"for your convenience, the webapp module includes Django's templating engine\". So have a look at the Django docs for templates...\nAs far as ... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python",
"template_engine"
] | stackoverflow_0006670341_google_app_engine_python_template_engine.txt |
Q:
Best way to find a tag among an array of tag objects in Django
I'm using django-tagging and I've got an array of tag objects. What's the best way to determine whether a given tag is among them?
def is_new (self):
tags = Tag.objects.get_for_object(self)
tagged = False
for tag in tags:
if tag ... | Best way to find a tag among an array of tag objects in Django | I'm using django-tagging and I've got an array of tag objects. What's the best way to determine whether a given tag is among them?
def is_new (self):
tags = Tag.objects.get_for_object(self)
tagged = False
for tag in tags:
if tag = 'new':
tagged = True
return tagged
| [
"I have never really used django tagging but looking through the source really quickly the .get_for_object returns a queryset of the tags for that object. Not an actual list. \nI'm not sure if your code is working [appart from the assignment/comparison issue] or if you just want to improve it. But Since you are ret... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006670220_django_python.txt |
Q:
Convert date retrieved from ntp server with python
Is it possible to convert time retrieved from NTP server (with python script) in this format "Wed Jul 13 00:17:58 CEST 2011" to this format "2011-07-13 00:18:10"
client = socket(AF_INET, SOCK_DGRAM)
data = '\x1b' + 47 * '\0'
client.sendto(data, (ntp.s... | Convert date retrieved from ntp server with python | Is it possible to convert time retrieved from NTP server (with python script) in this format "Wed Jul 13 00:17:58 CEST 2011" to this format "2011-07-13 00:18:10"
client = socket(AF_INET, SOCK_DGRAM)
data = '\x1b' + 47 * '\0'
client.sendto(data, (ntp.server.com,123))
data, address = client.recvfrom( 102... | [
"In your case you can go directly from the number of seconds to the time format you desire; however I will explain the general solution before the exact snippet for your case at the bottom.\nIn general this type of problem is solved with the help of strptime and strftime. You should also refer to the formatting cod... | [
3,
1
] | [] | [] | [
"date",
"format",
"ntp",
"python"
] | stackoverflow_0006671945_date_format_ntp_python.txt |
Q:
Python CRC-32 woes
I'm writing a Python program to extract data from the middle of a 6 GB bz2 file. A bzip2 file is made up of independently decryptable blocks of data, so I only need to find a block (they are delimited by magic bits), then create a temporary one-block bzip2 file from it in memory, and finally pas... | Python CRC-32 woes | I'm writing a Python program to extract data from the middle of a 6 GB bz2 file. A bzip2 file is made up of independently decryptable blocks of data, so I only need to find a block (they are delimited by magic bits), then create a temporary one-block bzip2 file from it in memory, and finally pass that to the bz2.decomp... | [
"\nhow come crc32(\"\\x00\") is not 0x00000000?\n\nThe basic CRC algorithm is to treat the input message as a polynomial in GF(2), divide by the fixed CRC polynomial, and use the polynomial remainder as the resulting hash.\nCRC-32 makes a number of modifications on the basic algorithm:\n\nThe bits in each byte of t... | [
10,
2
] | [] | [] | [
"bzip2",
"crc32",
"python"
] | stackoverflow_0005047494_bzip2_crc32_python.txt |
Q:
How can I get the correct case when calling Python's os.getcwd()?
When I call os.getcwd() on my Mac under OS X 10.6.4 from my home directory, the path is converted to lowercase. I get
/users/myusername
instead of
/Users/myusername
On another Mac I get the correct uppercase string. How can I configure this? Is the... | How can I get the correct case when calling Python's os.getcwd()? | When I call os.getcwd() on my Mac under OS X 10.6.4 from my home directory, the path is converted to lowercase. I get
/users/myusername
instead of
/Users/myusername
On another Mac I get the correct uppercase string. How can I configure this? Is there a (hidden) Python setting?
Reason for asking:
On OS X all user direc... | [
"The \"HFS plus\" filesystem, which has been Apple's filesystem of choice since the days of Mac OS 8, is normally not case-sensitive.\nMac OS X version 10.4, or \"Tiger\" as it's more commonly known, introduced the ability to create an HFS plus filesystem which is case-sensitive.\nCould one of them be using a case-... | [
2,
0,
0,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0004073469_macos_python.txt |
Q:
How to format a LaTeX string in python?
I'm writing an application, part of whose functionality is to generate LaTeX CVs, so I find myself in a situation where I have strings like
\begin{document}
\title{Papers by AUTHOR}
\author{}
\date{}
\maketitle
\begin{enumerate}
%% LIST OF PAPERS
%% Please comment out a... | How to format a LaTeX string in python? | I'm writing an application, part of whose functionality is to generate LaTeX CVs, so I find myself in a situation where I have strings like
\begin{document}
\title{Papers by AUTHOR}
\author{}
\date{}
\maketitle
\begin{enumerate}
%% LIST OF PAPERS
%% Please comment out anything between here and the
%% first \item... | [
"Why won't this work?\n>>> output = r'\\author{{email}}'.format(email='user@example.org')\n>>> print output\n\\author{email}\n\nedit: Use double curly braces to \"escape\" literal curly braces that only LaTeX understands:\n>>> output = r'\\begin{{document}} ... \\author{{{email}}}'.format(\n... email='user@example.... | [
17,
4
] | [] | [] | [
"format",
"latex",
"python",
"string"
] | stackoverflow_0006672213_format_latex_python_string.txt |
Q:
Python script to extract new data from file since it was last read
I am working on a python script to do the following:-
I would like to read a log file every ten mins and on each read, I would like to extract any added data to the file since it was last read (preferably without having to read the entire log file ... | Python script to extract new data from file since it was last read | I am working on a python script to do the following:-
I would like to read a log file every ten mins and on each read, I would like to extract any added data to the file since it was last read (preferably without having to read the entire log file each time). Example:-
At 09:00 I read the log file and the content is:-... | [
"\ncheck size of file\nwait until size changes\nopen file, seek to previous size\nread\n\nExample:\nimport os, time\nsize = os.stat(file).st_size\ntime.sleep(600)\nfh = open(file)\nfh.seek(size)\nnewData = fh.read()\n\nThis example will, from time to time, read a partial line if another process is writing to the lo... | [
2
] | [] | [] | [
"extraction",
"parsing",
"python"
] | stackoverflow_0006672683_extraction_parsing_python.txt |
Q:
Is a python script aware of its stored location path?
/home/bar/foo/test.py:
I am trying test.py to print /home/bar/foo irrespective of from where I run the script from:
import os
def foo():
print os.getcwd()
test run:
[/home/bar $] python /home/bar/foo/test.py # echoes /home/bar
[/tmp $] python /home/b... | Is a python script aware of its stored location path? | /home/bar/foo/test.py:
I am trying test.py to print /home/bar/foo irrespective of from where I run the script from:
import os
def foo():
print os.getcwd()
test run:
[/home/bar $] python /home/bar/foo/test.py # echoes /home/bar
[/tmp $] python /home/bar/foo/test.py # echoes /tmp
os.getcwd() not t... | [
"Try this:\nimport os.path\np = os.path.abspath(__file__)\n\n",
"The __file__ variable will contain the location of the individual Python file.\n",
"If the script is somewhere in your path, then yes, you can strip it from sys.argv\n#!/usr/bin/env python ... | [
7,
2,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006667460_python.txt |
Q:
Ruby's self vs. Python's self
Possible Duplicate:
What is the difference between Ruby and Python versions of“self”?
Ruby and Python are similar languages that both have a self keyword used in various situations. What does self mean in each language, and what are the differences?
A:
Ruby and Python are actually... | Ruby's self vs. Python's self |
Possible Duplicate:
What is the difference between Ruby and Python versions of“self”?
Ruby and Python are similar languages that both have a self keyword used in various situations. What does self mean in each language, and what are the differences?
| [
"Ruby and Python are actually very different languages (although they do share many similarities) even if Ruby has a syntax that can be written to look like Python (with the inclusion of end keywords) ;-)\nRuby is message-based (it was heavily influenced by SmallTalk-80) and \"messages\" are sent to objects. Ruby s... | [
14,
9,
9
] | [] | [] | [
"keyword",
"python",
"ruby",
"self"
] | stackoverflow_0006671784_keyword_python_ruby_self.txt |
Q:
How does one close a figure or replace a figure without having to manually close each figure in Python/pylab?
I have searched numerous sites, used plots, subplots, some basic animation, and other roundabout ways, but the figure will not close despite using close(), clf(), etc.
I have something like this:
impor... | How does one close a figure or replace a figure without having to manually close each figure in Python/pylab? | I have searched numerous sites, used plots, subplots, some basic animation, and other roundabout ways, but the figure will not close despite using close(), clf(), etc.
I have something like this:
import numpy
from pylab import *
import time
fig = Figure()
counter1 = 0
counter2 = 0
while co... | [
"Two side issues to start: first, are you sure that this is the code you're actually running? sleep isn't a function in my version of pylab, so your import time doesn't seem to match your call, it should be time.sleep(0.5).. Second, I don't understand your loops at all. It looks like you're plotting the same thin... | [
3
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0006672797_matplotlib_plot_python.txt |
Q:
Printing out elements of list into separate text files in python
Im new to python programming and need some help with some basic file I/O and list manipulation.
currently i have a list (s) that has these elements in it:
['taylor343', 'steven435', 'roger101\n']
what i need to do is print each line into new text fi... | Printing out elements of list into separate text files in python | Im new to python programming and need some help with some basic file I/O and list manipulation.
currently i have a list (s) that has these elements in it:
['taylor343', 'steven435', 'roger101\n']
what i need to do is print each line into new text files with only the 1 element in the text files as shown below:
file1.t... | [
"You need to open each new file you want to write into. As a quick example:\nitems = ['taylor', 'steven', 'roger']\nfilenames = ['file1', 'file2', 'file3']\n\nfor item, filename in zip(items, filenames):\n with open(filename, 'w') as output:\n output.write(item + '\\n')\n\n",
"@Joe Kington wrote an exce... | [
6,
2
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0006673092_file_io_python.txt |
Q:
pumping items out to csv file using python scrapy - issue with how outputted in csv file
Having an issue where I want to add output to a csv file but it does not start below the field name it is placed in the next row in sequence as opposed to placing it at row 2 when populating the playerMins item in the csv file... | pumping items out to csv file using python scrapy - issue with how outputted in csv file | Having an issue where I want to add output to a csv file but it does not start below the field name it is placed in the next row in sequence as opposed to placing it at row 2 when populating the playerMins item in the csv file. Can someone please tell me where my code is going wrong?? Here it is:
class EspnSpider3(Base... | [
"Was able to solve my issue, after much googling and rtfm: Trying to Use an ItemExporter in Scrapy\nHere is my working code:\ndef parse(self, response):\n hxs = HtmlXPathSelector(response)\n player_names = hxs.select('(//table[@class=\"mod-data\"][1]/tbody/tr)')\n for p_name in player_names:\n l = X... | [
2
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0006641297_python_scrapy.txt |
Q:
Python permutation difference
Is there something built-in to tell the permutation difference between two list? E.g.
difference("ijk", "ikj") = (0,2,1)
difference("jik", "ikj") = (2,0,1)
etc ...
oops, nevermind, here is a snippet
[a.index(i) for i in b]
A:
Pretty simple...
def difference(after, before):
ret... | Python permutation difference | Is there something built-in to tell the permutation difference between two list? E.g.
difference("ijk", "ikj") = (0,2,1)
difference("jik", "ikj") = (2,0,1)
etc ...
oops, nevermind, here is a snippet
[a.index(i) for i in b]
| [
"Pretty simple...\ndef difference(after, before):\n return tuple(before.index(x) for x in after)\n\nprint difference('ijk', 'ikj') # (0, 2, 1)\nprint difference('jik', 'ikj') # (2, 0, 1)\n\n",
"Is this short enough?\ntuple([s2.index(p) for p in s1])\n\n"
] | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0006673180_python.txt |
Q:
Django queryset ordering by _set
I've this models:
class Person(models.Model):
name = models.CharField()
likes = models.ManyToManyField(Image)
class Image(models.Model):
name = ...
image = ...
If I use [x.person_set.count() for x in Image.objects.all()] I get how many people likes every image.
No... | Django queryset ordering by _set | I've this models:
class Person(models.Model):
name = models.CharField()
likes = models.ManyToManyField(Image)
class Image(models.Model):
name = ...
image = ...
If I use [x.person_set.count() for x in Image.objects.all()] I get how many people likes every image.
Now I need to order the list. I want som... | [
"This does everything you want (# of likes, and order by count) in one query.\nfrom django.db.models import Count\nImage.objects.annotate(Count(\"person\")).order_by(\"person__count\")\n\n"
] | [
1
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0006673303_django_django_queryset_python.txt |
Q:
How can I rename the field names of a .dbf file when reading it with dbfpy?
I am using dbfpy to read from a .dbf file, which works great. However, I want to rename the field names, such that when I read each row using row.asDict(), the dict keys will be my field names and not the ones from the file. I can write ... | How can I rename the field names of a .dbf file when reading it with dbfpy? | I am using dbfpy to read from a .dbf file, which works great. However, I want to rename the field names, such that when I read each row using row.asDict(), the dict keys will be my field names and not the ones from the file. I can write my own wrapper for this, of course, but I didn't want to reinvent the wheel in ca... | [
"I have never used dbfpy, but using the package I wrote it would be like this:\nimport dbf\nsome_table = dbf.Table('dbf_file')\nsome_table.rename_field('oldname', 'newname')\n\nThis will, however, actually change the name in the original dbf file.\nEdit\nI remembered another way: this way doesn't actually rename an... | [
2
] | [] | [] | [
"dbf",
"python"
] | stackoverflow_0006364984_dbf_python.txt |
Q:
Does anyone know the attributes of a Google Analytics DataPoint object?
I'm currently trying to pull GA data using Python; I've gotten as far as retrieving a list of DataPoint objects, and I can see inside them using .list, but I can't access their values directly.
For example, I've got this
>>> print(data.list)
[... | Does anyone know the attributes of a Google Analytics DataPoint object? | I'm currently trying to pull GA data using Python; I've gotten as far as retrieving a list of DataPoint objects, and I can see inside them using .list, but I can't access their values directly.
For example, I've got this
>>> print(data.list)
[[[u'Android Browser'], [80]], [[u'Chrome'], [127]], [[u'Firefox'], [78]], [[u... | [
"There's a page at the documentation explaining each field.\nhttp://code.google.com/apis/analytics/docs/gdata/gdataReferenceDataFeed.html#dataResponse\n",
"I figured it out: I was able to crack open the object using the inspect module, and that told me that the attributes were accessible using the same names I us... | [
1,
0
] | [] | [] | [
"api",
"google_analytics",
"python"
] | stackoverflow_0006645352_api_google_analytics_python.txt |
Q:
How to get a functions arguments and values from outside the function?
I have searched a little bit to try to figure this one out but didn't get a solution that I was exactly looking for.
This is my use case:
I would like to evaluate expressions from a functions/methods doc-string against the f/m's parameters and... | How to get a functions arguments and values from outside the function? | I have searched a little bit to try to figure this one out but didn't get a solution that I was exactly looking for.
This is my use case:
I would like to evaluate expressions from a functions/methods doc-string against the f/m's parameters and values, but from outside the function (when being called but outside execut... | [
"While I have no clue why you would want to do this, what you've described can be achieved with the inspect module. This example is as close to your original example that I can come up with.\nfrom inspect import getcallargs\ndef f1(a,b):\n \"\"\"a==b\"\"\"\n pass\n\ndef f2(f, *f_args, **f_kwargs):\n f_callar... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0005668480_python.txt |
Q:
In NLTK, how do I get the concordance of a text?
>>> c = t.concordance('president')
Displaying 25 of 142 matches:
of Hays , Kan. as the school's new president . Dr. Clark will succeed Dr. J. R.
dollars , said C. Virgil Martin , president of Carson Pirie Scott & Co. , comm
dants '' . Washington , July 24 -- presid... | In NLTK, how do I get the concordance of a text? | >>> c = t.concordance('president')
Displaying 25 of 142 matches:
of Hays , Kan. as the school's new president . Dr. Clark will succeed Dr. J. R.
dollars , said C. Virgil Martin , president of Carson Pirie Scott & Co. , comm
dants '' . Washington , July 24 -- president Kennedy today pushed aside other W
ionwide televis... | [
"The code you're calling is in nltk/nltk/text.py, and looks like:\n if '_concordance_index' not in self.__dict__:\n print \"Building index...\"\n self._concordance_index = ConcordanceIndex(self.tokens,\n key=lambda s:s.lower())\n\n self._concorda... | [
5
] | [] | [] | [
"nltk",
"python"
] | stackoverflow_0006673304_nltk_python.txt |
Q:
Storing strings somewhere then writing out at once
I read that file I/O is slow and was looking at my own code that wrote to a file and found that I'm constantly calling write write write everywhere even for little things like a comma.
outFile.write(",")
So I figured maybe it'd be better if I stored all my chara... | Storing strings somewhere then writing out at once | I read that file I/O is slow and was looking at my own code that wrote to a file and found that I'm constantly calling write write write everywhere even for little things like a comma.
outFile.write(",")
So I figured maybe it'd be better if I stored all my characters somewhere (like, I don't know, 1 KB of characters ... | [
"Take a look at the io module's documentation for information on buffered I/O. As S.Lott pointed out, there is already a buffer built into much of Python's built-in I/O objects, so you probably are already using it without your knowledge.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006673606_python.txt |
Q:
cannot set initial value for forms.ChoiceField in django
everyone
I want to set initial value for ChoiceField while that value isn't in choices of ChoiceField
following is the ArticleForm definition:
def ArticleForm(forms.Form):
choice = forms.ChoiceField(choices=[['a':'a'],['b':'b']])
then I instantiated the f... | cannot set initial value for forms.ChoiceField in django | everyone
I want to set initial value for ChoiceField while that value isn't in choices of ChoiceField
following is the ArticleForm definition:
def ArticleForm(forms.Form):
choice = forms.ChoiceField(choices=[['a':'a'],['b':'b']])
then I instantiated the form by passing the initial argument:
form = ArticleForm(initia... | [
"May be something like this:\nclass ArticleForm(forms.Form):\n LETTER_A = 'a'\n LETTER_B = 'b'\n # look not a dict\n CHOICES = ((LETTER_A,'letter a'),\n (LETTER_B,'letter b'))\n\n choice = forms.ChoiceField(choices=CHOICES)\n\n def __init__(self, *args, **kwargs):\n initial = ... | [
6
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006673308_django_django_forms_python.txt |
Q:
inconsistent indentation with Python after split
edit in progress will re-submit sometimes later
edit in progress will re-submit sometimes later
edit in progress will re-submit sometimes later
A:
You can use .strip() to remove any whitespace around an item before entering it. This would allow a bit more clarity ... | inconsistent indentation with Python after split | edit in progress will re-submit sometimes later
edit in progress will re-submit sometimes later
edit in progress will re-submit sometimes later
| [
"You can use .strip() to remove any whitespace around an item before entering it. This would allow a bit more clarity and solve any indentation issues.\nFor example:\nb=a.split('chr').strip() # No white space either side now\nc=b[1].split(':').strip() # No white space\nd=c[1].split('..').strip()\ne=b[0]+'\\t'+c[0]+... | [
0,
0,
0
] | [] | [] | [
"indentation",
"mysql",
"python",
"split",
"warnings"
] | stackoverflow_0006673917_indentation_mysql_python_split_warnings.txt |
Q:
How to define a dynamic two-dimensional array in python?
I want to define a dynamic two-dimensional array in python.
I don't know how many rows my two-dimensional array will have at the start of my program. I would like to define new rows in this 2D array as needed.
As like this code:
array = [][100]
array[0][] =... | How to define a dynamic two-dimensional array in python? | I want to define a dynamic two-dimensional array in python.
I don't know how many rows my two-dimensional array will have at the start of my program. I would like to define new rows in this 2D array as needed.
As like this code:
array = [][100]
array[0][] = new array()
array[0][2] = 'hello'
array[1][] = new array()
a... | [
"Do you mean something like the following?\nclass DynamicList(list):\n\n def __getslice__(self, i, j):\n return self.__getitem__(slice(i, j))\n def __setslice__(self, i, j, seq):\n return self.__setitem__(slice(i, j), seq)\n def __delslice__(self, i, j):\n return self.__delitem__(slice... | [
6,
4
] | [] | [] | [
"arrays",
"dynamic_arrays",
"python"
] | stackoverflow_0006673006_arrays_dynamic_arrays_python.txt |
Q:
URL recorder in python
i'm trying to make a FF URL recorder in python. What this plugin will do is whenever user writes a URL and hit enter it will record that url in a file. I've tried building this in win32gui but it did not work. Then tried using XPCOM but can't able to do it cause there is no good easily under... | URL recorder in python | i'm trying to make a FF URL recorder in python. What this plugin will do is whenever user writes a URL and hit enter it will record that url in a file. I've tried building this in win32gui but it did not work. Then tried using XPCOM but can't able to do it cause there is no good easily understandable tutorial for it ou... | [
"Why do you want it to be done in Python?\nYou can read this article of how to How to create Firefox extensions. It's not Python, but it might help you get the job done.\n"
] | [
2
] | [] | [] | [
"firefox",
"python"
] | stackoverflow_0006674124_firefox_python.txt |
Q:
Python-memcache connection timeout
How do I reduce the connection timeout for python-memcache?
When a machine in my cluster goes down, the healthy machines hang for too long trying to connect to it.
Is settimeout the only way?
A:
After adjusting time out, also adjust number of retries per server before purging ... | Python-memcache connection timeout | How do I reduce the connection timeout for python-memcache?
When a machine in my cluster goes down, the healthy machines hang for too long trying to connect to it.
Is settimeout the only way?
| [
"After adjusting time out, also adjust number of retries per server before purging it from the pool.\n"
] | [
0
] | [] | [] | [
"memcached",
"python",
"timeout"
] | stackoverflow_0006621127_memcached_python_timeout.txt |
Q:
Problem using greenlet to execute multiple functions simultaneously
The following script has the purpose of execute many functions simultaneously, but i don't have idea why it's not working correctly.
The functions are executed in sequential way, not parallel.
I would appreciate any suggestion to clarify me, about... | Problem using greenlet to execute multiple functions simultaneously | The following script has the purpose of execute many functions simultaneously, but i don't have idea why it's not working correctly.
The functions are executed in sequential way, not parallel.
I would appreciate any suggestion to clarify me, about what i'm doing wrong.
import time
import eventlet
EXECUTION_TIMEOUT = ... | [
"You're right about time.sleep() being the culprit.\nBut you don't have to replace time.sleep() with eventlet.sleep(). Instead, you can monkey patch time.sleep to become eventlet.sleep.\nThis is, in fact, preferred, because that way the libraries that you did not know use time.sleep also get fixed whereas if you fi... | [
2
] | [] | [] | [
"coroutine",
"multithreading",
"python"
] | stackoverflow_0006671790_coroutine_multithreading_python.txt |
Q:
Python 2.7: how to read only a few lines at a time from a file?
For example, I have 2,000 lines in a file, and I want to read 500 lines at a time and do something with these 500 lines before reading another 500 lines. I wonder if anyone would write some quick code for me to learn. Thanks!
A:
You could use a gene... | Python 2.7: how to read only a few lines at a time from a file? | For example, I have 2,000 lines in a file, and I want to read 500 lines at a time and do something with these 500 lines before reading another 500 lines. I wonder if anyone would write some quick code for me to learn. Thanks!
| [
"You could use a generator to group the lines together, and yield them in a way that is convenient to use in a simple for loop. This might get you started:\ndef chunks_of(iterable, chunk_size=500):\n out = []\n for item in iterable:\n out.append(item)\n if len(out) >= chunk_size:\n yi... | [
7,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0006673129_file_python.txt |
Q:
How to convert a python c extension into a pure python ctypes module
Does anyone have any experience porting python c extensions to a pure python ctypes module ? I would like to transition over to ironpython but want to start translating some c extensions or atleast parts of pywin32. What are some things to be aw... | How to convert a python c extension into a pure python ctypes module | Does anyone have any experience porting python c extensions to a pure python ctypes module ? I would like to transition over to ironpython but want to start translating some c extensions or atleast parts of pywin32. What are some things to be aware of before starting ?
| [
"ctypesgen seems interesting: \nthis post analyzes use of ctypesgen vs pycparser for generating ctypes bindings to sdl.\n"
] | [
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0006674051_ctypes_python.txt |
Q:
Modifying text documents with python
Let's say I had a .txt document with 1,000 names in it.
The document would look like this:
Jon
Jane
Joe
Jack
Jeremy
and, so on.
Now, let's say, I wanted to append "is lame." to each of the names.
So, I'd want the list to look like this:
Jon is lame.
Jane is lame.
Joe is lame.
J... | Modifying text documents with python | Let's say I had a .txt document with 1,000 names in it.
The document would look like this:
Jon
Jane
Joe
Jack
Jeremy
and, so on.
Now, let's say, I wanted to append "is lame." to each of the names.
So, I'd want the list to look like this:
Jon is lame.
Jane is lame.
Joe is lame.
Jack is lame.
Jeremy is lame.
and, so on.
H... | [
"See http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files.\nIn a nutshell:\nf = open('my_names_file.txt')\ndata = f.read()\nf.close()\noutput = \"\"\nfor name in data.split(' '): # This assumes each name is separated \n output += name + \" is lame. \" # by a space and no name contain... | [
3,
1,
0,
0,
0
] | [] | [] | [
"append",
"file",
"python",
"text"
] | stackoverflow_0006671852_append_file_python_text.txt |
Q:
Method for indexing an object database
I'm using an object database (ZODB) in order to store complex relationships between many objects but am running into performance issues. As a result I started to construct indexes in order to speed up object retrieval and insertion. Here is my story and I hope that you can h... | Method for indexing an object database | I'm using an object database (ZODB) in order to store complex relationships between many objects but am running into performance issues. As a result I started to construct indexes in order to speed up object retrieval and insertion. Here is my story and I hope that you can help.
Initially when I would add an object to... | [
"Yes, repoze.catalog is nice, and well documented.\nIn short : don't make indexing part of your site structure!\n\nLook at using a container/item hierarchy to store and traverse content item objects; plan to be able to traverse content by either (a) path (graph edges look like a filesystem) or (b) by identifying si... | [
8,
0
] | [] | [] | [
"indexing",
"object_oriented_database",
"python",
"zodb"
] | stackoverflow_0006668234_indexing_object_oriented_database_python_zodb.txt |
Q:
problem redirecting stdout of C functions when imported in python
I wrote a simple C module which prints to stdout using printf.
// sample.c
func_print()
{
printf("Hello World!\n");
}
Later, I made a wrapper around this using SWIG so that I could use func_print in my python program too. In this program, I hav... | problem redirecting stdout of C functions when imported in python | I wrote a simple C module which prints to stdout using printf.
// sample.c
func_print()
{
printf("Hello World!\n");
}
Later, I made a wrapper around this using SWIG so that I could use func_print in my python program too. In this program, I have redirected the stdout to a textctrl widget. Anything I print using pr... | [
"Your problem is that sys.stdout is a Python object, not an actual C stream or file descriptor. From the sys.stdout documentation:\n\n(Changing these objects doesn’t affect the standard I/O streams of\n processes executed by os.popen(), os.system() or the exec*() family of\n functions in the os module.)\n\nYour ... | [
5
] | [] | [] | [
"c",
"python",
"python_c_extension",
"swig"
] | stackoverflow_0006654955_c_python_python_c_extension_swig.txt |
Q:
Standardized python binary location?
On a native Mac OS X install, I see Python binary at /usr/bin at version 2.6
Recently I installed Python 2.7.2 from the official binaries and it installed it at /usr/local/bin
What path of the Python interpreter should I give in my #! which will be standardized across all platf... | Standardized python binary location? | On a native Mac OS X install, I see Python binary at /usr/bin at version 2.6
Recently I installed Python 2.7.2 from the official binaries and it installed it at /usr/local/bin
What path of the Python interpreter should I give in my #! which will be standardized across all platforms?
I am assuming it could be /usr/bin s... | [
"Nope. You would use env to find the python executable in $PATH and run it as appropriate.\n#!/usr/bin/env python\n\nprint 'Hi mom!'\n\n",
"On Mac OS X, do not modify anything in /usr (including /usr/bin) other than /usr/local, nor anything in /System/Library. Those directory spaces are managed by Apple as part ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006674401_python.txt |
Q:
Python Calculator Divide by Zero/Sqrting a Neg. Int. crashing program
Alright, I'm doing this for a project and whenever I attempt to have it divide by zero or square root a negative number that program closes out. I've attempted to find something I can insert into the code to make it display a message and then pr... | Python Calculator Divide by Zero/Sqrting a Neg. Int. crashing program | Alright, I'm doing this for a project and whenever I attempt to have it divide by zero or square root a negative number that program closes out. I've attempted to find something I can insert into the code to make it display a message and then prompt for the value again, but everything that I've tried inserting causes t... | [
"The problem is that you are trying to catch an exception before it is thrown. Instead, try this:\nelif choice == \"4\":\n numberA = raw_input(\"Enter your dividend: \")\n numberB = raw_input(\"Enter your divisor: \")\n while float(numberB) == 0:\n print \"You cannot divide by zero. Please choose an... | [
3,
2,
1,
0,
0
] | [] | [] | [
"calculator",
"negative_number",
"python"
] | stackoverflow_0006673247_calculator_negative_number_python.txt |
Q:
Python - finding date in a string
I want to be able to read a string and return the first date appears in it. Is there a ready module that I can use? I tried to write regexs for all possible date format, but it is quite long. Is there a better way to do it?
A:
You can run a date parser on all subtexts of your te... | Python - finding date in a string | I want to be able to read a string and return the first date appears in it. Is there a ready module that I can use? I tried to write regexs for all possible date format, but it is quite long. Is there a better way to do it?
| [
"You can run a date parser on all subtexts of your text and pick the first date. Of course, such solution would either catch things that are not dates or would not catch things that are, or most likely both.\nLet me provide an example that uses dateutil.parser to catch anything that looks like a date:\nimport dateu... | [
15,
2,
2,
0,
0
] | [] | [] | [
"date",
"python",
"string"
] | stackoverflow_0006562148_date_python_string.txt |
Q:
Python While Loop Issue
I'm blanking here. I want to grab all the users from the userbase, but then only loop through 10 of them (I'm leaving out code that would explain why I wouldn't just grab 10 users from the db in the first place).
users = User.objects.all()
i = 0
while i < 10:
for user in users:
... | Python While Loop Issue | I'm blanking here. I want to grab all the users from the userbase, but then only loop through 10 of them (I'm leaving out code that would explain why I wouldn't just grab 10 users from the db in the first place).
users = User.objects.all()
i = 0
while i < 10:
for user in users:
if user.is_active:
... | [
"If you want to look for 10 active users, you're going to need to be a bit more clever.\nfor user in itertools.islice((x for x in users if x.is_active), 10):\n # do something\n\n",
"Actually, it's not endless, it just runs through all users 10 times.\nIf you want the first 10 users (regardless if they're active ... | [
8,
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006674958_django_python.txt |
Q:
Modifying the foreign key of an existing model in the Django ORM
I have a model which has a ForeignKey field, and I wish to change its value in a model instance, I tried something like this:
#object and user are model instances, owner is a FK field
object.owner = user
This raises a ValueError : "object.owner is n... | Modifying the foreign key of an existing model in the Django ORM | I have a model which has a ForeignKey field, and I wish to change its value in a model instance, I tried something like this:
#object and user are model instances, owner is a FK field
object.owner = user
This raises a ValueError : "object.owner is not an instance of User"
Is there a workaround for this?
| [
"user should be a correct instance of User, and if you just created it instead of retrieved it from the database, it should be save()-d before you save object.\n",
"Make sure that user is an instance of the same User that was used in defining the ForeignKey.\n"
] | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006675259_django_django_models_python.txt |
Q:
PyPy C/API access
I've been looking through the reference docs and can't find any mention of a C API for PyPy. Does it exist? If so is it the same as the CPython C API? If PyPy was run on top of CPython would it change this?
A:
PyPy has alpha-level support for the CPython extension API via an emulation layer cal... | PyPy C/API access | I've been looking through the reference docs and can't find any mention of a C API for PyPy. Does it exist? If so is it the same as the CPython C API? If PyPy was run on top of CPython would it change this?
| [
"PyPy has alpha-level support for the CPython extension API via an emulation layer called CPyExt. Here's a blog post introducing the support; here's a later one discussing it. If your goal is to interface with a C library, you're probably best off just writing a Python wrapper module that uses ctypes to call into... | [
3
] | [] | [] | [
"api",
"pypy",
"python"
] | stackoverflow_0006675138_api_pypy_python.txt |
Q:
google app engine dev app server do not allow to change datastore file path
try 1 with sqlite and datastore path option
WARNING 2011-07-13 05:01:06,169 datastore_file_stub.py:511] Could not read datastore data from /home/gopal/temp.sqldb
INFO 2011-07-13 05:01:06,170 rdbms_sqlite.py:58] Connecting to SQLite da... | google app engine dev app server do not allow to change datastore file path | try 1 with sqlite and datastore path option
WARNING 2011-07-13 05:01:06,169 datastore_file_stub.py:511] Could not read datastore data from /home/gopal/temp.sqldb
INFO 2011-07-13 05:01:06,170 rdbms_sqlite.py:58] Connecting to SQLite database '' with file '/tmp/dev_appserver.rdbms'
try 2 with clear datastore and pa... | [
"/tmp/dev_appserver.rdbms is default location of your datastore file in linux.Whenever you restart your machine, /tmp/ directory is cleaned. That's why you cannot see your old datas.\nChange the datastore path to someother location other than tmp/ that should sove the issue.\ndev_appserver.py --datastore_path=/tmp/... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python",
"ubuntu"
] | stackoverflow_0006674335_google_app_engine_python_ubuntu.txt |
Q:
Going from .py to .exe
Alright, relevant information can be found in this thread(Is that what they're called here?).
Python Calculator Divide by Zero/Sqrting a Neg. Int. crashing program
Sorry if I should have just kept it to that thread, I'm unfamiliar with the etiquette here and was also unsure if it would be se... | Going from .py to .exe | Alright, relevant information can be found in this thread(Is that what they're called here?).
Python Calculator Divide by Zero/Sqrting a Neg. Int. crashing program
Sorry if I should have just kept it to that thread, I'm unfamiliar with the etiquette here and was also unsure if it would be seen.
Anyway, I've made some c... | [
"As you have mentioned other questons and outdated tools (I assume you mean py2exe, last update from 2008), have a look at PyInstaller and its documentation.\nAnother tool would be cx_freeze.\n",
"Py2exe always worked for me. I had made an exe out of a script using PIL, and it worked without problems. The documen... | [
6,
1
] | [] | [] | [
"compiler_construction",
"executable",
"python"
] | stackoverflow_0006675593_compiler_construction_executable_python.txt |
Q:
Does zc.buildout offer a lot more than pip when dealing with packages/eggs
We're all development team working on a Django site. Recently we've begun using zc.buildout inside a virtualenv. I can see how virtualenv helps you by making a sandboxed environment. After creating a sandbox, one can simply use pip to insta... | Does zc.buildout offer a lot more than pip when dealing with packages/eggs | We're all development team working on a Django site. Recently we've begun using zc.buildout inside a virtualenv. I can see how virtualenv helps you by making a sandboxed environment. After creating a sandbox, one can simply use pip to install the necessary packages/eggs. I've read that pip can load all the eggs from a ... | [
"Buildout does much more than pip; each part is a separate recipe which can run arbitrary python code to get your tasks accomplished. Coupled with dependencies between the parts and update detection, zc.buildout is more comparable to make than to pip.\nFor example, using the zc.recipe.cmmi recipe, you can download ... | [
7
] | [] | [] | [
"buildout",
"django",
"egg",
"pip",
"python"
] | stackoverflow_0006674946_buildout_django_egg_pip_python.txt |
Q:
Get each partition information with Python
How do you get all partitions and their info (total space, free space etc.) with Python on Windows?
Thi example shows how to get free space, but you must know partitions/folders... I would like to get info for all partitions (maybe except CD-ROMs).
A:
Check out the WMI ... | Get each partition information with Python | How do you get all partitions and their info (total space, free space etc.) with Python on Windows?
Thi example shows how to get free space, but you must know partitions/folders... I would like to get info for all partitions (maybe except CD-ROMs).
| [
"Check out the WMI module. There are many recipes in the WMI cookbook, including \n\nFind Drive Types\nShow the percentage free space for each fixed disk\nShow disk partitions\n\n"
] | [
1
] | [] | [] | [
"diskspace",
"python",
"windows"
] | stackoverflow_0006675556_diskspace_python_windows.txt |
Q:
How to introspectively connect handlers to signals?
gtk.Builder is capable to identify all signals that a GUI (described in a XML file) can emit and with the method connect_signals() automagically matches signals and handlers. Example:
class Gui(gobject.GObject):
def __init__(self):
self.gui_file = ".... | How to introspectively connect handlers to signals? | gtk.Builder is capable to identify all signals that a GUI (described in a XML file) can emit and with the method connect_signals() automagically matches signals and handlers. Example:
class Gui(gobject.GObject):
def __init__(self):
self.gui_file = "../data/gui.xml"
builder = gtk.Builder()
b... | [
"GtkBuilder takes the names to connect to from the XML, it does not search for methods starting with 'on'. This means your model needs to be represented in the XML, there is no way to pass GtkBuilder a widget you instantiated in code. Glade has documentation on custom widgets.\n"
] | [
2
] | [] | [] | [
"gtk",
"introspection",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0006487677_gtk_introspection_pygtk_python_user_interface.txt |
Q:
Languages without built-in support for constants
Why does neither Perl nor Python have support for constants? Is it just considered a marginal feature that just no one meant to implement, or is there maybe something more behind it?
A:
Python doesn't support constants because the idea is against its philosophy: w... | Languages without built-in support for constants | Why does neither Perl nor Python have support for constants? Is it just considered a marginal feature that just no one meant to implement, or is there maybe something more behind it?
| [
"Python doesn't support constants because the idea is against its philosophy: we're all consenting adults here. That is, Python doesn't forbid changing things through the software; instead, it merely indicates that you shouldn't change things and may stop working if you do. \nTo indicate a constant in a Python scri... | [
6,
1,
0
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0006675922_perl_python.txt |
Q:
How to run gtk.Builder.connect_signals multiple times?
This is a follow-up question to this other one.
I am trying to extend gtk.Builder but I found out that once the builder is instantiated one can only call the connect_signals method once: if called more than once, any call after the second will return None (wh... | How to run gtk.Builder.connect_signals multiple times? | This is a follow-up question to this other one.
I am trying to extend gtk.Builder but I found out that once the builder is instantiated one can only call the connect_signals method once: if called more than once, any call after the second will return None (which would mean: all signals have been connected, which is a ... | [
"That connect_signals only works once is an old but undocumented limitation of the GtkBuilder C code. Especially from Python there is no way to access its internals to remedy that.\nInstead of the builder you could pass around a dictionary. After everyone added their handlers you call connect_signals with it.\n"
] | [
1
] | [
"i think if you want to call connect_signals multiple times you must disconnect inbetween, kindof like\nx = self.menu.connect('activate', self.func1)\nself.menu.disconnect(x)\nx = self.menu.connect('activate', self.func2)\n\n"
] | [
-1
] | [
"glade",
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0006492000_glade_gtk_pygtk_python_user_interface.txt |
Q:
Generating images at runtime with Python
Long story short...I have a base64 encoded string that I retrieve from a database. I need to output an image from the encoded data but without saving the file. Is it possible to output the image through a python script? (by changing the header or something like that)?
A:
... | Generating images at runtime with Python | Long story short...I have a base64 encoded string that I retrieve from a database. I need to output an image from the encoded data but without saving the file. Is it possible to output the image through a python script? (by changing the header or something like that)?
| [
"import urllib\n\nuri = 'data:image/jpg;base64,' + urllib.quote(raw_data)\n return(or print depending what you're using - anyway, render to html) '<img src=\"'+uri+'\"/>'\n\nnot entirely cross-browser, IE not working, raw data needs to be base64 encoded\n\n",
"Have a look at the Tkinter PhotoImage Class. It ca... | [
1,
0,
0
] | [] | [] | [
"image",
"python",
"runtime"
] | stackoverflow_0006662734_image_python_runtime.txt |
Q:
How to change the file name runtime
I have imported a file using the below command
code='IN'
exec "import %s_tmp_file" % code
Now i want to use this same imported file for other operations. How to give the file name in that case?
str = code_tmp_file.dict # this does not work.
A:
Use the __import__ builtin inste... | How to change the file name runtime | I have imported a file using the below command
code='IN'
exec "import %s_tmp_file" % code
Now i want to use this same imported file for other operations. How to give the file name in that case?
str = code_tmp_file.dict # this does not work.
| [
"Use the __import__ builtin instead of exec:\nmy_module = __import__(\"%s_tmp_file\" % code)\nstr = my_module.dict\n\nSee this page or help(__import__) for more information.\n",
"Use __import__ (docs).\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006676618_python.txt |
Q:
A simple IF statement in python
I'm having trouble getting an "Else" statement to work.
My code looks like this so far:
roomNumber = (input("Enter the room number: "))
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['... | A simple IF statement in python | I'm having trouble getting an "Else" statement to work.
My code looks like this so far:
roomNumber = (input("Enter the room number: "))
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",... | [
"Python blocks are delineated by indentation so the \"else:\" (note lowercase and with a colon to indicate the start of a block) should be at the same indent level as the if statement.\ndef find_details(id2find):\n rb_text = open('roombookings2.txt', 'r')\n for line in rb_text:\n s = {}\n (s['Da... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006676595_python.txt |
Q:
UnitTesting the webapp.RequestHandler in GAE - Python
I'm struggling on how to setup my environment for TDD with Google App Engine - Python. (I'm also pretty new to Python). My environment is as follows:
Google App Engine 1.5.0
IntelliJ 10.2
IntelliJ setup to use Python 2.5.4 for this project
I am using IntelliJ... | UnitTesting the webapp.RequestHandler in GAE - Python | I'm struggling on how to setup my environment for TDD with Google App Engine - Python. (I'm also pretty new to Python). My environment is as follows:
Google App Engine 1.5.0
IntelliJ 10.2
IntelliJ setup to use Python 2.5.4 for this project
I am using IntelliJ with the Python plugin, so running unittests is as simple ... | [
"I found that I needed a slightly-modified version of Nick Johnson's code:\nrequest = webapp.Request({\n \"wsgi.input\": StringIO.StringIO(),\n \"CONTENT_LENGTH\": 0,\n \"METHOD\": \"GET\",\n \"PATH_INFO\": \"/\",\n})\nresponse = webapp.Response()\nhandler = MainHandler()\nhandler.initialize(request, re... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python",
"unit_testing"
] | stackoverflow_0006222528_google_app_engine_python_unit_testing.txt |
Q:
What does dry-run do in optparse Python?
What's the functionality of the dry-run option in the optparse module of Python?
A:
Dry run is a generic expression in many fields, including computing, meaning that a certain operation should be performed or simulated limiting its dangerous effects.
It is up to you to as... | What does dry-run do in optparse Python? | What's the functionality of the dry-run option in the optparse module of Python?
| [
"Dry run is a generic expression in many fields, including computing, meaning that a certain operation should be performed or simulated limiting its dangerous effects.\nIt is up to you to associate that option to something meaningful in your code. For example: if your script normally removes files from the hard dri... | [
4,
3
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0006676946_optparse_python.txt |
Q:
Python memory leak while populating a list - how to fix it?
I have a piece of code that looks like this:
downloadsByExtensionCount = defaultdict(int)
downloadsByExtensionList = []
logFiles = ['file1.log', 'file2.log', 'file3.log', 'file4.log']
for logFile in logFiles:
log = open(logFile, 'r', encoding='utf-8'... | Python memory leak while populating a list - how to fix it? | I have a piece of code that looks like this:
downloadsByExtensionCount = defaultdict(int)
downloadsByExtensionList = []
logFiles = ['file1.log', 'file2.log', 'file3.log', 'file4.log']
for logFile in logFiles:
log = open(logFile, 'r', encoding='utf-8')
logLines = log.readlines()
for logLine in logLines:
... | [
"log.readlines() reads the file contents into a list of lines. You can iterate over the file directly to avoid that extra list.\ndownloadsByExtensionCount = defaultdict(int)\ndownloadsByExtensionList = []\nlogFiles = ['file1.log', 'file2.log', 'file3.log', 'file4.log']\n\n\nfor logFile in logFiles:\n # closes th... | [
6,
2,
1
] | [] | [] | [
"list",
"memory_leaks",
"python"
] | stackoverflow_0006677016_list_memory_leaks_python.txt |
Q:
Using MacPython with MacPorts
I've installed MacPython 2.7 from python.org. How to set it as default in MacPorts?
PS: #port select offers variants: '
none(active)
python2.5-apple
python2.6-apple
A:
I think MacPorts is not aware of MacPython, and therefore your best bet would be to install python 2.7 from the po... | Using MacPython with MacPorts | I've installed MacPython 2.7 from python.org. How to set it as default in MacPorts?
PS: #port select offers variants: '
none(active)
python2.5-apple
python2.6-apple
| [
"I think MacPorts is not aware of MacPython, and therefore your best bet would be to install python 2.7 from the ports. That way you'll be able to select python 2.7 as default.\nAnother advantage of using python from MacPorts is that if you install ports that require python, MacPorts won't have to install python 2.... | [
1
] | [] | [] | [
"macports",
"python"
] | stackoverflow_0006676772_macports_python.txt |
Q:
Class decorators vs function decorators
In python there are two ways to declare decorators:
Class based
class mydecorator(object):
def __init__(self, f):
self.f = f
def __call__(self, *k, **kw):
# before f actions
self.f(*k, **kw)
# after f actions
Function based
def mydec... | Class decorators vs function decorators | In python there are two ways to declare decorators:
Class based
class mydecorator(object):
def __init__(self, f):
self.f = f
def __call__(self, *k, **kw):
# before f actions
self.f(*k, **kw)
# after f actions
Function based
def mydecorator(f):
def decorator(*k, **kw):
... | [
"If you want to keep state in the decorator you should use a class. \nFor example, this does not work\ndef mydecorator(f):\n x = 0 \n def decorator():\n x += 1 # x is a nonlocal name and cant be modified\n return f(x)\n return decorator \n\nThere are many workarounds for this but the simplest... | [
20,
20,
6,
2,
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0006676015_decorator_python.txt |
Q:
doxygen chokes on __init__.py files
I'm attempting to document a python module with Doxygen - however it seems that the existence of the __init__.py files is causing problems
Currently the __init__.py files are empty (I have tried added comments inside it like
## Nothing here
but with no success). Module namespac... | doxygen chokes on __init__.py files | I'm attempting to document a python module with Doxygen - however it seems that the existence of the __init__.py files is causing problems
Currently the __init__.py files are empty (I have tried added comments inside it like
## Nothing here
but with no success). Module namespaces are not resolved on the Doxygen side -... | [
"I have had exactly the same problem, I found the issue was with the naming of the package. The name given needs to be fully qualified. Otherwise you are creating documentation for a new package, in this case with the name stuff, but your class will be in an undocumented package, which unless you have EXTRACT_ALL s... | [
2
] | [] | [] | [
"doxygen",
"python"
] | stackoverflow_0006654951_doxygen_python.txt |
Q:
Python OrderedDict ordered by date
I am trying to use an OrderedDict (Raymond Hettingers version for pre2.7 Python) where my keys are dates. However it does not order them correctly, I imagine it may be ordering based on the ID.
Does anyone have any suggestions of how this could be done?
A:
In [1]: from collecti... | Python OrderedDict ordered by date | I am trying to use an OrderedDict (Raymond Hettingers version for pre2.7 Python) where my keys are dates. However it does not order them correctly, I imagine it may be ordering based on the ID.
Does anyone have any suggestions of how this could be done?
| [
"In [1]: from collections import OrderedDict\n\nIn [2]: import operator\n\nIn [3]: from datetime import date\n\nIn [4]: d = {date(2012, 1, 1): 123, date(2010,2,5): 542, date(2011,3,3):76 }\n\nIn [5]: d # Good old dict\nOut[5]: #it seems sorted, but it isn't guaranteed to be that way.\n{datetime.date(2010, 2, 5): 54... | [
9,
5
] | [] | [] | [
"date",
"datetime",
"ordereddictionary",
"python"
] | stackoverflow_0006677876_date_datetime_ordereddictionary_python.txt |
Q:
My django tests are not working due to order of south's schema migrations?
When I run
manage.py test myapp
it dies with this error
Creating test database for alias 'default'...
! Error found during real run of migration! Aborting.
_mysql_exceptions.OperationalError: (1005, "Can't create table
'test_dom.#sql-4... | My django tests are not working due to order of south's schema migrations? | When I run
manage.py test myapp
it dies with this error
Creating test database for alias 'default'...
! Error found during real run of migration! Aborting.
_mysql_exceptions.OperationalError: (1005, "Can't create table
'test_dom.#sql-49b_1a1' (errno: 150)")
I am using south to handle schema migrations, django 1.3... | [
"do you know that you can define dependencies in south migrations?\nhttp://south.aeracode.org/docs/dependencies.html\nIf you define the dependencies, a single \"manage.py migrate\" should work. If not, please post the error message.\n",
"Why do a migrate after a syncdb? Surely you have no migration to do after a ... | [
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006675088_django_python.txt |
Q:
How to keep random generators fixed in python?
I have a code to assign a tag to each node in my network randomly either 'up' or 'down'.
How I can fix this random tags for later on so that they won't change if I run my codes each time?
import networkx
import random
def assign_nodes(G):
state = ['up','down']
... | How to keep random generators fixed in python? | I have a code to assign a tag to each node in my network randomly either 'up' or 'down'.
How I can fix this random tags for later on so that they won't change if I run my codes each time?
import networkx
import random
def assign_nodes(G):
state = ['up','down']
for n in G:
G.node[n]['sign']=random.choic... | [
"Use random.seed(constant) to initialize the random number generator to a constant value (replace constant with a number of your choice).\n",
"You can save the graph:\nfrom random import random\nimport networkx as nx\n\ndef make_graph():\n G=nx.DiGraph()\n N=10\n #make a random graph\n for i in range(... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0006678377_python.txt |
Q:
Python - efficient way to create 20 variables?
I need to create 20 variables in Python. That variables are all needed, they should initially be empty strings and the empty strings will later be replaced with other strings. I cann not create the variables as needed when they are needed because I also have some if/e... | Python - efficient way to create 20 variables? | I need to create 20 variables in Python. That variables are all needed, they should initially be empty strings and the empty strings will later be replaced with other strings. I cann not create the variables as needed when they are needed because I also have some if/else statements that need to check whether the variab... | [
"\nWhere is my mistake?\n\nThere are possibly three mistakes. The first is that 'variable_' + 'a' obviously isn't equal to 'variable_1'. The second is the quoting in the argument to exec. Do\nfor x in list:\n exec(\"variable_%s = ''\" % x)\n\nto get variable_a etc.\nThe third mistake is that you're not using a l... | [
10
] | [
"I have the same question as others (of not using a list or hash), but if you need , you can try this:\nfor i in xrange(1,20):\n locals()['variable_%s' %i] = ''\n\nIm assuming you would just need this in the local scope. Refer to the manual for more information on locals \n",
"never used it, but something like... | [
-2,
-2
] | [
"creation",
"exec",
"python",
"variables"
] | stackoverflow_0006678547_creation_exec_python_variables.txt |
Q:
Installing modules for Bitnami Django Stack
I have installed Bitnami Django Stack on my windows machine. Now I have to extend an existing Django project. When I tried to run the project using manage.py runserver it gave me modules error. So I installed all the required modules in C:\Program Files\BitNami DjangoSta... | Installing modules for Bitnami Django Stack | I have installed Bitnami Django Stack on my windows machine. Now I have to extend an existing Django project. When I tried to run the project using manage.py runserver it gave me modules error. So I installed all the required modules in C:\Program Files\BitNami DjangoStack\apps folder.
Now When I run the manage.py runs... | [
"You have to import ImageField from sorl.thumbnail- not import thumbnail module.\nfrom sorl.thumbnail import ImageField\n#...\nclass Profile(models.Model):\n photo = ImageField(..)\n\nExample in documentation\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006678048_django_python.txt |
Q:
Amazon EC2 AMI pre-configured with Django Stack
What is the best available EC2 AMI configured with
Django Stack
MySql Installed and configured
Apache or any other Server
After searching I have found only one bitniami djangostack. Have any of you ever tried it. Are there any other options.
Thanks
A:
It might be... | Amazon EC2 AMI pre-configured with Django Stack | What is the best available EC2 AMI configured with
Django Stack
MySql Installed and configured
Apache or any other Server
After searching I have found only one bitniami djangostack. Have any of you ever tried it. Are there any other options.
Thanks
| [
"It might be better take a standard well known image and install the software. The Ubuntu installation is quick and easy. In my case I've had no trouble using the ubuntu-maverick-10.10-amd64-server AMI from Canonical to build up a Pylons stack. For your requirements you could start with this AMI and then using \... | [
6,
2
] | [] | [] | [
"amazon_ec2",
"cloud",
"django",
"python",
"web_services"
] | stackoverflow_0004278254_amazon_ec2_cloud_django_python_web_services.txt |
Q:
Interactive rename script in Python
For a while I've been using the rather useful file renaming utilities by Oskar Liljeblad for moving and copying files. However, although the program works fine for most purposes, it hasn't been updated for a few years and it's not Unicode-compatible—non ASCII characters are repl... | Interactive rename script in Python | For a while I've been using the rather useful file renaming utilities by Oskar Liljeblad for moving and copying files. However, although the program works fine for most purposes, it hasn't been updated for a few years and it's not Unicode-compatible—non ASCII characters are replaced with C escaped strings. This makes i... | [
"This sounds like an excellent project! You might want to start with the shutil module. You might also be interested in the os.path module.\nPerhaps to get you started, here's a function that takes a path to a file and backs the file up by copying it and giving it a .bak extension.\nimport os, shutil\n\ndef backu... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006678509_python.txt |
Q:
What's the best way to find the similarity among these vectors?
v1 = [33, 24, 55, 56]
v2 = [32, 25, 51, 40]
v3 = [ ... ]
v4 = [ ... ]
Normally, to find which vector is the most similar to v1, I would run v1 against the other vectors with a cosine similarity algorithm.
Now, I have a more complex set of vectors wit... | What's the best way to find the similarity among these vectors? | v1 = [33, 24, 55, 56]
v2 = [32, 25, 51, 40]
v3 = [ ... ]
v4 = [ ... ]
Normally, to find which vector is the most similar to v1, I would run v1 against the other vectors with a cosine similarity algorithm.
Now, I have a more complex set of vectors with the structure:
v1 = [ { 'a': 4, 'b':9, 'c': 12 ... },
{ 'a',... | [
"You do the same thing in more dimensions.\nPreviously you just had 4 dimensions. Now you have a much larger set of dimensions with 2-dimensional labeling of the indices. But the math remains the same. You have a dot product like this untested code:\ndef complicated_dot(v, w):\n dot = 0\n for (v_i, w_i) in... | [
2,
0
] | [] | [] | [
"algorithm",
"computer_science",
"python"
] | stackoverflow_0006678803_algorithm_computer_science_python.txt |
Q:
PyQt: Qt.Popup widget sometimes loses focus without closing, becomes unclosable
I'm writing a very small application with PyQt. All of my testing has been on Ubuntu/gnome so far.
I want a single "Popup" style window, with no taskbar/panel entry, that will close itself (and the application) the moment it loses focu... | PyQt: Qt.Popup widget sometimes loses focus without closing, becomes unclosable | I'm writing a very small application with PyQt. All of my testing has been on Ubuntu/gnome so far.
I want a single "Popup" style window, with no taskbar/panel entry, that will close itself (and the application) the moment it loses focus.
The Qt.Popup flag seems to fit the bill, but I'm having a weird problem. I've noti... | [
"Using QWidget::raise() seems to help here. \n(Also took the liberty and fixed your app event loop)\n#!/usr/bin/python\nimport sys\n#import time\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nif __name__ == '__main__':\n #time.sleep(2)\n app = QApplication(sys.argv)\n w = QDialog()\n w.setWin... | [
4
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"ubuntu"
] | stackoverflow_0006672214_pyqt_pyqt4_python_qt_ubuntu.txt |
Q:
simple example with spawnProcess
I have a simple example:
subprocesses = {}
class MyPP(protocol.ProcessProtocol):
def processExited(self, reason):
print "processExited, status %s" % (reason.value.exitCode,)
class Test:
def run(self):
for i in range(0, max_processes):
pp = MyP... | simple example with spawnProcess | I have a simple example:
subprocesses = {}
class MyPP(protocol.ProcessProtocol):
def processExited(self, reason):
print "processExited, status %s" % (reason.value.exitCode,)
class Test:
def run(self):
for i in range(0, max_processes):
pp = MyPP()
command = ['sleep','1... | [
"subprocesses = {}\nmax_processes = 3\n\nfrom twisted.internet import protocol, reactor\n\nclass MyPP(protocol.ProcessProtocol):\n def connectionMade(self):\n self.pid = self.transport.pid\n\n def processExited(self, reason):\n print \"processExited, status %s\" % (reason.value.exitCode,)\n ... | [
9
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0006678763_python_twisted.txt |
Q:
Selenium: FirefoxProfile fails with not found exception
I've the following code, though I set the profile_directory Firefox webdriver still attempts to store setting within the /tmp folder
profile = FirefoxProfile(profile_directory = '/home/sultan/profiles')
profile.set_preference('network.proxy.http', scheme);
pr... | Selenium: FirefoxProfile fails with not found exception | I've the following code, though I set the profile_directory Firefox webdriver still attempts to store setting within the /tmp folder
profile = FirefoxProfile(profile_directory = '/home/sultan/profiles')
profile.set_preference('network.proxy.http', scheme);
profile.set_preference('network.proxy.http_port', self.proxy.ge... | [
"I have same problem. As FF5 doesn't have \"user.js\" in profile -> we don't have to read it. \nso open selenium/webdriver/firefox/firefox_profile.py and add try except after def _read_existing_userjs(self), like this:\ndef _read_existing_userjs(self):\n try:\n f = open(os.path.join(self.profile_dir, ... | [
3
] | [] | [] | [
"firefox",
"python",
"selenium",
"webdriver"
] | stackoverflow_0006652819_firefox_python_selenium_webdriver.txt |
Q:
How can I visualize a Graph in (interactive) 3D with Python?
I have a Graph in Python like this one:
# Each element is a tuple with coordinates (x,y,z).
# The index is the id of the vertex
vertexList = [(0,0,0),(1,0,0),(1,1,0),(0,1,0),
(0,0,1),(1,0,1),(1,1,1),(0,1,1)]
# Each element is a tuple wi... | How can I visualize a Graph in (interactive) 3D with Python? | I have a Graph in Python like this one:
# Each element is a tuple with coordinates (x,y,z).
# The index is the id of the vertex
vertexList = [(0,0,0),(1,0,0),(1,1,0),(0,1,0),
(0,0,1),(1,0,1),(1,1,1),(0,1,1)]
# Each element is a tuple with the vertex-ids and a weight (vertexId1, vertexId2, weight)
edge... | [
"When you looked at matplotlib, did you see mplot3d? This may be what you require.\nMPlot3D\nIf not, I'm sorry I probably can't help any more than that.\n",
"I've not used this myself yet (beyond running example scripts) but mayavi2 looks promising. It comes bundled with the enthought python distribution.\nAlso, ... | [
2,
2
] | [] | [] | [
"graph",
"graph_visualization",
"python",
"visualization",
"vtk"
] | stackoverflow_0006676839_graph_graph_visualization_python_visualization_vtk.txt |
Q:
How to get another variable type from sql query
From this query...
self.cur.execute("""SELECT pub FROM "20091229"
GROUP BY pub ORDER BY pub""")
I get the following list with tuples back.
>>[(1,), (2,), (3,)]
But I need only a list or a list without decimal points in the tuples.
Something like th... | How to get another variable type from sql query | From this query...
self.cur.execute("""SELECT pub FROM "20091229"
GROUP BY pub ORDER BY pub""")
I get the following list with tuples back.
>>[(1,), (2,), (3,)]
But I need only a list or a list without decimal points in the tuples.
Something like these:
[1, 2, 3]
or
[(1), (2), (3)]
Thanks.
| [
"What about this?\nli = [tup[0] for tup in li]\n\nPlease note, a tuple get's written like this (1,), because (1) would imply mathematical brackets. Also, it seems you are trying to print a list, consider using a dedicated printing function.\n",
"It will be better if you tell us what module do you use to work with... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006679330_python.txt |
Q:
What's the most pythonic way to merge 2 dictionaries, but make the values the average values?
d1 = { 'apples': 2, 'oranges':5 }
d2 = { 'apples': 1, 'bananas': 3 }
result_dict = { 'apples': 1.5, 'oranges': 5, 'bananas': 3 }
What's the best way to do this?
A:
Here is one way:
result = dict(d2)
for k in d1:
i... | What's the most pythonic way to merge 2 dictionaries, but make the values the average values? | d1 = { 'apples': 2, 'oranges':5 }
d2 = { 'apples': 1, 'bananas': 3 }
result_dict = { 'apples': 1.5, 'oranges': 5, 'bananas': 3 }
What's the best way to do this?
| [
"Here is one way:\nresult = dict(d2)\nfor k in d1:\n if k in result:\n result[k] = (result[k] + d1[k]) / 2.0\n else:\n result[k] = d1[k]\n\n",
"This would work for any number of dictionaries:\ndicts = ({\"a\": 5},{\"b\": 2, \"a\": 10}, {\"a\": 15, \"b\": 4})\nkeys = set()\naveraged = {}\nfor d... | [
7,
6,
3,
2,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006677285_dictionary_python.txt |
Q:
How i can match on the ?next=/nextpage/ value when i decorate a view with @login_required?
How i can match on the ?next=/nextpage/ value when i decorate a view in django with @login_required?
It's not working on the "standard way" (in url.py via regular expression matching)!
Why it is not working on the standard w... | How i can match on the ?next=/nextpage/ value when i decorate a view with @login_required? | How i can match on the ?next=/nextpage/ value when i decorate a view in django with @login_required?
It's not working on the "standard way" (in url.py via regular expression matching)!
Why it is not working on the standard way?
in urls.py:
(r'^login/$', 'foo.nb.views.signup'),
#(r'^login/?next=(?P<next>\S{1,250})$', 'f... | [
"Django only matches paths based on the path of the URL, not the querystring. \nThis means that anything after '?' in your request from the server is not considered when deciding which view to serve up. Instead, that part of the string is turned into a dictionary like object.\nso if you request:\n/login/?next=/next... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006679916_django_python.txt |
Q:
How to make Emacs Python mode generate TABs for indent?
I'm working with a bunch of Python programmers who use vim and they make Python using TABs for indent. I use Emacs with python-mode which translates the tab key to 4 spaces (like it should, but never mind). Since I don't want to cause trouble I want to add ... | How to make Emacs Python mode generate TABs for indent? | I'm working with a bunch of Python programmers who use vim and they make Python using TABs for indent. I use Emacs with python-mode which translates the tab key to 4 spaces (like it should, but never mind). Since I don't want to cause trouble I want to add something to my .emacs file (or whatever) to make indents usi... | [
"You can define Python-specific settings in your ~/.emacs with python-mode-hook. In order to use tabs for indentation, you could use:\n(add-hook 'python-mode-hook\n (lambda () (setq indent-tabs-mode t)))\n\nSince python.el indents only 4 columns, by default, the above will use tabs when the indent is a multiple o... | [
15,
3
] | [
"As the commenters to the post correctly said, using tabs for indentation is a bad idea, and using a non-standard tab width is even worse. Nonetheless, sometimes you have no choice if you want to collaborate.\nDepending on exactly how your colleagues have vim configured, you may need to both turn on indent-tabs-mod... | [
-1
] | [
"emacs",
"python"
] | stackoverflow_0006679625_emacs_python.txt |
Q:
how to split a list in two at the point where predicate is first False
I keep thinking there should be a function for this, but I've searched the likely places (google, itertools docs, list methods, other SO questions), but nowhere found quite what I was looking for.
Naive and working implementation:
def split_at_... | how to split a list in two at the point where predicate is first False | I keep thinking there should be a function for this, but I've searched the likely places (google, itertools docs, list methods, other SO questions), but nowhere found quite what I was looking for.
Naive and working implementation:
def split_at_first_false(pred, seq):
first = []
second = []
true_so_far = Tru... | [
"This seems like a job for itertools.\n>>> first = list(itertools.takewhile(str.isalpha, l))\n>>> second = list(itertools.dropwhile(str.isalpha, l))\n>>> first\n['a', 'b', 'c']\n>>> second\n['1', 'a', '2', 'b']\n\nThis needs to be altered if l is an iterator rather than a sequence.\n>>> def bisect_iter(pred, i):\n.... | [
13,
7,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006679641_python.txt |
Q:
Pseudorandom number generator for hashing that can take in any size table
I am constructing a pseudo random number generator for hashing. The algorithm I need to use is as follows:
Initialize an integer R to be equal to 1 every time the tabling routine is called
On each successive call for a random number, set R... | Pseudorandom number generator for hashing that can take in any size table | I am constructing a pseudo random number generator for hashing. The algorithm I need to use is as follows:
Initialize an integer R to be equal to 1 every time the tabling routine is called
On each successive call for a random number, set R = R*5
Mask all but the lower order n+2 bits of the product and place the result... | [
"I didn't really understand how your code related to your algorithm (what is random_list?) or how the code should be structured, but I assume it is something similar to this:\nclass Rand:\n def __init__(self, n):\n # Initialize an integer R to be equal to 1 every time the tabling routine is called\n ... | [
0
] | [] | [] | [
"hash",
"python",
"random"
] | stackoverflow_0006547534_hash_python_random.txt |
Q:
syntax error near unexpected token `<' from Applescript to Python
I am using the following command to pass a string to python from Applescript
String mytext contains the HTML body of an email starting with <...
Applescript
display dialog (do shell script "/Users/mymac/Documents/'Microsoft User Data'/'Outlook Scrip... | syntax error near unexpected token `<' from Applescript to Python | I am using the following command to pass a string to python from Applescript
String mytext contains the HTML body of an email starting with <...
Applescript
display dialog (do shell script "/Users/mymac/Documents/'Microsoft User Data'/'Outlook Script Menu Items'/ test.py" & mytext)
Python
#!/usr/bin/env python
impor... | [
"You don't want to pass the HTML as an argument to the Python script. Instead, do something like:\ndisplay dialog (do shell script \"/Users/mymac/Documents/'Microsoft User Data'/'Outlook Script Menu Items'/ test.py < webpage.html\")\n\n\nprint sys.stdin.read()\n\n",
"The problem is you are executing a shell scrip... | [
2,
0
] | [] | [] | [
"applescript",
"html",
"python",
"runtime"
] | stackoverflow_0006659727_applescript_html_python_runtime.txt |
Q:
Most elegant way to configure a class in Python?
I'm simulating a distributed system in which all nodes follow some protocol. This includes assessing some small variations in the protocol. A variation means alternative implementation of a single method. All nodes always follow the same variation, which is determin... | Most elegant way to configure a class in Python? | I'm simulating a distributed system in which all nodes follow some protocol. This includes assessing some small variations in the protocol. A variation means alternative implementation of a single method. All nodes always follow the same variation, which is determined by experiment configuration (only one configuration... | [
"You could use the __slots__ mechanism and a factory class. You would need to instantiate a NodeFactory for each experiment, but it would handle creating Node instances for you from there on. Example:\nclass Node(object):\n __slots__ = [\"slow\",\"dumb\"]\n\nclass NodeFactory(object):\n def __init__(self, sl... | [
3,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006680029_python.txt |
Q:
Django 1.2: login issue (GET parameter: next)
I have a new question about django (I post a lost of them these days^^).
Here is my situation : I have a custom login view (registered as login url in the settings) where I authenticate the users. I chose to do a custom view to be able to add messages and logging.
The ... | Django 1.2: login issue (GET parameter: next) | I have a new question about django (I post a lost of them these days^^).
Here is my situation : I have a custom login view (registered as login url in the settings) where I authenticate the users. I chose to do a custom view to be able to add messages and logging.
The authentication works well, but I have a problem wit... | [
"\nWhen an anonymous user tries to go to /editor/25 (for example) and is redirected to login for authentication, \"next\" is always None even if present in the url (it should be \"/editor/25\").\n\nThis sounds strange. Can you check that the URL indeed has ?next=/editor/25/ as the query string? Also log request.GET... | [
3,
0
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0003861840_authentication_django_python.txt |
Q:
Twill alternative for integration testing
I am using to twill to do integration testing for an AppEngine (using tipfy micro framework) application but unfortunately twill is not maintained and I cannot test PUT and DELETE requests.
Is there any similar solution?
I am thinking of using PhantomJS, there are some pyt... | Twill alternative for integration testing | I am using to twill to do integration testing for an AppEngine (using tipfy micro framework) application but unfortunately twill is not maintained and I cannot test PUT and DELETE requests.
Is there any similar solution?
I am thinking of using PhantomJS, there are some python bindings and it can execute JS (as it is a ... | [
"There are not many alternatives for headless JS testing, you could try selenium 2 web driver. Good luck :)\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"integration_testing",
"python",
"tipfy",
"twill"
] | stackoverflow_0006678523_google_app_engine_integration_testing_python_tipfy_twill.txt |
Q:
how to call another window in pyqt4 python?
how to call another window in pytq4?
For example i have two separate form. I want to show the second form when i click a button in the login form.
EDITED:
for example i have this dialog for my login.
when the user click a button the main.py would appear and this dialog w... | how to call another window in pyqt4 python? | how to call another window in pytq4?
For example i have two separate form. I want to show the second form when i click a button in the login form.
EDITED:
for example i have this dialog for my login.
when the user click a button the main.py would appear and this dialog will be close.
LOGIN.py
from PyQt4 import QtCo... | [
"I had a similar situation and this is what I've done. Does not feel like the ideal solution but it worked for me.\n import Main\n self.main = Main.Form(user, loginWindow=self)\n\n self.hide() \n self.main.show()\n\n # You can do self.close() here OR\n ... | [
0
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0006634599_pyqt4_python.txt |
Q:
Mechanze form submission causes 'Assertion Error' in response when .read() is attempted
I am writing a web-crawl program with python and am unable to login using mechanize. The form on the site looks like:
<form method="post" action="PATLogon">
<h2 align="center"><img src="/myaladin/images/aladin_logo_rd.gi... | Mechanze form submission causes 'Assertion Error' in response when .read() is attempted | I am writing a web-crawl program with python and am unable to login using mechanize. The form on the site looks like:
<form method="post" action="PATLogon">
<h2 align="center"><img src="/myaladin/images/aladin_logo_rd.gif"></h2>
<!-- ALADIN Request parameters -->
<input type=hidden name=req value="db">
<i... | [
"This is the solution that I found:\nimport mechanize,urllib,ClientForm,cookielib,re,os,time\nfrom BeautifulSoup import BeautifulSoup\n\ncookies = mechanize.CookieJar()\nopener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))\nheaders = [(\"Accept\",\"text/html,application/xhtml+xml,application/xml;... | [
2
] | [] | [] | [
"assert",
"mechanize",
"python",
"urllib2",
"web_crawler"
] | stackoverflow_0006573526_assert_mechanize_python_urllib2_web_crawler.txt |
Q:
Django Error Reporting - How to know which user triggered the error?
Is there a way I can customize Django error reporting so when it emails me it lets me know which user triggered the error?
I'm in Django 1.2 if it matters.
Much Thanks in advance!
A:
If you don't want to use sentry you can use this simple middl... | Django Error Reporting - How to know which user triggered the error? | Is there a way I can customize Django error reporting so when it emails me it lets me know which user triggered the error?
I'm in Django 1.2 if it matters.
Much Thanks in advance!
| [
"If you don't want to use sentry you can use this simple middleware to attache the user-infos to the error mail:\n# source: https://gist.github.com/646372\nclass ExceptionUserInfoMiddleware(object):\n \"\"\"\n Adds user details to request context on receiving an exception, so that they show up in the error em... | [
14,
2
] | [] | [] | [
"django",
"django_email",
"django_errors",
"django_middleware",
"python"
] | stackoverflow_0006678895_django_django_email_django_errors_django_middleware_python.txt |
Q:
How can I record the number of times something happens over several files?
I'm looking to keep a summary of both the number of times a specific thing happens and when something very important arises. I'll give an example...
My code establishes a ssh connection and runs commands. An exception is raised and handled ... | How can I record the number of times something happens over several files? | I'm looking to keep a summary of both the number of times a specific thing happens and when something very important arises. I'll give an example...
My code establishes a ssh connection and runs commands. An exception is raised and handled every time the script loses connection to the ssh server. Let's say this type of... | [
"Try subclassing logging.Handler and overriding the handle or emit method to check the message being sent and increment a counter somewhere as appropriate, and then adding this handler to your application's root logger like so:\nimport logging\ncounter = 0\nclass CounterHandler(logging.Handler):\n def emit(self,... | [
1,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0006680695_logging_python.txt |
Q:
Python NumPy Arrays
Im working with two arrays, trying to work with them like a 2 dimensional array. I'm using a lot of vectorized calculations with NumPy. Any idea how I would populate an array like this:
X = [1, 2, 3, 1, 2, 3, 1, 2, 3]
or:
X = [0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 0.2, 0.... | Python NumPy Arrays | Im working with two arrays, trying to work with them like a 2 dimensional array. I'm using a lot of vectorized calculations with NumPy. Any idea how I would populate an array like this:
X = [1, 2, 3, 1, 2, 3, 1, 2, 3]
or:
X = [0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8, 0.2, 0.4, 0.6, 0.8]
Ignore the... | [
"You can use the function tile. From the examples:\n>>> a = np.array([0, 1, 2])\n>>> np.tile(a, 2)\narray([0, 1, 2, 0, 1, 2])\n\nWith this function, you can also reshape your array at once like they do in the other answers with reshape (by defining the 'repeats' is more dimensions):\n>>> np.tile(a, (2, 1))\narray([... | [
11,
1,
1,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0006681284_arrays_numpy_python.txt |
Q:
Help with PyEPL logging
I have never used Python before, most of my programming has been in MATLAB and Unix. However, recently I have been given a new assignment that involves fixing an old PyEPL program written by a former employee (I've tried contacting him directly but he won't respond to my e-mails). I know es... | Help with PyEPL logging | I have never used Python before, most of my programming has been in MATLAB and Unix. However, recently I have been given a new assignment that involves fixing an old PyEPL program written by a former employee (I've tried contacting him directly but he won't respond to my e-mails). I know essentially nothing about Pytho... | [
"I would first check if there is a line in the code \nfrom some_module_name import *\n\nThis could easily explain why you can call these functions (classes?). It will also tell you what file to look in to modify the code for LogTrack.\nEdit:\nSo, a little digging seems to find that LogTrack is part of PyEPL's textl... | [
0
] | [] | [] | [
"concatenation",
"file",
"logging",
"python"
] | stackoverflow_0006680623_concatenation_file_logging_python.txt |
Q:
Python Regex 'not' to identify pattern within
I am dealing a problem to write a python regex 'not'to identify a certain pattern within href tags.
My aim is to replace all occurrences of DSS[a-z]{2}[0-9]{2} with a href link as shown below,but without replacing the same pattern occurring inside href tags
Present ... | Python Regex 'not' to identify pattern within | I am dealing a problem to write a python regex 'not'to identify a certain pattern within href tags.
My aim is to replace all occurrences of DSS[a-z]{2}[0-9]{2} with a href link as shown below,but without replacing the same pattern occurring inside href tags
Present Regex:
replaced = re.sub("[^http://*/s](DSS[a-z]{2}[... | [
"The answer to any question having regexp and HTML in the same sentence is here.\nIn Python, the best HTML parser is indeed Beautilf Soup.\nIf you want to persist with regexp, you can try a negative lookbehind to avoid anything precessed by a \". At your own risk.\n"
] | [
3
] | [] | [] | [
"hyperlink",
"python",
"regex",
"regex_negation"
] | stackoverflow_0006681530_hyperlink_python_regex_regex_negation.txt |
Q:
How to optimally turn a multidimentional list into a single list of items in Python?
Possible Duplicates:
Making a flat list out of list of lists in Python
Flatten (an irregular) list of lists in Python
Input a list such as: [1,2,[3,4,[5,6,7,[8]]],[9],10]
Desired output: [1,2,3,4,5,6,7,8,9,10]
Currently I have t... | How to optimally turn a multidimentional list into a single list of items in Python? |
Possible Duplicates:
Making a flat list out of list of lists in Python
Flatten (an irregular) list of lists in Python
Input a list such as: [1,2,[3,4,[5,6,7,[8]]],[9],10]
Desired output: [1,2,3,4,5,6,7,8,9,10]
Currently I have the following recursive function:
def fix_list( li , l = [] ):
for i in li:
tr... | [
"Here is an iterative version (originally inspired by Artsiom Rudzenka's) that modifies the list in place using slice assignment rather than creating a new list on each pass. Interestingly, only one pass through the list is needed! My use of enumerate() is a little unorthodox; I use it to keep track of an index in... | [
2,
1,
1,
1,
0
] | [] | [] | [
"list",
"optimization",
"python",
"recursion"
] | stackoverflow_0006679228_list_optimization_python_recursion.txt |
Q:
Problem running PyDev-developed apps in terminal
Im having some import problems with an application I developed in python with Eclipse/PyDev.
Running the app from within Eclipse is no problem but when I try running it through the linux terminal the imports (which are imported from other folders (packages in Eclips... | Problem running PyDev-developed apps in terminal | Im having some import problems with an application I developed in python with Eclipse/PyDev.
Running the app from within Eclipse is no problem but when I try running it through the linux terminal the imports (which are imported from other folders (packages in Eclipse)) are broken and I get an ImportError: No module nam... | [
"The key here is that PyDev and Eclipse manage a custom Python Path when you're launching within Eclipse. You can modify your environment variables to contain a more complete PYTHONPATH value that contains the locations where you're importing from, or you can use sys.path.append() to add directories to the path at... | [
2
] | [] | [] | [
"eclipse",
"pydev",
"python",
"terminal"
] | stackoverflow_0006681690_eclipse_pydev_python_terminal.txt |
Q:
How to convert HEX data into BINARY data?
I am trying to send Binary data using python raw socket.
For that i will do following.
s = '\x01\x00\x12\x59' # some binary data
sock.send(s) # assuming "sock" is a valid, open socket object
i have created a DATAGRAM in HEX in by sniffing a network traffic with ... | How to convert HEX data into BINARY data? | I am trying to send Binary data using python raw socket.
For that i will do following.
s = '\x01\x00\x12\x59' # some binary data
sock.send(s) # assuming "sock" is a valid, open socket object
i have created a DATAGRAM in HEX in by sniffing a network traffic with wireshark.Which i want to send over the network... | [
"Try the following code:\n\"\".join(\"04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00\".split()).decode('hex')\n\nOR:\nimport binascii\nprint binascii.unhexlify(\"\".join(\"04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00\".split()))\n\n",
"\"04 f8 00 50\".replace(' ', '').decode('hex')\n\n... | [
4,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0006681678_python.txt |
Q:
replace a substring with a non-string value in python
I know we have a replace method to replace a substring within a string with another string. But what I want is to replace some substring within a given string with some non-string (could be any data type) values.
example -
string1='My name is val1. My age is v... | replace a substring with a non-string value in python | I know we have a replace method to replace a substring within a string with another string. But what I want is to replace some substring within a given string with some non-string (could be any data type) values.
example -
string1='My name is val1. My age is val2 years. I was born on val3'
val1='abc'
val2=40
val3= dat... | [
"Use str.format:\n>>> string1 = 'My name is {0}. My age is {1} years. I was born on {2}'\n>>> string1.format('abc', 40, datetime.date(1980, 1, 1))\n'My name is abc. My age is 40 years. I was born on 1980-01-01'\n\n",
"I prefer to use a dict for that because it makes it much more simple to see which argument goes ... | [
5,
4,
3,
0
] | [] | [] | [
"python",
"replace",
"string"
] | stackoverflow_0006681574_python_replace_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.