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:
Communicating to server with queries through stream. What is the right way?
I'm writing my first network application. It manipulates jabber client and communicates with some service with IQ-stanzas. But details are not important.
This interaction works through twisted xmlstream (python language). Typical situation... | Communicating to server with queries through stream. What is the right way? | I'm writing my first network application. It manipulates jabber client and communicates with some service with IQ-stanzas. But details are not important.
This interaction works through twisted xmlstream (python language). Typical situations are described here: http://juick.com/help/api/xmpp/ To be short, I can send a "... | [
"To pair a response with a reply, you use the iq.id attribute. You can store a few deferreds in a cache indexed by id and run them when they get a reply. Since XMPP is TCP-based, you will mostly get replies in the right order anyway. You can cap the cache and run the deferred's errback if the deferred has been in t... | [
0
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0002128545_networking_python_twisted.txt |
Q:
Python: Optimizing, or at least getting fresh ideas for a tree generator
I have written a program that generates random expressions and then uses genetic techniques to select for fitness.
The following part of the program generates the random expression and stores it in a tree structure.
As this can get called bil... | Python: Optimizing, or at least getting fresh ideas for a tree generator | I have written a program that generates random expressions and then uses genetic techniques to select for fitness.
The following part of the program generates the random expression and stores it in a tree structure.
As this can get called billions of times during a run, I thought it should be optimized for time.
I'm ne... | [
"Below, I've summarized some of the more obvious optimization efforts, without really touching the algorithm much. All timings are done with Python 2.6.4 on a Linux x86-64 system.\nInitial time: 8.3s\nLow-Hanging Fruits\njellybean already pointed some out. Just fixing those already improves the runtime a little bit... | [
4,
2,
2
] | [] | [] | [
"expression_trees",
"optimization",
"python"
] | stackoverflow_0002127680_expression_trees_optimization_python.txt |
Q:
Python - Rpy2 - Can't import a bunch of packages
I've just started using rpy2 with Python. I've installed it and am able to do basic things, like call R's plot function from inside Python. For everything I've done, I've used import calls like:
import rpy2
import rpy2.robjects
From robjects I can do most things ... | Python - Rpy2 - Can't import a bunch of packages | I've just started using rpy2 with Python. I've installed it and am able to do basic things, like call R's plot function from inside Python. For everything I've done, I've used import calls like:
import rpy2
import rpy2.robjects
From robjects I can do most things I want to do. However, if I want to use things like g... | [
"packages is new in 2.1. You're probably still using 2.0.x.\n",
"You can use the normal library() command from robjects.r to load a library in rpy2 2.0.x:\nfrom rpy2.robjects import r\nr.library(\"lattice\")\nr.library(\"ggplot2\")\n\nOr you can upgrade to the 2.1 alpha and see if the new way works for you.\n"
] | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002128806_python.txt |
Q:
Running django on IronPython
There have been some questions and answers here on stackoverflow, but no one asked if it's a good solution to run django on IIS.
Any experience is welcome, both good and bad.
A:
One thing I know is that Django has no official support for IronPython - just CPython and Jython. In addit... | Running django on IronPython | There have been some questions and answers here on stackoverflow, but no one asked if it's a good solution to run django on IIS.
Any experience is welcome, both good and bad.
| [
"One thing I know is that Django has no official support for IronPython - just CPython and Jython. In addition, PIL - which provides Django's support for image fields - does not natively support IronPython, though the ironclad project could help with that. (Caveat: I have never actually used IronPython, this is jus... | [
2
] | [] | [] | [
".net",
"django",
"iis",
"ironpython",
"python"
] | stackoverflow_0002128740_.net_django_iis_ironpython_python.txt |
Q:
Python, len, and size of ints
So, cPython (2.4) has some interesting behaviour when the length of something gets near to 1<<32 (the size of an int).
r = xrange(1<<30)
assert len(r) == 1<<30
is fine, but:
r = xrange(1<<32)
assert len(r) == 1<<32
ValueError: xrange object size cannot be reported`__len__() should ... | Python, len, and size of ints | So, cPython (2.4) has some interesting behaviour when the length of something gets near to 1<<32 (the size of an int).
r = xrange(1<<30)
assert len(r) == 1<<30
is fine, but:
r = xrange(1<<32)
assert len(r) == 1<<32
ValueError: xrange object size cannot be reported`__len__() should return 0 <= outcome
Alex's wowrang... | [
"cPython assumes that lists fit in memory. This extends to objects that behave like lists, such as xrange. essentially, the len function expects the __len__ method to return something that is convertable to size_t, which won't happen if the number of logical elements is too large, even if those elements don't act... | [
12,
5,
1
] | [] | [] | [
"int",
"python"
] | stackoverflow_0002128989_int_python.txt |
Q:
Error setting up Mercurial on Windows Server 2008
I want to set up a Mercurial SC server and have been following the instructions found here: http//stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis
I have checked all my settings multiple times and cannot seem to get passed this error af... | Error setting up Mercurial on Windows Server 2008 | I want to set up a Mercurial SC server and have been following the instructions found here: http//stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis
I have checked all my settings multiple times and cannot seem to get passed this error after completing the configuration. Any advice would be ... | [
"The traceback in the very long line says that mercurial isn't found in your PYTHON_PATH. Try making the hgwebdir.cgi edit as seen in step 5.1 from the HgWebDirStopByStep page.\n# adjust python path if not a system-wide install:\nimport sys\nsys.path.insert(0, \"c:/dev/Mercurial/lib\")\n\nWhere, of course, the pat... | [
6
] | [] | [] | [
"mercurial",
"python",
"windows_server_2008"
] | stackoverflow_0002123798_mercurial_python_windows_server_2008.txt |
Q:
What are the advantages of using Django insead of app-engine's default web framework?
I'm building my first python app on app-engine and wondering if I should use Django or not.
What are the strong points of each? If you have references that support your answer, please post them. Maybe we can make a wiki out o... | What are the advantages of using Django insead of app-engine's default web framework? | I'm building my first python app on app-engine and wondering if I should use Django or not.
What are the strong points of each? If you have references that support your answer, please post them. Maybe we can make a wiki out of this question.
| [
"Aral Balkan wrote a really nice piece addressing this very question. Its a year or so old, so take it with a grain of salt - I think that a lot more emphasis should be put on the awesomeness of django's Object-Relational-Model. Basically, IMHO, it all comes down to whether or not you have a preference for using DJ... | [
5,
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002125612_django_google_app_engine_python.txt |
Q:
Python: xml.dom.minidom empty nodeValue nonempty toxml() value
I have a line that gets the nodeValue of a Node:
parent.getElementsByTagName("Url")[0].nodeValue
that returns nothing:
<br/>
When I do:
parent.getElementsByTagName("Url")[0].toxml()
it returns:
< Url>www.something.com< /Url>
I am not sure what is g... | Python: xml.dom.minidom empty nodeValue nonempty toxml() value | I have a line that gets the nodeValue of a Node:
parent.getElementsByTagName("Url")[0].nodeValue
that returns nothing:
<br/>
When I do:
parent.getElementsByTagName("Url")[0].toxml()
it returns:
< Url>www.something.com< /Url>
I am not sure what is going on here. Another data point: when I do nodeName instead of node... | [
"Try this:\nparent.getElementsByTagName('Url')[0].childNodes[0].nodeValue\n\n",
"The DOM Level 2 documentation states that nodeName for an element node is the tag name, the nodeValue is always null and attributes is a NamedNodeMap, so this code behaves as expected.\n"
] | [
6,
1
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0002129252_minidom_python_xml.txt |
Q:
Code translation, from Python to Ruby
I would like to convert a few Python lines on Ruby, from this excellent article signed by Thomas Guest at: http://wordaligned.org/articles/drawing-chess-positions
(note: I'm a really bigger Python noob)
Here is a copy of the original Python version:
def expand_blanks(fen):
... | Code translation, from Python to Ruby | I would like to convert a few Python lines on Ruby, from this excellent article signed by Thomas Guest at: http://wordaligned.org/articles/drawing-chess-positions
(note: I'm a really bigger Python noob)
Here is a copy of the original Python version:
def expand_blanks(fen):
'''Expand the digits in an FEN string into... | [
"Looking at each method in turn, starting with outer_join.\nIn Python, join is a method on strings that takes a sequence and joins the elements delimited by the string. e.g. '|'.join(['p, 'p', 'p'])\nIn Ruby, join is a method on arrays that takes the delimiter as an argument e.g. ['p', 'p', 'p'].join('|')\nso the R... | [
2,
1
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0002129227_python_ruby.txt |
Q:
Python to C# Code Explanation
My ultimate aim is to convert the below code in python to C#, but I'd like to do it my self by learning the python syntax. I understand that the code is recursive.
The code produces polynomials of degree n with k variables. More specifically the list of exponents for each variable.
d... | Python to C# Code Explanation | My ultimate aim is to convert the below code in python to C#, but I'd like to do it my self by learning the python syntax. I understand that the code is recursive.
The code produces polynomials of degree n with k variables. More specifically the list of exponents for each variable.
def multichoose(n,k):
if k < 0 o... | [
"I would use LINQ in C# to translate the code:\n\n[] is the empty list.\nEnumerable.Empty<T>()\n\n[x] is the list containing a single item, x.\nEnumerable.Repeat(x, 1)\n\n[[0]*n] is the list containing the list containing n copies of 0.\nEnumerable.Repeat(Enumerable.Repeat(0, n), 1)\n\n[X for Y in Z] is a list comp... | [
3,
1,
1,
1
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0002128784_c#_python.txt |
Q:
Trying to run a Python program but all that opens is a DOS Window
I just completed a program that should (hopefully) play a GUI Tetris program. I've cleaned up all the syntax errors, but now when I double-click, or go through the Command Prompt to run the program a DOS window pops up for less than a second and dis... | Trying to run a Python program but all that opens is a DOS Window | I just completed a program that should (hopefully) play a GUI Tetris program. I've cleaned up all the syntax errors, but now when I double-click, or go through the Command Prompt to run the program a DOS window pops up for less than a second and disappears without ever running the program.
What's going on?
Heres a lin... | [
"Wow, there's really a huge number of errors in your code. I started running it under pdb, identifying and fixing them one by one, but after 20 or so I gave up. What I fixed so far (in diff's output, lines start with < to mean they're in your version, or with > to mean they're in my partially fixed version). Note... | [
9,
8,
2,
0,
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002129421_python_wxpython.txt |
Q:
How limiting are web frameworks
This is a general question about how limiting are web development frameworks such as Django and ruby-on-rails.
I am planning on building a RESTful web service which will have a purely JSON/XML interface, no GUI. The service will rely on a database however for a few of the more impor... | How limiting are web frameworks | This is a general question about how limiting are web development frameworks such as Django and ruby-on-rails.
I am planning on building a RESTful web service which will have a purely JSON/XML interface, no GUI. The service will rely on a database however for a few of the more important operations there is no clear way... | [
"Web frameworks tend to optimize around building websites, making most normal use cases simpler to accomplish. Once you start to do more \"out of the box\" stuff with a framework, you might find that you spend more time working around it then you save using it in the first place.\nIt's hard to generalize here (esp... | [
8,
6,
5,
2,
1,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"django",
"python",
"rest",
"ruby_on_rails"
] | stackoverflow_0002125865_django_python_rest_ruby_on_rails.txt |
Q:
Using Django's Model API without having to *include* the full Django stack
Currently an application of mine is using SQLAlchemy, but I have been considering the possibility of using Django model API.
Django 1.1.1 is about 3.6 megabytes in size, whereas SQLAlchemy is about 400 kilobytes (as reported by PyPM - whic... | Using Django's Model API without having to *include* the full Django stack | Currently an application of mine is using SQLAlchemy, but I have been considering the possibility of using Django model API.
Django 1.1.1 is about 3.6 megabytes in size, whereas SQLAlchemy is about 400 kilobytes (as reported by PyPM - which is essentially the size of the files installed by python setup.py install).
I ... | [
"The Django ORM is usable on its own - you can use \"settings.configure()\" to set up the database settings. That said, you'll have to do the stripping down and repackaging yourself, and you'll have to experiment with how much you can actually strip away. I'm sure you can ditch contrib/, forms/, template/, and prob... | [
1,
1
] | [] | [] | [
"deployment",
"django",
"python",
"size",
"sqlalchemy"
] | stackoverflow_0002126433_deployment_django_python_size_sqlalchemy.txt |
Q:
copying functions located in instances
Here's some (simplified) code for what I'm trying to do:
class a:
pass
class b:
def printSelf(self):
print self
instOfA = a()
instOfB = b()
instOfA.printSelf = instOfB.printSelf
instOfA.printSelf()
<__main__.b instance at 0x0295D238>
When I call instOfA.p... | copying functions located in instances | Here's some (simplified) code for what I'm trying to do:
class a:
pass
class b:
def printSelf(self):
print self
instOfA = a()
instOfB = b()
instOfA.printSelf = instOfB.printSelf
instOfA.printSelf()
<__main__.b instance at 0x0295D238>
When I call instOfA.printSelf(), it prints self as being instOfB... | [
"You can use the descriptor of the method to get a bound method:\ninstOfA.printSelf = b.printSelf.__get__(instOfA)\n\nOf course, you can use __class__ if you don't know the type of instOfB:\ninstOfA.printSelf = instOfB.__class__.printSelf.__get__(instOfA)\n\nIf instOfA doesn't need the method stored, you can just p... | [
2,
0
] | [] | [] | [
"function",
"multiple_instances",
"python",
"self"
] | stackoverflow_0002129930_function_multiple_instances_python_self.txt |
Q:
Image embossing in Python with PIL -- adding depth, azimuth, etc
I am trying to emboss an image using PIL.
PIL provides a basic way to emboss an image ( using ImageFilter.EMBOSS).
In image editing packages like GIMP, you can vary parameters like Azimuth, depth and elevation in this embossed image.
How to do th... | Image embossing in Python with PIL -- adding depth, azimuth, etc | I am trying to emboss an image using PIL.
PIL provides a basic way to emboss an image ( using ImageFilter.EMBOSS).
In image editing packages like GIMP, you can vary parameters like Azimuth, depth and elevation in this embossed image.
How to do this with PIL? At the very least I want to adjust the "depth" of the emb... | [
"If you cannot achieve your goal by using or combination of operations (like rotating, then applying the EMBOSS filter, the re-rotating), (or enhancing the contrast then embossing) then you may resort to changing (or creating your own) filter matrix.\nWithin ImageFilter.py you will find this class:\n##\n# Embossing... | [
10,
2
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0002034037_image_processing_python_python_imaging_library.txt |
Q:
Is it possible to narrow down the generated query in SQLAlchemy if it was created via query_property?
I have another quick question about SQLAlchemy.
If I have added a query_property [1] field in my SQLAlchemy Table class, is it possible to narrow down the SELECTed fields?
Here is what I mean.
Suppose my class Co... | Is it possible to narrow down the generated query in SQLAlchemy if it was created via query_property? | I have another quick question about SQLAlchemy.
If I have added a query_property [1] field in my SQLAlchemy Table class, is it possible to narrow down the SELECTed fields?
Here is what I mean.
Suppose my class Comments has this:
class Comments:
query = Session.query_property()
...
Then if I do the following:
... | [
"Try using query.values(Comment.comment). Note that it returns generator, not modified query, so this method should called last after applying all filters.\n"
] | [
1
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002128809_python_sql_sqlalchemy.txt |
Q:
Dynamically assign special methods to objects but not classes in Python
I would like to do the following:
class A(object): pass
a = A()
a.__int__ = lambda self: 3
i = int(a)
Unfortunately, this throws:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a s... | Dynamically assign special methods to objects but not classes in Python | I would like to do the following:
class A(object): pass
a = A()
a.__int__ = lambda self: 3
i = int(a)
Unfortunately, this throws:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'A'
This only seems to work if I assign the "special"... | [
"Python always looks up special methods on the class, not the instance (except in the old, aka \"legacy\", kind of classes -- they're deprecated and have gone away in Python 3, because of the quirky semantics that mostly comes from looking up special methods on the instance, so you really don't want to use them, be... | [
8,
2,
0
] | [] | [] | [
"dynamic",
"methods",
"python"
] | stackoverflow_0002129643_dynamic_methods_python.txt |
Q:
Adding a string in front of a string for each item in a list in python
I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change.
n is my list of websites
h is "http"
for p in n:
if p[0]!="h":
... | Adding a string in front of a string for each item in a list in python | I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change.
n is my list of websites
h is "http"
for p in n:
if p[0]!="h":
p= h+ p
else:
continue
return n
when i return the list, it ret... | [
"This could also be done using list comprehension:\nn = [i if i.startswith('h') else 'http' + i for i in n]\n\n",
"You need to reassign the list item -- strings are immutable, so += is making a new string, not mutating the old one. I.e.:\nfor i, p in enumerate(n):\n if not p.startswith('h'):\n n[i] = 'http' ... | [
15,
3,
0,
0
] | [] | [] | [
"for_loop",
"loops",
"python",
"string"
] | stackoverflow_0002130552_for_loop_loops_python_string.txt |
Q:
sqlite python insert
I have asked similar question before , here is detailed explanation of what i'm trying to achieve
I have two sqlite tables
table1 - is standard table - has fields like server,id,status
table2 - has fields like server,id,status,number,logfile
Table2 is empty and Table1 has values. I'm trying ... | sqlite python insert | I have asked similar question before , here is detailed explanation of what i'm trying to achieve
I have two sqlite tables
table1 - is standard table - has fields like server,id,status
table2 - has fields like server,id,status,number,logfile
Table2 is empty and Table1 has values. I'm trying to fill table2 with entrie... | [
"This statement is broken:\nself.cursor.execute(\"insert into server_table2(server,status,id) values (?,?,?)\",(record[0],)(record[1],),(record[2],));\n\nit should read:\nself.cursor.execute(\"insert into server_table2(server,status,id) values (?,?,?)\",record[0:2])\n\nAnd you might want to look into executemany as... | [
3
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0002130641_python_sqlite.txt |
Q:
django error in my code ,what does i do
from django.core.management import setup_environ
from register2 import settings
setup_environ(settings)
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
class AuthenticationRememberMeF... | django error in my code ,what does i do | from django.core.management import setup_environ
from register2 import settings
setup_environ(settings)
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
class AuthenticationRememberMeForm ( AuthenticationForm ):
""... | [
"The django forms module uses a metaclass to facilitate declarative syntax for form fields. As a consequence, you should consider remember_me to be a field of your form instance, not a class attribute. So accessing the field as so makes sense:\nform = AuthenticationRememberMeForm()\nfield_obj = form.fields['remembe... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002129992_django_python.txt |
Q:
Clojure Jython interop
I was wondering if anyone has tried somehow calling Jython functions
from within Clojure, and how you went about doing this if so. I have
not used Jython, but I would imagine the Jython interpreter can be
invoked in the same way as any other java code, and Python programs
can be run within ... | Clojure Jython interop | I was wondering if anyone has tried somehow calling Jython functions
from within Clojure, and how you went about doing this if so. I have
not used Jython, but I would imagine the Jython interpreter can be
invoked in the same way as any other java code, and Python programs
can be run within it. However I wonder if it ... | [
"A note: I just realised that the question is specifically about calling Jython functions from Clojure and not about building a full-fledged Jython-Clojure interop solution... But! I've already produced a smallish write-up on my initial thoughts on the latter and I guess that's the logical next step anyway. I mean,... | [
13
] | [] | [] | [
"clojure",
"interop",
"jython",
"lisp",
"python"
] | stackoverflow_0002129253_clojure_interop_jython_lisp_python.txt |
Q:
Python Qt: Qprinter not defined
I am trying to put the printer to run the output from an html document.
Here is a small function to do that:
def callPrinterHtml(self,document):
self.printer = QPrinter()
self.printer.setPageSize(QPrinter.Letter)
dialog = QPrintDialog(self.printer, self)
if dialog.e... | Python Qt: Qprinter not defined | I am trying to put the printer to run the output from an html document.
Here is a small function to do that:
def callPrinterHtml(self,document):
self.printer = QPrinter()
self.printer.setPageSize(QPrinter.Letter)
dialog = QPrintDialog(self.printer, self)
if dialog.exec_():
document.print_(self.... | [
"\nDid you import the module that contains QPrinter? using an import directive?\nIs the module containing QPrinter in your python path?\n\n"
] | [
2
] | [] | [] | [
"document",
"html",
"printing",
"python",
"qt"
] | stackoverflow_0002130895_document_html_printing_python_qt.txt |
Q:
How to get IUnknown from WDM driver CreateInstance
In documentation (C++ example)
LUnknown* pIUnknown = CreateInstance(slot);
I try this
>> import ctypes
>> print type(ctypes.cdll.lcomp.CreateInstance(0))
<type 'int'>
How to get IUNKNOWN and QueryInterface?
A:
I guess that accessing COM object with ctypes mi... | How to get IUnknown from WDM driver CreateInstance | In documentation (C++ example)
LUnknown* pIUnknown = CreateInstance(slot);
I try this
>> import ctypes
>> print type(ctypes.cdll.lcomp.CreateInstance(0))
<type 'int'>
How to get IUNKNOWN and QueryInterface?
| [
"I guess that accessing COM object with ctypes might be a bit difficult. I would recommend to have a look to win32com included in the windows extensions by Mark Hammond.\nYou can start with this tutorial : http://www.boddie.org.uk/python/COM.html\nI hope it helps\n"
] | [
0
] | [] | [] | [
"com",
"ctypes",
"iunknown",
"python"
] | stackoverflow_0002130559_com_ctypes_iunknown_python.txt |
Q:
Good language to develop a game server in?
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core s... | Good language to develop a game server in? | I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like ... | [
"I hate to say it, and I know I'm risking a down mod here, but it doesn't sound like there's a language out there for you. All programming languages have their quirks and programmers simply have to adapt to them. It's completely possible to write a working server in Python without classes (eliminating the \"self\" ... | [
20,
18,
17,
9,
7,
3,
2,
2,
1,
0,
0,
0,
0,
0
] | [
"C++ and Java are quite slow compared to C. The language should be a tool but not a crutch.\n"
] | [
-1
] | [
"c#",
"java",
"networking",
"python"
] | stackoverflow_0000392624_c#_java_networking_python.txt |
Q:
How can I convert a digraph to an undirected graph in networkx?
I am using the networkx package. Is there a function in networkx which can do the task for me?
A:
I found the function
http://networkx.lanl.gov/reference/generated/networkx.DiGraph.to_undirected.html?highlight=digraph
| How can I convert a digraph to an undirected graph in networkx? | I am using the networkx package. Is there a function in networkx which can do the task for me?
| [
"I found the function \nhttp://networkx.lanl.gov/reference/generated/networkx.DiGraph.to_undirected.html?highlight=digraph\n"
] | [
5
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0002131005_networkx_python.txt |
Q:
Classes, methods, and polymorphism in Python
I made a module prototype with the aim of building complex timer schedules in python. The class prototypes emulate Timer objects, each with their waiting times, Repeat objects that group Timer and other Repeat objects, and a Schedule class, just for holding a whole cons... | Classes, methods, and polymorphism in Python | I made a module prototype with the aim of building complex timer schedules in python. The class prototypes emulate Timer objects, each with their waiting times, Repeat objects that group Timer and other Repeat objects, and a Schedule class, just for holding a whole construction or Timers and Repeat instances. The const... | [
"The duck-typing-based approach is fine. If you want to be able to check if a given class is supposed to run in your framework, you can use Abstract Base Classes (needs Python 2.6). PEP 3119 states:\n\n[...] there are many different ways to test whether an object conforms to a particular protocol or not. For exampl... | [
6,
3,
2
] | [] | [] | [
"oop",
"polymorphism",
"python",
"timer"
] | stackoverflow_0002129891_oop_polymorphism_python_timer.txt |
Q:
Google App Engine (python) authorization web services /third party client
I have a google app engine project and i want to make my REST API available to third parties. Like twitter API.
Twitter requests the user and password to be sent so thet they can be authorized - can i do this with google user accounts?
I ha... | Google App Engine (python) authorization web services /third party client | I have a google app engine project and i want to make my REST API available to third parties. Like twitter API.
Twitter requests the user and password to be sent so thet they can be authorized - can i do this with google user accounts?
I have read somewhere on this site this is not a prefered method as their credentia... | [
"OAuth was created with this situation in mind. It's a specification for the sort of auth-token scheme you just described, and it's reasonably widespread these days.\nFor balance, see this recent StackOverflow thread.\n"
] | [
1
] | [] | [] | [
"authorization",
"google_app_engine",
"python",
"rest"
] | stackoverflow_0002130899_authorization_google_app_engine_python_rest.txt |
Q:
posix_memalign within python
I cannot seem to figure it out why the following does not work
import ctypes
from ctypes.util import find_library
libc = ctypes.CDLL(find_library('c'))
userpointer = ctypes.c_void_p
sizeimage = 320*240*2
if libc.posix_memalign(userpointer, libc.getpagesize(), sizeimage) != 0:
rai... | posix_memalign within python | I cannot seem to figure it out why the following does not work
import ctypes
from ctypes.util import find_library
libc = ctypes.CDLL(find_library('c'))
userpointer = ctypes.c_void_p
sizeimage = 320*240*2
if libc.posix_memalign(userpointer, libc.getpagesize(), sizeimage) != 0:
raise Exception('ENOMEM')
I am tryin... | [
"You have two problems in your code: you make userpointer the ctypes.c_void_p type rather than an instance of it, and you're passing the void* that is userpointer to posix_memalign directly, instead of the void** that posix_memalign requires. The following will do what you want:\nimport ctypes\nfrom ctypes.util imp... | [
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0002131946_ctypes_python.txt |
Q:
saving python variable to .mat file with scipy.io.savemat
Here is my python code.
>>import numpy as np
>>import scipy.io
>>exon = [ np.array([[1, 2], [3, 4], [5, 6]]), np.array([[7, 8], [9, 10]]) ]
>>obj_arr = np.zeros((2,), dtype=np.object)
>>obj_arr[0] = exon[0]
>>obj_arr[1] = exon[1]
>>scipy.io.savemat('/tmp/o... | saving python variable to .mat file with scipy.io.savemat | Here is my python code.
>>import numpy as np
>>import scipy.io
>>exon = [ np.array([[1, 2], [3, 4], [5, 6]]), np.array([[7, 8], [9, 10]]) ]
>>obj_arr = np.zeros((2,), dtype=np.object)
>>obj_arr[0] = exon[0]
>>obj_arr[1] = exon[1]
>>scipy.io.savemat('/tmp/out.mat', mdict={'exon': obj_arr}, format='5')
But I am getting... | [
"Looks like your scipy.io.savemat() doesn't take a 'format' keyword. Looks like it was added in SciPy 0.7, perhaps you need to upgrade?\n"
] | [
3
] | [] | [] | [
"mat_file",
"python",
"scipy",
"typeerror"
] | stackoverflow_0002132106_mat_file_python_scipy_typeerror.txt |
Q:
Python: Best method to reload class in XMLRPC Server
I have a multit-threaded xmlrpc service running which stores a huge amount of data ~2G in memory. Currently, if I want to update a method the server exposes I have to restart the service. The problem here is that if I restart the service it needs to load all o... | Python: Best method to reload class in XMLRPC Server | I have a multit-threaded xmlrpc service running which stores a huge amount of data ~2G in memory. Currently, if I want to update a method the server exposes I have to restart the service. The problem here is that if I restart the service it needs to load all of the data it had in memory back into memory by using a da... | [
"You could use the reload method. You would need to write some code to check the last modified time of the modules file.\n",
"If reload doesn't work, you could try twisted.python.rebuild; your application need not be written in Twisted to use this twisted.python utility.\nI also recently saw this livecoding thing... | [
4,
1
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0002064935_python_xml_rpc.txt |
Q:
Function called three times when in facebook?
I'm using the following code to add one to two values in case the user wins a challege.
def challengewin(request):
uid = 1313693
tempuser = User.objects.get(id=uid)
tempuser.challengeswon = tempuser.challengeswon + 1
tempuser.silver = tempuser.silver + ... | Function called three times when in facebook? | I'm using the following code to add one to two values in case the user wins a challege.
def challengewin(request):
uid = 1313693
tempuser = User.objects.get(id=uid)
tempuser.challengeswon = tempuser.challengeswon + 1
tempuser.silver = tempuser.silver + 1
tempuser.save()
return HttpResponse()
th... | [
"I would guess that the code you have included is not the culprit.\nHave you confirmed that challengewin(request); is not being called 3 times?\n"
] | [
0
] | [] | [] | [
"facebook",
"python"
] | stackoverflow_0002132215_facebook_python.txt |
Q:
Using Python like PHP in Apache/Windows
I understand that I should use mod_wsgi to run Python, and I have been trying to get that set up, but I'm confused about it:
This is a sample configuration I found for web.py:
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias /appname /var/www/webpy-app/code.py/
A... | Using Python like PHP in Apache/Windows | I understand that I should use mod_wsgi to run Python, and I have been trying to get that set up, but I'm confused about it:
This is a sample configuration I found for web.py:
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias /appname /var/www/webpy-app/code.py/
Alias /appname/static /var/www/webpy-app/stati... | [
"Most similar to the PHP model is perhaps Python Server Pages, PSP.\nmod_python has a PSP handler. The files you create look like this:\n<html>\n<body>\n<%\nfor n in range(3):\n # This indent will persist\n%>\n<p>This paragraph will be \nrepeated 3 times.</p>\n<%\n# This line will cause the block to end\n%>\nThis ... | [
6,
4,
2,
2,
1
] | [] | [] | [
"apache",
"configuration",
"python"
] | stackoverflow_0002131417_apache_configuration_python.txt |
Q:
How to run two functions simultaneously
I am running test but I want to run 2 functions at the same time. I have a camera and I am telling it to move via suds, I am then logging into the camera via SSH to check the speed the camera is set to. When I check the speed the camera has stopped so no speed is available. ... | How to run two functions simultaneously | I am running test but I want to run 2 functions at the same time. I have a camera and I am telling it to move via suds, I am then logging into the camera via SSH to check the speed the camera is set to. When I check the speed the camera has stopped so no speed is available. Is there a way I can get these functions to r... | [
"Import the threading module and run SudsMove() like so:\nthreading.Thread(target = SudsMove).start()\n\nThat will create and start a background thread which does the movement.\nANSWER TO EDITED QUESTION:\nAs far as I understand this, TestAbsoluteMove.Ssh(self) polls the speed once and stores the result in self.Val... | [
13,
6,
2,
1
] | [] | [] | [
"function",
"multithreading",
"python",
"synchronization",
"testing"
] | stackoverflow_0002108126_function_multithreading_python_synchronization_testing.txt |
Q:
How to return the count of related entities in sqlalchemy query
I'm new to sqlalchemy, and while the documentation seems fairly thorough, I couldn't find a way to do quite what I want.
Say I have two tables: forum and post. Each forum has a parent forum, and any number of posts. What I want is:
A list of top-leve... | How to return the count of related entities in sqlalchemy query | I'm new to sqlalchemy, and while the documentation seems fairly thorough, I couldn't find a way to do quite what I want.
Say I have two tables: forum and post. Each forum has a parent forum, and any number of posts. What I want is:
A list of top-level forums
Eagerly loaded child forums accessible through the top-level... | [
"Because you want the post count to be accessible on the child Forum objects you'll need to declare it as a column property when setting up the mappers. The column property declaration should look something like this (assuming you use declarative):\nForum.post_count = column_property(select([func.count()],\n ... | [
8
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002125041_python_sql_sqlalchemy.txt |
Q:
Parse .strings file with Python
I'm trying to write a small Python script to parse the .strings file in my iPhone application project and determine which keys might not be in use. I'm, also doing some string matching to filter out some of the results. This is where my problems start :). If I try something like
for... | Parse .strings file with Python | I'm trying to write a small Python script to parse the .strings file in my iPhone application project and determine which keys might not be in use. I'm, also doing some string matching to filter out some of the results. This is where my problems start :). If I try something like
for file_line in strings_file:
i... | [
"Use correct encoding to open the .strings-file and in your source code. According to documentation the encoding of your file could be utf-16.\n# -*- coding: utf-8 -*-\nimport codecs\n\nfor line in codecs.open(u'your_file.strings', encoding='utf-16'):\n if u'keyword' in line:\n # process line\n\n",
"No e... | [
3,
2,
0
] | [] | [] | [
"core_foundation",
"iphone",
"objective_c",
"python"
] | stackoverflow_0002132291_core_foundation_iphone_objective_c_python.txt |
Q:
TextMate and Django Integration - Supporting {% %} markup
I have installed a TextMate bundle that I believe enables the ability for automatic closing of the "{{" markup (so that it will automatically close the markup with "}}"), but this does not seem to be possible with the other markup that uses "{%" and "%}".
S... | TextMate and Django Integration - Supporting {% %} markup | I have installed a TextMate bundle that I believe enables the ability for automatic closing of the "{{" markup (so that it will automatically close the markup with "}}"), but this does not seem to be possible with the other markup that uses "{%" and "%}".
So, I was wondering if anyone out there knows how to get TextMat... | [
"It's possible - the Rails bundle does this for ERB (<% automatically gets closing %> tags).\nSo that's a place you could go look.\n",
"I don't think that's possible, but the Django bundle for TextMate does allow you to insert the opening and closing tags in one go, placing the cursor in the middle, with ctrl-% (... | [
2,
1
] | [] | [] | [
"django",
"python",
"textmate"
] | stackoverflow_0002127956_django_python_textmate.txt |
Q:
ArcGIS: accessing python list output from listFields geoprocessor
I'm trying to access the output from the listFields geoprocessing object using the following code:
sFields = gp.ListFields(linktofeatureclass)
for j in range(len(sFields)):
print sFields[j]
How do I get information about the fields that I have ... | ArcGIS: accessing python list output from listFields geoprocessor | I'm trying to access the output from the listFields geoprocessing object using the following code:
sFields = gp.ListFields(linktofeatureclass)
for j in range(len(sFields)):
print sFields[j]
How do I get information about the fields that I have enumerated? Printing them (i.e. sFields in the above) just returns "geo... | [
"try this:\nsFields = gp.ListFields(linktofeatureclass)\nfor field in sFields:\n print field.Name, field.Type, field.Scale\n\nFor more information, consult with the docs.\n"
] | [
1
] | [] | [] | [
"arcgis",
"python"
] | stackoverflow_0002133576_arcgis_python.txt |
Q:
How to import or include data structures (e.g. a dict) into a Python file from a separate file
I know I can include Python code from a common file using import MyModuleName - but how do I go about importing just a dict?
The problem I'm trying to solve is I have a dict that needs to be in a file in an editable loca... | How to import or include data structures (e.g. a dict) into a Python file from a separate file | I know I can include Python code from a common file using import MyModuleName - but how do I go about importing just a dict?
The problem I'm trying to solve is I have a dict that needs to be in a file in an editable location, while the actual script is in another file. The dict might also be edited by hand, by a non-pr... | [
"Just import it\nimport myDict\nprint myDict.airportCode\n\nor, better\nfrom myDict import airportCode\nprint airportCode\n\nJust be careful to put both scripts on the same directory (or make a python package, a subdir with __init__.py file; or put the path to script.py on the PYTHONPATH; but these are \"advanced o... | [
74,
16,
2,
2,
2,
1,
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0002132985_import_module_python.txt |
Q:
Paramiko equvalent of pipeline controls and input/output pipes
I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as:
ssh server "cat remote_file" > local_file
with... | Paramiko equvalent of pipeline controls and input/output pipes | I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as:
ssh server "cat remote_file" > local_file
with paramiko channels?
Can paramiko.Transport.open_channel() or Message... | [
"The following may be useful as a starting point (e.g. ./sshpipe host \"command\"):\n#! /usr/bin/env python\n\nimport sys\nimport paramiko\n\ndef sshpipe(host, line) :\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(host)\n stdin, stdout, s... | [
3
] | [] | [] | [
"file",
"paramiko",
"python",
"transfer"
] | stackoverflow_0002133326_file_paramiko_python_transfer.txt |
Q:
put stockprices into groups when they are within 0.5% of each other
Thanks for the answers, I have not used StackOverflow before so I was suprised by the number of answers and the speed of them - its fantastic.
I have not been through the answers properly yet, but thought I should add some information to the probl... | put stockprices into groups when they are within 0.5% of each other | Thanks for the answers, I have not used StackOverflow before so I was suprised by the number of answers and the speed of them - its fantastic.
I have not been through the answers properly yet, but thought I should add some information to the problem specification. See the image below.
I can't post an image in this beca... | [
"I suggest a repeated use of k-means clustering -- let's call it KMC for short. KMC is a simple and powerful clustering algorithm... but it needs to \"be told\" how many clusters, k, you're aiming for. You don't know that in advance (if I understand you correctly) -- you just want the smallest k such that no two i... | [
3,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"cluster_analysis",
"grouping",
"list",
"python",
"stocks"
] | stackoverflow_0002130202_cluster_analysis_grouping_list_python_stocks.txt |
Q:
gtk.Builder() and multiple glade files breaks
I have a glade gui, and I want to insert another object using a glade file as well.
When I do it as bellow (this is essentially what I am doing) the whole app hangs and the self.show() and maxes out the CPU at 100%. If I replace the first line of one's init() with s... | gtk.Builder() and multiple glade files breaks | I have a glade gui, and I want to insert another object using a glade file as well.
When I do it as bellow (this is essentially what I am doing) the whole app hangs and the self.show() and maxes out the CPU at 100%. If I replace the first line of one's init() with self.builder = gtk.Builder() then the app runs, I ca... | [
"Is there a good reason for using the same gtk.Builder object in two classes?\nThis might be the cause of your problem. In your one class, you load a glade file but you never do anything with its widgets. Something like this should work:\nclass one(gtk.VBox):\n\n def __init__(self):\n gtk.VBox.__init__(self)\n ... | [
3
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0002129369_gtk_pygtk_python.txt |
Q:
Most Pythonic way to concatenate strings
Given this harmless little list:
>>> lst = ['o','s','s','a','m','a']
My goal is to Pythonically concatenate the little devils using one of the following ways:
A. A plain old string function to get the job done, short, no imports
>>> ''.join(lst)
'ossama'
B. Lambda, lambda... | Most Pythonic way to concatenate strings | Given this harmless little list:
>>> lst = ['o','s','s','a','m','a']
My goal is to Pythonically concatenate the little devils using one of the following ways:
A. A plain old string function to get the job done, short, no imports
>>> ''.join(lst)
'ossama'
B. Lambda, lambda, lambda
>>> reduce(lambda x, y: x + y, lst)
'... | [
"''.join(lst)\n\nThe only Pythonic way:\n\nclear (that is what all the big boys do and what they expect to see),\nsimple (no additional imports needed, and stable across all versions),\nfast (written in C) and\nconcise (on an empty string, join elements of iterable!).\n\n",
"Have a look at Guido's essay on Python... | [
71,
40,
18,
8,
6,
4
] | [] | [] | [
"concatenation",
"python"
] | stackoverflow_0002133571_concatenation_python.txt |
Q:
Filtering models with ReferenceProperties
I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.
eg.
class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(G... | Filtering models with ReferenceProperties | I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.
eg.
class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(Group)
user = db.ReferenceProperty(User)
An... | [
"If your groups are uniquely named, then your \"group.name\" is a unique identifier of a Group entity.\nThat means you can write:\n members = models.GroupMember.all().filter(\n \"group =\",model.Group.gql(\"WHERE name=:1\", group_name).get()\n )\n\nthough you only need to do that if you don't already have th... | [
5,
4,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000448120_google_app_engine_python.txt |
Q:
gnomevfs or gio?
For async IO using Python, is it preferable to rely on gio or gnomevfs?
Also, which one is more "cross-platform"?
A:
Use GIO.
GnomeVFS has been deprecated since GNOME 2.22, in favour of GIO.
| gnomevfs or gio? | For async IO using Python, is it preferable to rely on gio or gnomevfs?
Also, which one is more "cross-platform"?
| [
"Use GIO.\nGnomeVFS has been deprecated since GNOME 2.22, in favour of GIO.\n"
] | [
4
] | [] | [] | [
"gio",
"python"
] | stackoverflow_0002134691_gio_python.txt |
Q:
PID files hanging around for daemons after server restart
I have some daemons that use PID files to prevent parallel execution of my program. I have set up a signal handler to trap SIGTERM and do the necessary clean-up including the PID file. This works great when I test using "kill -s SIGTERM #PID". However, w... | PID files hanging around for daemons after server restart | I have some daemons that use PID files to prevent parallel execution of my program. I have set up a signal handler to trap SIGTERM and do the necessary clean-up including the PID file. This works great when I test using "kill -s SIGTERM #PID". However, when I reboot the server the PID files are still hanging around ... | [
"Use flock (or lockf) on your pidfile, if it succeeds, you can rewrite the pidfile and continue.\nThis SO answer has a good example on how this is done.\n",
"Not a direct solution but it might be a good idea to check for an actual process running with the pid in the pid file at startup and if none exists, to clea... | [
4,
3,
2
] | [] | [] | [
"linux",
"python",
"sigterm"
] | stackoverflow_0002134732_linux_python_sigterm.txt |
Q:
Looking for input in model design for Django Schools
Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.
Before ... | Looking for input in model design for Django Schools | Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input.
Before I show you the current model layout, you need to have an i... | [
"From a quick look I think that its fairly comprehensive. Perhaps you should allow multiple teachers on a course, and allow reuse of addresses/locations between parents and students.\nAs a general rule I would say that you should start implementing and then you will find where you need improvement.\n",
"Some poss... | [
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000344826_django_django_models_python.txt |
Q:
Writing Pythons Errors to a txt file
I am having trouble getting this to work correctly (obviously) - I am ALMOST there, and I have a good idea of WHY it is not working - just not sure how to make it work.
This is suppose to attempt to read a file into memory, if it fails it goes to the "except" clause of the bl... | Writing Pythons Errors to a txt file | I am having trouble getting this to work correctly (obviously) - I am ALMOST there, and I have a good idea of WHY it is not working - just not sure how to make it work.
This is suppose to attempt to read a file into memory, if it fails it goes to the "except" clause of the block of code (that part is 'duh'). The err... | [
"First, you should use a logging library. It will help you deal with different logging levels (info/warn/error), timestamps and more.\nhttp://docs.python.org/library/logging.html\nSecond, you need to catch the error, and then you can log details about it. This example comes from the Python documentation.\nimport sy... | [
7,
3,
1,
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0002135174_error_handling_python.txt |
Q:
Using LaTeX Beamer to display code
I'm using the following LaTeX code in a Beamer presentation:
\begin{frame}
\begin{figure}
\centering
\tiny
\lstset{language=python}
\lstinputlisting{code/get_extent.py}
\end{figure}
\end{frame}
Is it possible to select specific lines from my get_extent.p... | Using LaTeX Beamer to display code | I'm using the following LaTeX code in a Beamer presentation:
\begin{frame}
\begin{figure}
\centering
\tiny
\lstset{language=python}
\lstinputlisting{code/get_extent.py}
\end{figure}
\end{frame}
Is it possible to select specific lines from my get_extent.py file rather than displaying it all?
| [
"This has nothing to do with beamer; it's about a listings feature. Its excellent manual has more. For example:\n\\lstinputlisting[firstline=2,lastline=5]{code/get_extent.py}\n\n"
] | [
12
] | [] | [] | [
"beamer",
"latex",
"python"
] | stackoverflow_0002135339_beamer_latex_python.txt |
Q:
python: processing a 16-element list into an 8-element list
I have a list of 16 elements [a00,a01,a02,...,a15] and would like to compute a list [b0,b1,b2,b3,b4,b5,b6,b7] where
b0 = a00*256+a01
b1 = a02*256+a03
b2 = a04*256+a05
(etc.)
what's the easiest way of doing this? (I'm a beginner in python)
A:
b_list = ... | python: processing a 16-element list into an 8-element list | I have a list of 16 elements [a00,a01,a02,...,a15] and would like to compute a list [b0,b1,b2,b3,b4,b5,b6,b7] where
b0 = a00*256+a01
b1 = a02*256+a03
b2 = a04*256+a05
(etc.)
what's the easiest way of doing this? (I'm a beginner in python)
| [
"b_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(8)]\nNote that this only works if a has 16 elements.\nA more general solution would be:\nb_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(len(a_list) / 2)]\nas long as a_list has an even number of elements.\n",
"Not to get too golfy, but if you... | [
4,
4,
2,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002135454_list_python.txt |
Q:
parsing a text string for dates - not the standard convert problem!
Does anyone know of a library - ideally Python, that can have a stab at pulling dates out of text?
"Shall we go to the library today" -> 21 Jan 10
"Starting on the 1st of January" -> 1 Jan 10
"Anytime between 3nd and 5th of Feb 2009" -> 3 Feb 09... | parsing a text string for dates - not the standard convert problem! | Does anyone know of a library - ideally Python, that can have a stab at pulling dates out of text?
"Shall we go to the library today" -> 21 Jan 10
"Starting on the 1st of January" -> 1 Jan 10
"Anytime between 3nd and 5th of Feb 2009" -> 3 Feb 09, 5 Feb 09
It's a tough problem and probably why I havn't found anything!... | [
"Looks like this module is what you are looking for: parsedatetime\n",
"The PyParsing site has a little bonus script for parsing time expressions. I would say that is worth a look for you!\nEdit: I see you already ended up there as I was typing my suggestion. Good luck to you!\n",
"Thanks for the contributions... | [
4,
2,
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0002109014_parsing_python.txt |
Q:
Creating a socket restricted to localhost connections only
I have a python program with many threads. I was thinking of creating a socket, bind it to localhost, and have the threads read/write to this central location. However I do not want this socket open to the rest of the network, just connections from 127.0.0... | Creating a socket restricted to localhost connections only | I have a python program with many threads. I was thinking of creating a socket, bind it to localhost, and have the threads read/write to this central location. However I do not want this socket open to the rest of the network, just connections from 127.0.0.1 should be accepted. How would I do this (in Python)? And is t... | [
"Given a socket created with socket.socket(), you can use bind() before listening:\nsocket.bind(('127.0.0.1', 80))\n\nUsing the address 127.0.0.1 indicates that the socket should bind to the local interface only.\n",
"http://www.amk.ca/python/howto/sockets/\nShows some socket example. This tidbit is interesting t... | [
8,
5,
3,
2,
0,
0
] | [] | [] | [
"client_server",
"python"
] | stackoverflow_0002135595_client_server_python.txt |
Q:
Enumerate a DateRange
I have 2 dates and I am trying to build labels of an x-axis of a plot.
As such, I need a way to take 2 datetime objects, i.e 2009-10-12 00:00:00 and 2009-10-20 00:00:00 and generate a list like so:
["2009-10-12", "2009-10-13", "2009-10-14", ..., "2009-10-19", "2009-10-20"]
What libraries sh... | Enumerate a DateRange | I have 2 dates and I am trying to build labels of an x-axis of a plot.
As such, I need a way to take 2 datetime objects, i.e 2009-10-12 00:00:00 and 2009-10-20 00:00:00 and generate a list like so:
["2009-10-12", "2009-10-13", "2009-10-14", ..., "2009-10-19", "2009-10-20"]
What libraries should I use to assist? I hav... | [
"import datetime\n\nfirst=datetime.date(2009,10,12)\nlast=datetime.date(2009,10,20)\nadate=first\ndates=[]\nwhile adate<=last:\n dates.append(adate)\n adate+=datetime.timedelta(1)\nprint(dates)\n\nOr, for lovers of list comprehension:\nlen=(last-first).days\ndates=[first+datetime.timedelta(n) for n in range(l... | [
2,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002136151_datetime_python.txt |
Q:
Interacting with a verified location? - Google Maps
Ok so there are loads of Businesses marked on Google Maps these days.
But I cannot interact with these in any way.
This is the information I have:
venue name: Ministry of Sound
address: 103 Gaunt Street London, SE1 6DP
Google's Geolocation only gives me
Coordi... | Interacting with a verified location? - Google Maps | Ok so there are loads of Businesses marked on Google Maps these days.
But I cannot interact with these in any way.
This is the information I have:
venue name: Ministry of Sound
address: 103 Gaunt Street London, SE1 6DP
Google's Geolocation only gives me
Coordinates (lat, long)
Formatted Address
I want an applicat... | [
"In response to your edited question: \nYou should look at microformats like hReview, Google indexes and uses these in search results if not on the page you linked to. See: http://googlewebmastercentral.blogspot.com/2009/05/introducing-rich-snippets.html\n",
"I think there is a certain confusion here. The main re... | [
2,
1,
1,
0
] | [] | [] | [
"django",
"google_maps",
"javascript",
"python"
] | stackoverflow_0002121780_django_google_maps_javascript_python.txt |
Q:
Dynamic Django model creation based on existing DB table
I'm trying to figure out how I can use the type() module to dynamically create a Django model based on existing DB tables without having to either write it out manually or use the manage.py generator to inspect the DB. Reason is my schema changes frequently... | Dynamic Django model creation based on existing DB table | I'm trying to figure out how I can use the type() module to dynamically create a Django model based on existing DB tables without having to either write it out manually or use the manage.py generator to inspect the DB. Reason is my schema changes frequently -- adding new tables, adding/deleting columns, etc. Anyone h... | [
"You can look at inspectdb code, and instead of outputting code return classes.\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002136371_django_django_models_python.txt |
Q:
Python / Linux/ Daemon process trying to show gtk.messagedialog
on Ubuntu 8/9,
i'm trying to write a daemon in python, that monitors a certain network condition and informs the user using a gtk.messagedialog.
I installed this script using rc-update.
The daemon starts at boot, but doesn't show the dialog even afte... | Python / Linux/ Daemon process trying to show gtk.messagedialog | on Ubuntu 8/9,
i'm trying to write a daemon in python, that monitors a certain network condition and informs the user using a gtk.messagedialog.
I installed this script using rc-update.
The daemon starts at boot, but doesn't show the dialog even after I login. I assume because init.d starts my daemon at tty1 and no gn... | [
"If five users are logged in to X sessions, who gets the message? Everyone?\nIf someone is logged in locally but only using the tty, and not X11, should they see the message?\nIf someone is logged in remotely via ssh -X to run a graphic application on their own system off of your CPU, should they see the message? H... | [
3,
0,
0
] | [] | [] | [
"daemon",
"gtk",
"linux",
"python",
"ubuntu"
] | stackoverflow_0002124455_daemon_gtk_linux_python_ubuntu.txt |
Q:
pyinstaller exe's not dying after sys.exit()
I have a cherrypy app compiled with pyinstaller. One function does the following:
cherrypy.engine.stop()
sys.exit()
the cherrypy engine stops without problem, but the process doesn't actually die and I can't figure out why.
A:
Try with os._exit(), which is a real sy... | pyinstaller exe's not dying after sys.exit() | I have a cherrypy app compiled with pyinstaller. One function does the following:
cherrypy.engine.stop()
sys.exit()
the cherrypy engine stops without problem, but the process doesn't actually die and I can't figure out why.
| [
"Try with os._exit(), which is a real system exit. I can't see why PyInstaller should change a thing when it comes to process quitting, though.\n",
"One thing to keep in mind: sys.exit() doesn't actually kill the process: it raises SystemExit, which usually results in the process ending, but doesn't have to.\n"
] | [
1,
0
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0002129935_pyinstaller_python.txt |
Q:
Using multiple modules/types with Python C API?
I've got two different Python extension modules; let's call them A and B. Module A contains a storage class type called container that I want to use within Module B as the return type of a class method.
I can't seem to find any documentation on how I'm supposed to... | Using multiple modules/types with Python C API? | I've got two different Python extension modules; let's call them A and B. Module A contains a storage class type called container that I want to use within Module B as the return type of a class method.
I can't seem to find any documentation on how I'm supposed to do this. I roughly followed this article to create ... | [
"Your problem is that type->tp_init doesn't do what you want. type->tp_init is called after an object is allocated to do the instantiation. You'd first have to allocate the object using type->tp_new, then pass that object as the first argument to type->tp_init. Since you pass an uninitialized pointer to tp_init, al... | [
3
] | [] | [] | [
"binding",
"c",
"python",
"python_c_api",
"python_extensions"
] | stackoverflow_0002136337_binding_c_python_python_c_api_python_extensions.txt |
Q:
Python web frontend, retaining interpreter state
I have a python script that parses a large set of data into an internal memory structure, and implements various fetch functions on the structure.
I want to built a simple web frontend for this script, with the condition that the data is only initialized/loaded once... | Python web frontend, retaining interpreter state | I have a python script that parses a large set of data into an internal memory structure, and implements various fetch functions on the structure.
I want to built a simple web frontend for this script, with the condition that the data is only initialized/loaded once (since re-loading upon each fetch would consume too m... | [
"I have implemented a solution to a very similar problem. My solution was to use an xmlrpc server, specifically \ntwisted.web.xmlrpc\n\nI have a method that allows for injection of new data, and have methods for retrieving the data. \n",
"Use a persistent server like CherryPy or Twisted Web. All requests will ... | [
1,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0002136457_php_python.txt |
Q:
Read last n lines of file (tail) without reading it line-by-line?
Possible Duplicate:
Get last n lines of a file with Python, similar to tail
Hello,
How can I have Python return the last n lines of a file without reading it line by line?
A:
Something like this:
Use seek() to get something like the last 4096 b... | Read last n lines of file (tail) without reading it line-by-line? |
Possible Duplicate:
Get last n lines of a file with Python, similar to tail
Hello,
How can I have Python return the last n lines of a file without reading it line by line?
| [
"Something like this:\n\nUse seek() to get something like the last 4096 bytes of a file.\nSee how many newlines you have in those bytes. If you have n or more, then you're done. If you have fewer, then read the previous 4096 bytes until you're done.\n\nNot sure if there's a built-in way to do this.\n"
] | [
1
] | [] | [] | [
"file",
"file_io",
"python",
"tail"
] | stackoverflow_0002136800_file_file_io_python_tail.txt |
Q:
python Qt: main widget scroll bar
We are trying to put scrollbar on the main widget, so if the user resizes the main window, the scrollbar appears, and let he move up and down to see child widgets that is outside the smaller window widget, allowing it to move right and left.
Here is the code for the main widget wi... | python Qt: main widget scroll bar | We are trying to put scrollbar on the main widget, so if the user resizes the main window, the scrollbar appears, and let he move up and down to see child widgets that is outside the smaller window widget, allowing it to move right and left.
Here is the code for the main widget with the scroll-bar..
def centralWDG(self... | [
"You use centralWidget (which is a QWidget) as the central widget of the main window, the scroll area is never added to the window. Having it contain the central widget is not enough.\nThe following code has been generated by pyuic:\ndef setupUi(self, MainWindow):\n self.centralwidget = QtGui.QWidget(MainWindow)... | [
3,
1
] | [] | [] | [
"python",
"qt",
"scrollbar",
"widget"
] | stackoverflow_0002130446_python_qt_scrollbar_widget.txt |
Q:
shared data utilizing multiple processor in python
I have a cpu intensive code which uses a heavy dictionary as data (around 250M data). I have a multicore processor and want to utilize it so that i can run more than one task at a time. The dictionary is mostly read only and may be updated once a day.
How can i w... | shared data utilizing multiple processor in python | I have a cpu intensive code which uses a heavy dictionary as data (around 250M data). I have a multicore processor and want to utilize it so that i can run more than one task at a time. The dictionary is mostly read only and may be updated once a day.
How can i write this in python without duplicating the dictionary?
... | [
"Use shelve for the dictionary. Since writes are infrequent there shouldn't be an issue with sharing it.\n",
"You can share read-only data among processes simply with a fork (on Unix; no easy way on Windows), but that won't catch the \"once a day change\" (you'd need to put an explicit way in place for each proce... | [
1,
1,
0
] | [] | [] | [
"concurrency",
"python",
"shared_memory"
] | stackoverflow_0002136885_concurrency_python_shared_memory.txt |
Q:
Python multiple inheritance: which __new__ to call?
I have a class Parent. I want to define a __new__ for Parent so it does some magic upon instantiation (for why, see footnote). I also want children classes to inherit from this and other classes to get Parent's features. The Parent's __new__ would return an insta... | Python multiple inheritance: which __new__ to call? | I have a class Parent. I want to define a __new__ for Parent so it does some magic upon instantiation (for why, see footnote). I also want children classes to inherit from this and other classes to get Parent's features. The Parent's __new__ would return an instance of a subclass of the child class's bases and the Pare... | [
"I think this will get you what you want:\nreturn super(Parent, cls).__new__(cls, *args, **kwargs)\n\nand you won't need the bases keyword argument. Unless I'm getting you wrong and you're putting that in there on purpose.\n"
] | [
4
] | [] | [] | [
"class_hierarchy",
"multiple_inheritance",
"new_operator",
"python"
] | stackoverflow_0002137150_class_hierarchy_multiple_inheritance_new_operator_python.txt |
Q:
Web2Py Working Directory
Well I want to use WEb2Py because it's pretty nice..
I just need to change the working directory to the directory where all my modules/libraries/apps are so i can use them. I want to be able to import my real program when I use the web2py interface/applications. I need to do this instead ... | Web2Py Working Directory | Well I want to use WEb2Py because it's pretty nice..
I just need to change the working directory to the directory where all my modules/libraries/apps are so i can use them. I want to be able to import my real program when I use the web2py interface/applications. I need to do this instead of putting all my apps and stu... | [
"In any multi-threaded Python program (and not only Python) you should not use os.chdir and you should not change sys.path when you have more than one thread running. It is not safe because it affects other threads. Moreover you should not sys.path.append() in a loop because it may explode.\nAll web frameworks are ... | [
5,
0,
0
] | [] | [] | [
"directory",
"python",
"web2py"
] | stackoverflow_0001978188_directory_python_web2py.txt |
Q:
Pyparsing - where order of tokens in unpredictable
I want to be able to pull out the type and count of letters from a piece of text where the letters could be in any order. There is some other parsing going on which I have working, but this bit has me stumped!
input -> result
"abc" -> [['a',1], ['b',1],['c',1]]... | Pyparsing - where order of tokens in unpredictable | I want to be able to pull out the type and count of letters from a piece of text where the letters could be in any order. There is some other parsing going on which I have working, but this bit has me stumped!
input -> result
"abc" -> [['a',1], ['b',1],['c',1]]
"bbbc" -> [['b',3],['c',1]]
"cccaa" -> [['a',2],['c',3]... | [
"One solution:\ntext = 'sufja srfjhvlasfjkhv lasjfvhslfjkv hlskjfvh slfkjvhslk'\nprint([(x,text.count(x)) for x in set(text)])\n\nNo pyparsing involved, but it seems like overkill.\n",
"I wasn't clear from your description whether the input characters could be mixed like \"ababc\", since in all your test cases, t... | [
6,
6,
3,
2,
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0002134416_pyparsing_python.txt |
Q:
multiprocess or threading in python?
I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequent... | multiprocess or threading in python? | I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel.... | [
"If you are truly compute bound, using the multiprocessing module is probably the lightest weight solution (in terms of both memory consumption and implementation difficulty.)\nIf you are I/O bound, using the threading module will usually give you good results. Make sure that you use thread safe storage (like the ... | [
30,
9,
7,
7,
0,
0,
0,
0
] | [] | [] | [
"multiprocess",
"multithreading",
"python"
] | stackoverflow_0001226584_multiprocess_multithreading_python.txt |
Q:
Python,multi-threads,fetch webpages,download webpages
I want to batch dowload webpages in one site. There are 5000000 urls links in my 'urls.txt' file. It's about 300M. How make a multi-threads link these urls and dowload these webpages? or How batch dowload these webpages?
my ideas:
with open('urls.txt','r') as f... | Python,multi-threads,fetch webpages,download webpages | I want to batch dowload webpages in one site. There are 5000000 urls links in my 'urls.txt' file. It's about 300M. How make a multi-threads link these urls and dowload these webpages? or How batch dowload these webpages?
my ideas:
with open('urls.txt','r') as f:
for el in f:
##fetch these urls
or twisted?
... | [
"If this isn't part of a larger program, then notnoop's idea of using some existing tool to accomplish this is a pretty good one. If a shell loop invoking wget solves your problem, that'll be a lot easier than anything involving more custom software development.\nHowever, if you need to fetch these resources as pa... | [
3,
1,
1,
0
] | [] | [] | [
"python",
"twisted",
"web_scraping"
] | stackoverflow_0002135047_python_twisted_web_scraping.txt |
Q:
Matching one-line JavaScript comments (//) with re
I'd like to filter out (mostly one-line) comments from (mostly valid) JavaScript using python's re module. For example:
// this is a comment
var x = 2 // and this is a comment too
var url = "http://www.google.com/" // and "this" too
url += 'but // this is not a co... | Matching one-line JavaScript comments (//) with re | I'd like to filter out (mostly one-line) comments from (mostly valid) JavaScript using python's re module. For example:
// this is a comment
var x = 2 // and this is a comment too
var url = "http://www.google.com/" // and "this" too
url += 'but // this is not a comment' // however this one is
url += 'this "is not a com... | [
"My regex powers had gone a bit stale so I've used your question to fresh what I remember.\nIt became a fairly large regex mostly because I also wanted to filter multi-line comments.\nimport re\n\nreexpr = r\"\"\"\n ( # Capture code\n \"(?:\\\\.|[^\"\\\\])*\" # String liter... | [
7,
1
] | [] | [] | [
"javascript",
"python",
"regex",
"replace"
] | stackoverflow_0002136363_javascript_python_regex_replace.txt |
Q:
urllib2 times out but doesn't close socket connection
I'm making a python URL grabber program. For my purposes, I want it to time out really really fast, so I'm doing
urllib2.urlopen("http://.../", timeout=2)
Of course it times out correctly as it should. However, it doesn't bother to close the connection to the s... | urllib2 times out but doesn't close socket connection | I'm making a python URL grabber program. For my purposes, I want it to time out really really fast, so I'm doing
urllib2.urlopen("http://.../", timeout=2)
Of course it times out correctly as it should. However, it doesn't bother to close the connection to the server, so the server thinks the client is still connected. ... | [
"I have a suspicion that the socket is still open in the stack frames. When Python raises an exception it stores the stack frames so debuggers and other tools can view the stack and introspect values.\nFor historical reasons, and now for backwards compatibility, the stack information is stored (on a per-thread basi... | [
2,
0
] | [] | [] | [
"http",
"python",
"sockets",
"timeout",
"urllib2"
] | stackoverflow_0002137335_http_python_sockets_timeout_urllib2.txt |
Q:
Django - Store unescaped html in model
I am trying to store raw, unescaped HTML inside one of my Django models for display on my home page. However, when I store it in a TextField it gets escaped, and ends up just being displayed as raw text. How can I store raw HTML in a Django model?
** EDIT **
It seems as if it... | Django - Store unescaped html in model | I am trying to store raw, unescaped HTML inside one of my Django models for display on my home page. However, when I store it in a TextField it gets escaped, and ends up just being displayed as raw text. How can I store raw HTML in a Django model?
** EDIT **
It seems as if its not getting escaped in the model layer, bu... | [
"You can use the safe filter to present unescaped text, or escape filter to present escaped text. You can also use autoescape tag to set a block. ({% autoescape on %} or {% autoescape off %})\n"
] | [
17
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002137736_django_django_models_python.txt |
Q:
Depth-First search in Python
I'm trying to do a Depth-First search in Python but it's not working.
Basically we have a peg-solitaire board:
[1,1,1,1,1,0,1,1,1,1]
1's represent a peg, and 0 is an open spot. You must move a peg one at a time TWO SLOTS backwards or forward ONLY to an empty spot. If you jump over an... | Depth-First search in Python | I'm trying to do a Depth-First search in Python but it's not working.
Basically we have a peg-solitaire board:
[1,1,1,1,1,0,1,1,1,1]
1's represent a peg, and 0 is an open spot. You must move a peg one at a time TWO SLOTS backwards or forward ONLY to an empty spot. If you jump over another peg in the process it become... | [
"The normal way to implement DFS in a situation where each step is a \"move\" from a \"board position\" to some possible next one, until a goal is reached, is as follows (pseudocode)\nseenpositions = set()\ncurrentpositions = set([startingposition])\nwhile currentpositions:\n nextpositions = set()\n for p in curr... | [
10,
1,
0,
0
] | [] | [] | [
"depth_first_search",
"python"
] | stackoverflow_0002137731_depth_first_search_python.txt |
Q:
Change class instance inside an instance method
Any idea if there is a way to make the following code to work
class Test(object):
def __init__(self, var):
self.var = var
def changeme(self):
self = Test(3)
t = Test(1)
assert t.var == 1
t.changeme()
assert t.var == 3
is something like the... | Change class instance inside an instance method | Any idea if there is a way to make the following code to work
class Test(object):
def __init__(self, var):
self.var = var
def changeme(self):
self = Test(3)
t = Test(1)
assert t.var == 1
t.changeme()
assert t.var == 3
is something like the following safe to use for more complex objects (like... | [
"self = Test(3) is re-binding the local name self, with no externally observable effects.\nAssigning self.__dict__ (unless you're talking about instances with __slots__ or from classes with non-trivial metaclasses) is usually OK, and so is self.__init__(3) to re-initialize the instance. However I'd prefer to have ... | [
7,
2,
2
] | [] | [] | [
"class",
"hotswap",
"instance",
"python"
] | stackoverflow_0002137772_class_hotswap_instance_python.txt |
Q:
Problems using PIL 1.1.7
The trivial
import Image
im = Image.OPEN('C:\abc.bmp')
results in the following exception
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
im = Image.OPEN('C:\Documents and Settings\umair.ahmed\My Documents\My Pictures\avanza.bmp')
TypeError: 'dict' object... | Problems using PIL 1.1.7 | The trivial
import Image
im = Image.OPEN('C:\abc.bmp')
results in the following exception
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
im = Image.OPEN('C:\Documents and Settings\umair.ahmed\My Documents\My Pictures\avanza.bmp')
TypeError: 'dict' object is not callable
not sure if ... | [
"Use:\nImage.open()\n\nIt's case-sensitive.\n",
"I don't think the error message came from your input, because the file names are different, but you should not use 'C:\\abc.bmp', in your open() call, but use either C:/abc.bmp, or r'C:\\abc.bmp'. Backslash is an escape character in Python.\n"
] | [
4,
1
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0002137953_python_python_imaging_library.txt |
Q:
(python) sgmlparser and how to extract data between tags, not attributes/values
Every example I see for sgmlparser involves finding a tag, then finding the attributes/values of the tag. So for it would be the ability to extract 'google.com' out. but i want the data between tags. so if i used sgmlparser, i would l... | (python) sgmlparser and how to extract data between tags, not attributes/values | Every example I see for sgmlparser involves finding a tag, then finding the attributes/values of the tag. So for it would be the ability to extract 'google.com' out. but i want the data between tags. so if i used sgmlparser, i would look for and extract out everything in that div until it's closing tag. is that the ... | [
"Because you mention div's, I gather you want to parse HTML. For doing that your best choice is BeautifulSoup.\n"
] | [
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0002135964_html_python.txt |
Q:
How can I keep on-the-fly application-level statistics in an application running under Apache?
I have an application running under apache that I want to keep "in the moment" statistics on. I want to have the application tell me things like:
requests per second, broken down by types of request
latency to make req... | How can I keep on-the-fly application-level statistics in an application running under Apache? | I have an application running under apache that I want to keep "in the moment" statistics on. I want to have the application tell me things like:
requests per second, broken down by types of request
latency to make requests to various backend services via thrift (broken down by service and server)
number of errors be... | [
"Perhaps you could keep the relevant counters and other statistics in a memcached, that is accessed by all apache processes?\n",
"\nI want to do this without any external\n dependencies.\n\nWhat if your apache dies somehow? (Separation of concerns?)\nPersonally I am using (redundant) Nagios to monitor the hardwa... | [
1,
1
] | [
"Use pylons.g object. It is an instance of Globals class in your Pylons application's lib/app_globals.py file. Its state changes will be visible to all threads, so stuff in it needs to be threadsafe.\nlib/app_globals.py:\nclass Globals(object):\n def __init__(self):\n self.requests_served = 0\n\ncontrolle... | [
-1
] | [
"apache",
"fork",
"multithreading",
"pylons",
"python"
] | stackoverflow_0002113352_apache_fork_multithreading_pylons_python.txt |
Q:
Convert Line Number Into its corresponding co-ordinates
I have a application written in PyGtk. I need to convert a particular line number into its corresponding window co-ordinates in a GtkTextView. How can this be done?
A:
Begin by using gtk_text_buffer_get_iter_at_line() to get a handle on the line. Then use g... | Convert Line Number Into its corresponding co-ordinates | I have a application written in PyGtk. I need to convert a particular line number into its corresponding window co-ordinates in a GtkTextView. How can this be done?
| [
"Begin by using gtk_text_buffer_get_iter_at_line() to get a handle on the line. Then use gtk_text_view_get_line_yrange() to convert that into pixel coordinates. Finally use gtk_text_view_buffer_to_window_coords() to convert the buffer pixel coordinates into window coordinates.\nThese are links to the C API calls, b... | [
2,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0002137517_gtk_pygtk_python.txt |
Q:
How can I link (C++) with renamed Python .lib and .dll?
When I include "Python.h" from Python 2.5 in a C++ project, it knows through some magical process that it has to link with "python25.lib" and load "python25.dll" at runtime, though I didn't specified anything neither in "Linker -> Additional Dependencies" nor... | How can I link (C++) with renamed Python .lib and .dll? | When I include "Python.h" from Python 2.5 in a C++ project, it knows through some magical process that it has to link with "python25.lib" and load "python25.dll" at runtime, though I didn't specified anything neither in "Linker -> Additional Dependencies" nor in "Linker -> Additional Library Directories".
Now I would l... | [
"MSVC supports this feature through pragmas:\n#pragma comment(lib, \"python25.lib\");\n\nMore info in MSDN.\nLook into Python.h file and modify the name of the linkage, if that what you want.\n"
] | [
1
] | [] | [] | [
"c++",
"dll",
"linker",
"python"
] | stackoverflow_0002138625_c++_dll_linker_python.txt |
Q:
How do I abort the execution of a Python script?
I have a simple Python script that I want to stop executing if a condition is met.
For example:
done = True
if done:
# quit/stop/exit
else:
# do other stuff
Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the bod... | How do I abort the execution of a Python script? | I have a simple Python script that I want to stop executing if a condition is met.
For example:
done = True
if done:
# quit/stop/exit
else:
# do other stuff
Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to e... | [
"To exit a script you can use,\nimport sys\nsys.exit()\n\nYou can also provide an exit status value, usually an integer.\nimport sys\nsys.exit(0)\n\nExits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.\nimport sys\nsys.exit(\"a... | [
325,
21,
20,
19,
6,
4,
4,
3
] | [] | [] | [
"exit",
"python",
"scripting",
"syntax"
] | stackoverflow_0000179369_exit_python_scripting_syntax.txt |
Q:
Creating an Instance of a Class with a variable in Python
I had this question posted earlier, but it wasn't very clear, and I had trouble with the answers. Since I edited it to make MUCH more sense it seems that people haven't been looking at it, perhaps because they see it already has 6 answers. So I'm re=-postin... | Creating an Instance of a Class with a variable in Python | I had this question posted earlier, but it wasn't very clear, and I had trouble with the answers. Since I edited it to make MUCH more sense it seems that people haven't been looking at it, perhaps because they see it already has 6 answers. So I'm re=-posting it here:
I'm still new to Python and Programming in general,... | [
"There is no point in making a special getNewToy function. Just create the class:\n newtoy = Toy(name, data1, data2, data3, data4, data5)\n\nThat's all you need to do.\n\"method I want the instance to reflect the name of the Toy each time one is called.\"\nclass Toy:\n def __repr__(self):\n return \"<type... | [
2,
2,
1,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002138027_class_python.txt |
Q:
Import by file/module name in GAE
I am trying to make a simple localization module that takes a key name and returns the localized string based on the language given. The language is one of the constants and maps to a python file that contains the string table. I want to do this dynamically at runtime. Below is my... | Import by file/module name in GAE | I am trying to make a simple localization module that takes a key name and returns the localized string based on the language given. The language is one of the constants and maps to a python file that contains the string table. I want to do this dynamically at runtime. Below is my approach, but GAE does not support the... | [
"The alternative to the imp module that (I believe) should be available in GAE is __import__(). It's in fact what the 'import' statement calls to do the actual importing.\nuser_language = getattr(__import__('localizable.%s' % language), language)\n\nor\nuser_language __import__('localizable.%s' % language, {}, glob... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002139110_google_app_engine_python.txt |
Q:
how to install open-library on ubuntu?
i want to install openlibrary in my ubuntu system and i followed the instruction from the below link http://openlibrary.org/dev/docs/setup
$ ./scripts/openlibrary-server openlibrary.yml
while i am using the above command it shows infogami module not found error message
... | how to install open-library on ubuntu? | i want to install openlibrary in my ubuntu system and i followed the instruction from the below link http://openlibrary.org/dev/docs/setup
$ ./scripts/openlibrary-server openlibrary.yml
while i am using the above command it shows infogami module not found error message
| [
"You will need to install 'infogami'. See here\n"
] | [
2
] | [] | [] | [
"installation",
"python",
"ubuntu"
] | stackoverflow_0002139262_installation_python_ubuntu.txt |
Q:
Python Process blocked by urllib2
I set up a process that read a queue for incoming urls to download but when urllib2 open a connection the system hangs.
import urllib2, multiprocessing
from threading import Thread
from Queue import Queue
from multiprocessing import Queue as ProcessQueue, Process
def download(url... | Python Process blocked by urllib2 | I set up a process that read a queue for incoming urls to download but when urllib2 open a connection the system hangs.
import urllib2, multiprocessing
from threading import Thread
from Queue import Queue
from multiprocessing import Queue as ProcessQueue, Process
def download(url):
"""Download a page from an url.
... | [
"The issue here is not urllib2, but the use of the multiprocessing module. When using the multiprocessing module under Windows, you must not use code that runs immediately when importing your module - instead, put things in the main module inside a if __name__=='__main__' block. See section \"Safe importing of main... | [
4
] | [] | [] | [
"multiprocess",
"multithreading",
"python",
"urllib2"
] | stackoverflow_0002137187_multiprocess_multithreading_python_urllib2.txt |
Q:
user pointer in python
*I am trying to display preview from webcam captured using v4l.
Here is an idea of how the code looks like:
from ctypes import *
from v4l2 import *
from Image import fromstring
from Tkinter import Tk, Label
from ImageTk import PhotoImage
from ctypes.util import find_library
libc = CDLL(find... | user pointer in python | *I am trying to display preview from webcam captured using v4l.
Here is an idea of how the code looks like:
from ctypes import *
from v4l2 import *
from Image import fromstring
from Tkinter import Tk, Label
from ImageTk import PhotoImage
from ctypes.util import find_library
libc = CDLL(find_library('c'))
posix_memalig... | [
"Looks like ctypes.string_at(address, size) is what you want. That'll give you a python string buffer with the contents of the memory at your pointer's address. This should be suitable to pass to Image.fromstring or pygame.image.frombuffer.\n",
"I don't know much about ctypes, but I am doing a similar thing (wrap... | [
1,
0,
0,
0,
0
] | [] | [] | [
"ctypes",
"python",
"v4l2"
] | stackoverflow_0002070768_ctypes_python_v4l2.txt |
Q:
How to read a CSV line with "?
A trivial CSV line could be spitted using string split function. But some lines could have ", e.g.
"good,morning", 100, 300, "1998,5,3"
thus directly using string split would not solve the problem.
My solution is to first split out the line using , and then combining the strings wi... | How to read a CSV line with "? | A trivial CSV line could be spitted using string split function. But some lines could have ", e.g.
"good,morning", 100, 300, "1998,5,3"
thus directly using string split would not solve the problem.
My solution is to first split out the line using , and then combining the strings with " at then begin or end of the str... | [
"There's a csv module in Python, which handles this.\nEdit: This task falls into \"build a lexer\" category. The standard way to do such tasks is to build a state machine (or use a lexer library/framework that will do it for you.) \nThe state machine for this task would probably only need two states:\n\nInitial one... | [
11,
3,
1,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0002139750_csv_python.txt |
Q:
Bash or Python or Awk to match and modify files
I have a set of 10000 files c1.dat ... c10000.dat. Each of these files contains a line which starts with @ and contains a string with spaces specific for this file, lije c37 7.379 6.23.
I have another set of 10000 files kind of determined_cXXX_send.dat (where XXX go... | Bash or Python or Awk to match and modify files | I have a set of 10000 files c1.dat ... c10000.dat. Each of these files contains a line which starts with @ and contains a string with spaces specific for this file, lije c37 7.379 6.23.
I have another set of 10000 files kind of determined_cXXX_send.dat (where XXX goes from 1 to 10000). Each of these files has only one... | [
"A language basically made for processing text: Perl!\n",
"If each of the two types of files only has one line:\nfor i in {1..10000}\ndo\n paste \"c${i}.dat\" \"determined_c${i}_send.dat\" > c${i}.out && \n mv \"c{$i}.out\" \"determined_c${i}_send.dat\"\ndone\n\nEdit:\nfor i in {1..10000}\ndo\n line=$(gr... | [
1,
1,
1,
0,
0
] | [] | [] | [
"awk",
"bash",
"python"
] | stackoverflow_0002139823_awk_bash_python.txt |
Q:
Ping a network using threads and testing it
I am trying to ping two different networks with thread. I am able to get the response I want but I want to convert it into a test. I have the code that I have tried below but the test runner says that no tests were run. The code is below:
#!/home/workspace/downloads/Pyth... | Ping a network using threads and testing it | I am trying to ping two different networks with thread. I am able to get the response I want but I want to convert it into a test. I have the code that I have tried below but the test runner says that no tests were run. The code is below:
#!/home/workspace/downloads/Python-2.6.4/python
from threading import Thread
imp... | [
"When you subclass unittest.TestCase, all methods whose name begins with test, get run automatically. Otherwise, the code is not run as a test. (So RunTest is not getting run).\nSo if you change RunTest to (the not so mellifluous) test_RunTest:\nclass TestPing(unittest.TestCase):\n def test_RunTest(self):\n ... | [
3
] | [] | [] | [
"multithreading",
"ping",
"python",
"testing"
] | stackoverflow_0002139947_multithreading_ping_python_testing.txt |
Q:
How to build standalone python installation
How can I build python interpreter which can be installed by just extracting the archive?
e.g. I want to python-2.6.tar.gz. User will extract it in any directory, and start using it.
A:
Maybe portablepython (currently Windows only) will help. You can try using it direc... | How to build standalone python installation | How can I build python interpreter which can be installed by just extracting the archive?
e.g. I want to python-2.6.tar.gz. User will extract it in any directory, and start using it.
| [
"Maybe portablepython (currently Windows only) will help. You can try using it directly, or follow the install process to learn how to create such an environment.\n\nPortable Python is a Python® programming language preconfigured to run directly from any USB storage device, enabling you to have, at any time, a por... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0002130608_python.txt |
Q:
How to write a wrapper over functions and member functions that executes some code before and after the wrapped function?
I'm trying to write some wrapper class or function that allows me to execute some code before and after the wrapped function.
float foo(int x, float y)
{
return x * y;
}
BOOST_PYTHON_MODUL... | How to write a wrapper over functions and member functions that executes some code before and after the wrapped function? | I'm trying to write some wrapper class or function that allows me to execute some code before and after the wrapped function.
float foo(int x, float y)
{
return x * y;
}
BOOST_PYTHON_MODULE(test)
{
boost::python::def("foo", <somehow wrap "&foo">);
}
Ideally, the wrapper should be generic, working for functio... | [
"In this case, you can write a Functor class that wraps over your function, and then overload boost::python::detail::get_signature to accept your Functor!\nUPDATE: Added support for member functions too!\nExample:\n#include <boost/shared_ptr.hpp>\n#include <boost/python.hpp>\n#include <boost/python/signature.hpp>\n... | [
11,
0
] | [] | [] | [
"binding",
"boost_python",
"c++",
"python",
"wrapper"
] | stackoverflow_0002135457_binding_boost_python_c++_python_wrapper.txt |
Q:
How to invoke a method that has been discovered through inspect.getmembers?
import re
import sys
import inspect
import testcases
testClass = re.compile(r'.*Case$')
testMethod = re.compile(r'.*Test$')
for class_name, class_obj in inspect.getmembers(testcases, inspect.isclass):
if testClass.match(class_name):
... | How to invoke a method that has been discovered through inspect.getmembers? | import re
import sys
import inspect
import testcases
testClass = re.compile(r'.*Case$')
testMethod = re.compile(r'.*Test$')
for class_name, class_obj in inspect.getmembers(testcases, inspect.isclass):
if testClass.match(class_name):
for method_name, method_obj in inspect.getmembers(class_obj, inspect.isme... | [
"Right after your code:\nfor class_name, class_obj in inspect.getmembers(testcases, inspect.isclass):\n if testClass.match(class_name):\n for method_name, method_obj in inspect.getmembers(class_obj, inspect.ismethod):\n if testMethod.match(method_name):\n # RIGHT HERE I WOULD LIK... | [
8,
0
] | [] | [] | [
"inspect",
"python"
] | stackoverflow_0002137539_inspect_python.txt |
Q:
How can I make this long_description and README differ by a couple of sentences?
For a package of mine, I have a README.rst file that is read into the setup.py's long description like so:
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
...
long_description = README_TEXT,... | How can I make this long_description and README differ by a couple of sentences? | For a package of mine, I have a README.rst file that is read into the setup.py's long description like so:
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
...
long_description = README_TEXT,
....
)
This way that I can have the README file show up on my github page ev... | [
"You can just use a ReST comment with some text like \"split here\", and then split on that in your setup.py. Ian Bicking does that in virtualenv with index.txt and setup.py.\n",
"Another option is to side-step the issue completely by adding a paragraph that works in both environments: \"The latest unstable code ... | [
9,
5,
2
] | [] | [] | [
"distutils",
"github",
"pypi",
"python",
"setuptools"
] | stackoverflow_0002134941_distutils_github_pypi_python_setuptools.txt |
Q:
Reformatting code with Regular Expressions
We have an ArrayList of items in several classes which are giving me trouble every time I'd like to insert a new item into the list. It was a mistake on my part to have designed the classes in the way I did but changing the design now would be more headache than it's wor... | Reformatting code with Regular Expressions | We have an ArrayList of items in several classes which are giving me trouble every time I'd like to insert a new item into the list. It was a mistake on my part to have designed the classes in the way I did but changing the design now would be more headache than it's worth (bureaucratic waterfall model.) I should hav... | [
"Don't do this with regexp. Create symbolic constants (using for example an enum) that map the names to numbers.\n",
"You want your regular expression to be as flexible as the compiler will be with respect to whitespace between tokens. Doing so and mimicking whitespace usage makes the pattern pretty messy. The co... | [
4,
4,
4,
0
] | [] | [] | [
"java",
"perl",
"python",
"regex"
] | stackoverflow_0002140268_java_perl_python_regex.txt |
Q:
using the symbol font for Greek symbols in TeX via matplotlib
To annotate my figures with Greek letters in the matplotlib package of Python, I use the following:
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helve... | using the symbol font for Greek symbols in TeX via matplotlib | To annotate my figures with Greek letters in the matplotlib package of Python, I use the following:
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sa... | [
"Funny you should ask this; I've been struggling with similar problems not too long ago. Considering how complicated font handling is in TeX, I'd sidestep TeX altogether.\nHowever, any decent Helvetica has the Greek letters built-in, so you don't need to use the Symbol font. Just put some Unicode code points into y... | [
15
] | [] | [] | [
"latex",
"matplotlib",
"python"
] | stackoverflow_0002140865_latex_matplotlib_python.txt |
Q:
Python bind - allow multiple keys to be pressed simultaniously
I have a problem in Python.
I'm using Tkinter and have four bind events, that listen to key presses on my form.
My problem is, that these don't run asynchronously. So, for example I can press one button, and the events are recognized. But when I press ... | Python bind - allow multiple keys to be pressed simultaniously | I have a problem in Python.
I'm using Tkinter and have four bind events, that listen to key presses on my form.
My problem is, that these don't run asynchronously. So, for example I can press one button, and the events are recognized. But when I press and hold two keys at the same time, just one event gets fired.
Is th... | [
"Unfortunately, you are somewhat at the mercy of the underlying auto-repeat mechanism of your system. For example, on the mac I'm using at the moment if I press and hold \"w\" I'll get a stream of press and release events. While pressed, if I press \"o\" I get a stream of presses and releases for \"o\" but no more ... | [
9
] | [
"You could bind to \"<Key>\" and then check event.char and perform the action you want based on the value of that? Granted, I have no idea if this works when multiple keys are pressed at the same time, it may still run in to the exact same problem. I haven't used Tk in ages.\n\"<Key> The user pressed any key. Th... | [
-1
] | [
"bind",
"keyboard_events",
"python",
"tkinter"
] | stackoverflow_0002138518_bind_keyboard_events_python_tkinter.txt |
Q:
Which technology is preferable to build a web based GUI Client?
I've well developed Python Server having workflows, views, object - ORM/OSV, etc...
Server/Client communication based on socket protocol, can be done by any of service
1. XMLRPC Service
2. Socket Service
now I want to develop a Fully Ajax based GUI... | Which technology is preferable to build a web based GUI Client? | I've well developed Python Server having workflows, views, object - ORM/OSV, etc...
Server/Client communication based on socket protocol, can be done by any of service
1. XMLRPC Service
2. Socket Service
now I want to develop a Fully Ajax based GUI web Client..
I've web/socket services to communicate with server.
wh... | [
"Try using pyjamas, which is a port of GWT for Python. Instead of writing code in js, which is pretty disturbing experience, you can code in Python and compile it to js.\n",
"You've said you have a server. So what protocol is understood by it? If it is just HTTP you don't need a web framework like Django/CherryPy... | [
5,
1,
1,
1,
0
] | [] | [] | [
"django",
"extjs",
"gwt",
"python",
"webclient"
] | stackoverflow_0002138868_django_extjs_gwt_python_webclient.txt |
Q:
How are debug consoles implemented in Python?
I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine ... | How are debug consoles implemented in Python? | I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.
Can anyone tell m... | [
"You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory.\n",
"Right, I'm ashamed to admit it's actually in the documentation for InteractiveConsole after all. You can make it run in the local cont... | [
6,
3,
2,
1,
0
] | [] | [] | [
"debugging",
"interactive",
"python"
] | stackoverflow_0000444509_debugging_interactive_python.txt |
Q:
Addressing part of a string via the array syntax in Python
Is it, in Python, possible to address a specific character in a string by the standard array syntax?
Example, PHP:
$foo = 'bar';
echo $foo[1]; // Output: a
It didn't work like in PHP so I wanted to know if it is possible using some other way?
A:
As Adam... | Addressing part of a string via the array syntax in Python | Is it, in Python, possible to address a specific character in a string by the standard array syntax?
Example, PHP:
$foo = 'bar';
echo $foo[1]; // Output: a
It didn't work like in PHP so I wanted to know if it is possible using some other way?
| [
"As Adam pointed out, reading from a string array is possible in Python using the indexing syntax. What isn't possible though is writing to a string using this syntax:\n>>> s = 'bar'\n>>> s[2] = 'z'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'str' object does not suppo... | [
5,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002141334_python_string.txt |
Q:
Retrieving text from password field [python][pyqt4]
def welcomeStage (self):
self.test = QtGui.QLineEdit (self)
self.test.move (50, 150)
QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.passwordStage)
def passwordStage (self):
self.email = self.test.text()
se... | Retrieving text from password field [python][pyqt4] | def welcomeStage (self):
self.test = QtGui.QLineEdit (self)
self.test.move (50, 150)
QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.passwordStage)
def passwordStage (self):
self.email = self.test.text()
self.test.clear()
self.test.setEchoMode (QtGui.QLineEdi... | [
"I can't offer a fix for using a QLineEdit, but you can get passwords in a QInputDialog by specifying mode in the getText() method. Like this:\ndiag = QtGui.QInputDialog\ns = None\nwhile s is None:\n qstring, ok = diag.getText(self, QtCore.QString(title), QtCore.QString(text), mode=QtGui.QLineEdit.Password)\n ... | [
0
] | [] | [] | [
"passwords",
"pyqt4",
"python",
"user_interface"
] | stackoverflow_0002141808_passwords_pyqt4_python_user_interface.txt |
Q:
problems Wrapping Patricia Tries using Swig, python
I'm trying to wrap the Patricia Tries (Perl's NET::Patricia) to be exposed in python. I am having difficulty with one of the classes.
So instances the patricia node (below) as viewed from python have a "data" property. Reading it goes fine, but writing to it br... | problems Wrapping Patricia Tries using Swig, python | I'm trying to wrap the Patricia Tries (Perl's NET::Patricia) to be exposed in python. I am having difficulty with one of the classes.
So instances the patricia node (below) as viewed from python have a "data" property. Reading it goes fine, but writing to it breaks.
typedef struct _patricia_node_t {
u_int bit; ... | [
"I haven't used SWIG in a while, but I am pretty sure that you want to use a typemap that will take a PyObject* and cast it to the required void* and vice versa. Be sure to keep track of reference counts, of course.\n",
"It looks like you should pass SWIG a pointer to an integer. For example, if this was all in C... | [
1,
0,
0
] | [] | [] | [
"c",
"pointers",
"python",
"swig"
] | stackoverflow_0000674494_c_pointers_python_swig.txt |
Q:
Python and Rpy2: Calling plot function with options that have "." in them
I'm just starting to learn how to use rpy2 with python. I'm able to make simple plots and such, but I've run into the problem that many options in R use ".". For example, here's an R call that works:
barplot(t, col=heat.colors(2), names.a... | Python and Rpy2: Calling plot function with options that have "." in them | I'm just starting to learn how to use rpy2 with python. I'm able to make simple plots and such, but I've run into the problem that many options in R use ".". For example, here's an R call that works:
barplot(t, col=heat.colors(2), names.arg=c("pwn", "pwn2"))
where t is a matrix.
I want to use the same call in pytho... | [
"You can use a dictionary here for the named arguments (using **) as described in the docs, and call R directly for the functions. Also remember that RPy2 expects its own vector objects. Yes, it's a bit awkward, but on the plus side, you should be able to do anything in rpy2 you could do in R.\nfrom rpy2 import rob... | [
9,
1,
0
] | [] | [] | [
"python",
"rpy2"
] | stackoverflow_0002125218_python_rpy2.txt |
Q:
Stored Procedures in Python for PostgreSQL
we are still pretty new to Postgres and came from Microsoft Sql Server.
We are wanting to write some stored procedures now. Well, after struggling to get something more complicated than a hello world to work in pl/pgsql, we decided it's better if we are going to learn a n... | Stored Procedures in Python for PostgreSQL | we are still pretty new to Postgres and came from Microsoft Sql Server.
We are wanting to write some stored procedures now. Well, after struggling to get something more complicated than a hello world to work in pl/pgsql, we decided it's better if we are going to learn a new language we might as well learn Python becaus... | [
"\nDepends on what operations you're doing.\nWell, combine that with a general Python documentation, and that's about what you have.\nNo. Again, depends on what you're doing. If you're only going to run a query once, no point in preparing it separately.\nIf you are using persistent connections, it might. But they g... | [
9
] | [] | [] | [
"plpgsql",
"postgresql",
"python",
"stored_procedures"
] | stackoverflow_0002141589_plpgsql_postgresql_python_stored_procedures.txt |
Q:
Build Python scripts and call methods from C#
Is there any way to make this scenario work?
There is a Python script. It is built into a DLL by running this script with IronPython:
import clr
clr.CompileModules("CompiledScript.dll", "script.py")
The goal is to call this DLL's methods from C# code. .NET Reflector s... | Build Python scripts and call methods from C# | Is there any way to make this scenario work?
There is a Python script. It is built into a DLL by running this script with IronPython:
import clr
clr.CompileModules("CompiledScript.dll", "script.py")
The goal is to call this DLL's methods from C# code. .NET Reflector shows there is one class in the DLL - DLRCashedCode ... | [
"Sort of. You cannot access the Python methods directly from C# code. Unless you are playing with C# 4.0 and the dynamic keyword or you are very, very special ;). However, you can compile an IronPython class to a DLL and then use IronPython hosting in C# to access the methods (this is for IronPython 2.6 and .NET 2... | [
8,
6
] | [] | [] | [
"c#",
"ironpython",
"python"
] | stackoverflow_0002139202_c#_ironpython_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.