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: How does Cookie Crumbler work in Zope? I'd like to log users from my other web app to a Zope app without having them to sign in again (Single Sign On). I wonder if it's possible to set a cookie like the way Cookie Crumbler does, and log in the user to Zope. Thanks. A: In Plone 4, the cookie function is handled b...
How does Cookie Crumbler work in Zope?
I'd like to log users from my other web app to a Zope app without having them to sign in again (Single Sign On). I wonder if it's possible to set a cookie like the way Cookie Crumbler does, and log in the user to Zope. Thanks.
[ "In Plone 4, the cookie function is handled by plone.session.\nIt uses a tk-auth compatible cookie, meaning you can generate these cookies if you have the shared secret. The package page contains a lot of information on how to use this for a SSO setup.\n" ]
[ 1 ]
[]
[]
[ "cookies", "python", "single_sign_on", "zope" ]
stackoverflow_0008360876_cookies_python_single_sign_on_zope.txt
Q: Is there any application out there to visualize data flow between tables and databases in a Django application in real time? The first step is done - a simple relational model of all tables (and hopefully their fields) in the given databases. The next step I haven't found done anywhere after some basic googling - ...
Is there any application out there to visualize data flow between tables and databases in a Django application in real time?
The first step is done - a simple relational model of all tables (and hopefully their fields) in the given databases. The next step I haven't found done anywhere after some basic googling - a graphical display that shows (maybe with a pulse of color) access to a given table's fields in a given database as it happens, m...
[ "If you are about to implement it yourself, you should start with writing a wrapper to the original django.db.models.Model' s default manager and log access, or use signals to communicate with a visualizer app.\n" ]
[ 1 ]
[]
[]
[ "data_visualization", "database", "django", "orm", "python" ]
stackoverflow_0008362868_data_visualization_database_django_orm_python.txt
Q: Continue to elif after a nested if-statement? If the nested if-statement doesn't fulfill a condition, how do I continue on to the outer if? Eg. I have this (very impractical) example: a = 2 if( a > 1 ): if( a == 3 ): print "yes" elif( a == 2 ): print "yes" I want a == 2 to be checked next. How wo...
Continue to elif after a nested if-statement?
If the nested if-statement doesn't fulfill a condition, how do I continue on to the outer if? Eg. I have this (very impractical) example: a = 2 if( a > 1 ): if( a == 3 ): print "yes" elif( a == 2 ): print "yes" I want a == 2 to be checked next. How would I do this? (I have multiple conditions in that ...
[ "combine the conditions and flatten the nesting:\na = 2\n\nif ( a > 1 and a == 3 ):\n print \"yes\"\nelif ( a == 2 ):\n print \"yes\"\n\n", "Considering the example is just indicative but your original question was to understand nested if-else, association, scoping ....\nIn Python, unlike Algol-like languag...
[ 4, 3, 3, 0, 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0008365714_if_statement_python.txt
Q: How to extract info from scikits.learn classifier to then use in C code I have trained a bunch of RBF SVMs using scikits.learn in Python and then Pickled the results. These are for image processing tasks and one thing I want to do for testing is run each classifier on every pixel of some test images. That is, extr...
How to extract info from scikits.learn classifier to then use in C code
I have trained a bunch of RBF SVMs using scikits.learn in Python and then Pickled the results. These are for image processing tasks and one thing I want to do for testing is run each classifier on every pixel of some test images. That is, extract the feature vector from a window centered on pixel (i,j), run each classi...
[ "Yes your solution looks alright. To pass the raw memory of a numpy array directly to a C program you can use the ctypes helpers from numpy or wrap you C program with cython and call it directly by passing the numpy array (see the doc at http://cython.org for more details).\nHowever, I am not sure that trying to sp...
[ 9 ]
[]
[]
[ "libsvm", "python", "scikit_learn", "scikits", "svm" ]
stackoverflow_0008360253_libsvm_python_scikit_learn_scikits_svm.txt
Q: how to feed pybrain ffn with one entry (to already trained network)? I need to train network and then feed it with test data one by one. Is there some example or doc including it? To achieve that I serialized trained network and I use it with every new incoming entry. The problem is, I got crash from _convertToOne...
how to feed pybrain ffn with one entry (to already trained network)?
I need to train network and then feed it with test data one by one. Is there some example or doc including it? To achieve that I serialized trained network and I use it with every new incoming entry. The problem is, I got crash from _convertToOneOfMany and even tho I understand its purpose (from here) I do not understa...
[ "It may be good if you paste more of your code. Regarding your question, it is on their documentation: http://pybrain.org/docs/quickstart/network.html\nBasically is this command: net.activate([2, 1])\nit this case the network has 2 inputs, and he/she inputs the values 2 and 1\nI recommend you going through their do...
[ 0 ]
[]
[]
[ "neural_network", "pybrain", "python" ]
stackoverflow_0008311593_neural_network_pybrain_python.txt
Q: Using Python to automate the use of online file converter How do I use Python to automate the file conversion of SBML (XML) files, stored locally, using a web-based file converter located here: http://www.ebi.ac.uk/compneur-srv/converters/converters Here are the steps for manually doing this: 1. Select "SBML" from...
Using Python to automate the use of online file converter
How do I use Python to automate the file conversion of SBML (XML) files, stored locally, using a web-based file converter located here: http://www.ebi.ac.uk/compneur-srv/converters/converters Here are the steps for manually doing this: 1. Select "SBML" from the Model Format drop-down menu 2. Select "Octave" from the Ou...
[ "selenium seems to be an obvious answer, here's for example how you can \"click\" a link:\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\n\ndriver = webdriver.Firefox()\ndriver.get(\"http://whatever\")\ndriver.find_element_by_link_text(\"link-text\").click()\n\nAs a s...
[ 1 ]
[]
[]
[ "mechanize", "python", "screen_scraping", "scripting", "web_scraping" ]
stackoverflow_0008365334_mechanize_python_screen_scraping_scripting_web_scraping.txt
Q: Python 3.0 - Idle wont open. It just bounces in the dock Python/Unix noob. On Mac OSX. Been running Python 2.7.2 for a few weeks, along with Idle app. No problems. Today I just installed Python3.0 along side 2.7 - tested both and can still be ran via Terminal. Now when I open Idle for 2.7, it opens just fine. Bu...
Python 3.0 - Idle wont open. It just bounces in the dock
Python/Unix noob. On Mac OSX. Been running Python 2.7.2 for a few weeks, along with Idle app. No problems. Today I just installed Python3.0 along side 2.7 - tested both and can still be ran via Terminal. Now when I open Idle for 2.7, it opens just fine. But when I open the new Idle app within the Python3.0 folder, th...
[ "Do not use Python 3.0. The initial releases of Python 3 were somewhat experimental and had a number of serious problems that have been fixed in subsequent releases. The fixed problems include the one you're seeing which I believe was covered by Issue5196. The current release of Python 3 is 3.2.2 and is considere...
[ 3 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0008366401_macos_python.txt
Q: Highlighting glossary terms inside a HTML document We have a glossary with up to 2000 terms (where each glossary term may consist of one, two or three words (either separated with whitespaces or a dash). Now we are looking for a solution for highlighting all terms inside a (longer) HTML document (up to 100 KB of H...
Highlighting glossary terms inside a HTML document
We have a glossary with up to 2000 terms (where each glossary term may consist of one, two or three words (either separated with whitespaces or a dash). Now we are looking for a solution for highlighting all terms inside a (longer) HTML document (up to 100 KB of HTML markup) in order to generate a static HTML page with...
[ "You could use a parser to navigate your tree in a recursive manner and replace only tags that are made of text.\nIn doing so, there are still several things you will need to account for:\n - Not all text needs to be replaced (ex. Inline javascript)\n - Some elements of the document might not need parsing (ex. Head...
[ 2, 0 ]
[ "How about going through each term in the glossary and then, for each term, using regex to find all occurrences in the HTML? You could replace each of those occurrences with the term wrapped in a span with a class \"highlighted\" that will be styled to have a background color.\n" ]
[ -1 ]
[ "glossaries", "glossary", "highlighting", "javascript", "python" ]
stackoverflow_0008366909_glossaries_glossary_highlighting_javascript_python.txt
Q: Are there any other queues in the standard library? I want to queue lambda : Popen(.....) To call/wait at a later time. Then add some more to paused Popens to the queue, then consume them again and so on. The main Queue module cares a lot about synchronization and this makes the api feel a bit weird in places. I...
Are there any other queues in the standard library?
I want to queue lambda : Popen(.....) To call/wait at a later time. Then add some more to paused Popens to the queue, then consume them again and so on. The main Queue module cares a lot about synchronization and this makes the api feel a bit weird in places. I don't care about syncing(single threaded program, Popen ...
[ "Yes, you can use a deque (collections.deque), which is a list that you can efficiently push and pop on either end. You could also use a list and not worry about the inefficiency since it probably doesn't matter.\n", "You can use collections.deque:\nfrom collections import deque\n\nqueue = deque()\nqueue.append(n...
[ 3, 3, 2 ]
[]
[]
[ "producer_consumer", "python", "queue", "thunk" ]
stackoverflow_0008367872_producer_consumer_python_queue_thunk.txt
Q: Select all of django foreign key model if condition or part if another condition I have the following models: class Project(models.Model): title = models.CharField(max_length=75) description = models.CharField(max_length=250) project_collaborators = models.ManyToManyField(User) ... class Node(models.M...
Select all of django foreign key model if condition or part if another condition
I have the following models: class Project(models.Model): title = models.CharField(max_length=75) description = models.CharField(max_length=250) project_collaborators = models.ManyToManyField(User) ... class Node(models.Model): title = models.CharField(max_length=75) collaborators = models.ManyToMa...
[ "I'll give you two approaches:\nDoing this with as few queries as possible\nGet the Node objects and then use them to get the Project objects, rather than the other way around:\nnodes = Node.objects.filter(Q(project__project_collaborators=user) | Q(collaborators=user)).select_related('project').distinct()\n\nNow yo...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008360438_django_django_models_python.txt
Q: Way to ensure unique constraint of a field I have the following model class. class Human(db.Model): email = db.StringProperty(required=True) date = db.DateTimeProperty(auto_now=True) checksum = db.IntegerProperty(required=True) version = db.IntegerProperty(required=True) content = blobstore.Blo...
Way to ensure unique constraint of a field
I have the following model class. class Human(db.Model): email = db.StringProperty(required=True) date = db.DateTimeProperty(auto_now=True) checksum = db.IntegerProperty(required=True) version = db.IntegerProperty(required=True) content = blobstore.BlobReferenceProperty(required=True) Currently, to...
[ "This is really the only way to do it.\nThe email property is probably redundant in this case, since you're already storing the data in the key name.\nThe only other option is to give all of the Human entities the same parent, thus putting them together in an entity group, which will allow you to do updates within ...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008368249_google_app_engine_python.txt
Q: How do I split a unicode string on code points in python? (eg. \u00B7 or \u2022)? I tried everything I could think of... 1. unicode_obj.split('\u2022') 2. re.split(r'\u2022', unicode_object) 3. re.split(r'(?iu)\u2022', unicode_object) Nothing worked The problem is that I want to split on special characters. examp...
How do I split a unicode string on code points in python? (eg. \u00B7 or \u2022)?
I tried everything I could think of... 1. unicode_obj.split('\u2022') 2. re.split(r'\u2022', unicode_object) 3. re.split(r'(?iu)\u2022', unicode_object) Nothing worked The problem is that I want to split on special characters. example string : u'<special char like middot:\u00b7 or bullet:\u2022> sdfhsdf <repeat specia...
[ "Consider:\n>>> print '\\u2022'\n\\u2022\n>>> print len('\\u2022')\n6\n>>> import unicodedata\n>>> map(unicodedata.name, '\\u2022'.decode('ascii'))\n['REVERSE SOLIDUS', 'LATIN SMALL LETTER U', 'DIGIT TWO', 'DIGIT ZERO', 'DIGIT TWO', 'DIGIT TWO']\n>>> \n\nvs:\n>>> print u'\\u2022'\n•\n>>> print len(u'\\u2022')\n1\n>...
[ 8 ]
[]
[]
[ "codepoint", "points", "python", "split", "unicode" ]
stackoverflow_0008368469_codepoint_points_python_split_unicode.txt
Q: Is it necessary to have the knowledge of using terminal/command-prompt for learning python I saw a couple of tutorials and they all make use of termial/command-prompt and I just dont know how they work. Is it necessary to know how they work before learning python or you can just earn it like you would learn some o...
Is it necessary to have the knowledge of using terminal/command-prompt for learning python
I saw a couple of tutorials and they all make use of termial/command-prompt and I just dont know how they work. Is it necessary to know how they work before learning python or you can just earn it like you would learn some other language(lets say C) It'll be great if you could recommend something. NOTE: I am a windows...
[ "Python can generally be used in two ways: interactively (command line) or by writing and executing modules (which are generally executed at the command line anyway). It is really hard to say if you need to have knowledge of the command line because it depends on your application.\nMost of the power of Python comes...
[ 1, 0 ]
[]
[]
[ "command_prompt", "python", "windows" ]
stackoverflow_0008368463_command_prompt_python_windows.txt
Q: Python - Searching for text, copying part of the line SO I have a text file (alarm.txt) that I convert to a string. The alarm.txt file contains: Customer Name: LOU Site: Sao Paulo Node Name: SPRouter IP address: 1.2.3.4 I open it using read(). I have experimented with readlines() but that doesn't seem to work as ...
Python - Searching for text, copying part of the line
SO I have a text file (alarm.txt) that I convert to a string. The alarm.txt file contains: Customer Name: LOU Site: Sao Paulo Node Name: SPRouter IP address: 1.2.3.4 I open it using read(). I have experimented with readlines() but that doesn't seem to work as well: alarm = open('alarm.txt').read() So now I am trying ...
[ "Just to offer a different solution, you can split the lines into key/value pairs and populate a dict:\nconf = dict()\nfor line in open(\"test.txt\"):\n key, value = line.rstrip().split(\": \", 1)\n conf[key] = value\n\nprint conf[\"Site\"]\n\n", "I think you need\nprint re.search(r\"Site:\\s*(.*)\", alarm)...
[ 3, 2, 2 ]
[]
[]
[ "python", "search" ]
stackoverflow_0008368623_python_search.txt
Q: Python: argparse subcommand subcommand? I have a program that has many available options. For example a configuration option to change settings. ./app config -h gives me the help using normal argparse subcommands now i would like to add another subcommand to the config subcommand called list to list config values...
Python: argparse subcommand subcommand?
I have a program that has many available options. For example a configuration option to change settings. ./app config -h gives me the help using normal argparse subcommands now i would like to add another subcommand to the config subcommand called list to list config values ./app config list additionally that command...
[ "#file: argp.py\n\nimport argparse\n\nparser = argparse.ArgumentParser(prog='PROG')\nparser_subparsers = parser.add_subparsers()\nsub = parser_subparsers.add_parser('sub')\nsub_subparsers = sub.add_subparsers()\nsub_sub = sub_subparsers.add_parser('sub_sub') ...
[ 10 ]
[]
[]
[ "argparse", "arguments", "python" ]
stackoverflow_0008368110_argparse_arguments_python.txt
Q: Will the function in python for loop be executed multiple times? Say I have the following class with a method returning a list: class C: def f(self): return [1,2,3] If I loop over the list returned fro the method, as follows: c = C() for i in c.f(): print(i) Inside the for loop, will c.f() be exe...
Will the function in python for loop be executed multiple times?
Say I have the following class with a method returning a list: class C: def f(self): return [1,2,3] If I loop over the list returned fro the method, as follows: c = C() for i in c.f(): print(i) Inside the for loop, will c.f() be executed multiple times? If yes, in order to get it once, do I have to do...
[ "In [395]: def tester():\n ...: print \"Tester Called!\"\n ...: return [1,2,3]\n\nIn [396]: for i in tester():\n ...: pass\nTester Called!\n\nSeems the answer is no.\n", "from the python docs:\n\nThe for statement is used to iterate over the elements of a sequence\n (such as a string, tup...
[ 6, 5, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008369029_python.txt
Q: Setup Eclipse to work with Python bindings for Subversion I'm new in the Python world, coming from PHP. So, this question may sound silly for experienced Python developers, but I'm really confused. So, I want to implement simple Python app to work with subversion. For that purpose I want to use python bindings for...
Setup Eclipse to work with Python bindings for Subversion
I'm new in the Python world, coming from PHP. So, this question may sound silly for experienced Python developers, but I'm really confused. So, I want to implement simple Python app to work with subversion. For that purpose I want to use python bindings for subversion, so I installed Ubuntu python-subversion and python...
[ "I remember installing this a while ago. Did you follow all the step of the? \nThe ones that you have to get right are:\n\ncd Source\nCreate the Makefile using 'python setup.py configure'\nmake\ncd Tests\nTest pysvn by running make\n\nIf that runs you know you are ok with the build. Then install pysvn by copying th...
[ 1 ]
[]
[]
[ "eclipse", "python", "svn", "ubuntu" ]
stackoverflow_0008369020_eclipse_python_svn_ubuntu.txt
Q: Binary search over a huge file with unknown line length I'm working with huge data CSV file. Each file contains milions of record , each record has a key. The records are sorted by thier key. I dont want to go over the whole file when searching for certian data. I've seen this solution : Reading Huge File in Pytho...
Binary search over a huge file with unknown line length
I'm working with huge data CSV file. Each file contains milions of record , each record has a key. The records are sorted by thier key. I dont want to go over the whole file when searching for certian data. I've seen this solution : Reading Huge File in Python But it suggests that you use the same length of lines on th...
[ "You don't have to have a fixed width record because you don't have to do a record-oriented search. Instead you can just do a byte-oriented search and make sure that you realign to keys whenever you do a seek. Here's a (probably buggy) example of how to modify the solution you linked to from record-oriented to byte...
[ 8, 2, 1 ]
[]
[]
[ "binary_search", "database", "io", "large_files", "python" ]
stackoverflow_0008369175_binary_search_database_io_large_files_python.txt
Q: Decode data sent through websocket I'm trying to build a simple Python Websocket server. I managed to do the handshaking and all that stuff. However, I can't figure out how to decode the messages received from the browser, this is the raw output of what the server receives: 'xÙõKþ°pãüCY. How am I supposed to decod...
Decode data sent through websocket
I'm trying to build a simple Python Websocket server. I managed to do the handshaking and all that stuff. However, I can't figure out how to decode the messages received from the browser, this is the raw output of what the server receives: 'xÙõKþ°pãüCY. How am I supposed to decode that?
[ "The WebSocket protocol involves a framing protocol. The browser does not just send raw application bytes to the server (nor vice versa). You need to parse the framing protocol to extract the raw bytes.\nMany libraries have been implemented to do this parsing for you. You should probably try using one of those. ...
[ 3, 0 ]
[]
[]
[ "html", "python", "websocket" ]
stackoverflow_0008368361_html_python_websocket.txt
Q: How to do Java like type casting (byte) (Integer.parseInt(byteArrayStr[i],16)) in Python? In Java i did it like this but how do you do this in Python? Specially the bytesArray[i] = (byte) (Integer.parseInt(byteArrayStr[i],16)); public static byte[] toBytes(String bytes) throws IOException { String byteArra...
How to do Java like type casting (byte) (Integer.parseInt(byteArrayStr[i],16)) in Python?
In Java i did it like this but how do you do this in Python? Specially the bytesArray[i] = (byte) (Integer.parseInt(byteArrayStr[i],16)); public static byte[] toBytes(String bytes) throws IOException { String byteArrayStr[] = bytes.split("\\/"); byte bytesArray[] = new byte[byteArrayStr.length]; for (in...
[ "To answer directly: int(x, 16). What you're doing in Python would be a single list comprehension (I'm assuming string looks like af/ce/13/...)\nl = [int(x, 16) for x in string.split('/')]\n\n", "Just 'call' the type on the value you want to cast.\n>>> stringlist = ['123', '245', '456']\n>>> intlist = [int(e) for...
[ 3, 1 ]
[]
[]
[ "casting", "python", "python_3.x" ]
stackoverflow_0008369455_casting_python_python_3.x.txt
Q: PKCS #5 padding with m2crypto Is there any way to use PKCS #5 padding with AES CBC in m2crypto? Can't seem to find one too easily. Is there any python library that can do this? Or do I need to do it manually? If so, are there any resources on doing this? A: After much thrashing through OpenSSL docs, it looks lik...
PKCS #5 padding with m2crypto
Is there any way to use PKCS #5 padding with AES CBC in m2crypto? Can't seem to find one too easily. Is there any python library that can do this? Or do I need to do it manually? If so, are there any resources on doing this?
[ "After much thrashing through OpenSSL docs, it looks like PKCS #5 is the padding scheme it uses. Well, the OpenSSL docs aren't that great either so I'm still only 90% sure of this.\n" ]
[ 0 ]
[]
[]
[ "aes", "m2crypto", "pkcs#5", "python" ]
stackoverflow_0008358178_aes_m2crypto_pkcs#5_python.txt
Q: how to sort tuple in python? Possible Duplicate: Sorting a tuple that contains tuples I am having some trouble with sorting a tuple which contain number and string. in the beginning, I have a tuple like this: a=(("a",2),("b",2),("a",1)) then how can I sort it into: (by number first then alphabetical) a=(("a",1)...
how to sort tuple in python?
Possible Duplicate: Sorting a tuple that contains tuples I am having some trouble with sorting a tuple which contain number and string. in the beginning, I have a tuple like this: a=(("a",2),("b",2),("a",1)) then how can I sort it into: (by number first then alphabetical) a=(("a",1),("a",2),("b",2)) Thank a lot fo...
[ "Tuples cannot be sorted by definition because they are immutable. You can convert this to a list, sort the list, and then convert back to tuple. Something like this,\nmylist = sorted(a, key = lambda x: str(x[1])+str(x[0]))\na = tuple(mylist)\n\n", ">>> a=((\"a\",2),(\"b\",2),(\"a\",1))\n>>> from operator impor...
[ 2, 2, 1 ]
[]
[]
[ "python", "sorting", "tuples" ]
stackoverflow_0008369606_python_sorting_tuples.txt
Q: Increasing fps when grabbing from screen i want to record scenes from my screen, only keeping those that contain a certain pixelcolor. I have already written a screengrabber using python for this: import PIL.ImageGrab def get_pixel_colour(i_x, i_y): return PIL.ImageGrab.grab().load()[i_x, i_y] print get...
Increasing fps when grabbing from screen
i want to record scenes from my screen, only keeping those that contain a certain pixelcolor. I have already written a screengrabber using python for this: import PIL.ImageGrab def get_pixel_colour(i_x, i_y): return PIL.ImageGrab.grab().load()[i_x, i_y] print get_pixel_colour(0, 1) i= 0 while (True): ...
[ "How big is your screen?\nIf you want to screen grab a 1920x1080 screen at 25fps, and write to a bmp at 25fps you are going to need some much better hardware and probably a totally different software approach.\n" ]
[ 0 ]
[]
[]
[ "compiler_construction", "frame_rate", "python", "python_imaging_library", "screen_grab" ]
stackoverflow_0008369282_compiler_construction_frame_rate_python_python_imaging_library_screen_grab.txt
Q: Is the "profile" package part of python standard distribution? I just noticed that the import profile fails on my Ubuntu Linux box that has Python 2.6.4 installed. This surprised me because I thought it was part of the standard Python distribution. It turned out I needed to install the python-profiler Debian packa...
Is the "profile" package part of python standard distribution?
I just noticed that the import profile fails on my Ubuntu Linux box that has Python 2.6.4 installed. This surprised me because I thought it was part of the standard Python distribution. It turned out I needed to install the python-profiler Debian package to get the profile package. My question is, should I expect profi...
[ "The profile module is part of standard Python (and is different from cProfile as it is implemented purely in Python), but Ubuntu doesn't install it by default likely because of its Debian lineage. profile isn't default included in Debian either, because profile.py has a different license from the rest of Python.\n...
[ 4, 2, 1 ]
[]
[]
[ "profiler", "python" ]
stackoverflow_0008369678_profiler_python.txt
Q: Knight's Tour using a Neural Network I was looking at the knights tour problem and decided to have a go at implementing it in python using a neural network to find solutions. The general explanation of the method can be found on Wikipedia While I think I have implemented it correctly (I can't see anything else tha...
Knight's Tour using a Neural Network
I was looking at the knights tour problem and decided to have a go at implementing it in python using a neural network to find solutions. The general explanation of the method can be found on Wikipedia While I think I have implemented it correctly (I can't see anything else that is wrong), it doesn't work, it updates a...
[ "You can't update the neurons in place. Since U[t+1] depends on U[t] and V[t], if you have already updated V the calculation for U will be wrong\nI think you should split the update into two phases\nupdate_state and update_output, so all the U are updated and then all the V\n for n in neurons:\n n.update_...
[ 3, 2, 0 ]
[]
[]
[ "graph", "knights_tour", "neural_network", "python" ]
stackoverflow_0001551157_graph_knights_tour_neural_network_python.txt
Q: Is there any built in django authentication and acl=access controll list library? Is there any built in django authentication and acl=access controll list library ? Acl is for allow/deny action/method or resources. These auth/acl are available in other web framework as built in or as library or as packages/gems. ...
Is there any built in django authentication and acl=access controll list library?
Is there any built in django authentication and acl=access controll list library ? Acl is for allow/deny action/method or resources. These auth/acl are available in other web framework as built in or as library or as packages/gems.
[ "There is django.contrib.auth: https://docs.djangoproject.com/en/dev/topics/auth/\n" ]
[ 6 ]
[]
[]
[ "acl", "authentication", "django", "python" ]
stackoverflow_0008369443_acl_authentication_django_python.txt
Q: PyCharm (1.5.4) and Pandas 0.6.0 - ImportError: No module named data I am using PyCharm (1.5.4) as my python IDE on MacOS 10.6.4. I am tinkering with some code to manipulate stock price data. As part of that I want to import price data from yahoo by using the DataReader function that comes with Pandas 0.6.0. The c...
PyCharm (1.5.4) and Pandas 0.6.0 - ImportError: No module named data
I am using PyCharm (1.5.4) as my python IDE on MacOS 10.6.4. I am tinkering with some code to manipulate stock price data. As part of that I want to import price data from yahoo by using the DataReader function that comes with Pandas 0.6.0. The code is as follow: http://www.statalgo.com/2011/09/08/pandas-getting-financ...
[ "Seems like deleting PyCharm's python interpreter configuration and re-configuring solved the problem. Strange... but fixed\n" ]
[ 4 ]
[]
[]
[ "importerror", "module", "pycharm", "python" ]
stackoverflow_0008282662_importerror_module_pycharm_python.txt
Q: How do I replace characters in a string in Python? I'm trying to find the best way to do the following: I have a string lets say: str = "pkm adp" and I have a certain code in a dictionary to replace each charecter such as this one: code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'} ('a' should be replace...
How do I replace characters in a string in Python?
I'm trying to find the best way to do the following: I have a string lets say: str = "pkm adp" and I have a certain code in a dictionary to replace each charecter such as this one: code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'} ('a' should be replaced by 'c', 'd' by 'a' ...) How can I convert the first s...
[ "Try this:\n>>> import string\n>>> code = {'a': 'c', 'd': 'a', 'p': 'r', 'k': 'e', 'm': 'd'}\n>>> trans = string.maketrans(*[\"\".join(x) for x in zip(*code.items())])\n>>> str = \"pkm adp\"\n>>> str.translate(trans)\n'red car'\n\nExplanation: \n>>> help(str.translate)\nHelp on built-in function translate:\n\ntrans...
[ 8, 6, 6, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008370072_python.txt
Q: ManyToMany relationships on the same table in SQLObject My google foo has been coming up short on this, so I throw this to the geniuses here. I'm writing some beer recipe creation software and I've got a class in SQLObject and I'd like to have a RelatedJoin back to itself. But it's not working. If it matters I'm ...
ManyToMany relationships on the same table in SQLObject
My google foo has been coming up short on this, so I throw this to the geniuses here. I'm writing some beer recipe creation software and I've got a class in SQLObject and I'd like to have a RelatedJoin back to itself. But it's not working. If it matters I'm using SQLite3. Here's the table: class Hop(SQLObject): BI...
[ "Solved it. You have explicitly name the columns and the table for the join since it's only \"one-sided\":\nclass Hop(SQLObject):\n BITTERING = 0 \n AROMA = 1\n BOTH = 2\n LEAF = 0\n PELLET = 1\n PLUG = 2\n hop_types = ['Bittering', 'Aroma', 'Both',]\n hop_forms = ['Leaf', 'Pellet', 'Plug',...
[ 0 ]
[]
[]
[ "python", "sqlite", "sqlobject" ]
stackoverflow_0008370009_python_sqlite_sqlobject.txt
Q: beautifulSoup screenscraping list of improperly nested s I'm (very) new to BeautifulSoup, and for the last three days trying to get a list of churches from http://www.ucanews.com/diocesan-directory/html/ordinary-of-philippine-cagayandeoro-parishes.html. It seems that data is not properly nested but only tagged for...
beautifulSoup screenscraping list of improperly nested s
I'm (very) new to BeautifulSoup, and for the last three days trying to get a list of churches from http://www.ucanews.com/diocesan-directory/html/ordinary-of-philippine-cagayandeoro-parishes.html. It seems that data is not properly nested but only tagged for presentation purposes only. Supposedly, the hierarchical stru...
[ "Unfortunately this is going to be a little complicated because this format has some of the data you need uncontained by clear markers.\nData Model\nAlso, your understanding of the nesting is not entirely correct. Actual Catholic church structure (not this document structure) is more like:\nDistrict (also called de...
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping", "web_scraping" ]
stackoverflow_0008367499_beautifulsoup_python_screen_scraping_web_scraping.txt
Q: Displaying google search without using Google API? I want to make Google browser which when supplied with key word returns search results and download any file as required. I have created the downloader need help on searching part how to about it? I want to do it in python as I have created the downloader in the s...
Displaying google search without using Google API?
I want to make Google browser which when supplied with key word returns search results and download any file as required. I have created the downloader need help on searching part how to about it? I want to do it in python as I have created the downloader in the same.
[ "As per Section 5.3 of the Terms of Service (http://www.google.com/accounts/TOS), you need to use the API.\nHere's their custom search API, which can be used to search the whole web: http://code.google.com/apis/customsearch/v1/overview.html\n" ]
[ 3 ]
[]
[]
[ "google_search", "python" ]
stackoverflow_0008370087_google_search_python.txt
Q: Get IP address of url in python? Possible Duplicate: How can I do DNS lookups in Python, including referring to /etc/hosts? Im using Python 2.7 and im creating a iptracer with an online API. And i want the user to have the option to type e.g google.com, http://google.com or www.google.com and then get the ip add...
Get IP address of url in python?
Possible Duplicate: How can I do DNS lookups in Python, including referring to /etc/hosts? Im using Python 2.7 and im creating a iptracer with an online API. And i want the user to have the option to type e.g google.com, http://google.com or www.google.com and then get the ip address of that and add the ip to a vari...
[ ">>> import socket\n>>> print socket.gethostbyname('google.com')\n74.125.236.52\n\n", "You can use gethostbyname_ex() function located in socket module http://docs.python.org/library/socket.html\n" ]
[ 48, 2 ]
[]
[]
[ "api", "http", "python", "web" ]
stackoverflow_0008370361_api_http_python_web.txt
Q: python: incrementing values in a tokyo cabinet store I am using tcdb to hold a large key-value store. The keys are strings representing user IDs, the values are dicts of the form {'coord':0,'node':0,'way':0,'relation':0} The store is filled iterating over a data file that has coord, node, way and relation objects...
python: incrementing values in a tokyo cabinet store
I am using tcdb to hold a large key-value store. The keys are strings representing user IDs, the values are dicts of the form {'coord':0,'node':0,'way':0,'relation':0} The store is filled iterating over a data file that has coord, node, way and relation objects, each linked to a specific user. Here's my code for incre...
[ "After this line:\nself.cache[uid] = {'coord':0,'node':0,'way':0,'relation':0}\n\nAdd this:\nself.cache[uid][type] = 1\n\nAlso, please don't use type as a variable name as it hides the built-in of the same name.\n" ]
[ 2 ]
[]
[]
[ "python", "tokyo_cabinet" ]
stackoverflow_0008370311_python_tokyo_cabinet.txt
Q: Importing python modules for use in only one file More specifically let's say I have a number of .py files, with main.py importing stuff like os, pygame, math and all my other .py files, mymodule01.py etc. My problem is that whenever main.py calls on one of my .py files and that file contains something like an os....
Importing python modules for use in only one file
More specifically let's say I have a number of .py files, with main.py importing stuff like os, pygame, math and all my other .py files, mymodule01.py etc. My problem is that whenever main.py calls on one of my .py files and that file contains something like an os.listdir() I keep getting an error saying stuff like 'os...
[ "I think you may be under the impression that \"import\" acts like \"include\" in other languages. It doesn't.\nEach module object is a singleton. There's no performance degradation or danger of initializing a module's code more than once.\nFurthermore, each file has its own scope, so in your example if you define ...
[ 7, 5 ]
[]
[]
[ "import", "module", "package", "python" ]
stackoverflow_0008370487_import_module_package_python.txt
Q: What syntax is represented by an ExtSlice node in Python's AST? I'm wading through Python's ast module and can't figure out the slices definition: slice = Ellipsis | Slice(expr? lower, expr? upper, expr? step) | ExtSlice(slice* dims) | Index(expr value) So far, I know that Ell...
What syntax is represented by an ExtSlice node in Python's AST?
I'm wading through Python's ast module and can't figure out the slices definition: slice = Ellipsis | Slice(expr? lower, expr? upper, expr? step) | ExtSlice(slice* dims) | Index(expr value) So far, I know that Ellipsis is [...], Slice is the usual [start:end:step] notation, Index i...
[ "An extended slice is a slice with multiple parts which uses some slice-specific feature.\nA slice specific feature is something like ... (a literal ellipsis) or a : (a test separator).\nSo, an example where ExtSlice is involved for an expression like o[...:None] or o[1,2:3].\nHere are some examples demonstrating t...
[ 4 ]
[]
[]
[ "abstract_syntax_tree", "internals", "python" ]
stackoverflow_0008370132_abstract_syntax_tree_internals_python.txt
Q: eclipse-python IDE if else matching line/indicator I am using eclipse pydev IDE for coding python. I found that by default I am not able to see any lines/dotted lines/indicator which basically shows which "if" statement is being matched for which "else" statement. This is usually shown as a dotted line in other ID...
eclipse-python IDE if else matching line/indicator
I am using eclipse pydev IDE for coding python. I found that by default I am not able to see any lines/dotted lines/indicator which basically shows which "if" statement is being matched for which "else" statement. This is usually shown as a dotted line in other IDEs. I really miss this since if the condition branches o...
[ "No, eclipse/pydev do not have column pos indicators. However you can get them with the EditBox plugin for eclipse.\nI had to customize a little bit this tool because its defaults are too colourfoul. You have to eliminate everything except some of the square lines to get the typical tabulation vertical dotted line ...
[ 1 ]
[]
[]
[ "eclipse", "ide", "pydev", "python" ]
stackoverflow_0008370715_eclipse_ide_pydev_python.txt
Q: Loop through dictionary and change values Lets say I have a dictionary with names and grades: {"Tom" : 65, "Bob" : 90, "John" : 80...} and I want to take all the values in the dictionary and add 10% to each: {"Tom" : 71.5, "Bob" : 99, "John" : 88...} How can I do it through all the values in the dictionary? A: ...
Loop through dictionary and change values
Lets say I have a dictionary with names and grades: {"Tom" : 65, "Bob" : 90, "John" : 80...} and I want to take all the values in the dictionary and add 10% to each: {"Tom" : 71.5, "Bob" : 99, "John" : 88...} How can I do it through all the values in the dictionary?
[ "Dict comprehension:\nmydict = {key:value*1.10 for key, value in mydict.items()}\n\nPre 2.7 :\nmydict = dict(((key, value*1.10) for key, value in mydict.items()))\n\n", "You didn't ask for your dict to be replaced by a new one. The following code updates your existing dictionary. It uses basic looping techniques,...
[ 8, 5, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0008369291_python.txt
Q: How to print name of class in Python I am trying to find the syntax to print the name of my classes. Given the following: #!/usr/bin/python class a: whatever = 0 foo = a() bar = a() listOfClasses = [foo,bar] for l in listOfClasses: print l #I'm trying to find the syntax to print the name of the c...
How to print name of class in Python
I am trying to find the syntax to print the name of my classes. Given the following: #!/usr/bin/python class a: whatever = 0 foo = a() bar = a() listOfClasses = [foo,bar] for l in listOfClasses: print l #I'm trying to find the syntax to print the name of the class (eg foo and bar)
[ "From your example, you're looking for the name of the instance (foo and bar). In a nutshell, there isn't a way to do it since there could be multiple named variables pointing to the same instance.\nIf you're looking for the name of the class (i.e. a), you could use l.__class__.__name__. However, this is not totall...
[ 3, 1, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0008370943_class_python.txt
Q: panda 3d importing module error I'm trying to learn panda 3d, but I'm getting this error importerror no module named direct.showbase.showbase I'm using the latest versions of panda 3d 1.7.2, python 2.7 on windows xp, how to fix the error? A: http://www.panda3d.org/forums/viewtopic.php?t=10363 Panda 3D on Window...
panda 3d importing module error
I'm trying to learn panda 3d, but I'm getting this error importerror no module named direct.showbase.showbase I'm using the latest versions of panda 3d 1.7.2, python 2.7 on windows xp, how to fix the error?
[ "http://www.panda3d.org/forums/viewtopic.php?t=10363\nPanda 3D on Windows comes with a special version of python that is preconfigured to work correctly with Panda, that python is run with ppython.\nOtherwise you need to add the Panda libraries to your Python path from the Panda install. There is a file called pand...
[ 6 ]
[]
[]
[ "activepython", "panda3d", "python", "python_2.7" ]
stackoverflow_0008370559_activepython_panda3d_python_python_2.7.txt
Q: Data Mining in a Django/Postgres application I need to build in a analytics (reporting, charting & graphing) system into my Django application. In an ideal world I could just query my Postgres DB and get the data I want but when the amount of data in the DB goes through the roof, I'll hit performance bottlenecks a...
Data Mining in a Django/Postgres application
I need to build in a analytics (reporting, charting & graphing) system into my Django application. In an ideal world I could just query my Postgres DB and get the data I want but when the amount of data in the DB goes through the roof, I'll hit performance bottlenecks and other issues like index hell. I'm wondering if ...
[ "You might want to consider Cube. It is not a Django app, but it has a lot of nice features baked in, and Django can communicate to it easily. Also, it is lovely.\n\nYou could have you Django app just blast off events into MongoDB when the occur. This separation of systems would prevent any additional strain on y...
[ 10, 2 ]
[]
[]
[ "business_intelligence", "django", "nosql", "postgresql", "python" ]
stackoverflow_0008317478_business_intelligence_django_nosql_postgresql_python.txt
Q: How can I move to the end of a tag using BeautifulSoup in python? I have html as follows: html = '<html><table>this is a table<p>some text</p></table><p>text outside of table</p></html>' I want to move to the end of table and then find the next tag. I tried using findNext but if there is a tag inside the table i...
How can I move to the end of a tag using BeautifulSoup in python?
I have html as follows: html = '<html><table>this is a table<p>some text</p></table><p>text outside of table</p></html>' I want to move to the end of table and then find the next tag. I tried using findNext but if there is a tag inside the table it finds that tag instead of the next tag outside of the table. soup = B...
[ "would\ntest = table.nextSibling\n\nwork for you?\n" ]
[ 4 ]
[]
[]
[ "beautifulsoup", "python", "tags" ]
stackoverflow_0008370874_beautifulsoup_python_tags.txt
Q: How to run an argv script from Mac OSX terminal Had a quick question regarding running a script in Python. I have the following code typed into a file saved as "ex13.py": from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "...
How to run an argv script from Mac OSX terminal
Had a quick question regarding running a script in Python. I have the following code typed into a file saved as "ex13.py": from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third v...
[ "If you want to run from terminal you would write \npython Desktop/ex13.py 1 2 3\n\nassuming you are in your home folder and want to pass arguments 1, 2 and 3.\nHowever, your print line does not seem to be valid, separating the prints to separate lines\nprint \"The script is called:\", script \nprint \"Your first v...
[ 2, 1, 1 ]
[]
[]
[ "macos", "python", "python_idle" ]
stackoverflow_0008371468_macos_python_python_idle.txt
Q: how to use two level proxy setting in Python? I am working on web-crawler [using python]. Situation is, for example, I am behind server-1 and I use proxy setting to connect to the Outside world. So in Python, using proxy-handler I can fetch the urls. Now thing is, I am building a crawler so I cannot use only one I...
how to use two level proxy setting in Python?
I am working on web-crawler [using python]. Situation is, for example, I am behind server-1 and I use proxy setting to connect to the Outside world. So in Python, using proxy-handler I can fetch the urls. Now thing is, I am building a crawler so I cannot use only one IP [otherwise I will be blocked]. To solve this, I h...
[ "Update Sounds like you're looking to connect to proxy A and from there initiate HTTP connections via proxies B, C, D which are outside of A. You might look into the proxychains project which says it can \"tunnel any protocol via a user-defined chain of TOR, SOCKS 4/5, and HTTP proxies\". \nVersion 3.1 is availabl...
[ 8, 1 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0005719545_python_web_crawler.txt
Q: String with non-letters This is my second week of learning python and I got an homework assignment which I have already finished. The thing is that one of the first stages was to take a string and delete all non letters from it (such as "," "." ";", spaces, etc..) so I took the string and each time wrote: str1 = s...
String with non-letters
This is my second week of learning python and I got an homework assignment which I have already finished. The thing is that one of the first stages was to take a string and delete all non letters from it (such as "," "." ";", spaces, etc..) so I took the string and each time wrote: str1 = str.replace(',', '') str2 = st...
[ "You could use the re module like this:\nimport re\nstr = re.sub(r'[^a-zA-Z]+', '', str)\n\n", "Of course! You can use a loop:\ntoBeReplaced = [',',' ', ... some more chars ...]\nfor c in toBeReplaced:\n yourString = yourString.replace(c,'')\n\nYou might also have a look at regular expressions, which would mak...
[ 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008371524_python.txt
Q: `pip: error: No command by the name pip install -r requirements.txt` after running I am trying to create a boostrap.py script that will create a virtualenv and install requirements from a requirements.txt file. Other contributors to my project should be able to checkout the project from github and run python boots...
`pip: error: No command by the name pip install -r requirements.txt` after running
I am trying to create a boostrap.py script that will create a virtualenv and install requirements from a requirements.txt file. Other contributors to my project should be able to checkout the project from github and run python bootstrap.py and then source env/bin/activate to have a working install of my app. Below is t...
[ "In\nsubprocess.call([join(home_dir,bin,'pip'),'install -r requirements.txt'])\n\n'install -r requirements.txt' is being treated as a single argument that contains spaces, so the subprocess module interprets this as a call to pip 'install -r requirements.txt'.\nYou can fix this by specifying each argument separatel...
[ 3 ]
[]
[]
[ "bootstrapping", "python", "virtualenv" ]
stackoverflow_0008370215_bootstrapping_python_virtualenv.txt
Q: urllib and regular expression substitution error Why does the following result in an error? import re from urllib import quote as q s = re.compile(r'[^a-zA-Z0-9.: ^*$@!+_?-]') s.sub(q, "A/B") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/python/python-2.7.1/lib/python2.7/urllib....
urllib and regular expression substitution error
Why does the following result in an error? import re from urllib import quote as q s = re.compile(r'[^a-zA-Z0-9.: ^*$@!+_?-]') s.sub(q, "A/B") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/python/python-2.7.1/lib/python2.7/urllib.py", line 1236, in quote if not s.rstrip(safe): At...
[ "Because re.sub calls the repl parameter with an instance of re.match.\nI think you want to use:\ns.sub(lambda m: q(m.group()), \"A/B\")\n\nHowever, a simpler way of doing this might be to use the safe argument to urllib.quote:\nurllib.quote(\"A/B\", safe=\"/.: ^*$@!+_?-\")\n\n" ]
[ 2 ]
[]
[]
[ "escaping", "python", "python_2.7", "regex", "urllib" ]
stackoverflow_0008371858_escaping_python_python_2.7_regex_urllib.txt
Q: how to avoid substrings I currently process sections of a string like this: for (i, j) in huge_list_of_indices: process(huge_text_block[i:j]) I want to avoid the overhead of generating these temporary substrings. Any ideas? Perhaps a wrapper that somehow uses index offsets? This is currently my bottleneck. No...
how to avoid substrings
I currently process sections of a string like this: for (i, j) in huge_list_of_indices: process(huge_text_block[i:j]) I want to avoid the overhead of generating these temporary substrings. Any ideas? Perhaps a wrapper that somehow uses index offsets? This is currently my bottleneck. Note that process() is another ...
[ "I think what you are looking for are buffers.\nThe characteristic of buffers is that they \"slice\" an object supporting the buffer interface without copying its content, but essentially opening a \"window\" on the sliced object content. Some more technical explanation is available here. An excerpt:\n\nPython obje...
[ 8, 3, 1, 0, 0 ]
[ "\nprocess(huge_text_block[i:j]) \nI want to avoid the overhead of generating these temporary substrings.\n (...)\n Note that process() is another python module\n that expects a string as input.\n\nCompletely contradictory.\nHow can you imagine to find a way for not creating what the function requires ?!\n" ]
[ -2 ]
[ "python", "regex", "string" ]
stackoverflow_0004485942_python_regex_string.txt
Q: SOAP methods with point on its name description Ok, i've a problem consuming a soap client with python with a soap server that gives method's name with points on it like 'MyClass.mymethod(xs:string)'. This is cause by a PHP lib called nusoap that can handle those types of name with it. I've tried with suds and SOA...
SOAP methods with point on its name description
Ok, i've a problem consuming a soap client with python with a soap server that gives method's name with points on it like 'MyClass.mymethod(xs:string)'. This is cause by a PHP lib called nusoap that can handle those types of name with it. I've tried with suds and SOAPy without success. Anyone have solve a similar issue...
[ "To negate the use of a period in the method name you could access is using the map of function avaiable on the client object.\nE.G.\nreturn = client.service[0]['MyClass.mymethod']('input string')\n\nThat's a best guess with teh available information\nHope that helps\n" ]
[ 1 ]
[]
[]
[ "nusoap", "python", "soap", "soappy", "suds" ]
stackoverflow_0008368780_nusoap_python_soap_soappy_suds.txt
Q: Add to list vs. Increment Given that in Python: element = element + [0] should be equal to: element += [0] Why does one modify a list and the other does not? Here is a example: >>> a = [[0, 0], [0,0]] >>> for element in a: ... element = element + [0] ... >>> a [[0, 0], [0, 0]] a is not modified. But if I i...
Add to list vs. Increment
Given that in Python: element = element + [0] should be equal to: element += [0] Why does one modify a list and the other does not? Here is a example: >>> a = [[0, 0], [0,0]] >>> for element in a: ... element = element + [0] ... >>> a [[0, 0], [0, 0]] a is not modified. But if I increment: >>> a = [[0, 0], [0,0...
[ "This is a fun side-effect of += operatior, which calls __iadd__ instead of __add__.\nThe statement x = x + y is equivalent to x = x.__add__(y), while x += y is equivalent to x = x.__iadd__(y).\nThis lets the list class optimize += by extending the existing (ex, x += y is roughly equivalent to x.extend(y)) list ins...
[ 7, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008371433_python.txt
Q: Deep zoom on a function such as Weierstrass functions - working example or library or starter code for very-high-precision floating point math? This link shows information, including a "zoom into" the detail of a subsection of a Weierstrass function. It stops, and the notes say that the limitations of the software...
Deep zoom on a function such as Weierstrass functions - working example or library or starter code for very-high-precision floating point math?
This link shows information, including a "zoom into" the detail of a subsection of a Weierstrass function. It stops, and the notes say that the limitations of the software used to analyze the values for f(x) are hitting the limits of (I'm guessing) the most precise floating point type on the system. My question is: I...
[ "Try gmpy, which is Python bindings to the GNU multiprecision library. It can handle the range \"roughly 2^-68719476768 to 2^68719476736\" on a 32 bit system.\n", "Python's Decimal type will give you arbitrary precision floats. matplotlib will allow you to create plots.\n" ]
[ 3, 1 ]
[]
[]
[ "decimal", "floating_point", "python" ]
stackoverflow_0008371823_decimal_floating_point_python.txt
Q: TypeError: 'float' object is not iterable I am writing a program that calculates the minimum and maximum of 10 numbers from a list (data1). I am receiving a "TypeError: 'float' object is not iterable" for the following lines: temp_min10=min(data1[x-z][3]) temp_max10=max(data1[x-z][2]) Full program: x=int(0) for l...
TypeError: 'float' object is not iterable
I am writing a program that calculates the minimum and maximum of 10 numbers from a list (data1). I am receiving a "TypeError: 'float' object is not iterable" for the following lines: temp_min10=min(data1[x-z][3]) temp_max10=max(data1[x-z][2]) Full program: x=int(0) for line in data1: if x>=9: min10=0 ...
[ "The possible args for min and max are either one iterable or 2 or more scalars. Docs here. You have given it one arg which is not an iterable; it's a float.\nAside: (1) Your indentation as displayed is patently incorrect. You need to (a) avoid tabs in your source file (b) ensure that your indentation is logically ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008372030_python.txt
Q: Socket gives me error when i try to connect -python im trying to learn about sockets and i cant manage to connect to the ip,port. this is the script i got: stian's socket test tool import socket print "send request to website to check if sockets work right" ip = raw_input("website ip: ") port = raw_input("website...
Socket gives me error when i try to connect -python
im trying to learn about sockets and i cant manage to connect to the ip,port. this is the script i got: stian's socket test tool import socket print "send request to website to check if sockets work right" ip = raw_input("website ip: ") port = raw_input("website port: ") socket.connect(ip, port) tosend = "this is a te...
[ "You're calling .connect() on the module instead of an object. You will have to instantiate a socket object first, which is normally achieved via socket.socket(). You can then call .connect() on the object that is returned.\ns = socket.socket()\ns.connect((ip, int(port))\n\n", "You must first create a socket obje...
[ 4, 2, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008372345_python_sockets.txt
Q: Python/Django QuerySet to list of dicts? This is my code: obj = Object1.objects.get(pk=1) other_objs = ob1.other_objs.all() other_objs is a ManyToManyField on the Object1 object. When I execute this code: print other_objs[0] I do not get an other_obj (which should be a dict), I get a string based off the __unico...
Python/Django QuerySet to list of dicts?
This is my code: obj = Object1.objects.get(pk=1) other_objs = ob1.other_objs.all() other_objs is a ManyToManyField on the Object1 object. When I execute this code: print other_objs[0] I do not get an other_obj (which should be a dict), I get a string based off the __unicode__ method in the other_obj class. How can I ...
[ "other_objs[0] will be the first element of query and will not be a dict or string but the django model object, you can access attributes like other_objs[0].myattr1, if you want dict you can ask for specifc attributes using objects.values_list and then create a dict out of them e.g.\nattrs = ['id', 'attr1']\nvalues...
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008372364_django_python.txt
Q: How to Combine Each of the Elements of Two Lists in Python? I have a huge group of lists within lists that I want to combine: It looks sort of like this: [[1,2,3,4,5], [6,7,8,9,0], [2,5,7,9,4], [4,7,8,43,6]...] up to about 20 of these lists in a list. I now want to combine the first list and second list to look...
How to Combine Each of the Elements of Two Lists in Python?
I have a huge group of lists within lists that I want to combine: It looks sort of like this: [[1,2,3,4,5], [6,7,8,9,0], [2,5,7,9,4], [4,7,8,43,6]...] up to about 20 of these lists in a list. I now want to combine the first list and second list to look like this: [[1,6], [2,7], [3,8], [4,9], [5,0]] And then I want...
[ "How about something like this:\n>>> import itertools\n>>> foo = [[1, 2, 3], [4, 5, 6], [7, 8, 8]]\n>>> for p in itertools.permutations(foo, 2):\n... print zip(*p)\n... \n[(1, 4), (2, 5), (3, 6)]\n[(1, 7), (2, 8), (3, 8)]\n[(4, 1), (5, 2), (6, 3)]\n[(4, 7), (5, 8), (6, 8)]\n[(7, 1), (8, 2), (8, 3)]\n[(7, 4), (8...
[ 7, 2, 2, 2, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0008372268_dictionary_list_python.txt
Q: Why are PNG images rendered from a QGraphicsScene being incorrectly offset? I have a program that draws the contents of a QGraphicsScene to a PNG image. I have found that in some circumstances the PNG image is not being created correctly. The image generated appears to be 'offset' by some amount, in that the top...
Why are PNG images rendered from a QGraphicsScene being incorrectly offset?
I have a program that draws the contents of a QGraphicsScene to a PNG image. I have found that in some circumstances the PNG image is not being created correctly. The image generated appears to be 'offset' by some amount, in that the top-left corner of the QGraphicsScene isn't at (0,0) in the PNG image. The code belo...
[ "What is happening, is that the view is automatically calculating a rect for the scene and then centring itself on the graphics items that have been added. Depending on the dimensions of the items, this may sometimes leave blank areas around the edges.\nThe solution is to explicitly set a rect for the scene:\nview ...
[ 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qgraphicsscene" ]
stackoverflow_0008372045_pyqt_pyqt4_python_qgraphicsscene.txt
Q: How to disable NoReverseMatch error email on production server? I about 100 emails in my inbox this morning telling me various pages don't exist (I suspect some bot was looking for security vulnerabilities). The error is: NoReverseMatch: Reverse for 'view_profile' with arguments '('',)' and keyword arguments '{}' ...
How to disable NoReverseMatch error email on production server?
I about 100 emails in my inbox this morning telling me various pages don't exist (I suspect some bot was looking for security vulnerabilities). The error is: NoReverseMatch: Reverse for 'view_profile' with arguments '('',)' and keyword arguments '{}' not found. But when I go to the specified URL on my production serve...
[ "Somewhere (presumably in templates), you resolve view_profile with empty string instead of id. So find out why is it happening and fix it\n", "It could be that the bot is simply requesting all mappable urls (as a site crawler would) and not respecting redirect requests or cookies. \n", "You might want a robot...
[ 1, 1, 0 ]
[]
[]
[ "django", "exception", "http", "python", "url" ]
stackoverflow_0008369370_django_exception_http_python_url.txt
Q: Get command from input commands = ['chat', 'call', 'exit', 'friends', 'status'] class MainHub(object): def menu(self): while True: selection = raw_input("> ") if selection != any(commands): print "Not a recognized command!\n" else: pr...
Get command from input
commands = ['chat', 'call', 'exit', 'friends', 'status'] class MainHub(object): def menu(self): while True: selection = raw_input("> ") if selection != any(commands): print "Not a recognized command!\n" else: print selection it prints "No...
[ "You don't want the any function, you want the not in syntax:\nif selection not in commands:\n\nany is from predicate calculus and checks whether any of its inputs are True. In this case, you're comparing your input to any(commands), which is True since there is a True element in commands.\n", "\nselection != any...
[ 4, 3, 1, 0 ]
[]
[]
[ "input", "list", "python", "string" ]
stackoverflow_0008372719_input_list_python_string.txt
Q: Lazy data-flow (spreadsheet like) properties with dependencies in Python My problem is the following: I have some python classes that have properties that are derived from other properties; and those should be cached once they are calculated, and the cached results should be invalidated each time the base properti...
Lazy data-flow (spreadsheet like) properties with dependencies in Python
My problem is the following: I have some python classes that have properties that are derived from other properties; and those should be cached once they are calculated, and the cached results should be invalidated each time the base properties are changed. I could do it manually, but it seems quite difficult to mainta...
[ "Here, this should do the trick. \nThe descriptor mechanism (through which the language implements \"property\") is\nmore than enough for what you want.\nIf the code bellow does not work in some corner cases, just write me.\nclass DependentProperty(object):\n def __init__(self, calculate=None, default=None, depe...
[ 8, 1, 1 ]
[]
[]
[ "dataflow", "dependencies", "lazy_loading", "properties", "python" ]
stackoverflow_0008340289_dataflow_dependencies_lazy_loading_properties_python.txt
Q: How to populate my WTForm variables? I'm enabling a function that can edit an entity. I want to populate the form with the variables from the datastore. How can I do it? My code doesn't populate the form: if self.request.get('id'): id = int(self.request.get('id')) ad = Ad.get(db.Key.from_path('Ad', id)) im =...
How to populate my WTForm variables?
I'm enabling a function that can edit an entity. I want to populate the form with the variables from the datastore. How can I do it? My code doesn't populate the form: if self.request.get('id'): id = int(self.request.get('id')) ad = Ad.get(db.Key.from_path('Ad', id)) im = ad.matched_images editAdForm = AdForm(a...
[ "You need to pass your object via the form's second argument, \"obj\":\neditAdForm = AdForm(obj=ad)\n\nOutlined in the documentation crash course here: http://wtforms.simplecodes.com/docs/dev/crash_course.html#editing-existing-objects\n" ]
[ 26 ]
[]
[]
[ "google_app_engine", "jinja2", "python", "wtforms" ]
stackoverflow_0008128238_google_app_engine_jinja2_python_wtforms.txt
Q: Synchronous wget command sent via socket in python I'm sending wget commands to a remote server via sockets. Here is the client code: import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('192.168.1.16',12345)) s.send('wget http://url/file1') print "file 1 OK" s.send('wget http://url/file2')...
Synchronous wget command sent via socket in python
I'm sending wget commands to a remote server via sockets. Here is the client code: import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('192.168.1.16',12345)) s.send('wget http://url/file1') print "file 1 OK" s.send('wget http://url/file2') print "file 2 OK" s.send('wget http://url/file3') print...
[ "I had a similar problem just yesterday. You need some way for the server to signal \"I'm done.\"\nIn the client code you need it to wait for the server to be ready. In this simple protocol any response means \"I'm done.\" You could do more error checking if you need it.\ns.send('wget http://url/file1')\nprint \...
[ 2 ]
[]
[]
[ "python", "sockets", "synchronous", "wget" ]
stackoverflow_0008367451_python_sockets_synchronous_wget.txt
Q: Dealing with spaces in Flask url creation In a flask app I'm working on, I use U.S. state names as part of the url structure. State names are pulled from a python dictionary that links state abbreviations with their respective proper name, e.g. state_dict = {"Alabama" : "AL", "Alaska" : "AK",... This is fine whe...
Dealing with spaces in Flask url creation
In a flask app I'm working on, I use U.S. state names as part of the url structure. State names are pulled from a python dictionary that links state abbreviations with their respective proper name, e.g. state_dict = {"Alabama" : "AL", "Alaska" : "AK",... This is fine when the state name has no spaces. e.g. http://exa...
[ "The most common pattern for python would be to use a pair of dictionaries for the forward / reverse lookup to go from and to your friendly dictionary. On a side note, the term commonly used for such a \"url-friendly\" representation of a string value is \"slug\". \n# state_slugs lets you lookup either state name ...
[ 5, 2 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0008372221_flask_python.txt
Q: Numbers following Django's HTTP Response Code I'm currently working on an existing Django project which runs rather slowly (I assume it's mostly due to the AJAX calls). However, in order to prioritize optimization, I'd like to know what the numbers behind the HTTP Response codes mean. [03/Dec/2011 22:25:00] "GET /...
Numbers following Django's HTTP Response Code
I'm currently working on an existing Django project which runs rather slowly (I assume it's mostly due to the AJAX calls). However, in order to prioritize optimization, I'd like to know what the numbers behind the HTTP Response codes mean. [03/Dec/2011 22:25:00] "GET /userbase HTTP/1.1" 200 5914 <--This number [03/Dec/...
[ "Those are the size of the response in bytes. The longer ones are probably larger responses that take longer to calculate. Unfortunately, the output doesn't show time elapsed for requests, though I believe there was a feature request with that at one point.\nIf you're concerned about how long your requests are taki...
[ 9 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008373112_django_python.txt
Q: cheetah templating with flask I can't seem to find any information about using the cheetah templating engine with flask. Can anyone point me to something that google can't find, or show me how to use cheetah templates in a simple flask app? A: I am no Cheetah or Flask expert, but I don't think you need any speci...
cheetah templating with flask
I can't seem to find any information about using the cheetah templating engine with flask. Can anyone point me to something that google can't find, or show me how to use cheetah templates in a simple flask app?
[ "I am no Cheetah or Flask expert, but I don't think you need any special support to make it work. Looking at the examples for both, I came up with this (and it seems to work fine for me).\nfrom flask import Flask\nfrom Cheetah.Template import Template\n\n\nmainTemplate = \"\"\"\n<html>\n <head><title>$title</ti...
[ 6 ]
[]
[]
[ "cheetah", "flask", "python" ]
stackoverflow_0008365244_cheetah_flask_python.txt
Q: python coding of user input of hex numerals How do I get the A to F hex numerals in as user input via something like: hexnum=raw_input("input your hex number -> ") Then I have a problem with such input not being convertible via: number=int(hexnum) I am looking for a simple example with a basic explanation. A: Th...
python coding of user input of hex numerals
How do I get the A to F hex numerals in as user input via something like: hexnum=raw_input("input your hex number -> ") Then I have a problem with such input not being convertible via: number=int(hexnum) I am looking for a simple example with a basic explanation.
[ "The int constructor takes a base as its optional second argument.\n>>> int('12AF', 16)\n4783\n\n", "This should work fine. Just inform int that it is working with base 16: int(hexnum, 16).\n>>> hexnum = raw_input(\"input your hex number -> \")\ninput your hex number -> 2F\n>>> print int(hexnum, 16)\n47\n\n" ]
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0008373205_python.txt
Q: pycrypto is down? how to install pycrypto? The following is what happens: $ sudo easy_install pycrypto Searching for pycrypto Reading http://pypi.python.org/simple/pycrypto/ Reading http://pycrypto.sourceforge.net Reading http://www.pycrypto.org/ Download error: [Errno 101] Network is unreachable -- Some packages ...
pycrypto is down? how to install pycrypto?
The following is what happens: $ sudo easy_install pycrypto Searching for pycrypto Reading http://pypi.python.org/simple/pycrypto/ Reading http://pycrypto.sourceforge.net Reading http://www.pycrypto.org/ Download error: [Errno 101] Network is unreachable -- Some packages may not be found! Reading http://www.amk.ca/pyth...
[ "Softpedia also has a copy of the file:\nhttp://mac.softpedia.com/get/Development/Libraries/PyCrypto.shtml\nOnce you have the archive, I believe you should be able to install it with\n$ sudo easy_install pycrypto-2.3.tar.gz\n\n(I used pip in my case so the line above isn't confirmed.)\n", "PyCrypto releases are n...
[ 2, 1, 0 ]
[]
[]
[ "pycrypto", "python" ]
stackoverflow_0004339536_pycrypto_python.txt
Q: wrapping a numpy array in python I'm using numpy arrays in python and am trying to better visualize them to see what I am working with. Is there a way to change when the array wraps to the next line? For instance, in the terminal window I have enough columns to show 0-49 on one line, but it automatically wraps on ...
wrapping a numpy array in python
I'm using numpy arrays in python and am trying to better visualize them to see what I am working with. Is there a way to change when the array wraps to the next line? For instance, in the terminal window I have enough columns to show 0-49 on one line, but it automatically wraps on me when I convert to an array data typ...
[ "http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html\nNumpy by default prints only 75 characters when displaying arrays. You can change this by using numpy.set_printoptions()\nFor eg. I set my terminal to display 132x43 and got this:\n>>> import numpy as np\n>>> np.set_printoptions(linew...
[ 13 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0008373197_arrays_numpy_python.txt
Q: numpy.delete() requires me to return a new matrix (name) and that can't work with my code I have a matrix which is built at the start of the class and then I go on and use within a couple of functions then at the last function I want to delete a row from the matrix without having to use a new variable name for it ...
numpy.delete() requires me to return a new matrix (name) and that can't work with my code
I have a matrix which is built at the start of the class and then I go on and use within a couple of functions then at the last function I want to delete a row from the matrix without having to use a new variable name for it otherwise I would have to change every single function call (it loops until a winner is found)....
[ "I'm not sure what version of Numpy you have (or exactly what you're trying to do for that matter), but if you have Numpy 1.7, numpy.squeeze looks like it might be what you're looking for... http://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html#numpy.squeeze\n", "If changing a row to all zeros is...
[ 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008373375_numpy_python.txt
Q: JSON.dump of a given object works in command line, not inside a script object = {'score-set': [('SomeString', 1.0)], 'n': 10, 'num-found': 1, 'start': 0} type(object) is dict. When I do this in the command line json.dump(object,f) where f is an writable open file. I get the dump in the file perfectly. But insid...
JSON.dump of a given object works in command line, not inside a script
object = {'score-set': [('SomeString', 1.0)], 'n': 10, 'num-found': 1, 'start': 0} type(object) is dict. When I do this in the command line json.dump(object,f) where f is an writable open file. I get the dump in the file perfectly. But inside a program in a context like this: def JSONresponse(object,request,jsonInd...
[ "I'm guessing your float isn't really a float, but acts like it in certain ways. Try converting it to a float before serializing it:\nobject['score-set'] = [(a, float(b)) for (a, b) in object['score-set']]\n\n" ]
[ 3 ]
[]
[]
[ "json", "python" ]
stackoverflow_0008373599_json_python.txt
Q: Create a sparse diagonal matrix from row of a sparse matrix I process rather large matrices in Python/Scipy. I need to extract rows from large matrix (which is loaded to coo_matrix) and use them as diagonal elements. Currently I do that in the following fashion: import numpy as np from scipy import sparse def com...
Create a sparse diagonal matrix from row of a sparse matrix
I process rather large matrices in Python/Scipy. I need to extract rows from large matrix (which is loaded to coo_matrix) and use them as diagonal elements. Currently I do that in the following fashion: import numpy as np from scipy import sparse def computation(A): for i in range(A.shape[0]): diag_elems = np.ar...
[ "Here's what I came up with:\ndef computation(A):\n for i in range(A.shape[0]):\n idx_begin = A.indptr[i]\n idx_end = A.indptr[i+1]\n row_nnz = idx_end - idx_begin\n diag_elems = A.data[idx_begin:idx_end]\n diag_indices = A.indices[idx_begin:idx_end]\n ith_diag = sparse....
[ 3 ]
[]
[]
[ "numpy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0008339299_numpy_python_scipy_sparse_matrix.txt
Q: how to specify values in objects in django: is [] not equal to None? how can i specify or determine the values in my objects in python if it has this value [] or it has [<Booking: arab>], let us say that in my queryset, i filter a value that not exist in my objects. here is what i have done : this date_select has ...
how to specify values in objects in django: is [] not equal to None?
how can i specify or determine the values in my objects in python if it has this value [] or it has [<Booking: arab>], let us say that in my queryset, i filter a value that not exist in my objects. here is what i have done : this date_select has no data >>> x = Booking.objects.filter(date_select='2011-12-3') >>> print ...
[ "No, [] is not equal to None. [] is an empty list - a list with no content but that exists nonetheless and can come to have some elements. None is a value representing \"nothing\" - when you find the None value, it meas something like \"this variable has no relevant content\". Since empty lists can be relevant cont...
[ 3, 3, 2 ]
[]
[]
[ "django", "django_queryset", "if_statement", "python" ]
stackoverflow_0008365090_django_django_queryset_if_statement_python.txt
Q: How do a get a clean import namespace for a package in python? I'm sure this is trivial to do, but I can't figure it out. Directory structure: mylib/__init__.py mylib/MyClass.py init.py reads: import MyClass __all__ = [MyClass] MyClass.py: class MyClass(object): def __init__(self): pass I have to c...
How do a get a clean import namespace for a package in python?
I'm sure this is trivial to do, but I can't figure it out. Directory structure: mylib/__init__.py mylib/MyClass.py init.py reads: import MyClass __all__ = [MyClass] MyClass.py: class MyClass(object): def __init__(self): pass I have to create instances of MyClass using mylib.MyClass.MyClass(), when I wan...
[ "In your __init__.py, nstead of import MyClass try from MyClass import MyClass.\nThe former command imports the module's name into your namespace; the second imports a symbol from the module (in this case, the name of a class) into your namespace.\nAlso, __all__ should be a list of names, i.e., strings, not referen...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0008373813_python.txt
Q: Why this mocking script doesn't work (unittest, Mocker, python) I want to mock MyClass.toBeMockedMethod which is called in MyClass.mymethod using the following script. It runs without actually mocking it. Not sure why.... class Test_mytest(MockerTestCase): def mock_it_up(self, function, result=None, mmin=0, m...
Why this mocking script doesn't work (unittest, Mocker, python)
I want to mock MyClass.toBeMockedMethod which is called in MyClass.mymethod using the following script. It runs without actually mocking it. Not sure why.... class Test_mytest(MockerTestCase): def mock_it_up(self, function, result=None, mmin=0, mmax=None): function = self.m.mock() function(ARGS) ...
[ "As with this question what you're really trying to do is patch your instance of MyClass. If MyClass is a new-style class then you can do this:\nclass Test_mytest(MockerTestCase):\n\n def mock_it_up(self, function, result = None, mmin = 0, mmax = None):\n methodToMock = getattr(self.p, function)\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008347573_python.txt
Q: Python Elixir OneToMany and ManyToOne implementation: On Inserting new record with OneToMany relationship? How do you insert a record with one to many relationship in Python Elixir? See code below. from elixir import * class Product(Entity): using_options(shortnames=True) name = Field(Unicode) cat...
Python Elixir OneToMany and ManyToOne implementation: On Inserting new record with OneToMany relationship?
How do you insert a record with one to many relationship in Python Elixir? See code below. from elixir import * class Product(Entity): using_options(shortnames=True) name = Field(Unicode) category = ManyToOne('Category') brand = ManyToOne('Brand') barcode = Field(String) cost = Field(Float)...
[ "just figured it out. Its...\nasrock = Brand(name='Asrock')\nasus = Brand(name='Asus')\nmobo = Category(name='Motherboard')\nproc = Category(name='Processor') \nsession.commit()\n\np1 = Product(name='N98', cost=2100.50, price=2500.50, order_quantity=5, unit='unit', \n category=mobo, brand=asrock)\n\np2 = ...
[ 0 ]
[]
[]
[ "cpython", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0008373358_cpython_python_python_elixir_sqlalchemy.txt
Q: Send packet to webserver? I'm just getting into python, and I dont now how to send packets. So can anyone tell me how can I send packets to a webserver? I would also like to choose the size of the packet myself? I'm using python 2.7. A: You can use the httplib module, to easily create http requests. Or, if you w...
Send packet to webserver?
I'm just getting into python, and I dont now how to send packets. So can anyone tell me how can I send packets to a webserver? I would also like to choose the size of the packet myself? I'm using python 2.7.
[ "You can use the httplib module, to easily create http requests. Or, if you want to take a bare approach, you can use the socket module to manually create a TCP connection and send whatever packets you would like.\n", "from httplib import HTTPConnection\n...\nHTTPConnection.putheader(\"Content-Length\",\"512\")\n...
[ 0, 0 ]
[]
[]
[ "packets", "python" ]
stackoverflow_0008373395_packets_python.txt
Q: How can i check type of object? Possible Duplicate: Python - Determine the type of an object? I want 'complex' to be printed, but nothing happend, why? How to do this right? >>> c = (5+3j) >>> type(c) <type 'complex'> >>> if type(c) == 'complex': print 'complex' ... >>> A: You can use isinstance: if isinstan...
How can i check type of object?
Possible Duplicate: Python - Determine the type of an object? I want 'complex' to be printed, but nothing happend, why? How to do this right? >>> c = (5+3j) >>> type(c) <type 'complex'> >>> if type(c) == 'complex': print 'complex' ... >>>
[ "You can use isinstance:\nif isinstance(c, complex):\n\nFrom the documentation:\n\nReturn true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that typ...
[ 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008374599_python.txt
Q: How to make a linux service for python CGIHTTPServer? I run python CGIHTTPServer with (server.py) #!/usr/bin/env python import CGIHTTPServer def main(): server_address = ('', 8000) handler = CGIHTTPServer.CGIHTTPRequestHandler handler.cgi_directories = ['/cgi'] server = CGIHTTPServer.BaseHTTPServe...
How to make a linux service for python CGIHTTPServer?
I run python CGIHTTPServer with (server.py) #!/usr/bin/env python import CGIHTTPServer def main(): server_address = ('', 8000) handler = CGIHTTPServer.CGIHTTPRequestHandler handler.cgi_directories = ['/cgi'] server = CGIHTTPServer.BaseHTTPServer.HTTPServer(server_address, handler) try: serv...
[ "Use supervisor. It's much easier than rolling your own service management code. It includes monitoring, control, limited restarts, status logging, custom event notifications and an XML-RPC API for controlling supervisor programmatically.\nIt'll also start multiple instances of your web server — if that suits your ...
[ 1, 1 ]
[]
[]
[ "linux", "python", "service", "shell", "webserver" ]
stackoverflow_0008374523_linux_python_service_shell_webserver.txt
Q: Sine Tone that is constantly changing based on time related variables #Sine wave calculations by vegaseat. #The program will take in the current time that the computer has, and turn that into a #tone that is unique to that moment in time. It then makes an accompaning graph to #view for easier comparison of th...
Sine Tone that is constantly changing based on time related variables
#Sine wave calculations by vegaseat. #The program will take in the current time that the computer has, and turn that into a #tone that is unique to that moment in time. It then makes an accompaning graph to #view for easier comparison of the sound and an interesting view of the sound heard. from Tkinter import * ...
[ "Here is an approach you can take for a continuous varying frequency:\ndef gen_scale(samples_per_wave, samples_per_change):\n pi2 = 2 * math.pi\n rad = 0\n while (samples_per_wave > 1):\n for i in range(0, samples_per_change):\n yield math.sin(rad)\n rad = rad + pi2 / samples_p...
[ 1 ]
[]
[]
[ "audio", "live", "python", "time", "variables" ]
stackoverflow_0008372980_audio_live_python_time_variables.txt
Q: Installing MySQLdb package for Python on lion Possible Duplicate: mysql-python installation problems (on mac os x lion) I know this question is similar to other questions people have asked but I could't find my answer after searching so please bear with me. I installed Django fine, now I am installing MySQLdb pa...
Installing MySQLdb package for Python on lion
Possible Duplicate: mysql-python installation problems (on mac os x lion) I know this question is similar to other questions people have asked but I could't find my answer after searching so please bear with me. I installed Django fine, now I am installing MySQLdb package, but given the code below: !/usr/bin/env pyt...
[ "I think you need to install package called \"setuptools\". If you use macports you can execute (for python 2.7):\nsudo port install py27-setuptools\n\nin your terminal.\n" ]
[ 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0008374007_django_mysql_python.txt
Q: Google Apps Engine reading URL Query (python) Can someone please provide an example of how to read and print "sydney" and "NSW" from URL: http://xyz.appspot.com/main?city=sydney&state=NSW Using the def get (name, city, state) function? Thank you A: Its quite simple use def get(self): city = self.request.g...
Google Apps Engine reading URL Query (python)
Can someone please provide an example of how to read and print "sydney" and "NSW" from URL: http://xyz.appspot.com/main?city=sydney&state=NSW Using the def get (name, city, state) function? Thank you
[ "Its quite simple use \ndef get(self):\n city = self.request.get('city')\n state = self.request.get('state')\n\nThis is one the first things you get from \n\nGetting started with Google AppEngine\n\n", "Assuming you are using webapp2 under Python 2.7\ncheck out \nhttp://webapp-improved.appspot.com/guide/handler...
[ 5, 0 ]
[]
[]
[ "get", "google_app_engine", "python", "url" ]
stackoverflow_0008374045_get_google_app_engine_python_url.txt
Q: Efficient Python Daemon I was curious how you can run a python script in the background, repeating a task every 60 seconds. I know you can put something in the background using &, is that effeictive for this case? I was thinking of doing a loop, having it wait 60s and loading it again, but something feels off abou...
Efficient Python Daemon
I was curious how you can run a python script in the background, repeating a task every 60 seconds. I know you can put something in the background using &, is that effeictive for this case? I was thinking of doing a loop, having it wait 60s and loading it again, but something feels off about that.
[ "Rather than writing your own daemon, use python-daemon instead! python-daemon implements the well-behaved daemon specification of PEP 3143, \"Standard daemon process library\". \nI have included example code based on the accepted answer to this question, and even though the code looks almost identical, it has an i...
[ 110, 16, 8 ]
[]
[]
[ "daemon", "python" ]
stackoverflow_0004637420_daemon_python.txt
Q: Python progression path - From apprentice to guru I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with...
Python progression path - From apprentice to guru
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
[ "I thought the process of Python mastery went something like:\n\nDiscover list comprehensions\nDiscover generators\nIncorporate map, reduce, filter, iter, range, xrange often into your code\nDiscover Decorators\nWrite recursive functions, a lot\nDiscover itertools and functools\nRead Real World Haskell (read free o...
[ 471, 108, 92, 66, 59, 48, 41, 24, 23, 20, 12, 10, 10, 7, 6, 5, 3, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002573135_python.txt
Q: Working with pointers to struct I'm working with python and import dll that have the following function: int ReadMem(long Addr, long NumBytes, void* pData); and I'm using this function to read memory from my target. I want to create structure in python that is identical to structure defined in my target and then ...
Working with pointers to struct
I'm working with python and import dll that have the following function: int ReadMem(long Addr, long NumBytes, void* pData); and I'm using this function to read memory from my target. I want to create structure in python that is identical to structure defined in my target and then read it in python I.E if i used C , i...
[ "I came across an answer for similar question in this SO link\nand learn that i need to use the following code:\nmemory_ptr = pointer(memory)\nReadMem(0x20000000, 100, memory_ptr)\n\nNote : using byref(memory) probably works too\n" ]
[ 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0008169083_ctypes_python.txt
Q: An exercise from fundamentals of python Possible Duplicate: Fundamentals of Python Chapter 8 project 3 Hi I am a newbie programmer who just started to learn about python. I have recently posted this same question before and I have solved it but my answer is not exactly what the question is asking. I need help o...
An exercise from fundamentals of python
Possible Duplicate: Fundamentals of Python Chapter 8 project 3 Hi I am a newbie programmer who just started to learn about python. I have recently posted this same question before and I have solved it but my answer is not exactly what the question is asking. I need help on why I need to implement a new method even ...
[ "I think the question expects you to define ordering in the SavingsAccount class, that is, be able to determine whether an instance of SavingAccounts comes after or before another instance of SavingAccount. I don't want to write any spoiler here, but tell me if my hint is not enough ;).\nUPDATE\nAlso, a common sour...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008375209_python.txt
Q: Define function in Python as it defined in C I have function in C that reads byte by byte from a given buffer and returns the result of a mathematical formula. I need to write the same function in Python The buffer in C is struct and in python i used ctypes Structure class my prototype in c is int calc_formula(cha...
Define function in Python as it defined in C
I have function in C that reads byte by byte from a given buffer and returns the result of a mathematical formula. I need to write the same function in Python The buffer in C is struct and in python i used ctypes Structure class my prototype in c is int calc_formula(char *buff,int len) so calling the function in c is s...
[ "In c, try using the type c_char_p rather than char* (see the ctypes documentation). \nIn python the parameter (buff) will be a python string. Loop through it as follows:\ndef calc_formula(buff, len):\n sum = 0\n for curChar in buff:\n numericByteValue = ord(curChar)\n sum += numericByteValue\n ...
[ 1, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0008327307_ctypes_python.txt
Q: Reading multimedia playlist file in Python (libraries) Which libraries do you recommend for reading (parsing) multimedia playlist files?, would be useful if the library supports differents playlist formats, like M3U, WPL, and anothers. For Python i found this page http://wiki.python.org/moin/PythonInMusic, that po...
Reading multimedia playlist file in Python (libraries)
Which libraries do you recommend for reading (parsing) multimedia playlist files?, would be useful if the library supports differents playlist formats, like M3U, WPL, and anothers. For Python i found this page http://wiki.python.org/moin/PythonInMusic, that points to m3ute2 project, but it seems to be dead.
[ "Here is a library to parse playlists. The library relies heavily on correct mimetype of the playlist. There are several samples the library can be tested on.\nhttp://t11.mine.nu/playlists_analyser.tar.gz\n", "Like Misha said, they are plain text files so you can parse them pretty easily.\nHere's a quick python s...
[ 1, 0 ]
[]
[]
[ "audio", "libraries", "m3u", "playlist", "python" ]
stackoverflow_0004858436_audio_libraries_m3u_playlist_python.txt
Q: Updating notification using KNotify I've converted a gnome python script to use KDE notifications every time Spotify changes track. The code is below: #!/usr/bin/env python # -*- coding: utf-8 -*- """ Title: Spotify Notification Demo Author: Stuart Colville, http://muffinresearch.co.uk Modified to work with KDE: ...
Updating notification using KNotify
I've converted a gnome python script to use KDE notifications every time Spotify changes track. The code is below: #!/usr/bin/env python # -*- coding: utf-8 -*- """ Title: Spotify Notification Demo Author: Stuart Colville, http://muffinresearch.co.uk Modified to work with KDE: Steve Nixon License: BSD """ import dbu...
[ "Easier would be to simply set a timeout upon creation of the notification event:\nknotify.event(event, fromApp, contexts, title, text, pixmap, actions, timeout, winId)\n\ntimeout is an integer value representing milli-seconds.\n", "event method returns int. That's notification's Id. So, You can use it for closin...
[ 3, 1 ]
[]
[]
[ "kde_plasma", "notifications", "python" ]
stackoverflow_0004107743_kde_plasma_notifications_python.txt
Q: Implementing a WSGI Streaming Service: (how to detect client disconnects) So what I am doing is writing a WSGI streaming service which makes use of a Queue wrapped in an iterator to implement a multicast push. What follows is a simplified model of the service: # this is managed by another thread def processor_run...
Implementing a WSGI Streaming Service: (how to detect client disconnects)
So what I am doing is writing a WSGI streaming service which makes use of a Queue wrapped in an iterator to implement a multicast push. What follows is a simplified model of the service: # this is managed by another thread def processor_runner(): generator = SerialMessageGenerator() for message in generator: ...
[ "twisted calls .close() on the iterator if present when the request is finished or interrupted. You could do something like:\n# ...\nstart_response(status, response_headers)\nreturn ResponseIterator(iter(queue.get, None),\n on_finish=lambda: Processor.connections.remove(queue))\n\nwhere ResponseIterator could b...
[ 1, 0 ]
[]
[]
[ "python", "streaming", "twisted", "wsgi" ]
stackoverflow_0008371807_python_streaming_twisted_wsgi.txt
Q: plot histogram of datetime.time python / matplotlib I am trying to plot a histogram of datetime.time values. Where these values are discretized into five minute slices. The data looks like this, in a list: ['17:15:00', '18:20:00', '17:15:00', '13:10:00', '17:45:00', '18:20:00'] I would like to plot a histogram, o...
plot histogram of datetime.time python / matplotlib
I am trying to plot a histogram of datetime.time values. Where these values are discretized into five minute slices. The data looks like this, in a list: ['17:15:00', '18:20:00', '17:15:00', '13:10:00', '17:45:00', '18:20:00'] I would like to plot a histogram, or some form of distribution graph so that the number of o...
[ "I did what David Zwicker said and used seconds, and then changed the x axis. I will look at what Dave said about 'bins'. This works roughly and gives a bar per hour plot to start with. \ndef chart(occurance_list):\n hour_list = [t.hour for t in occurance_list]\n print hour_list\n numbers=[x for x in xrang...
[ 9 ]
[ "you have to convert the data in two variable and then you can use plotlab to plot in histograms.\n" ]
[ -10 ]
[ "datetime", "histogram", "matplotlib", "python" ]
stackoverflow_0008369584_datetime_histogram_matplotlib_python.txt
Q: Translate python regex to sed I'm a bit familiar with python's re module but I don't know much about sed. can anyone help me transforming the following python regex statement to the one that is usable for sed? re.sub(r'main\s*\(([a-zA-Z_0-9\s\,\*\[\]]*)\)([a-zA-Z_0-9\s\,\*\[\]]*){' , r'main (\1) \2 { \n signal(S...
Translate python regex to sed
I'm a bit familiar with python's re module but I don't know much about sed. can anyone help me transforming the following python regex statement to the one that is usable for sed? re.sub(r'main\s*\(([a-zA-Z_0-9\s\,\*\[\]]*)\)([a-zA-Z_0-9\s\,\*\[\]]*){' , r'main (\1) \2 { \n signal(SIGSEGV|SIGILL,leave);', string_buff...
[ "This might work for you:\n echo 'int main (int argc, char** argv) {' |\n sed '/\\<main\\>.*(.*).*{.*$/a\\ signal(SIGSEGV|SIGILL,leave);'\n int main (int argc, char** argv) {\n signal(SIGSEGV|SIGILL,leave);\n\nExplanation:\nThe regex can be shortened knowing that the .*(.*).*{.*$ will gobble everything up because ...
[ 1, 0, 0 ]
[]
[]
[ "awk", "python", "regex", "sed" ]
stackoverflow_0008375329_awk_python_regex_sed.txt
Q: Python Xlrd Result format i want to know, the result format of xlrd. See the code >>> sh.cell_value(rowx=2, colx=1) u'Adam Gilchrist xxxxxxxxxxxxxxxxxxxxx' Now when i try running a res.search >>> temp1=sh.cell_value(rowx=2, colx=1) >>> x=re.search("Adam",'temp1') >>> x.group() Traceback (most recent call last):...
Python Xlrd Result format
i want to know, the result format of xlrd. See the code >>> sh.cell_value(rowx=2, colx=1) u'Adam Gilchrist xxxxxxxxxxxxxxxxxxxxx' Now when i try running a res.search >>> temp1=sh.cell_value(rowx=2, colx=1) >>> x=re.search("Adam",'temp1') >>> x.group() Traceback (most recent call last): File "<pyshell#58>", line 1,...
[ "\nIt's a Unicode string\nCell_value returns the value of the cell. The type depends on the type of the cell.\nYes. You can use regular expressions on Unicode strings, but your code isn't right. \n\nYour code passes \"temp1\" to re.search as a string. It does not pass the variable temp1. You want:\n>>> x=re.searc...
[ 1, 1 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0008375379_python_xlrd.txt
Q: Watching for file changes within a directory Possible Duplicate: How do I watch a file for changes using Python? Detect File Change Without Polling I am trying to write an application which must perform an action when files are modified or added within a particular directory and its sub-directories. I imagine th...
Watching for file changes within a directory
Possible Duplicate: How do I watch a file for changes using Python? Detect File Change Without Polling I am trying to write an application which must perform an action when files are modified or added within a particular directory and its sub-directories. I imagine that an ideal solution would be to bind to some typ...
[ "As you have asked the question with Python Tag you may want to check pyinotify\n", "I think libnotify is what you're looking for. You'll find it available for pretty much every language and OS. Here it is for Python/Linux\n" ]
[ 4, 3 ]
[]
[]
[ "filesystems", "linux", "operating_system", "python", "windows" ]
stackoverflow_0008375588_filesystems_linux_operating_system_python_windows.txt
Q: self in python decorators I want a decorator that would add the decorated function to list, like this : class My_Class(object): def __init__(self): self.list=[] @decorator def my_function(self) print 'Hi' I expect my_function to be added to self.list, but I just can't write this decor...
self in python decorators
I want a decorator that would add the decorated function to list, like this : class My_Class(object): def __init__(self): self.list=[] @decorator def my_function(self) print 'Hi' I expect my_function to be added to self.list, but I just can't write this decorator. If I try to write it insi...
[ "You can't access self from the decorator, because the decorator is run at the time the function is defined, and at that time there are no instances of My_Class yet.\nIt's better to put the function list as a class attribute instead of an instance attribute. Then you can pass this list as a parameter to the decorat...
[ 13, 3, 2 ]
[]
[]
[ "decorator", "python", "self" ]
stackoverflow_0008375862_decorator_python_self.txt
Q: How can I import the sqlite3 module into Python 2.4? The sqlite3 module is included in Python version 2.5+. However, I am stuck with version 2.4. I uploaded the sqlite3 module files, added the directory to sys.path, but I get the following error when I try to import it: Traceback (most recent call last): File "<...
How can I import the sqlite3 module into Python 2.4?
The sqlite3 module is included in Python version 2.5+. However, I am stuck with version 2.4. I uploaded the sqlite3 module files, added the directory to sys.path, but I get the following error when I try to import it: Traceback (most recent call last): File "<stdin>", line 1, in ? File "sqlite3/__init__.py", line 2...
[ "I had same problem with CentOS and python 2.4\nMy solution:\nyum install python-sqlite2\n\nand try following python code\ntry:\n import sqlite3\nexcept:\n from pysqlite2 import dbapi2 as sqlite3\n\n", "Did you install it? That often works better than messing with sys.path. \npython setup.py install\n\nIf...
[ 13, 1, 1 ]
[ "You must ensure your sqlite, sqlite-devel, python-sqlite are installed correctly first and then recompile Python.\n" ]
[ -2 ]
[ "python", "sqlite" ]
stackoverflow_0000789030_python_sqlite.txt
Q: Can't apply template in django I'm following the Django tutorial. I've been trying to change the default template, but for some reason, changes in my admin/base_site.html do not reflect on the site, even though the path in settings.py is correct. here's my settings.py: # Django settings for django_test project. D...
Can't apply template in django
I'm following the Django tutorial. I've been trying to change the default template, but for some reason, changes in my admin/base_site.html do not reflect on the site, even though the path in settings.py is correct. here's my settings.py: # Django settings for django_test project. DEBUG = True TEMPLATE_DEBUG = DEBUG ...
[ "You forgot a comma after '/home/mhh91/django_test/polls/admin' and...\nYou need to add /home/mhh91/django_test/templates', to your template list, and move admin/base_site.html to /home/mhh91/django_test/templates/ as per the documentation:\n\nIn order to override one or more of them, first create an admin\n direc...
[ 3, 1 ]
[]
[]
[ "django", "django_admin", "django_templates", "python" ]
stackoverflow_0008375973_django_django_admin_django_templates_python.txt
Q: Doxygen python linking to functions I'm using Doxygen to document my python module and I'm trying to get it to link to a function in-text. I can get it to link to the function's namespace ok but not to the function itself. E.g. ModuleName::Namespace works but ModuleName::Namespace::getSomething() doesn't. How do I...
Doxygen python linking to functions
I'm using Doxygen to document my python module and I'm trying to get it to link to a function in-text. I can get it to link to the function's namespace ok but not to the function itself. E.g. ModuleName::Namespace works but ModuleName::Namespace::getSomething() doesn't. How do I get these links to work?
[ "Doxygen automatically wraps functions in a namespace per module. You have to document this module in order to make the documentation visible and linkable (or use EXTRACT_ALL = YES).\nHere is an example func.py\n## @package func\n# Module docs\n\n## A function\n#\n# More documentation.\ndef foo():\n print \"He...
[ 5 ]
[]
[]
[ "documentation", "doxygen", "module", "namespaces", "python" ]
stackoverflow_0008375631_documentation_doxygen_module_namespaces_python.txt
Q: Python package to find pre-defined keywords/tags in a file / url / string Are there any python packages that can take a list of keywords / tags and match them up to a given string / file / url ? Specifically using stemming and/or some other synonym way of matching. i.e. my pre saved keywords: Ski, Bike, Climb my t...
Python package to find pre-defined keywords/tags in a file / url / string
Are there any python packages that can take a list of keywords / tags and match them up to a given string / file / url ? Specifically using stemming and/or some other synonym way of matching. i.e. my pre saved keywords: Ski, Bike, Climb my text: Skiing in the mountains is great Should get tagged with Ski Skiing and mou...
[ "See Thesaurus (you can also try different modules, such as synonym module).\nAlso you can test sentences for containing specific strings using in:\n>>> 'Ski' in 'Skiing in the mountains is great'\nTrue\n>>> 'Bike' in 'Skiing in the mountains is great'\nFalse\n\n", "I don't know any package to do that but actuall...
[ 0, 0 ]
[]
[]
[ "keyword", "python", "stemming" ]
stackoverflow_0008374902_keyword_python_stemming.txt
Q: initializing Arrays in python I am new to python and am struggling to figure out how to initialize an array of unicode chars to a certain size. I want to use arrays not lists as I desire O(1) random access and O(1) amortized cost for insertion. So far I have this: from arrays import * a = array('u') but obviously...
initializing Arrays in python
I am new to python and am struggling to figure out how to initialize an array of unicode chars to a certain size. I want to use arrays not lists as I desire O(1) random access and O(1) amortized cost for insertion. So far I have this: from arrays import * a = array('u') but obviously this is a zero length array. Thank...
[ "This creates a new array initialized to \"unicode string\".\nfrom array import *\na = array('u', u\"unicode string\")\n\nIf you only want it initialized to a certain size, you can do this:\na = array('u', u'\\0' * size)\n\nThis will initialize a unicode character array with size size initialized to null characters...
[ 3 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0008376597_arrays_python.txt
Q: appSpot does not find my public posts Testing several plus feeds - Made my own app from this post which gives list index out of range and then found plu.sr but nothing is showing as if I never posted anything public. Please help me find out why my public GPlus posts are not found here plu.sr nor here: mhpgplusfee...
appSpot does not find my public posts
Testing several plus feeds - Made my own app from this post which gives list index out of range and then found plu.sr but nothing is showing as if I never posted anything public. Please help me find out why my public GPlus posts are not found here plu.sr nor here: mhpgplusfeed (the latter running the code from git/plu...
[ "It probably doesn't work because it uses an unofficial google+ api that they must have secured at some point. The object that's supposed to contain the feed contains some gibberish and in effect you get index out of range caught here. This is the line that causes it. There's an official API available.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "google_plus", "python" ]
stackoverflow_0008376336_google_app_engine_google_plus_python.txt
Q: What is the standard pattern for releasing a python module I am new to python and have been playing around with it for a while. I have written two python modules: gapbuffer and gapbuffertests. The question I have is - to release this publically for use do I just release the gapbuffer.py module file standalone or i...
What is the standard pattern for releasing a python module
I am new to python and have been playing around with it for a while. I have written two python modules: gapbuffer and gapbuffertests. The question I have is - to release this publically for use do I just release the gapbuffer.py module file standalone or is there a Java .jar equivalent? Thanks, Aly
[ "Setuptools is the standard packaging solution for Python. With setuptools, you can create eggs, which are the near-equivalent of jars. If your package is open source, you can also have it listed on PyPI (setuptools includes support for that) so that it can be installed with a command like pip install gapbuffer.\n"...
[ 4, 2 ]
[]
[]
[ "packaging", "python" ]
stackoverflow_0008375826_packaging_python.txt
Q: connect telnet with python I tried to connect bbs with python's library "telnetlib", try to make a robot to answer the message. While I answered the message,the robot return more than 1 message.These are my code. # -*- coding: cp950 -*- import telnetlib,random #f= open("ans.txt","r") ans = [b"oao", b"xd"] '''while...
connect telnet with python
I tried to connect bbs with python's library "telnetlib", try to make a robot to answer the message. While I answered the message,the robot return more than 1 message.These are my code. # -*- coding: cp950 -*- import telnetlib,random #f= open("ans.txt","r") ans = [b"oao", b"xd"] '''while True: line = f.readline() if li...
[ "First, I have absolutely no experience with telnet.\nLooking at the Python documentation on telnetlib I can see some differences between your code and the example at the bottom of the docs page. The major difference is they wait for a prompt to log-in or provide a password. Even if your read_very_eager should do...
[ 0 ]
[]
[]
[ "python", "sockets", "telnet", "telnetlib" ]
stackoverflow_0007763199_python_sockets_telnet_telnetlib.txt