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:
From escaped html -> to regular html? - Python
I used BeautifulSoup to handle XML files that I have collected through a REST API.
The responses contain HTML code, but BeautifulSoup escapes all the HTML tags so it can be displayed nicely.
Unfortunately I need the HTML code.
How would I go on about transforming the... | From escaped html -> to regular html? - Python | I used BeautifulSoup to handle XML files that I have collected through a REST API.
The responses contain HTML code, but BeautifulSoup escapes all the HTML tags so it can be displayed nicely.
Unfortunately I need the HTML code.
How would I go on about transforming the escaped HTML into proper markup?
Help would be ver... | [
"I think you want xml.sax.saxutils.unescape from the Python standard library.\nE.g.:\n>>> from xml.sax import saxutils as su\n>>> s = '<foo>bar</foo>'\n>>> su.unescape(s)\n'<foo>bar</foo>'\n\n",
"You could try the urllib module?\nIt has a method unquote() that might suit your needs.\nEdit: on second t... | [
19,
2
] | [] | [] | [
"beautifulsoup",
"escaping",
"html",
"lxml",
"python"
] | stackoverflow_0002474971_beautifulsoup_escaping_html_lxml_python.txt |
Q:
Help me find an appropriate ruby/python parser generator
The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the tracing capabilities ( activated by setting $RD_TRACE to 1 ... | Help me find an appropriate ruby/python parser generator | The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the tracing capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug... | [
"Python is a pretty easy language to debug. You can just do import pdb pdb.settrace().\nHowever, these parser generators supposedly come with good debugging facilities.\nhttp://www.antlr.org/\nhttp://www.dabeaz.com/ply/\nhttp://pyparsing.wikispaces.com/\nIn response to bounty\nHere is PLY debugging in action.\nSour... | [
6,
2,
2,
1,
0
] | [] | [] | [
"debugging",
"parser_generator",
"python",
"ruby"
] | stackoverflow_0000952648_debugging_parser_generator_python_ruby.txt |
Q:
Extending Python and Objective-C
I'm a fan of clean code. I like my languages to be able to express what I'm trying to do, but I like the syntax to mirror that too.
For example, I work on a lot of programs in Objective-C for jailbroken iPhones, which patch other code using the method_setImplementation() function o... | Extending Python and Objective-C | I'm a fan of clean code. I like my languages to be able to express what I'm trying to do, but I like the syntax to mirror that too.
For example, I work on a lot of programs in Objective-C for jailbroken iPhones, which patch other code using the method_setImplementation() function of the runtime. Or, in PyObjC, I have t... | [
"If you don't have any experience in compiler or interpreter design my answer is an emphatic NO, it is one of the biggest challenges in computer science.\nIf you do have experience my answer shifts to \"that is a really dumb idea.\"\nDo you envision this becoming a large mature product that other people will want t... | [
2,
1
] | [] | [] | [
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0002474554_objective_c_pyobjc_python.txt |
Q:
Python for a hobbyist programmer ( a few questions)
I'm a hobbyist programmer (only in TI-Basic before now), and after much, much, much debating with myself, I've decided to learn Python. I don't have a ton of free time to teach myself a hundred languages and all programming I do will be for personal use or for di... | Python for a hobbyist programmer ( a few questions) | I'm a hobbyist programmer (only in TI-Basic before now), and after much, much, much debating with myself, I've decided to learn Python. I don't have a ton of free time to teach myself a hundred languages and all programming I do will be for personal use or for distributing to people who need them, so I decided that I n... | [
"\nIs python powerful enough to handle\n most things?\n\nYes. Period. Study EveOnline game for more information. Look at pygame framework. Free free to use Google to find more.\n\nDoes python handle networking tasks\n fairly well?\n\nYes. Look at the number of Python web frameworks plus the Twisted framework... | [
14,
6,
4,
3,
2,
0,
0
] | [] | [] | [
"networking",
"programming_languages",
"python",
"robust"
] | stackoverflow_0002474224_networking_programming_languages_python_robust.txt |
Q:
How do I set prifix to django contrib tables names?
HI
One of my requirement is to have prefix on all the tables of the django based project (Because db is hosted on shared server). I have used db_table Meta option to set the prefix for the tables which I have created.
Now my query is how do I set the prefix for ... | How do I set prifix to django contrib tables names? | HI
One of my requirement is to have prefix on all the tables of the django based project (Because db is hosted on shared server). I have used db_table Meta option to set the prefix for the tables which I have created.
Now my query is how do I set the prefix for tables provided by django.contrib.
Instead of auth_group ... | [
"From reading this ticket, I would say it is not possible without a hack.\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002475215_django_django_models_python.txt |
Q:
Modules for Python that can be used as a TFTP server
Are there any modules for Python, that can be used as a TFTP server? I tried Tftpy, but when I try to upload something, it says:
ERROR:tftpy:Write requests not implemented at this time.
In fact, that's the only function that I need.
A:
You may try tftpgui fr... | Modules for Python that can be used as a TFTP server | Are there any modules for Python, that can be used as a TFTP server? I tried Tftpy, but when I try to upload something, it says:
ERROR:tftpy:Write requests not implemented at this time.
In fact, that's the only function that I need.
| [
"You may try tftpgui from http://code.google.com/p/tftpgui/ but it's GPL'ed.\nUPD: uploading is available starting with TFTPy 0.5.0+\nUPD2: I personally found PyPXE minimal hackish TFTP implementation sufficient for bootstrapping virtual machines. If your use case the same as mine - use that.\n"
] | [
4
] | [] | [] | [
"python",
"tftp"
] | stackoverflow_0002469632_python_tftp.txt |
Q:
construct graph from python set type
The short question, is there an off the self function to make a graph from a collection of python sets?
The longer question: I have several python sets. They each overlap or some are sub sets of others. I would like to make a graph (as in nodes and edges) nodes are the elements... | construct graph from python set type | The short question, is there an off the self function to make a graph from a collection of python sets?
The longer question: I have several python sets. They each overlap or some are sub sets of others. I would like to make a graph (as in nodes and edges) nodes are the elements in the sets. The edges are intersection o... | [
"It's not too hard to code yourself:\ndef intersection_graph(sets):\n adjacency_list = {}\n for i, s1 in enumerate(sets):\n for j, s2 in enumerate(sets):\n if j == i:\n continue\n try:\n lst = adjacency_list[i]\n except KeyError:\n ... | [
2,
2
] | [] | [] | [
"edges",
"graph",
"nodes",
"python",
"set"
] | stackoverflow_0002475176_edges_graph_nodes_python_set.txt |
Q:
C/C++ for Core Logic Development of a Web Application?
Can C/C++ be choice of keeping all your logic (business/domain) for web application?
Why?
I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript.
We like to utilize our free time to work on our some ... | C/C++ for Core Logic Development of a Web Application? | Can C/C++ be choice of keeping all your logic (business/domain) for web application?
Why?
I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript.
We like to utilize our free time to work on our some good ideas we developed together. The ideas require knowledg... | [
"C/C++ and Python can be integrated fairly easily, but Python really should be a snap for anyone that knows C well to pick up in a week.\n",
"I don't think you should use a compiled language (at least not c++) for web programming. I thought about doing this once too but remember that for any change you'll have to... | [
2,
0,
0
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0002467807_c_c++_python.txt |
Q:
What should I learn & use to become a pro in PHP & Python Web development?
I'll just show some code to show how I do web development in PHP.
<html>
<head>
<title>Example #3 TDavid's Very First PHP Script ever!</title>
</head>
<? print(Date("m/j/y"));
require_once("somefile.php");
$mysql_db = "DATABASE NAME";
$m... | What should I learn & use to become a pro in PHP & Python Web development? | I'll just show some code to show how I do web development in PHP.
<html>
<head>
<title>Example #3 TDavid's Very First PHP Script ever!</title>
</head>
<? print(Date("m/j/y"));
require_once("somefile.php");
$mysql_db = "DATABASE NAME";
$mysql_user = "YOUR MYSQL USERNAME";
$mysql_pass = "YOUR MYSQL PASSWORD";
$mysql_l... | [
"PHP was built for making web pages, so a lot of the infrastructure is already set up for you. Python was built more as a general-purpose scripting language so you need a bit of extra infrastructure to handle requests and produce web pages.\nThere are multiple frameworks for Python. Django is the most popular but P... | [
3,
2,
1,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0002476335_php_python.txt |
Q:
python Illegal instruction on AIX5.2
I run my python script functions like this:
read from a text file, and store the data as dict. But when in the loop, an Illegal instruction occurs. why this happens?
the code is like this:
d={}
datafile=open('a.txt') # a big text file
for line in datafile:
line=line.rstrip(... | python Illegal instruction on AIX5.2 | I run my python script functions like this:
read from a text file, and store the data as dict. But when in the loop, an Illegal instruction occurs. why this happens?
the code is like this:
d={}
datafile=open('a.txt') # a big text file
for line in datafile:
line=line.rstrip('\n')
for token in line.split():
... | [
"This looks very wrong. token is a string in an array of strings returned by line.split(). So token[0] is the first character of that string. Therefore I don't believe that you'll ever get anything like Parsing line 1065 in your output. As Mark wrote, you'd see a TypeError. \nPlease post \n\nthe real code\nthe real... | [
3
] | [] | [] | [
"aix",
"python"
] | stackoverflow_0002476881_aix_python.txt |
Q:
Python app engine put(self):
I am using this middleware to make my app restful, but it looks like my form parameters are not coming through:
from google.appengine.ext import webapp
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
m... | Python app engine put(self): | I am using this middleware to make my app restful, but it looks like my form parameters are not coming through:
from google.appengine.ext import webapp
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
method = webapp.Request(environ).ge... | [
"Instantiating webapp.Request and calling .get on it causes it to read the request body and parse form parameters in it. When your actual webapp starts later, it instantiates another request object, and once again tries to read the request body - but it's already been read, so nothing is returned.\nYou could modify... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002460431_google_app_engine_python.txt |
Q:
Game cross-compiling and packaging
Some friends and I wanted to develop a game. Any language will do. I've been programming in C for years, but never wrote a game before. One of us knows SDL a little bit. It would also be a nice excuse to learn Python+pygame.
We wish our game to be 'standalone'. By standalone, I m... | Game cross-compiling and packaging | Some friends and I wanted to develop a game. Any language will do. I've been programming in C for years, but never wrote a game before. One of us knows SDL a little bit. It would also be a nice excuse to learn Python+pygame.
We wish our game to be 'standalone'. By standalone, I mean most users (at least Linux, Mac and ... | [
"If you haven't programmed a game before, I'd recommend that you start with Python and Pygame. Python itself is very easy to learn if you're already a programmer, so that won't be too much of a leap for you.\nWith Pygame, you spend almost no time writing \"glue\" or dealing with mundane low-level details like windo... | [
9,
4,
3,
1,
0,
0
] | [] | [] | [
"c",
"cross_compiling",
"cross_platform",
"packaging",
"python"
] | stackoverflow_0002401599_c_cross_compiling_cross_platform_packaging_python.txt |
Q:
Storing and Retrieving Images from Database using Python
I want to store the images related to a each person's profile in the DB and retrieve them
when requested and save it as .jpg file - and display it to the users.
How could I render the image data stored in the DB as an image and store it locally??
A:
This S... | Storing and Retrieving Images from Database using Python | I want to store the images related to a each person's profile in the DB and retrieve them
when requested and save it as .jpg file - and display it to the users.
How could I render the image data stored in the DB as an image and store it locally??
| [
"This StackOverflow Question is a good one to start with when figuring out whether to store images in a DB or on a filesystem\nStoring Images in DB - Yea or Nay?\nI have also written about the issues on my blog\nhttp://www.atalasoft.com/cs/blogs/loufranco/archive/2007/12/03/images-in-databases-part-i-what-to-store.... | [
9,
2,
1
] | [] | [] | [
"image_manipulation",
"python"
] | stackoverflow_0002477045_image_manipulation_python.txt |
Q:
write special characters into excel table by python package pyExcelerator/xlwt
Task:
I generate formated excel tables from csv-files by using the python package pyExcelerator (comparable with xlwt). I need to be able to write less-than-or-equal-to (≤) and greater-than-or-equal-to (≥) signs.
So far:
I can save my t... | write special characters into excel table by python package pyExcelerator/xlwt | Task:
I generate formated excel tables from csv-files by using the python package pyExcelerator (comparable with xlwt). I need to be able to write less-than-or-equal-to (≤) and greater-than-or-equal-to (≥) signs.
So far:
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in ... | [
"This should help with writing UTF-8 chars using pyexcelerator or xlwt:\nwb = xlwt.Workbook(**encoding='utf-8'**)\n\nedit:\nSeems it's not working for pyexcelerator, but I havent confirmed it.\n",
"You may be overthinking the problem. The font shouldn't play into the matter, although character encoding might.\nI... | [
5,
4,
1
] | [] | [] | [
"character_encoding",
"excel",
"python",
"special_characters",
"xlwt"
] | stackoverflow_0001342402_character_encoding_excel_python_special_characters_xlwt.txt |
Q:
Is this the right way of handling command line arguments?
ask_username = True
ask_password = True
ask_message = True
ask_number = True
def Usage():
print '\t-h, --help: View help'
print '\t-u, --username: Username'
print '\t-p, --password: Password'
print '\t-n, --number: numbber to send the sms'... | Is this the right way of handling command line arguments? | ask_username = True
ask_password = True
ask_message = True
ask_number = True
def Usage():
print '\t-h, --help: View help'
print '\t-u, --username: Username'
print '\t-p, --password: Password'
print '\t-n, --number: numbber to send the sms'
print '\t-m, --message: Message to send'
sys.exit(1)
... | [
"You might find that the optparse module is useful -- it allows you to specify which options you want and their types and help text, then to parse the options and get all the results back.\nIt also auto-generates the help output for you, so you only have to maintain your options in one place.\n",
"argparse is ano... | [
16,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002476344_python.txt |
Q:
Python code that needs some overview
im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.
Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)
import random
dez = ['0', '1', '2', '3', '4',... | Python code that needs some overview | im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.
Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)
import random
dez = ['0', '1', '2', '3', '4', '5', '6']
uni = ['0', '1', '2', '3', '4',... | [
"You do realize you can write the exact same code in 1 line, right? It is easy using randint:\n>>> [random.randint(1,60) for _ in range(6)]\n[22, 29, 48, 18, 20, 22]\n\nThis will give you a list of 6 random integers between 1 and 60. In your code you are creating strings that have these numbers. If you are delibera... | [
4,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000909279_python.txt |
Q:
Easy way to find "not enough arguments..." in python logging library
Do you know any easy way to find a logging call that throws "not enough argumenst for format string".
On my workstation I've modified logging/__init__.py to print the msg so I can easily find the line in the source.
But do you have any idea what... | Easy way to find "not enough arguments..." in python logging library | Do you know any easy way to find a logging call that throws "not enough argumenst for format string".
On my workstation I've modified logging/__init__.py to print the msg so I can easily find the line in the source.
But do you have any idea what to do on the testing environment where you can't change python standard l... | [
"Generally, the best way to catch an exception (including the one you mention) is to put the suspect code in the try clause of a try/except statement; in the except clause you can use the traceback module or other ways to pinpoint the errant statement.\nOtherwise-uncaught exceptions end up in sys.excepthook, which ... | [
2,
0
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0002477934_debugging_python.txt |
Q:
Python | How to append elements to a list randomly
Is there a way to append elements to a list randomly, built in function
ex:
def random_append():
lst = ['a']
lst.append('b')
lst.append('c')
lst.append('d')
lst.append('e')
return print lst
this will out put ['a', 'b', 'c', 'd', 'e']... | Python | How to append elements to a list randomly | Is there a way to append elements to a list randomly, built in function
ex:
def random_append():
lst = ['a']
lst.append('b')
lst.append('c')
lst.append('d')
lst.append('e')
return print lst
this will out put ['a', 'b', 'c', 'd', 'e']
But I want it to add elements randomly and out put some... | [
"If you need to perform single insert in a random position then the already given trivial example works:\nfrom random import randrange\n\ndef random_insert(lst, item):\n lst.insert(randrange(len(lst)+1), item)\n\nHowever if you need to insert k items to a list of length n then using the previously given function... | [
12,
11,
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0002475518_python.txt |
Q:
How do I parse a VCard to a Python dictionary?
I'm trying to figure out how to parse a VCard to a Python dictionary using VObject.
vobj=vobject.readOne(string)
print vobj.behavior.knownChildren
This is all I get:
{'CATEGORIES': (0, None, None), 'ADR': (0, None, None), 'UID': (0, None, None), 'PHOTO': (0, None, No... | How do I parse a VCard to a Python dictionary? | I'm trying to figure out how to parse a VCard to a Python dictionary using VObject.
vobj=vobject.readOne(string)
print vobj.behavior.knownChildren
This is all I get:
{'CATEGORIES': (0, None, None), 'ADR': (0, None, None), 'UID': (0, None, None), 'PHOTO': (0, None, None), 'LABEL': (0, None, None), 'VERSION': (1, 1, Non... | [
"You don't want to look at the behavior, you want to look at vobj itself. The behavior is a data structure describing what children are required/expected, and how to translate those children into appropriate Python data structures.\nThe vobj object is a vobject Component. Its contents attribute is a dictionary of v... | [
9
] | [] | [] | [
"python",
"vcf_vcard"
] | stackoverflow_0002478027_python_vcf_vcard.txt |
Q:
Writing 'bits' to C++ file streams
How can I write 'one bit' into a file stream or file structure each time?
Is it possible to write to a queue and then flush it?
Is it possible with C# or Java?
This was needed when trying to implement an instance of Huffman coding. I can't write bits into files, so write them to ... | Writing 'bits' to C++ file streams | How can I write 'one bit' into a file stream or file structure each time?
Is it possible to write to a queue and then flush it?
Is it possible with C# or Java?
This was needed when trying to implement an instance of Huffman coding. I can't write bits into files, so write them to a bitset and then (when compression was ... | [
"Buffering the individual bits until you've accumulated a whole byte seems like a good idea:\nbyte b;\nint s;\n\nvoid WriteBit(bool x)\n{\n b |= (x ? 1 : 0) << s;\n s++;\n\n if (s == 8)\n {\n WriteByte(b);\n b = 0;\n s = 0;\n }\n}\n\nYou just have to deal with the case when the n... | [
13,
8,
3,
0,
0,
0,
0
] | [] | [] | [
"bit_manipulation",
"c#",
"c++",
"java",
"python"
] | stackoverflow_0002476748_bit_manipulation_c#_c++_java_python.txt |
Q:
Why does my buffered GraphicsContext application have a flickering problem?
import wx
class MainFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=DoubleBufferTest(self,-1)
self.Show(True)
class DoubleBufferT... | Why does my buffered GraphicsContext application have a flickering problem? | import wx
class MainFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=DoubleBufferTest(self,-1)
self.Show(True)
class DoubleBufferTest(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init_... | [
"You get flicker because each Refresh() causes the background to get erased before calling onPaint. You need to bind to EVT_ERASE_BACKGROUND and make it a no-op.\nclass DoubleBufferTest(wx.Panel):\n def __init__(self,parent=None,id=-1):\n # ... existing code ...\n self.Bind(wx.EVT_ERASE_BACKGROUND... | [
2,
1
] | [] | [] | [
"graphicscontext",
"python",
"wxpython"
] | stackoverflow_0002452012_graphicscontext_python_wxpython.txt |
Q:
Python (Twisted) - reading from fifo and sending read data to multiple protocols
Im trying to write some kind of multi protocol bot (jabber/irc) that would read messages from fifo file (one liners mostly) and then send them to irc channel and jabber contacts. So far, I managed to create two factories to connect to... | Python (Twisted) - reading from fifo and sending read data to multiple protocols | Im trying to write some kind of multi protocol bot (jabber/irc) that would read messages from fifo file (one liners mostly) and then send them to irc channel and jabber contacts. So far, I managed to create two factories to connect to jabber and irc, and they seem to be working.
However, I've problem with reading the ... | [
"You can read/write on a file descriptor without blocking the reactor as you do with sockets, by the way doesn't sockets use file descriptors?\nIn your case create a class that implements twisted.internet.interfaces.IReadDescriptor and add to reactor using twisted.internet.interfaces.IReactorFDSet.addReader. For an... | [
3,
1
] | [] | [] | [
"fifo",
"irc",
"python",
"twisted",
"xmpp"
] | stackoverflow_0002476234_fifo_irc_python_twisted_xmpp.txt |
Q:
Python: Check if all dictionaries in list are empty
I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.
Is there a single line way to do the following (not including the print)?
l = [{},{},{}] # this list is... | Python: Check if all dictionaries in list are empty | I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.
Is there a single line way to do the following (not including the print)?
l = [{},{},{}] # this list is generated elsewhere...
all_empty = True
for i in l:
if... | [
"all(not d for d in l)\n\n",
"not any(d for d in l) could be shortened to just not any(l) in this case.\n",
"not any(d for d in l) is equivalent by De Morgan's Law to all(not d for d in l), but applies just one not operator. The short-circuiting behavior is also equivalent.\nEdit 1: the inner genexp is actuall... | [
26,
10,
9
] | [] | [] | [
"python"
] | stackoverflow_0002479472_python.txt |
Q:
Segfault in multithreaded python extension in C
I have a very trimmed down example that creates a segfault that I can't seem to get rid of. Python script calls a C function in an extension, which creates a new thread using pthreads. I use PyGILState_Ensure and PyGILState_Release around my python call (PyRun_Simp... | Segfault in multithreaded python extension in C | I have a very trimmed down example that creates a segfault that I can't seem to get rid of. Python script calls a C function in an extension, which creates a new thread using pthreads. I use PyGILState_Ensure and PyGILState_Release around my python call (PyRun_SimpleString) in the new thread, but perhaps I'm not usin... | [
"I'm not positive that this will be relevant to your question, but one thing that looks suspicious is the PyEval_ReleaseLock() call in your module initializer function. I doubt that Python expects your module initializer to release the GIL out from underneath it, and a quick look at some example code here doesn't ... | [
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002478939_multithreading_python.txt |
Q:
Does python import all the listed libraries?
I'm just wondering, I often have really long python files and imports tend to stack quite quickly.
PEP8 says that the imports should always be written at the beginning of the file.
Do all the imported libraries get imported when calling a function coded in the file? Or... | Does python import all the listed libraries? | I'm just wondering, I often have really long python files and imports tend to stack quite quickly.
PEP8 says that the imports should always be written at the beginning of the file.
Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary libraries get called?
Does ... | [
"Every time Python hits an import statement, it checks to see if that module has already been imported, and if not, imports it. So the imports at the top of your file will happen as soon as your file is run or imported by another module.\nThere is some overhead to this, so it's generally best to keep imports at the... | [
3,
2,
1,
0,
0
] | [] | [] | [
"import",
"libraries",
"pep8",
"python"
] | stackoverflow_0002479902_import_libraries_pep8_python.txt |
Q:
How do I go about setting up an application so that it has a persistent process in memory and does not have to re-initialize to run?
I'm not sure what's the appropriate terminology here, but I'd like to have an application running passively that is ready to accept commands without having to reinitialize the whole ... | How do I go about setting up an application so that it has a persistent process in memory and does not have to re-initialize to run? | I'm not sure what's the appropriate terminology here, but I'd like to have an application running passively that is ready to accept commands without having to reinitialize the whole thing.
The precise application is a machine learning system written in Python that takes a somewhat long time to train a classifier or to ... | [
"Depending on your implementation this is known as a server process, a daemon, a Windows service etc.\nA typical implementation will run and accept incoming network connections and service those for clients (e.g. an HTTP server). Some threading or other asynchronous mechanism will exist to allow servicing of multip... | [
2
] | [] | [] | [
"asynchronous",
"command_line",
"machine_learning",
"php",
"python"
] | stackoverflow_0002480363_asynchronous_command_line_machine_learning_php_python.txt |
Q:
Directory layout for a Python project with C extension modules
We have numerous projects in our organization that are mixed Python/C. Currently we're trying to standardize on a directory layout for our projects and are trying to come up with a convenient scheme. One point of contention is where to put C extension ... | Directory layout for a Python project with C extension modules | We have numerous projects in our organization that are mixed Python/C. Currently we're trying to standardize on a directory layout for our projects and are trying to come up with a convenient scheme. One point of contention is where to put C extension modules in the tree.
We're tossing around a couple of options (relat... | [
"I think the layout of the Python standard library is a reasonable example: under trunk, which is basically the root for the SVN repo (net of branches &c), the Modules directory has a lot of .c and .h files, the Lib directory a lot of .py files.\nIn my own projects I tend to divide sources up similarly (and actuall... | [
1
] | [] | [] | [
"c",
"module",
"python"
] | stackoverflow_0002480565_c_module_python.txt |
Q:
How can I optimize this code?
I'm developing a logger daemon to squid to grab the logs on a mongodb database. But I'm experiencing too much cpu utilization. How can I optimize this code?
from sys import stdin
from pymongo import Connection
connection = Connection()
db = connection.squid
logs = db.logs
buffer = ... | How can I optimize this code? | I'm developing a logger daemon to squid to grab the logs on a mongodb database. But I'm experiencing too much cpu utilization. How can I optimize this code?
from sys import stdin
from pymongo import Connection
connection = Connection()
db = connection.squid
logs = db.logs
buffer = []
a = 'timestamp'
b = 'resp_time'
... | [
"This might be a better question for a python profiler. There's a few builtin Python profiling modules such as cProfile; you can read more about it here.\n",
"I'd suspect it might actually be readline() causing cpu utilization. Try running the same code with the readline replaced with just looking at some consta... | [
1,
0,
0
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0002480729_mongodb_python.txt |
Q:
In Python, how do I do a string replacement AND retrive the replaced substring?
In Perl, I would write:
$x = "abbbc";
$x =~ s/(b+)/z/;
print "Replaced $1 and ended up with $x\n";
# "Replaced bbb and ended up with azc"
How do I do this in Python -- do a regular-expression string replacement and record what it was ... | In Python, how do I do a string replacement AND retrive the replaced substring? | In Perl, I would write:
$x = "abbbc";
$x =~ s/(b+)/z/;
print "Replaced $1 and ended up with $x\n";
# "Replaced bbb and ended up with azc"
How do I do this in Python -- do a regular-expression string replacement and record what it was that got replaced?
| [
"Python does not simultaneously return a match and a substitution. Calling group(0) on a returned Match object will find the matched substring:\n>>> r=re.compile('(b+)')\n>>> r.search('abbbc')\n<_sre.SRE_Match object at 0x7f04af497af8>\n>>> r.search('abbbc').group(0)\n'bbb'\n>>> r.sub('z', 'abbbc')\n'azc'\n\n"
] | [
6
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002480841_python_regex.txt |
Q:
Export list as .txt (Python)
My Python module has a list that contains all the data I want to save as a .txt file somewhere. The list contains several tuples like so:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
How do I print the list so each tuple item is separated by a tab and each tuple is separ... | Export list as .txt (Python) | My Python module has a list that contains all the data I want to save as a .txt file somewhere. The list contains several tuples like so:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
How do I print the list so each tuple item is separated by a tab and each tuple is separated by a newline?
Thanks
| [
"You can solve it, as other answers suggest by just joining lines but better way would be to just use python csv module, so that later on you can easily change delimter or add header etc and read it back too, looks like you want tab delimited file\nimport sys\nimport csv\n\ncsv_writer = csv.writer(sys.stdout, delim... | [
9,
8,
2,
2,
1,
0
] | [] | [] | [
"csv",
"export",
"list",
"python",
"tuples"
] | stackoverflow_0002308883_csv_export_list_python_tuples.txt |
Q:
ctypes buffer modification
I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer.
The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle in... | ctypes buffer modification | I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer.
The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle individual values in my buffers? ... | [
"You mean, something like...:\n>>> import ctypes\n>>> x = ctypes.create_string_buffer('howdy!')\n>>> x.value\n'howdy!'\n>>> x[0] = 'C'\n>>> x.value\n'Cowdy!'\n\n...?\n",
"You may find that Cython is a lot nicer then the ctypes module for melding C libraries with Python code.\n"
] | [
2,
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0002480197_ctypes_python.txt |
Q:
Is it inefficient to access a python class member container in a loop statement?
I'm trying to adopt some best practices to keep my python code efficient. I've heard that accessing a member variable inside of a loop can incur a dictionary lookup for every iteration of the loop, so I cache these in local variables ... | Is it inefficient to access a python class member container in a loop statement? | I'm trying to adopt some best practices to keep my python code efficient. I've heard that accessing a member variable inside of a loop can incur a dictionary lookup for every iteration of the loop, so I cache these in local variables to use inside the loop.
My question is about the loop statement itself... if I have th... | [
"An iterator is created from self.myList, and that iterator is used. No other extra lookups are done on self for the iteration.\n"
] | [
6
] | [] | [] | [
"language_features",
"performance",
"python"
] | stackoverflow_0002481254_language_features_performance_python.txt |
Q:
Python: Creating directories
I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:
import os
os.mkdir('~/Desktop/downloaded/')
A:
You can't simply use ~ You must use os.path.expanduser to replace the ~ with a proper path.
A:
Use
import os
os.mkdir(os.path.expanduse... | Python: Creating directories | I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:
import os
os.mkdir('~/Desktop/downloaded/')
| [
"You can't simply use ~ You must use os.path.expanduser to replace the ~ with a proper path.\n",
"Use\nimport os\nos.mkdir(os.path.expanduser(\"~/Desktop/downloaded\"))\n\nThe ~ character is a POSIX shell convention that represents the contents of the HOME environment variable. So, when you type in a shell:\n$ m... | [
15,
10,
2
] | [] | [] | [
"python"
] | stackoverflow_0002480936_python.txt |
Q:
Why does socket.inet_ntoa returns packed format in python
Why does socket.inet_aton returns packed format in python?
If I am storing the IP as integer in Database (mysql), do I have to always extract the integer value or is there any easier way out?
A:
inet_aton is clearly documented to perform exactly this tas... | Why does socket.inet_ntoa returns packed format in python | Why does socket.inet_aton returns packed format in python?
If I am storing the IP as integer in Database (mysql), do I have to always extract the integer value or is there any easier way out?
| [
"inet_aton is clearly documented to perform exactly this task, and the \"why\" is even very explicitly explained...:\n\nConvert an IPv4 address from\n dotted-quad string format (for\n example, ‘123.45.67.89’) to 32-bit\n packed binary format, as a string four\n characters in length. This is useful\n when conve... | [
1
] | [] | [] | [
"ip_address",
"python"
] | stackoverflow_0002481413_ip_address_python.txt |
Q:
Start Python from Twisted
I have learnt Python for about a month as a one year's PHPer.And I started from Twisted as I'm working in a corporation supplying webservice.I have finished some simple application such as data transferring service,page images-fetch service etc.But the problem is ,I don't understand the s... | Start Python from Twisted | I have learnt Python for about a month as a one year's PHPer.And I started from Twisted as I'm working in a corporation supplying webservice.I have finished some simple application such as data transferring service,page images-fetch service etc.But the problem is ,I don't understand the struture of codes I wrote in the... | [
"Just \"remembering\" the code structure isn't all that much extra value with respect to simply looking it up (just make yourself a handy repository of the examples you're using) -- rote memorization, while once a popular thing to force students to do, isn't all that useful.\nUnderstanding is, of course, much bette... | [
3
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0002481779_python_twisted.txt |
Q:
pygtk - dynamically update the widgets taking input from the gtk combo box
On selecting value from 1 to 10 from gtk combox box it should populate the checkbox by taking combo box value as an input. Say for example if i select 5 then 5 checkbox will be generated.
It works.. But the issue is after i selected 5 now i... | pygtk - dynamically update the widgets taking input from the gtk combo box | On selecting value from 1 to 10 from gtk combox box it should populate the checkbox by taking combo box value as an input. Say for example if i select 5 then 5 checkbox will be generated.
It works.. But the issue is after i selected 5 now im selecting next value as 3 from combo box then there 8 checkboxes are displayed... | [
"Add this to your code right before you add your comboboxes:\nfor widget in myVBox.get_children():\n myVBox.remove(widget)\n\n"
] | [
2
] | [] | [] | [
"glade",
"gtk",
"pygtk",
"python"
] | stackoverflow_0002475872_glade_gtk_pygtk_python.txt |
Q:
Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python
I want to convert the mysql database table contents to an Excel(.xls) or comma separated file(csv) using python script... Is it possible? Any one can help me?
Thanks in advance,
Nimmy
A:
With third-party project mysqld... | Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python | I want to convert the mysql database table contents to an Excel(.xls) or comma separated file(csv) using python script... Is it possible? Any one can help me?
Thanks in advance,
Nimmy
| [
"With third-party project mysqldb installed you can easily read that table, e.g:\nimport MySQLdb\nconn = MySQLdb.connect (host = \"localhost\",\n user = \"testuser\",\n passwd = \"testpass\",\n db = \"test\")\ncursor = conn.cursor()\ncursor.execut... | [
1
] | [] | [] | [
"csv",
"file",
"mysql",
"python",
"xlwt"
] | stackoverflow_0002482024_csv_file_mysql_python_xlwt.txt |
Q:
python metaprogramming
I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.
I want to have a module locations with function get_location(name), which returns a class defined in a folder locations/ in the file with the name passed to function. Name ... | python metaprogramming | I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.
I want to have a module locations with function get_location(name), which returns a class defined in a folder locations/ in the file with the name passed to function. Name of a class is something like... | [
"You do need to __import__ the module; after that, getting an attr from it is not hard.\nimport sys\n\ndef get_location(name):\n fullpath = 'locations.' + name\n package = __import__(fullpath)\n module = sys.modules[fullpath]\n return getattr(module, name.title() + 'Location')\n\nEdit: __import__ return... | [
6,
1
] | [] | [] | [
"metaprogramming",
"python",
"python_module"
] | stackoverflow_0002482060_metaprogramming_python_python_module.txt |
Q:
GetLastInputInfo equivalent in Linux to detect last input time
Is there a GetLastInputInfo() equivalent that can be used in Linux?
The intention is to detect the last input time (keyboard or mouse) of the user.
Am using python to script the program.
A:
XScreenSaverQueryInfo
The idle field specifies the number o... | GetLastInputInfo equivalent in Linux to detect last input time | Is there a GetLastInputInfo() equivalent that can be used in Linux?
The intention is to detect the last input time (keyboard or mouse) of the user.
Am using python to script the program.
| [
"XScreenSaverQueryInfo\n\nThe idle field specifies the number of milliseconds since the last input was received from the user on any of the input devices.\n The event-mask field specifies which, if any, screen saver events this client has requested using ScreenSaverSelectInput.\n\n"
] | [
4
] | [] | [] | [
"input",
"linux",
"python",
"time"
] | stackoverflow_0002482103_input_linux_python_time.txt |
Q:
Search backward through a string using a regex (in Python)?
Context
I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.
Current Approach
import re
funct... | Search backward through a string using a regex (in Python)? | Context
I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.
Current Approach
import re
function_re = re.compile(
r"\/\*\*(.+)\*\/\s*void\s+(\w+)\s*::\s*f... | [
"simplest way is to just use a group, you don't need to go backwards...\n (commentRegex)functionRegex\n\nThen just extract group 1. You will need to run in multi-line mode to get it working, i don't know python so i can't be more helpful.\nIt's also possible with lookahead assertions, but this way is simpler.\n",
... | [
2,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002480808_python_regex.txt |
Q:
Send an email using python script
Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need.
import smtplib
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["user@example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This messag... | Send an email using python script | Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need.
import smtplib
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["user@example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# P... | [
"You've named your module the same as one of Python's internal modules. When you import smtplib, it tries to import email, and finds your module instead of the internal one. When two modules import one another, only the variables in each module visible before the both import statements will be visible to one anot... | [
14,
5,
3,
1
] | [] | [] | [
"email",
"python"
] | stackoverflow_0002482160_email_python.txt |
Q:
Trac default language
How can I set default language for trac. There's nothing about i18n in trac.ini
A:
Trac will use the locale provided by your http server by default. Easiest thing to do is just change the locale Apache is running under.
Or if you are running trac under mod_python you can modify the TracLoc... | Trac default language | How can I set default language for trac. There's nothing about i18n in trac.ini
| [
"Trac will use the locale provided by your http server by default. Easiest thing to do is just change the locale Apache is running under.\nOr if you are running trac under mod_python you can modify the TracLocale option:\n\n SetHandler mod_python\n PythonOption TracLocale \"de_DE.UTF-8\"\n ...\n \nFor mo... | [
1,
0
] | [] | [] | [
"internationalization",
"python",
"trac"
] | stackoverflow_0002482399_internationalization_python_trac.txt |
Q:
How to check the read/write status of storage media in python?
How can i check the read/ write permission of the file storing media? ie assume i have to write some file inside a directory and that directory may be available on read only media like (cd or dvd)or etc. So how can i check that storing media ( cd, hard... | How to check the read/write status of storage media in python? | How can i check the read/ write permission of the file storing media? ie assume i have to write some file inside a directory and that directory may be available on read only media like (cd or dvd)or etc. So how can i check that storing media ( cd, hard disk) having a read only or read write both permission.
I am using ... | [
"Use the os.access(path, mode) function. It should be much more portable than the win32api function. Though, I have no experience with it on non-POSIX systems.\nOn the other hand, why don't you just try to write the file and handle exception appropriately?\n",
"import os\nfrom stat import *\n\nif S_IMODE(os.stat(... | [
3,
1,
0
] | [] | [] | [
"filesystems",
"python",
"windows_xp"
] | stackoverflow_0002482701_filesystems_python_windows_xp.txt |
Q:
Seeking enlightenment - global variables in AppEngine (aeoid.get_current_user())
This may be a 'Python Web Programming 101' question, but I'm confused about some code in the aeoid project (http://github.com/Arachnid/aeoid). here's the code:
_current_user = None
def get_current_user():
"""Returns the currently... | Seeking enlightenment - global variables in AppEngine (aeoid.get_current_user()) | This may be a 'Python Web Programming 101' question, but I'm confused about some code in the aeoid project (http://github.com/Arachnid/aeoid). here's the code:
_current_user = None
def get_current_user():
"""Returns the currently logged in user, or None if no user is logged in."""
global _current_user
if ... | [
"The App Engine Python runtime is single-threaded - only a single request is processed, per runtime instance, at a time. As a result, you can use globals for request-specific parameters, so long as you take care to reset them at the beginning of each request, so they don't leak data from one request to another.\n",... | [
2,
0
] | [] | [] | [
"global_variables",
"google_app_engine",
"python",
"session"
] | stackoverflow_0002482224_global_variables_google_app_engine_python_session.txt |
Q:
Pass by reference in Boost::Python
Consider something like:
struct Parameter
{
int a;
Parameter(){a = 0;}
void setA(int newA){a = newA;}
};
struct MyClass
{
void changeParameter(Parameter &p){ p.setA(-1);}
};
Well, let's fast forward, and imagine I already wrapped those classes, exposing everythin... | Pass by reference in Boost::Python | Consider something like:
struct Parameter
{
int a;
Parameter(){a = 0;}
void setA(int newA){a = newA;}
};
struct MyClass
{
void changeParameter(Parameter &p){ p.setA(-1);}
};
Well, let's fast forward, and imagine I already wrapped those classes, exposing everything to python, and imagine also I instanti... | [
"Python doesn't have references, so when you pass reference to python boost::python calls copy-ctor of your object.\nIn this case you have two choices: Replace references with pointers (or smart-pointers) or pass into python your own 'smart-reference' object/wrapper.\n"
] | [
2
] | [] | [] | [
"boost_python",
"c++",
"python",
"scripting"
] | stackoverflow_0002459588_boost_python_c++_python_scripting.txt |
Q:
Python - retrieving info from a syslog file
I have been asked to write a program using python for an assignment.
I have been given a syslog file and I have to find things out about it
How do I find out how many attempts were made to login to the root account?
Any advice would be highly appreciated as I am very new... | Python - retrieving info from a syslog file | I have been asked to write a program using python for an assignment.
I have been given a syslog file and I have to find things out about it
How do I find out how many attempts were made to login to the root account?
Any advice would be highly appreciated as I am very new to python and completely lost!
| [
"You want /var/log/auth.log, not syslog. \nIt'll contain lines like like this: \nMar 20 10:47:24 Opus su[15918]: pam_unix(su:auth): authentication failure; logname=lfaraone uid=1000 euid=0 tty=/dev/pts/25 ruser=lfaraone rhost= user=root\n\nBasic, naive code to accomplish the problem would be as follows:\nloginatte... | [
1,
0,
0
] | [] | [] | [
"authentication",
"count",
"python",
"syslog"
] | stackoverflow_0002483421_authentication_count_python_syslog.txt |
Q:
Should I use fork or threads?
In my script, I have a function foo which basically uses pynotify to notify user about something repeatedly after a time interval say 15 minutes.
def foo:
while True:
"""Does something"""
time.sleep(900)
My main script has to interact with user & does all other t... | Should I use fork or threads? | In my script, I have a function foo which basically uses pynotify to notify user about something repeatedly after a time interval say 15 minutes.
def foo:
while True:
"""Does something"""
time.sleep(900)
My main script has to interact with user & does all other things so I just cant call the foo()... | [
"I won't tell you which one to use, but here are some of the advantages of each:\nThreads can start more quickly than processes, and threads use fewer operating system resources than processes, including memory, file handles, etc. Threads also give you the option of communicating through shared variables (although... | [
9,
4,
4,
3,
1
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0002482926_coding_style_python.txt |
Q:
MySQL UTC Date format
I am pulling data from Twitter's API and the return date is UTC in the following form:
Sat Jan 24 22:14:29 +0000 2009
Can MySQL handle this format specifically or do I need to transform it? I am pulling the data using Python.
A:
Yes, if you are not willing to transform it in Python, MySQ... | MySQL UTC Date format | I am pulling data from Twitter's API and the return date is UTC in the following form:
Sat Jan 24 22:14:29 +0000 2009
Can MySQL handle this format specifically or do I need to transform it? I am pulling the data using Python.
| [
"Yes, if you are not willing to transform it in Python, MySQL can handle this with the STR_TO_DATE() function, as in the following example:\nINSERT INTO\n your_table\nVALUES ( \n STR_TO_DATE('Sat Jan 24 22:14:29 +0000 2009', '%a %b %d %H:%i:%s +0000 %Y')\n);\n\nYou may also want to check the full list of poss... | [
3
] | [] | [] | [
"mysql",
"python",
"twitter",
"utc"
] | stackoverflow_0002483569_mysql_python_twitter_utc.txt |
Q:
How to give extra arguments for the Python itertools.ifilter function?
In python I have the following function:
def is_a_nice_element(element, parameter):
#do something
return True or False
Now I would like to filter a list with this function as predicate, giving a fixed parameter. Python has the itertool... | How to give extra arguments for the Python itertools.ifilter function? | In python I have the following function:
def is_a_nice_element(element, parameter):
#do something
return True or False
Now I would like to filter a list with this function as predicate, giving a fixed parameter. Python has the itertools.ifilter function, but I can't figure out how to pass the parameter. Is thi... | [
"I like functools.partial much better than lambda.\nitertools.ifilter( partial(is_a_nice_element, parameter=X), iterable )\n\n",
"Wrap it in a lambda:\nitertools.ifilter(lambda e: is_a_nice_element(e, 42), iterable)\n\n42 is your extra argument, or whatever else you want it to be.\n",
"The solutions use lambda ... | [
5,
3,
1
] | [
"If you are using ifilter then parameter would need to be constant in which case you could use a default argument parameter=something. If you want parameter to vary, you'd need to use another method to take a dyadic predicate.\nIf you already have the list in hand, ifilter is a bit of overkill relative to the built... | [
-1
] | [
"ifilter",
"python",
"python_itertools"
] | stackoverflow_0002483118_ifilter_python_python_itertools.txt |
Q:
Python method to remove iterability
Suppose I have a function which can either take an iterable/iterator or a non-iterable as an argument. Iterability is checked with try: iter(arg).
Depending whether the input is an iterable or not, the outcome of the method will be different. Not when I want to pass a non-iterab... | Python method to remove iterability | Suppose I have a function which can either take an iterable/iterator or a non-iterable as an argument. Iterability is checked with try: iter(arg).
Depending whether the input is an iterable or not, the outcome of the method will be different. Not when I want to pass a non-iterable as iterable input, it is easy to do: I... | [
"The more I think about it, it seems like it’s not possible to do without type checking or passing argments to the function.\nHowever, depending on the intention of the function, one way to handle it could be:\nfrom itertools import repeat\nfunc(repeat(string_iterable))\n\nfunc still sees an iterable but it won’t i... | [
3,
2,
0,
0,
0
] | [] | [] | [
"data_structures",
"iterator",
"python",
"string"
] | stackoverflow_0002482996_data_structures_iterator_python_string.txt |
Q:
Django logs: any tutorial to log to a file
I am working with a django project, I haven't started. The developed working on the project left. During the knowledge transfer, it was told to me that all the events are logged to the database. I don't find the database interface useful to search for logs and sometimes t... | Django logs: any tutorial to log to a file | I am working with a django project, I haven't started. The developed working on the project left. During the knowledge transfer, it was told to me that all the events are logged to the database. I don't find the database interface useful to search for logs and sometimes they don't even log(I might be wrong). I want to ... | [
"If you are talking about the Django admin log (the one that shows on the right side of the main page of the admin interface), you could just enable an admin model for the log itself.\nOpen the admin.py for one of your django apps and add this:\nfrom django.contrib.admin.models import LogEntry\n\nclass LogEntryAdmi... | [
4
] | [] | [] | [
"django",
"logging",
"mod_python",
"python"
] | stackoverflow_0002479858_django_logging_mod_python_python.txt |
Q:
How to set the size of a wx.aui.AuiManager Pane that is centered?
I have three panes with the InfoPane center option.
I want to know how to set their size.
Using this code:
import wx
import wx.aui
class MyFrame(wx.Frame):
def __init__(self, parent, id=-1, title='wx.aui Test',
pos=wx.DefaultP... | How to set the size of a wx.aui.AuiManager Pane that is centered? | I have three panes with the InfoPane center option.
I want to know how to set their size.
Using this code:
import wx
import wx.aui
class MyFrame(wx.Frame):
def __init__(self, parent, id=-1, title='wx.aui Test',
pos=wx.DefaultPosition, size=(800, 600),
style=wx.DEFAULT_FRAME_STYLE... | [
"I've discovered what I want.\nIt was the wx.aui.AuiPaneInfo.dock_proportion property :)\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002482914_python_wxpython.txt |
Q:
Python: Does one of these examples waste more memory?
In a Django view function which uses manual transaction committing, I have:
context = RequestContext(request, data)
transaction.commit()
return render_to_response('basic.html', data, context) # Returns a Django ``HttpResponse`` object which is similar to a dic... | Python: Does one of these examples waste more memory? | In a Django view function which uses manual transaction committing, I have:
context = RequestContext(request, data)
transaction.commit()
return render_to_response('basic.html', data, context) # Returns a Django ``HttpResponse`` object which is similar to a dictionary.
I think it is a better idea to do this:
context =... | [
"You say, \"there won't likely be many exceptions at that point in the function\". This may not be true. Keep in mind that querysets are lazily fetched from the db, so in fact, a lot of your db activity could be inside the render_to_response call. \nI'd use the second style. It's more correct in the sense that ... | [
3
] | [] | [] | [
"django",
"memory_management",
"python"
] | stackoverflow_0002483761_django_memory_management_python.txt |
Q:
Python - Filter by Date
How do I count how many logins were done per day on a system using the log file in Python?
A:
You don't need Python, the shell will do:
grep "Login succeeded_or_whatever_the_log_says" logfile | wc -l
If you really insist on using Python, try
print(sum(
1 for line in open('logfile')
... | Python - Filter by Date | How do I count how many logins were done per day on a system using the log file in Python?
| [
"You don't need Python, the shell will do:\ngrep \"Login succeeded_or_whatever_the_log_says\" logfile | wc -l\n\nIf you really insist on using Python, try\nprint(sum(\n 1 for line in open('logfile')\n if 'Login succeeded_or_whatever_the_log_says' in line))\n\nIf the login suceeded message spans multip... | [
1
] | [
"You can create dictionary with day as a key, and login count as a value.\nThen read file line by line, extract date from each line and increase login count for that day.\nI think something like this should work:\nlogin_cnts = {}\n\ndef get_date(line):\n \"\"\"extract date from line, in this example line starts ... | [
-1
] | [
"authentication",
"python"
] | stackoverflow_0002483822_authentication_python.txt |
Q:
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my... | How can I deploy a Perl/Python/Ruby script without installing an interpreter? | I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be w... | [
"You can get Windows executables in all three languages. \n\nAs usual with Perl, there's more than one way to do it:\n\n\nPAR Packer (free/open-source)\nperl2exe (shareware)\nPerlApp (part of the Perl Dev Kit from ActiveState, commercial)\n\nPython \n\n\npy2exe\nPyInstaller\n\nRuby \n\n\nRubyScript2Exe\nOCRA\n\n\n... | [
31,
23,
8,
6,
3,
2,
1,
1,
0
] | [] | [] | [
"perl",
"python",
"ruby"
] | stackoverflow_0000446685_perl_python_ruby.txt |
Q:
Testing variable types in Python
I'm creating an initialising function for the class 'Room', and found that the program wouldn't accept the tests I was doing on the input variables.
Why is this?
def __init__(self, code, name, type, size, description, objects, exits):
self.code = code
self.name = name
s... | Testing variable types in Python | I'm creating an initialising function for the class 'Room', and found that the program wouldn't accept the tests I was doing on the input variables.
Why is this?
def __init__(self, code, name, type, size, description, objects, exits):
self.code = code
self.name = name
self.type = type
self.size = size
... | [
"Not answering the \"why\", but \n\nstr itself is a type already. You can use type(self.code) != str\nBut a better way is to use isinstance(self.code, str).\n\n",
"Python is a dynamic language. It bad idea to test the types explicitly. In fact the code you write should in itself be such that you dont ever need to... | [
13,
8,
3,
2,
2,
0
] | [
"in python you just use the variables as if they where the type you want. \nif for some reason you have a function you call with different types, you can wrap your code in a try/catch.\ndef addOne(a):\n ''' \n increments a with 1 if a is a number. \n if a is a string, append '.' to it. \n '''\n tr... | [
-1
] | [
"python",
"testing",
"variables"
] | stackoverflow_0002482230_python_testing_variables.txt |
Q:
How do you subclass the file type in Python?
I'm trying to subclass the built-in file class in Python to add some extra features to stdin and stdout. Here's the code I have so far:
class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream... | How do you subclass the file type in Python? | I'm trying to subclass the built-in file class in Python to add some extra features to stdin and stdout. Here's the code I have so far:
class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream, and to add a timestamp to each message printed.
... | [
"Calling file.__init__ is quite feasible (e.g., on '/dev/null') but no real use because your attempted override of write doesn't \"take\" for the purposes of print statements -- the latter internally calls the real file.write when it sees that sys.stdout is an actual instance of file (and by inheriting you've made ... | [
12,
3
] | [] | [] | [
"file",
"python",
"subclass"
] | stackoverflow_0001082801_file_python_subclass.txt |
Q:
How do I override a parent class's functions in python?
I have a private method def __pickSide(self): in a parent class that I would like to override in the child class. However, the child class still calls the inherited def __pickSide(self):. How can I override the function? The child class's function name is exa... | How do I override a parent class's functions in python? | I have a private method def __pickSide(self): in a parent class that I would like to override in the child class. However, the child class still calls the inherited def __pickSide(self):. How can I override the function? The child class's function name is exactly the same as the parent's function name.
| [
"Let's look at the easiest example:\nfrom dis import dis\n\nclass A(object):\n def __pick(self):\n print \"1\"\n\n def doitinA(self):\n self.__pick()\n\nclass B(A):\n def __pick(self):\n print \"2\"\n\n def doitinB(self):\n self.__pick()\n\nb = B()\nb.doitinA() # prints 1\nb.doitinB() # prin... | [
35,
5,
4
] | [] | [] | [
"inheritance",
"overriding",
"parent",
"python"
] | stackoverflow_0002484215_inheritance_overriding_parent_python.txt |
Q:
PyLab - changing text color and background fill color of text box
I'm using PyLab to make some graphs in Python. I want to make a text box that is colored magenta with black text, but cannot get the text to be black.
text(x, y, 'Summary', backgroundcolor = 'm', color = 'k')
This gives me a magenta background and ... | PyLab - changing text color and background fill color of text box | I'm using PyLab to make some graphs in Python. I want to make a text box that is colored magenta with black text, but cannot get the text to be black.
text(x, y, 'Summary', backgroundcolor = 'm', color = 'k')
This gives me a magenta background and then text that is almost just as pink. Any ideas what I'm doing wrong?
... | [
"it doesn't appear as though you're doing anything wrong:\nIn [23]: pylab.text(0.25, 0.5, 'test', backgroundcolor='m', color='r')\nIn [24]: pylab.text(0.5, 0.5, 'test', backgroundcolor='m', color='k')\nIn [25]: pylab.text(0.75, 0.5, 'test', backgroundcolor='m', color='b')\n\nalt text http://student.physics.ucdavis.... | [
5
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0002484256_matplotlib_python.txt |
Q:
Would it be possible to integrate Python or Perl with Ruby?
Would it be possible to integrate Python (and/or Perl) and Ruby? I've looked at http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python/doc/ and http://code.google.com/p/ruby-perl/ , but they both seem rather outdated.
Has someone generated a Ruby interfa... | Would it be possible to integrate Python or Perl with Ruby? | Would it be possible to integrate Python (and/or Perl) and Ruby? I've looked at http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python/doc/ and http://code.google.com/p/ruby-perl/ , but they both seem rather outdated.
Has someone generated a Ruby interface for Python's C API?
Edit: Python can be integrated with many o... | [
"My school (Georgia Tech), along with Bryn Mawr and Microsoft Research, are doing a project right now called Pyjama. Basically, it uses the Microsoft DLR to allow you to freely mix Python and Ruby. I haven't tried it, but it sounds pretty cool.\nHere's an example from the website. You enter the class in \"Python mo... | [
7,
5,
2,
2,
2,
1
] | [] | [] | [
"perl",
"python",
"ruby"
] | stackoverflow_0002413878_perl_python_ruby.txt |
Q:
Euclidian Distances between points
I have an array of points in numpy:
points = rand(dim, n_points)
And I want to:
Calculate all the l2 norm (euclidian distance) between a certain point and all other points
Calculate all pairwise distances.
and preferably all numpy and no for's. How can one do it?
A:
If you'r... | Euclidian Distances between points | I have an array of points in numpy:
points = rand(dim, n_points)
And I want to:
Calculate all the l2 norm (euclidian distance) between a certain point and all other points
Calculate all pairwise distances.
and preferably all numpy and no for's. How can one do it?
| [
"If you're willing to use SciPy, the scipy.spatial.distance module (the functions cdist and/or pdist) do exactly what you want, with all the looping done in C. You can do it with broadcasting too but there's some extra memory overhead.\n",
"This might help with the second part:\nimport numpy as np\nfrom numpy imp... | [
4,
1
] | [] | [] | [
"euclidean_distance",
"numpy",
"python"
] | stackoverflow_0002483100_euclidean_distance_numpy_python.txt |
Q:
How can I access the "through" object of a Django ManyToManyField?
I have the following models in my Django app. How can I from the Team model find all the User objects who have accepted as True in the Membership model? I know I need to use Team.objects.filter(), but I'm not sure how to check the value of the acce... | How can I access the "through" object of a Django ManyToManyField? | I have the following models in my Django app. How can I from the Team model find all the User objects who have accepted as True in the Membership model? I know I need to use Team.objects.filter(), but I'm not sure how to check the value of the accepted field.
from django.contrib.auth.models import User
class Team(model... | [
"Accepted members of a team:\nteam_42.members.filter(membership__accepted=True)\n\nTeams user alice has been accepted by:\nalice.team_set.filter(membership__accepted=True)\n\nI believe you want to get the set of Team or User objects and not the set of intermediate Membership objects. You answered the question your... | [
1
] | [
"Team.objects.filter(members__accepted__exact=True)\nTake a look at this. It has a lot of great examples and explanations.\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0002483948_django_python.txt |
Q:
Prevent python from printing newline
I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't... | Prevent python from printing newline | I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't depend on user input, I do not get the ne... | [
"You are correct - a newline is included in inputted. To remove it, you can just call strip(\"\\r\\n\") to remove the newline from the end:\nprint(\"Input is {0}, including the return\".format(inputted.strip(\"\\r\\n\")))\n\nThis won't cause any issues if inputted does not have a newline at the end, but will remove... | [
7,
4,
3,
2
] | [] | [] | [
"input",
"newline",
"python",
"user_input"
] | stackoverflow_0002484420_input_newline_python_user_input.txt |
Q:
Which dynamic language can easily use libraries from other languages?
Tell why you think Python, Perl, Ruby, etc is easiest for plugging in modules from other languages with minimal thought.
To clarify, an example: I want to write business logic in Python, but use functionality that conveniently exists as a Perl m... | Which dynamic language can easily use libraries from other languages? | Tell why you think Python, Perl, Ruby, etc is easiest for plugging in modules from other languages with minimal thought.
To clarify, an example: I want to write business logic in Python, but use functionality that conveniently exists as a Perl module.
In other words, which language "just works" with the most modules?
| [
"Perl has very good support for other languages via the Inline set of modules.\nInline::Python allows you to import Python modules, classes and functions into your Perl code and call them from Perl as if they were native - see Importing Functions.\nInline::Ruby works virtually the same way.\n",
"The Parrot VM loo... | [
9,
6,
3,
0,
0,
0,
0
] | [] | [] | [
"dynamic_languages",
"module",
"perl",
"python",
"ruby"
] | stackoverflow_0002483924_dynamic_languages_module_perl_python_ruby.txt |
Q:
What's the Ruby equivalent of Python's output[:-1]?
In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
A:
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather... | What's the Ruby equivalent of Python's output[:-1]? | In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
| [
"I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing \"StackOverflow\"[0..-2] you can do \"StackOverflow\"[0...-1] for the same result.\nIn Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string sl... | [
11,
4,
2,
1,
1
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0002484863_python_ruby.txt |
Q:
Aggregation over a few models - Django
I'm trying to compute the average of a field over various subsets of a queryset.
Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level'))
This works perfectly!
But... if I try to compute it for the top 50 players it does not work.
Player.objects.order_b... | Aggregation over a few models - Django | I'm trying to compute the average of a field over various subsets of a queryset.
Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level'))
This works perfectly!
But... if I try to compute it for the top 50 players it does not work.
Player.objects.order_by('-score').filter(sex='male')[:50].aggregat... | [
"topfifty = Player.objects.order_by('-score')[:50]\nPlayer.objects.filter(sex='male',pk__in=topfifty).aggregate(avglevel=Avg('level'))\n\nedit: i haven't tested this, but i think you get the idea of where i'm going.\ntopfifty = Player.objects.order_by('-score')[:50]\nids = []\nfor t in topfifty:\n ids += [t.id]\... | [
4,
3
] | [
"Hmm. The docs say\n\"Slicing. As explained in Limiting QuerySets, a QuerySet can be sliced, using Python's array-slicing syntax. Usually slicing a QuerySet returns another (unevaluated) QuerySet, but Django will execute the database query if you use the \"step\" parameter of slice syntax.\" http://docs.djangoproje... | [
-1
] | [
"database",
"django",
"django_models",
"python"
] | stackoverflow_0002481839_database_django_django_models_python.txt |
Q:
Modify Django settings variables in a middleware
I set a variable MAX_REQUEST = 100 in settings.py
I write a middleware which may lower this value for request origining from a proxy ip address by the following code:
settings.MAX_REQUEST = 10
However, looks like the above modification affects all legitimate users.... | Modify Django settings variables in a middleware | I set a variable MAX_REQUEST = 100 in settings.py
I write a middleware which may lower this value for request origining from a proxy ip address by the following code:
settings.MAX_REQUEST = 10
However, looks like the above modification affects all legitimate users.
Is it normal?
| [
"Yes. settings is a module referenced all over by Django (and probably your code too). Modifying any variable in settings is like modifying a global variable and alters the behaviour of your whole web app.\n",
"Django settings are global. They affect the whole process.\n",
"If you want 'per user' variables, I s... | [
6,
0,
0
] | [] | [] | [
"django",
"middleware",
"python",
"settings"
] | stackoverflow_0002485274_django_middleware_python_settings.txt |
Q:
Learning Python and trying to get first two letters and last two letters of a string
Here's my code:
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the ... | Learning Python and trying to get first two letters and last two letters of a string | Here's my code:
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
if len(s) <= 2:
return ""
else:
return s[0] + ... | [
"Misplaced parenthesis:\nreturn s[0] + s[1] + s[len(s)-2] + s[len(s)-1]\n\nBy the way:\nreturn s[0] + s[1] + s[-2] + s[-1]\n\nor\nreturn s[:2] + s[-2:]\n\n",
"Your immediate problem is s[len(s-1)] instead of s[len(s)-1] .\nYou can probably simplify to s[:2] + s[-2:] as well.\n",
"There is an error in the last p... | [
4,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0002485300_python.txt |
Q:
Which implementation of OrderedDict should be used in python2.6?
As some of you may know in python2.7/3.2 we'll get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompatible.
So which one of the 8 current implementati... | Which implementation of OrderedDict should be used in python2.6? | As some of you may know in python2.7/3.2 we'll get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompatible.
So which one of the 8 current implementations in the PEP is backwards compatible with the 2.7 odict from python ... | [
"This package (for Python 2.4 or better) claims to be \"A drop-in substitute for Py2.7's new collections.OrderedDict that works in Python 2.4-2.6.\", but I have not checked that claim.\n"
] | [
3
] | [] | [] | [
"dictionary",
"pep",
"python"
] | stackoverflow_0002484046_dictionary_pep_python.txt |
Q:
Python mistaking float for string
I receive
TypeError: Can't convert 'float' object to str implicitly
while using
Gambler.pot += round(self.bet + self.money * 0.1)
where pot, bet, and money are all doubles (or at least are supposed to be). I'm not sure if this is yet another Eclipse thing, but how do I get the l... | Python mistaking float for string | I receive
TypeError: Can't convert 'float' object to str implicitly
while using
Gambler.pot += round(self.bet + self.money * 0.1)
where pot, bet, and money are all doubles (or at least are supposed to be). I'm not sure if this is yet another Eclipse thing, but how do I get the line to compile?
Code where bet and mone... | [
"input() in 3.x only returns strings. It is the programmer's job to pass it to a numeric constructor in order to turn it into a number.\n",
"Are you initializing pot? Have you tried storing intermediate results to track down here the problem is coming from? And finally, do you know about pdb? That may be a big... | [
6,
4,
3,
3,
2,
0
] | [] | [] | [
"floating_point",
"python",
"python_3.x",
"string"
] | stackoverflow_0002485521_floating_point_python_python_3.x_string.txt |
Q:
Django model: Reference foreign key table in __unicode__ function for admin
Example models:
class Parent(models.Model):
name = models.CharField()
def __unicode__(self):
return self.name
class Child(models.Model):
parent = models.ForeignKey(Parent)
def __unicode__(self):
return se... | Django model: Reference foreign key table in __unicode__ function for admin | Example models:
class Parent(models.Model):
name = models.CharField()
def __unicode__(self):
return self.name
class Child(models.Model):
parent = models.ForeignKey(Parent)
def __unicode__(self):
return self.parent.name # Would reference name above
I'm wanting the Child.unicode to ref... | [
"return u'Child of %s' % unicode(self.parent)\n\nObviously you've defined a __unicode__() method in the parent that makes sense, right?\n"
] | [
3
] | [] | [] | [
"admin",
"django",
"python"
] | stackoverflow_0002485766_admin_django_python.txt |
Q:
Clever way of building a tag cloud? - Python
I've built a content aggregator and would like to add a tag cloud representing the current trends.
Unfortunately this is quite complex, as I have to look for keywords that represent the context of each article.
For example words such as I, was, the, amazing, nice have n... | Clever way of building a tag cloud? - Python | I've built a content aggregator and would like to add a tag cloud representing the current trends.
Unfortunately this is quite complex, as I have to look for keywords that represent the context of each article.
For example words such as I, was, the, amazing, nice have no relation to context.
Help would be much appreci... | [
"Use NLTK, and in particular its Stopwords corpus:\n\nBesides regular content words, there\n is another class of words called stop\n words that perform important\n grammatical functions, but are\n unlikely to be interesting by\n themselves. These include\n prepositions, complementizers, and\n determiners. NL... | [
9,
2
] | [] | [] | [
"data_mining",
"django",
"indexing",
"keyword",
"python"
] | stackoverflow_0002485800_data_mining_django_indexing_keyword_python.txt |
Q:
very quickly getting total size of folder
I want to quickly find the total size of any folder using python.
import os
from os.path import join, getsize, isfile, isdir, splitext
def GetFolderSize(path):
TotalSize = 0
for item in os.walk(path):
for file in item[2]:
try:
To... | very quickly getting total size of folder | I want to quickly find the total size of any folder using python.
import os
from os.path import join, getsize, isfile, isdir, splitext
def GetFolderSize(path):
TotalSize = 0
for item in os.walk(path):
for file in item[2]:
try:
TotalSize = TotalSize + getsize(join(item[0], fil... | [
"You are at a disadvantage.\nWindows Explorer almost certainly uses FindFirstFile/FindNextFile to both traverse the directory structure and collect size information (through lpFindFileData) in one pass, making what is essentially a single system call per file.\nPython is unfortunately not your friend in this case. ... | [
82,
22,
5
] | [] | [] | [
"directory",
"optimization",
"python"
] | stackoverflow_0002485719_directory_optimization_python.txt |
Q:
How to import modules that are used in both the main code and a module correctly?
Let's assume I have a main script, main.py, that imports another python file with import coolfunctions and another: import chores
Now, suppose coolfunctions also uses stuff from chores, hence I declare import chores inside coolfun... | How to import modules that are used in both the main code and a module correctly? | Let's assume I have a main script, main.py, that imports another python file with import coolfunctions and another: import chores
Now, suppose coolfunctions also uses stuff from chores, hence I declare import chores inside coolfunctions.
Since both main.py, and coolfunctions import chores ~ is this redundant? Is th... | [
"If two modules want to use chores, then each one must import chores (or some equivalent import). Each import creates a name binding only in the namespace of the module that does the import; that is, import's namespace effect is local to a module's namespace.\nThis is good, because by looking at a module's code you... | [
2,
1,
1,
0
] | [] | [] | [
"file",
"import",
"module",
"python"
] | stackoverflow_0002485901_file_import_module_python.txt |
Q:
Calling gawk from Python
I am trying to call gawk (the GNU implementation of AWK) from Python in this manner.
import os
import string
import codecs
ligand_file=open( "2WTKA_ab.txt", "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.... | Calling gawk from Python | I am trying to call gawk (the GNU implementation of AWK) from Python in this manner.
import os
import string
import codecs
ligand_file=open( "2WTKA_ab.txt", "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.strip, ligand_lines )
ligand_... | [
"That's a non-portable and messy way to check if something is in a file. Imagine you have 1000 lines, you will be making system call to gawk 1000 times. It's super inefficient. You are using Python, so do them in Python. \n....\nligand_file=open( \"2WTKA_ab.txt\", \"r\" ) #Open the receptor.txt file\nligand_lines=l... | [
4,
1
] | [] | [] | [
"gawk",
"python"
] | stackoverflow_0002485362_gawk_python.txt |
Q:
Python: Script works, but seems to deadlock after some time
I have the following script, which is working for the most part Link to PasteBin The script's job is to start a number of threads which in turn each start a subprocess with Popen. The output from each subprocess is as follows:
1
2
3
.
.
.
n
Done
Bascia... | Python: Script works, but seems to deadlock after some time | I have the following script, which is working for the most part Link to PasteBin The script's job is to start a number of threads which in turn each start a subprocess with Popen. The output from each subprocess is as follows:
1
2
3
.
.
.
n
Done
Bascially the subprocess is transferring 10M records from tables in one... | [
"You have a few places in your script where you return without releasing your locks. This could cause a problem - lines: 97 and 99 - this is where try: finally: blocks can help you a lot as you can then ensure that the release is called properly.\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"signals",
"subprocess"
] | stackoverflow_0002483840_multithreading_python_signals_subprocess.txt |
Q:
How to display a QGraphicsScene?
I've got the following code and I'm not sure how to add the QGraphicsScene to my layout..
class MainForm(QDialog):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.scene = QGraphicsScene(self)
self.scene.setSceneRect(0, 0, 500... | How to display a QGraphicsScene? | I've got the following code and I'm not sure how to add the QGraphicsScene to my layout..
class MainForm(QDialog):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.scene = QGraphicsScene(self)
self.scene.setSceneRect(0, 0, 500, 500)
self.view = QGraphicsVi... | [
"You'll have to do something like this:\n...\nlayout = QVBoxLayout()\nlayout.addWidget(zoomSlider)\nlayout.addWidget(view)\nself.setLayout(layout)\n...\n\n",
"You have added a scene to view, and it's enough. But you should add the view to your MainForm and Layout. View is a kind of widget that can be displayed by... | [
2,
0
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0002484461_pyqt_python_qt.txt |
Q:
How to get Eclipse + PyDev + App Engine + Unit testing to work?
I want to run my unit tests for a Python Google App Engine project using
Run As => Python unit-test
But when I try that all my Model tests bail with the error message:
BadArgumentError: app must not be empty.
Anyone got this to work?
NB: The tests ... | How to get Eclipse + PyDev + App Engine + Unit testing to work? | I want to run my unit tests for a Python Google App Engine project using
Run As => Python unit-test
But when I try that all my Model tests bail with the error message:
BadArgumentError: app must not be empty.
Anyone got this to work?
NB: The tests runs fine using Nose --with-gae. But I want the PyDev integration wit... | [
"Pasting the answer I got from the Fabioz (the PyDev creator) himself over at the PyDev forums on SF: https://sourceforge.net/projects/pydev/forums/forum/293649/topic/3618848\n\nThere's no such option right now... please enter a feature request for that. Note that you can run nose itself from inside of pydev (with ... | [
3
] | [] | [] | [
"google_app_engine",
"pydev",
"python",
"unit_testing"
] | stackoverflow_0002473467_google_app_engine_pydev_python_unit_testing.txt |
Q:
Convert python script to binary executable
I wrote a number crunching python code. The calculations involved can take hours. Is it possible somehow to compile it to binary?
Thanks
A:
Not in any useful (for you) way, but moving the calculations into NumPy or Cython will speed them up.
A:
First you can try psyco... | Convert python script to binary executable | I wrote a number crunching python code. The calculations involved can take hours. Is it possible somehow to compile it to binary?
Thanks
| [
"Not in any useful (for you) way, but moving the calculations into NumPy or Cython will speed them up.\n",
"First you can try psyco, that may give you a speed up as much as 10x, but 2x is more typical\nIf you can post the code up somewhere, perhaps someone can point out how to leverage numpy.\nIf your task doesn'... | [
5,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002486737_python.txt |
Q:
Need help with re for matching and getting the value python
Need help regarding re.
file = 'file No.WR79050107006 from files'
So what I am trying to do is validate if file string contains WR + 11 digit.
result = re.match('^(\S| )*(?P<sr>(\d){11})(\S| )*', file)
Its validate only 11 digit but not WR before it.
H... | Need help with re for matching and getting the value python | Need help regarding re.
file = 'file No.WR79050107006 from files'
So what I am trying to do is validate if file string contains WR + 11 digit.
result = re.match('^(\S| )*(?P<sr>(\d){11})(\S| )*', file)
Its validate only 11 digit but not WR before it.
How can I do that?
Using re after matching how can I get the match... | [
"If by \"validate if file string contains WR + 11 digit\" you mean \"exactly 11, not 12+\",\nmo = re.search(r'WR(\\d{11})(\\D|$)', thestring)\n\nshould do. If you actually mean \"11 or more\", there's no need for the (\\D|$) part (or equivalent negative lookahead, etc).\nEdit: as the OP now says in a comment that ... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002486150_python.txt |
Q:
Python: date, time formatting
I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '.
Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?
A:
import time
localtime ... | Python: date, time formatting | I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '.
Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?
| [
"import time\n\nlocaltime = time.localtime()\ntimeString = time.strftime(\"%Y%m%d%H%M%S\", localtime)\n\n# is DST in effect?\ntimezone = -(time.altzone if localtime.tm_isdst else time.timezone)\ntimeString += \"Z\" if timezone == 0 else \"+\" if timezone > 0 else \"-\"\ntimeString += time.strftime(\"%H'%M'\",... | [
32,
8
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002487109_datetime_python.txt |
Q:
diffstrings.py : how do you specify path arguments?
I am trying to use diffstrings.py from Three20 on my iPhone project, and I can't find the proper format for the path arguments (as in "Usage: diffstrings.py [options] path1 path2 ...").
For example, when I run the script in my Xcode project directory like this
~/... | diffstrings.py : how do you specify path arguments? | I am trying to use diffstrings.py from Three20 on my iPhone project, and I can't find the proper format for the path arguments (as in "Usage: diffstrings.py [options] path1 path2 ...").
For example, when I run the script in my Xcode project directory like this
~/py/diffstrings.py -b
it analyzes just the main.m and fin... | [
"Taking a quick look at the code here http://github.com/facebook/three20/blob/master/diffstrings.py I see that if you don't specify any command line options, it assumes you mean the directory wherever the script lives in. So the option is to either copy .py file to where your .m files are, or simple use the command... | [
0
] | [] | [] | [
"iphone",
"localization",
"python"
] | stackoverflow_0002486822_iphone_localization_python.txt |
Q:
How to set cookies with redirect in Pylons
In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?
A:
... | How to set cookies with redirect in Pylons | In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?
| [
"Drilling down a bit, the webkit folks say it's not their problem, so the possible solutions aren't as pretty. One possible ugly solution: setting the tracking information in the beaker session (if you're using beaker?) and retrieving it from the page that you're redirecting to, setting a cookie at that later stag... | [
1
] | [] | [] | [
"cookies",
"pylons",
"python",
"redirect"
] | stackoverflow_0002292881_cookies_pylons_python_redirect.txt |
Q:
programming language implemented in pure python
i am creating ( researching possibility of ) a highly customizable python client and would like to allow users to actually edit the code in another language to customize the running of program. ( analogous to browser which itself coded in c/c++ and run another langua... | programming language implemented in pure python | i am creating ( researching possibility of ) a highly customizable python client and would like to allow users to actually edit the code in another language to customize the running of program. ( analogous to browser which itself coded in c/c++ and run another language html/js ). so my question is , is there any progra... | [
"The question isn't completely clear on scope, but I have a hunch that PyPy, embedding other full languages, and similar solutions might be overkill. It sounds like iamgopal may really be interested in something more like Interpreter Pattern or Little Language.\nIf the language you want to support is really small ... | [
4,
3,
3,
1,
1,
1,
0,
0
] | [] | [] | [
"interpreter",
"programming_languages",
"python"
] | stackoverflow_0002486348_interpreter_programming_languages_python.txt |
Q:
Using ManagementClass.Getinstances() from IronPython
I have an IronPython script that looks for current running processes using WMI. The code looks like this:
import clr
clr.AddReference('System.Management')
from System.Management import ManagementClass
from System import Array
mc = ManagementClass('Win32_Processe... | Using ManagementClass.Getinstances() from IronPython | I have an IronPython script that looks for current running processes using WMI. The code looks like this:
import clr
clr.AddReference('System.Management')
from System.Management import ManagementClass
from System import Array
mc = ManagementClass('Win32_Processes')
procs = mc.GetInstances()
That last line where I call... | [
"I think the only problem is that 'Win32_Processes' is a typo for 'Win32_Process'. This seems to work:\n>>> mc = ManagementClass('Win32_Process')\n>>> procs = mc.GetInstances()\n>>> for p in procs:\n... print p['Name']\n... \nSystem Idle Process\nSystem\nsmss.exe\n(etc)\n\n"
] | [
1
] | [] | [] | [
"ironpython",
"python",
"wmi"
] | stackoverflow_0002487475_ironpython_python_wmi.txt |
Q:
How to clear wxpython frame content when dragging a panel?
I have 3 panels and I want to make drags on them.
The problem is that when I do a drag on one this happens:
http://img41.yfrog.com/img41/9043/soundlog.png http://img41.yfrog.com/img41/9043/soundlog.png
How can I refresh the frame to happear its color when ... | How to clear wxpython frame content when dragging a panel? | I have 3 panels and I want to make drags on them.
The problem is that when I do a drag on one this happens:
http://img41.yfrog.com/img41/9043/soundlog.png http://img41.yfrog.com/img41/9043/soundlog.png
How can I refresh the frame to happear its color when the panel is no longer there?
This is the code that I have to ma... | [
"To refresh the parent on every repositioning of self, you could add\nself.parent.Refresh()\n\nright after your existing call to self.SetPosition in your def onMouseMove method. Right now you're refreshing the frame only in the def onDraggingDown method, i.e., the first time the mouse left button is clicked and hel... | [
1
] | [] | [] | [
"panel",
"python",
"refresh",
"wxpython"
] | stackoverflow_0002437818_panel_python_refresh_wxpython.txt |
Q:
Hidden line removal in JavaScript or Python?
I have the following task:
Input:
A 3D scene comprised of a set of cuboids. Could be broken down to a set of triangles.
A description of a camera: position, direction, focal length.
Output: 2D wire frame projection of the scene as a set of lines. Important: Hidden line... | Hidden line removal in JavaScript or Python? | I have the following task:
Input:
A 3D scene comprised of a set of cuboids. Could be broken down to a set of triangles.
A description of a camera: position, direction, focal length.
Output: 2D wire frame projection of the scene as a set of lines. Important: Hidden lines removal should have been applied.
Platform: Web ... | [
"Maybe the Python Nacrisse interface is useful?\n"
] | [
0
] | [] | [] | [
"3d",
"hidden",
"javascript",
"lines",
"python"
] | stackoverflow_0002487235_3d_hidden_javascript_lines_python.txt |
Q:
Pypcap for mac on python 2.6?
How do you end up running pypcap for python 2.6 on a mac? It seems that there hasn't been any new releases since 2.5 or am I just looking in the wrong places?
I seem to be unable to install the 2.5 binary with the following error: You cannot install pcap 1.1 on this volume. pcap requ... | Pypcap for mac on python 2.6? | How do you end up running pypcap for python 2.6 on a mac? It seems that there hasn't been any new releases since 2.5 or am I just looking in the wrong places?
I seem to be unable to install the 2.5 binary with the following error: You cannot install pcap 1.1 on this volume. pcap requires System Python 2.5 to install.
| [
"Python 2.5 code should run fine unaltered on Python 2.6 (you'll just occasionaly get a DeprecationWarning for features which are changing in Python 3.x).\n"
] | [
1
] | [] | [] | [
"packet_sniffers",
"pcap",
"python"
] | stackoverflow_0002488185_packet_sniffers_pcap_python.txt |
Q:
django image upload forms
I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files
my models
class UserProfile(User):
"""user with app settings. """
DESIGNATION_CHOICES=(
('ADM', 'Administr... | django image upload forms | I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files
my models
class UserProfile(User):
"""user with app settings. """
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Offic... | [
"the issue was actually that this line \n<form method=\"post\" id=\"form\" action=\"\" enctype=\"multipart/form-data\" class=\"infotabs accfrm\">\n\nappeared as \n<form method=\"post\" id=\"form\" action=\"\" enctype=\"multipart/form\n-data\" class=\"infotabs accfrm\">\n\nhence the forms were not uploading. And to ... | [
3
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002487521_django_django_forms_python.txt |
Q:
Newbie Python programmer tangling with Lists
Here's what I've got so far:
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
... | Newbie Python programmer tangling with Lists | Here's what I've got so far:
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
counter = 0
for word in... | [
"You should do:\ncounter += 1\n\ninstead of\ncounter += counter\n\nwhich stays at 0 for all ages.\n",
"counter += 1\n\nyou add 0 to 0\n"
] | [
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002488447_list_python.txt |
Q:
Djangobb problem
I've installed Djangobb app on my server (Debian, mod_python) by cloning original source. The only things I've changed is database options in settings.py. All needed components are installed - syncdb query was executed right.
But, when I'm trying to enter on my forum, it returns me error:
Imprope... | Djangobb problem | I've installed Djangobb app on my server (Debian, mod_python) by cloning original source. The only things I've changed is database options in settings.py. All needed components are installed - syncdb query was executed right.
But, when I'm trying to enter on my forum, it returns me error:
ImproperlyConfigured: Error i... | [
"There are two obvious reasons to why this might happen:\n\ndjangobb_forum is not on your Python path\nThere is no __init__.py in the djangobb_forum folder\n\nIf the code says from djangobb_forum import ... then you need to have the parent folder of djangobb_forum on your Python path.\n"
] | [
2
] | [] | [] | [
"django",
"mod_python",
"python"
] | stackoverflow_0002488142_django_mod_python_python.txt |
Q:
Python: Inheritance of a class attribute (list)
inheriting a class attribute from a super class and later changing the value for the subclass works fine:
class Unit(object):
value = 10
class Archer(Unit):
pass
print Unit.value
print Archer.value
Archer.value = 5
print Unit.value
print Archer.value
lea... | Python: Inheritance of a class attribute (list) | inheriting a class attribute from a super class and later changing the value for the subclass works fine:
class Unit(object):
value = 10
class Archer(Unit):
pass
print Unit.value
print Archer.value
Archer.value = 5
print Unit.value
print Archer.value
leads to the output:
10
10
10
5
which is just fine: Arch... | [
"It is not a matter of shallow or deep copies, it is a matter of references and assignments.\nIt the first case Unit.value and Archer.value are two variables which reference the same value. When you do Archer.value = 5, you are assigning a new reference to Acher.value.\nTo solve your problem you need to assign a n... | [
16,
10,
0
] | [] | [] | [
"class_attributes",
"deep_copy",
"inheritance",
"list",
"python"
] | stackoverflow_0002488306_class_attributes_deep_copy_inheritance_list_python.txt |
Q:
ping ip's / hostname in app engine
I'm trying to ping an ip address and telnet to some port from an app hosted on app engine. I've tried using http://svn.pylucid.net/pylucid/CodeSnippets/ping.py but for some reason it failing
Thanks
A:
GAE does not support ICMP nor Telnet.
For communication with outside hosts a... | ping ip's / hostname in app engine | I'm trying to ping an ip address and telnet to some port from an app hosted on app engine. I've tried using http://svn.pylucid.net/pylucid/CodeSnippets/ping.py but for some reason it failing
Thanks
| [
"GAE does not support ICMP nor Telnet.\nFor communication with outside hosts at the moment only mail/xmpp/http(s) work through the specific API calls. \n",
"\nNote that ICMP messages can only be\n sent from processes running as root.\n\nYour app on GAE is not running as root. Why bother pinging when you want to ... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002488430_google_app_engine_python.txt |
Q:
Read more numbers in a line in Python
Let say i want to read the integers a, b and c from stdin (in one line, do not need to press return after each number). In c++, i would just do:
cin >> a >>b >> c;
How to do this in Python ?
A:
for string
a,b,c=raw_input().split()
for int
a,b,c=map(int,raw_input().split())
... | Read more numbers in a line in Python | Let say i want to read the integers a, b and c from stdin (in one line, do not need to press return after each number). In c++, i would just do:
cin >> a >>b >> c;
How to do this in Python ?
| [
"for string\na,b,c=raw_input().split()\n\nfor int\na,b,c=map(int,raw_input().split())\n\n",
"values = raw_input()\n# 1 3 15\na, b, c = values.split()\n\na will be '1', b will be '3' and c will be '15'.\n\nIf you want to be extra short and get ints try this:\na, b, c = [int(_) for _ in raw_input().split()]\n\n"
] | [
3,
3
] | [] | [] | [
"python",
"user_input"
] | stackoverflow_0002488769_python_user_input.txt |
Q:
django admin - adding fields on the fly
Basically I am writing a simple shopping cart. Each item can have multiple prices. (i.e. shirts where each size is priced differently). I would like to have a single price field in my admin panel, where when the first price is entered, an additional price field pops up. Howe... | django admin - adding fields on the fly | Basically I am writing a simple shopping cart. Each item can have multiple prices. (i.e. shirts where each size is priced differently). I would like to have a single price field in my admin panel, where when the first price is entered, an additional price field pops up. However I am kind of at a loss as to how to do th... | [
"Sounds like you want two related models - Item and Option. Item would contain the name of the item, and Option would contain the option - eg size - and the price of that option. You would then set up your admin to use an inline form for Option.\n",
"You probably want inlines and some javascript.\n",
"You might... | [
1,
0,
0
] | [] | [] | [
"django",
"django_admin",
"django_nonrel",
"python",
"shopping_cart"
] | stackoverflow_0002488710_django_django_admin_django_nonrel_python_shopping_cart.txt |
Q:
Trouble with this Python newbie exercise. Using Lists and finding if two adjacent elements are the same
Here's what I got:
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify t... | Trouble with this Python newbie exercise. Using Lists and finding if two adjacent elements are the same | Here's what I got:
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
for number in nums:
numberHolder = number
# +++your co... | [
">>> import itertools\n>>> [i[0] for i in itertools.groupby([1,2,2,3,3,3,2,2])]\n[1, 2, 3, 2]\n\nOr:\n>>> def f(l):\n... r = []\n... last = None\n... for i in l:\n... if i != last:\n... r.append(i)\n... last = i\n... return r \n... \n>>> f([1,2,2,3,3,3,4,4,2,2]... | [
5,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002488651_list_python.txt |
Q:
Python performance: iteration and operations on nested lists
Problem Hey folks. I'm looking for some advice on python performance. Some background on my problem:
Given:
A (x,y) mesh of nodes each with a value (0...255) starting at 0
A list of N input coordinates each at a specified location within the range (0... | Python performance: iteration and operations on nested lists | Problem Hey folks. I'm looking for some advice on python performance. Some background on my problem:
Given:
A (x,y) mesh of nodes each with a value (0...255) starting at 0
A list of N input coordinates each at a specified location within the range (0...x, 0...y)
A value Z that defines the "neighborhood" in count of... | [
"1. A (smaller) speedup could definitely be the initialization of your rows...\nReplace\nrows = []\nfor i in range(x):\n rows.append([0 for i in xrange(y)])\n\nwith\nrows = [[0] * y for i in xrange(x)]\n\n2. You can also avoid some lookups by moving random.random out of the loops (saves a little).\n3. EDIT: afte... | [
2,
2,
1,
1,
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0002488654_performance_python.txt |
Q:
python, wrapping class returning the average of the wrapped members
The title isn't very clear but I'll try to explain.
Having this class:
class Wrapped(object):
def method_a(self):
# do some operations
return n
def method_b(self):
# also do some operations
return n
I w... | python, wrapping class returning the average of the wrapped members | The title isn't very clear but I'll try to explain.
Having this class:
class Wrapped(object):
def method_a(self):
# do some operations
return n
def method_b(self):
# also do some operations
return n
I want to have a class that performs the same way as this one:
class Wrapper... | [
"While quite doable, it's just a little bit tricky because the getting of a method (or other attribute) and the calling thereof are separate operations. Here's a solution:\nclass Wrapper(object):\n def __init__(self):\n self.ws = [Wrapped(1),Wrapped(2),Wrapped(3)]\n\n def __getattr__(self, n):\n ... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002489133_python.txt |
Q:
importing same module more than once
So after a few hours, I discovered the cause of a bug in my application. My app's source is structured like:
main/
__init__.py
folderA/
__init__.py
fileA.py
fileB.py
Really, there are about 50 more files. But that's not the point. In main/__init... | importing same module more than once | So after a few hours, I discovered the cause of a bug in my application. My app's source is structured like:
main/
__init__.py
folderA/
__init__.py
fileA.py
fileB.py
Really, there are about 50 more files. But that's not the point. In main/__init__.py, I have this code: from folderA.file... | [
"Don't modify sys.path this way, as it provides two ways (names) to access your modules, leading to your problem.\nUse absolute or unambiguous-relative imports instead. (The ambiguous-relative imports can be used as a last resort with older Python versions.)\nfolderA/fileB.py\nfrom main.folderA.fileA import * # ... | [
5,
5
] | [] | [] | [
"import",
"import_hooks",
"python"
] | stackoverflow_0002489601_import_import_hooks_python.txt |
Q:
python parallel computing: split keyspace to give each node a range to work on
My question is rather complicated for me to explain, as i'm not really good at maths, but i'll try to be as clear as possible.
I'm trying to code a cluster in python, which will generate words given a charset (i.e. with lowercase: aaaa,... | python parallel computing: split keyspace to give each node a range to work on | My question is rather complicated for me to explain, as i'm not really good at maths, but i'll try to be as clear as possible.
I'm trying to code a cluster in python, which will generate words given a charset (i.e. with lowercase: aaaa, aaab, aaac, ..., zzzz) and make various operations on them.
I'm searching how to c... | [
"Any way that you could compute a small integer from the string would be fine for clustering. For example, compute a hash with md5, and look at a byte of it:\nimport hashlib\n\ns = \"aaac\"\nnum_nodes = 5 # or whatever\nm = hashlib.md5(s)\nnode = ord(m.digest()[0]) % num_nodes\n\nprint node # prints 2\n\nThis won... | [
1,
1
] | [] | [] | [
"algorithm",
"character_encoding",
"cluster_analysis",
"python"
] | stackoverflow_0002488670_algorithm_character_encoding_cluster_analysis_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.