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:
Building a decorator with three parameters - closure not working in Python 2.x
def ensure_type(parameter_name, the_type, type_converter_fn=None):
def decorator(fn):
def wrapped(self, *args, **kwargs):
if not type_converter_fn: # fails here
type_converter_fn = the_type
retur... | Building a decorator with three parameters - closure not working in Python 2.x | def ensure_type(parameter_name, the_type, type_converter_fn=None):
def decorator(fn):
def wrapped(self, *args, **kwargs):
if not type_converter_fn: # fails here
type_converter_fn = the_type
return fn(self, *args, **kwargs)
return wrapped
return decorator
When stepping ... | [
"Scoping in Python is determined statically. An assignment inside a function makes a variable local to that function. You cannot access a local variable before its first assignment.\nThe second line in\nif not type_converter_fn:\n type_converter_fn = the_type\n\nmakes type_converter_fn local to wrapped(), so t... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008518766_python.txt |
Q:
comparison of two strings and returning the one most similar
I have to write a function that takes a string as argument and compair this string to two other strings and return the string most similar and the number of differences.
def func("LUMB"):
lst=["JIBM", "NUNE", "NUMB"]
should return:
("NUMB",1)
I hav... | comparison of two strings and returning the one most similar | I have to write a function that takes a string as argument and compair this string to two other strings and return the string most similar and the number of differences.
def func("LUMB"):
lst=["JIBM", "NUNE", "NUMB"]
should return:
("NUMB",1)
I have tried:
def f(word):
lst=["JIBM", "NUNE", "NUMB"]
for i i... | [
"Looks like Shawn Chin has provided the best solution, but if you're prevented from using non-builtin modules, it seems like get_close_matches from difflib might help:\nimport difflib\ndifflib.get_close_matches(\"LUMB\", [\"JIBM\", \"NUNE\", \"NUMB\"], 1)\n\nThe number of differences can be gotten using the get_opc... | [
10,
6
] | [] | [] | [
"comparison",
"python"
] | stackoverflow_0008519181_comparison_python.txt |
Q:
How to store number from string in python
i have string like this:
string = "The stock item "28031 (111111: Test product)" was added successfully."
I need store from string the first 5 numbers ( for example "28031" ) and save them to another string.
It's because i am selenium tester and every time i am create ne... | How to store number from string in python | i have string like this:
string = "The stock item "28031 (111111: Test product)" was added successfully."
I need store from string the first 5 numbers ( for example "28031" ) and save them to another string.
It's because i am selenium tester and every time i am create new stock item he has different first 5 numbers.
... | [
"m = re.search(\"\\d+\", string)\nprint m.group(0)\n\nprints 28031\nIt just selects the first group of digits, regardless of the length (2803 would be selected, too)\n",
"Firstly I am assuming all these strings have exactly the same format. If so the simplest way to get your stock item number is:\nstocknumber = s... | [
3,
1,
1,
0
] | [] | [] | [
"numbers",
"python",
"store",
"string"
] | stackoverflow_0008519542_numbers_python_store_string.txt |
Q:
Screenshot of screen subregion using GTK
I'm trying to take screenshots of only part of the screen using Python under Ubuntu 10.04.
Here's my code (assume IMAGE_GRAB is False):
def screenshot_roi(regions):
if IMAGE_GRAB:
return map(ImageGrab.grab, regions)
else:
w = gtk.gdk.get_default_root... | Screenshot of screen subregion using GTK | I'm trying to take screenshots of only part of the screen using Python under Ubuntu 10.04.
Here's my code (assume IMAGE_GRAB is False):
def screenshot_roi(regions):
if IMAGE_GRAB:
return map(ImageGrab.grab, regions)
else:
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
pb... | [
"I think that's because get_pixels returns you the data as it is stored in memory. What you're missing here is that a line may have some padding at the end of it, for performance reasons (because of memory alignment constraints).\nSee the GdkPixbuf structure: the interesting information is the rowstride, which is t... | [
4
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0008514334_gtk_python.txt |
Q:
python csv find text in file and then find a specific column
i have a database of csv something like
apple,10,red,date
orange,12,yellow,date
pear,13,green,date
pineapple,14,brown,date
i want to first search for eg: pineapple and then get third column" from it, i need some ideas, i am using the python csv module
i... | python csv find text in file and then find a specific column | i have a database of csv something like
apple,10,red,date
orange,12,yellow,date
pear,13,green,date
pineapple,14,brown,date
i want to first search for eg: pineapple and then get third column" from it, i need some ideas, i am using the python csv module
i am able to get
#!/usr/bin/env python
import csv
import sys
fil... | [
"You can just check whether the first element of the line is pineapple. A neat way to get all the third values is to use a list comprehension:\nimport csv\nwith open(\"/tmp/database.txt\", 'r') as file:\n reader = csv.reader(file)\n third_where_pineapple = [line[2] for line in reader if line[0] == 'pineapple']\n ... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0008520329_python.txt |
Q:
Style for checking multiple elements in a Python sequence
I frequently find myself writing code like this:
tupla = (1, 2, 3, 4)
if (1 in tupla) and (4 in tupla):
...
Is there any Pythonic way to write this more compactly, without typing tupla twice?
A:
if all(x in tupla for x in list_of_x):
or
if set(list_... | Style for checking multiple elements in a Python sequence | I frequently find myself writing code like this:
tupla = (1, 2, 3, 4)
if (1 in tupla) and (4 in tupla):
...
Is there any Pythonic way to write this more compactly, without typing tupla twice?
| [
"if all(x in tupla for x in list_of_x):\n\nor\nif set(list_of_x).issubset(set(tupla)):\n\nThe first one will stop as soon as the first x is not in tupla. The second one will create both sets in any case.\n",
"What your code is asking is essentially\n\nIs [1, 4] a subset of tupla?\n\nYou can express this question ... | [
5,
2
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0008520600_coding_style_python.txt |
Q:
Python C extension: Use extension PYD or DLL?
I have a Python extension written in C and I wonder if I should use the file extension DLL or PYD under Windows. (And what would I use in Linux?)
Are there any differences (besides the filename)?
I found an unofficial article. Is this the secret of pyc?
Why can't I fin... | Python C extension: Use extension PYD or DLL? | I have a Python extension written in C and I wonder if I should use the file extension DLL or PYD under Windows. (And what would I use in Linux?)
Are there any differences (besides the filename)?
I found an unofficial article. Is this the secret of pyc?
Why can't I find any official article on this topic?
| [
"pyd files are just dll files ready for python importing.\nTo distinguish them from normal dlls, I recommend .pyd not .dll in windows.\nHere is the official doc about this issue:\nhttp://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll\n",
"According to the Creating Your Own Project step (Step 7 o... | [
28,
9,
8,
3
] | [] | [] | [
"pyd",
"python",
"python_c_extension"
] | stackoverflow_0008262884_pyd_python_python_c_extension.txt |
Q:
format messed up while performing read xml file, append elements and write to a file
Using python, minidom..
I'm reading a pretty-formatted xml file, then adding elements before writing it back to a file again.
Everything works fine except the format of new added elements.
It looks like,
<previousTag>
.. everyt... | format messed up while performing read xml file, append elements and write to a file | Using python, minidom..
I'm reading a pretty-formatted xml file, then adding elements before writing it back to a file again.
Everything works fine except the format of new added elements.
It looks like,
<previousTag>
.. everything which was already in the xml file is correctly formatted.
<addedTag1><addedTag2></... | [
"You'll need to either strip the whitespace yourself, or inform your parser to do it for you (if possible).\nI've spent a few minutes trying to look for parser configuration options available using minidom looked at the source code and to be honest, I can't be bothered to look any further as it's well documented us... | [
0
] | [] | [] | [
"dom",
"pretty_print",
"python",
"xml"
] | stackoverflow_0008519578_dom_pretty_print_python_xml.txt |
Q:
Measuring USB live-transfer speed with Python
I'm trying to find out the speed of a live data-transfer via USB on a Mac run from the command line with Android Debug Bridge.
Is there a way to do this with any Python-packages ?
Basically, I just want to the script to show me the speed as-is shown at the bottom of ... | Measuring USB live-transfer speed with Python | I'm trying to find out the speed of a live data-transfer via USB on a Mac run from the command line with Android Debug Bridge.
Is there a way to do this with any Python-packages ?
Basically, I just want to the script to show me the speed as-is shown at the bottom of a file-transfer window. If not with Python, any com... | [
"Are you doing the file transfer inside python? \nWith a reader and writer?\nIf so, you can read a piece into a buffer, write it out, update a progressbar and repeat this until the file is completely transfered.\nThe progressbar module has options to calculate and display the transfer rate just by giving it updates... | [
1
] | [] | [] | [
"bash",
"macos",
"python"
] | stackoverflow_0008519668_bash_macos_python.txt |
Q:
Need assistance debugging my python code, it's a wreck
I'm using Python 2.7x and am having trouble debugging it. I'm not really sure what I can do. Any help is appreciated. Thanks.
import re
import sys
# Grab parameters from the command line
(filename, threshold) = sys.argv[1:3]
# Validate arguments
if (re.match... | Need assistance debugging my python code, it's a wreck | I'm using Python 2.7x and am having trouble debugging it. I'm not really sure what I can do. Any help is appreciated. Thanks.
import re
import sys
# Grab parameters from the command line
(filename, threshold) = sys.argv[1:3]
# Validate arguments
if (re.match("\D", threshold)):
print "The threshold must be a number... | [
"In general, debugging Python code is easiest with the pdb module. Place the following code where you want the debugger to start:\nimport pdb\npdb.set_trace()\n\nYou can use n to execute the next line of code, s to step into functions, and p to print a value (e.g., p words will print your words list).\nI can't real... | [
2
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0008521481_debugging_python.txt |
Q:
Logging every step and action by Python in a Large Script
I have created a large python script at the end. But now I need a logger for it. I have input steps, prompts.. Function calls.. While Loops.., etc. in the script.
And also, the logger is have to log success operations too.
I couldn't find a suitable answer ... | Logging every step and action by Python in a Large Script | I have created a large python script at the end. But now I need a logger for it. I have input steps, prompts.. Function calls.. While Loops.., etc. in the script.
And also, the logger is have to log success operations too.
I couldn't find a suitable answer for me. I'm searching on the internet again, and wanted to ask ... | [
"There's a module logging in the standard library. Basic usage is very simple; in every module that needs to do logging, put\nlogger = logging.getLogger(__name__)\n\nand log with, e.g.,\nlogger.info(\"Doing something interesting\")\nlogger.warn(\"Oops, something's not right\")\n\nThen in the main module, put someth... | [
2
] | [] | [] | [
"python",
"trace"
] | stackoverflow_0008521540_python_trace.txt |
Q:
Python BaseHTTP gets struck while starting nginx or other services
I am using BaseHTTP since its very simple. Please advice if I'm using it wrong.
if self.path.endswith("nginxstart"):
xxxxxx
status=os.system("/home/karthik/nginx/nginx-1.0.4/sbin/nginx"); #tried ls -l and works
self.wfile.write("nginx... | Python BaseHTTP gets struck while starting nginx or other services | I am using BaseHTTP since its very simple. Please advice if I'm using it wrong.
if self.path.endswith("nginxstart"):
xxxxxx
status=os.system("/home/karthik/nginx/nginx-1.0.4/sbin/nginx"); #tried ls -l and works
self.wfile.write("nginx restarted")
nginx gets started but doesn't write "nginx restarted" to ... | [
"Your code is stuck because os.system block until the command is finished. So if the nginx command is not going to background, the process will not end, and your code will stuck.\nAn alternative is to use subprocess module:\nfrom subprocess import Popen\n\n# start a new command\ncmd = Popen(\"/home/.../nginx\", she... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008520995_python.txt |
Q:
Empty browser screen with python cgi
i need to display dynamic data in a graph in real time.
And so i need to draw a new graph with updated data every second.
The problem is that i cannot empty the previous output in the browser
and so instead of getting a simple graph with the updated data
i get lots of graphs
... | Empty browser screen with python cgi | i need to display dynamic data in a graph in real time.
And so i need to draw a new graph with updated data every second.
The problem is that i cannot empty the previous output in the browser
and so instead of getting a simple graph with the updated data
i get lots of graphs
here is the code. currently it has random ... | [
"I would create a separate CGI script for creating the image. You can then reference the new script in the image tag. src=\"makepic.py\".\nFollow this guide for making a Python script serve a dynamic image. On the page, you can use JavaScript's settimeout to refresh the image.\n",
"You could think about a page... | [
0,
0
] | [] | [] | [
"cgi",
"flush",
"python",
"real_time"
] | stackoverflow_0008522139_cgi_flush_python_real_time.txt |
Q:
Replace string in Python and open browser with result
I am trying to build a plugin for the program Sublimetext2.
It uses plugins coded with Python. I have no Python knowledge at all but from looking at existing plugins and my PHP knowledge here is what I need help with...
this is the start of the Python file s... | Replace string in Python and open browser with result | I am trying to build a plugin for the program Sublimetext2.
It uses plugins coded with Python. I have no Python knowledge at all but from looking at existing plugins and my PHP knowledge here is what I need help with...
this is the start of the Python file so far
import sublime, sublime_plugin
import webbrowser
set... | [
"Use\nos.system(\"path_to_browser url\")\n\nTo run any external program. I also recomend to take a look at this comment\n",
"Ok after many hours (I hate Python now) my solution (i'm very not impressed) but it partially works\n#Context.sublime-menu\n[\n { \"command\": \"openserver\", \"caption\": \"Open on Serv... | [
1,
0
] | [] | [] | [
"python",
"sublimetext"
] | stackoverflow_0008520038_python_sublimetext.txt |
Q:
how to determine what headers are necessary in form submission
I am writing a python script to collect a large amount of data, unfortunately this involves submitting a few web forms to get the information that I am interested in. Since this has to be repeated a few thousand times it makes sense to automate it.
I ... | how to determine what headers are necessary in form submission | I am writing a python script to collect a large amount of data, unfortunately this involves submitting a few web forms to get the information that I am interested in. Since this has to be repeated a few thousand times it makes sense to automate it.
I have never dealt with the forms aspect of this sort of thing so I ha... | [
"I'd recommend taking a look at the Mechanize module. It allows you to select a form, fill fields, select options, and click buttons. It automatically generates the form data that the form would have submitted in a normal browser.\nHere's a nice little tutorial/example: http://stockrt.github.com/p/emulating-a-brows... | [
0
] | [] | [] | [
"http",
"python",
"urllib2"
] | stackoverflow_0008522390_http_python_urllib2.txt |
Q:
HTTP POST request and headers with MIME attachments multipart/related and xop?
I'm trying to upload a bulk data exchange call to eBay using their FileTransfer API.
In order to do this, I've got to POST an xml request string to the eBay server but the xml
request contains a <Data> section that must include the data... | HTTP POST request and headers with MIME attachments multipart/related and xop? | I'm trying to upload a bulk data exchange call to eBay using their FileTransfer API.
In order to do this, I've got to POST an xml request string to the eBay server but the xml
request contains a <Data> section that must include the data you're transferring( in this case it's a base64 encoded zipfile containing another ... | [
"I figured out what was wrong with my request. It's a combination of constructing the request string and also the headers. I went with a much more organized and programmatic approach to it, and it worked.\nHere's what the section that builds the request string looks like:\n#########################################... | [
2
] | [] | [] | [
"ebay_lms",
"mime_types",
"python",
"xml",
"xop"
] | stackoverflow_0008482135_ebay_lms_mime_types_python_xml_xop.txt |
Q:
Python ctypes variable content issue
I am using the following DLL function
int ReadMemU32(long address , long *pdata)
i'm using it with ctypes byref like this:
read_data = c_ulong(0)
result = ReadMemU32(address, byref(read_data))
when i checked its value i notice this:
>>> read_data
c_ulong(55L)
>>> read_data =... | Python ctypes variable content issue | I am using the following DLL function
int ReadMemU32(long address , long *pdata)
i'm using it with ctypes byref like this:
read_data = c_ulong(0)
result = ReadMemU32(address, byref(read_data))
when i checked its value i notice this:
>>> read_data
c_ulong(55L)
>>> read_data == 55
False
>>> read_data == c_ulong(55L)
F... | [
"For your code, just use:\nread_data.value == 55\n\nThe motive why :\n>>> read_data == c_ulong(55L)\nFalse\n\nhappens is because ctyps does not implement proper Python comparison for C objects - it tests for object identity, as is the default. If you compare the \".value\" property of each object, though, you are f... | [
3
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0008522463_ctypes_python.txt |
Q:
How to temporary hide stdout or stderr while running a unittest in Python
I have a faulty third party python module that is outputing to stdout or stderr while it is imported and this is breaking the output of my unittests.
How can I temporary redirect the stdout in order to hide its output.
Limit to Python 2.5 sy... | How to temporary hide stdout or stderr while running a unittest in Python | I have a faulty third party python module that is outputing to stdout or stderr while it is imported and this is breaking the output of my unittests.
How can I temporary redirect the stdout in order to hide its output.
Limit to Python 2.5 syntax :)
Update, I forgot to mention that sys.stdout and sys.__stderr__ methods ... | [
"You can also use mock to let you patch sys.stdout and sys.stderr for you when the module is imported. An example of a testing module that using this strategy would be:\nimport os\ndevnull = open(os.devnull, 'w')\n\nfrom mock import patch\nwith patch('sys.stdout', devnull):\n with patch('sys.stderr', devnull):\n... | [
22,
19
] | [] | [] | [
"python"
] | stackoverflow_0008522689_python.txt |
Q:
python win32com Dispatch fails with 'CrystalRuntime.Application' (64bit issue)
The essential details here are as follows:
Windows Server 2008 64bit
Python26 64bit
Visual Studio 2008(Team) which installs Crystal Reports (both 32bit and 64bit runtimes)
My problem is the following code fails when Dispatch('CrystalR... | python win32com Dispatch fails with 'CrystalRuntime.Application' (64bit issue) | The essential details here are as follows:
Windows Server 2008 64bit
Python26 64bit
Visual Studio 2008(Team) which installs Crystal Reports (both 32bit and 64bit runtimes)
My problem is the following code fails when Dispatch('CrystalRuntime.Application') is called, this worked fine on same 32bit OS configuration of t... | [
"When I use py26 with Excel, I've found that this syntax works better.\nExcel_App = win32com.client.gencache.EnsureDispatch('Excel.Application')\n\nMaybe that can be altered to fit crystal reports..\nApp= win32com.client.gencache.EnsureDispatch('CrystalRuntime.Application')\n\n"
] | [
0
] | [] | [] | [
"64_bit",
"crystal_reports",
"python"
] | stackoverflow_0008523207_64_bit_crystal_reports_python.txt |
Q:
Does python twisted framework HttpClient access proxy?
I need to access a webpage using
twisted.web.client.getPage()
or a similar method to download a webpage from a known address (ie:www.google.com), the problem is: I am behind a proxy server and I couldn't find anywhere explanations on how to configure twisted ... | Does python twisted framework HttpClient access proxy? | I need to access a webpage using
twisted.web.client.getPage()
or a similar method to download a webpage from a known address (ie:www.google.com), the problem is: I am behind a proxy server and I couldn't find anywhere explanations on how to configure twisted or factories to use my proxy, any ideas?
Bear in mind I have... | [
"from twisted.internet import reactor\nfrom twisted.web import client\n\ndef processResult(page):\n print \"I got some data\", repr(page)\n reactor.callLater(0.1, reactor.stop)\ndef dealWithError(err):\n print err.getErrorMessage()\n reactor.callLater(0.1, reactor.stop)\n\nclass ProxyClientFactory(clien... | [
3,
1,
1,
0
] | [] | [] | [
"networking",
"proxy",
"python",
"twisted"
] | stackoverflow_0001651527_networking_proxy_python_twisted.txt |
Q:
How do I get multiple user inputs in python?
Hi I got the following problem, I'm trying to build a program that reads a txt file that contains lines with name of fruits and their respective base prices as the following example:
apple $ 2.00
pearl $ 4.00
guava $ 2.50
and so it goes on.
Yesterday I had some help ... | How do I get multiple user inputs in python? | Hi I got the following problem, I'm trying to build a program that reads a txt file that contains lines with name of fruits and their respective base prices as the following example:
apple $ 2.00
pearl $ 4.00
guava $ 2.50
and so it goes on.
Yesterday I had some help with people here and I've learned how to make pyth... | [
"mult_by = int(raw_input('gimme a number for something: '))\n\ntry and familiarize yourself with the basic built in functions, should be helpful.\nhttp://docs.python.org/library/functions.html\n"
] | [
1
] | [] | [] | [
"python",
"string",
"text_files"
] | stackoverflow_0008523535_python_string_text_files.txt |
Q:
Clear selection when clicking on blank area of Item View
I made a tree structure with QTreeWidget, and it works well. But I have a problem with that. Commonly, with a tree structure, if I want to deselect all, I click on a blank area of the tree-widget. But QTreeWidget does not seem to support that (or I can't fin... | Clear selection when clicking on blank area of Item View | I made a tree structure with QTreeWidget, and it works well. But I have a problem with that. Commonly, with a tree structure, if I want to deselect all, I click on a blank area of the tree-widget. But QTreeWidget does not seem to support that (or I can't find out how).
Could sub-classing or something else solve the pro... | [
"The example code below will clear the selection (and current item) when clicking on a blank area, or when pressing Esc when the tree widget has the keyboard focus. It will work with any widget which inherits QAbstractItemView (not just QTreeWidget):\nclass MyWidget(QTreeWidget):\n def keyPressEvent(self, event)... | [
9
] | [] | [] | [
"pyqt",
"python",
"qabstractitemview",
"qtreewidget",
"selection"
] | stackoverflow_0008516163_pyqt_python_qabstractitemview_qtreewidget_selection.txt |
Q:
Catching exceptions in django templates
I'm using a template tag in a Django template (the tag is thumbnail) and it's throwing an exception that makes the template fail with a 500 error. I would like to stop this from happening, as I don't have complete control over the source images that sporadically trigger this... | Catching exceptions in django templates | I'm using a template tag in a Django template (the tag is thumbnail) and it's throwing an exception that makes the template fail with a 500 error. I would like to stop this from happening, as I don't have complete control over the source images that sporadically trigger this exception, and use a blank/placeholder image... | [
"The way I've always handled this is to push it up to the model layer. So in your model:\n class MyImageModel(model.Model):\n # model fields go here..\n\n def get_url(self):\n try:\n # or whatever causes the exception\n return self.url\n except IOE... | [
17,
0
] | [] | [] | [
"django",
"django_templates",
"exception",
"python"
] | stackoverflow_0008524077_django_django_templates_exception_python.txt |
Q:
python error when insert data
table x_giolam:
class x_giolam(osv.osv):
_name = 'x_giolam'
_description = 'Gio Lam'
_columns = {
'name': fields.integer('Lọai',size=64,required="true"),
'giolam' : fields.float('Gio lam',size=64,required="True"),
... | python error when insert data | table x_giolam:
class x_giolam(osv.osv):
_name = 'x_giolam'
_description = 'Gio Lam'
_columns = {
'name': fields.integer('Lọai',size=64,required="true"),
'giolam' : fields.float('Gio lam',size=64,required="True"),
'time_in': fields.char... | [
"It seems that some how the self.browse() method returns the obj that have no ma_luong property.\nI suggest to put some debug output after obj=… before values=… eg print dir(obj).\n"
] | [
0
] | [] | [] | [
"openerp",
"python"
] | stackoverflow_0008524018_openerp_python.txt |
Q:
Working with dictionaries, how would you find/track duplicate GUIDs given this list?
I work a lot with WiX XML files and just about every object in WiX requires a GUID. To avoid copy-paste errors, I've set about on a way to sort and display all duplicate GUIDs given a list like this (created with find and egrep):... | Working with dictionaries, how would you find/track duplicate GUIDs given this list? | I work a lot with WiX XML files and just about every object in WiX requires a GUID. To avoid copy-paste errors, I've set about on a way to sort and display all duplicate GUIDs given a list like this (created with find and egrep):
./A2.Spam.EggsMgrSvc/__A2.Spam.EggsMgrSvc.wixproj:3A206536-FBCC-4911-AF2B-CBCD76E2C23E
./... | [
"I'd do it something like this, although I haven't actually tested this code:\n#!/usr/bin/env python\n\nimport collections\nimport operator\n\nguids = collections.defaultdict(collections.Counter)\nf_and_g = open('files-and-guids.txt', 'r')\n\nfor fg in f_and_g:\n fname, guid = map(str.strip, fg.split(':'))\n\n ... | [
2,
2,
0
] | [] | [] | [
"dictionary",
"guid",
"python"
] | stackoverflow_0008455394_dictionary_guid_python.txt |
Q:
Ending a While Loop if a Condition is Not Met
I am trying to end a while loop if a condition is not met.
The purpose of this code is to get the most out of a multiple subjects without going over the maximum hours of work a student is willing to put in.
I have created a dictionary called "subjects" which maps out a... | Ending a While Loop if a Condition is Not Met | I am trying to end a while loop if a condition is not met.
The purpose of this code is to get the most out of a multiple subjects without going over the maximum hours of work a student is willing to put in.
I have created a dictionary called "subjects" which maps out a certain subject to (value, work) with value as how... | [
"Adding done = True after the last for loop should be sufficient, but your code has other problems.\nThe while loop is totally unnecessary. If you remove it, the code should work as desired.\nYou've also got three loops based on the number of subjects, so your total iterations (withou the while) is going to be the ... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008524078_python.txt |
Q:
Loading Matlab sparse matrix saved with -v7.3 (HDF5) into Python and operating on it
I'm new to python, coming from matlab. I have a large sparse matrix saved in matlab v7.3 (HDF5) format. I've so far found two ways of loading in the file, using h5py and tables. However operating on the matrix seems to be extremel... | Loading Matlab sparse matrix saved with -v7.3 (HDF5) into Python and operating on it | I'm new to python, coming from matlab. I have a large sparse matrix saved in matlab v7.3 (HDF5) format. I've so far found two ways of loading in the file, using h5py and tables. However operating on the matrix seems to be extremely slow after either. For example, in matlab:
>> whos
Name Size ... | [
"Most of your problem is that you're using python sum on what's effectively a memory-mapped array (i.e. it's on disk, not in memory). \nFirst off, you're comparing the time it takes to read things from disk to the time it takes to read things in memory. Load the array into memory first, if you want to compare to ... | [
3,
2,
0
] | [] | [] | [
"hdf5",
"matlab",
"python",
"sparse_array",
"sparse_matrix"
] | stackoverflow_0008403144_hdf5_matlab_python_sparse_array_sparse_matrix.txt |
Q:
Django - Rating on Multiple Criteria: Model Formset?
I have a content that I'd like to rate on multiple criteria.
Imagine this kind of model:
class Content(models.Model):
name = models.CharField(max_length=50)
class Criteria(models.Model):
name = models.CharField(max_length=50)
content = models.ForeignKey(C... | Django - Rating on Multiple Criteria: Model Formset? | I have a content that I'd like to rate on multiple criteria.
Imagine this kind of model:
class Content(models.Model):
name = models.CharField(max_length=50)
class Criteria(models.Model):
name = models.CharField(max_length=50)
content = models.ForeignKey(Content)
class ContRate(models.Model):
user = models.For... | [
"I would use a model formset for this kind of problem although you are not going to use my_formset.is_valid() nor my_formset.save() but because it ease the forms construction in the view and the render in the template. \nNo need to worry with the form prefixes etc.\nYour Ajax call on the onclick event (fired by a c... | [
1
] | [] | [] | [
"django",
"django_forms",
"python",
"rating"
] | stackoverflow_0008520861_django_django_forms_python_rating.txt |
Q:
'Module' object is not callable
I am new to python and django and having trouble doing a math function in my model.py file.
class Orders(models.Model):
...
total = models.DecimalField(
max_digits = 6,
decimal_places = 2,
... | 'Module' object is not callable | I am new to python and django and having trouble doing a math function in my model.py file.
class Orders(models.Model):
...
total = models.DecimalField(
max_digits = 6,
decimal_places = 2,
null = True,
... | [
"The error is because you used\nship_rate = decimal(0.12)\n\nThis should be\nship_rate = decimal.Decimal(0.12)\n\ndecimal is the name of the module. You can't call a module, that's what the error message says. The reason for the strange traceback you got is that the module source and the code in memory got out of... | [
7,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008523963_django_python.txt |
Q:
Readline feature in Directory Lister class
The below class is a dynamic attribute generating directory walker by Anurag.
import os
class DirLister(object):
def __init__(self, root):
self.root = root
self._list = None
def __getattr__(self, name):
try:
var = super(DirLis... | Readline feature in Directory Lister class | The below class is a dynamic attribute generating directory walker by Anurag.
import os
class DirLister(object):
def __init__(self, root):
self.root = root
self._list = None
def __getattr__(self, name):
try:
var = super(DirLister).__getattr__(self, name)
return ... | [
"You should be able to accomplish this by checking to see if self.root is a file or a directory in _load(). Read the first line if it is a file and do os.listdir() if it is a directory. Try the following:\nimport os\n\nclass DirLister(object):\n def __init__(self, root):\n self.root = root\n self... | [
2
] | [] | [] | [
"attributes",
"file",
"instances",
"os.walk",
"python"
] | stackoverflow_0008524311_attributes_file_instances_os.walk_python.txt |
Q:
Django Flowchart Model
Is anyone aware of a Django app for designing and storing flowcharts in a database? After searching for variations of "Django flowcharts", I've only found flowcharts of Django's internal design, not anything about authoring or storing flowcharts in a Django webapp.
As asked in a similar ques... | Django Flowchart Model | Is anyone aware of a Django app for designing and storing flowcharts in a database? After searching for variations of "Django flowcharts", I've only found flowcharts of Django's internal design, not anything about authoring or storing flowcharts in a Django webapp.
As asked in a similar question, I've found several imp... | [
"Why couldn't you do it yourself? The behavior and presentation is already implemented in the several truly impressive JavaScript libraries you've referenced, now all that's left to be done is to store the models in the database for your favorite pick you'd like to persist through Django.\nThere is a library that i... | [
1,
1,
0
] | [] | [] | [
"django",
"django_models",
"flowchart",
"python"
] | stackoverflow_0008509391_django_django_models_flowchart_python.txt |
Q:
numpy.insert troubles
I am trying to insert nans at certain indices.
import numpy
z = numpy.array([1., 1., 0., 0., 0., 2., 3., 4., 5., 6., 0., 7., 8., 9.])
a = z[z!=0]
# Some processing magic happens to a but stays the same shape
b = numpy.argwhere(z == 0).flatten()
c = numpy.insert(a, b, numpy.nan)
I would like... | numpy.insert troubles | I am trying to insert nans at certain indices.
import numpy
z = numpy.array([1., 1., 0., 0., 0., 2., 3., 4., 5., 6., 0., 7., 8., 9.])
a = z[z!=0]
# Some processing magic happens to a but stays the same shape
b = numpy.argwhere(z == 0).flatten()
c = numpy.insert(a, b, numpy.nan)
I would like the result to be:
[1, 1, n... | [
"The following will do it:\nnumpy.insert(a, b-numpy.arange(len(b)), numpy.nan)\n\nHere is a complete ipython session with your example:\nIn [87]: import numpy\n\nIn [88]: z = numpy.array([1., 1., 0., 0., 0., 2., 3., 4., 5., 6., 0., 7., 8., 9.])\n\nIn [89]: a = z[z!=0]\n\nIn [90]: b = numpy.argwhere(z == 0).flatten(... | [
4
] | [] | [] | [
"insert",
"numpy",
"python"
] | stackoverflow_0008524585_insert_numpy_python.txt |
Q:
Pygame bouncing ball
So I am very new to pygame and I am trying to create a few different slides, like 6 or so of a ball bouncing. Each one of them will have the ball at a different height off the ground and what not. I have been trying to figure out how to start this. I don't really know how to combine a bunc... | Pygame bouncing ball | So I am very new to pygame and I am trying to create a few different slides, like 6 or so of a ball bouncing. Each one of them will have the ball at a different height off the ground and what not. I have been trying to figure out how to start this. I don't really know how to combine a bunch of different slides to c... | [
"If your trying to make an animation sort of thing then just simply load the 6 pictures, put them into a list and count through the list blitting as you go.\nimport pygame\n\nscreen = pygame.display.set_mode((500, 500))\n\npic1 = pygame.image.load(\"pic1.png\")\npic2 = pygame.image.load(\"pic2.png\")\npic3 = pygame... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0008442178_pygame_python.txt |
Q:
Migrate App engine python application to Appscale platform
How can I migrate a complete App Engine Python application to AppScale on Amazon EC2?
I need to migrate all datastore records, cron jobs, TaskQueues and indexes.
A:
Data can be downloaded via the bulk downloader/uploader from GAE. See this document on ho... | Migrate App engine python application to Appscale platform | How can I migrate a complete App Engine Python application to AppScale on Amazon EC2?
I need to migrate all datastore records, cron jobs, TaskQueues and indexes.
| [
"Data can be downloaded via the bulk downloader/uploader from GAE. See this document on how to upload data to AppScale: https://github.com/AppScale/appscale/wiki/Uploading-and-downloading-data-%28bulkloader%29\nAppScale Systems provides much faster migration tools as well.\nCron jobs and taskqueues are supported in... | [
3
] | [] | [] | [
"amazon_ec2",
"appscale",
"google_app_engine",
"migration",
"python"
] | stackoverflow_0008520321_amazon_ec2_appscale_google_app_engine_migration_python.txt |
Q:
Comment conventions in python
It seems like you can use both '''comments...''' and """comments...""" for multi-line comments. Is there any substantive difference between the two, or is it just a matter of preference?
A:
These are not comments, they are docstrings. Python allows you to define multi-line strings ... | Comment conventions in python | It seems like you can use both '''comments...''' and """comments...""" for multi-line comments. Is there any substantive difference between the two, or is it just a matter of preference?
| [
"These are not comments, they are docstrings. Python allows you to define multi-line strings using triplets of either apostrophes or quotation marks, but PEP 257 recommends using the quotation marks with docstrings for consistency. It has no effect on the contents of the string, however.\n",
"It's a matter of pre... | [
8,
1
] | [] | [] | [
"comments",
"python"
] | stackoverflow_0008525386_comments_python.txt |
Q:
How can you parse xml in Google Refine using jython/python ElementTree
I trying to parse some xml in Google Refine using Jython and ElementTree but I'm struggling to find any documentation to help me getting this working (probably not helped by not being a python coder)
Here's an extract of the XML I'm trying to p... | How can you parse xml in Google Refine using jython/python ElementTree | I trying to parse some xml in Google Refine using Jython and ElementTree but I'm struggling to find any documentation to help me getting this working (probably not helped by not being a python coder)
Here's an extract of the XML I'm trying to parse. I'm trying to return a joined string of all the dc:indentifier:
<oai_d... | [
"You've used the wrong namespace. This works on Jython 2.5.1:\nfrom xml.etree import ElementTree as ET\nelement = ET.fromstring(value) # `value` is a string with the xml from question\n\nnamespace = \"{http://purl.org/dc/elements/1.1/}\"\nfor e in element.getiterator(namespace+'identifier'):\n print e.text\n\nOu... | [
2,
2,
0
] | [] | [] | [
"google_refine",
"jython",
"python",
"xml_parsing"
] | stackoverflow_0008513709_google_refine_jython_python_xml_parsing.txt |
Q:
Django - Inline (has no ForeignKey to)
I'm trying to implement InlineModels but I'm getting error message. Will you please help me? Thank you .
myproject.api.models
from django.db import models
from django.contrib.auth.models import User
from myproject.song.models import Album, Song, Artist
class UserLibrary(mode... | Django - Inline (has no ForeignKey to) | I'm trying to implement InlineModels but I'm getting error message. Will you please help me? Thank you .
myproject.api.models
from django.db import models
from django.contrib.auth.models import User
from myproject.song.models import Album, Song, Artist
class UserLibrary(models.Model):
user = models.ForeignKey(User... | [
"You've built the wrong relationship--your Song model should have a foreign key relationship to the UserLibrary model, not the other way around. Other than that, everything seems to be correct.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008526159_django_python.txt |
Q:
Performing GLM within python script on windows 7 64
I'm trying to perform GLM (Generalized linear model) repeatedly within a python script (within a loop).
1- I tried to use Stats within Scipy glm function but description is quite inexistant and I think I did not use it well --> error message "ValueError: only tte... | Performing GLM within python script on windows 7 64 | I'm trying to perform GLM (Generalized linear model) repeatedly within a python script (within a loop).
1- I tried to use Stats within Scipy glm function but description is quite inexistant and I think I did not use it well --> error message "ValueError: only ttest_ind implemented". I searched within stats.py file and ... | [
"I don't know why the answers here seem to indicate that statsmodels test coverage for GLM is not that good. I wrote the tests. The models are verified against Stata, R, and SAS. They're pretty comprehensive. If you find something unexpected or this not to be the case then please report it to developers.\nhttps://g... | [
5,
1
] | [
"I answer at me:\nstatsmodels are not developed and tested enough to be employed, so DO NOT USE STATSMODELS in its current version to perform GLM --> rpy2 is appropriate but need some complicated install (copy into /Pythonxx/Lib/site-packages/ folders extracted from rpy2 tar and get 'nose' and copy it at the same p... | [
-2
] | [
"glm",
"python",
"r",
"scipy",
"windows"
] | stackoverflow_0004024972_glm_python_r_scipy_windows.txt |
Q:
insert image in text widget without using imageTK
Unfortunately I'm developing under a osx machine where I've been unable to install imageTK...
I need to insert an image taken from a dictionary of images, saved thus:
i = open(filename, 'rb')
i.seek(0)
w = i.read()
i.close()
allicons[d]=w
so at insert time I don't... | insert image in text widget without using imageTK | Unfortunately I'm developing under a osx machine where I've been unable to install imageTK...
I need to insert an image taken from a dictionary of images, saved thus:
i = open(filename, 'rb')
i.seek(0)
w = i.read()
i.close()
allicons[d]=w
so at insert time I don't have a filename, just the dict.
with imageTk, this wor... | [
"PhotoImage has a 'data' option. You can supply it with gif data that's been encoded using base64. something like:\ndat = base64.encodestring(allicons[key])\npic = PhotoImage(data=dat)\n...\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008443174_python_tkinter.txt |
Q:
Determining Betweenness Centrality With The Igraph Library
I am a very, very mediocre programmer, but I still aim to use the igraph python library to determine the effect of a user's centrality in a given forum to predict his later contributions to that forum.
I got in touch with someone else who used the NetworkX... | Determining Betweenness Centrality With The Igraph Library | I am a very, very mediocre programmer, but I still aim to use the igraph python library to determine the effect of a user's centrality in a given forum to predict his later contributions to that forum.
I got in touch with someone else who used the NetworkX library to do something similar, but given the current size of ... | [
"So, for the sake of clarity, the following eventually proved to do the trick:\nimport igraph\nimport sys, csv\n\nfrom igraph import *\nfrom itertools import izip\n\ngraph = Graph.Read_GML(\"C:\\stack.gml\")\n\nprint igraph.summary(graph)\n\nmy_id_to_igraph_id = dict((v, k) for k, v in enumerate(graph.vs[\"id\"]))\... | [
2,
1
] | [] | [] | [
"igraph",
"python"
] | stackoverflow_0008196922_igraph_python.txt |
Q:
PyQT/PySide vs PyObjC: worth it?
I'm thinking of creating a cross platform app, but I want it to look as natively as possible on OS X, is PyObjC a good choice? How easy is it? In contrast, how good is QT when it comes to looking native?
A:
I'm not quite sure if my answer is in your request. But let me say one th... | PyQT/PySide vs PyObjC: worth it? | I'm thinking of creating a cross platform app, but I want it to look as natively as possible on OS X, is PyObjC a good choice? How easy is it? In contrast, how good is QT when it comes to looking native?
| [
"I'm not quite sure if my answer is in your request. But let me say one thing - take a look at Route Buddy which is developed in Qt for OSX and it is a good example that ii is sometimes hard to distinguish if it's a native Cocoa application or not. \nAnother - but bad - example is SlickEdit , which has IMO a quite ... | [
3
] | [] | [] | [
"pyobjc",
"pyqt",
"pyside",
"python"
] | stackoverflow_0008526201_pyobjc_pyqt_pyside_python.txt |
Q:
Beautifulsoup parse through poor tags
My understanding is that regex is the poor man's approach to dealing with beautifulsoup, but I was wondering if it's my only option if there aren't well defined tags in the html I'm trying to parse?
I'm ultimately just trying to get some simple data from the html...but it's ju... | Beautifulsoup parse through poor tags | My understanding is that regex is the poor man's approach to dealing with beautifulsoup, but I was wondering if it's my only option if there aren't well defined tags in the html I'm trying to parse?
I'm ultimately just trying to get some simple data from the html...but it's just in a series of tables that look like thi... | [
"You can also do this with lxml instead of beautifulsoup. I switched over to using lxml.html instead of beautifulsoup because of the cssselect() method. It takes css rules just like you would use in a css file or jQuery.\nfrom lxml.html import fromstring\n\nraw_html_data = \"\"\" ... your html data here ... \"\"\... | [
2,
0
] | [
"The lxml people claim to work well with malformed HTML.\n"
] | [
-1
] | [
"beautifulsoup",
"python"
] | stackoverflow_0008525624_beautifulsoup_python.txt |
Q:
linking between two modules with distutils
I have recently exposed a problem when working with several compiled C++ modules and would like to rephrase the question.
I have two modules 'mod1' and 'mod2'. They are compiled as two distinct 'ext_modules' in my setup.py, as shown here :
#!/usr/bin/python2
from setupto... | linking between two modules with distutils | I have recently exposed a problem when working with several compiled C++ modules and would like to rephrase the question.
I have two modules 'mod1' and 'mod2'. They are compiled as two distinct 'ext_modules' in my setup.py, as shown here :
#!/usr/bin/python2
from setuptools import setup, Extension
mod1 = Extension('m... | [
"In the end, I could not find how to do that with distutils / distribute. So I switched to cmake, and so far it works flawlessly !\nwith cmake, you can easily compile one module as a shared library, and later add this shared library to the dependencies of another module.\n",
"If your mod2 depend of mod1, then, im... | [
1,
0
] | [] | [] | [
"bjam",
"boost_python",
"python"
] | stackoverflow_0008455830_bjam_boost_python_python.txt |
Q:
Data recognition, parsing, filtering, and transformation -- GUI?
Looking for a non-cloud based open source app for doing data transformation; though for a killer (and I mean killer) app just built for data transformations, I might be willing to spend up to $1000.
I've looked at Perl, Kapow Katalyst, Pentaho Kettle... | Data recognition, parsing, filtering, and transformation -- GUI? | Looking for a non-cloud based open source app for doing data transformation; though for a killer (and I mean killer) app just built for data transformations, I might be willing to spend up to $1000.
I've looked at Perl, Kapow Katalyst, Pentaho Kettle, and more.
Perl, Python, Ruby which are clearly languages, but unable... | [
"Google Refine?\n",
"Talend will need more than 5 minutes of your time, perhaps closer to about 1 hour to begin to wire up a basic transformations and being able to fulfill your requirement to keep versioned control transformations as well. You described a Pipeline process that can be done easily in Talend when ... | [
3,
2,
1
] | [] | [] | [
"data_manipulation",
"kettle",
"perl",
"python",
"ruby"
] | stackoverflow_0004341756_data_manipulation_kettle_perl_python_ruby.txt |
Q:
How to use dictionary to evaluate input of two variables in python
Inititally what I would like to do is convert two variables into a value and key and then use them to evaluate against a constant dictionary.
Desired output:
Enter your task: framing
Enter (LF) Linear Feet: 1200
Framing job is estimated at $7,800... | How to use dictionary to evaluate input of two variables in python | Inititally what I would like to do is convert two variables into a value and key and then use them to evaluate against a constant dictionary.
Desired output:
Enter your task: framing
Enter (LF) Linear Feet: 1200
Framing job is estimated at $7,800
class Lookup(dict):
"""
a dictionary class which can lookup val... | [
"If you need a dictionary that goes both ways, use two dictionaries.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008526900_python.txt |
Q:
What is 'size' in pymongo's Cursor.batch_size(size)?
From version 1.9, pymongo added the option to change the batch size of a cursor operation See description here.
But they don't say anywhere what this size is supposed to mean. Is this the number of records to fetch at a time? Or is this absolute size?
Also, wha... | What is 'size' in pymongo's Cursor.batch_size(size)? | From version 1.9, pymongo added the option to change the batch size of a cursor operation See description here.
But they don't say anywhere what this size is supposed to mean. Is this the number of records to fetch at a time? Or is this absolute size?
Also, what is the default size for the cursor? I checked __dict__ f... | [
"The batch size refers to the number of results that are retrieved with the cursor before issuing a getMore message to fetch more results. The default is 101 documents.\nEdit:\nSorry, I should clarify - the default is actually set by the server, but as of the current latest release it is 101.\n"
] | [
4
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0008526926_mongodb_pymongo_python.txt |
Q:
django dynamic file serving optimization
I am working on a django project that provides an API to generate thumbnails of images, and the basic logic is like the following:
when the source image URL comes for the first time, the django would do some sort of image manipulation, and return the thumbnail image
when t... | django dynamic file serving optimization | I am working on a django project that provides an API to generate thumbnails of images, and the basic logic is like the following:
when the source image URL comes for the first time, the django would do some sort of image manipulation, and return the thumbnail image
when the same image URL comes again, django would si... | [
"The simplest solution of the top of my head would be to use an Apache rewrite rule with a condition.\nRewriteCond %(REQUEST_URI) ^media\nRewriteCond %{REQUEST_FILENAME} !-f \nRewriteRule #Some rewrite rule to redirect from '/media/filename' to '/image_generator/filename'\n\nThis basically just checks to see whethe... | [
2,
0,
0
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0008514467_apache_django_python.txt |
Q:
Python gzip - extracting .csv.gz file - memory error
I tried to write a script to access a .csv.gz file from a ftp server and write the contents to a .csv file back on the same server. This method seems to work fine as long as the file is less than 100mb, over that it fails, giving a memory error. I wasn't able to... | Python gzip - extracting .csv.gz file - memory error | I tried to write a script to access a .csv.gz file from a ftp server and write the contents to a .csv file back on the same server. This method seems to work fine as long as the file is less than 100mb, over that it fails, giving a memory error. I wasn't able to find a way to just extract the .csv file so it reads the ... | [
"Right now you are reading in the whole file at once, which is fine for small files but (obviously) causes problems if you have a lot of data. Since you are dealing with the file line-by-line, you can use the built-in Python iterators for files/csvfiles. These are typically implemented as lazy, meaning they only re... | [
2
] | [] | [] | [
"extraction",
"gzip",
"memory",
"memory_efficient",
"python"
] | stackoverflow_0008527063_extraction_gzip_memory_memory_efficient_python.txt |
Q:
Printing a Data Structure
I'm programming a Sudoku solver, and as part of that I'm creating a class to represent a Sudoku board. Part of the functionality of the class is the ability to print itself. Right now I have a method PrintBoard as part of my class. So I would use it like this:
myBoard.PrintBoard()
But I ... | Printing a Data Structure | I'm programming a Sudoku solver, and as part of that I'm creating a class to represent a Sudoku board. Part of the functionality of the class is the ability to print itself. Right now I have a method PrintBoard as part of my class. So I would use it like this:
myBoard.PrintBoard()
But I was thinking; is there a way to... | [
"Yes. Have a look at the __str__ method.\nYou can also use the __repr__ method, but as stated in the documentation:\n\nIf at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).\n\nFrom your description, that ... | [
8,
2
] | [] | [] | [
"python"
] | stackoverflow_0008527386_python.txt |
Q:
Use a dictionary to handle variables
i want to know if it is possible to handle variables through a dictionary.
Example:
global MyVar
...
MyVar = 0xFFFF
d={"MyVar":MyVar}
def ChangeVar (var_to_change, value)
d[var_to_change] = value #I know this code assigns a new value to the key...
...
ChangeVar("MyVar",25)
..... | Use a dictionary to handle variables | i want to know if it is possible to handle variables through a dictionary.
Example:
global MyVar
...
MyVar = 0xFFFF
d={"MyVar":MyVar}
def ChangeVar (var_to_change, value)
d[var_to_change] = value #I know this code assigns a new value to the key...
...
ChangeVar("MyVar",25)
...
I want to use the dictionary to "select... | [
"Yes, I think @JBernardo has the right idea.\nAfter staring at your code a while to try & figure out what exactly you were trying to do:\nYou are trying to create a dictionary of all the variable names, and use that dictionary as a lookup table for changing values?\nhttp://docs.python.org/library/functions.html#glo... | [
1,
1,
0
] | [] | [] | [
"dictionary",
"pointers",
"python"
] | stackoverflow_0008527135_dictionary_pointers_python.txt |
Q:
imports & pathnames on windows
newbie Python question, 2.7.2 on Windows XP
I saved a one-line hello.py file [print "hello there"] in the current directory.
At the command prompt I use import to run the command
>>> import hello
hello there
ok - that's fine.
But what do you type if hello.py were in a subfolder ... | imports & pathnames on windows | newbie Python question, 2.7.2 on Windows XP
I saved a one-line hello.py file [print "hello there"] in the current directory.
At the command prompt I use import to run the command
>>> import hello
hello there
ok - that's fine.
But what do you type if hello.py were in a subfolder of the current directory called "tem... | [
"Assuming this is your directory structure:\ncurrentdir\n /tempFolder\n hello.py\n\nShort Answer:\nYou should have a __init__.py in your directory of import.\nSo it should look like:\ncurrentdir\n /tempFolder\n __init__.py\n hello.py\n\nNote: the __init__.py could be blank. There is no ha... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008527204_python.txt |
Q:
Python minidom element.data only returns object, not text
I am fairly new to Python and am just trying to parse the results of a simple Web-API that returns the following XML-Syntax:
<rss version='2.0'>
<channel>
<title>www.onlinetvrecorder.com</title>
<description>OTR Torrents</description>
<link>http://www.onli... | Python minidom element.data only returns object, not text | I am fairly new to Python and am just trying to parse the results of a simple Web-API that returns the following XML-Syntax:
<rss version='2.0'>
<channel>
<title>www.onlinetvrecorder.com</title>
<description>OTR Torrents</description>
<link>http://www.onlinetvrecorder.com/</link>
<copyright>OTR</copyright>
<STATIONS>
... | [
"Seems to work OK to me. You get a DOM element object, which works as a string in most contexts. So, print x[0] etc. (where x is the return value from your function) will generally get you the results you seek.\nIf you just want a list of the station names as strings, then convert them to strings (XML is Unicode or... | [
0
] | [] | [] | [
"minidom",
"python",
"xml_parsing"
] | stackoverflow_0008527244_minidom_python_xml_parsing.txt |
Q:
Python Mechanize won't open these sites
I'm working with Python's Mechanize module. I've come across 3 different sites that cannot be opened by mechanize directly:
en.wikipedia.org/wiki/Dog (new user, can't post more than 2 links T-T )
https://www.google.com/search?num=100&hl=en&site=&q=dog&oq=dog&aq=f&aqi=g10&aq... | Python Mechanize won't open these sites | I'm working with Python's Mechanize module. I've come across 3 different sites that cannot be opened by mechanize directly:
en.wikipedia.org/wiki/Dog (new user, can't post more than 2 links T-T )
https://www.google.com/search?num=100&hl=en&site=&q=dog&oq=dog&aq=f&aqi=g10&aql=1&gs_sm=e&gs_upl=618l914l0l1027l3l2l0l0l0l0... | [
"In the case of the cpsc.gov site, it looks like there's a refresh header that isn't being correctly processed by mechanize HTTPRefreshProcessor. However, you can workaround the problem as follows:\nimport mechanize\n\nurl = 'http://www.cpsc.gov/cpscpub/prerel/prhtml03/03059.html'\nbr = mechanize.Browser()\nbr.set_... | [
15
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0008527862_mechanize_python.txt |
Q:
load parameters from a file in Python
I am writing a Python class to model a process and I want to initialized the parameters from a file, say 'input.dat'. The format of the input file looks like this.
'input.dat' file:
Z0: 0 0
k: 0.1
g: 1
Delta: 20
t_end: 300
The code I wrote is the following. It works but appea... | load parameters from a file in Python | I am writing a Python class to model a process and I want to initialized the parameters from a file, say 'input.dat'. The format of the input file looks like this.
'input.dat' file:
Z0: 0 0
k: 0.1
g: 1
Delta: 20
t_end: 300
The code I wrote is the following. It works but appears redundant and inflexible. Is there a bet... | [
"Assuming the params are coming from a safe place (made by you or users, not the internet), just make the parameters file a Python file, params.py:\nZ0 = (0, 0)\nk = 0.1\ng = 1\nDelta = 20\nt_end = 300\n\nThen in your code all you need is:\nimport params\nfancy_calculation(10, k=params.k, delta=params.Delta)\n\nThe... | [
35,
20,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"file",
"input",
"python",
"serialization"
] | stackoverflow_0008525765_file_input_python_serialization.txt |
Q:
values of an array set to 0
I wrote this function (used later to select elite species in the genetic algorithm) to select k best values out of n, where not all n values are unique. First of all, I'd massively appreciate any comments to the code, but I'm primarily concerned with the fact that for some reason values... | values of an array set to 0 | I wrote this function (used later to select elite species in the genetic algorithm) to select k best values out of n, where not all n values are unique. First of all, I'd massively appreciate any comments to the code, but I'm primarily concerned with the fact that for some reason values in second vector (var2) are also... | [
"You are just giving var1 the alias var2. They both point to the same content.\nYou must copy the content over to a new object.\nIn [1]: x = numpy.arange(5)\n\nIn [2]: x\nOut[2]: array([0, 1, 2, 3, 4])\n\nIn [3]: y = x.copy()\n\nIn [4]: x[:] = 0\n\nIn [5]: x\nOut[5]: array([0, 0, 0, 0, 0])\n\nIn [6]: y\nOut[6]: arr... | [
4
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008528335_numpy_python.txt |
Q:
Unable to make a factorial function in Python
My code
import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
I get the error
File "factorial.py", line 5
if number == 0
^
SyntaxE... | Unable to make a factorial function in Python | My code
import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
I get the error
File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
How can you make a factorial ... | [
"The line that your error is on should read\nif number == 0:\n\nNote the colon on the end.\nAdditionally, you would need to add the same colon after the else and the for. The colons work similarly to {} in other languages.\nFinally, thats not how for loops work in Python. The code you want to use that list would be... | [
12,
9,
8,
3,
2,
1
] | [] | [] | [
"factorial",
"python"
] | stackoverflow_0001041348_factorial_python.txt |
Q:
Isolate Facebook URL user ID from the URL with python regex
okay i found this regex from Stack overflow, which can isolate the URL and ID, but when ever i tried to use it in app engine (py) an error popup saying "nothing to repeat, i know theres a bug in Python regarding this regex repeating, can anyone fix this? ... | Isolate Facebook URL user ID from the URL with python regex | okay i found this regex from Stack overflow, which can isolate the URL and ID, but when ever i tried to use it in app engine (py) an error popup saying "nothing to repeat, i know theres a bug in Python regarding this regex repeating, can anyone fix this? tx
File "C:\Program Files\Python27\lib\re.py", line 244, in _co... | [
"There is a urlparse module to parse url.\nThe urlparse module is renamed to urllib.parse in Python 3.0.\n$ python\n>>> from urlparse import urlparse\n>>> urlparse('http://www.facebook.com/hello/world.php?id=789')\nParseResult(scheme='http', netloc='www.facebook.com', path='/hello/world.php', params='', query='id=7... | [
7,
0
] | [] | [] | [
"google_app_engine",
"python",
"regex"
] | stackoverflow_0008527448_google_app_engine_python_regex.txt |
Q:
what is wrong in networkx installation
This is my first time do programming; i have a project that requires netwok analysis.
I downloaded networkx 1.6 and tried out the blockmodel, i got this error message:
Traceback (most recent call last):
File "C:\Users\dell\Desktop\Research Project\python\blockmodel.py", lin... | what is wrong in networkx installation | This is my first time do programming; i have a project that requires netwok analysis.
I downloaded networkx 1.6 and tried out the blockmodel, i got this error message:
Traceback (most recent call last):
File "C:\Users\dell\Desktop\Research Project\python\blockmodel.py", line 52, in <module>
G=nx.read_edgelist("ha... | [
"You need the data file hartford_drug.edgelist which you can get from here:http://networkx.lanl.gov/hg/networkx/raw-file/bec267f40c83/examples/algorithms/hartford_drug.edgelist\n"
] | [
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0008528430_networkx_python.txt |
Q:
auto detect file in a folder
Sorry wasn't sure how to best word this question.
My scenario is that I have some python code (on a linux machine) that uses an xml file to acquire its arguements to perform a task, on completion of the task it disposes of the xml file and waits for another xml file to arrive to do it ... | auto detect file in a folder | Sorry wasn't sure how to best word this question.
My scenario is that I have some python code (on a linux machine) that uses an xml file to acquire its arguements to perform a task, on completion of the task it disposes of the xml file and waits for another xml file to arrive to do it all over again.
I'm trying to find... | [
"If you're looking for something \"easy\" to just run a specific script when new files arrive, the incron daemon provides a very handy combination of inotify(7) and cron(8)-like support for executing programs on demand.\nIf you want something a little better integrated into your application, or if you can't afford ... | [
3
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0008528628_linux_python.txt |
Q:
Get file(name) in the dictionary as key and all directories(if file is in) as the value
I have directories and subdirectories, I want to get all the files in the dictionary and also directories into dictionary... Like this:
{'randomfile': '.\map\randomdirectory' , '\map\map2' , \somerandom\map\map3'}
Where key is ... | Get file(name) in the dictionary as key and all directories(if file is in) as the value | I have directories and subdirectories, I want to get all the files in the dictionary and also directories into dictionary... Like this:
{'randomfile': '.\map\randomdirectory' , '\map\map2' , \somerandom\map\map3'}
Where key is file(name) and all the directories where this file exsist are in value.
I have my project sav... | [
"$ python3\n>>> import os\n>>> d = {}\n>>> for x,y,z in os.walk('/path/to/dir'):\n... for f in z:\n... if f not in d:\n... d[f] = []\n... d[f].append(x)\n...\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008527473_python.txt |
Q:
Python pdb (debugger) disp equivalent?
Is there a pdb equivalent to disp in gdb?
E.g. when I'm debugging C using gdb I can have variables printed on every 'step' through the code by typing:
disp var
When I'm debugging python using pdb I would like similar functionality, but disp does not seem to be there, the pyt... | Python pdb (debugger) disp equivalent? | Is there a pdb equivalent to disp in gdb?
E.g. when I'm debugging C using gdb I can have variables printed on every 'step' through the code by typing:
disp var
When I'm debugging python using pdb I would like similar functionality, but disp does not seem to be there, the python pdb documentation does not seem to offer... | [
"The code bellow uses Python introspection features to add two new commands to the PDB module 0\njust put the given function, and its call in a separate module, and import this module before starting debugging - you should have the 'disp' and 'undisp' commands do add and retract watches to variables.\nIt works by m... | [
3,
3,
1
] | [] | [] | [
"debugging",
"pdb",
"python"
] | stackoverflow_0008520550_debugging_pdb_python.txt |
Q:
how to create an extra infinite loop in an gtk/python program?
New at this, I know that the program is supposed to enter an infinite loop when you call gtk.main. The loop in gtk.main will break when self.quit is called.
But I need another loop active that would check a log file for changes, and keep updating the c... | how to create an extra infinite loop in an gtk/python program? | New at this, I know that the program is supposed to enter an infinite loop when you call gtk.main. The loop in gtk.main will break when self.quit is called.
But I need another loop active that would check a log file for changes, and keep updating the changes, into a gtk.Textbuffer, to be shown in a gtk.Textbox. So wher... | [
"Only exists one mainloop in gtk at the same time, that is, gtk.main enters into a new level and gtk.main_quit exists from that level.\nUsually, what you'd need to do is is a create worker thread that keeps working in parallel and updates the widgets when it gets new information. However, according to the problem y... | [
5
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0008528820_gtk_pygtk_python.txt |
Q:
Printing data to list styled (table) from XML in Python
I'd like to print my servers as listed. Like this:
Machine | Group | IP | Services
- Alpha | Public Server Group | 192.168.1.251 | JBoss, Tomcat
- Public | Public Server Group | 192.168.1.253 | JBoss, Tomcat
My XML is:
<?xml versio... | Printing data to list styled (table) from XML in Python | I'd like to print my servers as listed. Like this:
Machine | Group | IP | Services
- Alpha | Public Server Group | 192.168.1.251 | JBoss, Tomcat
- Public | Public Server Group | 192.168.1.253 | JBoss, Tomcat
My XML is:
<?xml version="1.0" ?>
<AllConfigurations>
<DeployConfigurations>
<... | [
"First of all, you cannot print the lines right away; rather store the data (as tuples) in a list (servers). To group the services by machine / group / IP, you can use the itertools function groupby, specifying the first three fields as key tuple. (Before that, the list has to be sorted so groupby finds all duplica... | [
4,
2
] | [] | [] | [
"list",
"python",
"tabular",
"xml"
] | stackoverflow_0008528825_list_python_tabular_xml.txt |
Q:
Running total for list of dict
Have a python list of dict as following:
Dict1 = [{'date': 1, 'name': 'xyz', 'qty': 100},
{'date': 1, 'name': 'xyz', 'qty': 200},
{'date': 1, 'name': 'xyz', 'qty': 300},
{'date': 1, 'name': 'xyz2', 'qty': 30},
{'date': 2, 'name': 'xyz', 'qty': 1000... | Running total for list of dict | Have a python list of dict as following:
Dict1 = [{'date': 1, 'name': 'xyz', 'qty': 100},
{'date': 1, 'name': 'xyz', 'qty': 200},
{'date': 1, 'name': 'xyz', 'qty': 300},
{'date': 1, 'name': 'xyz2', 'qty': 30},
{'date': 2, 'name': 'xyz', 'qty': 1000},
{'date': 2, 'name': 'xyz... | [
"from itertools import groupby\nfrom operator import itemgetter\nfor k, gr in groupby(Dict1, key=itemgetter('date', 'name')):\n print \"date:%i,name:%s,qty:%i\" % (k[0], k[1], sum(d['qty'] for d in gr))\n\n",
"I assumed date is increasing order. \n# store values\ntot = {}\n# the last date \ndate0 = Dict1[-1]['... | [
4,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008528868_dictionary_python.txt |
Q:
Cannot import pygtk in pythonbrew after manual install
Since it is impossible to install pygtk via pip I tried to install it manually.
I downloaded the source tar from pypi and ran
./configure --prefix=/home/user/.pythonbrew/pythons/Python-2.7.2
make
make install
It installed alright, e.g. pygtk-demo is in my pat... | Cannot import pygtk in pythonbrew after manual install | Since it is impossible to install pygtk via pip I tried to install it manually.
I downloaded the source tar from pypi and ran
./configure --prefix=/home/user/.pythonbrew/pythons/Python-2.7.2
make
make install
It installed alright, e.g. pygtk-demo is in my path. However whenever I try to import pygtk I get the followin... | [
"I do not use pip or pythonbrew, but here is my experience, hope it can help and maybe put you on the good path !\nThe best option is to use the repository.\nUnder ubuntu, this goes with synaptic or apt-get.\nWhen manually must be choosen, remember the pygtk is just a bridge to the gtk package, and this one must be... | [
0,
0
] | [] | [] | [
"pygtk",
"python",
"pythonbrew"
] | stackoverflow_0008494129_pygtk_python_pythonbrew.txt |
Q:
appengine import_transform two function at the same time: truncate & export_date_time
I have this datetime 2011-07-02 03:03:32.793
To deal with the millisecond issue with python 2.5 version(mentioned here), I try to truncate it & convert it date time as:
import_transform: 'lambda x: x[:18]'
import_transform: t... | appengine import_transform two function at the same time: truncate & export_date_time | I have this datetime 2011-07-02 03:03:32.793
To deal with the millisecond issue with python 2.5 version(mentioned here), I try to truncate it & convert it date time as:
import_transform: 'lambda x: x[:18]'
import_transform: transform.import_date_time('%Y-%m-%d %H:%M:%S')
How can I write these two import_transform ... | [
"You can do this by writing a lambda function that does both together:\nimport-transform: lambda x: transform.import_date_time('%Y-%m-%d %H:%M:%S')(x[:18])\n\nNote the chained function calls - transform.import_date_time returns a function, which you're then calling.\n"
] | [
1
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0008526224_bulkloader_google_app_engine_python.txt |
Q:
Store/retrieve a data structure
I have implemented a suffix tree in Python to make full-text-searchs, and it's working really well. But there's a problem: the indexed text can be very big, so we won't be able to have the whole structure in RAM.
IMAGE: Suffix tree for the word BANANAS (in my scenario, imagine a tr... | Store/retrieve a data structure | I have implemented a suffix tree in Python to make full-text-searchs, and it's working really well. But there's a problem: the indexed text can be very big, so we won't be able to have the whole structure in RAM.
IMAGE: Suffix tree for the word BANANAS (in my scenario, imagine a tree 100000 times bigger).
So, research... | [
"An effective way to manage a structure like this is to use a memory-mapped file. In the file, instead of storing references for the node pointers, you store offsets into the file. You can still use pickle to serialise the node data to a stream suitable for storing on disk, but you will want to avoid storing refere... | [
4,
3,
1,
1,
1
] | [] | [] | [
"data_structures",
"disk_io",
"python",
"ram"
] | stackoverflow_0008300364_data_structures_disk_io_python_ram.txt |
Q:
webdriverbackedselenium in python
Is there a way of using webdriverbackedselenium in python, as in
selenium =
webdriverbackedselenium(driver,"http://www.google.com")
A:
In the meantime, one could manually write wrapper class that routes Selenium RC calls to WebDriver equivalent. I did some work on that for PH... | webdriverbackedselenium in python | Is there a way of using webdriverbackedselenium in python, as in
selenium =
webdriverbackedselenium(driver,"http://www.google.com")
| [
"In the meantime, one could manually write wrapper class that routes Selenium RC calls to WebDriver equivalent. I did some work on that for PHP, it's not that hard, though not all functions can be ported, but a majority can. And the process is similar across languages in terms of code flow / algorithm to wrap the c... | [
0
] | [] | [] | [
"python",
"selenium_webdriver",
"webdriver"
] | stackoverflow_0005475154_python_selenium_webdriver_webdriver.txt |
Q:
Generate a Sound file with a 15Khz tone
I'm playing around with high-pitched sounds. I'd like to generate an MP3 file with a 1 second 15Khz burst. Is there a simple way to do this from C or Python? I don't want to use MATLAB.
A:
You could use Python's wave module to create a wave file which you could then compre... | Generate a Sound file with a 15Khz tone | I'm playing around with high-pitched sounds. I'd like to generate an MP3 file with a 1 second 15Khz burst. Is there a simple way to do this from C or Python? I don't want to use MATLAB.
| [
"You could use Python's wave module to create a wave file which you could then compress to MP3. To create a one second 15khz sine wave:\nimport math\nimport wave\nimport struct\n\nnchannels = 1\nsampwidth = 2\nframerate = 44100\nnframes = 44100\ncomptype = \"NONE\"\ncompname = \"not compressed\"\namplitude = 4000\n... | [
14,
2
] | [
"Have you tried:\n#include<dos.h>\n#include<iostream.h>\n#include<conio.h>\nmain()\n{\n sound(500); // Frequency\n delay(1000); // Time\n nosound(); // Stop\n}\n\n"
] | [
-1
] | [
"audio",
"c",
"mp3",
"python"
] | stackoverflow_0008529258_audio_c_mp3_python.txt |
Q:
Issues with floodcount (similar to a floodfill algorithm) [python]
A couple of days ago I asked for help with the floodfill function and the stackoverflow community was very helpful in pointing me to the bugs in my function (I am new to python and programming). The function will search adjoining elements in an arr... | Issues with floodcount (similar to a floodfill algorithm) [python] | A couple of days ago I asked for help with the floodfill function and the stackoverflow community was very helpful in pointing me to the bugs in my function (I am new to python and programming). The function will search adjoining elements in an array and look for ones with values within 0.05 of each other much like a f... | [
"you seem to be causing a stack overflow. Instead of this recursive solution it may be better to use an array of points to check and push/pop them from that array as you encounter/process them. \nfor example:\ncreate an array called toProcess\ncreate an array or similar to mark which points have been encountered\na... | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008529827_numpy_python.txt |
Q:
regular expression: chopping last character if second last is upper case?
I want to chop off last character if it is lower case and second last one is upper case. For example.
14-ME -> 14-ME
MEA -> MEA
MEAm -> MEA #like this one
mama -> mama
How to write the regx ? I am thinking of something like r"(.+?)" but n... | regular expression: chopping last character if second last is upper case? | I want to chop off last character if it is lower case and second last one is upper case. For example.
14-ME -> 14-ME
MEA -> MEA
MEAm -> MEA #like this one
mama -> mama
How to write the regx ? I am thinking of something like r"(.+?)" but not sure how to do conditional thing on the last part. The word could have anyth... | [
"Don't really need a regex to do this when you can write a simple piece of code to do it.\ndef chop_char(some_string):\n try:\n # determine if the second to last character is upper case\n if some_string[-2].istitle() and not some_string[-1].istitle():\n return some_string[:-1] # slice of... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008529916_python_regex.txt |
Q:
Match multiple lines in a file using regular expression python
I have some many files each file has a set of lines in a given pattern. I want to match those multiple lines at once and do some operations on them such as delete, move to another file etc.
the multiple lines in a file are as given below.
self.unsuppor... | Match multiple lines in a file using regular expression python | I have some many files each file has a set of lines in a given pattern. I want to match those multiple lines at once and do some operations on them such as delete, move to another file etc.
the multiple lines in a file are as given below.
self.unsupported_cmds = [r'\s*clns\s+routing',
r'\s*bfd... | [
"As python re module documentation says you may add the MULTILINE flag to re.compile method. This will let you match entire file at once.\nimport re\n\nregex = re.match(r'''(\n ^\\s*clns\\s+routing$ |\n ^\\s*bfd\\s+graceful-restart$ |\n ^\\s*ip\\s+default-network$ |\n ^\\s*ip\\s+default-gateway$ |\n ... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008530203_python_regex.txt |
Q:
Get recarray attributes/columns python
I'm trying to retrieve the column titles of a recarray, and running into considerable trouble. If I read in a .csv file using pylab's csv2rec function, I am able to access column titles in the following manner:
from pylab import csv2rec
x = csv2rec(file.csv)
x.column1
x.colu... | Get recarray attributes/columns python | I'm trying to retrieve the column titles of a recarray, and running into considerable trouble. If I read in a .csv file using pylab's csv2rec function, I am able to access column titles in the following manner:
from pylab import csv2rec
x = csv2rec(file.csv)
x.column1
x.column2
Where 'column1' is the title of the fir... | [
"You can use x.dtype.names:\n>>> import numpy as np\n\n>>> a = np.array([0.1,0.2])\n>>> b = np.array([0.3,0.4])\n>>> dtype = {'names' : ['a','b'], 'formats' : ['f8', 'f8']}\n>>> c = np.rec.fromarrays([a,b], dtype = dtype)\n>>> c\nrec.array([(0.1, 0.3), (0.2, 0.4)], \n dtype=[('a', '<f8'), ('b', '<f8')])\n>>> p... | [
14
] | [] | [] | [
"python",
"recarray"
] | stackoverflow_0008530670_python_recarray.txt |
Q:
Python uwsgi w/ virtualenv --no-site-packages -- import site = AttributeError {'userbase'}
Long story short I have a nginx/uwsgi deployment where I cannot use
import site
within the deploy script without raising error
Traceback (most recent call last):
File "/home/PROJECT/virtualenv/PROJECT/deploy/deploy.py", l... | Python uwsgi w/ virtualenv --no-site-packages -- import site = AttributeError {'userbase'} | Long story short I have a nginx/uwsgi deployment where I cannot use
import site
within the deploy script without raising error
Traceback (most recent call last):
File "/home/PROJECT/virtualenv/PROJECT/deploy/deploy.py", line 1, in <module>
import site
File "/usr/lib/python2.7/site.py", line 562, in <module>
... | [
"I'm not very familiar with uwsgi and nginx configuration. But I know that you need to run your WSGI application runner deploy.py with the python interpreter provided by your virtualenv. /home/project/virtualenv/bin/python in your case.\nIt is possible that you have uWSGI 0.9.7 or later. In this case here is the wo... | [
2
] | [] | [] | [
"nginx",
"python",
"uwsgi",
"virtualenv"
] | stackoverflow_0008528779_nginx_python_uwsgi_virtualenv.txt |
Q:
Remove ' from python list
I have a list, that looks like this in python:
ex = ['(1..3),(5..8)']
I need to get out the list like this:
[(1, 3), (5, 8)]
I tried using the replace function, but could only get like
['(1, 3), (5,8)'] and could not lose the ' marks.
Hope someone can help me.
Thanks
A:
import ast
ex ... | Remove ' from python list | I have a list, that looks like this in python:
ex = ['(1..3),(5..8)']
I need to get out the list like this:
[(1, 3), (5, 8)]
I tried using the replace function, but could only get like
['(1, 3), (5,8)'] and could not lose the ' marks.
Hope someone can help me.
Thanks
| [
"import ast\nex = ['(1..3),(5..8)']\nlist(ast.literal_eval(ex[0].replace('..', ',')))\n# returns [(1, 3), (5, 8)]\n\nast.literal_eval is safe. eval is not.\nFor your updated question:\nex2 = ['(2..5)', '(7..10)']\n[ast.literal_eval(a.replace('..', ',')) for a in ex2]\n# returns [(2, 5), (7, 10)]\n\n",
"Look like ... | [
8,
2,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008530925_list_python.txt |
Q:
Where is my emacs configuration file on Win7?
Possible Duplicate:
Where can I find my .emacs file for Emacs running on Windows?
I am a total newbie to emacs.
I know I can edit a configuration file to change the behavior of my emacs editor and customize it for python editing. but I can't seem to find it.
Any he... | Where is my emacs configuration file on Win7? |
Possible Duplicate:
Where can I find my .emacs file for Emacs running on Windows?
I am a total newbie to emacs.
I know I can edit a configuration file to change the behavior of my emacs editor and customize it for python editing. but I can't seem to find it.
Any help would be appreciated.
| [
"I'm on windows XP. But inside emacs i can open it using:\n C-x C-f ~/.emacs\n\nor\n C-x C-f ~/.emacs.d/init.el\n\nYou then can also see to what ~ autocompletes to locate it.\n",
"I think GNU Emacs puts it in the Documents folder '_emacs'. I'm not at a Win 7 box right now to double check.\n"
] | [
1,
0
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0008531046_emacs_python.txt |
Q:
Python implementation for permutation given specific conditions
How can I generate permutations given the following conditions?
There are two integers, for ex. 1 and 4.
The two integers given will be part of the permutation where each integer will appear at most N times and the size of each permutation is K.
So ... | Python implementation for permutation given specific conditions | How can I generate permutations given the following conditions?
There are two integers, for ex. 1 and 4.
The two integers given will be part of the permutation where each integer will appear at most N times and the size of each permutation is K.
So let's say for N = 3 and K = 5, so the correct result should be:
{1, ... | [
"See if this works for you\n>>> K=5\n>>> N=3\n>>> src=[['1']*n+['4']*(K-n) for n in xrange(K-N,N+1)]\n>>> set(x for s in src for x in itertools.permutations(s))\nset([('1', '4', '1', '4', '1'), ('4', '1', '4', '1', '1'), ('1', '1', '4', '4', '4'), ('1', '4', '4', '1', '1'), ('1', '4', '4', '4', '1'), ('4', '4', '4'... | [
4,
2,
1,
0
] | [] | [] | [
"algorithm",
"permutation",
"python"
] | stackoverflow_0008530128_algorithm_permutation_python.txt |
Q:
Flat file key-value store in python
I'm looking for a flat-file, portable key-value store in Python. I'll be using strings for keys and either strings or lists for values. I looked at ZODB but I'd like something which is more widely used and is more actively developed. Do any of the dmb modules in Python require s... | Flat file key-value store in python | I'm looking for a flat-file, portable key-value store in Python. I'll be using strings for keys and either strings or lists for values. I looked at ZODB but I'd like something which is more widely used and is more actively developed. Do any of the dmb modules in Python require system libraries or a database server (lik... | [
"You may want to consider h5py which is a Python interface to HDF5.\nIn [1]: import h5py\n\nIn [2]: f = h5py.File('test.hdf5', 'w')\n\nIn [3]: f['abc'] = [1, 2, 3]\n\nIn [4]: f['d'] = 'hello'\n\nIn [5]: f.close()\n\nIn [6]: f2 = h5py.File('test.hdf5', 'r')\n\nIn [7]: f2['abc'].value\nOut[7]: array([1, 2, 3])\n\nIn ... | [
7,
5,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008528001_python.txt |
Q:
Opposite of os.path.commonprefix
What's the opposite of os.path.commonprefix? I have two paths and I want the non-overlapping path, e.g.:
>>> p1 = '/Users/foo/something'
>>> p2 = '/Users/foo/something/else/etc'
>>> print somefunction([p1, p2])
'/else/etc'
A:
>>> p1 = '/Users/foo/something'
>>> p2 = '/Users/foo/s... | Opposite of os.path.commonprefix | What's the opposite of os.path.commonprefix? I have two paths and I want the non-overlapping path, e.g.:
>>> p1 = '/Users/foo/something'
>>> p2 = '/Users/foo/something/else/etc'
>>> print somefunction([p1, p2])
'/else/etc'
| [
">>> p1 = '/Users/foo/something'\n>>> p2 = '/Users/foo/something/else/etc'\n>>> os.path.relpath(p2, start=p1)\n'else/etc'\n\nThe correct answer is 'else/etc' and not '/else/etc'.\nIf you are in p1 and type cd /else/etc you wouldn't land in p2, but somewhere else.\nos.path.join(p1, 'else/etc') gives you p2 again.\n"... | [
14
] | [] | [] | [
"path",
"python"
] | stackoverflow_0008531275_path_python.txt |
Q:
Python PIL: image crop with black area if not enough photo region
I want to make thumb and crop it to needed size. It works fine, but if my new thumb area is smaller than crop one, all empty space fills with black color.
Code:
import os
from PIL import Image
def resize(file_path):
file, ext = os.path.splitext... | Python PIL: image crop with black area if not enough photo region | I want to make thumb and crop it to needed size. It works fine, but if my new thumb area is smaller than crop one, all empty space fills with black color.
Code:
import os
from PIL import Image
def resize(file_path):
file, ext = os.path.splitext(file_path)
im = Image.open(file_path)
size = (100, 'auto')
... | [
"You will need to apply some simple algorithm there instead of a blind cropping.\n\nGet the square of maximum size possible in the image with square center aligning with the center of the image.\nSquare of maximum size would be having side equal to max of height or width of the image.\nAfter getting the square, res... | [
2,
1,
1,
1
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0008530443_python_python_imaging_library.txt |
Q:
Bind event to variable in Python
Is there any way to bind an event to a variable in Python or wxPython? Something like this:
self.Bind(EVT_ONCHANGE_VAR, self.mycallback, variable_to_watch)
This would let a dialog to show or hide depending on the value of such variable.
Thanks!
A:
traits allows you to get no... | Bind event to variable in Python | Is there any way to bind an event to a variable in Python or wxPython? Something like this:
self.Bind(EVT_ONCHANGE_VAR, self.mycallback, variable_to_watch)
This would let a dialog to show or hide depending on the value of such variable.
Thanks!
| [
"traits allows you to get notifications when the value is changed.\nIn your case you could make variable_to_watch a property:\nclass C(object):\n def __init__(self):\n self._x = None\n\n @property\n def x(self):\n return self._x\n\n @x.setter\n def x(self, value):\n self._x = val... | [
3,
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008530693_python_wxpython.txt |
Q:
Python pickle: fix \r characters before loading
I got a pickled object (a list with a few numpy arrays in it) that was created on Windows and apparently saved to a file loaded as text, not in binary mode (ie. with open(filename, 'w') instead of open(filename, 'wb')). Result is that now I can't unpickle it (not ev... | Python pickle: fix \r characters before loading | I got a pickled object (a list with a few numpy arrays in it) that was created on Windows and apparently saved to a file loaded as text, not in binary mode (ie. with open(filename, 'w') instead of open(filename, 'wb')). Result is that now I can't unpickle it (not even on Windows) because it's infected with \r characte... | [
"Presuming that the file was created with the default protocol=0 ASCII-compatible method, you should be able to load it anywhere by using open('pickled_file', 'rU') i.e. universal newlines.\nIf this doesn't work, show us the first few hundred bytes: print repr(open('pickled_file', 'rb').read(200)) and paste the res... | [
17,
5,
0,
0
] | [] | [] | [
"carriage_return",
"pickle",
"python"
] | stackoverflow_0008527241_carriage_return_pickle_python.txt |
Q:
'easy_install -U cython' fails complaining about vcvarsall.bat and -mno-cygwin
Under Windows, it seems that easy_install with a C dependency isn't very easy.
Attempt 1 - vcvarsall.bat errors
I am installing cython under Windows7, with MinGw; I modified Windows7's PATH to include C:\MinGw\bin. At this point, I tri... | 'easy_install -U cython' fails complaining about vcvarsall.bat and -mno-cygwin | Under Windows, it seems that easy_install with a C dependency isn't very easy.
Attempt 1 - vcvarsall.bat errors
I am installing cython under Windows7, with MinGw; I modified Windows7's PATH to include C:\MinGw\bin. At this point, I tried to easy_install -U cython, and got...
C:\Users\mike_pennington\Desktop\TestDrive>... | [
"After more some googling, I found guidance that recommended removing -mno-cygwin from C:\\Python27\\Lib\\distutils\\cygwinccompiler.py because of a distutils bug.\nRemoving -mno-cygwin from C:\\Python27\\Lib\\distutils\\cygwinccompiler.py got cython to compile.\n"
] | [
15
] | [] | [] | [
"cython",
"easy_install",
"mingw",
"python",
"windows"
] | stackoverflow_0008531983_cython_easy_install_mingw_python_windows.txt |
Q:
Check ID across tables using Django Queryset
I'm currently trying to count user activity, but will only count it two days after they first sign up. Since I'm going to be postprocessing the data, I'd like to have it return a Django QuerySet.
The only fields that are relevant are the following:
User
user_id, install... | Check ID across tables using Django Queryset | I'm currently trying to count user activity, but will only count it two days after they first sign up. Since I'm going to be postprocessing the data, I'd like to have it return a Django QuerySet.
The only fields that are relevant are the following:
User
user_id, install_time
Activity
user_id, date, [list of activities... | [
"As your models aren't using explicit joins, you can't use field F objects as Chris Pratt suggested.\nIf you are unable to modify your schema, I can see two other options that still leverage some of the django ORM, but require you to write SQL queries/fragments.\nI'm assuming postgresql and completely guessing at t... | [
3,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008523705_django_django_models_python.txt |
Q:
Regular expression to match the string
Please provide me the regular expression to match the following string.
"self.unsupported_cmds = [r'\s*clns\s+routing',"
Thanks in advance.
I tried the following,
re.match("^self\.unsupported\_cmds| ?=\ ?\[r\'.*\,", line)
where line is the above mentioned string. It did not... | Regular expression to match the string | Please provide me the regular expression to match the following string.
"self.unsupported_cmds = [r'\s*clns\s+routing',"
Thanks in advance.
I tried the following,
re.match("^self\.unsupported\_cmds| ?=\ ?\[r\'.*\,", line)
where line is the above mentioned string. It did not work.
I did not get any error or exception,... | [
"I am not sure what is your problem, I think its not the regex.\nAre you really calling only this code?\nre.match(\"^self\\.unsupported\\_cmds| ?=\\ ?\\[r\\'.*\\,\", line)\n\nIf yes, try this:\nif(re.match(\"^self\\.unsupported\\_cmds| ?=\\ ?\\[r\\'.*\\,\", line)):\n print \"Match\"\n\nFor me this is returning M... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008532615_python_regex.txt |
Q:
How to recover from Segmentation fault in Python?
I am running the Python program to call the other 3rd module, which may written in C. In this case, how can I recover from the Segmentation fault and continue to process others in a loop?
Segmentation Fault is not exception so that cannot be catched. And I already ... | How to recover from Segmentation fault in Python? | I am running the Python program to call the other 3rd module, which may written in C. In this case, how can I recover from the Segmentation fault and continue to process others in a loop?
Segmentation Fault is not exception so that cannot be catched. And I already know the root of Segmentation Fault and needn't to trac... | [
"Call the third module in another process, so it doesn't crash the main one when segfault occurs.\n",
"A segmentation fault might be a bug in that C module you are calling from you Python program. If you own the code and know the reason for the segmentation fault, it would be better to fix it instead of skipping ... | [
4,
2
] | [] | [] | [
"exception_handling",
"python",
"segmentation_fault"
] | stackoverflow_0008530696_exception_handling_python_segmentation_fault.txt |
Q:
Prompting user on package install "pip install "
I've created a tar.gz of a package that includes a setup.py file. setup.py uses the setup() function provided in distutils.core. I want to prompt the user when they run "pip install .tar.gz". Unfortunately, it looks like pip redirects all stdout and stderr of the "p... | Prompting user on package install "pip install " | I've created a tar.gz of a package that includes a setup.py file. setup.py uses the setup() function provided in distutils.core. I want to prompt the user when they run "pip install .tar.gz". Unfortunately, it looks like pip redirects all stdout and stderr of the "python setup.py install" command through a special log ... | [
"Don't do that.\nIf it is absolutely necessary to have information from the user during the install, ask for an environment variable to be set, and fail if it is not set. Better yet, require a plain text configure file to run your module - and set it with default values during the install\nDon't try to make an inte... | [
2
] | [] | [] | [
"distutils",
"pip",
"python",
"stdout"
] | stackoverflow_0008532369_distutils_pip_python_stdout.txt |
Q:
outlook PST File extracting via libpst + python
had anyone successfully import and used libpst via python, to extract outlook PST files : http://www.five-ten-sg.com/libpst/ from source package?
It have python bindings but i cannot import after installing (even test.py script comes with it dont work)
Here is Mercur... | outlook PST File extracting via libpst + python | had anyone successfully import and used libpst via python, to extract outlook PST files : http://www.five-ten-sg.com/libpst/ from source package?
It have python bindings but i cannot import after installing (even test.py script comes with it dont work)
Here is Mercurial repo to latest version. Can you guys give a try? ... | [
"Actually libpst Python is not well developed , and i had to use from readpst commandline , wrapping inside subprocess call.\nSo i have to answer this my own. \n"
] | [
1
] | [] | [] | [
"email",
"outlook",
"parsing",
"pst",
"python"
] | stackoverflow_0003244296_email_outlook_parsing_pst_python.txt |
Q:
celery, one bye one queue and parallel many in time queues
I am trying to use celery to manage tasks.
The problem i am into now, that i have many minor tasks(emails, cross-server posts, etc)
And time consumable tasks, like file uploads.
Is there any way, to specify, that uploads will always will be one by one. Onl... | celery, one bye one queue and parallel many in time queues | I am trying to use celery to manage tasks.
The problem i am into now, that i have many minor tasks(emails, cross-server posts, etc)
And time consumable tasks, like file uploads.
Is there any way, to specify, that uploads will always will be one by one. Only one task executed in time, while other workers will work on ot... | [
"An effective way to serialize the execution of tasks is to use a mutex (Mutual Exclusion).\nPython's threading module has a Lock object which can be used to this effect:\n# ...\nmodule_lock = threading.Lock() # or make this an attribute in an object with sufficiently-large scope\n# ...\ndef do_interesting_task():\... | [
0,
0
] | [] | [] | [
"celery",
"python",
"rabbitmq"
] | stackoverflow_0008528160_celery_python_rabbitmq.txt |
Q:
how to filter a django queryset where the conditions are taken from another list?
I have a situation where i have a list of primary keys. And i need to filter(OR) a queryset using the primarykeys in the list.
But the problem is that the list is dynamic.
Is there any way i can filter the queryset by doing an OR u... | how to filter a django queryset where the conditions are taken from another list? | I have a situation where i have a list of primary keys. And i need to filter(OR) a queryset using the primarykeys in the list.
But the problem is that the list is dynamic.
Is there any way i can filter the queryset by doing an OR using each primary keys on the queryset.
| [
"Maybe in will help https://docs.djangoproject.com/en/dev/ref/models/querysets/#in\n",
"This should help you: in_bulk\n"
] | [
0,
0
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0008533510_django_models_python.txt |
Q:
How can I transform an image so that projected image is same as original
Problem statement: An image A is projected through a projector, goes through a microscope and the projected image is captured via a camera through the same microscope as image B. Due to the optical elements, the B is rotated, sheared and dist... | How can I transform an image so that projected image is same as original | Problem statement: An image A is projected through a projector, goes through a microscope and the projected image is captured via a camera through the same microscope as image B. Due to the optical elements, the B is rotated, sheared and distorted with respect to A. Now, I need to transform A into A' before projection ... | [
"I got it resolved finally. There were several issues:\n\nThe original images were not of the same size. Nor were the captured images. Hince, the affine transform from one pair was not applicable to the other. I resized them all to the same size.\nThe Undistort after camera calibration is not sufficient for rotatio... | [
0
] | [] | [] | [
"camera_calibration",
"image_processing",
"opencv",
"python"
] | stackoverflow_0008414611_camera_calibration_image_processing_opencv_python.txt |
Q:
Django - Rating System View & Template
I have a content that I'd like to rate on multiple criteria.
Imagine this kind of model:
class Content(models.Model):
name = models.CharField(max_length=50)
class Criterion(models.Model):
name = models.CharField(max_length=50)
content = models.ForeignKey(Content)
clas... | Django - Rating System View & Template | I have a content that I'd like to rate on multiple criteria.
Imagine this kind of model:
class Content(models.Model):
name = models.CharField(max_length=50)
class Criterion(models.Model):
name = models.CharField(max_length=50)
content = models.ForeignKey(Content)
class ContRate(models.Model):
user = models.Fo... | [
"Not sure what the point of the formset is here. The rates are all available via the criteria object, using the reverse foreign key to ContRate in exactly the same way as you've done from Criteria to Content.\nTo make this as efficient as possible, you probably want to get the relevant ratings in the view and bring... | [
1
] | [] | [] | [
"django",
"django_forms",
"python",
"rating_system"
] | stackoverflow_0008533461_django_django_forms_python_rating_system.txt |
Q:
Python and plot() : how to limit the number of x-axis ticks (labels)
I have two lists, same size, one is y_data and one is x_data
x_data is a time hh:mm:ss during day, in fact each minute
each serie is 1440 long.
problem is :
fig = Figure(figsize=(4,3))
a = gif.add_subplot(111)
a.plot(x_data, y_data)
give an unre... | Python and plot() : how to limit the number of x-axis ticks (labels) | I have two lists, same size, one is y_data and one is x_data
x_data is a time hh:mm:ss during day, in fact each minute
each serie is 1440 long.
problem is :
fig = Figure(figsize=(4,3))
a = gif.add_subplot(111)
a.plot(x_data, y_data)
give an unreadable x_axis (too many labels), if i reduce x_data to [range(24)] for ins... | [
"The pyplot interface of matplotlib provides a function locator_params, where you can set this option:\nfig = Figure(figsize=(4,3))\na = fig.add_subplot(111)\na.plot(x_data, y_data)\na.locator_params(nbins=4)\n\n"
] | [
7
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008533261_matplotlib_python.txt |
Q:
python loop array
arr = [(line.rstrip('\n').split(';')) for line in open('C:/Config_Changer.csv')]
import sys
import fileinput
for i, line in enumerate(fileinput.input('C:/1.cfg', inplace = 1)):
sys.stdout.write(line.replace(arr[0][0], arr[0][1]))
Hey all,
I wrote the above lines so it's working fine but its ... | python loop array | arr = [(line.rstrip('\n').split(';')) for line in open('C:/Config_Changer.csv')]
import sys
import fileinput
for i, line in enumerate(fileinput.input('C:/1.cfg', inplace = 1)):
sys.stdout.write(line.replace(arr[0][0], arr[0][1]))
Hey all,
I wrote the above lines so it's working fine but its replacing only ary[0][0... | [
"so what you want is to apply all the replacements that are in arr to the line: (unlike aix's answer, this one avoids the explicit indexing)\nfor i, line in enumerate(fileinput.input('C:/1.cfg', inplace = 1)):\n for f,t in arr:\n line = line.replace(f, t)\n sys.stdout.write(line)\n\n",
"Provided I am... | [
3,
0
] | [] | [] | [
"arrays",
"loops",
"python"
] | stackoverflow_0008533831_arrays_loops_python.txt |
Q:
Function inputs and recursion in python
This is a moronic question. Here goes:
I have two lists, candidates_input and constraint_input. The function below finds the winning candidate in candidates_input for a given ordering of constraints in constraint_input by eliminating candidates that can't be the winner until... | Function inputs and recursion in python | This is a moronic question. Here goes:
I have two lists, candidates_input and constraint_input. The function below finds the winning candidate in candidates_input for a given ordering of constraints in constraint_input by eliminating candidates that can't be the winner until only one is left. So I'm removing items from... | [
"The reason it \"works\" without making a copy is that when you make the recursive call, you don't return anything from it. Each recursive call re-filters the original data, and once you've returned from everything, the original data has been completely re-filtered. If you make copies, then successively more-filter... | [
2,
1
] | [] | [] | [
"input",
"python",
"recursion",
"variables"
] | stackoverflow_0008532128_input_python_recursion_variables.txt |
Q:
Iterating through python numpy array when used with scipy.optimize.curve_fit
I need to iterate through the elements in a numpy array so I can treat any zero elements separately. The code below works for straighforward evaluations, but not when used with scipy.optimize.curve_fit(). Is there a way to make this work ... | Iterating through python numpy array when used with scipy.optimize.curve_fit | I need to iterate through the elements in a numpy array so I can treat any zero elements separately. The code below works for straighforward evaluations, but not when used with scipy.optimize.curve_fit(). Is there a way to make this work with the curve_fit fn?
import numpy as np
from matplotlib.pyplot import *
from sci... | [
"To make the larsmans' answer actually work, you will also need to convert your data samples to NumPy arrays:\nx_meas = numpy.array([0, 5, 20, 50, 100, 200, 600], float)\ny_meas = numpy.array([0, 0.275, 1.22, 1.64, 1.77, 1.84, 1.9], float)\n\n(Converting y_meas is not strictly necessary.)\nHere is larsmans' code wi... | [
3,
1
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0008533765_numpy_python_scipy.txt |
Q:
Get CLASSPATH constructed in a .bat file from python
The java project I am working on has a .bat file and a .sh file which build the CLASSPATH for the project to run. (.bat for windows and .sh for the rest).
Now, I am writing a python script that needs access to the classpath created by these scripts, the one from... | Get CLASSPATH constructed in a .bat file from python | The java project I am working on has a .bat file and a .sh file which build the CLASSPATH for the project to run. (.bat for windows and .sh for the rest).
Now, I am writing a python script that needs access to the classpath created by these scripts, the one from .sh if on linux and the one from .bat if on windows.
Curr... | [
"The simplest way would be to create a batch file with the relevant commands. That way the variable doesn't get expanded until CMD processes the relevant line. Also use @echo off to disable echo:\n@echo off\ncall mkcp.bat\necho %CLASSPATH%\n\nThen just call that batch file from your Python code.\nIf you want to do ... | [
1
] | [] | [] | [
"batch_file",
"cmd",
"python",
"subprocess"
] | stackoverflow_0008533954_batch_file_cmd_python_subprocess.txt |
Q:
web based visual programming interface based on python for data visualization
I just discovered impure.com and was very impressed by what can be achieved in terms of visualizing data using their workspace. Although the platform is free to use, but not open source yet. This causes a few problems because the API sec... | web based visual programming interface based on python for data visualization | I just discovered impure.com and was very impressed by what can be achieved in terms of visualizing data using their workspace. Although the platform is free to use, but not open source yet. This causes a few problems because the API section works with .com sites for eg. for ebay, so I cannot visualize ebay listings fo... | [
"So, restating, Impure is like OpenDX but running in a browser and you are interested in suggestions for an architecture to build your own web version of it?\nI suggest using Cappuccino as your front end Web GUI. This is a toolkit for building RIAs in the browser that are completely based on HTML and Javascript (no... | [
1
] | [] | [] | [
"flash",
"python",
"visualization",
"web_applications"
] | stackoverflow_0008008462_flash_python_visualization_web_applications.txt |
Q:
How do you check if the PYTHONSTARTUP variable is defined?
I was looking at this Stack Overflow answer and in it the author says for the original poster to check if the PYTHONSTARTUP variable is defined. I looked around and can not find out how to check to see if it is defined.
How do you check to see if the PYT... | How do you check if the PYTHONSTARTUP variable is defined? | I was looking at this Stack Overflow answer and in it the author says for the original poster to check if the PYTHONSTARTUP variable is defined. I looked around and can not find out how to check to see if it is defined.
How do you check to see if the PYTHONSTARTUP variable is defined?
| [
"Windows (cmd.exe):\necho %PYTHONSTARTUP%\n\nElsewhere (in a shell, e.g. bash):\necho $PYTHONSTARTUP\n\nIn Python:\nimport os\nprint(os.environ['PYTHONSTARTUP'])\n\n",
"I assume it's an environment variable.\nimport os\n\nif os.getenv(\"PYTHONSTART\"):\n do_something()\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"readline",
"variables"
] | stackoverflow_0008534443_python_readline_variables.txt |
Q:
Pythonic? ...Dynamically calling nested functions
Is this a a pythonic implementation?
I'm calling nested functions dynamically from a string argument with wrappers to reduce the chance of calling a non-existent function. Here's an example where I want to perform different comparisons on arg1 and arg2 (in terms o... | Pythonic? ...Dynamically calling nested functions | Is this a a pythonic implementation?
I'm calling nested functions dynamically from a string argument with wrappers to reduce the chance of calling a non-existent function. Here's an example where I want to perform different comparisons on arg1 and arg2 (in terms of ==, >=, < etc)...
class ComparisonClass(object):
... | [
"Implementation is irrelevant here because the very thing you seek to implement isn't Pythonic.\nIn Python, we use the __eq__ family of methods for comparisons, and there exist tools in the standard library for implementing some of them in terms of others.\n",
"What you're missing is that in Python, functions are... | [
6,
1
] | [] | [] | [
"locals",
"nested_function",
"python"
] | stackoverflow_0008534351_locals_nested_function_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.