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: In Django, is there a built in filter which can mark these as safe? > <strong> HTML tags, and much more (these 3 are just examples) Is there a filter that I actually render these in Django template, but keep tags escaped. A: No, there isn't - if you mark something as safe, nothing will be escaped. If ...
In Django, is there a built in filter which can mark these as safe?
> <strong> HTML tags, and much more (these 3 are just examples) Is there a filter that I actually render these in Django template, but keep tags escaped.
[ "No, there isn't - if you mark something as safe, nothing will be escaped. If it's unsafe, everything will be. There isn't really way to say this content is varying degrees of safe - so if you want this, you'll have to write it yourself.\n", "This should help but not bundled with Django:\nhttp://djangosnippets.or...
[ 1, 0 ]
[]
[]
[ "django", "django_templates", "filter", "python", "templates" ]
stackoverflow_0004494842_django_django_templates_filter_python_templates.txt
Q: User input delay in Python I am starting from the VERY basics and I'm trying to create a simple madlibs-esque game where a user can import a verb, noun etc and the program will print a paragraph using these inputs, so far I have: a = raw_input("Enter a verb") input("\n\n") b = raw_input("Enter a person") input("\n...
User input delay in Python
I am starting from the VERY basics and I'm trying to create a simple madlibs-esque game where a user can import a verb, noun etc and the program will print a paragraph using these inputs, so far I have: a = raw_input("Enter a verb") input("\n\n") b = raw_input("Enter a person") input("\n\n") c = raw_input("Enter a plac...
[ "If you do only : \na = raw_input(\"Enter a verb : \")\nb = raw_input(\"Enter a person : \")\nc = raw_input(\"Enter a place : \")\n\nit should work.\nAs explained in python documentation, input() is only a sort of shortcut for eval(raw_input(prompt)), you don't need it in your case.\n", "I wouldn't think you woul...
[ 1, 0 ]
[]
[]
[ "delay", "input", "python" ]
stackoverflow_0007933368_delay_input_python.txt
Q: How to write to beginning and end of every line in a text file? I'm currently looking for a way to write to the beginning and end of every line of a text file in Python. For example, Current TXT document: Jimmy Was Here Write the 1st VALUE to the beginning of every line 111Jimmy 111Was 111Here Write the 2nd VALU...
How to write to beginning and end of every line in a text file?
I'm currently looking for a way to write to the beginning and end of every line of a text file in Python. For example, Current TXT document: Jimmy Was Here Write the 1st VALUE to the beginning of every line 111Jimmy 111Was 111Here Write the 2nd VALUE to the end of every line 111Jimmy222 111Was222 111Here222 Can't se...
[ "prefix = '111'\nsuffix = '222'\n\nwith open('source.txt', 'r') as src:\n with open('dest.txt', 'w') as dest:\n for line in src:\n dest.write('%s%s%s\\n' % (prefix, line.rstrip('\\n'), suffix))\n\n", "You can make changes to the file without opening multiple files by using fileinput with inplac...
[ 12, 5, 0 ]
[ "f1o = open(\"input.txt\", \"r\")\nf2o = open(\"output.txt\", \"w\")\n\nfor line in f1o:\n f2o.write(\"111%s222\\n\" % line.replace(\"\\n\"))\n\nf1o.close()\nf2o.close()\n\n" ]
[ -1 ]
[ "file_io", "python", "text_files" ]
stackoverflow_0007933472_file_io_python_text_files.txt
Q: How to get the the User ID from an email in GAE I'm working on a small app that will allow the user to login to the App, allow the app OAuth access to a service, then interact with the service using the app via email. I've successfully enabled Oauth using gdata and gdata.gauth and can store/recover the Oauth token...
How to get the the User ID from an email in GAE
I'm working on a small app that will allow the user to login to the App, allow the app OAuth access to a service, then interact with the service using the app via email. I've successfully enabled Oauth using gdata and gdata.gauth and can store/recover the Oauth token and user_id easily when the user is logged in. Howev...
[ "Reading http://code.google.com/appengine/docs/python/users/userclass.html#User\nUnder the method call user_id, it is noted that if you create the User object yourself, the user_id field will return None.\n" ]
[ 1 ]
[]
[]
[ "gdata", "gdata_api", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007933515_gdata_gdata_api_google_app_engine_google_cloud_datastore_python.txt
Q: What are the advantages of MongoDB over MySQL and PostgreSQL? i've been thinking to use MongoDB for my next project (python), but for now, i don't understand which are the advantages of use NoSQL MongoDB against SQL. Can you give some ideas or reasons of why to use NoSQL MongoDB? Thanks in advance A: In this pre...
What are the advantages of MongoDB over MySQL and PostgreSQL?
i've been thinking to use MongoDB for my next project (python), but for now, i don't understand which are the advantages of use NoSQL MongoDB against SQL. Can you give some ideas or reasons of why to use NoSQL MongoDB? Thanks in advance
[ "In this presentation there are some great points about using Mongodb link\n", "Since MongoDB is a document oriented database like RavenDB maybe the following can give you an idea:\n\nThe schema-less nature makes it ideal to store dynamic data, such as\n CMS and CRM entities, which the end user can usually custo...
[ 5, 0 ]
[]
[]
[ "mongodb", "nosql", "python", "sql" ]
stackoverflow_0007931971_mongodb_nosql_python_sql.txt
Q: Struggling understanding a part in an exercise Link to exercise: http://books.google.no/books?id=Hi1KVomG148C&lpg=PA231&ots=tyhy6959R7&dq=exercise%205.13%20python%20scientific&hl=no&pg=PA231#v=onepage&q&f=false Exercise 5.13, bottom of that page: 231. What I actually is struggeling with is in that notation not si...
Struggling understanding a part in an exercise
Link to exercise: http://books.google.no/books?id=Hi1KVomG148C&lpg=PA231&ots=tyhy6959R7&dq=exercise%205.13%20python%20scientific&hl=no&pg=PA231#v=onepage&q&f=false Exercise 5.13, bottom of that page: 231. What I actually is struggeling with is in that notation not sigma, but that other one. That one who multiplies. Th...
[ "I believe you're looking at a typo in that book. xj should be xi. See Lagrange Interpolating Polynomial for reference.\nEDIT: I found the errata list (see Item #5) for the second edition of this book. It is indeed a typo.\n" ]
[ 6 ]
[]
[]
[ "computer_science", "python" ]
stackoverflow_0007933674_computer_science_python.txt
Q: Loop through django list in javascript I need to loop through my django list that I have passed to the template. I have this code in my django view: if plan: investments = Investment.objects.all().filter(plan = plan).order_by('maturity_date').filter(maturity_date__gte = now) for i in investments: f...
Loop through django list in javascript
I need to loop through my django list that I have passed to the template. I have this code in my django view: if plan: investments = Investment.objects.all().filter(plan = plan).order_by('maturity_date').filter(maturity_date__gte = now) for i in investments: financial_institution = i.financial_instituti...
[ "I don't know what you intend to do with the fi_list variable that you add to the context. If you plan to list the institutions and their limits in a systematic way, such as a table, then it should be simple enough to retrieve the amount data in much the same way as you retrieved the selected financial institution'...
[ 1 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0007932295_django_javascript_jquery_python.txt
Q: How to reference the child of a many to one relationship in SQLAlchemy? Using the example off the documentation, I have the following code. When I try to append I get the error: AttributeError: 'NoneType' object has no attribute 'append' Obviously even without using append the parent.child is of NoneType. I d...
How to reference the child of a many to one relationship in SQLAlchemy?
Using the example off the documentation, I have the following code. When I try to append I get the error: AttributeError: 'NoneType' object has no attribute 'append' Obviously even without using append the parent.child is of NoneType. I don't know how to work with this relationship. Base = declarative_base() clas...
[ "You set up the many to one relationship so that a parent can have one child and a child can have many parents. If that's how you intended, you can just set the child like so:\nparent.child = child\n\nA child, however, could add a parent like so:\nchild.parents.append(parent)\n\nIf this isn't how you intended, you ...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007933166_python_sqlalchemy.txt
Q: What is wrong with this end? I was going through a tutorial about defining functions with an example on creating new lines, and the code you had to write was this: def new_line(): print def three_lines(): new_line() new_line() new_line() def nine_lines(): three_lines() three_lines() t...
What is wrong with this end?
I was going through a tutorial about defining functions with an example on creating new lines, and the code you had to write was this: def new_line(): print def three_lines(): new_line() new_line() new_line() def nine_lines(): three_lines() three_lines() three_lines() print "hello world" ...
[ "print nine_lines()\n\nYou are printing the result of calling the nine_lines() function. Since that function does not explicitly return a value (using the return statement, if you haven't seen that yet then you will soon), Python returns the special value None.\nTo fix this, change that line to simply\nnine_lines()...
[ 6, 1, 1 ]
[]
[]
[ "delay", "input", "python" ]
stackoverflow_0007934181_delay_input_python.txt
Q: How to write an ElementTree with UTF-8 stripped out I have a giant (50MB) XML ElementTree that I've generated and somewhere in the raw data were some UTF-8 letters that didn't get stripped out. ElementTree.write and .tostring seem to choke on unicode even though there's an "encoding='UTF-8'" option in tostring. Th...
How to write an ElementTree with UTF-8 stripped out
I have a giant (50MB) XML ElementTree that I've generated and somewhere in the raw data were some UTF-8 letters that didn't get stripped out. ElementTree.write and .tostring seem to choke on unicode even though there's an "encoding='UTF-8'" option in tostring. The docs are rather limited and I'm not even sure that tost...
[ "You need to explain \"somewhere in the raw data were some UTF-8 letters that didn't get stripped out\" -- like what is a \"UTF-8 letter\", and why you want to strip them out.\nIt would also help if you explained what \"ElementTree.write and .tostring seem to choke on unicode\" means. Please edit your question to s...
[ 2, 0, 0, 0 ]
[]
[]
[ "elementtree", "python", "tostring", "unicode", "utf_8" ]
stackoverflow_0007923090_elementtree_python_tostring_unicode_utf_8.txt
Q: sort by count in json I'm using tastypie to create json from my django models however I'm running into a problem that I think should have a simple fix. I have an object Blogs wich has Comment object children. I want to be able to do something like this with my json: /api/v1/blogs/?order_by=comment_count But I c...
sort by count in json
I'm using tastypie to create json from my django models however I'm running into a problem that I think should have a simple fix. I have an object Blogs wich has Comment object children. I want to be able to do something like this with my json: /api/v1/blogs/?order_by=comment_count But I can't figure out how to sort...
[ "If I understood correctly this should help:\nBlog.objects.annotate(comment_count=Count('comments')).order_by('comment_count')\n\n", "You might be able to do it with extra like something like:\nBlog.objects.extra(\n select={\n 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = bl...
[ 2, 1 ]
[]
[]
[ "django", "json", "python", "tastypie" ]
stackoverflow_0007932224_django_json_python_tastypie.txt
Q: Match "byte spans" to a text document, Python I'm working with an annotated corpus that contains two sets of .txt files. The first set contains the documents that were annotated (i.e, articles, blog-posts,etc.) and the second set contains the actual annotations. The way to match the annotation to the text annotat...
Match "byte spans" to a text document, Python
I'm working with an annotated corpus that contains two sets of .txt files. The first set contains the documents that were annotated (i.e, articles, blog-posts,etc.) and the second set contains the actual annotations. The way to match the annotation to the text annotated is via "byte spans." From the readme file: "Th...
[ "\"This means that the start of this annotation is \nbyte 730 in the file docs/temp_fbis/20.20.10-3414, and byte 740 \nis the character after the last character of the annotation.\n\n blah, blah, blah, example annotation, blah, blah, blah\n | |\n start byte...
[ 0, 0 ]
[]
[]
[ "nlp", "python", "tagged_corpus" ]
stackoverflow_0007934470_nlp_python_tagged_corpus.txt
Q: Finding the label preceding the longest line in a file I have a file that follows a format of _line 1 this is a string on a line _line 2 this is another string _line 3 short line I am trying to write some Python code to get me the _line X label of the string below it that has the longest string length. Can you he...
Finding the label preceding the longest line in a file
I have a file that follows a format of _line 1 this is a string on a line _line 2 this is another string _line 3 short line I am trying to write some Python code to get me the _line X label of the string below it that has the longest string length. Can you help me fix my code please? Here is what I have so far. f = op...
[ "If all you wanted were the longest line in the file (like the question title says), then this one is shockingly simple in modern Python:\n>>> max(open('test.txt'), key=len)\n\n", "To fetch the label of the longest line, build a mapping of labels to line-lengths\nIn your sample dataset, it looks like labels start...
[ 8, 8, 3, 2, 2, 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007846000_python_string.txt
Q: Will multiprocessing be a good solution for this operation? while True: Number = len(SomeList) OtherList = array([None]*Number) for i in xrange(Number): OtherList[i] = (Numpy Array Calculation only using i_th element of arrays, Array_1, Array_2, and Array_3.) 'Number' number of elements in ...
Will multiprocessing be a good solution for this operation?
while True: Number = len(SomeList) OtherList = array([None]*Number) for i in xrange(Number): OtherList[i] = (Numpy Array Calculation only using i_th element of arrays, Array_1, Array_2, and Array_3.) 'Number' number of elements in OtherList and other arrays can be calculated seperately. However,...
[ "It is possible to use numpy arrays with multiprocessing but you shouldn't do it yet.\nRead A beginners guide to using Python for performance computing and its Cython version: Speeding up Python (NumPy, Cython, and Weave).\nWithout knowing what are specific calculations or sizes of the arrays here're generic guidel...
[ 4, 0 ]
[]
[]
[ "multiprocessing", "numpy", "python" ]
stackoverflow_0007933555_multiprocessing_numpy_python.txt
Q: Python nested for loop Vs generator for repeatedly iterating over a list provided by a function The problem is quite simple, I have a method that returns a list. I want to iterate over every item in this list, and once finished, call the method to receive a new list, and repeat. At the moment, my code looks someth...
Python nested for loop Vs generator for repeatedly iterating over a list provided by a function
The problem is quite simple, I have a method that returns a list. I want to iterate over every item in this list, and once finished, call the method to receive a new list, and repeat. At the moment, my code looks something like: generator = iter([]) while Condition: try: item = next(generator) except St...
[ "I'd suggest you use some iterators\nitems = itertools.chain.from_iterable( iter(list_returning_method, None) )\n\nfor item in items:\n # do something with item\n print item\n\n if not Condition:\n break\n\niter(callable, sentinel) returns an iterator which produces the result of callable() until it ...
[ 2, 1 ]
[]
[]
[ "for_loop", "iterator", "python" ]
stackoverflow_0007934854_for_loop_iterator_python.txt
Q: get amount of used resources in app engine I am thinking about implementing resource throttling in my application in google app engine. My idea is checking whether I am running out of resources (for example, bandwidth) and disabling part of the website, using the final part of the available daily traffic to inform...
get amount of used resources in app engine
I am thinking about implementing resource throttling in my application in google app engine. My idea is checking whether I am running out of resources (for example, bandwidth) and disabling part of the website, using the final part of the available daily traffic to inform the user that the site is running in a "resourc...
[ "Unfortunately this is not possible, there is no API that you can use for this.\nLooking at the App Engine roadmap there is no such feature coming along any time soon.\nThe only thing i can recommend is you sign up for billing and recieve the 50$ free quota, it's here till 31 october. You can enable billing and dis...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007931936_google_app_engine_python.txt
Q: Python Workflow Design Pattern I'm working on a piece of software design, and I'm stuck between not having any idea what I'm doing, and feeling like I'm reinventing the wheel. My situation is the following: I am designing a scientific utility with an interactive UI. User input should trigger visual feedback (duh),...
Python Workflow Design Pattern
I'm working on a piece of software design, and I'm stuck between not having any idea what I'm doing, and feeling like I'm reinventing the wheel. My situation is the following: I am designing a scientific utility with an interactive UI. User input should trigger visual feedback (duh), some of it directly, i.e. editing a...
[ "I believe that you are both, right and wrong, in doubt of re-inventing the wheel. Maybe different levels of thinking gives you a hint here.\nHow to eat an elephant?\nLevel A: software design\nAt that level, you would want to stick to the best practice that no long operations are done in the UI (and UI thread). You...
[ 19 ]
[]
[]
[ "python", "workflow" ]
stackoverflow_0007902647_python_workflow.txt
Q: name error in python and also what is indentation error in python? movies=["the holy grail",1975,"terry jones & Terry gilliam",91, ["gilliam chapman",["michael palin","john cleese","terry gilliam","eric idle","terry jones"]]] for each_item in movies: if isinstance(each_item , list): for nested_item in ea...
name error in python and also what is indentation error in python?
movies=["the holy grail",1975,"terry jones & Terry gilliam",91, ["gilliam chapman",["michael palin","john cleese","terry gilliam","eric idle","terry jones"]]] for each_item in movies: if isinstance(each_item , list): for nested_item in each_item: if isinstance(nested_item , list): ...
[ "You're going to have to format your example better, and you'll likely solve your problem in the process. Because else: can follow both if and 'for`, that code can be interprett]ed differently depending on how it's indented.\nfor each_item in movies: \n if isinstance(each_item , list): \n for nested_item ...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0007934643_python_python_idle.txt
Q: Creating Python timer for Nokia 5800 I've been asked to write a microsecond timer for nokia 5800. I have googled it but still haven't made any headway. Firstly, i don't know jack about programming nokia devices and mobiles in general. Please could someone point me in the right directions. thank you in advance A:...
Creating Python timer for Nokia 5800
I've been asked to write a microsecond timer for nokia 5800. I have googled it but still haven't made any headway. Firstly, i don't know jack about programming nokia devices and mobiles in general. Please could someone point me in the right directions. thank you in advance
[ "why you have been asked to do the job if you know nothing about it?\nread this\n" ]
[ 0 ]
[]
[]
[ "mobile", "nokia", "python" ]
stackoverflow_0007935072_mobile_nokia_python.txt
Q: Define a function to repeat a word I'm trying to do a task from a tutorial which is to define a function that will repeat an inputted word an inputted number of times, so far I have: s = raw_input("Enter a word:") n = input("Enter a number:") def repeat_this(s, n): print s * n However s and n aren't defined ...
Define a function to repeat a word
I'm trying to do a task from a tutorial which is to define a function that will repeat an inputted word an inputted number of times, so far I have: s = raw_input("Enter a word:") n = input("Enter a number:") def repeat_this(s, n): print s * n However s and n aren't defined locally in repeat_this, but I couldn't g...
[ "You're not calling the function. Add this to the end of the script:\nrepeat_this(s, n)\n\nAlso, your inputs should both be raw_input() (coerce the number to an integer using int() rather than dangerously allowing Python to parse it) and should probably go below the function definition (it'll work either way, but i...
[ 2, 0 ]
[]
[]
[ "function", "python", "repeat" ]
stackoverflow_0007934455_function_python_repeat.txt
Q: Is there any patch tools that work well with mercurial, when patch-based workflows fail causing .rej hunks in your repo I am looking for a better patch tool than the ones built into Mercurial, or a visual tool to help me edit patches so that they will get accepted into Mercurial or Gnu patch. The mercurial wiki ha...
Is there any patch tools that work well with mercurial, when patch-based workflows fail causing .rej hunks in your repo
I am looking for a better patch tool than the ones built into Mercurial, or a visual tool to help me edit patches so that they will get accepted into Mercurial or Gnu patch. The mercurial wiki has a topic HandlingRejects which shows how simple it is to have Patching fail. I am looking to implement a mercurial based wo...
[ "Emacs is quite capable of handling .rej files.\nHowever, if at all practical, I try to use hg pull --rebase whenever possible. Often I find myself wanting to rebase some lineage of patches onto another changeset that I've already pulled. In these cases I just strip the changeset and pull it in again from .hg/strip...
[ 2 ]
[]
[]
[ "mercurial", "mercurial_queue", "patch", "python" ]
stackoverflow_0007933032_mercurial_mercurial_queue_patch_python.txt
Q: undefined symbol: vmldExp2 I am using f2py and Intel fortran compiler to wrap some fortran code which calls some math library like dexp and dpow. The compilation went smoothly without reporting any err, but when I attempted to run the wrapped python modules, the error prompts up: ImportError: /usr/lib/python2.7/...
undefined symbol: vmldExp2
I am using f2py and Intel fortran compiler to wrap some fortran code which calls some math library like dexp and dpow. The compilation went smoothly without reporting any err, but when I attempted to run the wrapped python modules, the error prompts up: ImportError: /usr/lib/python2.7/site-packages/foo/foo.so: undefi...
[ "It seems that the intel svml lib has been changed quite a bit, I tried various ways and option/flags but ended up not solving the problem at all, but after I upgraded intel fortran compiler from 9.1 to 12.0, it disappeared and now everything works like a charm.\n" ]
[ 0 ]
[]
[]
[ "f2py", "fortran", "fortran90", "gfortran", "python" ]
stackoverflow_0007932623_f2py_fortran_fortran90_gfortran_python.txt
Q: Function in Python to PHP Does anyone know how to convert this function from Python to PHP? I have been around it but there is things in Python code I can't figure out. This function is used in the follow context: http://www.dmcloud.net/doc/api/general.html#authentication def normalize(input=None): output = '' if...
Function in Python to PHP
Does anyone know how to convert this function from Python to PHP? I have been around it but there is things in Python code I can't figure out. This function is used in the follow context: http://www.dmcloud.net/doc/api/general.html#authentication def normalize(input=None): output = '' if type(input) in (list, tuple): ...
[ "php has no distinction between dictionaries and tuples/lists, so:\nfunction normalize($input=null) {\n if (! is_array($input)) {\n return strval($input);\n }\n\n $res = '';\n $keys = array_keys($input);\n sort($keys);\n foreach ($keys as $k) {\n if (!is_int($k)) $res .= $k;\n $res .= normalize($v);\...
[ 2 ]
[]
[]
[ "normalize", "php", "python" ]
stackoverflow_0007935261_normalize_php_python.txt
Q: Python newbie array - list conversion I have an array like this type ["1" "2" "3"], how can I change this into a list [1, 2, 3] Could some one please help me regarding this? A: Here's one way: myList = [ "1", "2", "3" ] myList = [ int(i) for i in myList ] A: Both ["1", "2", "3"] and [1, 2, 3] are lists. The fo...
Python newbie array - list conversion
I have an array like this type ["1" "2" "3"], how can I change this into a list [1, 2, 3] Could some one please help me regarding this?
[ "Here's one way:\nmyList = [ \"1\", \"2\", \"3\" ]\nmyList = [ int(i) for i in myList ]\n\n", "Both [\"1\", \"2\", \"3\"] and [1, 2, 3] are lists. The former is just a list of strings, whereas the latter is a list of integers. Call int on every element to convert it to an integer, like this:\nstr_list = [\"1\", \...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007935741_python.txt
Q: Python Backup file script problems I've been working on a backup script below, copying files from one server to another, with several requirements. The code is below. Any help? And I have a sample test input. import arcpy # Import arcpy module from arcpy import env ...
Python Backup file script problems
I've been working on a backup script below, copying files from one server to another, with several requirements. The code is below. Any help? And I have a sample test input. import arcpy # Import arcpy module from arcpy import env # Import env module fro...
[ "One prime mistake is giving a glob argument to shutil.copyfile.\nshutil.copyfile(\"D:\\backup\\*\", \"D:\\data\\*\")\n\nshould read\nimport glob\nfor fn in glob.glob(\"D:\\\\backup\\\\*\"):\n shutil.copyfile(fn, \"D:\\\\data\")\n\nSimilarly, the following line is strange:\nhdr = logging.FileHandler(\"G:\\data\\*....
[ 2 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0007935784_python_python_2.6.txt
Q: formatted Input from file in Python i'm trying to read a file into my python program and apply tokenizer on it to split the text into a set of sentences. However, in my output i'm getting the '/n' character that i'd like to avoid in the output, as it might hinder my further processes on the sentences. I read the ...
formatted Input from file in Python
i'm trying to read a file into my python program and apply tokenizer on it to split the text into a set of sentences. However, in my output i'm getting the '/n' character that i'd like to avoid in the output, as it might hinder my further processes on the sentences. I read the input using the read() command. Also trie...
[ "If you want to remove the newlines entirely:\nall_sents = file_sent.read().replace('\\n', '')\n\nIf you want to replace them with spaces:\nall_sents = file_sent.read().replace('\\n', ' ')\n\nObviously you could replace them with something else if you wanted.\n" ]
[ 2 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0007935686_nltk_python.txt
Q: Writing to a new directory in Python without changing directory Currently, I have the following code... file_name = content.split('=')[1].replace('"', '') #file, gotten previously fileName = "/" + self.feed + "/" + self.address + "/" + file_name #add folders output = open(file_name, 'wb') output.write(url.read())...
Writing to a new directory in Python without changing directory
Currently, I have the following code... file_name = content.split('=')[1].replace('"', '') #file, gotten previously fileName = "/" + self.feed + "/" + self.address + "/" + file_name #add folders output = open(file_name, 'wb') output.write(url.read()) output.close() My goal is to have python write the file (under file...
[ "First, I'm not 100% confident I understand the question, so let me state my assumption:\n1) You want to write to a file in a directory that doesn't exist yet.\n2) The path is relative (to the current directory).\n3) You don't want to change the current directory.\nSo, given that:\nCheck out these two functions: os...
[ 12, 10, 1 ]
[]
[]
[ "directory", "file", "io", "python", "rss" ]
stackoverflow_0007935972_directory_file_io_python_rss.txt
Q: Python: find out if an element in a list has a specific string I am looking for a specific string in a list; this string is part of a longer string. Basically i loop trough a text file and add each string in a different element of a list. Now my objective is to scan the whole list to find out if any of the element...
Python: find out if an element in a list has a specific string
I am looking for a specific string in a list; this string is part of a longer string. Basically i loop trough a text file and add each string in a different element of a list. Now my objective is to scan the whole list to find out if any of the elements string contain a specific string. example of the source file: asfa...
[ "You want it to be:\nif \"mystring\" in item:\n\n", "A concise (and usually faster) way to do this:\nif any(\"my string\" in item for item in work_list):\n has_string = True\n print \"found mystring\"\n\nBut really what you've done is implement grep.\n", "Method 1\n[s for s in stringList if (\"my string\"...
[ 5, 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0007936125_python.txt
Q: SMS text solution With google app engine, is there a way to send a text message from a cell phone, to the app(written in python) and have the data stored in the app database. then be able to retreive it from the app in a browser. and vice versa. after searching a few Days I have not come close to finding this answ...
SMS text solution
With google app engine, is there a way to send a text message from a cell phone, to the app(written in python) and have the data stored in the app database. then be able to retreive it from the app in a browser. and vice versa. after searching a few Days I have not come close to finding this answer, or a cloud based so...
[ "\nYou can use Twilio to send text messages from AppEngine using Twilio SMS API. \nCheck out the code of weather by phone app documented here on Google Appengine blog: \nWeather by phone app (python+appengine) how-to \nI have heard that Tropo is also good. Try it out, it's Free for developers.\n\nI have never don...
[ 4 ]
[]
[]
[ "google_app_engine", "python", "sms" ]
stackoverflow_0007936217_google_app_engine_python_sms.txt
Q: Python Proxy isn't handling POST requests I'm creating a simple Python proxy that logs all requests sent through it. For now, everything works except POST requests (I can't vote on StackOverflow questions). I haven't defined an explicit POST function, but I am using the GET function instead. Could anyone tell me w...
Python Proxy isn't handling POST requests
I'm creating a simple Python proxy that logs all requests sent through it. For now, everything works except POST requests (I can't vote on StackOverflow questions). I haven't defined an explicit POST function, but I am using the GET function instead. Could anyone tell me where the problem is? This is my code: #!/usr/lo...
[ "The read-select on self.connection never returns, and if one manually reads from that object, no data is coming. It looks like you have to read from self.rfile.\nNote that calling select on self.rfile doesn't return, but self.rfile.read() does work. That is probably because self.rfile is a Python file-like object,...
[ 1 ]
[]
[]
[ "post", "proxy", "python" ]
stackoverflow_0007935442_post_proxy_python.txt
Q: How to open an specific section of a chm file in Python? How can I open a .chm help file in a particular section using Python? Actually I am opening the file with the following function: def help(self): # Open the help file os.startfile( os.getcwd()+"/config/help.chm") A: Other sugestion : subprocess.Popen(...
How to open an specific section of a chm file in Python?
How can I open a .chm help file in a particular section using Python? Actually I am opening the file with the following function: def help(self): # Open the help file os.startfile( os.getcwd()+"/config/help.chm")
[ "Other sugestion :\nsubprocess.Popen(\"hh.exe d:/help.chm::/4_Userguide.htm#_Toc270510\")\n\n", "I find a way to do it, but is more related to the hh program in Windows:\nMy help file was generated using the program chmprocessor which generate the chm file and I generate a hhk file (containing the references). Us...
[ 3, 0 ]
[]
[]
[ "chm", "python" ]
stackoverflow_0003814892_chm_python.txt
Q: Python: "Self" is not not defined? Back with the same confusing script.. there was A LOT of spacing issues that I fixed... but seem to be missing more? Whats wrong with this -- its saying line 332 self is not defined... Here are a few lines above and below that script in case it matters: #-Whats being decompiled...
Python: "Self" is not not defined?
Back with the same confusing script.. there was A LOT of spacing issues that I fixed... but seem to be missing more? Whats wrong with this -- its saying line 332 self is not defined... Here are a few lines above and below that script in case it matters: #-Whats being decompiled start #map(None,*list) = zip(*list) cla...
[ "If the code excerpt accurately reflects what's in your program the problem is that you have only a single line in your __init__ constructor. You need to fix your indentation.\nSelf is only defined in member functions. Your non-indented code is not part of the constructor, but is actually getting run when you imp...
[ 10, 4 ]
[]
[]
[ "defined", "python", "python_3.x", "self" ]
stackoverflow_0007936426_defined_python_python_3.x_self.txt
Q: Mongodb FindAndModify problem with multiprocess use I use python 2.6.6, pymongo 1.9, mongodb 1.6.5, Ubuntu 10.10 I have strange problem with FindAndModify command. I have two identical process running at the same time. They get records from db with FindAndModify(implements some sort of queue). So to make that o...
Mongodb FindAndModify problem with multiprocess use
I use python 2.6.6, pymongo 1.9, mongodb 1.6.5, Ubuntu 10.10 I have strange problem with FindAndModify command. I have two identical process running at the same time. They get records from db with FindAndModify(implements some sort of queue). So to make that only one process get record i do this: find_and_modify({q...
[ "While was trying to reproduce this bug in standalone script, found that problem was not in MongoDB. MongoDB works as said in manual, so the question is closed now.\nFor thous who found same bug - Don't forget to check another threads/processes for modifying queue data at runtime.\n", "You can use the snapshot=Tr...
[ 1, 0 ]
[]
[]
[ "mongodb", "pymongo", "python", "queue" ]
stackoverflow_0004738296_mongodb_pymongo_python_queue.txt
Q: More Efficient way to code this? I'm supposed to get the excel date of Dec 1 2011 and what day of the week it is and print it out in this format. The Excel date for Thursday, 2011-Dec-1 is 40878. I've been able to get both, but I don't think my method of getting the day using if statements is the best approach. T...
More Efficient way to code this?
I'm supposed to get the excel date of Dec 1 2011 and what day of the week it is and print it out in this format. The Excel date for Thursday, 2011-Dec-1 is 40878. I've been able to get both, but I don't think my method of getting the day using if statements is the best approach. This is my Original script file, so ple...
[ "How about:\ndays = ['sun', 'mon', 'tue', 'wed', 'thur', 'fri', 'sat']\n\nprint days[Day_Of_week]\n\nAlso take a look at this: How do I read a date in Excel format in Python?\n", "\"\"\"I'm supposed to get the excel date of Dec 1 2011\"\"\": There is no such thing as the Excel date\". There are two\" date systems...
[ 4, 0, 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0007775603_date_python.txt
Q: Search for Files with Extension and Copy to Directory in Python? I'm quite new to Python, and am attempting to create a basic backup program, that'll allow me to search for files of a certain extension (in this case, .doc), throughout the entire home drive of a computer, and then copy to a predetermined directory ...
Search for Files with Extension and Copy to Directory in Python?
I'm quite new to Python, and am attempting to create a basic backup program, that'll allow me to search for files of a certain extension (in this case, .doc), throughout the entire home drive of a computer, and then copy to a predetermined directory (as the program will be run from a USB). I've got a handle on some of ...
[ "To explore the filesystem, you can try os.walk. It will recursively follow a directory yielding a list of files and dirs in each dir.\nFor example, given a directory structure like this:\n.\n├── baz\n│   └── bif\n│   ├── bang\n│   └── file1.doc\n└── foo\n ├── bar\n │   └── file3.doc\n └── file2.d...
[ 2 ]
[]
[]
[ "backup", "copy", "directory", "io", "python" ]
stackoverflow_0007936432_backup_copy_directory_io_python.txt
Q: matplotlib 3d wireframe plot Right, so I've got a list of x values, y values and z values (which I think I converted into arrays?) which I want to make a surface plot, but it's not working. Here's what I'm trying to do, you can ignore most of the code as it is pretty irrelevant - just look at the end where I have ...
matplotlib 3d wireframe plot
Right, so I've got a list of x values, y values and z values (which I think I converted into arrays?) which I want to make a surface plot, but it's not working. Here's what I'm trying to do, you can ignore most of the code as it is pretty irrelevant - just look at the end where I have xdis, ydis and dist and where I'm ...
[ "plot_wireframe expects three 2D-arrays (X,Y,Z) as input. So,\nafter:\nX=np.array(xdis)\nY=np.array(ydis)\nZ=np.array(resis)\n\nadd:\nX=X.reshape((-1,16))\nY=Y.reshape((-1,16))\nZ=Z.reshape((-1,16)) \n\n", "It doesn't seem like the \"sweep\" function is modifying 'v' so you're getting an empty list.\n" ]
[ 3, 0 ]
[]
[]
[ "3d", "matplotlib", "numpy", "python" ]
stackoverflow_0007935729_3d_matplotlib_numpy_python.txt
Q: Default method implementations in python(__str__,__eq__,__repr__,ect.) Are there any ways to add a simple implementations for __str__,__eq__,__repr__ to a class? Basically I want an __eq__ to be just be whether all non prefixed instance variables are equal. And a __str__/__repr__ that just names each variable and ...
Default method implementations in python(__str__,__eq__,__repr__,ect.)
Are there any ways to add a simple implementations for __str__,__eq__,__repr__ to a class? Basically I want an __eq__ to be just be whether all non prefixed instance variables are equal. And a __str__/__repr__ that just names each variable and calls str/repr on each variable. Is there a mechanism for this in the standa...
[ "You could define a Default mixin:\nclass Default(object):\n def __repr__(self):\n return '-'.join(\n str(getattr(self,key)) for key in self.__dict__ if not key.startswith('_'))\n def __eq__(self,other):\n try:\n return all(getattr(self,key)==getattr(other,key)\n ...
[ 12 ]
[]
[]
[ "metaprogramming", "oop", "python" ]
stackoverflow_0007937994_metaprogramming_oop_python.txt
Q: How to write a Web Service for Google App Engine? I am really new to Python and I have been looking for an example on how to write a Web Service (XML - SOAP) in Python with Google App Engine with no luck. Can anyone point me to an article or give me an example on how to do this? A: I was curious about this mys...
How to write a Web Service for Google App Engine?
I am really new to Python and I have been looking for an example on how to write a Web Service (XML - SOAP) in Python with Google App Engine with no luck. Can anyone point me to an article or give me an example on how to do this?
[ "I was curious about this myself and not finding anything I decided to try to get something to work. The short answer is that it turns out a SOAP service can actually be done using the latest alpha ZSI library. However it isn't simple and I didn't do much more than a simple request so it could fall apart with a com...
[ 17, 4, 1, 0 ]
[ "You could take a look at the Bottle framework. It's a Python framework which with you can easily create a REST api.\nIn my opinion, REST is definitely better than SOAP. It can be easily consumed by any software able to speak http, and it's faster to implement.\n" ]
[ -1 ]
[ "google_app_engine", "python", "soap", "web_services", "xml" ]
stackoverflow_0000331600_google_app_engine_python_soap_web_services_xml.txt
Q: Eclipse and python not resolving imports I'm doing some imports with python and sometimes I do not have that package yet, so I install the package. The problem is when I test it in python's interpreter it resolves the imports : Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on ...
Eclipse and python not resolving imports
I'm doing some imports with python and sometimes I do not have that package yet, so I install the package. The problem is when I test it in python's interpreter it resolves the imports : Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "...
[ "Probably you have to reconfigure in Pydev the python interpreter to get the new added libs.\nFrom Pydev tutorial:\n\nIf you add something to your python installation, you need to either\n add it manually as a 'new folder' in the System PYTHONPATH (if it's\n still not under a folder in the PYTHONPATH) or (recomme...
[ 2 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0007938027_eclipse_python.txt
Q: Is there any function to convert None to empty string? Something my string var is equal to None. I don't want to have if statements to verify the value. Is there any simple way (like str(my_var)) which will return string value if this is not None and '' if None? A: You can use foo or '', but in case foo is any o...
Is there any function to convert None to empty string?
Something my string var is equal to None. I don't want to have if statements to verify the value. Is there any simple way (like str(my_var)) which will return string value if this is not None and '' if None?
[ "You can use foo or '', but in case foo is any other falsy value (0, an empty list, etc.) it will result in an empty string, too.\nAnother way would be '' if foo is None else foo\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0007938297_python.txt
Q: Python Batch convert of FLAC files I want to convert all FLAC files to OGG in the working directory: This is what I ALREADY have. for root, dirs, files in os.walk(args): flacs = [f for f in files if f.endswith('.flac')] oggs = [o for o in files if o.endswith('.ogg')] for flacfiles in flacs...
Python Batch convert of FLAC files
I want to convert all FLAC files to OGG in the working directory: This is what I ALREADY have. for root, dirs, files in os.walk(args): flacs = [f for f in files if f.endswith('.flac')] oggs = [o for o in files if o.endswith('.ogg')] for flacfiles in flacs: id3 = ('id3v2', '-C', flac...
[ "for flacfiles in flacs:\n if os.path.exists(os.path.splitext(flacfiles)[0] + '.cue')):\n # do something \n\n" ]
[ 0 ]
[]
[]
[ "flac", "ogg", "os.walk", "python" ]
stackoverflow_0007938128_flac_ogg_os.walk_python.txt
Q: How to get value from selected item in treeview in PyGTK? I'm learning PyGtk. I have a simple treeview with 1 column, I get items for that treeview from list. How to get value of selected item in treeview? A: You may use the gtk.TreeView.get_selection() method to get the gtk.TreeSelection. Next, you should use...
How to get value from selected item in treeview in PyGTK?
I'm learning PyGtk. I have a simple treeview with 1 column, I get items for that treeview from list. How to get value of selected item in treeview?
[ "You may use the gtk.TreeView.get_selection() method to get the gtk.TreeSelection.\nNext, you should use the gtk.TreeSelection.get_selected_rows() method to get the TreeModel (the ListStore) and the selected items\n paths.\nThen, you can use the gtk.TreeModel.get_iter() in order to get the iter from the path (retu...
[ 27 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0007938007_gtk_gtktreeview_pygtk_python.txt
Q: get first paragraph from wikipedia article I'm using following code to get the first paragraph from a Wikipedia article. Here is the result of my code. I need only this paragraph. Is it possible? Or is there any better alternative? '''Papori''' ({{lang-as|'''?????'''}}) is an [[Assamese language]] feature ...
get first paragraph from wikipedia article
I'm using following code to get the first paragraph from a Wikipedia article. Here is the result of my code. I need only this paragraph. Is it possible? Or is there any better alternative? '''Papori''' ({{lang-as|'''?????'''}}) is an [[Assamese language]] feature film directed by [[Jahnu Barua]]. The film st...
[ "To remove everything from {{ to '''Papori''':\nimport re\nregex = re.compile(r\"\"\"{{.*?}}\\s*('''Papori''')\"\"\", re.DOTALL)\nprint regex.sub(r\"\\1\", rev_data)\n\nTo remove everything from the first \"{{\" to matching \"}}\":\nprefix, sep, rest = rev_data.partition(\"{{\")\nif sep: # found the first \"{{\"\n ...
[ 1, 0 ]
[]
[]
[ "python", "wikipedia", "xml" ]
stackoverflow_0007937855_python_wikipedia_xml.txt
Q: Python: threads using join() in while loop I would like my while loop to block at most 5 seconds for all threads it creates in the for loop. However, the following code will block by the threads one by one. How can I approach my goal? Thanks. threads = [] while True: for 3: newThread = threading.Thread...
Python: threads using join() in while loop
I would like my while loop to block at most 5 seconds for all threads it creates in the for loop. However, the following code will block by the threads one by one. How can I approach my goal? Thanks. threads = [] while True: for 3: newThread = threading.Thread(..) threads.append(newThread) n...
[ "You need to use condition variable (threading.Condition in Python). It allows to wait for a predicate to become true. In your case the predicate is all threads have finished work or time out exceeded. Here is code which creates ten threads and waits until they are finished with 5sec time out. Verbose logs will...
[ 3, 2, 0 ]
[]
[]
[ "block", "join", "python", "python_multithreading", "while_loop" ]
stackoverflow_0007937755_block_join_python_python_multithreading_while_loop.txt
Q: How do I make the parameters parsed by configparser visible to every .py I like to parse parameters, vars by using configparser. However, I have to pass the instance to every .py, in order to get the parameters. What is the most elegant way to make the parameters visible to every .py ? Thanks! A: You could have...
How do I make the parameters parsed by configparser visible to every .py
I like to parse parameters, vars by using configparser. However, I have to pass the instance to every .py, in order to get the parameters. What is the most elegant way to make the parameters visible to every .py ? Thanks!
[ "You could have \"config\" module, which parses the options into a global variable (in that same module) which you then include in all places where you need it.\nAdmittedly though, I do agree with delnan's comment, avoid globals if it's possible as in general it will push you to design better code. Personally I don...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007938889_python_python_3.x.txt
Q: How to remove the row that has special characters in it I have a large text file that has a lot of special characters in it like "$!@%#$/" plus many more and I would like to remove the line in the text file if it has any special characters in that line. The only characters I want to keep is a-z and A-Z. If this w...
How to remove the row that has special characters in it
I have a large text file that has a lot of special characters in it like "$!@%#$/" plus many more and I would like to remove the line in the text file if it has any special characters in that line. The only characters I want to keep is a-z and A-Z. If this was the file... !Somejunk)(^% )%(&_ this my_file is *(%%$ the ...
[ "$ grep '^[[:alpha:]]\\+$' << EOF\n> !Somejunk)(^%\n> )%(&_\n> this\n> my_file\n> is\n> *(%%$\n> the\n> they're\n> file\n> EOF\nthis\nis\nthe\nfile\n\n", "This seems to work:\n sed '/[^[:alpha:]]/d' source_file\n\n", "If you want to keep ONLY lines with alpha characters (as the OP requested), then:\n$ grep -v '...
[ 8, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0007937042_bash_linux_python.txt
Q: Problem decrypting PGP in python with pyme without user interaction I am trying to decrypt messages using pyme (a python wrapper from gpgme). It works fine if I type in the password when it prompts but I cannot get the passphrase callback to work. Here is the code import pyme.core def Callback( x, y, z ): pri...
Problem decrypting PGP in python with pyme without user interaction
I am trying to decrypt messages using pyme (a python wrapper from gpgme). It works fine if I type in the password when it prompts but I cannot get the passphrase callback to work. Here is the code import pyme.core def Callback( x, y, z ): print 'in passphrase callback' return 'passphrase' plain = pyme.core.Data(...
[ "apparently, you need to interpret the keyword hook:\n def Callback( x, y, z, hook=None):\n ...\n\nworks perfectly well.\n", "I'm able to reproduce the error you're reporting by returning None from the passphrase callback. Python functions return None by default if they reach the end of executing a function ...
[ 2, 0 ]
[]
[]
[ "gnupg", "gpgme", "pgp", "pyme", "python" ]
stackoverflow_0003660150_gnupg_gpgme_pgp_pyme_python.txt
Q: How do I create a multicast stream socket over IPv6 in Python? I need some help in implementing Multicast Streaming server over IPv6 preferably in Python. I am able to do so with Datagram servers but since I need to send large amounts of data (images and videos) over the connection, I get an error stating , data t...
How do I create a multicast stream socket over IPv6 in Python?
I need some help in implementing Multicast Streaming server over IPv6 preferably in Python. I am able to do so with Datagram servers but since I need to send large amounts of data (images and videos) over the connection, I get an error stating , data too large to send. Can any one tell me how do I implement a Streamin...
[ "You DO want to use datagrams, as with multicast there are multiple receivers and a stream socket will not work.\nYou need to send your data in small chunks (datagrams) and state in each which part of the stream it is so receivers can detect lost (and reordered) datagrams.\nInstead of inventing a new mechanism for ...
[ 3 ]
[]
[]
[ "ipv6", "multicast", "python", "sockets", "streaming" ]
stackoverflow_0007937928_ipv6_multicast_python_sockets_streaming.txt
Q: What HTTP framework to use for simple but scalable app? What HTTP framework should I use for a simple application with implied scalability, priferable Pythonic? I would like to be able to smoothly add new features to my app when it has already been deployed. A: I'm a big fan of Pylons. It behaves just like a fra...
What HTTP framework to use for simple but scalable app?
What HTTP framework should I use for a simple application with implied scalability, priferable Pythonic? I would like to be able to smoothly add new features to my app when it has already been deployed.
[ "I'm a big fan of Pylons. It behaves just like a framework should; not excessive on the magic and contains many good components that you can pick-and-choose that help you hit the ground running. It's small and easy to deploy, and requires minimal boilerplate or other syntactic cruft. Scalability seems pretty good -...
[ 2, 1, 0 ]
[]
[]
[ "frameworks", "http", "python", "scalability" ]
stackoverflow_0000793501_frameworks_http_python_scalability.txt
Q: Python: Trouble with Encoding I am saving my data into a dictionary and after saving it to the dictionary I printed the data to see what it looks like and I see the unicode: (u'520775', [[u'Kategori:2. divisjon fotball for herrer 2008']]) (u'754686', [[u'Kategori:Debutalbum', u'Kategori:Musikkalbum fra 1990', u'Ka...
Python: Trouble with Encoding
I am saving my data into a dictionary and after saving it to the dictionary I printed the data to see what it looks like and I see the unicode: (u'520775', [[u'Kategori:2. divisjon fotball for herrer 2008']]) (u'754686', [[u'Kategori:Debutalbum', u'Kategori:Musikkalbum fra 1990', u'Kategori:Tre Sm\xe5 Kinesere-album']]...
[ "When you print a dict, or list, or tuple, repr is called on the items in the container, rather than str like when you print them directly, so you see the unicode escape codes.\nIf you were to \nmydict = dict(((u'520775', [[u'Kategori:2. divisjon fotball for herrer 2008']]),\n(u'754686', [[u'Kategori:Debutalbum', u...
[ 1 ]
[]
[]
[ "encoding", "python", "unicode" ]
stackoverflow_0007940056_encoding_python_unicode.txt
Q: Need help to find right Regex match pattern I can't find a working regex in python to split these strings: CAT One | desired: CAT DOG SILVER FOX Two | desired: DOG SILVER FOX KING KONG | desired: KING KONG P'OT THEN Mark First | desired P'OT THEN Just stupid examples, but i need to separate words that are ful...
Need help to find right Regex match pattern
I can't find a working regex in python to split these strings: CAT One | desired: CAT DOG SILVER FOX Two | desired: DOG SILVER FOX KING KONG | desired: KING KONG P'OT THEN Mark First | desired P'OT THEN Just stupid examples, but i need to separate words that are full uppercase from words that are only capitalized. ...
[ "import re\n\nlines = [\n \"CAT One\",\n \"DOG SILVER FOX Two\",\n \" KING KONG \",\n \"P'OT THEN Mark First\",\n \"FOO-BAR Second FISH\",\n \"horsE YELLOW thirD BLUE\",\n ]\n\nfor line in lines:\n print re.findall(r'\\b[A-Z]+(?:\\W*[A-Z]+)*\\b', line)\n\nOutput:\n['CAT']\n['DOG SILVER FOX']...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "regex", "uppercase" ]
stackoverflow_0007938438_python_regex_uppercase.txt
Q: Getting the array as GET query parameters in Python I know in php I could just use $_GET['key1']['key2'] to retrieve GET data that is sent in the form of an array but is that something possible in Python as I just receive a string and it's not recognized as an array/list. I use flask/werkzeug if that matters. A: ...
Getting the array as GET query parameters in Python
I know in php I could just use $_GET['key1']['key2'] to retrieve GET data that is sent in the form of an array but is that something possible in Python as I just receive a string and it's not recognized as an array/list. I use flask/werkzeug if that matters.
[ "The deep parsing of argument names is unique for PHP AFAIK.\nIf you need just a simple list, just pass several parameters with the same name and use request.args.getlist(<paramname>) (documentation).\nOtherwise you have to parse the query string yourself.\n", "request.args is a MultiDict instance (MultiDict, Fla...
[ 72, 67 ]
[]
[]
[ "flask", "list", "python", "request", "werkzeug" ]
stackoverflow_0007940085_flask_list_python_request_werkzeug.txt
Q: Write to File open in Second Function (Python) I currently have the below function within my code:- def openFiles(): file1 = open('file1.txt', 'w') file2 = open('file2.txt', 'w') What I'm hoping to do is now, in a second method is to write to the open file. However, whenever I try to write to the files us...
Write to File open in Second Function (Python)
I currently have the below function within my code:- def openFiles(): file1 = open('file1.txt', 'w') file2 = open('file2.txt', 'w') What I'm hoping to do is now, in a second method is to write to the open file. However, whenever I try to write to the files using for example "file1.write("hello")", an error is ...
[ "You can use python global keyword as shown below. \ndef openFiles():\n global file1\n global file2\n file1 = open('file1.txt', 'w')\n file2 = open('file2.txt', 'w')\n\ndef writeFiles():\n file1.write(\"hello\")\n\nopenFiles()\nwriteFiles()\n\nHowever I would recommend you use a class for this instea...
[ 9 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007940321_function_python.txt
Q: Programmatically logging in a user? Is it possible to sign into a website (and allow that website to be visited with any browser without the user having to sign in) via a background process without user interaction and allow the user to browse the site without logging in from any browser? I'd guess that I would ne...
Programmatically logging in a user?
Is it possible to sign into a website (and allow that website to be visited with any browser without the user having to sign in) via a background process without user interaction and allow the user to browse the site without logging in from any browser? I'd guess that I would need to register the created session with e...
[ "yes is possible.I suggest two ways to solve your problem. Both of them uses HTTP requests. You should check more info about HTTP request.\n1) the easiest way and recommended one for only login Requests: HTTP for Humans \n2) python scrapy, but scrapy is for crawling or screen scraping.\ncheck this example:\nLogin s...
[ 1, 0 ]
[]
[]
[ "authentication", "language_agnostic", "proxy", "python", "session" ]
stackoverflow_0007935405_authentication_language_agnostic_proxy_python_session.txt
Q: Reading huge data from files and calling them I am creating a program that reads x,y,z in the format of (1.000 2.000 3.000), first coloumn is x second is y and the third is z. I would like to read this data from this file (hiz.txt) and then call up on them as variables later on. I am looking for about 50-100 rows ...
Reading huge data from files and calling them
I am creating a program that reads x,y,z in the format of (1.000 2.000 3.000), first coloumn is x second is y and the third is z. I would like to read this data from this file (hiz.txt) and then call up on them as variables later on. I am looking for about 50-100 rows of this data, and i want my program to keep looking...
[ "I assume by \"huge data\" you mean the file won't all fit into memory, so you have to go line by line.\nI also assume you just want to save up the 50 or so rows you are looking for and that those will fit into memory.\nSo Like this:\ntheDataIWant = []\n\ndef isThisSomethingIWant(x, y, z):\n return the condition...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007940467_python.txt
Q: is it possible to overwrite "self" to point to another object inside self.method in python? class Wrapper(object): def __init__(self, o): # get wrapped object and do something with it self.o = o def fun(self, *args, **kwargs): self = self.o # here want to swap # or some low ...
is it possible to overwrite "self" to point to another object inside self.method in python?
class Wrapper(object): def __init__(self, o): # get wrapped object and do something with it self.o = o def fun(self, *args, **kwargs): self = self.o # here want to swap # or some low level C api like # some_assign(self, self.o) # so that it swaps id() mem addr to ...
[ "Assigning to self inside a method simply rebinds the local variable self to the new object. Generally, an assignment to a bare name never changes any objects, it just rebinds the name on the left-hand side to point to the object on the right-hand side.\nSo what you would need to do is modify the object self point...
[ 15, 4 ]
[]
[]
[ "python", "python_c_api" ]
stackoverflow_0007940470_python_python_c_api.txt
Q: python csv is separating too much here's my code f= open('test1.txt','r') todo = open('fb12.txt','w') reader = csv.reader(f,delimiter=' ', quotechar='|') writer = csv.writer(todo) for row in reader: writer.writerows(row) I want the output to be just the same as the input it should look like ...
python csv is separating too much
here's my code f= open('test1.txt','r') todo = open('fb12.txt','w') reader = csv.reader(f,delimiter=' ', quotechar='|') writer = csv.writer(todo) for row in reader: writer.writerows(row) I want the output to be just the same as the input it should look like this "DDD","3D Systems Corporation","23...
[ "You've got one too many layers of iteration :-)\nReplace the for-loop with:\nwriter.writerows(reader)\n\nOr change the writerows to writerow:\nfor row in reader:\n writer.writerow(row)\n\n" ]
[ 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007940648_csv_python.txt
Q: Install Django on Mac by copying to directory? I'm kind of confused where I should have installed Django 1.3.1 on my Mac. I moved the Django 1.3.1 folder to Documents, and then opens terminal, cd Documents/Django-1.3.1 setup.py install. Now, i'm having all sorts of problems after trying to install psycopg2. How c...
Install Django on Mac by copying to directory?
I'm kind of confused where I should have installed Django 1.3.1 on my Mac. I moved the Django 1.3.1 folder to Documents, and then opens terminal, cd Documents/Django-1.3.1 setup.py install. Now, i'm having all sorts of problems after trying to install psycopg2. How can i uninstall and remove django, so that i can inst...
[ "I think you should use pip or easy_install for installing any python libraries.\neasy_install is already available with python, so for installing django you do \neasy_install django from the terminal. \npip is a replacement for easy_install for installing pip you do easy_install pip now pip is installed, for insta...
[ 4 ]
[]
[]
[ "django", "macos", "psycopg2", "python", "terminal" ]
stackoverflow_0007940770_django_macos_psycopg2_python_terminal.txt
Q: Monte Carlo and Area -calculation It should be close to 0.3 $ cat monte.py import random,math density=int(1e6) x = [random.uniform(0,1)*7*math.pi for _ in range(density)] y = [random.uniform(0,1) for _ in range(density)] i = [math.sin(xx)*math.cos(xx) > yy for (xx,yy) in zip(x,y)] print sum(i)/(float(density)*10...
Monte Carlo and Area -calculation
It should be close to 0.3 $ cat monte.py import random,math density=int(1e6) x = [random.uniform(0,1)*7*math.pi for _ in range(density)] y = [random.uniform(0,1) for _ in range(density)] i = [math.sin(xx)*math.cos(xx) > yy for (xx,yy) in zip(x,y)] print sum(i)/(float(density)*10.0)*7*math.pi $ python monte.py 0.350...
[ "I'm getting identical results between your matlab and python versions... Are you sure that the matlab version is giving you ~2, and not ~0.35?\nFor example:\nMATLAB:\nx = rand(1, 1000000)*7*pi;\ny = rand(1, 1000000);\ni = sin(x).* cos(x) >y;\nArea3 = (sum(i) / 10000000)*7*pi\n\nThis yields: 0.3511\nYour pure-pytho...
[ 2 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0007940740_matlab_python.txt
Q: passing variable to loop as string in python I have a python script that will take each file in a directory, iterate through the contents of the file and create an output file for each input file. This output file may have duplicate entries and if it does I would like to take only the unique values similar to the ...
passing variable to loop as string in python
I have a python script that will take each file in a directory, iterate through the contents of the file and create an output file for each input file. This output file may have duplicate entries and if it does I would like to take only the unique values similar to the UNIX command uniq -u input.file > output.file Alt...
[ "You have \nos.system(\n \"uniq -u %s > %s\"\n ) % ( # The % and this paren should be inside the call to os.system\n str(curfile), \n str(curfile[:-4] + \".uniq\")\n # you're missing a close paren here\n\nyou need\nos.system(\n \"uniq -u ...
[ 3 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0007940857_python_unix.txt
Q: Error when importing OpenCV python module (when built with Qt and QtOpenGL) I recently downloaded OpenCV 2.3.1, compiled with the CMake flags withQt and withQtOpenGL turned on. My Qt version is 4.7.4 and is configured with OpenGL enabled. Supposedly I only need to copy cv2.pyd to Python's site-package path: C:\Py...
Error when importing OpenCV python module (when built with Qt and QtOpenGL)
I recently downloaded OpenCV 2.3.1, compiled with the CMake flags withQt and withQtOpenGL turned on. My Qt version is 4.7.4 and is configured with OpenGL enabled. Supposedly I only need to copy cv2.pyd to Python's site-package path: C:\Python27\Lib\site-packages And in the mean time make sure the OpenCV dlls are some...
[ "Probably need the qt dll's in the same place as the opencv dlls - and they have to be the version built with the same compiler as opencv (and possibly python)\n" ]
[ 0 ]
[]
[]
[ "import", "opencv", "python", "qt" ]
stackoverflow_0007940848_import_opencv_python_qt.txt
Q: Searching through file (Python) Possible Duplicate: Reading huge data from files and calling them I want to read through an input(text file) and the format for this text file is 2.000 3.000 4.000 , now i want to assign 2.000 to be x and 3.000 to be y and 4.000 to be z. The problem is that I will be searching thr...
Searching through file (Python)
Possible Duplicate: Reading huge data from files and calling them I want to read through an input(text file) and the format for this text file is 2.000 3.000 4.000 , now i want to assign 2.000 to be x and 3.000 to be y and 4.000 to be z. The problem is that I will be searching through the entire file which might hav...
[ "Read the file line-by-line, split the line into components, and then make each component a float so that you can use it as a number instead of a string:\nhandle = open('myfile.txt', 'r')\n\nfor line in handle:\n x, y, z = map(float, line.split(' '))\n\n print 'x is', x\n print 'y is', y\n print 'z is', z\n pr...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007940990_python.txt
Q: Taking input containing " or ' with argparse I've made a quick python script that converts to Unicode from ASCII and back. I'm taking input via argparse so it has to be contained within quotation marks, i.e. ./Converter.py -a "there's my friend". The script will then output comma separated Unicode values. Of co...
Taking input containing " or ' with argparse
I've made a quick python script that converts to Unicode from ASCII and back. I'm taking input via argparse so it has to be contained within quotation marks, i.e. ./Converter.py -a "there's my friend". The script will then output comma separated Unicode values. Of course the ' will break the input, and I know I can ...
[ "Your condition\nif letter != text[-1]: \n\nsays to write a comma and space character whenever the last character is not equal to the value of the last character - in this case, ' (your first character) is the same character as ' (your last character). You should change the condition to check that it really is the...
[ 3 ]
[]
[]
[ "argparse", "input", "python" ]
stackoverflow_0007940947_argparse_input_python.txt
Q: Search through file until no more data Possible Duplicate: Reading huge data from files and calling them I do not know how to search through a file, I have a file which has around 50 lines of data in this format (1.000 2.000 3.000) but I do not know how to do one line do a conversion(already have) then go to the...
Search through file until no more data
Possible Duplicate: Reading huge data from files and calling them I do not know how to search through a file, I have a file which has around 50 lines of data in this format (1.000 2.000 3.000) but I do not know how to do one line do a conversion(already have) then go to the next line do the same until it reaches the...
[ "with open('filename') as f:\n for line in f:\n line = line.rstrip()\n # do the conversion (that you already know how to do)\n\nHere:\n\nwith open('filename') as f: opens the file (and automatically closes it at the end);\nfor line in f: reads every line of the file into line;\nline = line.rstrip() removes a...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007941105_python.txt
Q: How can I exec an interactive shell from Jython? I need some example Jython, or Java, code to exec an interactive OS shell (/bin/sh). Our development environment is Java on Linux. What I would like to do is provide a means for developers to write Jython scripts, and then drop into a shell, which allows them to i...
How can I exec an interactive shell from Jython?
I need some example Jython, or Java, code to exec an interactive OS shell (/bin/sh). Our development environment is Java on Linux. What I would like to do is provide a means for developers to write Jython scripts, and then drop into a shell, which allows them to inspect the system. The reason I need to exec this fro...
[ "What is wrong with this simple jython code, is that the stdin, stdout do not work as we expect\nimport subprocess\nimport os \nsubprocess.call([os.environ.get('SHELL', '/bin/sh'), '-i'])\n\nAssuming that we want to spawn the shell on the tty, the following seems to\ngive better results:\nimport os\nimport...
[ 2 ]
[]
[]
[ "exec", "java", "jython", "python", "sh" ]
stackoverflow_0007941148_exec_java_jython_python_sh.txt
Q: How to use a QStyledItemDelegate to render QIcons for a column? I am using a QTableView and QSqlTableModel to show data from a sqlite DB. In the DB (and model) there is a column with fields that contain either paths ie: '/home/foo/bar.txt' or nothing. For this column in the view I would like to render one icon fo...
How to use a QStyledItemDelegate to render QIcons for a column?
I am using a QTableView and QSqlTableModel to show data from a sqlite DB. In the DB (and model) there is a column with fields that contain either paths ie: '/home/foo/bar.txt' or nothing. For this column in the view I would like to render one icon for items with a path, and a different icon for items with nothing (and...
[ "Instead of subclassing the delegate, you can subclass the model, and return the icon in the item's DecorationRole.\nUntested sketch of solution:\nclass IconModel(QSqlTableModel):\n def data(self, index, role=Qt.DisplayRole):\n if index.column() == FILENAME_COLUMN_INDEX:\n if role == Qt.Decora...
[ 1 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0007941123_pyqt_python_qt.txt
Q: Python - Get sorted list of user-defined classes I have a class: class Prediction(): def __init__(self, l): self.start = l[0] self.end = l[1] self.score = l[2] And a list, where each element is a Prediction. It's aptly named predictions. I want to sort predictions by the start attribut...
Python - Get sorted list of user-defined classes
I have a class: class Prediction(): def __init__(self, l): self.start = l[0] self.end = l[1] self.score = l[2] And a list, where each element is a Prediction. It's aptly named predictions. I want to sort predictions by the start attribute of the Prediction class. Something like this: predic...
[ "predictions_start_order = sorted(predictions, key=lambda x: x.start)\n\n", "The key argument to sorted takes a function, not an attribute. What you're looking for is:\nclass Prediction():\n def __init__(self, l):\n self.start = l[0]\n self.end = l[1]\n self.score = l[2]\n\n def __lt__(...
[ 4, 2 ]
[]
[]
[ "class", "list", "python", "user_defined_types" ]
stackoverflow_0007941283_class_list_python_user_defined_types.txt
Q: Squeezing characters with python How would I do this with python : if I have a string formatted like : A..a.b.c To make it like : A.a.b.c But I do not know beforehand how many dots I have ? It's like the tr -s function in linux A: If you want a general format to replace any sequence of repeated characters...
Squeezing characters with python
How would I do this with python : if I have a string formatted like : A..a.b.c To make it like : A.a.b.c But I do not know beforehand how many dots I have ? It's like the tr -s function in linux
[ "If you want a general format to replace any sequence of repeated characters with just one of those characters:\n>>> import re\n>>> s='aaa,,bb,c'\n>>> re.sub(r'(.)(\\1+)', r'\\1', s)\n'a,b,c'\n\nIf you want to limit by only certain characters:\n>>> re.sub(r'([\\w])(\\1+)', r'\\1', s)\n'a,,b,c'\n>>> re.sub(r'([,])(\...
[ 7, 5, 4, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007940619_python_regex.txt
Q: retrieve data from database to insert it to list using python? How i can insert data to list from database i have already build it and insert into it ?? i build database from two columns and it's variable columns you can insert what you need , i need to retrieve what i insert on each column and insert and save it ...
retrieve data from database to insert it to list using python?
How i can insert data to list from database i have already build it and insert into it ?? i build database from two columns and it's variable columns you can insert what you need , i need to retrieve what i insert on each column and insert and save it into list and the second column at same ? what should i do ? i write...
[ "You can extract the data like this:\ndef retrieve(self):\n ... \n query = QtSql.QSqlQuery()\n if not query.exec_(\"SELECT * FROM name\"):\n print(\"Error: \" + query.lastError().text())\n\n myList = []\n while query.next():\n myList += [[str(query.value(0).toString()), query.value...
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0007929267_pyqt4_python.txt
Q: Encoding error with Django models I have two tables with utf-8 collation. I am using Django to fetch a row from one table and insert it to the other as follows: cursor.execute("select * from Table1") results = dictfetchall(cursor) for row in results: table2_row = Table2(name=row["Name"]) table2_row.save() Th...
Encoding error with Django models
I have two tables with utf-8 collation. I am using Django to fetch a row from one table and insert it to the other as follows: cursor.execute("select * from Table1") results = dictfetchall(cursor) for row in results: table2_row = Table2(name=row["Name"]) table2_row.save() The problem is that I sometimes get error...
[ "Try To Do These Works:\n1- Add # encoding: UTF-8 On Top Of Your Module\n\n2- Define Your Character Set When Create Your Database Like This Snippet:\n\nCreate Database DB_NAME CHARACTER SET = UTF8;\n\n3- Try To Assign row['name'] Like This:\n\nname = row['name'].encode('utf8')\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007939273_django_python.txt
Q: Appengine converting unicode char to blank char in urllib.unquote I am sending encoded post data to appengine project.But appengine shows blank char in response. I am sending this form data : mdata=I%FD%FD%FE%DE%DE%E7%E7%C7%D6%F6%F6%D6%D6%0A%0A and my appengine response code is : request_data = self.request.get('...
Appengine converting unicode char to blank char in urllib.unquote
I am sending encoded post data to appengine project.But appengine shows blank char in response. I am sending this form data : mdata=I%FD%FD%FE%DE%DE%E7%E7%C7%D6%F6%F6%D6%D6%0A%0A and my appengine response code is : request_data = self.request.get('mdata') mailhtmldata = urllib.unquote_plus(request_data) And repr(requ...
[ "What you are sending appears to be the result of url-encoding some characters expressed in cp1254 (Windows Turkish) encoding (or the very similar ISO-8859-9 encoding). Have you told \"appengine\" what encoding you are using?\nWe need a bit more information about \"Still unicode chars like \"İşÇöÖü\" are blank\". B...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007935228_google_app_engine_python.txt
Q: Django syncdb error for blog tables i'm following this tutorial: http://www.programmersbook.com/page/21/Django-Beginner-Tutorial-Part-I/ and I added the database details (running django.db.backends.postgresql_psycopg2) and i added the template dirs. But when i do ./manage.py syncdb i get: self.connection = D...
Django syncdb error for blog tables
i'm following this tutorial: http://www.programmersbook.com/page/21/Django-Beginner-Tutorial-Part-I/ and I added the database details (running django.db.backends.postgresql_psycopg2) and i added the template dirs. But when i do ./manage.py syncdb i get: self.connection = Database.connect(**conn_params) psycopg2.O...
[ "Before connecting to database you need to install database server, and configure it for any user to access. \nIf you want just follow tutorial use SQLite -it's most simple to configure. \nOtherwise, install database server of your choose, create database, configure access, make sure that connection details are cor...
[ 0 ]
[]
[]
[ "database", "django", "psycopg2", "python" ]
stackoverflow_0007941443_database_django_psycopg2_python.txt
Q: Abstract classes in Python 2.5? I am trying to use Abstract Base Classes in Python 2.5 (http://docs.python.org/library/abc.html). However, this feature is new in Python 2.6. Can I just copy the source file abc.py into my pythonpath and have everything work properly? If not, how else would I get abstract base class...
Abstract classes in Python 2.5?
I am trying to use Abstract Base Classes in Python 2.5 (http://docs.python.org/library/abc.html). However, this feature is new in Python 2.6. Can I just copy the source file abc.py into my pythonpath and have everything work properly? If not, how else would I get abstract base classes in Python 2.5?
[ "You can copy the abc.py module from Python2.6. It has no dependencies and does not use any features specific to Python 2.6.\nThe Python 2.7 source is more complicated with a dependency on WeakRefSet.\nIn addition to copying abc.py, you may what to create versions of isinstance and issubclass functions that are ab...
[ 1 ]
[]
[]
[ "abstract_class", "python" ]
stackoverflow_0007941507_abstract_class_python.txt
Q: changing dtypes of structured/record arrays Q1. When recasting a column to a different data type, is np.array or np.astype preferred? I've seen examples using np.astype but both seem to return the desired result (both return copies of the original array). import numpy as np ## recasting string to integer x = np.r...
changing dtypes of structured/record arrays
Q1. When recasting a column to a different data type, is np.array or np.astype preferred? I've seen examples using np.astype but both seem to return the desired result (both return copies of the original array). import numpy as np ## recasting string to integer x = np.rec.array([('a','1'),('b','2')],names='col1,col2')...
[ "Q1: Both the np.array and np.astype approaches do the same work in the same way under-the-hood. Using np.astype involves a little less typing, and it is more clear to the reader that the intention is to change the datatype.\n" ]
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007941591_numpy_python.txt
Q: Run web.py as daemon I have a simple web.py program to load data. In the server I don't want to install apache or any webserver. I try to put it as a background service with http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ And subclassing: (from http://www.jejik.com/files/examples/daemo...
Run web.py as daemon
I have a simple web.py program to load data. In the server I don't want to install apache or any webserver. I try to put it as a background service with http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ And subclassing: (from http://www.jejik.com/files/examples/daemon.py) class Daemon: de...
[ "I finally find the problem.\nWeb.py accept from command-line the optional port number:\npython code.py 80\n\nAnd the script also take input from the command-line:\npython WebServer start\n\nthen web.py try to use \"start\" as port number and fail. I don't see the error because was in the bacground. \nI fix this wi...
[ 5, 5, 0, 0 ]
[]
[]
[ "backgroundworker", "python" ]
stackoverflow_0001093485_backgroundworker_python.txt
Q: How to get the function definition from an object? Suppose we have following code defined in tester.py class Tester( object ): def method( self ): print 'I am a Tester' and we have following defined in main.py from tester import Tester t = Tester() #print definition of t is there anyway we could get ...
How to get the function definition from an object?
Suppose we have following code defined in tester.py class Tester( object ): def method( self ): print 'I am a Tester' and we have following defined in main.py from tester import Tester t = Tester() #print definition of t is there anyway we could get the definitions of a class/function from an object in a ...
[ "You can use the inspect module:\nimport inspect\n\nclass Tester( object ):\n def method( self ):\n print 'I am a Tester'\n\nprint inspect.getsource(Tester)\n\nOutput:\nclass Tester( object ):\n def method( self ):\n print 'I am a Tester'\n\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0007941773_python.txt
Q: How can I send data to Chrome extension? I am developing a user authentication for my bookmarking extension. The extension works with the Google App Engine (Python) backend at http://ting-1.appspot.com/. The first time the extension runs, background.html opens options.html in a new tab and the user enters his ema...
How can I send data to Chrome extension?
I am developing a user authentication for my bookmarking extension. The extension works with the Google App Engine (Python) backend at http://ting-1.appspot.com/. The first time the extension runs, background.html opens options.html in a new tab and the user enters his email address. I send the email address to the ap...
[ "You can use the Channel API to accomplish this. Request a token at the same time you make the XMLHttpRequest, and open the channel to listen for messages. When your app processes the HTTP request corresponding to the user clicking on the link, send a message to the channel that was created for that user's extensio...
[ 5 ]
[]
[]
[ "google_app_engine", "google_chrome_extension", "javascript", "python" ]
stackoverflow_0007939633_google_app_engine_google_chrome_extension_javascript_python.txt
Q: Python XML Parsing *Note: lxml will not run on my system. I was hoping to find a solution that does not involve lxml. I have gone through some of the documentation around here already, and am having difficulties getting this to work how I would like to. I would like to parse some XML file that looks like this: <...
Python XML Parsing
*Note: lxml will not run on my system. I was hoping to find a solution that does not involve lxml. I have gone through some of the documentation around here already, and am having difficulties getting this to work how I would like to. I would like to parse some XML file that looks like this: <dict> <key>1375</key...
[ "You can use xml.etree.ElementTree which is included with Python. There is an included companion C-implemented (i.e. much faster) xml.etree.cElementTree. lxml.etree offers a superset of the functionality but it's not needed for what you want to do. \nThe code provided by @Acorn works identically for me (Python 2.7...
[ 10, 7 ]
[]
[]
[ "lxml", "parsing", "python", "xml" ]
stackoverflow_0007939954_lxml_parsing_python_xml.txt
Q: Pyglet: Library "GL" not found I tried installing pyglet with sudo python setup.py install and with sudo apt-get install python-pyglet but I had no luck running a simple script. I am with Ubuntu 11.10 64-bits. File "test.py", line 3, in <module> window = pyglet.window.Window() File "/usr/local/lib/python2.7/dist-p...
Pyglet: Library "GL" not found
I tried installing pyglet with sudo python setup.py install and with sudo apt-get install python-pyglet but I had no luck running a simple script. I am with Ubuntu 11.10 64-bits. File "test.py", line 3, in <module> window = pyglet.window.Window() File "/usr/local/lib/python2.7/dist-packages/pyglet/__init__.py", line 30...
[ "It's probably a problem with your graphics drivers. You could try installing the dev packages for whatever graphics driver you are using, look for packages with dev and one of fglrx(amd), nvidia or mesa(open source) in the name. You probably also want to install freeglut. \nNow as always be careful messing around ...
[ 1 ]
[]
[]
[ "importerror", "pyglet", "python", "ubuntu" ]
stackoverflow_0007940001_importerror_pyglet_python_ubuntu.txt
Q: Python 3.2.2 Function Returns None on Non-Empty Variable I am writing a simple script to download .mp4 TEDTalks given a list of TEDTalk website links: # Run through a list of TEDTalk website links and download each # TEDTalk in high quality MP4 import urllib.request #List of website links l = [ "http://w...
Python 3.2.2 Function Returns None on Non-Empty Variable
I am writing a simple script to download .mp4 TEDTalks given a list of TEDTalk website links: # Run through a list of TEDTalk website links and download each # TEDTalk in high quality MP4 import urllib.request #List of website links l = [ "http://www.ted.com/index.php/talks/view/id/28", "http://www.te...
[ "\nI am certain that the function findFullURL works.\n\nBeing certain that a certain piece of code works is the best way to waste hours of debugging time looking in the wrong place.\nIn fact that function does not work. You are missing a return:\ndef findFullURL(d, e, s):\n a = s[d]\n if a != \"/\":\n ...
[ 10, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007942107_python_python_3.x.txt
Q: Django Streaming DumpData How do you get Django's dumpdata management command to stream contents to a file instead of loading everything into memory? I'm trying to convert a 1GB Sqlite3 database to PostgreSQL, and one method I'm considering is dumping the database to json using python manage.py dumpdata --all --fo...
Django Streaming DumpData
How do you get Django's dumpdata management command to stream contents to a file instead of loading everything into memory? I'm trying to convert a 1GB Sqlite3 database to PostgreSQL, and one method I'm considering is dumping the database to json using python manage.py dumpdata --all --format=json > mydatabase.json. Th...
[ "You can try a patch from https://code.djangoproject.com/ticket/5423, but I think a better way is to dump data to sql.\n" ]
[ 3 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0007942185_database_django_python.txt
Q: what is the use of recursive relationship and a relationship to an undefined model in Django? Text below is from Django docs which provide To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey(’self’). If you need to create a relationship on a m...
what is the use of recursive relationship and a relationship to an undefined model in Django?
Text below is from Django docs which provide To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey(’self’). If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model obje...
[ "You can use it to create links to other objects of this Model. \nFor example if you have many members in a website and each has an inviter (also of Member type) you can do the following:\nclass Member(Model):\n inviter = models.ForeignKey(\n 'self',\n related_name=\"invited_set\"\n )\n\nIf you ...
[ 3, 1 ]
[]
[]
[ "database", "django", "python", "relational_database" ]
stackoverflow_0007941502_database_django_python_relational_database.txt
Q: QWebKit - Run page's javascript function? Basically I want to go into my Router's settings, set a checkbutton and than call a function on the page, all programmatically. I know all the javascript to do this, and can do it via the Google Chrome console. I can syntactically perform it through QWebKit, but the actu...
QWebKit - Run page's javascript function?
Basically I want to go into my Router's settings, set a checkbutton and than call a function on the page, all programmatically. I know all the javascript to do this, and can do it via the Google Chrome console. I can syntactically perform it through QWebKit, but the actual page remains unaffected. import sys from PyQ...
[ "You should probably wait for the page to finish loading, by moving the javascript evaluation to a slot connected to the loadFinished() signal.\nBut as Pointy suggested, you could also try to send POST requests yourself, through QNetworkAccessManager, instead of using a widget.\n" ]
[ 0 ]
[]
[]
[ "javascript", "pyqt4", "python", "qwebkit" ]
stackoverflow_0007939090_javascript_pyqt4_python_qwebkit.txt
Q: Using Python Flask, mod_wsgi, apache2 - unable to get custom 500 error page I am running Ubuntu, Flask 0.8, mod_wsgi 3 and apache2. When an error occurs, I am unable to get Flask's custom 500 error page to trigger (and not the debug mode output either). It works fine when I run it without WSGI via app.run(debug=...
Using Python Flask, mod_wsgi, apache2 - unable to get custom 500 error page
I am running Ubuntu, Flask 0.8, mod_wsgi 3 and apache2. When an error occurs, I am unable to get Flask's custom 500 error page to trigger (and not the debug mode output either). It works fine when I run it without WSGI via app.run(debug=True). I've tried setting WSGIErrorOverride to both On and Off in apache settings...
[ "Are you sure the error is actually coming from Flask if you are getting a generic Apache 500 error page? You should look in the Apache error log to see what error messages are in there first. The problem could be configuration or your WSGI script file being wrong or failing due to wrong sys.path etc.\n" ]
[ 1 ]
[]
[]
[ "apache", "flask", "python", "wsgi" ]
stackoverflow_0007940745_apache_flask_python_wsgi.txt
Q: Using python multiprocessing pipes I am trying to write a class that will calculate checksums using multiple processes, thereby taking advantage of multiple cores. I have a quite simple class for this, and it works great when executing a simple case. But whenever I create two or more instances of the class, the wo...
Using python multiprocessing pipes
I am trying to write a class that will calculate checksums using multiple processes, thereby taking advantage of multiple cores. I have a quite simple class for this, and it works great when executing a simple case. But whenever I create two or more instances of the class, the worker never exits. It seems like it never...
[ "Yep, that is surprising behaviour indeed.\nHowever, if you look at the output of lsof for the two parallel child processes it is easy to notice that the second child process has more file descriptors open.\nWhat happens is that when two parallel child processes get started the second child inherits the pipes of th...
[ 7 ]
[]
[]
[ "multiprocessing", "pipe", "python", "python_2.6" ]
stackoverflow_0007938457_multiprocessing_pipe_python_python_2.6.txt
Q: How does python compare functions? How come this doesn't rise Attribute error? function object doesn't have any of the comparison methods. Does it use id() somehow? fun1 = lambda:x fun2 = lambda:x print fun1 == fun1 # True print fun1 == fun2 # False print fun1 > fun2 # True print fun1 < fun2 # False print fun1 > 1...
How does python compare functions?
How come this doesn't rise Attribute error? function object doesn't have any of the comparison methods. Does it use id() somehow? fun1 = lambda:x fun2 = lambda:x print fun1 == fun1 # True print fun1 == fun2 # False print fun1 > fun2 # True print fun1 < fun2 # False print fun1 > 1 # True I understand that it compares a...
[ "Function objects do not define their own comparisons or rich comparisons. Instead, they inherit from type objects which implement rich comparisons based on the object's address in memory.\nSo yes, it effectively uses addresses just like the built-in id() function does.\nIn Python 3, functions are no longer ordera...
[ 23, 9 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0007942346_python_sorting.txt
Q: How does itertools.combinations scale in Python? I'm doing a brute-force approach to trying to find the combination to an extension to a puzzle. I am trying to get a large number of combinations and then test each combination to see if they fit certain criteria. I generate the combinations using Python's excellen...
How does itertools.combinations scale in Python?
I'm doing a brute-force approach to trying to find the combination to an extension to a puzzle. I am trying to get a large number of combinations and then test each combination to see if they fit certain criteria. I generate the combinations using Python's excellent itertools, essentially this gives me an iterator I c...
[ "You're asking for 365 choose 6 = (365 * 364 * ... * 360) / (6 * 5 * ... * 2 * 1) = 3,151,277,509,380 combinations. That's a lot. Looping over 3 trillion elements is just not going to happen on your desktop in Python – no way.\nIf you're just looking for how many there are supposed to be, the formula to calculate t...
[ 6, 2, 0 ]
[]
[]
[ "combinations", "python", "python_itertools" ]
stackoverflow_0007942026_combinations_python_python_itertools.txt
Q: sympy - can't make nsolve method work I did this code: from scitools.std import * from sympy import * x=Symbol('x') #Integral function #def f(x): --> I also tried this # return exp(-x**2) f=exp(-x**2) intac=integrate(f,(x,0,1)) print(nsolve(f,x,1)) The interpreter gives me: "local variable x ref...
sympy - can't make nsolve method work
I did this code: from scitools.std import * from sympy import * x=Symbol('x') #Integral function #def f(x): --> I also tried this # return exp(-x**2) f=exp(-x**2) intac=integrate(f,(x,0,1)) print(nsolve(f,x,1)) The interpreter gives me: "local variable x referenced before assignment" If I try nsolve(...
[ "I don't know anything about nsolve's call syntax, but I can tell you why neither sympy nor mpmath can find a real root of the function: there aren't any. If f(x)=exp(-x^2), then f(x) > 0 for any real x. f(0) = 1 and the function decreases as abs(x) gets bigger in either direction, but it's always positive. Cert...
[ 3 ]
[]
[]
[ "mpmath", "python", "sympy" ]
stackoverflow_0007940441_mpmath_python_sympy.txt
Q: Receiving extended data with ssh using twisted.conch as client I'm currently in the process of learning ssh via the brute-force/ just keep hacking until I understand it approach. After some trial and error I've been able to successfully send a "pty-req" followed by a "shell" request, I can get the login preamble,...
Receiving extended data with ssh using twisted.conch as client
I'm currently in the process of learning ssh via the brute-force/ just keep hacking until I understand it approach. After some trial and error I've been able to successfully send a "pty-req" followed by a "shell" request, I can get the login preamble, send commands and receive stdout but I'm not exactly sure how to te...
[ "Digging through the source code for OpenSSH, channel session logic is handled in session.c at line \n2227 function -> session_input_channel_req which if given a pty-req then a \"shell\" request leads to do_exec_pty which ultimately leads to the call to session_set_fds(s, ptyfd, fdout, -1, 1, 1). The forth argume...
[ 0 ]
[]
[]
[ "python", "ssh", "twisted", "twisted.conch" ]
stackoverflow_0007937651_python_ssh_twisted_twisted.conch.txt
Q: Create a python object that can be accessed with square brackets I would like to create a new class that acts as a special type of container for objects, and can be accessed using square brackets. For example, suppose I have a class called ListWrapper. Suppose obj is a ListWrapper. When I say obj[0], I expect the ...
Create a python object that can be accessed with square brackets
I would like to create a new class that acts as a special type of container for objects, and can be accessed using square brackets. For example, suppose I have a class called ListWrapper. Suppose obj is a ListWrapper. When I say obj[0], I expect the method obj.access() to be called with 0 as an argument. Then, I can re...
[ "You want to define the special __getitem__[docs] method.\nclass Test(object): \n def __getitem__(self, arg):\n return str(arg)*3\n\ntest = Test()\n\nprint test[0]\nprint test['kitten']\n\nResult:\n\n000\nkittenkittenkitten\n\n", "Python's standard objects have a series of methods named __something_...
[ 121, 11 ]
[]
[]
[ "python" ]
stackoverflow_0007942669_python.txt
Q: Client Not Receiving Data in Python I am very new to Python and have a basic question, can a client side of a network socket connection make receive data? In my question, the client is the one who initiates the connection, which is probably obvious but I wanted to be clear. I ask because I have another server an...
Client Not Receiving Data in Python
I am very new to Python and have a basic question, can a client side of a network socket connection make receive data? In my question, the client is the one who initiates the connection, which is probably obvious but I wanted to be clear. I ask because I have another server and client (both python) that allows the se...
[ "In applications like this, it is sometimes helpful to bypass the low level detail and use socket.makefile with its higher-level API instead.\nIn the client close, replace:\ndata = mysocket.recv(1024)\n\nwith:\nf = mysocket.makefile('rb')\ndata = f.read(1024) # or any other file method call you need\n\nTh...
[ 1, 0 ]
[]
[]
[ "broken_pipe", "client_server", "python", "sockets" ]
stackoverflow_0007942589_broken_pipe_client_server_python_sockets.txt
Q: Google App Engine: Scheduled Tasks With Cron for Python I have read the manual here: http://code.google.com/appengine/docs/python/config/cron.html But I want to do a task at some specific times: - description: do this cron url: /do-this-cron schedule: every day 08:15,12:15,16:15 Is this legit? I havent seen a...
Google App Engine: Scheduled Tasks With Cron for Python
I have read the manual here: http://code.google.com/appengine/docs/python/config/cron.html But I want to do a task at some specific times: - description: do this cron url: /do-this-cron schedule: every day 08:15,12:15,16:15 Is this legit? I havent seen any other examples where times are seperated by comma.
[ "No, the schedule format doesn't support comma-separated times. You can do this instead:\n- description: do this cron\n url: /do-this-cron\n schedule: every 4 hours from 08:15 to 16:15\n\n" ]
[ 6 ]
[]
[]
[ "cron", "google_app_engine", "python" ]
stackoverflow_0007942148_cron_google_app_engine_python.txt
Q: how to implement bidimensional array where each element has a set of values in python? I have a problem implementing the following in python: I have a nxn matrix like this: [ X11 X12 X13 ... x1n Xn1 Xn2 Xn3 ... Xnn ] Thats simple to get but any of those "Xij" values has 4 simple int values(0 or 1 each) and i ca...
how to implement bidimensional array where each element has a set of values in python?
I have a problem implementing the following in python: I have a nxn matrix like this: [ X11 X12 X13 ... x1n Xn1 Xn2 Xn3 ... Xnn ] Thats simple to get but any of those "Xij" values has 4 simple int values(0 or 1 each) and i cant seem to understand how to create an array or collection that i can use. Does anyone know ...
[ "Why not just a three-dimensional array, that is, an array of arrays of arrays, where the innermost array contains four elements, and the outer two arrays are your matrix?\n", "Why not package the integers into a tuple? Then you would have a bidimensional array in the form:\n[[(1,0,0,1), (1,1,1,0), (0,0,0,1)]...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007942722_python.txt
Q: Using twisted words in a WSGI container I am running django on twisted in a wsgi container. Obviously I am avoiding all the async stuff with deferreds inside my django code because according to the documentation, twisted async abilities are not allowed inside WSGI apps. However, I would like to use twisted.words i...
Using twisted words in a WSGI container
I am running django on twisted in a wsgi container. Obviously I am avoiding all the async stuff with deferreds inside my django code because according to the documentation, twisted async abilities are not allowed inside WSGI apps. However, I would like to use twisted.words inside my WSGI app to send requests to a jabbe...
[ "To call a function in the main event loop (I/O thread) in Twisted from another thread (non-I/O thread i.e., a WSGI application thread) you could use reactor.callFromThread(). If you'd like to wait for results then use threads.blockingCallFromThread(). Thus you could call functions that use twisted.words See Using ...
[ 0 ]
[]
[]
[ "asynchronous", "django", "python", "twisted.words", "wsgi" ]
stackoverflow_0007938112_asynchronous_django_python_twisted.words_wsgi.txt
Q: how do i create a database in psycopg2 and do i need to? I'm create a blog using django. I'm getting an 'operational error: FATAL: role "[database user]" does not exist. But i have not created any database yet, all i have done is filled in the database details in setting.py. Do i have to create a database using ps...
how do i create a database in psycopg2 and do i need to?
I'm create a blog using django. I'm getting an 'operational error: FATAL: role "[database user]" does not exist. But i have not created any database yet, all i have done is filled in the database details in setting.py. Do i have to create a database using psycopg2? If so, how do i do it? Is it: python import psycop...
[ "before connecting to database, you need to create database, add user, setup access for user you selected. \nReffer to installation/configuration guides for Postgres. \n", "Generally, you would create the database externally before trying to hook it up with Django.\nIs this your private server? If so, there are...
[ 0, 0 ]
[]
[]
[ "database", "django", "psycopg2", "python" ]
stackoverflow_0007941623_database_django_psycopg2_python.txt
Q: Are there any method that perform same as using "column stack" in numpy PYTHON I am using Python 2.7. My system is running Window Vista, 32 bits. I have a piece of code that reads radiance, Latitude and Longitude and an image file(in hdf extension). And then try to perform approximated nearest neighbor and map it....
Are there any method that perform same as using "column stack" in numpy PYTHON
I am using Python 2.7. My system is running Window Vista, 32 bits. I have a piece of code that reads radiance, Latitude and Longitude and an image file(in hdf extension). And then try to perform approximated nearest neighbor and map it. But when it tries to do the approximated nearest neighbor, it gives me Memory Error...
[ "I agree with yosukesabai that you should print out x and y, but I think you also make things a bit harder than it has to. I might not understand the code, but it seems like you are converting all the lat-lon coordinates to km and then convert the lat-lon vectors from get_lat_lon to a matrix and then back to vector...
[ 2, 1 ]
[]
[]
[ "hdf5", "image_processing", "numpy", "python" ]
stackoverflow_0007942643_hdf5_image_processing_numpy_python.txt
Q: Sharing variables between two classes in Python I felt like working on my network programming, threading and OOP skills. I've encountered a problem though. I have a class named IRC and a class named Pong. I want to use IRC to do stuff like connecting to the server, sending messages, etc. I want to use Pong as a th...
Sharing variables between two classes in Python
I felt like working on my network programming, threading and OOP skills. I've encountered a problem though. I have a class named IRC and a class named Pong. I want to use IRC to do stuff like connecting to the server, sending messages, etc. I want to use Pong as a thread in the background which checks for a message con...
[ "You'll need to call an instance of the IRC class which you can pass to the PONG constructor:\nclass IRC:\n def Connect(self):\n try:\n HOST = sys.argv[1]\n PORT = sys.argv[2]\n except IndexError:\n print \"Usage: \"+sys.argv[0]+\" [server] [port]\\n\"\n ...
[ 3 ]
[]
[]
[ "class", "multithreading", "python", "variables" ]
stackoverflow_0007942857_class_multithreading_python_variables.txt
Q: Elementtree displaying elements out of order I'm using Python's ElementTree to parse xml files. I have a "findall" to find all "revision" subelements, but when I iterate through the result, they are not in document order. What can I be doing wrong? Here's my code: allrevisions = page.findall('{http://www.mediawik...
Elementtree displaying elements out of order
I'm using Python's ElementTree to parse xml files. I have a "findall" to find all "revision" subelements, but when I iterate through the result, they are not in document order. What can I be doing wrong? Here's my code: allrevisions = page.findall('{http://www.mediawiki.org/xml/export-0.5/}revision') for rev in allrev...
[ "The documentation for ElementTree says that findall returns the elements in document order.\nA quick test shows the correct behaviour:\nimport xml.etree.ElementTree as et\n\nxmltext = \"\"\"\n<root>\n <number>1</number>\n <number>2</number>\n <number>3</number>\n <number>4</number>\n</root>\n\"\"\"\n\n...
[ 2 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0007942875_elementtree_python_xml.txt
Q: Testing for 400 errors with paste on a web.py app I'm using paste to do some functional testing on my 'controllers' in my web.py app. In one case I'm trying to test for a 400 response when a malformed post is made to an API endpoint. Here is what my test looks like: def test_api_users_index_post_malformed(self): ...
Testing for 400 errors with paste on a web.py app
I'm using paste to do some functional testing on my 'controllers' in my web.py app. In one case I'm trying to test for a 400 response when a malformed post is made to an API endpoint. Here is what my test looks like: def test_api_users_index_post_malformed(self): r = self.testApp.post('/api/users', params={}) a...
[ "I know I'm tardy to the party, but I ran across this searching for the answer to the same issue. To allow the TestApp to pass non 2xx/3xx responses back you need to tell the request to allow \"errors\".\ndef test_api_users_index_post_malformed(self):\n r = self.testApp.post('/api/users', params={}, expect_error...
[ 33 ]
[]
[]
[ "functional_testing", "paste", "python" ]
stackoverflow_0007071210_functional_testing_paste_python.txt
Q: Connecting to MySQL with Python in Ubuntu (Weird Error) I'm using ubuntu 10.10, and after making the mistake of installing LAMP, (was unable to connect to a database with it), I came here and read how important it is to use apt-get install python-mysqldb instead. Deleted LAMP, re-installed using apt-get, and am no...
Connecting to MySQL with Python in Ubuntu (Weird Error)
I'm using ubuntu 10.10, and after making the mistake of installing LAMP, (was unable to connect to a database with it), I came here and read how important it is to use apt-get install python-mysqldb instead. Deleted LAMP, re-installed using apt-get, and am now getting the same error when trying to run a basic server_ve...
[ "It looks like you have a file named copy.py that is being picked up instead of the Python standard library module copy. Rename or delete your file (and copy.pyc if it was created). Or run from a different directory.\n" ]
[ 3 ]
[]
[]
[ "lamp", "mysql", "mysql_python", "python", "ubuntu" ]
stackoverflow_0007943042_lamp_mysql_mysql_python_python_ubuntu.txt